text:
TensorFlow was designed from the ground up to be a good deep learning solution
for mobile platforms like Android and iOS. This mobile guide should help you
understand how machine learning can work on mobile platforms and how to
integrate TensorFlow into your mobile apps effectively and efficiently.

## About this Guide

This guide is aimed at developers who have a TensorFlow model that's
successfully working in a desktop environment, who want to integrate it into
a mobile application, and cannot use TensorFlow Lite. Here are the
main challenges you'll face during that process:

- Understanding how to use Tensorflow for mobile.
- Building TensorFlow for your platform.
- Integrating the TensorFlow library into your application.
- Preparing your model file for mobile deployment.
- Optimizing for latency, RAM usage, model file size, and binary size.

## Common use cases for mobile machine learning

**Why run TensorFlow on mobile?**

Traditionally, deep learning has been associated with data centers and giant
clusters of high-powered GPU machines. However, it can be very expensive and
time-consuming to send all of the data a device has access to across a network
connection. Running on mobile makes it possible to deliver very interactive
applications in a way that's not possible when you have to wait for a network
round trip.

Here are some common use cases for on-device deep learning:

### Speech Recognition

There are a lot of interesting applications that can be built with a
speech-driven interface, and many of these require on-device processing. Most of
the time a user isn't giving commands, and so streaming audio continuously to a
remote server would be a waste of bandwidth, since it would mostly be silence or
background noises. To solve this problem it's common to have a small neural
network running on-device @{$tutorials/audio_recognition$listening out for a particular keyword}.
Once that keyword has been spotted, the rest of the
conversation can be transmitted over to the server for further processing if
more computing power is needed.

### Image Recognition

It can be very useful for a mobile app to be able to make sense of a camera
image. If your users are taking photos, recognizing what's in them can help your
camera apps apply appropriate filters, or label the photos so they're easily
findable. It's important for embedded applications too, since you can use image
sensors to detect all sorts of interesting conditions, whether it's spotting
endangered animals in the wild
or
[reporting how late your train is running](https://svds.com/tensorflow-image-recognition-raspberry-pi/).

TensorFlow comes with several examples of recognizing the types of objects
inside images along with a variety of different pre-trained models, and they can
all be run on mobile devices. You can try out
our
[Tensorflow for Poets](https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/index.html#0) and
[Tensorflow for Poets 2: Optimize for Mobile](https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2/index.html#0) codelabs to
see how to take a pretrained model and run some very fast and lightweight
training to teach it to recognize specific objects, and then optimize it to
run on mobile.

### Object Localization

Sometimes it's important to know where objects are in an image as well as what
they are. There are lots of augmented reality use cases that could benefit a
mobile app, such as guiding users to the right component when offering them
help fixing their wireless network or providing informative overlays on top of
landscape features. Embedded applications often need to count objects that are
passing by them, whether it's pests in a field of crops, or people, cars and
bikes going past a street lamp.

TensorFlow offers a pretrained model for drawing bounding boxes around people
detected in images, together with tracking code to follow them over time. The
tracking is especially important for applications where you're trying to count
how many objects are present over time, since it gives you a good idea when a
new object enters or leaves the scene. We have some sample code for this
available for Android [on
Github](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android),
and also a [more general object detection
model](https://github.com/tensorflow/models/tree/master/research/object_detection/README.md)
available as well.

### Gesture Recognition

It can be useful to be able to control applications with hand or other
gestures, either recognized from images or through analyzing accelerometer
sensor data. Creating those models is beyond the scope of this guide, but
TensorFlow is an effective way of deploying them.

### Optical Character Recognition

Google Translate's live camera view is a great example of how effective
interactive on-device detection of text can be.

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="06olHmcJjS0"
            data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>

There are multiple steps involved in recognizing text in images. You first have
to identify the areas where the text is present, which is a variation on the
object localization problem, and can be solved with similar techniques. Once you
have an area of text, you then need to interpret it as letters, and then use a
language model to help guess what words they represent. The simplest way to
estimate what letters are present is to segment the line of text into individual
letters, and then apply a simple neural network to the bounding box of each. You
can get good results with the kind of models used for MNIST, which you can find
in TensorFlow's tutorials, though you may want a higher-resolution input.  A
more advanced alternative is to use an LSTM model to process a whole line of
text at once, with the model itself handling the segmentation into different
characters.

### Translation

Translating from one language to another quickly and accurately, even if you
don't have a network connection, is an important use case. Deep networks are
very effective at this sort of task, and you can find descriptions of a lot of
different models in the literature. Often these are sequence-to-sequence
recurrent models where you're able to run a single graph to do the whole
translation, without needing to run separate parsing stages.

### Text Classification

If you want to suggest relevant prompts to users based on what they're typing or
reading, it can be very useful to understand the meaning of the text. This is
where text classification comes in. Text classification is an umbrella term
that covers everything from sentiment analysis to topic discovery. You're likely
to have your own categories or labels that you want to apply, so the best place
to start is with an example
like
[Skip-Thoughts](https://github.com/tensorflow/models/tree/master/research/skip_thoughts/),
and then train on your own examples.

### Voice Synthesis

A synthesized voice can be a great way of giving users feedback or aiding
accessibility, and recent advances such as
[WaveNet](https://deepmind.com/blog/wavenet-generative-model-raw-audio/) show
that deep learning can offer very natural-sounding speech.

## Mobile machine learning and the cloud

These examples of use cases give an idea of how on-device networks can
complement cloud services. Cloud has a great deal of computing power in a
controlled environment, but running on devices can offer higher interactivity.
In situations where the cloud is unavailable, or your cloud capacity is limited,
you can provide an offline experience, or reduce cloud workload by processing
easy cases on device.

Doing on-device computation can also signal when it's time to switch to working
on the cloud. A good example of this is hotword detection in speech. Since
devices are able to constantly listen out for the keywords, this then triggers a
lot of traffic to cloud-based speech recognition once one is recognized. Without
the on-device component, the whole application wouldn't be feasible, and this
pattern exists across several other applications as well. Recognizing that some
sensor input is interesting enough for further processing makes a lot of
interesting products possible.

## What hardware and software should you have?

TensorFlow runs on Ubuntu Linux, Windows 10, and OS X. For a list of all
supported operating systems and instructions to install TensorFlow, see
@{$install$Installing Tensorflow}.

Note that some of the sample code we provide for mobile TensorFlow requires you
to compile TensorFlow from source, so you'll need more than just `pip install`
to work through all the sample code.

To try out the mobile examples, you'll need a device set up for development,
using
either [Android Studio](https://developer.android.com/studio/install.html),
or [XCode](https://developer.apple.com/xcode/) if you're developing for iOS.

## What should you do before you get started?

Before thinking about how to get your solution on mobile:

1. Determine whether your problem is solvable by mobile machine learning
2. Create a labelled dataset to define your problem
3. Pick an effective model for the problem

We'll discuss these in more detail below.

### Is your problem solvable by mobile machine learning?

Once you have an idea of the problem you want to solve, you need to make a plan
of how to build your solution. The most important first step is making sure that
your problem is actually solvable, and the best way to do that is to mock it up
using humans in the loop.

For example, if you want to drive a robot toy car using voice commands, try
recording some audio from the device and listen back to it to see if you can
make sense of what's being said. Often you'll find there are problems in the
capture process, such as the motor drowning out speech or not being able to hear
at a distance, and you should tackle these problems before investing in the
modeling process.

Another example would be giving photos taken from your app to people see if they
can classify what's in them, in the way you're looking for. If they can't do
that (for example, trying to estimate calories in food from photos may be
impossible because all white soups look the same), then you'll need to redesign
your experience to cope with that. A good rule of thumb is that if a human can't
handle the task then it will be difficult to train a computer to do better.

### Create a labelled dataset

After you've solved any fundamental issues with your use case, you need to
create a labeled dataset to define what problem you're trying to solve. This
step is extremely important, moreso than picking which model to use. You want it
to be as representative as possible of your actual use case, since the model
will only be effective at the task you teach it. It's also worth investing in
tools to make labeling the data as efficient and accurate as possible. For
example, if you're able to switch from having to click a button on a web
interface to simple keyboard shortcuts, you may be able to speed up the
generation process a lot. You should also start by doing the initial labeling
yourself, so you can learn about the difficulties and likely errors, and
possibly change your labeling or data capture process to avoid them. Once you
and your team are able to consistently label examples (that is once you
generally agree on the same labels for most examples), you can then try and
capture your knowledge in a manual and teach external raters how to run the same
process.

### Pick an effective model

The next step is to pick an effective model to use. You might be able to avoid
training a model from scratch if someone else has already implemented a model
similar to what you need; we have a repository of models implemented in
TensorFlow [on Github](https://github.com/tensorflow/models) that you can look
through. Lean towards the simplest model you can find, and try to get started as
soon as you have even a small amount of labelled data, since you'll get the best
results when you're able to iterate quickly. The shorter the time it takes to
try training a model and running it in its real application, the better overall
results you'll see. It's common for an algorithm to get great training accuracy
numbers but then fail to be useful within a real application because there's a
mismatch between the dataset and real usage. Prototype end-to-end usage as soon
as possible to create a consistent user experience.

## Next Steps

We suggest you get started by building one of our demos for
@{$mobile/android_build$Android} or @{$mobile/ios_build$iOS}.


text:
class Ownership < ActiveRecord::Base
  belongs_to :user, :dependent => :destroy
  belongs_to :group

  attr_accessible :group_id, :user_id
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="pendingViewStyle" format="reference" />
    <attr name="icon" format="reference" />
    <attr name="text" format="string" />
</resources>


text:
package com.fenixinfotech.location.geodesy;

import org.junit.Test;

import static org.junit.Assert.*;

public class GreatCircleCalculationsTest {

    private static final double BERLIN_LATITUDE = 52.507950;
    private static final double BERLIN_LONGITUDE = 13.408941;
    private static final double BRASILIA_LATITUDE = -15.786499;
    private static final double BRASILIA_LONGITUDE = -47.870515;
    private static final double DUBLIN_LATITUDE = 53.341545;
    private static final double DUBLIN_LONGITUDE = -6.254362;
    private static final double GREENWICH_LATITUDE = 51.482211;
    private static final double GREENWICH_LONGITUDE = 0;
    private static final double GULF_OF_GUINEA_LATITUDE = 0;
    private static final double GULF_OF_GUINEA_LONGITUDE = 0;
    private static final double NORTH_POLE_LATITUDE = 90;
    private static final double NORTH_POLE_LONGITUDE = 0;
    private static final double SOUTH_POLE_LATITUDE = -90;
    private static final double SOUTH_POLE_LONGITUDE = 0;
    private static final double WASHINGTON_LATITUDE = 38.900688;
    private static final double WASHINGTON_LONGITUDE = -77.033640;

    private static final double DEFAULT_DISTANCE_METRES = 500;
    @Test
    public void getHorizontalLatitudeRange() {
        // BERLIN
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, BERLIN_LATITUDE);

        // BRASILIA
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, BRASILIA_LATITUDE);

        // DUBLIN
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, DUBLIN_LATITUDE);

        // GREENWICH
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, GREENWICH_LATITUDE);

        // GULF_OF_GUINEA
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, GULF_OF_GUINEA_LATITUDE);

        // NORTH_POLE
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, NORTH_POLE_LATITUDE);

        // SOUTH_POLE
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, SOUTH_POLE_LATITUDE);

        // WASHINGTON
        GreatCircleCalculations.getLatLongOffsets(DEFAULT_DISTANCE_METRES, WASHINGTON_LATITUDE);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using OKHOSTING.UI.Controls;

namespace OKHOSTING.UI.Net4.WinForms.Syncfusion.Controls
{
    public class TextBox : global::Syncfusion.Windows.Forms.Tools.TextBoxExt, ITextBox
    {
		public TextBox()
		{
			base.TextChanged += TextBox_TextChanged;
			base.LostFocus += TextBox_LostFocus;
			base.GotFocus += TextBox_GotFocus;
		}

		private void TextBox_TextChanged(object sender, EventArgs e)
		{
			ValueChanged?.Invoke(this, ((IInputControl<string>)this).Value);
		}

		#region ITextControl

		string ITextControl.FontFamily
		{
			get
			{
				return base.Font.FontFamily.Name;
			}
			set
			{
				base.Font = new System.Drawing.Font(value, (float)base.FontHeight);
			}
		}

		System.Drawing.Color ITextControl.FontColor
		{
			get
			{
				return base.ForeColor;
			}
			set
			{
				base.ForeColor = value;
			}
		}

		bool ITextControl.Bold
		{
			get
			{
				return base.Font.Bold;
			}
			set
			{
				base.Font = new System.Drawing.Font(Font.Name, base.Font.Size, value ? System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular);
			}
		}

		bool ITextControl.Italic
		{
			get
			{
				return base.Font.Italic;
			}
			set
			{
				base.Font = new System.Drawing.Font(Font.Name, base.Font.Size, value ? System.Drawing.FontStyle.Italic : System.Drawing.FontStyle.Regular);
			}
		}

		bool ITextControl.Underline
		{
			get
			{
				return base.Font.Underline;
			}

			set
			{
				base.Font = new System.Drawing.Font(Font.Name, base.Font.Size, value ? System.Drawing.FontStyle.Underline : System.Drawing.FontStyle.Regular);
			}
		}

		HorizontalAlignment ITextControl.TextHorizontalAlignment
		{
			get
			{
				return (HorizontalAlignment)base.TextAlign;
			}
			set
			{
				base.TextAlign = (System.Windows.Forms.HorizontalAlignment)value;
			}
		}

		VerticalAlignment ITextControl.TextVerticalAlignment
		{
			get
			{
				return VerticalAlignment.Top;
			}
			set
			{
				//not supported
			}
		}

		Thickness ITextControl.TextPadding
		{
			get
			{
				return new Thickness(base.Padding.Left, base.Padding.Top, base.Padding.Right, base.Padding.Bottom);
			}
			set
			{
				base.Padding = new System.Windows.Forms.Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom);
			}
		}
		#endregion

		#region IControl

		public Guid Id { get; set; }

		Color IControl.BackgroundColor
		{
			get
			{
				return base.BackColor;
			}
			set
			{
				base.BackColor = value;
			}
		}

		Color IControl.BorderColor
		{
			get;
			set;
		}

		Thickness IControl.BorderWidth
		{
			get;
			set;
		}

		public string CssClass { get; set; }

		double? IControl.Width
		{
			get
			{
				return base.Width;
			}
			set
			{
				if (value.HasValue)
				{
					base.Width = (int)value.Value;
				}
			}
		}

		double? IControl.Height
		{
			get
			{
				return base.Height;
			}
			set
			{
				if (value.HasValue)
				{
					base.Height = (int)value.Value;
				}
			}
		}

		Thickness IControl.Margin
		{
			get
			{
				return new Thickness(base.Margin.Left, base.Margin.Top, base.Margin.Right, base.Margin.Bottom);
			}
			set
			{
				base.Margin = new System.Windows.Forms.Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom);
			}
		}

		Thickness IControl.Padding
		{
			get
			{
				return new Thickness(base.Padding.Left, base.Padding.Top, base.Padding.Right, base.Padding.Bottom);
			}
			set
			{
				base.Padding = new System.Windows.Forms.Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom);
			}
		}

		IControl IControl.Parent
		{
			get
			{
				return (IControl)base.Parent;
			}
		}

		HorizontalAlignment IControl.HorizontalAlignment
		{
			get
			{
				return Platform.Parse(base.Anchor).Item1;
			}
			set
			{
				base.Anchor = Platform.ParseAnchor(value, ((IControl)this).VerticalAlignment);
			}
		}
		VerticalAlignment IControl.VerticalAlignment
		{
			get
			{
				return Platform.Parse(base.Anchor).Item2;
			}
			set
			{
				base.Anchor = Platform.ParseAnchor(((IControl)this).HorizontalAlignment, value);
			}
		}

		#endregion

		ITextBoxInputType ITextBox.InputType
		{
			get;
			set;
		}

		private string _Placeholder;
		public string Placeholder
		{
			get
			{
				return _Placeholder;
			}
			set
			{
				_Placeholder = value;
				ShowPlaceholder();
			}
		}
		/// <summary>
		/// Private member to store the PlaceholderColor
		/// </summary>
		private Color _PlaceholderColor;

		/// <summary>
		/// The font color of the Placeholder text
		/// </summary>
		Color ITextBox.PlaceholderColor
		{
			get
			{
				return _PlaceholderColor;
			}
			set
			{
				_PlaceholderColor = value;
				ShowPlaceholder();
			}
		}

		public string Value
		{
			get
			{
				if (IsPlaceHolder)
				{
					return null;
				}
				else
				{
					return base.Text;
				}
			}
			set
			{
				if (!string.IsNullOrEmpty(value))
				{
					HidePlaceholder();
					base.Text = value;
				}
				else
				{
					ShowPlaceholder();
				}
			}
		}

		public double FontSize { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

		public event EventHandler<string> ValueChanged;

		private bool IsPlaceHolder;

		private void ShowPlaceholder()
		{
			if (string.IsNullOrEmpty(base.Text) || base.Text == ((ITextBox)this).Placeholder)
			{
				base.Text = ((ITextBox)this).Placeholder;
				base.ForeColor = ((ITextBox)this).PlaceholderColor;
				IsPlaceHolder = true;
			}
		}

		private void HidePlaceholder()
		{
			if (base.Text == ((ITextBox)this).Placeholder)
			{
				base.Text = null;
				base.ForeColor = ((ITextBox)this).FontColor;
				IsPlaceHolder = false;
			}
		}

		private void TextBox_LostFocus(object sender, EventArgs e)
		{
			ShowPlaceholder();
		}

		private void TextBox_GotFocus(object sender, EventArgs e)
		{
			HidePlaceholder();
		}

		public object Clone()
		{
			return MemberwiseClone();
		}
	}
}


text:
using System;
using ECommon.Utilities;

namespace EQueue.Broker.Storage
{
    public struct RecordWriteResult
    {
        public readonly bool Success;
        public readonly long Position;

        private RecordWriteResult(bool success, long position)
        {
            Success = success;
            Position = position;
        }

        public static RecordWriteResult NotEnoughSpace()
        {
            return new RecordWriteResult(false, -1);
        }
        public static RecordWriteResult Successful(long position)
        {
            return new RecordWriteResult(true, position);
        }

        public override string ToString()
        {
            return string.Format("[Success:{0}, Position:{1}]", Success, Position);
        }
    }
}


text:
var
  rs = require('readable-stream'),
  plugin,
  slash = {fwd: '/', back: '\\'},
  util = require('util');

module.exports = plugin = pathmodify;

/**
 * Main plugin.
 */
function pathmodify (b, opts) {
  // Temporarily allow people to continue using this by calling it as a factory
  // function, even though they should be mindful of semver.
  if (! arguments.length) {
    return util.deprecate(
      pathmodify,
      "Deprecated: pathmodify: Don't call the export as a factory. The export is now the plugin function."
    );
  }
  opts = opts || {};

  opts = {mods: [].concat(opts.mods || [])};

  // Map resolved pathnames to expose IDs.
  opts.mappings = {};

  // Record of already processed require() ID's, keyed on parent filename.
  opts.visited = {};

  opts.bify = b;

  opts.expose = function expose (key, val) {
    b._expose[key] = val;
    opts.pack.hasExports = true;
  };
  // expose

  opts.custom_resolver = make_resolver(opts);

  b.on('reset', function () {
    init(opts);
  });
  init(opts);
}
// pathmodify

/**
 * Common logic between initial setup and bundle reset.
 */
function init (opts) {
  var
    b = opts.bify,
    deps = b.pipeline.get('deps');

  // TODO `0` needs to be changed to a label.
  opts.pack = b.pipeline.get('pack').get(0);

  // TODO Should probably make sure this ends up directly after module-deps.
  deps.push(aliaser({mappings: opts.mappings}));

  // TODO `0` needs to be changed to a label.
  deps = deps.get(0);
  opts.deps = deps;

  opts.resolver = deps.resolver;
  deps.resolver = opts.custom_resolver;
}
// init

/**
 * Make a custom resolve function to override module-deps resolver.
 */
function make_resolver (opts) {
  var
    expose = opts.expose,
    modifiers = Array.isArray(opts.mods) ? opts.mods : [],
    mappings = opts.mappings,
    visited = opts.visited,
    bify = opts.bify;

  // These change at reset: resolve
  function current (prop) {
    return opts[prop];
  }
  // current

  return alias_resolver;

  /**
   * Custom resolve function. Same signature as node-resolve and
   * node-browser-resolve.
   */
  function alias_resolver (id, opts, cb) {
    var
      rec = {id: id, opts: {filename: opts.filename}},
      resolver = current('resolver'),
      mappings = current('mappings'),
      visited = current('visited'),
      par_vis = visited[opts.filename] || {},
      // boolean Whether the id has already been processed.
      processed;

    visited[opts.filename] = par_vis;

    // Retrieve any existing record for this id for this parent.
    processed = par_vis[rec.id];

    // Process modifiers for this module if it hasn't previously been processed.
    rec = processed || modify(rec);

    processed = !! processed;

    // Assign processed record to the records for its parent.
    if (! processed) par_vis[rec.id] = rec;

    // Calling walk() is the alternative to pushing the pipeline step (as
    // above). Currently unused. Would look like this:

    /*
      // Aliased, exposed, and not previously visited.
      if (
        ! processed &&
        rec.alias.expose
      ) {
        return opts.deps.walk({
          id: rec.alias.expose || rec.id,
          file: rec.id,
        }, opts, cb);
      }
    */

    // Delegate to original resolver.
    return resolver(rec.alias.id || rec.id, opts, function (err, res, pkg) {
      if (! err) {
        if (rec.alias.expose) {
          mappings[res] = rec.alias.expose;
          expose(rec.alias.expose, res);
        }
        bify.emit('pathmodify:resolved', {
          rec: rec,
          file: res,
        });
      }
      cb(err, res, pkg);
    });
  }
  // alias_resolver

  /**
   * Process exposure configuration.
   */
  function set_expose (rec, alias, modifier) {
    if (typeof modifier.expose === 'string') {
      alias.expose = modifier.expose;
    }
    else if (typeof modifier.expose === 'function') {
      alias.expose = modifier.expose(rec, alias);
    }

    if (modifier.expose === true || alias.expose === true) {
      alias.expose = rec.id;
    }

    return alias;
  }
  // set_expose

  /**
   * Process a modification that's a function or where the replacement is a
   * function.
   */
  function alias_with_func (mod, rec, opts) {
    var ret = {}, opts = opts || {};
    ret.alias = (typeof mod === 'function' ? mod : mod.to).call(mod, rec, opts);
    ret.matched = !! (ret.alias && ret.alias.id !== rec.id);
    return ret;
  }
  // alias_with_func

  /**
   * Apply modifiers configured by the user.
   */
  function modify (rec) {
    var
      // Switch for terminating looping over the modifiers once a match is
      // found.
      matched,
      // Restore this in the end in case the user modifies it.
      id = rec.id,
      alias,
      temp = {},
      path_sep;

    // Heuristically detect path separator.
    [slash.fwd, slash.back, slash.fwd].every(function (sep) {
      path_sep = sep;
      return rec.id.indexOf(path_sep) === -1;
    });

    modifiers.every(function (modifier) {
      matched = true;

      // Reset so modifiers can't munge data for later ones.
      rec.id = id;
      alias = {};

      if (
        (
          modifier.type === 'dir' &&
          rec.id.indexOf(modifier.from + path_sep) === 0
        )

        ||

        (modifier.type === 'id' && rec.id === modifier.from)
      ) {
        if (typeof modifier.to === 'function') {
          temp = alias_with_func(modifier, rec);
          alias = temp.alias;
          matched = temp.matched;
        }
        else {
          alias.id = modifier.to + rec.id.substr(modifier.from.length);
        }
      }

      else if (typeof modifier === 'function') {
        temp = alias_with_func(modifier, rec);
        alias = temp.alias;
        matched = temp.matched;
      }

      else if (
        modifier.type === 're' &&
        (matched = modifier.from[
          typeof modifier.to === 'function' ? 'exec' : 'test'
        ](rec.id))
      ) {
        if (typeof modifier.to === 'function') {
          temp = alias_with_func(modifier, rec, {matches: matched});
          alias = temp.alias;
          matched = temp.matched;
        }
        else {
          alias.id = rec.id.replace(modifier.from, modifier.to);
        }
      }

      else matched = false;

      if (matched) set_expose(rec, alias, modifier);

      return ! matched;
    });

    rec.id = id;
    if (! (alias && alias.id)) alias = {};
    rec.alias = alias;

    return rec;
  }
  // modify
}
// make_resolver

/**
 * Following module-deps, update record id's to reflect exposure configuration.
 */
function aliaser (opts) {
  opts = opts || {};
  var
    stream = new rs.Transform({objectMode: true}),
    mappings = opts.mappings;

  stream._transform = write;

  function write (rec, enc, cb) {
    // User exposed this file under an alternate id.
    if (mappings[rec.file]) {
      rec.id = mappings[rec.file];
    }

    this.push(rec);
    cb();
  }
  // write

  stream.label = "pathmodify:deps:post";

  return stream;
}
// aliaser

function simple (from, to, expose, type) {
  return {from: from, to: to, expose: expose, type: type};
}
// simple

// Functions for generating entries in opts.mods.
plugin.mod = {};

[
  ['id'],
  ['dir'],
  ['re'],
].forEach(function (type_def) {
  var
    type = type_def[0],
    aliases = type_def[1];

  plugin.mod[type] = function (from, to, expose) {
    return simple(from, to, expose, type);
  };

  if (Array.isArray(aliases)) {
    aliases.forEach(function (alias) {
      plugin.mod[alias] = plugin.mod[type];
    });
  }
});


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GL_ARB_vertex_shader'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_vertex_shader',error_checker=_errors._error_checker)
GL_CURRENT_VERTEX_ATTRIB_ARB=_C('GL_CURRENT_VERTEX_ATTRIB_ARB',0x8626)
GL_FLOAT=_C('GL_FLOAT',0x1406)
GL_FLOAT_MAT2_ARB=_C('GL_FLOAT_MAT2_ARB',0x8B5A)
GL_FLOAT_MAT3_ARB=_C('GL_FLOAT_MAT3_ARB',0x8B5B)
GL_FLOAT_MAT4_ARB=_C('GL_FLOAT_MAT4_ARB',0x8B5C)
GL_FLOAT_VEC2_ARB=_C('GL_FLOAT_VEC2_ARB',0x8B50)
GL_FLOAT_VEC3_ARB=_C('GL_FLOAT_VEC3_ARB',0x8B51)
GL_FLOAT_VEC4_ARB=_C('GL_FLOAT_VEC4_ARB',0x8B52)
GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB=_C('GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB',0x8B4D)
GL_MAX_TEXTURE_COORDS_ARB=_C('GL_MAX_TEXTURE_COORDS_ARB',0x8871)
GL_MAX_TEXTURE_IMAGE_UNITS_ARB=_C('GL_MAX_TEXTURE_IMAGE_UNITS_ARB',0x8872)
GL_MAX_VARYING_FLOATS_ARB=_C('GL_MAX_VARYING_FLOATS_ARB',0x8B4B)
GL_MAX_VERTEX_ATTRIBS_ARB=_C('GL_MAX_VERTEX_ATTRIBS_ARB',0x8869)
GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB=_C('GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB',0x8B4C)
GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB=_C('GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB',0x8B4A)
GL_OBJECT_ACTIVE_ATTRIBUTES_ARB=_C('GL_OBJECT_ACTIVE_ATTRIBUTES_ARB',0x8B89)
GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB=_C('GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB',0x8B8A)
GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB',0x8622)
GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB',0x886A)
GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB',0x8645)
GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB',0x8623)
GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB',0x8624)
GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB=_C('GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB',0x8625)
GL_VERTEX_PROGRAM_POINT_SIZE_ARB=_C('GL_VERTEX_PROGRAM_POINT_SIZE_ARB',0x8642)
GL_VERTEX_PROGRAM_TWO_SIDE_ARB=_C('GL_VERTEX_PROGRAM_TWO_SIDE_ARB',0x8643)
GL_VERTEX_SHADER_ARB=_C('GL_VERTEX_SHADER_ARB',0x8B31)
@_f
@_p.types(None,_cs.GLhandleARB,_cs.GLuint,arrays.GLcharARBArray)
def glBindAttribLocationARB(programObj,index,name):pass
@_f
@_p.types(None,_cs.GLuint)
def glDisableVertexAttribArrayARB(index):pass
@_f
@_p.types(None,_cs.GLuint)
def glEnableVertexAttribArrayARB(index):pass
@_f
@_p.types(None,_cs.GLhandleARB,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLintArray,arrays.GLuintArray,arrays.GLcharARBArray)
def glGetActiveAttribARB(programObj,index,maxLength,length,size,type,name):pass
@_f
@_p.types(_cs.GLint,_cs.GLhandleARB,arrays.GLcharARBArray)
def glGetAttribLocationARB(programObj,name):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLvoidpArray)
def glGetVertexAttribPointervARB(index,pname,pointer):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLdoubleArray)
def glGetVertexAttribdvARB(index,pname,params):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLfloatArray)
def glGetVertexAttribfvARB(index,pname,params):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLintArray)
def glGetVertexAttribivARB(index,pname,params):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLdouble)
def glVertexAttrib1dARB(index,x):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLdoubleArray)
def glVertexAttrib1dvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLfloat)
def glVertexAttrib1fARB(index,x):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLfloatArray)
def glVertexAttrib1fvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLshort)
def glVertexAttrib1sARB(index,x):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLshortArray)
def glVertexAttrib1svARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLdouble,_cs.GLdouble)
def glVertexAttrib2dARB(index,x,y):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLdoubleArray)
def glVertexAttrib2dvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLfloat,_cs.GLfloat)
def glVertexAttrib2fARB(index,x,y):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLfloatArray)
def glVertexAttrib2fvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLshort,_cs.GLshort)
def glVertexAttrib2sARB(index,x,y):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLshortArray)
def glVertexAttrib2svARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLdouble,_cs.GLdouble,_cs.GLdouble)
def glVertexAttrib3dARB(index,x,y,z):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLdoubleArray)
def glVertexAttrib3dvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat)
def glVertexAttrib3fARB(index,x,y,z):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLfloatArray)
def glVertexAttrib3fvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLshort,_cs.GLshort,_cs.GLshort)
def glVertexAttrib3sARB(index,x,y,z):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLshortArray)
def glVertexAttrib3svARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLbyteArray)
def glVertexAttrib4NbvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLintArray)
def glVertexAttrib4NivARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLshortArray)
def glVertexAttrib4NsvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLubyte,_cs.GLubyte,_cs.GLubyte,_cs.GLubyte)
def glVertexAttrib4NubARB(index,x,y,z,w):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLubyteArray)
def glVertexAttrib4NubvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLuintArray)
def glVertexAttrib4NuivARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLushortArray)
def glVertexAttrib4NusvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLbyteArray)
def glVertexAttrib4bvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLdouble,_cs.GLdouble,_cs.GLdouble,_cs.GLdouble)
def glVertexAttrib4dARB(index,x,y,z,w):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLdoubleArray)
def glVertexAttrib4dvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat,_cs.GLfloat)
def glVertexAttrib4fARB(index,x,y,z,w):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLfloatArray)
def glVertexAttrib4fvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLintArray)
def glVertexAttrib4ivARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLshort,_cs.GLshort,_cs.GLshort,_cs.GLshort)
def glVertexAttrib4sARB(index,x,y,z,w):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLshortArray)
def glVertexAttrib4svARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLubyteArray)
def glVertexAttrib4ubvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLuintArray)
def glVertexAttrib4uivARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,arrays.GLushortArray)
def glVertexAttrib4usvARB(index,v):pass
@_f
@_p.types(None,_cs.GLuint,_cs.GLint,_cs.GLenum,_cs.GLboolean,_cs.GLsizei,ctypes.c_void_p)
def glVertexAttribPointerARB(index,size,type,normalized,stride,pointer):pass


text:
package com.netflix.spinnaker.clouddriver.titus.client.model;

public class ResizeJobRequest extends AbstractJobRequest {

  private int instancesDesired;
  private int instancesMax;
  private int instancesMin;

  public ResizeJobRequest() {}

  public int getInstancesDesired() {
    return instancesDesired;
  }

  public ResizeJobRequest withInstancesDesired(int instancesDesired) {
    this.instancesDesired = instancesDesired;
    return this;
  }

  public int getInstancesMax() {
    return instancesMax;
  }

  public ResizeJobRequest withInstancesMax(int instancesMax) {
    this.instancesMax = instancesMax;
    return this;
  }

  public int getInstancesMin() {
    return instancesMin;
  }

  public ResizeJobRequest withInstancesMin(int instancesMin) {
    this.instancesMin = instancesMin;
    return this;
  }
}


text:
using Cauldron;
using Cauldron.XAML.ViewModels;
using System;
using System.Reflection;
using System.Threading.Tasks;

namespace Cauldron.XAML.Validation
{
    /// <summary>
    /// Validates the property if value is greater than the given value or the given property
    /// </summary>
    /// <exception cref="ArgumentException">The property was not found</exception>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public sealed class GreaterThanAttribute : ValidatorAttributeBase
    {
        private string propertyName;
        private object value;

        /// <summary>
        /// Initializes a new instance of <see cref="GreaterThanAttribute"/>
        /// </summary>
        /// <param name="value">The value to compare to</param>
        /// <param name="errorMessageKey">The key of the localized error message string</param>
        public GreaterThanAttribute(object value, string errorMessageKey) : base(errorMessageKey)
        {
            this.value = value;
        }

        /// <summary>
        /// Initializes a new instance of <see cref="GreaterThanAttribute"/>
        /// </summary>
        /// <param name="propertyName">The name of the property to validate against</param>
        /// <param name="errorMessageKey">The key of the localized error message string</param>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null</exception>
        public GreaterThanAttribute(string propertyName, string errorMessageKey) : base(errorMessageKey)
        {
            if (propertyName == null)
                throw new ArgumentNullException(nameof(propertyName));

            this.propertyName = propertyName;
        }

        /// <summary>
        /// Invokes the validation on the specified context with the specified parameters
        /// </summary>
        /// <param name="sender">The property that invoked the validation</param>
        /// <param name="context">The Viewmodel context that has to be validated</param>
        /// <param name="propertyInfo">The <see cref="PropertyInfo"/> of the validated property</param>
        /// <param name="value">The value of the property</param>
        /// <returns>Has to return true on validation error otherwise false</returns>
        protected override Task<bool> OnValidateAsync(PropertyInfo sender, IValidatableViewModel context, PropertyInfo propertyInfo, object value)
        {
            // if the value is null, then we should return a validation successfull, so that it is
            // possible to have non mandatory inputs
            if (value == null)
                return Task.FromResult(false);

            if (this.value != null)
                return Task.FromResult(!Comparer.GreaterThan(value, this.value));

            var otherProperty = context.GetType().GetPropertyEx(this.propertyName);

            if (otherProperty == null)
                throw new ArgumentException(string.Format("The property '{0}' was not found on '{1}'.", this.propertyName, context.GetType().FullName));

            // Also same for this value
            var comparisonValue = otherProperty.GetValue(context);

            if (comparisonValue == null)
                return Task.FromResult(false);

            return Task.FromResult(!Comparer.GreaterThan(value, comparisonValue));
        }

        /// <summary>
        /// Occures on validation
        /// <para/>
        /// Can be used to modify the validation error message.
        /// </summary>
        /// <param name="errorMessage">The validation error message</param>
        /// <param name="context">The Viewmodel context that has to be validated</param>
        /// <returns>A modified validation error message</returns>
        protected override string ValidationMessage(string errorMessage, IValidatableViewModel context)
        {
            if (this.value != null)
                return string.Format(errorMessage, this.value);

            var otherProperty = context.GetType().GetPropertyEx(this.propertyName);

            if (otherProperty == null)
                return errorMessage;

            return errorMessage.ToString(otherProperty.GetValue(context));
        }
    }
}


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2012 Live Networks, Inc.  All rights reserved.
// Inclusion of header files representing the interface
// for the entire library
//
// Programs that use the library can include this header file,
// instead of each of the individual media header files

#ifndef _LIVEMEDIA_HH
#define _LIVEMEDIA_HH

#include "MPEG1or2AudioRTPSink.hh"
#include "MP3ADURTPSink.hh"
#include "MPEG1or2VideoRTPSink.hh"
#include "MPEG4ESVideoRTPSink.hh"
#include "AMRAudioFileSink.hh"
#include "H264VideoFileSink.hh"
#include "BasicUDPSink.hh"
#include "GSMAudioRTPSink.hh"
#include "H263plusVideoRTPSink.hh"
#include "H264VideoRTPSink.hh"
#include "DVVideoRTPSource.hh"
#include "DVVideoRTPSink.hh"
#include "DVVideoStreamFramer.hh"
#include "H264VideoStreamDiscreteFramer.hh"
#include "JPEGVideoRTPSink.hh"
#include "SimpleRTPSink.hh"
#include "uLawAudioFilter.hh"
#include "MPEG2IndexFromTransportStream.hh"
#include "MPEG2TransportStreamTrickModeFilter.hh"
#include "ByteStreamMultiFileSource.hh"
#include "ByteStreamMemoryBufferSource.hh"
#include "BasicUDPSource.hh"
#include "SimpleRTPSource.hh"
#include "MPEG1or2AudioRTPSource.hh"
#include "MPEG4LATMAudioRTPSource.hh"
#include "MPEG4LATMAudioRTPSink.hh"
#include "MPEG4ESVideoRTPSource.hh"
#include "MPEG4GenericRTPSource.hh"
#include "MP3ADURTPSource.hh"
#include "QCELPAudioRTPSource.hh"
#include "AMRAudioRTPSource.hh"
#include "JPEGVideoRTPSource.hh"
#include "JPEGVideoSource.hh"
#include "MPEG1or2VideoRTPSource.hh"
#include "VorbisAudioRTPSource.hh"
#include "VP8VideoRTPSource.hh"
#include "MPEG2TransportStreamFromPESSource.hh"
#include "MPEG2TransportStreamFromESSource.hh"
#include "MPEG2TransportStreamFramer.hh"
#include "ADTSAudioFileSource.hh"
#include "H261VideoRTPSource.hh"
#include "H263plusVideoRTPSource.hh"
#include "H264VideoRTPSource.hh"
#include "MP3HTTPSource.hh"
#include "MP3ADU.hh"
#include "MP3ADUinterleaving.hh"
#include "MP3Transcoder.hh"
#include "MPEG1or2DemuxedElementaryStream.hh"
#include "MPEG1or2AudioStreamFramer.hh"
#include "H263plusVideoStreamFramer.hh"
#include "AC3AudioStreamFramer.hh"
#include "AC3AudioRTPSource.hh"
#include "AC3AudioRTPSink.hh"
#include "VorbisAudioRTPSink.hh"
#include "VP8VideoRTPSink.hh"
#include "MPEG4GenericRTPSink.hh"
#include "MPEG1or2VideoStreamDiscreteFramer.hh"
#include "MPEG4VideoStreamDiscreteFramer.hh"
#include "DeviceSource.hh"
#include "AudioInputDevice.hh"
#include "WAVAudioFileSource.hh"
#include "RTSPServerSupportingHTTPStreaming.hh"
#include "RTSPClient.hh"
#include "SIPClient.hh"
#include "QuickTimeFileSink.hh"
#include "QuickTimeGenericRTPSource.hh"
#include "AVIFileSink.hh"
#include "PassiveServerMediaSubsession.hh"
#include "MPEG4VideoFileServerMediaSubsession.hh"
#include "H264VideoFileServerMediaSubsession.hh"
#include "WAVAudioFileServerMediaSubsession.hh"
#include "AMRAudioFileServerMediaSubsession.hh"
#include "AMRAudioFileSource.hh"
#include "AMRAudioRTPSink.hh"
#include "T140TextRTPSink.hh"
#include "TCPStreamSink.hh"
#include "MP3AudioFileServerMediaSubsession.hh"
#include "MPEG1or2VideoFileServerMediaSubsession.hh"
#include "MPEG1or2FileServerDemux.hh"
#include "MPEG2TransportFileServerMediaSubsession.hh"
#include "H263plusVideoFileServerMediaSubsession.hh"
#include "ADTSAudioFileServerMediaSubsession.hh"
#include "DVVideoFileServerMediaSubsession.hh"
#include "AC3AudioFileServerMediaSubsession.hh"
#include "MatroskaFileServerDemux.hh"
#include "DarwinInjector.hh"

#endif


text:
const config = require('./config')
const readme = require('./xampp/readme')

module.exports = function () {
  console.log()
  console.log('XAMPP is installed at', config.xamppInstallDir)
  console.log()
  run()
}

async function run() {
  const text = await readme()
  const lines = text.split('\n')
  console.log(lines[0])
  console.log()

  let started = false
  for (var i = 1; i < lines.length; i++) {
    const line = lines[i]
    if (line.startsWith('  +')) {
      started = true
      console.log(line)
    } else if (started) {
      break
    }
  }
  console.log()
}


text:
package com.thevoxelbox.fmoka.compiler.c.emitter.insn;

import com.thevoxelbox.fmoka.ast.insn.var.LocalAccess;
import com.thevoxelbox.fmoka.compiler.c.emitter.CEmitter;
import com.thevoxelbox.fmoka.compiler.c.emitter.InstructionEmitter;
import com.thevoxelbox.fmoka.compiler.error.CompileException;

public class LocalAccessEmitter implements InstructionEmitter<LocalAccess> {

    @Override
    public void emit(CEmitter emitter, LocalAccess insn, String type) throws CompileException {
        emitter.print(insn.getLocal().getName());
    }

}


text:
<?php
/**
 * API Log Event Controller
 *
 * @author tmannherz
 */
class Grommet_ApiLog_Adminhtml_ApilogController extends Mage_Adminhtml_Controller_Action
{

	/**
	 * Additional initialization
	 */
	protected function _construct ()
	{
		$this->setUsedModuleName('Grommet_ApiLog');
	}

	/**
	 * Initializes the model for use.
	 *
	 * @param string $idField
	 * @return bool|Grommet_ApiLog_Model_Event
	 */
	protected function _initModel ($idField = 'id')
	{
		$id = (int)$this->getRequest()->getParam($idField);
		$model = Mage::getModel('apilog/event');
		if ($id) {
			$model->load($id);
			if (!$model->getId()) {
				$this->getSession()->addError(Mage::helper('apilog')->__('The event you are trying to access no longer exists.'));
				$this->_redirect('*/*');
				return false;
			}
		}
		Mage::register('current_event', $model);
		return $model;
	}

	/**
	 * Grid
	 */
	public function indexAction ()
	{
		$this->_title($this->__('System'))
			->_title($this->__('API Event Log'));

		$this->loadLayout();
		$this->_setActiveMenu('system/apilog');
		$this->renderLayout();
	}

	/**
	 * AJAX grid
	 */
	public function gridAction ()
	{
		$this->loadLayout(false);
		$this->renderLayout();
	}

	/**
	 * View event details
	 */
	public function viewAction ()
	{
		if ($this->_initModel()) {
			$this->_title($this->__('System'))
				->_title($this->__('API Event Log'))
				->_title($this->__('View Event'));

			$this->loadLayout();
			$this->_setActiveMenu('system/apilog');
			$this->renderLayout();
		}
	}

	/**
	 * Export log to CSV
	 */
	public function exportCsvAction ()
	{
		$this->_prepareDownloadResponse('apilog.csv', $this->getLayout()->createBlock('apilog/adminhtml_event_grid')->getCsvFile());
	}

	/**
	 * Export log to XML
	 */
	public function exportXmlAction ()
	{
		$this->_prepareDownloadResponse('apilog.xml', $this->getLayout()->createBlock('apilog/adminhtml_event_grid')->getExcelFile());
	}

	/**
	 * ACL check
	 *
	 * @return bool
	 */
	protected function _isAllowed ()
	{
		return Mage::getSingleton('admin/session')->isAllowed('admin/system/api/apilog');
	}
}


text:
/* $Id: recode-insns.c,v 1.4 2010/02/07 17:32:01 fredette Exp $ */

/* libtme/recode-insns.c - generic recode instruction support: */

/*
 * Copyright (c) 2008 Matt Fredette
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Matt Fredette.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <tme/common.h>
_TME_RCSID("$Id: recode-insns.c,v 1.4 2010/02/07 17:32:01 fredette Exp $");

#if TME_HAVE_RECODE

/* includes: */
#include "recode-impl.h"

/* macros: */

/* the undefined flags offset: */
#define TME_RECODE_FLAGS_OFFSET_UNDEF	(0 - (tme_uint32_t) 1)

/* this returns the thunk offset for a new instructions thunk.  it
   returns less than zero when thunks memory is exhausted and all
   instructions thunks are flushed: */
tme_recode_thunk_off_t
tme_recode_insns_thunk(struct tme_recode_ic *ic,
		       const struct tme_recode_insns_group *insns_group)
{
  signed long reg_guest;
  signed long ruses_record_tmp;
  signed long ruses_record_right;
  tme_uint32_t flags_offset;
  tme_recode_uguest_t flags_needed;
  tme_uint32_t flags_offset_else;
  tme_recode_uguest_t flags_needed_else;
  struct tme_recode_insn *insns;
  struct tme_recode_insn *insn;
  tme_uint32_t opcode_mask;
  signed long operand_i;
  tme_uint32_t ruses;
  const struct tme_recode_flags_thunk *flags_thunk;
  const struct tme_recode_conds_thunk *conds_thunk;

  /* initialize the mapping from host register to read-uses count for
     a cached guest register, to all host registers free: */
#if TME_RECODE_REG_RUSES_FREE != 0
#error "TME_RECODE_REG_RUSES_FREE changed"
#endif
  memset(ic->tme_recode_ic_reg_host_to_ruses,
	 TME_RECODE_REG_RUSES_FREE,
	 sizeof(ic->tme_recode_ic_reg_host_to_ruses));

  /* there are no reserved registers: */
  ic->tme_recode_ic_reg_host_reserve_next = 0;

  /* initialize the read-uses counts for all guest registers.  this
     also marks the guest register tags as invalid: */
  reg_guest = TME_RECODE_REG_GUEST(ic->tme_recode_ic_reg_count - 1);
  do {
    ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses = (TME_RECODE_REG_RUSES_FREE + 1);
  } while (--reg_guest >= TME_RECODE_REG_GUEST(0));

  /* the largest guest register number must fit in
     [TME_RECODE_REG_RUSES_RECORD_REG_GUEST(0)..TME_RECODE_REG_RUSES_RECORD_UNDEF): */
  assert (ic->tme_recode_ic_reg_count
	  < (TME_RECODE_REG_RUSES_RECORD_UNDEF
	     - TME_RECODE_REG_RUSES_RECORD_REG_GUEST(0)));

  /* reset the read-uses records: */
  ruses_record_tmp = 0;
  ruses_record_right = ic->tme_recode_ic_reg_guest_ruses_record_count;
  assert (ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right]
	  == TME_RECODE_REG_RUSES_RECORD_UNDEF);

  /* we haven't found any flags register yet: */
  flags_offset = TME_RECODE_FLAGS_OFFSET_UNDEF;
  flags_needed = 0;
  flags_offset_else = TME_RECODE_FLAGS_OFFSET_UNDEF;
  flags_needed_else = 0;

  /* loop over the instructions, from last to first: */
  insns = insns_group->tme_recode_insns_group_insns;
  insn = insns_group->tme_recode_insns_group_insns_end;
  do {
    insn--;

    /* get the bitmask for this instruction's opcode: */
    opcode_mask = (1 << insn->tme_recode_insn_opcode);

    /* if this is an else instruction, or an endif instruction, or a
       guest instruction with unknown destination registers: */
    if ((opcode_mask
	 & ((1 << TME_RECODE_OPCODE_ELSE)
	    | (1 << TME_RECODE_OPCODE_ENDIF)))
	|| ((opcode_mask & (1 << TME_RECODE_OPCODE_GUEST))
	    && insn->tme_recode_insn_operand_dst == TME_RECODE_OPERAND_NULL)) {

      /* if there are no guest register writes between this else,
	 endif, or guest instruction and the next else, endif, or
	 guest instruction: */
      if (ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right]
	  >= TME_RECODE_REG_RUSES_RECORD_REG_GUEST(0)) {

	/* if we can, make a delimiter between any initial read-uses
	   records that we're about to make, and the initial read-uses
	   records that we previously made: */
	if (ruses_record_right > 0) {
	  ruses_record_right--;
	  ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right]
	    = TME_RECODE_REG_RUSES_RECORD_UNDEF;
	}
      }

      /* loop over any temporary read-uses records: */
      for (; ruses_record_tmp > 0; ) {

	/* if this temporary read-uses record was overwritten by a
	   write read-uses record: */
	ruses_record_tmp--;
	if (ruses_record_tmp >= ruses_record_right) {

	  /* skip to the last temporary read-uses record that hasn't
	     been overwritten yet: */
	  ruses_record_tmp = ruses_record_right;
	  continue;
	}

	/* get the guest register: */
	reg_guest = ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_tmp];

	/* get this guest register's read-uses count: */
	ruses = ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses;

	/* if this guest register has a read use before any first
	   write after this else, endif, or guest instruction: */
	if (ruses > (TME_RECODE_REG_RUSES_FREE + 1)) {

	  /* reset this guest register's read-uses count: */
	  ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses = (TME_RECODE_REG_RUSES_FREE + 1);

	  /* if we can't make another initial read-uses record, stop now: */
	  if (ruses_record_right < 2) {
	    break;
	  }

	  /* make the initial read-uses record: */
	  ruses_record_right -= 2;
	  ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right + 0]
	    = TME_RECODE_REG_RUSES_RECORD_REG_GUEST(reg_guest);
	  ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right + 1] = ruses;
	}
      }
    }

    /* if this is an integer, or guest, or read/write instruction: */
    if (opcode_mask
	& (((1 << TME_RECODE_OPCODES_INTEGER) - 1)
	   | (1 << TME_RECODE_OPCODE_GUEST)
	   | (1 << TME_RECODE_OPCODE_RW))) {

      /* if the destination operand is a guest register: */
      reg_guest = insn->tme_recode_insn_operand_dst;
      if (reg_guest >= TME_RECODE_REG_GUEST(0)) {

	/* if this guest register is not fixed: */
	if ((ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_all
	     & TME_RECODE_REGINFO_TYPE_FIXED) == 0) {

	  /* get and reset this guest register's read-uses count: */
	  ruses = ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses;
	  ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses = (TME_RECODE_REG_RUSES_FREE + 1);

	  /* make a write read-uses record: */
	  if (ruses_record_right > 0) {
	    ruses_record_right--;
	  }
	  ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_right] = ruses;
	}
      }

      /* all integer and guest instructions can have a guest register
	 as the first source operand.  all of those instructions can
	 also have a guest register as the second source operand,
	 except for the zero- and sign-extension instructions, which
	 always have a TME_RECODE_SIZE for their second source
	 operand: */
      operand_i
	= ((opcode_mask
	    & ((1 << TME_RECODE_OPCODE_EXTZ)
	       | (1 << TME_RECODE_OPCODE_EXTS)))
	   == 0);

      /* loop over the source operands that can be guest registers: */
      do {

	/* if this source operand is a guest register: */
	reg_guest = insn->tme_recode_insn_operand_src[operand_i];
	if (reg_guest >= TME_RECODE_REG_GUEST(0)) {

	  /* get this guest register's current read-uses count: */
	  ruses = ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses;

	  /* if this guest register's current read-uses count is the
	     minimum: */
	  if (ruses == (TME_RECODE_REG_RUSES_FREE + 1)) {

	    /* if we can, make a temporary read-uses record for this
	       guest register: */
	    if (ruses_record_tmp < ruses_record_right) {
	      ic->tme_recode_ic_reg_guest_ruses_records[ruses_record_tmp] = reg_guest;
	      ruses_record_tmp++;
	    }
	  }

	  /* increment the guest register's current read-uses count,
	     unless it would become TME_RECODE_REG_RUSES_RESERVED: */
	  if (__tme_predict_true(ruses < (TME_RECODE_REG_RUSES_RESERVED - 1))) {
	    ruses++;
	  }
	  ic->tme_recode_ic_reginfo[reg_guest].tme_recode_reginfo_tags_ruses = ruses;
	}
      } while (--operand_i >= 0);
    }

    /* if this is an integer instruction: */
    if (opcode_mask & ((1 << TME_RECODE_OPCODES_INTEGER) - 1)) {

      /* if the second source operand is a zero, and the operation is
	 commutative: */
      if (insn->tme_recode_insn_operand_src[1] == TME_RECODE_OPERAND_ZERO) {
	if (opcode_mask
	    & ((1 << TME_RECODE_OPCODE_AND)
	       | (1 << TME_RECODE_OPCODE_OR)
	       | (1 << TME_RECODE_OPCODE_XOR)
	       | (1 << TME_RECODE_OPCODE_ADD)
	       | (1 << TME_RECODE_OPCODE_ADDC))) {

	  /* we have the convention of always putting a zero source
	     operand first whenever possible, so swap the first and
	     second source operands: */
	  insn->tme_recode_insn_operand_src[1] = insn->tme_recode_insn_operand_src[0];
	  insn->tme_recode_insn_operand_src[0] = TME_RECODE_OPERAND_ZERO;
	}
      }

      /* if this integer instruction can change flags: */
      flags_thunk = insn->tme_recode_insn_flags_thunk;
      if (flags_thunk != NULL) {

	/* if this integer instruction changes flags in a different
	   flags register: */
	if (__tme_predict_false(flags_offset != flags_thunk->tme_recode_flags_thunk_flags_offset)) {

	  /* switch to this different flags register, and need all of
	     its flags: */
	  flags_offset = flags_thunk->tme_recode_flags_thunk_flags_offset;
	  flags_needed = 0 - (tme_recode_uguest_t) 1;
	}

	/* if this integer instruction doesn't define any of the flags
	   in this flags register needed by later instructions: */
	if ((flags_needed & flags_thunk->tme_recode_flags_thunk_flags_defined) == 0) {

	  /* this integer instruction doesn't need to define flags any
	     more: */
	  insn->tme_recode_insn_flags_thunk = NULL;
	}

	/* any earlier instruction that also defines flags in this
	   flags register, doesn't need to define any of the flags
	   that this instruction changes: */
	flags_needed &= ~flags_thunk->tme_recode_flags_thunk_flags_changed;
      }
    }

    /* if this is a defc instruction: */
    else if (opcode_mask == (1 << TME_RECODE_OPCODE_DEFC)) {

      /* get the conditions thunk for this instruction: */
      conds_thunk = insn->tme_recode_insn_conds_thunk;

      /* if this defc instruction tests flags in a different flags register: */
      if (__tme_predict_false(flags_offset != conds_thunk->tme_recode_conds_thunk_flags_offset)) {

	/* switch to this different flags register, and need all of
	   its flags: */
	flags_offset = conds_thunk->tme_recode_conds_thunk_flags_offset;
	flags_needed = 0 - (tme_recode_uguest_t) 1;
      }

      /* any earlier instruction that can define flags tested by this
	 defc instruction, needs to define those flags: */
      flags_needed |= conds_thunk->tme_recode_conds_thunk_flags;
    }

    /* if this is an endif instruction: */
    else if (opcode_mask == (1 << TME_RECODE_OPCODE_ENDIF)) {

      /* if we find an earlier else, as an optimization we can restore
	 the flags needed by the instructions after the endif, so save
	 them now: */
      flags_offset_else = flags_offset;
      flags_needed_else = flags_needed;
    }

    /* if this is an else instruction: */
    else if (opcode_mask == (1 << TME_RECODE_OPCODE_ELSE)) {

      /* restore the flags needed by the instructions after the endif: */
      flags_offset = flags_offset_else;
      flags_needed = flags_needed_else;
    }

    /* otherwise, this must be a guest, read/write, or if instruction: */
    else {
      assert (opcode_mask
	      & ((1 << TME_RECODE_OPCODE_GUEST)
		 | (1 << TME_RECODE_OPCODE_RW)
		 | (1 << TME_RECODE_OPCODE_IF)
		 ));

      /* since a guest function may fault and never return, we have to
	 make sure that all flags are correct in the guest ic state at
	 the time of the fault.

	 since a read/write instruction may fault and never return, we
	 have to make sure that all flags are correct in the guest ic
	 state at the time of the fault.

	 since an if body may not run, we have to make sure that all
	 flags are correct in the guest ic state at the time of the
	 if.

	 since a jump may never return, we have to make sure that all
	 flags are correct in the guest ic state at the time of the
	 jump.

	 in all of these cases, we need any earlier instruction that
	 can define flags to do so: */
      flags_needed = 0 - (tme_recode_uguest_t) 1;
    }

  } while (insn > insns);

  /* set the next read-uses record: */
  ic->tme_recode_ic_reg_guest_ruses_record_next = ruses_record_right;

  /* build the new instructions thunk: */
  return (tme_recode_host_insns_thunk_new(ic,
					  insns_group));
}

/* this invalidates all instructions thunks: */
void
tme_recode_insns_thunk_invalidate_all(struct tme_recode_ic *ic)
{

  /* invalidate all instructions thunks: */
  tme_recode_host_thunk_invalidate_all(ic, ic->tme_recode_ic_thunk_off_variable);
}

#endif /* TME_HAVE_RECODE */


text:
import sys, datetime

class Hacker:
    def __init__ (self, name, id, elist, email):
        self.name = name
        self.id = id
        self.employer = [ elist ]
        self.email = [ email ]
        self.changed = self.added = self.removed = 0
        self.patches = [ ]
        self.signoffs = [ ]
        self.reviews = [ ]
        self.tested = [ ]
        self.reports = [ ]
        self.testcred = self.repcred = 0
        self.activity_start = datetime.date.max
        self.activity_end = datetime.date.min
        self.versions = [ ]

    def addemail (self, email, elist):
        self.email.append (email)
        self.employer.append (elist)
        HackersByEmail[email] = self

    def emailemployer (self, email, date):
        for i in range (0, len (self.email)):
            if (email is None) or (self.email[i] == email):
                for edate, empl in self.employer[i]:
                    if edate > date:
                        return empl
        print 'OOPS.  ', self.name, self.employer, self.email, email, date
        return None # Should not happen

    def addpatch (self, patch):
        self.added += patch.added
        self.removed += patch.removed
        self.changed += max(patch.added, patch.removed)
        self.patches.append (patch)
        if patch.date < self.activity_start:
            self.activity_start = patch.date
        if patch.date > self.activity_end:
            self.activity_end= patch.date

    #
    # Note that the author is represented in this release.
    #
    def addversion (self, release):
        if release not in self.versions:
            self.versions.append (release)
    #
    # There's got to be a better way.
    #
    def addsob (self, patch):
        self.signoffs.append (patch)
    def addreview (self, patch):
        self.reviews.append (patch)
    def addtested (self, patch):
        self.tested.append (patch)
    def addreport (self, patch):
        self.reports.append (patch)

    def reportcredit (self, patch):
        self.repcred += 1
    def testcredit (self, patch):
        self.testcred += 1

HackersByName = { }
HackersByEmail = { }
HackersByID = { }
MaxID = 0

def StoreHacker (name, elist, email):
    global MaxID

    id = MaxID
    MaxID += 1
    h = Hacker (name, id, elist, email)
    HackersByName[name] = h
    HackersByEmail[email] = h
    HackersByID[id] = h
    return h

def LookupEmail (addr):
    try:
        return HackersByEmail[addr]
    except KeyError:
        return None

def LookupName (name):
    try:
        return HackersByName[name]
    except KeyError:
        return None

def LookupID (id):
    try:
        return HackersByID[id]
    except KeyError:
        return None

def LookupStoreHacker(name, email, mapunknown = True):
    email = RemapEmail(email)
    h = LookupEmail(email)
    if h: # already there
        return h
    elist = LookupEmployer(email, mapunknown)
    h = LookupName(name)
    if h: # new email
        h.addemail(email, elist)
        return h
    return StoreHacker(name, elist, email)

def AllHackers ():
    return HackersByID.values ()

def DumpDB ():
    out = open ('database.dump', 'w')
    names = HackersByName.keys ()
    names.sort ()
    for name in names:
        h = HackersByName[name]
        out.write ('%4d %s %d p (+%d -%d) sob: %d\n' % (h.id, h.name,
                                                        len (h.patches),
                                                        h.added, h.removed,
                                                        len (h.signoffs)))
        for i in range (0, len (h.email)):
            out.write ('\t%s -> \n' % (h.email[i]))
            for date, empl in h.employer[i]:
                out.write ('\t\t %d-%d-%d %s\n' % (date.year, date.month, date.day,
                                                 empl.name))
        if h.versions:
            out.write ('\tVersions: %s\n' % ','.join (h.versions))

#
# Hack: The first visible tag comes a ways into the stream; when we see it,
# push it backward through the changes we've already seen.
#
def ApplyFirstTag (tag):
    for n in HackersByName.keys ():
        if HackersByName[n].versions:
            HackersByName[n].versions = [tag]

#
# Employer info.
#
class Employer:
    def __init__ (self, name):
        self.name = name
        self.added = self.removed = self.count = self.changed = 0
        self.sobs = 0
        self.hackers = [ ]

    def AddCSet (self, patch):
        self.added += patch.added
        self.removed += patch.removed
        self.changed += max(patch.added, patch.removed)
        self.count += 1
        if patch.author not in self.hackers:
            self.hackers.append (patch.author)

    def AddSOB (self):
        self.sobs += 1

Employers = { }

def GetEmployer (name):
    try:
        return Employers[name]
    except KeyError:
        e = Employer (name)
        Employers[name] = e
        return e

def AllEmployers ():
    return Employers.values ()

#
# Certain obnoxious developers, who will remain nameless (because we
# would never want to run afoul of Thomas) want their work split among
# multiple companies.  Let's try to cope with that.  Let's also hope
# this doesn't spread.
#
class VirtualEmployer (Employer):
    def __init__ (self, name):
        Employer.__init__ (self, name)
        self.splits = [ ]

    def addsplit (self, name, fraction):
        self.splits.append ((name, fraction))

    #
    # Go through and (destructively) apply our credits to the
    # real employer.  Only one level of weirdness is supported.
    #
    def applysplits (self):
        for name, fraction in self.splits:
            real = GetEmployer (name)
            real.added += int (self.added*fraction)
            real.removed += int (self.removed*fraction)
            real.changed += int (self.changed*fraction)
            real.count += int (self.count*fraction)
        self.__init__ (name) # Reset counts just in case

    def store (self):
        if Employers.has_key (self.name):
            print Employers[self.name]
            sys.stderr.write ('WARNING: Virtual empl %s overwrites another\n'
                              % (self.name))
        if len (self.splits) == 0:
            sys.stderr.write ('WARNING: Virtual empl %s has no splits\n'
                              % (self.name))
            # Should check that they add up too, but I'm lazy
        Employers[self.name] = self

class FileType:
    def __init__ (self, patterns={}, order=[]):
        self.patterns = patterns
        self.order = order

    def guess_file_type (self, filename, patterns=None, order=None):
        patterns = patterns or self.patterns
        order = order or self.order

        for file_type in order:
            if patterns.has_key (file_type):
                for patt in patterns[file_type]:
                    if patt.search (filename):
                        return file_type

        return 'unknown'

#
# By default we recognize nothing.
#
FileTypes = FileType ({}, [])

#
# Mix all the virtual employers into their real destinations.
#
def MixVirtuals ():
    for empl in AllEmployers ():
        if isinstance (empl, VirtualEmployer):
            empl.applysplits ()

#
# The email map.
#
EmailAliases = { }

def AddEmailAlias (variant, canonical):
    if EmailAliases.has_key (variant):
        sys.stderr.write ('Duplicate email alias for %s\n' % (variant))
    EmailAliases[variant] = canonical

def RemapEmail (email):
    email = email.lower ()
    try:
        return EmailAliases[email]
    except KeyError:
        return email

#
# Email-to-employer mapping.
#
EmailToEmployer = { }
nextyear = datetime.date.today () + datetime.timedelta (days = 365)

def AddEmailEmployerMapping (email, employer, end = nextyear):
    if end is None:
        end = nextyear
    email = email.lower ()
    empl = GetEmployer (employer)
    try:
        l = EmailToEmployer[email]
        for i in range (0, len(l)):
            date, xempl = l[i]
            if date == end:  # probably both nextyear
                print 'WARNING: duplicate email/empl for %s' % (email)
            if date > end:
                l.insert (i, (end, empl))
                return
        l.append ((end, empl))
    except KeyError:
        EmailToEmployer[email] = [(end, empl)]

def MapToEmployer (email, unknown = 0):
    # Somebody sometimes does s/@/ at /; let's fix it.
    email = email.lower ().replace (' at ', '@')
    try:
        return EmailToEmployer[email]
    except KeyError:
        pass
    namedom = email.split ('@')
    if len (namedom) < 2:
        print 'Oops...funky email %s' % email
        return [(nextyear, GetEmployer ('Funky'))]
    s = namedom[1].split ('.')
    for dots in range (len (s) - 2, -1, -1):
        addr = '.'.join (s[dots:])
        try:
            return EmailToEmployer[addr]
        except KeyError:
            pass
    #
    # We don't know who they work for.
    #
    if unknown:
        return [(nextyear, GetEmployer ('(Unknown)'))]
    return [(nextyear, GetEmployer (email))]

def LookupEmployer (email, mapunknown = 0):
    elist = MapToEmployer (email, mapunknown)
    return elist # GetEmployer (ename)


text:
package foulkon

import (
	"io"
	"os"

	"errors"

	"fmt"

	"time"

	"github.com/Tecsisa/foulkon/api"
	"github.com/pelletier/go-toml"
	"github.com/sirupsen/logrus"

	"github.com/Tecsisa/foulkon/database/postgresql"
)

var proxyLogfile *os.File

// Proxy - Authorize resources using definitions in proxy config file
type Proxy struct {
	// Server config
	Host string
	Port string

	// Worker location
	WorkerHost string

	// Proxy Flush Interval Duration for flushing data in reverse proxy calls
	ProxyFlushInterval time.Duration

	// TLS configuration
	CertFile string
	KeyFile  string

	// API
	ProxyApi api.InternalProxyAPI

	// Refresh time
	RefreshTime time.Duration
}

func NewProxy(config *toml.Tree) (*Proxy, error) {
	// Create logger
	var logOut io.Writer
	var err error
	logOut = os.Stdout
	loggerType := getDefaultValue(config, "logger.type", "Stdout")
	if loggerType == "file" {
		logFileDir := getDefaultValue(config, "logger.file.dir", "/tmp/foulkon.log")
		proxyLogfile, err = os.OpenFile(logFileDir, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			return nil, err
		}
		logOut = proxyLogfile
	}
	// Loglevel. defaults to INFO
	loglevel, err := logrus.ParseLevel(getDefaultValue(config, "logger.level", "info"))
	if err != nil {
		loglevel = logrus.InfoLevel
	}

	api.Log = &logrus.Logger{
		Out:       logOut,
		Formatter: &logrus.JSONFormatter{},
		Hooks:     make(logrus.LevelHooks),
		Level:     loglevel,
	}
	api.Log.Infof("Logger type: %v, LogLevel: %v", loggerType, api.Log.Level.String())

	// Start DB with API
	var prApi api.ProxyAPI

	dbType, err := getMandatoryValue(config, "database.type")
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}
	switch dbType {
	case "postgres": // PostgreSQL DB
		api.Log.Info("Connecting to postgres database")
		dbdsn, err := getMandatoryValue(config, "database.postgres.datasourcename")
		if err != nil {
			api.Log.Error(err)
			return nil, err
		}
		gormDB, err := postgresql.InitDb(dbdsn,
			getDefaultValue(config, "database.postgres.idleconns", "5"),
			getDefaultValue(config, "database.postgres.maxopenconns", "20"),
			getDefaultValue(config, "database.postgres.connttl", "300"),
		)
		if err != nil {
			api.Log.Error(err)
			return nil, err
		}
		db = gormDB.DB()
		api.Log.Info("Connected to postgres database")

		// Create repository
		repoDB := postgresql.PostgresRepo{
			Dbmap: gormDB,
		}
		prApi = api.ProxyAPI{
			ProxyRepo: repoDB,
		}

	default:
		err := errors.New("Unexpected db_type value in configuration file (Maybe it is empty)")
		api.Log.Error(err)
		return nil, err
	}

	host, err := getMandatoryValue(config, "server.host")
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}
	port, err := getMandatoryValue(config, "server.port")
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}
	workerHost, err := getMandatoryValue(config, "server.worker-host")
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}

	proxyFlushInterval, err := time.ParseDuration(getDefaultValue(config, "server.proxy_flush_interval", "500ms"))
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}

	refresh, err := time.ParseDuration(getDefaultValue(config, "resources.refresh", "10s"))
	if err != nil {
		api.Log.Error(err)
		return nil, err
	}

	return &Proxy{
		Host:               host,
		Port:               port,
		WorkerHost:         workerHost,
		CertFile:           getDefaultValue(config, "server.certfile", ""),
		KeyFile:            getDefaultValue(config, "server.keyfile", ""),
		ProxyApi:           prApi,
		ProxyFlushInterval: proxyFlushInterval,
		RefreshTime:        refresh,
	}, nil
}

func CloseProxy() int {
	status := 0
	if err := db.Close(); err != nil {
		api.Log.Errorf("Couldn't close DB connection: %v", err)
		status = 1
	}
	if proxyLogfile != nil {
		if err := proxyLogfile.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't close logfile: %v", err)
			status = 1
		}
	}
	return status
}


text:
module Oj
  # Current version of the module.
  VERSION = '2.14.0'
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>linseg</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="linrand.html" title="linrand" />
    <link rel="next" href="linsegb.html" title="linsegb" />

          linseg

          Prev
          Orchestra Opcodes and Operators
           Next

          linseg

linseg —
      Trace a series of line segments between specified points.

Description

      Trace a series of line segments between specified points.

Syntax

ares linseg ia, idur1, ib [, idur2] [, ic] [...]

kres linseg ia, idur1, ib [, idur2] [, ic] [...]

Initialization

      ia -- starting value.

      ib, ic, etc. -- value after dur1 seconds, etc.

      idur1 -- duration in seconds of first segment. A zero or negative value will cause all initialization to be skipped.

      idur2, idur3, etc. -- duration in seconds of subsequent segments. A zero or negative value will terminate the initialization process with the preceding point, permitting the last-defined line or curve to be continued indefinitely in performance. The default is zero.

Performance

      These units generate control or audio signals whose values can pass through 2 or more specified points. The sum of dur values may or may not equal the instrument's performance time: a shorter performance will truncate the specified pattern, while a longer one will cause the last value to be repeated until the end of the note.

Examples

      Here is an example of the linseg opcode. It uses the file linseg.csd.

            Example 445. Example of the linseg opcode.

See the sections Real-time Audio and Command Line Flags for more information on using command line flags.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac      ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if realtime audio input is needed too
; For Non-realtime ouput leave only the line below:
;-o linseg.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

giSine ftgen 0, 0, 2^10, 10, 1

instr 1

kcps = cpspch(p4)
kenv linseg 0, 0.25, 1, 0.75, 0	; together = 1 sec
asig poscil kenv, kcps, giSine
     outs asig, asig

endin

instr 2	; scaling to duration

kcps = cpspch(p4)
kenv linseg 0, p3*0.25, 1, p3*0.75, 0
asig poscil kenv, kcps, giSine
     outs asig, asig

endin

instr 3	; with negative value

kcps = cpspch(p4)
aenv linseg 0, 0.1, 1, 0.5, -0.9, 0.4, 0
asig poscil aenv, kcps, giSine
     outs asig, asig

endin
</CsInstruments>
<CsScore>

i 1 0 1   7.00	; = 1 sec, p3 fits exactly
i 1 2 2   7.00	; = 2 sec, p3 truncated at 1 sec

i 2 4 1   7.00	; scales to duration
i 2 6 2   7.00	; of p3

i 3 9 2   7.00
e
</CsScore>
</CsoundSynthesizer>

See Also

      expon,
      expseg,
      expsegb,
      expsegr,
      cosseg,
      line,
      linsegr
      transeg
      transegb

Credits

            Author: Barry L. Vercoe

          Prev

            Up

           Next

          linrand

            Home

           linsegb


text:
@implementation RuntimeProtocol
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<efi:AdjustableInstruction efi:efiVersion="2.0"
  xmlns:efi="http://www.flexiblepower.org/efi-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.flexiblepower.org/efi-2 ../schema/efi-2.0.xsd ">
  <efi:header>
    <efi:efiResourceId>adjustble-device-001</efi:efiResourceId>
    <efi:timestamp>2001-12-31T12:00:00</efi:timestamp>
  </efi:header>
  <efi:instructionId>instruction-001</efi:instructionId>
  <efi:flexibilityUpdateId>update-012</efi:flexibilityUpdateId>
  <efi:isEmergencyInstruction>true</efi:isEmergencyInstruction>
  <efi:runningModeId>0</efi:runningModeId>
  <efi:startTime>2001-12-31T12:00:00</efi:startTime>
</efi:AdjustableInstruction>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chocolate
{
    class Shell
    {

    }
    public static partial class AdvConsole
    {
        private static int indent = 0;
        /// <summary>
        /// ForegroundColor Property
        /// </summary>
        public static ConsoleColor ForegroundColor { get { return System.Console.ForegroundColor; } set { System.Console.ForegroundColor = value; } }
        /// <summary>
        /// BackgroundColor Property
        /// </summary>
        public static ConsoleColor BackgroundColor { get { return System.Console.BackgroundColor; } set { System.Console.BackgroundColor = value; } }
        /// <summary>
        /// CursorTop Property
        /// </summary>
        public static int CursorTop { get { return System.Console.CursorTop; } set { System.Console.CursorTop = value; } }
        /// <summary>
        /// CursorLeft Property
        /// </summary>
        public static int CursorLeft { get { return System.Console.CursorLeft; } set { System.Console.CursorLeft = value; } }
        /// <summary>
        /// WindowWidth Property
        /// </summary>
        public static int WindowWidth { get { return System.Console.WindowWidth; } set { System.Console.WindowWidth = value; } }
        /// <summary>
        /// WindowHeight Property
        /// </summary>
        public static int WindowHeight { get { return System.Console.WindowHeight; } set { System.Console.WindowHeight = value; } }
        /// <summary>
        /// KeyAvailable Property
        /// </summary>
        public static bool KeyAvailable { get { return System.Console.KeyAvailable; } }
        /// <summary>
        /// Write Method
        /// </summary>
        /// <param name="chr">The char to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void Write(char chr = char.MinValue, ConsoleColor color = ConsoleColor.White, bool xcenter = false, bool ycenter = false)
        {
            Write(chr.ToString(), color, xcenter, ycenter);
        }
        /// <summary>
        /// Write Method
        /// </summary>
        /// <param name="chr">The char to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void WriteEx(char chr = char.MinValue, ConsoleColor color = ConsoleColor.White, ConsoleColor backColor = ConsoleColor.Black, bool xcenter = false, bool ycenter = false)
        {
            WriteEx(chr.ToString(), color, backColor, xcenter, ycenter);
        }
        /// <summary>
        /// Write Method
        /// </summary>
        /// <param name="text">The text to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void Write(string text = "", ConsoleColor color = ConsoleColor.White, bool xcenter = false, bool ycenter = false)
        {
            ConsoleColor originalColor = ForegroundColor;
            ForegroundColor = color;
            int X = CursorLeft + indent;
            if (xcenter) CursorLeft = ((WindowWidth / 2) - (text.Length / 2));
            int Y = CursorTop;
            if (ycenter) CursorTop = ((WindowHeight / 2) - 1);
            System.Console.Write(text);
            if (xcenter) CursorLeft = X;
            if (ycenter) CursorTop = Y;
            ForegroundColor = originalColor;
        }
        /// <summary>
        /// Write Method
        /// </summary>
        /// <param name="text">The text to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="backcolor">The background color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void WriteEx(string text = "", ConsoleColor color = ConsoleColor.White, ConsoleColor backcolor = ConsoleColor.Black, bool xcenter = false, bool ycenter = false)
        {
            ConsoleColor originalColor = ForegroundColor;
            ConsoleColor originalColor2 = BackgroundColor;
            ForegroundColor = color;
            BackgroundColor = backcolor;
            int X = CursorLeft + indent;
            if (xcenter) CursorLeft = ((WindowWidth / 2) - (text.Length / 2));
            int Y = CursorTop;
            if (ycenter) CursorTop = ((WindowHeight / 2) - 1);
            System.Console.Write(text);
            if (xcenter) CursorLeft = X;
            if (ycenter) CursorTop = Y;
            ForegroundColor = originalColor;
            BackgroundColor = originalColor2;
        }
        /// <summary>
        /// WriteLine Method
        /// </summary>
        /// <param name="text">The text to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void WriteLine(string text = "", ConsoleColor color = ConsoleColor.White, bool xcenter = false, bool ycenter = false)
        {
            ConsoleColor originalColor = ForegroundColor;
            ForegroundColor = color;
            int X = CursorLeft + indent;
            if (xcenter) CursorLeft = ((WindowWidth / 2) - (text.Length / 2));
            int Y = CursorTop;
            if (ycenter) CursorTop = ((WindowHeight / 2) - 1);
            System.Console.WriteLine(text);
            if (xcenter) CursorLeft = X;
            if (ycenter) CursorTop = Y;
            ForegroundColor = originalColor;
        }
        /// <summary>
        /// WriteLine Method
        /// </summary>
        /// <param name="text">The text to write</param>
        /// <param name="color">The color of the text</param>
        /// <param name="backcolor">The background color of the text</param>
        /// <param name="xcenter">Horizontal centered?</param>
        /// <param name="ycenter">Vertical centered?</param>
        public static void WriteLineEx(string text = "", ConsoleColor color = ConsoleColor.White, ConsoleColor backcolor = ConsoleColor.Black, bool xcenter = false, bool ycenter = false)
        {
            ConsoleColor originalColor = ForegroundColor;
            ConsoleColor originalColor2 = BackgroundColor;
            ForegroundColor = color;
            BackgroundColor = backcolor;
            int X = CursorLeft + indent;
            if (xcenter) CursorLeft = ((WindowWidth / 2) - (text.Length / 2));
            int Y = CursorTop;
            if (ycenter) CursorTop = ((WindowHeight / 2) - 1);
            System.Console.WriteLine(text);
            if (xcenter) CursorLeft = X;
            if (ycenter) CursorTop = Y;
            ForegroundColor = originalColor;
            BackgroundColor = originalColor2;
        }
        /// <summary>
        /// Fills the Console Background with a color
        /// </summary>
        /// <param name="color"></param>
        public static void Fill(ConsoleColor color)
        {
            Console.Clear();
            ConsoleColor backup = Console.BackgroundColor;
            Console.BackgroundColor = color;
            for (int i = 0; i < (80 * 25); i++)
            {
                Console.Write(" ");
            }
            Console.BackgroundColor = backup;
            Console.CursorTop = 0;
        }
        /// <summary>
        /// Clear Method
        /// </summary>
        public static void Clear() { System.Console.Clear(); }
        /// <summary>
        /// Wipes the first two lines and writes a text (e.g. "YourOSName")
        /// at the horizontal center of the first line
        /// </summary>
        /// <param name="text">The text to write</param>
        /// <param name="color">The color of the text</param>
        public static void PrintAlias(string text, ConsoleColor color)
        {
            int curTop = CursorTop;
            int curLeft = CursorLeft;
            for (int i = 0; i < 2; i++)
            {
                CursorTop = i;
                for (int ix = 0; ix < WindowWidth; ix++) Write(" ");
            }
            CursorTop = 0;
            WriteLine(text, color, true);
            if (curTop >= 2) CursorTop = curTop;
            else CursorTop = 2;
            CursorLeft = curLeft;
        }
        /// <summary>
        /// Inserts a line break
        /// </summary>
        public static void NewLine() { WriteLine(); }
        /// <summary>
        /// System.Console.Read()-Implementation
        /// </summary>
        /// <returns></returns>
        public static int Read() { return System.Console.Read(); }
        /// <summary>
        /// System.Console.ReadKey()-Implementation
        /// </summary>
        /// <returns></returns>
        public static ConsoleKeyInfo ReadKey() { return System.Console.ReadKey(); }
        /// <summary>
        /// System.Console.ReadLine()-Implementation
        /// </summary>
        /// <returns></returns>
        public static string ReadLine() { return System.Console.ReadLine(); }
        /// <summary>
        /// Sets a custom indent
        /// </summary>
        /// <param name="_indent"></param>
        public static void SetIndent(int _indent)
        {
            indent = _indent;
        }
    }
}


text:
(function (angular) {
    'use strict';

    var module = angular.module('app', []);

    module.run(['$rootScope', function (root) {
        root.nodeVersion = process.version;
        root.atomShellVersion = process.versions['atom-shell'];
    }]);

}(angular));


text:
/*
For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web
 page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L >= W.

3. The difference between length L and width W should be as small as possible.
You need to output the length L and the width W of the web page you designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2].
 So the length L is 2, and the width W is 2.
Note:
The given area won't exceed 10,000,000 and is a positive integer
The web page's width and length you designed must be positive integers.
*/

/*
 *
*/

#include "helper.h"

class Solution {
public:
    vector<int> constructRectangle(int area) {
        vector<int> res;
        int w = int(sqrt(area));
        while (area % w != 0) {
            w--;
        }
        res.push_back(area / w);
        res.push_back(w);
        return res;
    }
};

int main() {
    Solution s;

    cout << s.constructRectangle(4) << endl;
    cout << s.constructRectangle(1) << endl;
    cout << s.constructRectangle(8) << endl;
    cout << s.constructRectangle(15) << endl;
    cout << s.constructRectangle(5) << endl;
    cout << s.constructRectangle(9999998) << endl;
    return 0;
}


text:
<?php

$data = array(
    "Payment" => "ASDFASDFASDFASDFASDFASDFASDFASD"
);

// json encode data

$data_string = json_encode($data);

// the token

$token = 'your token here';

// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://asst2paypalpayments.firebaseio.com/payments.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
));

// execute the request

$output = curl_exec($ch);

// output the profile information - includes the header

echo($output) . PHP_EOL;

// close curl resource to free up system resources
curl_close($ch);
?>


text:
/**
 * Test the Gaussian function.
 */
import {GaussianFunction} from "./gaussian-function";
import {Aifh} from "../../aifh";

describe('GaussianFunction', () => {
  it('testEvaluate', () => {
    const params:number[] = [5, 0, 0, 0];
    const funct:GaussianFunction = new GaussianFunction(3, params, 0);
    const x:number[] = [-1, 0, 1];
    const y:number = funct.evaluate(x);

    expect(y).toBeCloseTo(0.9607894391523232, Aifh.DEFAULT_PRECISION);
  });

  it('testToString', () => {
    const params:number[] = [5, 0, 0, 0];
    const funct:GaussianFunction = new GaussianFunction(3, params, 0);
    const x:number[] = [-1, 0, 1];
    const y:number = funct.evaluate(x);

    expect(funct.toString()).toBe("[GaussianFunction:width=5.00,center=0.00,0.00,0.00]");
  });

  it('testOther', () => {
    const params:number[] = [5, 0, 0, 0];
    const funct:GaussianFunction = new GaussianFunction(3, params, 0);
    expect(funct.getDimensions()).toBe(3);
    funct.setCenter(0, 100);
    expect(funct.getCenter(0)).toBeCloseTo(100, Aifh.DEFAULT_PRECISION);
    funct.setWidth(5);
    expect(funct.getWidth()).toBeCloseTo(5, Aifh.DEFAULT_PRECISION);
  });

});


text:
class Book
  include Mongoid::Document
  field :title, :type => String
  has_one :rating, :as => :ratable, :dependent => :nullify
end


text:
package io.egen.proteus.service;

import java.util.List;

import io.egen.proteus.entity.Rating;
import io.egen.proteus.entity.Title;
import io.egen.proteus.exception.TitleAlreadyExistsException;
import io.egen.proteus.exception.TitleNotFoundException;
import io.egen.proteus.exception.UnauthorizedException;
import io.egen.proteus.exception.UserNotFoundException;

/**
 *
 * @author Pravin Umamaheswaran
 *
 */
public interface TitleService {

	public void rateTitle(Title title) throws TitleNotFoundException;

	public List<Title> getTopRatedTitles();

	public Title addNewTitle(Title title, String role) throws TitleAlreadyExistsException,UnauthorizedException;

	public Title editTitle(Title title, String role) throws TitleNotFoundException,UnauthorizedException;

	public void deleteTitle(String imdbID, String role) throws TitleNotFoundException,UnauthorizedException;

	public Title getTitleDetails(String imdbId) throws TitleNotFoundException;

	public Rating registerRating(String subject, String imdbId, Rating rating) throws TitleNotFoundException, UserNotFoundException;

	public List<Title> getCatalog();
}


text:
using System.Web.Mvc;

namespace SportPredictionsSystem.Web.Areas.Administration_Users.Controllers
{
    using System.Linq;
    using System.Net;

    using AutoMapper;
    using AutoMapper.QueryableExtensions;

    using SportPredictionsSystem.Data;
    using SportPredictionsSystem.Data.Models;
    using SportPredictionsSystem.Web.Areas.Administration_Predictions.InputModels.FootballPredictions;
    using SportPredictionsSystem.Web.Areas.Administration_Predictions.ViewModels.FootballPredictions;
    using SportPredictionsSystem.Web.Areas.Administration_Users.InputModels.Users;
    using SportPredictionsSystem.Web.Areas.Administration_Users.ViewModels.Users;
    using SportPredictionsSystem.Web.Controllers;

    public class UsersController : BaseController
    {
        public UsersController(ISportPredictionsSystemData data) : base(data)
        {
        }

        public ActionResult Index()
        {
            return this.View(this.Data.Users.All().Project().To<UserViewModel>().ToList());
        }

        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var user = this.Data.Users.All().Project().To<EditUserInputModel>().FirstOrDefault();

            if (user == null)
            {
                return this.HttpNotFound();
            }

            this.ViewBag.Countries = this.Data.Countries.All().Select(x => new SelectListItem { Text = x.NameEn, Value = x.Id.ToString() });

            return this.View(user);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditUserInputModel inputModel)
        {
            if (this.ModelState.IsValid)
            {
                var entity = this.Data.Users.GetById(inputModel.Id);
                var entityForUpdate = Mapper.Map(inputModel, entity);
                this.Data.Users.Update(entityForUpdate);
                this.Data.SaveChanges();
                return this.RedirectToAction("Index");
            }

            return this.View(inputModel);
        }

        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var footballPrediction = this.Data.FootballPredictions
                .All()
                .Where(fp => fp.Id == id)
                .Project()
                .To<FootballPredictionViewModel>()
                .FirstOrDefault();

            if (footballPrediction == null)
            {
                return this.HttpNotFound();
            }

            return this.View(footballPrediction);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            var footballPrediction = this.Data.FootballPredictions.GetById(id);
            this.Data.FootballPredictions.Delete(footballPrediction);
            this.Data.SaveChanges();
            return this.RedirectToAction("Index");
        }
    }
}