text:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { Http } from '@angular/http';
import { Toast, BodyOutputType } from 'angular2-toaster/angular2-toaster';
import { ContentBlock } from '../models';

@Injectable()
export class ContentService {

  private contentBlockTitle: string;
  contentBlocks: ContentBlock[];

  constructor(private http: Http) {}

  loadData() {
    // call for each type of content block used in the app
    this.getContentBlocks().then(contentBlocks => {
      this.contentBlocks = contentBlocks;
    });
  }

  getContentBlocks () {
      const url = `${process.env.CRDS_CMS_CLIENT_ENDPOINT}/api/contentblock?category[]=main&category[]=common&category[]=echeck`;
      return this.http.get(url).toPromise()
                    .then(res => { return res.json().contentblocks; })
                    .catch(this.handleError);
  }

  getToastContent (contentBlockTitle): Promise<any> {
    this.contentBlockTitle = contentBlockTitle;
    if (this.contentBlocks === undefined) {
      return this.getContentBlocks().then(mainContentBlocks => {
        this.contentBlocks = mainContentBlocks;

        return this.displayToast(this.contentBlockTitle);

      });
    } else {
      return Promise.resolve(this.displayToast(this.contentBlockTitle));
    }
  }

  displayToast(contentBlockTitle) {
      const contentBlock = this.contentBlocks.find(x => x.title === contentBlockTitle);

      const toast: Toast = {
        type: contentBlock.type,
        body: contentBlock.content,
        bodyOutputType: BodyOutputType.TrustedHtml
      };

    return toast;
  }

  private handleError (error: any) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :omniauthable,
         :recoverable, :rememberable
  has_many :identities
  has_many :commitments

  def twitter
    identities.where( :provider => "twitter" ).first
  end

  def twitter_client
    @twitter_client ||= Twitter.client( access_token: twitter.accesstoken )
  end

end

redpajama_set_name: RedPajamaGithub


text:
import fncOnly_m4 = require("fncOnly_m4");
export declare var useFncOnly_m4_f4: fncOnly_m4.d;


text:
<?php

require dirname(__DIR__) . '/vendor/autoload.php';

function load_config() {
  $baseDir = dirname(__DIR__);
  $settings = require $baseDir . '/config/config.php.dist';
  $localFile = $baseDir . '/config/config.php';
  if(file_exists($baseDir) && is_readable($baseDir)) {
    $localSettings = require $localFile;
    $settings = array_replace_recursive($settings, $localSettings);
  }
  $settings['basePath'] = $baseDir;
  return $settings;
}

define_routes(
  define_middleware(
    new Slim\App(
      define_services(
        new Slim\Container(['settings' => load_config()])
      )
    )
  )
)->run();


text:
package com.xamoom.android.xamoom_pingeborg_android;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xamoom.android.xamoomsdk.APIListCallback;
import com.xamoom.android.xamoomsdk.EnduserApi;
import com.xamoom.android.xamoomsdk.Enums.SpotSortFlags;
import com.xamoom.android.xamoomsdk.Resource.Spot;

import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;

import at.rags.morpheus.Error;

public class SpotListFragment extends android.support.v4.app.Fragment {

  private RecyclerView mRecyclerView;
  private ProgressBar mProgressBar;
  private LinearLayoutManager mLayoutManager;
  private BestLocationProvider mBestLocationProvider;
  final List<Spot> mSpotList = new LinkedList<>();
  static Location mUserLocation = null;

  private OnSpotListFragmentInteractionListener mListener;

  /**
   * Use this factory method to create a new instance of
   * this fragment.
   *
   * @return A new instance of fragment SpotListFragment.
   */
  public static SpotListFragment newInstance() {
    return new SpotListFragment();
  }

  public SpotListFragment() {
    // Required empty public constructor
  }

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

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_spot_list, container, false);
    mRecyclerView = (RecyclerView) view.findViewById(R.id.spotListRecyclerView);
    mProgressBar = (ProgressBar) view.findViewById(R.id.loadingSpotsProgressBar);
    mProgressBar.setVisibility(View.VISIBLE);
    setupRecyclerView(mRecyclerView);
    setupLocation();
    return view;
  }

  private void setupLocation() {
    if (ContextCompat.checkSelfPermission(this.getActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      return;
    }

    mBestLocationProvider = new BestLocationProvider(getActivity(), false, true, 10000, 10000, 10, 40);
    BestLocationListener mBestLocationListener = new BestLocationListener() {

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
        //Log.i("pingeborg", "onStatusChanged PROVIDER:" + provider + " STATUS:" + String.valueOf(status));
      }

      @Override
      public void onProviderEnabled(String provider) {
        //Log.i("pingeborg", "onProviderEnabled PROVIDER:" + provider);
      }

      @Override
      public void onProviderDisabled(String provider) {
        //Log.i("pingeborg", "onProviderDisabled PROVIDER:" + provider);
      }

      @Override
      public void onLocationUpdateTimeoutExceeded(BestLocationProvider.LocationType type) {
        //Log.w("pingeborg", "onLocationUpdateTimeoutExceeded PROVIDER:" + type);
      }

      @Override
      public void onLocationUpdate(Location location, BestLocationProvider.LocationType type, boolean isFresh) {
        if(isFresh) {
          mUserLocation = location;
          Log.i(Global.DEBUG_TAG, "onLocationUpdate TYPE:" + type + " Location:" + mBestLocationProvider.locationToString(location));
          getClosesSpots(location);
          mBestLocationProvider.stopLocationUpdates();
        }
      }
    };

    //start Location Updates
    mBestLocationProvider.startLocationUpdatesWithListener(mBestLocationListener);
  }

  private void getClosesSpots(final Location location) {
    if(this.isAdded()) {
      EnduserApi.getSharedInstance().getSpotsByLocation(location, 2000, 40, null, null,
              EnumSet.of(SpotSortFlags.DISTANCE),
              new APIListCallback<List<Spot>, List<Error>>() {
                @Override
                public void finished(List<Spot> result, String cursor, boolean hasMore) {
                  mProgressBar.setVisibility(View.GONE);
                  mSpotList.addAll(result);
                  mRecyclerView.getAdapter().notifyDataSetChanged();
                }

                @Override
                public void error(List<Error> error) {

                }
              });
    }

  }

  private void setupRecyclerView(final RecyclerView recyclerView) {
    mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setAdapter(new SpotListRecyclerViewAdapter(getActivity(), mSpotList));
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
      mListener = (OnSpotListFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString()
              + " must implement OnSpotListFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }

  /**
   * closeGeofenceFragment must be implemented to remove the fragment from activity.
   */
  public interface OnSpotListFragmentInteractionListener {
    void clickedSpot(Spot spot);
  }

  /**
   *
   *
   *
   *
   */
  public class SpotListRecyclerViewAdapter extends RecyclerView.Adapter<SpotListRecyclerViewAdapter.ViewHolder> {
    private final static int VIEW_ITEM = 1;
    private final static int VIEW_PROG = 0;

    private final TypedValue mTypedValue = new TypedValue();
    private final Context mContext;
    private int mBackground;
    private List<Spot> mSpotList;

    public class ViewHolder extends RecyclerView.ViewHolder {
      public Spot mBoundContent;

      public final View mView;
      public final LinearLayout mTextOverlay;
      public final TextView mTitleTextView;
      public final TextView mDistanceTextView;
      public final ImageView mImageView;

      public ViewHolder(View view) {
        super(view);
        mView = view;
        mTextOverlay = (LinearLayout) view.findViewById(R.id.spotListTextOverlay);
        mTitleTextView = (TextView) view.findViewById(R.id.spotNameTextView);
        mDistanceTextView = (TextView) view.findViewById(R.id.spotDistanceTextView);
        mImageView = (ImageView) view.findViewById(R.id.spotListImageView);
      }

      @Override
      public String toString() {
        return super.toString() + " '" + mTitleTextView.getText();
      }
    }

    public Spot getValueAt(int position) {
      return mSpotList.get(position);
    }

    @Override
    public int getItemViewType(int position) {
      return mSpotList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    public SpotListRecyclerViewAdapter(Context context, List<Spot> items) {
      if(context != null)
        context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);

      mBackground = mTypedValue.resourceId;
      mSpotList = items;
      mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View view = LayoutInflater.from(parent.getContext())
              .inflate(R.layout.spot_list_item, parent, false);
      view.setBackgroundResource(mBackground);
      return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
      if (holder.getItemViewType() == VIEW_ITEM) {
        //save content for later use
        holder.mBoundContent = mSpotList.get(position);

        //set text
        holder.mTitleTextView.setText(holder.mBoundContent.getName());

        //display distance
        Location spotLocation = new Location("");
        spotLocation.setLatitude(holder.mBoundContent.getLocation().getLatitude());
        spotLocation.setLongitude(holder.mBoundContent.getLocation().getLongitude());
        float distance = mUserLocation.distanceTo(spotLocation);
        holder.mDistanceTextView.setText(String.valueOf(Math.round(distance)) + " Meter");

        //holder.mImageView.setImageURI(null);

        //add Image
        if(holder.mBoundContent.getPublicImageUrl() != null) {
          Glide.with(mContext)
                  .load(holder.mBoundContent.getPublicImageUrl())
                  .dontTransform()
                  .crossFade()
                  .into(holder.mImageView);
        }
        else {
          holder.mImageView.setImageResource(0);
          if(position%2 == 1) {
            holder.mTextOverlay.setBackgroundColor(mContext.getResources().getColor(R.color.artist_list_text_background_lighter));
          } else {
            holder.mTextOverlay.setBackgroundColor(mContext.getResources().getColor(R.color.artist_list_text_background));
          }
        }

        holder.mView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            mListener.clickedSpot(holder.mBoundContent);
          }
        });
      }
    }

    @Override
    public int getItemCount() {
      return mSpotList.size();
    }
  }
}


text:
var util = require('util');
var events = require('events');
var gearman = require('gearman-coffee');
var Multiserver = require('./multiserver');
var log = require('../log');

/**
 * A gearman client that supports multiple servers.
 * Contains multiple gearman-coffee clients that are each
 * connected to a different server. The client which submits a job
 * is selected with round robin.
 *
 * Servers are provided in an array of json-objects, possible fields are:
 *  `.host`:    a string that identifies a gearman job server host
 *  `.port`:    an integer that identifies a geaerman job server port
 *  `._debug`:   a boolean that tells whether debug mode should be used
 *
 * @param {[Object]} servers
 * @param {Object} options
 * @return {Object}
 */

function MultiserverClient(servers, options) {
  options = options || {};
  Multiserver.call(this, servers, function(server) {
    return new gearman.Client({
      host: server.host,
      port: server.port,
      debug: options.debug || false
    });
  }, Multiserver.component_prefix(options.component_name) + 'client');
  this._rr_index = -1;    // round robin index
}

util.inherits(MultiserverClient, Multiserver);

/**
 * Selects a connected client and submits a job to it.
 */

MultiserverClient.prototype.submitJob = function(func_name, payload) {
  var index = this._pickConnectedClient();
  this._debug('submitting job to server', this._serverString(index));
  return this._connections[index].submitJob(func_name, payload);
};

/**
 * Selects a connected client and submits a job to it with gearman's
 * SUBMIT_JOB_BG call. This means that the job will be forgotten as soon
 * as it is sent, and no JOB_COMPLETE is expected.
 */

MultiserverClient.prototype.submitJobBg = function(func_name, payload) {
  var index = this._pickConnectedClient();
  this._debug('submitting background job to', this._serverString(index));

  var that = this;
  var client = this._connections[index];
  var job = new events.EventEmitter();
  client.queue.push(job);
  client.sendCommand('SUBMIT_JOB_BG', func_name, false, payload);
  job.on('created', function(handle) {
    that._debug('background job created with handle', handle);
    // delete job immediately because WORK_COMPLETE is not expected
    delete client.jobs[handle];
  });

  return job;
};

/** Returns a connected client from the clients array */
MultiserverClient.prototype._pickConnectedClient = function() {
  if (!this.connected) {
    this._debug('all servers disconnected, buffering to any server');
  }
  var counter = 0;
  do {
    this._rr_index = (this._rr_index + 1) % this._connections.length;
  } while ((!this._connections[this._rr_index].connected) &&
            ++counter < this._connections.length &&
            this.connected);
  return this._rr_index;
};

module.exports.MultiserverClient = MultiserverClient;


text:
This project constructs Large-Gap Gray codes (LGGC), which is a special type of Gray code with the additional property that it contains large bit runs along the tracks. LGGC was introduced by [1], where the mathematical derivation of the codes is described. More description of LGGC can be found in [2, section 5.2].

A comparison of *Binary Reflected Gray code* and *Large-Gap Gray code* is shown below:

##### 7-bit Binary Reflected Gray code
![7-bit Binary Reflected Gray code](doc/7bit-binary-reflected.png "7-bit Binary Reflected Gray code")

##### 7-bit Large-Gap Gray code
![7-bit Large-Gap Gray code](doc/7bit-large-gap.png "7-bit Large-Gap Gray code")

They are both cyclic Gray codes with one bit changing between two successive values, however the LGGC is constructed in a way to obtain higher minimum run lengths and lower maximum run lengths along the bit tracks.

##### Comparison of min/max gaps
![Comparison of min/max gaps for BRGC and LGGC for various bit widths](doc/min_max_gaps.png)

# Utilization in structured light application
The codes have been used in a structured light application [2]. The LGGC pattern was projected to a scene and captured by cameras. Afterwards, the pattern was decoded and used for reconstruction of 3D information.

In comparison to traditional BRGC, the properties of LGGC makes it more robust towards defocusing, subsurface scattering and interreflections, which are common challenges in scenes with active illumination. For more information, see [2] and [3].

# How to use it
The project is tested on Linux using CMake and make:
```
mkdir build
cd build
cmake ..
make
```

Two applications are provided, which can be executed by running;
```
./src/examples
./src/imagePatterns
```

# References
* [1] Luis Goddyn, George M Lawrence, and Evi Nemeth. Gray codes with optimized run lengths. Utilitas Mathematica, 34:179–192, 1988
* [2] Pedersen, J. and Hansen, K. (2014). Robot Mountable Embedded Vision Platform for Multimodal Point Cloud Acquisition in Industrial Applications. Master Thesis, University of Southern Denmark. [Online version](http://caro.sdu.dk/index.php/publications/master-theses?view=publication&task=show&id=2048)
* [3] Hansen, K.; Pedersen, J.; Sølund, T.; Aanæs, H.; Kraft, D., "A Structured Light Scanner for Hyper Flexible Industrial Automation", 3D Vision - 3DV 2014


text:
'use strict';

angular.module('ioAtSpotApp')
    .controller('MembersCtrl',
        function ($scope, $http, socket, Members, Organizations, $modal, $document, messageCenterService, Auth) {
            $scope.model = new function () {
                var model = this;

                model.addingMember = false;
                model.organization = null;
                model.editingMember = null;
                model.newTimeOffType = '';
            };

            $scope.actions = {

                editMember: function (member) {
                    angular.forEach($scope.model.organizations, function (org) {
                        angular.forEach(org.members, function (mem) {
                            $scope.actions.cancelEditMember(mem);
                        });
                    });

                    $scope.model.editingMember = JSON.parse(JSON.stringify(member));
                    //member.editing = true;
                },

                readUid: function (member) {
                    $scope.utils.readingUid = true;

                    Organizations.readUid({
                        organizationId: $scope.model.organization._id
                    }).$promise.then(function (data) {
                        member.nfc_uid = data.uid;
                        $scope.utils.readingUid = false;
                    }, function (err) {
                        messageCenterService.add('danger', err.data.error, {
                            timeout: 3000
                        });
                        $scope.utils.readingUid = false;
                    });
                },

                cancelEditMember: function (member) {
                    $scope.model.editingMember = null;
                },

                removeMember: function (member) {

                    Members.remove({
                        organizationId: $scope.model.organization._id,
                        id: member._id
                    }, {}).$promise.then(
                        function () {
                            $scope.actions.loadMembers();
                        },
                        function (err) {
                            messageCenterService.add('danger', err.data.error, {
                                timeout: 3000
                            });
                        });
                },

                updateMember: function (member) {

                    Members.update({
                        organizationId: $scope.model.organization._id,
                        id: member._id
                    }, {
                        role: $scope.model.editingMember.role,
                        nfc_uid: $scope.model.editingMember.nfc_uid,
                        hours: $scope.model.editingMember.hours
                    }).$promise.then(
                        function () {
                            $scope.model.editingMember = null;
                            $scope.actions.loadMembers();
                        },
                        function (err) {
                            messageCenterService.add('danger', err.data.error, {
                                timeout: 3000
                            });
                        });
                },

                loadMembers: function () {
                    Members.query({
                        organizationId: $scope.model.organization._id,
                    }, {}).$promise.then(function (members) {
                            $scope.model.organization.members = members;
                        },
                        function (err) {
                            messageCenterService.add('danger', err.data.error, {
                                timeout: 3000
                            });
                        });
                }
            };

            $scope.utils = {
                isMemberCurrentUser: function (member) {
                    return member._user._id === Auth.getAuthModel().currentUser._id;
                },
                currentUserIsAdmin: function () {
                    return $scope.model.organization.userRole === 'admin';
                },
                readingUid: false
            };

            $scope.$watch('model.organization', function (value) {
                $scope.actions.loadMembers();
            });
        });


text:
using PropertyChangeLogger;

namespace TestPropertyChangeLogger
{
    public class Customer : PropertyChangeLoggingClass
    {
        public string Name { get; set; }
        [DoNotLogValuesWhenThisPropertyChanges]
        public string Password { get; set; }
        [DoNotLogChangesToThisProperty]
        public double ComputedValue { get; set; }

        public Customer()
        {
        }

        public Customer(string name, string password, double computedValue)
        {
            Name = name;
            Password = password;
            ComputedValue = computedValue;

            SetInitialPropertyValues();
        }
    }
}


text:
package saga

import (
	"fmt"
)

type SagaRecoveryType int

//
// Saga Recovery Types define how to interpret SagaState in RecoveryMode.
//
// ForwardRecovery: all tasks in the saga must be executed at least once.
//                 tasks MUST BE idempotent
//
// RollbackRecovery: if Saga is Aborted or in unsafe state, compensating
//                  tasks for all started tasks need to be executed.
//                   compensating tasks MUST BE idempotent.
//
const (
	RollbackRecovery SagaRecoveryType = iota
	ForwardRecovery
)

//
// Recovers SagaState from SagaLog messages
//
func recoverState(sagaId string, saga SagaCoordinator) (*SagaState, error) {

	// Get Logged Messages For this Saga from the Log.
	msgs, err := saga.log.GetMessages(sagaId)
	if err != nil {
		return nil, err
	}

	if msgs == nil || len(msgs) == 0 {
		return nil, nil
	}

	// Reconstruct Saga State from Logged Messages
	startMsg := msgs[0]
	if startMsg.MsgType != StartSaga {
		return nil, fmt.Errorf("InvalidMessages: first message must be StartSaga")
	}

	state, err := makeSagaState(sagaId, startMsg.Data)
	if err != nil {
		return nil, err
	}

	for _, msg := range msgs {
		// skip applying StartSaga message we already did this
		// duplicate messages are just ignored since msgs are idempotent
		if msg.MsgType == StartSaga {
			continue
		}

		err = updateSagaState(state, msg)
		if err != nil {
			return nil, err
		}
	}

	return state, nil
}

//
// Returns true if saga is in a safe state, i.e. execution can pick up where
// it left off.  This is only used in RollbackRecovery
//
// A Saga is in a Safe State if all StartedTasks also have EndTask Messages
// A Saga is also in a Safe State if the Saga has been aborted and compensating
// actions have started to be applied.
//
func isSagaInSafeState(state *SagaState) bool {

	if state.IsSagaAborted() {
		return true
	}

	for taskId, _ := range state.taskState {
		if state.IsTaskStarted(taskId) && !state.IsTaskCompleted(taskId) {
			return false
		}
	}

	return true
}


text:
import java.io.File;

import com.jme3.math.Vector3f;

import network.ClientMain;
import network.ServerMain;
import GUI.WorldTestMain;
import world.World;
import world.WorldType;

/**
 * Console startup main for the three modes: Single player, server, client
 *
 * @author Garming Sam 300198721
 *
 */
public class Main {
	public static void main(String[] args) {
		String ip = "localhost";
		String port = "6143";
		boolean fast = false;
		WorldType w = WorldType.SP;
		String name = "";

		for (int i = 0; i < args.length; i++) {
			if (args[i].startsWith("-")) {
				String arg = args[i];
				if(arg.equals("-help")) {
					usage();
					System.exit(0);
				} else if(arg.equals("-server")) {
					w = WorldType.SERVER;
				} else if(arg.equals("-client")) {
					w = WorldType.CLIENT;
					if (i + 1 < args.length && !args[i+1].startsWith("-"))
						ip = args[++i];
				} else if (arg.equals("-fast")) {
					fast = true;
				} else if (arg.equals("-port")) {
					if (i + 1 < args.length)
						port = args[++i];
				} else if (arg.equals("-mobs")) {
					try {
						if (i + 1 < args.length)
							World.MAX_MOBS = Integer.parseInt(args[++i]);
					} catch(NumberFormatException e){
						// leave it as it is
					}
				} else if (arg.equals("-name")){
					if (i + 1 < args.length)
						name = args[++i];
				} else if (arg.equals("-clean")) {
					File f = new File("server.sav");
					if(f.exists()) {
						f.setWritable(true);
						f.delete();
					}
				} else if (arg.equals("-test")) {
					World.MAPFILE = "maps/alexMap.txt";
					fast = true;
				}
			}
		}

		switch (w) {
		case SP:
			System.out.println("Single player");
			World.USE_SUPERFAST_RENDERING = fast;
			WorldTestMain.main(null);
			break;
		case SERVER:
			World.USE_SUPERFAST_RENDERING = true;
			System.out.println("SERVER - Port: " + port);
			ServerMain.main(new String[]{port});
			break;
		case CLIENT:
			System.out.println("Client - Address: " + ip + "  Port: " + port);
			World.USE_SUPERFAST_RENDERING = fast;
			ClientMain.main(new String[]{ip, port, name});
			break;
		}

	}

	public static void usage(){
		System.out.println("Usage: -client [<address>] -server -fast -port <port num> -mobs <mob count> -name <name>");
		System.out.println("Client allows an optional arguments for which address and port.");
		System.out.println("Mobs flag allows you to set the max mobs. ");
		System.out.println("Fast flag sets the the rendering type to fast.");
		System.out.println("Name flag allows setting of your name on clients.");
	}
}


text:
<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>native-maven-plugin</artifactId>
        <configuration>
          <project implementation="org.codehaus.mojo.natives.plugin.stubs.ProjectStub" />
          <provider>noop</provider>
          <ranlibOutputDirectory>target</ranlibOutputDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
package io.jafka.consumer;

import io.jafka.BaseJafkaServer;
import io.jafka.Jafka;
import io.jafka.PortUtils;
import io.jafka.api.FetchRequest;
import io.jafka.api.MultiFetchResponse;
import io.jafka.message.ByteBufferMessageSet;
import io.jafka.message.MessageAndOffset;
import io.jafka.producer.Producer;
import io.jafka.producer.ProducerConfig;
import io.jafka.producer.StringProducerData;
import io.jafka.producer.serializer.StringEncoder;
import io.jafka.utils.Closer;
import io.jafka.utils.Gateway;
import io.jafka.utils.Utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * @author adyliu (imxylz@gmail.com)
 * @since 1.0
 */
public class SimpleConsumerTest2 extends BaseJafkaServer {

    Jafka jafka;

    SimpleConsumer consumer;

    public SimpleConsumerTest2() {
    }

    final int partitions = 3;
    final int INIT_MESSAGE_COUNT = 27;
    final int MESSAGE_BATCH_SIZE = 5;
    final int httpPort = PortUtils.checkAvailablePort(9093);
    final int gatewayPort = PortUtils.checkAvailablePort(9095);
    private Gateway gateway;

    @Before
    public void init() throws IOException {
        if (jafka == null) {

            Properties props = new Properties();
            //force flush message to disk
            //we will fetch nothing while messages have note been flushed to disk
            props.put("log.flush.interval", "1");
            props.put("log.default.flush.scheduler.interval.ms", "100");//flush to disk every 100ms
            props.put("log.file.size", "5120");//5k for rolling
            props.put("num.partitions", "" + partitions);//default divided three partitions
            props.put("http.port", "" + httpPort);
            jafka = createJafka(props);
            sendSomeMessages(INIT_MESSAGE_COUNT, "demo", "test");

            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));//waiting to receive all message
            flush(jafka);//force flush all logs to the disk
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
        }
        if (consumer == null) {
            gateway = new Gateway(gatewayPort, jafka.getPort());
            gateway.start();
            consumer = new SimpleConsumer("localhost", gatewayPort, 100, 1000 * 1000);
        }
    }

    private void sendSomeMessages(final int count, final String... topics) {
        Properties producerConfig = new Properties();
        producerConfig.setProperty("broker.list", "0:localhost:" + jafka.getPort());
        producerConfig.setProperty("serializer.class", StringEncoder.class.getName());
        Producer<String, String> producer = new Producer<String, String>(new ProducerConfig(producerConfig));
        int index = 0;
        boolean over = false;
        while (!over) {
            StringProducerData[] data = new StringProducerData[topics.length];
            for (int x = 0; x < data.length; x++) {
                data[x] = new StringProducerData(topics[x]);
            }
            int batch = MESSAGE_BATCH_SIZE;
            while (batch-- > 0 && !over) {
                for (StringProducerData sd : data) {
                    if (!(over = index >= count)) {
                        sd.add(sd.getTopic() + "#message#" + (index++));
                    }
                }
            }
            for (StringProducerData sd : data) {
                producer.send(sd);
            }
        }
        Closer.closeQuietly(producer);
        logger.info("SEND_MESSAGE_COUNT {}/{}", index, count);
        assertEquals(count, index);
    }

    @After
    public void destroy() throws Throwable {
        close(jafka);
        jafka = null;
        if (consumer != null) {
            consumer.close();
            consumer = null;
        }
        if (gateway != null) {
            gateway.stop();
            gateway = null;
        }
    }

    //    @Test
    //    public void testCreatePartitions() throws IOException{
    //        int size = consumer.createPartitions("demo", partitions-1, false);
    //        assertEquals(partitions, size);
    //        size = consumer.createPartitions("demo", partitions+1, false);
    //        assertEquals(partitions, size);
    //        size = consumer.createPartitions("demo", partitions+3, true);
    //        assertEquals(partitions, size);
    //        //
    //        final String largePartitionTopic = "largepartition";
    //        size = consumer.createPartitions(largePartitionTopic, partitions+5, true);
    //        assertEquals(partitions+5, size);
    //        sendSomeMessages(1000, largePartitionTopic);
    //    }

    /**
     * Test method for
     * {@link SimpleConsumer#multifetch(java.util.List)}
     * .
     */
    @Test
    public void testMultifetch() throws IOException {

        long bigestOffset = -1;
        int total = 0, democnt = 0, testcnt = 0;
        //

        //
        int loop = 10;
        while (loop-- > 0 && total < INIT_MESSAGE_COUNT) {
            for (int i = 0; i < partitions && total < INIT_MESSAGE_COUNT; i++) {

                long demoOffset = 0;
                long testOffset = 0;

                FetchRequest request1 = new FetchRequest("demo", i, demoOffset, 64000);
                FetchRequest request2 = new FetchRequest("test", i, testOffset, 64000);
                MultiFetchResponse responses = consumer.multifetch(Arrays.asList(request1, request2));
                assertEquals(2, responses.size());
                Iterator<ByteBufferMessageSet> iter = responses.iterator();
                assertTrue(iter.hasNext());
                ByteBufferMessageSet demoMessages = iter.next();
                assertTrue(iter.hasNext());
                ByteBufferMessageSet testMessages = iter.next();
                assertFalse(iter.hasNext());
                //
                for (MessageAndOffset msg : demoMessages) {
                    System.out.printf("Receive offset=%s data=%s\n", msg.offset, Utils.toString(msg.message.payload(), "UTF-8"));
                    bigestOffset = Math.max(bigestOffset, msg.offset);
                    total++;
                    democnt++;
                    demoOffset = msg.offset;
                }
                for (MessageAndOffset msg : testMessages) {
                    System.out.printf("Receive offset=%s data=%s\n", msg.offset, Utils.toString(msg.message.payload(), "UTF-8"));
                    bigestOffset = Math.max(bigestOffset, msg.offset);
                    total++;
                    testcnt++;
                    testOffset = msg.offset;
                }
                gateway.supsend(TimeUnit.SECONDS.toMillis(1));
                LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
                gateway.supsend(0);

            }
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
        }
        consumer.close();
        logger.info("multifetch receive message count: {}, demo={}, test={}", total, democnt, testcnt);
        assertTrue(bigestOffset > 0);
        assertEquals(total, INIT_MESSAGE_COUNT);
    }

}


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Core.Core;
using WpfExecutor.Converter;
using WpfExecutor.Helpers;
using WpfExecutor.Model;

namespace WpfExecutor.Control
{
    /// <summary>
    /// Логика взаимодействия для ESearchParamControl.xaml
    /// </summary>
    public partial class EStackActionControl : ComboBox, ICustomControl
    {
        public EStackActionControl()
        {
            InitializeComponent();
        }

        [UsedImplicitly]
        public static FrameworkElementFactory GetFrameworkElementFactory()
        {
            var list = typeof(EStackAction).GeEnumTuple();
            var factory = new FrameworkElementFactory(typeof(EStackActionControl));
            factory.SetValue(ItemsSourceProperty, list);
            factory.SetBinding(SelectedItemProperty, new Binding(nameof(IPropModel.Value))
            {
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Converter = new TupleConverter(),
                ConverterParameter = list
            });
            return factory;
        }
    }
}


text:
package com.netflix.hollow.core.type;

import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.provider.HollowFactory;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
import com.netflix.hollow.core.type.delegate.IntegerDelegateCachedImpl;

public class IntegerHollowFactory extends HollowFactory<HInteger> {

    @Override
    public HInteger newHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) {
        return new HInteger(((IntegerTypeAPI)typeAPI).getDelegateLookupImpl(), ordinal);
    }

    @Override
    public HInteger newCachedHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) {
        return new HInteger(new IntegerDelegateCachedImpl((IntegerTypeAPI)typeAPI, ordinal), ordinal);
    }

}


text:
// This file was originally written by Christian Kuendig. It was
// obtained from www.codeguru.com in May 2005 and modified as necessary.

///////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////
#ifndef __hexeditbase_h
#define __hexeditbase_h
#if _MSC_VER > 1000
#pragma once
#endif

/////////////////////////////////////////////////////////////////////////////
// defines
/////////////////////////////////////////////////////////////////////////////
#define NOSECTION_VAL				0xffffffff

// notification codes
#define HEN_CHANGE					EN_CHANGE	//the same as the EDIT (CEdit)

// data length that can be handled
#define MAXHEXEDITLENGTH 0x7ffff000

// increase capacity by 1 + m_nCapacity/CAPACICTYINCDIVISOR when a character is appended/inserted
#define CAPACICTYINCDIVISOR 8

#define HE_FIND_MATCHCASE 1
#define HE_FIND_REGEXP 2
// don't skip the first char of the current select (standard behaviour to enable repeated search)
#define HE_FIND_NOSKIP 4
#define HE_FIND_BACKWARDS 8

class CHexEditAction;

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// class CHexEditBase
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

// forward declaration
class CHexEditBaseView;

class CHexEditBase : public CWnd
{
public:
	CHexEditBase();
	virtual ~CHexEditBase();
	void SetShowAddress(bool bShow, bool bUpdate = true);
	void SetShowAscii(bool bShow, bool bUpdate = true);
	void SetData(const BYTE *pData, UINT nLen, bool bUpdate = true);
	void SetDirectDataPtr(BYTE *pData, UINT nLen, bool bUpdate = true); // won't copy data and won't free memory
	void SetHighlighted(UINT nBegin, UINT nEnd, bool bMakeVisible = true, bool bUpdate = true);
	void SetSelection(UINT nBegin, UINT nEnd, bool bMakeVisible = true, bool bUpdate = true);
	void MakeVisible(UINT nBegin, UINT nEnd, bool bUpdate=true);
	UINT GetData(BYTE *pByte, UINT nLength);
	UINT GetCurrentAddress() const;
	UINT GetBytesPerRow() const;
	void SetBytesPerRow(UINT nBytesPerRow, bool bAuto = false, bool bUpdate = true);
	void SetAddressSize(BYTE nAdrSize, bool bUpdate = true);
	void SetAdrCol(COLORREF tAdrBkgCol, COLORREF tAdrTxtCol, bool bUpdate = true);
	void SetAsciiCol(COLORREF tAsciiBkgCol, COLORREF tAsciiTxtCol, bool bUpdate = true);
	void SetHighlightCol(COLORREF tHighlightFrameCol, COLORREF tHighlightBkgCol, COLORREF tHighlightTxtCol, bool bUpdate = true);
	void SetHexCol(COLORREF tHexBkgCol, COLORREF tHexTxtCol, bool bUpdate = true);
	void SetSelectedNoFocusCol(COLORREF tSelectedNoFocusBkgCol, COLORREF tSelectedNoFocusTxtCol, bool bUpdate = true);
	void SetSelectedFocusCol(COLORREF tSelectedFousTxtCol, COLORREF tSelectedFousBkgCol, bool bUpdate = true);
	void SetNotUsedCol(COLORREF tNotUsedBkCol, bool bUpdate = true);
	bool GetSelection(UINT& nBegin, UINT& nEnd) const;
	bool GetHighlighted(UINT& nBegin, UINT& nEnd) const;
	bool IsSelection() const;
	bool IsHighlighted() const;
	bool IsInsert() const;
	UINT GetDataSize() const { return m_nLength; }
	UINT GetDataSize1() const { return m_nLength + 1; } // for all caret related operations assume add one byte for appending data
	virtual void SetReadonly(bool bReadOnly, bool bUpdate = true);
	BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
	BOOL CreateEx(DWORD dwExStyle, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hwndParent, HMENU nIDorHMenu, LPVOID lpParam = NULL);
	BOOL CreateEx(DWORD dwExStyle, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, LPVOID lpParam = NULL);
	static void RegisterClass();
	static LRESULT CALLBACK WndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
	void SetContextCopyStr(const CString& cStr) { m_cContextCopy = cStr; }
	void SetContextPasteStr(const CString& cStr) { m_cContextPaste = cStr; }
	void Serialize(CArchive& ar);
	bool Search(LPCSTR text, size_t length, UINT flags);
	bool ReplaceSelection(LPCSTR text, size_t length);
	int ReplaceAll(LPCSTR pfind, size_t findlen, LPCSTR preplace, size_t replacelen, UINT searchflags);
	void Undo();
	void Redo();
	BOOL CanUndo() { return m_undo != 0; }
	BOOL CanRedo() { return m_redo != 0; }

	// quick and dirty: to access copy/paste functions from outside
	void callOnEditCut() { OnEditCut(); }
	void callOnEditCopy() { OnEditCopy(); }
	void callOnEditPaste() { OnEditPaste(); }
	void callOnEditClear() { OnEditClear(); }
	void callOnEditSelectAll() { OnEditSelectAll(); }

protected:
	CHexEditBaseView *view;
public:
	void setView(CHexEditBaseView *_view) { view = _view; }

protected:
	bool PrepareReplace(UINT pos, UINT oldlen, UINT newlen); // Prepare replacing [pos, pos+oldlen] with new content of newlen bytes
	BOOL SaveUndoAction(UINT type, UINT position, const BYTE* replaceData, UINT replaceLen, const BYTE* insertData, UINT insertLen);

	struct PAINTINGDETAILS {
		UINT nFullVisibleLines;
		UINT nLastLineHeight;
		UINT nVisibleLines;
		UINT nLineHeight;
		UINT nCharacterWidth;
		UINT nBytesPerRow;
		UINT nHexPos;
		UINT nHexLen;
		UINT nAsciiPos;
		UINT nAsciiLen;
		UINT nAddressPos;
		UINT nAddressLen;
		CRect cPaintingRect;
	};

	bool m_bSelfCleanup;
	bool m_bDeleteData;
	PAINTINGDETAILS m_tPaintDetails;
	BYTE *m_pData;
	UINT m_nBytesPerRow;
	UINT m_nAdrSize;
	UINT m_nHighlightedEnd;
	UINT m_nHighlightedBegin;
	UINT m_nSelectionBegin;
	UINT m_nSelectionEnd;
	UINT m_nCurrentAddress;
	UINT m_nCurCaretHeight;
	UINT m_nLength;
	UINT m_nCapacity;
	UINT m_nScrollPostionY;
	UINT m_nScrollRangeY;
	UINT m_nScrollPostionX;
	UINT m_nScrollRangeX;
	UINT m_nCurCaretWidth;
	UINT m_nSelectingBeg;
	UINT m_nSelectingEnd;
	UINT m_nBinDataClipboardFormat;
	bool m_bRecalc;
	bool m_bHasCaret;
	bool m_bHighBits; // caret on high nibble
	bool m_bCaretAscii;	// true: caret in ASCII area; false: caret in hex area
	bool m_bAutoBytesPerRow;
	bool m_bShowAddress;
	bool m_bShowAscii;
	bool m_bAddressIsWide;
	bool m_bShowCategory;
	bool m_bReadOnly;
	bool m_bInsert;
	COLORREF m_tAdrBkgCol;
	COLORREF m_tAdrTxtCol;
	COLORREF m_tAsciiBkgCol;
	COLORREF m_tAsciiTxtCol;
	COLORREF m_tHighlightBkgCol;
	COLORREF m_tHighlightTxtCol;
	COLORREF m_tHighlightFrameCol;
	COLORREF m_tHexTxtCol;
	COLORREF m_tHexBkgCol;
	COLORREF m_tNotUsedBkCol;
	COLORREF m_tSelectedNoFocusTxtCol;
	COLORREF m_tSelectedNoFocusBkgCol;
	COLORREF m_tSelectedFousTxtCol;
	COLORREF m_tSelectedFousBkgCol;
	CString m_cContextCut;
	CString m_cContextCopy;
	CString m_cContextPaste;
	CString m_cContextToTxt;
	CFont m_cFont;
	CRect m_cDragRect;
	CPoint m_cMouseRepPoint;
	int m_iMouseRepDelta;
	WORD m_nMouseRepSpeed;
	WORD m_nMouseRepCounter;
	bool m_bIsMouseRepActive;
	CHexEditAction* m_undo;
	CHexEditAction* m_redo;

	// overrideables
	virtual void OnExtendContextMenu(CMenu&) {} // override this to add your own context-menue-items

	void NotifyParent(WORD wNBotifictionCode);
	void CalculatePaintingDetails(CDC& cDC);
	void PaintAddresses(CDC& cDC);
	void PaintHexData(CDC& cDC);
	void PaintAsciiData(CDC& cDC);
	void CreateEditCaret(UINT nCaretHeight, UINT nCaretWidth);
	void DestoyEditCaret();
	void SetEditCaretPos(UINT nOffset, bool bHighBits);
	bool OnEditInput(WORD nInput);
	void MoveCurrentAddress(int iDeltaAdr, bool bHighBits, bool bIgnoreShift = false);
	void SetScrollPositionY(UINT nPosition, bool bUpdate=false);
	void SetScrollPositionX(UINT nPosition, bool bUpdate=false);
	void SetScrollbarRanges();
	void MoveScrollPostionY(int iDelta, bool bUpdate=false);
	void MoveScrollPostionX(int iDelta, bool bUpdate=false);
	void StartMouseRepeat(const CPoint& cPoint, int iDelta, WORD nSpeed);
	void StopMouseRepeat();
	void GetAddressFromPoint(const CPoint& cPt, UINT& nAddress, bool& bHighByte);
	UINT CreateHighlightingPolygons(const CRect& cHexRect,
		UINT nBegin, UINT nEnd, POINT *pPoints);
	void ReInitialize();
	bool Allocate(UINT nLen);
	void OnEditCopyCutDelete(bool cutdel,bool clipboard);
	void OnDelete(WPARAM wParam);

	//{{AFX_VIRTUAL(CHexEditBase)
	virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
	virtual BOOL PreTranslateMessage(MSG* pMsg);
	virtual void PostNcDestroy();
	//}}AFX_VIRTUAL

	//{{AFX_MSG(CHexEditBase)
	afx_msg void OnDestroy();
	afx_msg void OnTimer(UINT nTimerID);
	afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint);
	afx_msg void OnContextMenu(CWnd* pWnd, CPoint cPoint);
	afx_msg LRESULT OnWMChar(WPARAM wParam, LPARAM);
	afx_msg LRESULT OnWMSetFont(WPARAM wParam, LPARAM lParam);
	afx_msg LRESULT OnWMGetFont(WPARAM wParam, LPARAM lParam);
	afx_msg LRESULT OnUmSetScrollRange(WPARAM, LPARAM);
	afx_msg void OnKillFocus(CWnd* pNewWnd);
	afx_msg void OnPaint();
	afx_msg void OnSetFocus(CWnd*);
	afx_msg void OnSize(UINT nType, int cx, int cy);
	afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar*);
	afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar*);
	afx_msg UINT OnGetDlgCode();
	afx_msg BOOL OnEraseBkgnd(CDC*);
	afx_msg void OnLButtonDown(UINT, CPoint point);
	afx_msg void OnLButtonDblClk(UINT, CPoint point);
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
	afx_msg void OnLButtonUp(UINT, CPoint);
	afx_msg void OnKeyDown(UINT nChar, UINT, UINT);
	afx_msg void OnEditCut();
	afx_msg void OnEditCopy();
	afx_msg void OnEditPaste();
	afx_msg void OnEditClear();
	afx_msg void OnEditSelectAll();
	afx_msg void OnToTxt();
	//}}AFX_MSG
	DECLARE_DYNCREATE(CHexEditBase)
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// class CHexEditBaseView
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

#include "CrypToolView.h"

class CHexEditBaseView : public CCrypToolView
{
	DECLARE_DYNCREATE(CHexEditBaseView)

public:
	enum { IDC_HEXEDITBASEVIEW_HEXCONTROL = 0x100 };

	CHexEditBaseView();
	virtual ~CHexEditBaseView();
	CHexEditBase& GetHexEditCtrl() { return m_cHexEdit; }

protected:
	CHexEditBase m_cHexEdit;

	//{{AFX_VIRTUAL(CHexEditBaseView)
	virtual void OnDraw(CDC*);
	//}}AFX_VIRTUAL

	//{{AFX_MSG(CHexEditBaseView)
	afx_msg BOOL OnEraseBkgnd(CDC*);
	afx_msg int OnCreate(LPCREATESTRUCT pCreateStruc);
	afx_msg void OnSize(UINT nType, int cx, int cy);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
public:
	// this function is re-implemented in CHexEditCtrlView
	virtual void showAsText() { }
};

#endif


text:
.class public final Landroid/view/WindowManagerImpl;
.super Ljava/lang/Object;
.source "WindowManagerImpl.java"

# interfaces
.implements Landroid/view/WindowManager;

# instance fields
.field private final mDisplay:Landroid/view/Display;

.field private final mGlobal:Landroid/view/WindowManagerGlobal;

.field private final mParentWindow:Landroid/view/Window;

# direct methods
.method public constructor <init>(Landroid/view/Display;)V
    .locals 1
    .parameter "display"

    .prologue
    .line 51
    const/4 v0, 0x0

    invoke-direct {p0, p1, v0}, Landroid/view/WindowManagerImpl;-><init>(Landroid/view/Display;Landroid/view/Window;)V

    .line 52
    return-void
.end method

.method private constructor <init>(Landroid/view/Display;Landroid/view/Window;)V
    .locals 1
    .parameter "display"
    .parameter "parentWindow"

    .prologue
    .line 54
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 46
    invoke-static {}, Landroid/view/WindowManagerGlobal;->getInstance()Landroid/view/WindowManagerGlobal;

    move-result-object v0

    iput-object v0, p0, Landroid/view/WindowManagerImpl;->mGlobal:Landroid/view/WindowManagerGlobal;

    .line 55
    iput-object p1, p0, Landroid/view/WindowManagerImpl;->mDisplay:Landroid/view/Display;

    .line 56
    iput-object p2, p0, Landroid/view/WindowManagerImpl;->mParentWindow:Landroid/view/Window;

    .line 57
    return-void
.end method

# virtual methods
.method public addView(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V
    .locals 3
    .parameter "view"
    .parameter "params"

    .prologue
    .line 69
    iget-object v0, p0, Landroid/view/WindowManagerImpl;->mGlobal:Landroid/view/WindowManagerGlobal;

    iget-object v1, p0, Landroid/view/WindowManagerImpl;->mDisplay:Landroid/view/Display;

    iget-object v2, p0, Landroid/view/WindowManagerImpl;->mParentWindow:Landroid/view/Window;

    invoke-virtual {v0, p1, p2, v1, v2}, Landroid/view/WindowManagerGlobal;->addView(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;Landroid/view/Display;Landroid/view/Window;)V

    .line 70
    return-void
.end method

.method public createLocalWindowManager(Landroid/view/Window;)Landroid/view/WindowManagerImpl;
    .locals 2
    .parameter "parentWindow"

    .prologue
    .line 60
    new-instance v0, Landroid/view/WindowManagerImpl;

    iget-object v1, p0, Landroid/view/WindowManagerImpl;->mDisplay:Landroid/view/Display;

    invoke-direct {v0, v1, p1}, Landroid/view/WindowManagerImpl;-><init>(Landroid/view/Display;Landroid/view/Window;)V

    return-object v0
.end method

.method public createPresentationWindowManager(Landroid/view/Display;)Landroid/view/WindowManagerImpl;
    .locals 2
    .parameter "display"

    .prologue
    .line 64
    new-instance v0, Landroid/view/WindowManagerImpl;

    iget-object v1, p0, Landroid/view/WindowManagerImpl;->mParentWindow:Landroid/view/Window;

    invoke-direct {v0, p1, v1}, Landroid/view/WindowManagerImpl;-><init>(Landroid/view/Display;Landroid/view/Window;)V

    return-object v0
.end method

.method public getDefaultDisplay()Landroid/view/Display;
    .locals 1

    .prologue
    .line 89
    iget-object v0, p0, Landroid/view/WindowManagerImpl;->mDisplay:Landroid/view/Display;

    return-object v0
.end method

.method public removeView(Landroid/view/View;)V
    .locals 2
    .parameter "view"

    .prologue
    .line 79
    iget-object v0, p0, Landroid/view/WindowManagerImpl;->mGlobal:Landroid/view/WindowManagerGlobal;

    const/4 v1, 0x0

    invoke-virtual {v0, p1, v1}, Landroid/view/WindowManagerGlobal;->removeView(Landroid/view/View;Z)V

    .line 80
    return-void
.end method

.method public removeViewImmediate(Landroid/view/View;)V
    .locals 2
    .parameter "view"

    .prologue
    .line 84
    iget-object v0, p0, Landroid/view/WindowManagerImpl;->mGlobal:Landroid/view/WindowManagerGlobal;

    const/4 v1, 0x1

    invoke-virtual {v0, p1, v1}, Landroid/view/WindowManagerGlobal;->removeView(Landroid/view/View;Z)V

    .line 85
    return-void
.end method

.method public updateViewLayout(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V
    .locals 1
    .parameter "view"
    .parameter "params"

    .prologue
    .line 74
    iget-object v0, p0, Landroid/view/WindowManagerImpl;->mGlobal:Landroid/view/WindowManagerGlobal;

    invoke-virtual {v0, p1, p2}, Landroid/view/WindowManagerGlobal;->updateViewLayout(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V

    .line 75
    return-void
.end method


text:
<?xml version="1.0"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wso2.bpel</groupId>
    <artifactId>ode-jacob</artifactId>
    <packaging>jar</packaging>
    <name>ODE :: Java Concurrent Objects (JACOB)</name>
    <parent>
        <groupId>org.wso2.bpel</groupId>
        <artifactId>ode</artifactId>
        <version>1.3.5-wso2v17-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.wso2.bpel</groupId>
            <artifactId>ode-utils</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
         <!-- uncomment it for @ChannelType classes regeneration -->
         <!--plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>apt-maven-plugin</artifactId>
			<version>1.0-alpha-3</version>
			<configuration>
			  <factory>org.apache.ode.jacob.ap.JacobAnnotationProcessorFactory</factory>
			  <outputDirectory>src/main/java</outputDirectory>
			</configuration>
			<executions>
			   <execution>
			    <goals>
			       <goal>process</goal>
			       <goal>test-process</goal>
			    </goals>
			   </execution>
		        </executions>
			<dependencies>
			   <dependency>
			      <groupId>org.wso2.bpel</groupId>
			      <artifactId>ode-jacob-ap</artifactId>
			      <version>${ode.version}</version>
			   </dependency>
			 </dependencies>
            </plugin-->
        </plugins>
    </build>
</project>


text:
import sys
import re
import itertools
import copy
import types
import StringIO
import collections
import time
import os
import os.path
import platform
if platform.system() in ["Darwin"]:
    # Mac OS is dumb and uses netbsd's readline, so we need to import a
    # different lib
    import gnureadline as readline
else:
    import readline

readline.parse_and_bind("tab: complete")
history_path = os.path.expanduser("~/.vision_history")
try:
    readline.read_history_file(history_path)
except IOError as ioe:
    if ioe.errno == 2:
        # The file wasn't there, make it and try again
        open(history_path, 'w+').write('')
        readline.read_history_file(history_path)

# MIE libraries
import visionparser
import visionexceptions

"""
Vision Scanner

This defines the keywords, seperators, scope indicators, etc of the
Vision language.  It takes a filish input which iterates over its input
by lines seperated by newline characters.

It is an iterator that produces a token each iteration.  A token is
defined as either a Command (which represents the start of a line), a
ScopeChange (in this case, four spaces '    '), a Literal (a string
of arbitrary characters surrounded by single quotes, with option escaped
single quotes inside), or a ParserObject (one of the keywords of the
language).
"""

class BasicTokenizer(object):
    """
    Splits a line into tokens.
    """

    # Tokens that are there to let the user write English, not Caveman
    sugar = (
        'to',
        'in',
        'for',
        'with',
        'new',
        'item',
        'from',
        'on',
        'into',
        'it',
        'and_get',
    )

    # These things seperate one token from another
    seperators = (
        'punctuation',
        'whitespace'
    )

    # These tokens are searched for before keywords
    before_keywords = ('literal',)

    # These tokens are searched for after keywords
    after_keywords = ()

    # This tells what to do when we get particular kinds of tokens
    tokens = {}

    REs = {
        'attributenoun': """(?P<attributenoun>{([^}]|\\\\})+})""",
        'literal': """(?P<literal>"[^"]*"|'[^']*')""",
        'fileliteral': r"""(?P<fileliteral><[^>]+>)""",
        'punctuation': r"(?P<punctuation>([^\w'<>]|_))",
        'whitespace': r"(?P<whitespace>[ ]+)",
        'ordinalnumber': "(?P<ordinalnumber>%s)" % visionparser.Ordinal.regexp,
    }

    # These functions will be applied to the tokenmapper just before it
    # is returned
    token_transforms = ()

    def __init__(self, scanner=None, commandtype=None):
        self.scanner = scanner
        self.commandtype = commandtype

    def scanline(self, line, position):
        """
        Takes a line of Vision and returns a line of tokens
        """

        command = self.commandtype(
            scanner=self.scanner,
            lineno=position)
        try:
            tokens, remainder = self.scanline_with_remainder(line)
            if remainder:
                # We have a remainder, this is an error
                start = len(line) - len(remainder)
                msg = "Parse failure at line %d, starting at character %d: " % (command.lineno, start + 1)
                compiled_regex = re.compile(self.regexps['whitespace'], re.IGNORECASE)
                newpos = start + 1
                while newpos < len(line):
                    if compiled_regex.match(line[newpos:]):
                        break
                    newpos += 1
                msg += '"%s" was not recognized' % line[start:newpos]
                raise visionexceptions.GarbageInputError(
                    code=line,
                    command=command,
                    start=start,
                    message=msg)
            return [command] + tokens
        except Exception as e:
            e.command = command
            raise

    def scanline_with_remainder(self, line):
        """
        Takes a line of Vision and returns a line of tokens and a string
        that is the part that could not be tokenized
        """

        start=0
        tokens = []

        # We're going to save the lines after stripping leading
        # whitespace, we need to get the ammount of offset that'll be so
        # we can tell the tokens their proper start/end postions
        offset = len(line) - len(line.lstrip())
        compiled_regexes = [re.compile(regex, re.IGNORECASE) for regex in self.regexes]
        remainder = line
        while start < len(line):
            token_type = None
            token = None
            for regex in compiled_regexes:
                token_match = regex.match(line[start:])
                try:
                    match_dict = token_match.groupdict()
                    token_type = next(itertools.dropwhile(
                        lambda token_type: not match_dict.get(token_type, None),
                        self.token_order))
                    token = match_dict[token_type]

                    # We found a match, call the action and break this loop
                    self.scanner.token_match_action(token, line[:start])
                    break
                except visionexceptions.GarbageInputError, gie:
                    # if we got garbage here, reraise
                    raise
                except:
                    # There were no matches, eat this so we can try the
                    # next one
                    pass
            else:
                # We never found a match, this is the remainder
                break

            # We always update our postion in the line
            end = start + len(token)
            to_emit = None
            if token_type not in self.ignore:
                emitter, arguments = self.token_mapper[token_type]
                to_emit = emitter(
                    identifier=token,
                    start=start - offset,
                    scanner_args=arguments)
            start = end
            if to_emit:
                tokens.append(to_emit)

            remainder = line[start:]
        return (tokens,remainder)

    @property
    def regexes(self):
        if not hasattr(self, '_regexes'):
            self._regexes = []
            current = []
            for i, token in enumerate(self.token_order):
                regex = self.regexps.get(
                    token,
                    "(?P<%s>%s)" % (token, token.replace('_', ' ')))
                if i and not(100 % i):
                    # We need another regex, we can only group so many
                    # at a time
                    self._regexes.append('|'.join(current))
                    current = []
                current.append(regex)
            self._regexes.append('|'.join(current))
        return self._regexes

    @property
    def ignore(self):
        return self.sugar + self.seperators

    def get_regexps(self):
        return copy.deepcopy(BasicTokenizer.REs)

    @property
    def regexps(self):
        regexps = self.get_regexps()
        regexps.update(
            self.scanner.get_regexps() if self.scanner else {})
        return regexps

    def get_token_mapper(self):
        return copy.deepcopy(BasicTokenizer.tokens)

    @property
    def token_mapper(self):
        token_mapper = self.get_token_mapper()
        token_mapper.update(
            self.scanner.get_token_mapper() if self.scanner else {})
        for transform in self.token_transforms:
            transform(token_mapper)
        return token_mapper

    @property
    def token_order(self):
        """
        This is the order in which we need to look for tokens
        """

        if not hasattr(self, '_token_order'):
            _token_order = collections.OrderedDict()
            tokens_tuple = (
                self.before_keywords,
                tuple(self.regexps),
                tuple(self.token_mapper),
                self.after_keywords,
                self.sugar)
            for t in itertools.chain.from_iterable(
              [sorted(toks, key=len, reverse=True) for toks in tokens_tuple]):
                _token_order[t] = True
            self._token_order = tuple(_token_order)
        return self._token_order

class VisionScanner(object):
    """
    Iterable scanner

    This is basic class for Scanners.  All it needs is a name and a
    tokenizer, although giving it a parts is a good idea.
    """

    def __init__(self, name, tokenizer, parser=None, maximum_time=15, allowable_time=3):
        self.parser = parser
        self.name = name
        self.tokenizer = tokenizer
        self.lines = []
        self.position = 0
        self.maximum_time=maximum_time
        self.allowable_time=allowable_time
        tokenizer.scanner = self

    def __iter__(self):
        return self

    def __bool__(self):
        return True
    # Python 2 compatibility
    __nonzero__ = __bool__

    def addline(self, newlines):
        self.lines.extend(newlines)

    def insertline(self, newlines):
        self.lines = self.lines[:self.position] + newlines + self.lines[self.position:]

    def format_line(self, line):
        mod_line = '    '.join(line.split('\t')).rstrip()
        return mod_line

    def get_regexps(self):
        # something for subclasses to extend
        return {}

    def get_token_mapper(self):
        # something for subclasses to extend
        return {}

    def scanline(self, line, position):
        """
        This method provides a hook that subscanners can override if
        they need to provide special handling for lines.
        """
        return self.tokenizer.scanline(line, position + 1)

    def next(self):
        token_list = []
        command = self.commandtype(
            scanner=self,
            lineno=self.position + 1)
        line_iter = iter(self.lines[self.position:])
        line = ''
        exception = None
        while not line:
            # read until there's a non-blank line
            # or we run out of lines
            line = self.format_line(next(line_iter))
            exception = None
            try:
                if line:
                    # We have a string, tokenize it
                    token_list = self.scanline(line, self.position)
                    command = token_list[0]
                else:
                    self.advance()
            except StopIteration as si:
                si.command = command
                raise
            except Exception as e:
                command = e.command = getattr(e, 'command', command)
                if command and command not in token_list:
                    token_list.insert(0, command)
        return token_list

    def advance(self, lines=1):
        if not self.done:
            self.position += lines

    def token_match_action(self, token, scanned_line):
        # This is a hook for other scanners
        pass

    @property
    def done(self):
        return self.position >= len(self.lines)

class VisionFileScanner(VisionScanner):
    """
    This is a VisionScanner for the version of Vision that is loaded
    from a file.
    """

    # Set up the special regexps
    commandtype = visionparser.InterpreterCommand

    tokens = {
        'scope_change': [visionparser.ScopeChange, {}],
        'interactive': [visionparser.InterpreterVerb, {'cant_have':(visionparser.Literal,)}],
    }

    REs = {
        'scope_change': '(?P<scope_change>    )',
        'whitespace': '(?P<whitespace>[ \n])',
    }

    def __init__(self, filish, tokenizer, filename=None, subcommand=False, parser=None, *args, **kwargs):
        file_name = filename or filish.name
        super(VisionFileScanner, self).__init__(
            name=file_name,
            parser=parser,
            tokenizer=tokenizer,
            *args,
            **kwargs)
        self.addline(filish)

    def next(self):
        command = None
        exception = None
        try:
            command = super(VisionFileScanner, self).next()
            return command
        except StopIteration as si:
            exception = si
            raise
        except Exception as e:
            import traceback;traceback.print_exc()
            exception = e
            raise
        finally:
            if not (isinstance(exception, StopIteration) or (getattr(command, 'error', None) and not self.parser.interpreter.interactivity_enabled)):
                self.advance()

    def get_regexps(self):
        regexps = super(VisionFileScanner, self).get_regexps()
        regexps.update(copy.deepcopy(VisionFileScanner.REs))
        return regexps

    def get_token_mapper(self):
        tokens = super(VisionFileScanner, self).get_token_mapper()
        tokens.update(copy.deepcopy(VisionFileScanner.tokens))
        return tokens

    def scanline(self, line, position):
        """
        This handles indention scoping
        """
        tokens = super(VisionFileScanner, self).scanline(line, position)
        command, tokens = tokens[0], tokens[1:]

        # Handle all the indentation stuff
        # Count the number of ScopeChanges at the front
        scope_level = len(list(itertools.takewhile(
            lambda tok:isinstance(tok, visionparser.ScopeChange),
            tokens)))

        scopes = command.scopes
        if scope_level > len(scopes):
            # We've indented too far
            raise visionexceptions.GarbageInputError(
                code=line,
                start=0,
                message="Too many indents on line",
                command=command)

        # Filter out any remaining ScopeChanges
        tokens = [t for t in tokens if not isinstance(t, visionparser.ScopeChange)]
        if scope_level < len([scope for scope in scopes if scope.scanner is self]) and scope_level < len(scopes):
            # This line is dedented from the rest of the file it's from
            # and we haven't done and "end" command via interactive prompt
            # add the appropriate "end command"

            # Now we'll put a line ending the scope in the
            # test that matches the indentation level of the line
            scope = scopes[scope_level + (len(scopes) - len([scope for scope in scopes if scope.scanner is self]))]

            label, scope_type = str(scope.verb.value), scope.verb.type
            literal_marker = "'" if "'" not in label else '"'
            line = "End %s %s%s%s" % (scope_type, literal_marker, label, literal_marker)
            self.parser.subcommand_scanner.addline(StringIO.StringIO(line))
            self.parser.scanner = self.parser.subcommand_scanner

            # raise StopIteration so that the parser can pull from
            # the subcommand scanner
            raise StopIteration()

        return [command] + tokens

    def addline(self, newlines):
        super(VisionFileScanner, self).addline(
            {'breakpoint': False, 'code': line} for line in newlines)

    def insertline(self, newlines):
        super(VisionFileScanner, self).insertline(
            {'breakpoint': False, 'code': line} for line in newlines)

    def get_line(self):
        line = tokens = None
        while not tokens:
            # read lines until we get one that isn't empty
            # or just indents
            line = super(VisionFileScanner, self).get_line()['code']
            tokens = line.strip()

        return line

    def advance(self, lines=1, honor_breakpoints=True):
        if not self.done:
            for x in range(lines):
                self.lines[self.position]['breakpoint'] = False
                self.position += 1

    def rewind(self, lines=1):
        self.position -= lines

    def format_line(self, line):
        if (self.lines[self.position]['breakpoint'] or not self.parser.interpreter.next_command) and self.parser.interpreter.interactivity_enabled:
            # We're moving to the next line and the interpreter supports interactive mode
            self.lines[self.position]['breakpoint'] = False
            raise StopIteration()
        return super(VisionFileScanner, self).format_line(line['code'])

    def toggle_breakpoint(self, number=None):
        number = (number - 1) if number else self.position
        self.lines[number]['breakpoint'] = not self.lines[number]['breakpoint']

    def toggle_token_breakpoint(self, token_type):
        found = False
        if "_".join(token_type.split()) in self.tokenizer.token_mapper:
            # Toggle the breakpoint for each line with
            # this kind of token, if there are any lines
            for (i, line) in itertools.dropwhile(lambda pair, start=self.position: pair[0] < start, enumerate(self.lines)):
                tokens, remainder = self.tokenizer.scanline_with_remainder(line['code'])
                if not remainder and [tok for tok in tokens if tok.type == token_type]:
                    self.toggle_breakpoint(i + 1)
                    found = True
            if not found:
                raise visionexceptions.VisionException(
                    message="'%s' does not contain token type '%s' after line %d" % (
                        self.name,
                        token_type,
                        self.position))
        else:
            raise visionexceptions.VisionException(
                message="'%s' is not an accepted token type in '%s'" % (
                    token_type,
                    self.name))

    def token_match_action(self, token, line):
        if not line.strip():
            # Have't seen anything but spaces/tabs
            if token == ' ':
                # We've got bad indentation, raise GarbageInputError
                raise visionexceptions.GarbageInputError(
                    code=line,
                    start=0,
                    message="Improper indentation")
        return True

    @property
    def scope_level(self):
        for command in reversed(self.parser.children):
            if command.usable and (command.scanner is self):
                return len(list(itertools.takewhile(
                    lambda tok:isinstance(tok, visionparser.ScopeChange),
                    self.scanline(self.lines[command.lineno - 1], command.lineno))))
        else:
            return 0

class InteractiveTokenizer(BasicTokenizer):
    """
    This is a tokenizer that knows how to handle tokens specific to
    the interactive prompt.
    """

    tokens = {
        'end_test': [visionparser.InterpreterVerb, {}],
        'end_require': [visionparser.InterpreterVerb, {}],
        'set': [visionparser.InterpreterVerb, {'must_have': (visionparser.Literal,)}],
        'load_test': [visionparser.InterpreterVerb, {}],
        'run_test': [visionparser.InterpreterVerb, {}],
        'save_test': [visionparser.InterpreterVerb, {'must_have': (visionparser.Literal,)}],
        'show_context': [visionparser.InterpreterVerb, {}],
        'where': [visionparser.InterpreterVerb, {}],
        'show_test': [visionparser.InterpreterVerb, {}],
        'show_input': [visionparser.InterpreterVerb, {}],
        'pop': [visionparser.InterpreterVerb, {'cant_have': {visionparser.Literal: 2}}],
        'show_all_input': [visionparser.InterpreterVerb, {}],
        'skip': [visionparser.InterpreterVerb, {}],
        'next_command': [visionparser.InterpreterVerb, {'cant_have': (visionparser.Literal,)}],
        'break': [visionparser.InterpreterVerb, {'must_have': (visionparser.Literal,)}],
        'step_into_python': [visionparser.InterpreterVerb, {'cant_have': (visionparser.Literal,)}],
        'quit': [visionparser.InterpreterVerb, {}],
        'finish': [visionparser.InterpreterVerb, {'cant_have':[visionparser.Literal]}],
        'help': [visionparser.InterpreterVerb, {'cant_have': {visionparser.Literal: 2}}],
    }

    def get_token_mapper(self):
        tokens = super(InteractiveTokenizer, self).get_token_mapper()
        tokens.update(copy.deepcopy(InteractiveTokenizer.tokens))

        return tokens

class InteractiveVisionScanner(VisionScanner):
    """
    This is a VisionScanner for the version of Vision that is intended
    to be used interactively.
    """
    # We use InterpreterCommands
    commandtype = visionparser.InterpreterCommand

    def __init__(self, name, tokenizer, subcommand=False, parser=None, *args, **kwargs):
        super(InteractiveVisionScanner, self).__init__(
            name=name,
            tokenizer=tokenizer,
            parser=parser,
            *args,
            **kwargs)
        self.subcommand = subcommand

    def next(self):
        try:
            tokens = super(InteractiveVisionScanner, self).next()
            if self is self.parser.subcommand_scanner and self.parser.children:
                # This is a subcommand, set the origin scanner to be the
                # one from the previous command that has a Verb that is
                # not an InterpreterVerb or is End, if there is one
                try:
                    tokens[0].origin_scanner = next(
                        com.origin_scanner
                        for com in reversed(self.parser.children)
                        if com.verb and not isinstance(com.verb, visionparser.InterpreterVerb))
                except StopIteration as si:
                    # there wasn't a previous command.
                    pass
        except StopIteration, si:
            if not self.subcommand:
                try:
                    scope = str(self.scopes[-1].verb.value) if self.scopes else 'global'
                    if self.parser.file_scanner:
                        inp = raw_input( "<%s>:%s|%s:  " % (
                            self.parser.file_scanner.name,
                            self.parser.file_scanner.position + 1 if self.parser.file_scanner.position + 1 <= len(self.parser.file_scanner.lines) else "EOF",
                            scope))
                    else:
                        inp = raw_input( "<%s>:%s|%s:  " % (
                            "NO FILE",
                            self.position + 1,
                            scope))
                except Exception, e:
                    inp = 'quit'
                self.addline(StringIO.StringIO(inp))
                tokens = super(InteractiveVisionScanner, self).next()
            else:
                # If it's a subcommand, when we're done, we're done
                raise
        finally:
            readline.write_history_file(os.path.expanduser("~/.vision_history"))
            self.advance()
        return tokens

    @property
    def scopes(self):
        scopes = []
        try:
            command = next(com for com in reversed(self.parser.children) if com.parsed and not com.error)
            scopes.extend(command.scopes)
            if command.scopechange > 0:
                # The most recent command opened a scope,
                # include it in the list
                scopes.append(command)
            elif command.scopechange < 0:
                # The most recent command closed a scope,
                # cut the end of the scope list
                scopes = scopes[:command.scopechange]
        except StopIteration as si:
            pass
        return scopes


text:
var assert = require('assert')

var carbon = require('carbon-io')

var __ = carbon.fibers.__(module)
var o = carbon.atom.o(module)
var testtube = carbon.testtube

__(function() {
  module.exports = o.main({
    _type: testtube.Test,
    name: 'SimpleNestedTests',
    description: 'A simple set of tests',
    setup: function() {
      assert(typeof this.level === 'undefined')
      this.level = 0
    },
    doTest: function() {
      assert.equal(this.level, 0)
    },
    teardown: function() {
      assert.equal(this.level, 0)
      delete this.level
    },
    tests: [
      o({
        _type: testtube.Test,
        name: 'SimpleNestedTest',
        setup: function() {
          this._oldLevel = this.parent.level
          this.parent.level += 1
        },
        doTest: function() {
          assert.equal(this.parent.level, this._oldLevel + 1)
        },
        teardown: function() {
          try {
            assert.equal(this.parent.level, this._oldLevel + 1)
          } finally {
            this.parent.level = this._oldLevel
          }
        },
        tests: [
          o({
            _type: testtube.Test,
            name: 'SimpleDoubleNestedAsyncTest',
            setup: function(_, done) {
              var self = this
              setImmediate(function() {
                self._oldLevel = self.parent.parent.level
                self.parent.parent.level += 1
                done()
              })
            },
            doTest: function(_, done) {
              var self = this
              setImmediate(function() {
                var err = undefined
                try {
                  assert.equal(self.parent.parent.level, self._oldLevel + 1)
                } catch (e) {
                  err = e
                }
                done(err)
              })
            },
            teardown: function(_, done) {
              var self = this
              setImmediate(function() {
                var err = undefined
                try {
                  assert.equal(self.parent.parent.level, self._oldLevel + 1)
                } catch (e) {
                  err = e
                } finally {
                  self.parent.parent.level = self._oldLevel
                }
                done(err)
              })
            },
            tests: [
              o({
                _type: testtube.Test,
                name: 'SimpleTripleNestedTest',
                setup: function() {
                  this._oldLevel = this.parent.parent.parent.level
                  this.parent.parent.parent.level += 1
                },
                doTest: function() {
                  assert.equal(
                    this.parent.parent.parent.level, this._oldLevel + 1)
                },
                teardown: function() {
                  try {
                    assert.equal(
                      this.parent.parent.parent.level, this._oldLevel + 1)
                  } finally {
                    this.parent.parent.parent.level = this._oldLevel
                  }
                }
              })
            ]
          })
        ]
      })
    ]
  })
})


text:
package com.pavelsklenar.rest.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pavelsklenar.rest.pojo.Customer;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @GetMapping("/{id}")
    @Secured("ROLE_USER")
    public Customer GetCustomer(@PathVariable Long id) {
        return new Customer(id, "Customer" + id);
    }
}


text:
SELECT TOP(5)
		c.CountryName ,
		r.RiverName
  FROM CountriesRivers AS cr
 FULL JOIN Countries AS c
  ON c.CountryCode = cr.CountryCode
 FULL JOIN Rivers AS r
  ON r.Id = cr.RiverId
 FULL JOIN Continents
  ON Continents.ContinentCode = c.ContinentCode
  WHERE Continents.ContinentName = 'Africa'
ORDER BY CountryName ASC


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Android.Graphics;
using Android.Hardware;
using Rb.Forms.Barcode.Droid.Logger;
using Rb.Forms.Barcode.Pcl.Logger;
using AndroidCamera = Android.Hardware.Camera;
using JObject = Java.Lang.Object;
using RebuyCameraSource = Com.Rebuy.Play.Services.Vision.CameraSource;

#pragma warning disable 618
namespace Rb.Forms.Barcode.Droid.Camera
{
    public class CameraConfigurator : JObject, ILog, RebuyCameraSource.IConfigurationCallback
    {

        public class FpsRange
        {
            public uint Min { get; private set; }
            public uint Max { get; private set; }

            public FpsRange(int[] range)
            {
                Min = Convert.ToUInt32(range[(int) Preview.FpsMinIndex]);
                Max = Convert.ToUInt32(range[(int) Preview.FpsMaxIndex]);
            }

            public FpsRange(uint[] range)
            {
                Min = range[(int) Preview.FpsMinIndex];
                Max = range[(int) Preview.FpsMaxIndex];
            }

            public FpsRange(uint min, uint max)
            {
                Min = min;
                Max = max;
            }
        }
        private Configuration config;
        private System.Drawing.Size viewSize;

        /// <summary>
        /// Sets the camera configuration.
        /// </summary>
        public CameraConfigurator SetConfiguration(Configuration config)
        {
            this.config = config;
            return this;
        }

        /// <summary>
        /// Sets current view size.
        ///
        /// This affects the selected camera preview size as we try to use a resolution which is
        /// within the bounds of the aspect ratio threshold.
        ///
        /// <see cref="Configuration.PreviewResolution"/>
        /// <see cref="Configuration.AspectRatioThreshold" />
        /// </summary>
        public CameraConfigurator SetViewSize(System.Drawing.Size viewSize)
        {
            this.viewSize = viewSize;
            return this;
        }

        /// <summary>
        /// Configures the specified camera.
        /// </summary>
        public AndroidCamera Configure(AndroidCamera camera)
        {
            var parameters = camera.GetParameters();

            try {
                camera.CancelAutoFocus();
            } catch (Exception e) {
                this.Debug(e.Message);
            }

            parameters.PreviewFormat = ImageFormatType.Nv21;

            var focusMode = determineFocusMode(parameters);

            invokeIfAvailable(focusMode, val => {
                this.Debug("Focus Mode [{0}]", val);
                parameters.FocusMode = val;
            });

            var preview = determinePreviewResolution(parameters);
            this.Debug("Preview resolution [Width: {0}] x [Height {1}]", preview.Width, preview.Height);
            parameters.SetPreviewSize(preview.Width, preview.Height);

            // Set picture size with an equal ratio as the preview image.
            // According to google you will get a distorted image on some hardware, if you would only set the preview size.
            var picture = determinePictureResolution(parameters, preview);
            this.Debug("Picture resolution [Width: {0}] x [Height {1}]", picture.Width, picture.Height);
            parameters.SetPictureSize(picture.Width, picture.Height);

            if (config.TargetFps > 0) {
                var range = determineFpsRange(parameters, config.TargetFps);
                this.Debug("FPS Range [Min: {0}] - [Max {1}]", range.Min / 1000, range.Max / 1000);
                parameters.SetPreviewFpsRange((int) range.Min, (int) range.Max);
            }

            if (config.CompatibilityMode) {
                this.Debug("Compatibility mode enabled. Skipping advanced configuration to ensure highest compatibility.");
            }

            if (!config.CompatibilityMode) {
                if (config.SceneMode) {
                    var sceneMode = determineSceneMode(parameters);

                    invokeIfAvailable(sceneMode, val => {
                        this.Debug("Scene Mode [{0}]", val);
                        parameters.SceneMode = val;
                    });
                }

                if (config.MeteringAreas && parameters.MaxNumMeteringAreas > 0) {
                    this.Debug("Metering area [{0}]", (parameters.MaxNumMeteringAreas > 0).ToString());
                    parameters.MeteringAreas = createAreas();
                }

                if (config.FocusAreas && parameters.MaxNumFocusAreas > 0) {
                    this.Debug("Focusing area [{0}]", (parameters.MaxNumFocusAreas > 0).ToString());
                    parameters.FocusAreas = createAreas();
                }

                if (config.VideoStabilization && parameters.IsVideoStabilizationSupported) {
                    this.Debug("Video stabilization [{0}]", parameters.IsVideoStabilizationSupported.ToString());
                    parameters.VideoStabilization = true;
                }

                if (config.WhiteBalance) {
                    var whiteBalance = determineWhiteBalance(parameters);

                    invokeIfAvailable(whiteBalance, val => {
                        this.Debug("White balance [{0}]", val);
                        parameters.WhiteBalance = val;
                    });

                }
            }

            camera.SetParameters(parameters);

            if (config.Zoom > 0) {
                Zoom(camera, config.Zoom);
            }

            return camera;
        }

        /// <summary>
        /// Toggles the camera torch.
        /// If the camera does not support flash this is a noop.
        /// </summary>
        public void ToggleTorch(AndroidCamera camera, bool state)
        {
            var parameters = camera.GetParameters();

            var flashMode = determineFlashMode(parameters, state);

            invokeIfAvailable(flashMode, val => {
                this.Debug("Flash mode [{0}]", val);
                parameters.FlashMode = val;
                camera.SetParameters(parameters);
            });
        }

        /// <summary>
        /// Apply camera zoom. The zoom value is capped to the maximum supported zoom value.
        /// If the camera does not support zoom this method is a noop.
        /// </summary>
        public void Zoom(AndroidCamera camera, uint zoom)
        {
            var parameters = camera.GetParameters();

            if (!parameters.IsZoomSupported) {
                return;
            }

            var cappedZoom = Convert.ToInt32(zoom);
            cappedZoom = (cappedZoom > parameters.MaxZoom) ? parameters.MaxZoom : cappedZoom;

            this.Debug("Zoom [{0}]", cappedZoom);
            parameters.Zoom = cappedZoom;

            camera.SetParameters(parameters);
        }

        /// <summary>
        /// Determines if the camera supports one of the requested focus modes in FIFO order.
        /// <see cref="Configuration.FocusModes" />
        /// </summary>
        private string determineFocusMode(AndroidCamera.Parameters parameters)
        {
            foreach (var mode in config.FocusModes) {
                if (parameters.SupportedFocusModes.Contains(mode)) {
                    return mode;
                }
            }

            return "";
        }

        /// <summary>
        /// Selects the fps range which is nearest to the desired target fps by calculating the diff between the
        /// target fps and the min and max range individually and then selecting the range with the lowest difference.
        /// If no matching fps range can be found, the currently active range will be returned.
        /// </summary>
        private FpsRange determineFpsRange(AndroidCamera.Parameters parameters, uint targetFps)
        {
            var ranges = parameters.SupportedPreviewFpsRange;

            if (ranges.Count == 1) {
                return new FpsRange(ranges.First());
            }

            Func<int[], long> fpsSorter = range =>  {
                var min = targetFps - range[(int) Preview.FpsMinIndex];
                var max = targetFps - range[(int) Preview.FpsMaxIndex];

                return Math.Abs(min) + Math.Abs(max);
            };

            var currentRange = new [] {0, 0};
            parameters.GetPreviewFpsRange(currentRange);

            var targetRange = ranges
                .OrderBy(fpsSorter)
                .DefaultIfEmpty(currentRange)
                .First();

            return new FpsRange(targetRange);
        }

        /// <summary>
        /// Determines if the camera supports the scene mode "Barcode".
        /// </summary>
        private string determineSceneMode(AndroidCamera.Parameters parameters)
        {
            if (parameters.SupportedSceneModes.Contains(AndroidCamera.Parameters.SceneModeBarcode)) {
                return AndroidCamera.Parameters.SceneModeBarcode;
            }

            return AndroidCamera.Parameters.SceneModeAuto;
        }

        /// <summary>
        /// Determines if the camera supports the white balance mode "auto".
        /// </summary>
        private string determineWhiteBalance(AndroidCamera.Parameters parameters)
        {
            if (parameters.SupportedWhiteBalance.Contains(AndroidCamera.Parameters.WhiteBalanceAuto)) {
                return AndroidCamera.Parameters.WhiteBalanceAuto;
            }

            return "";
        }

        /// <summary>
        /// Determines if the camera supports flash modes that allow us to switch it on or off.
        /// </summary>
        private string determineFlashMode(AndroidCamera.Parameters p, bool state)
        {
            if (state && p.SupportedFlashModes.Contains(AndroidCamera.Parameters.FlashModeTorch)) {
                return AndroidCamera.Parameters.FlashModeTorch;
            }

            if (state && p.SupportedFlashModes.Contains(AndroidCamera.Parameters.FlashModeOn)) {
                return AndroidCamera.Parameters.FlashModeOn;
            }

            if (!state && p.SupportedFlashModes.Contains(AndroidCamera.Parameters.FlashModeOff)) {
                return AndroidCamera.Parameters.FlashModeOff;
            }

            return "";
        }

        private List<AndroidCamera.Area> createAreas()
        {
            var area = new AndroidCamera.Area(new Rect(-1000, -400, 1000, 400), 1000);

            return new List<AndroidCamera.Area>() {
                area
            };
        }

        /// <summary>
        /// Invoke callback if value is not null or empty.
        /// </summary>
        private void invokeIfAvailable(string value, Action<string> cb)
        {
            if (string.IsNullOrEmpty(value)) {
                return;
            }

            cb.Invoke(value);
        }

        /// <summary>
        /// Filters preview sizes based on the current view dimensions by considering the aspect ratio.
        /// The preview size is then selected according the configured quality.
        ///
        /// <see cref="Configuration.PreviewResolution"/>
        /// <see cref="Configuration.AspectRatioThreshold" />
        /// </summary>
        private AndroidCamera.Size determinePreviewResolution(AndroidCamera.Parameters parameters)
        {
            var referenceRatio = getViewRatio();

            /**
             * The aspect ratio between the preview resolution and the actual preview view
             * is not allowed to expand the configurated aspect ratio threshold.
             */
            Func<AndroidCamera.Size, bool> ratioFilter = preview =>  {
                var rawr = ((double) preview.Width / (double) preview.Height) - referenceRatio;

                return Math.Abs(rawr) <= config.AspectRatioThreshold;
            };

            /**
             * Remove all sizes that do not adhere to the desired aspect ratio
             * and sort them by size so we can pick according to the desired quality.
             */
            var previewSizes = parameters.SupportedPreviewSizes
                .Where(ratioFilter)
                .OrderByDescending(preview => preview.Width * preview.Height)
                .DefaultIfEmpty(parameters.PreviewSize);

            switch (config.PreviewResolution) {
                case Configuration.Quality.High:
                    return previewSizes.First();

                case Configuration.Quality.Low:
                    return previewSizes.Last();

                case Configuration.Quality.Medium:
                default:
                    // when working with medium quality we always opt for the higher resolution.
                    var index = (int) Math.Ceiling(previewSizes.Count() / 2.0) - 1;
                    return previewSizes.ElementAt(index);
            }
        }

        /// <summary>
        /// Filters picture sizes based on the given preview size by considering the aspect ratio and the resolution.
        /// The first size in the remaining list is then selected.
        /// </summary>
        private AndroidCamera.Size determinePictureResolution(AndroidCamera.Parameters parameters, AndroidCamera.Size preview)
        {
            /**
             * The picture aspect ratio has to be as close as possible to the preview ratio.
             */
            Func<AndroidCamera.Size, bool> ratioFilter = picture =>  {
                var rawr = ((double) picture.Width / (double) picture.Height) - ((double) preview.Width / (double) preview.Height);

                return Math.Abs(rawr) <= 0.1;
            };

            return parameters.SupportedPictureSizes
                .Where(ratioFilter)
                // the picture resolution should not exceed the preview resolution
                .Where(picture => picture.Width * picture.Height <= preview.Width * preview.Height)
                .OrderByDescending(picture => picture.Width * picture.Height)
                .DefaultIfEmpty(parameters.PictureSize)
                .First();
        }

        /// <summary>
        /// Calculates the current view aspect ratio.
        /// </summary>
        private double getViewRatio()
        {
            var ratio =  (double) viewSize.Width / (double) viewSize.Height;

            this.Debug("View [Ratio: {0}] based on [Width: {2}] / [Height {1}]", ratio, viewSize.Height, viewSize.Width);

            return ratio;
        }

    }
}
#pragma warning restore 618


text:
name: Question
about: Have a question? Please check our spectrum community chat.
---

First of all please check our spectrum community chat and we recommend to ask your question there for a quickest response and the indexing in search engines:
- https://spectrum.chat/typesafe-actions

The only good reason to use issue tracker for your questions would be for "special cases" that doesn't fit into bug reports and feature requests categories.