text:
using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace cppcoreguidelines {

namespace {
AST_MATCHER_P(CXXForRangeStmt, hasRangeBeginEndStmt,
              ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
  for (const DeclStmt *Stmt : {Node.getBeginStmt(), Node.getEndStmt()})
    if (Stmt != nullptr && InnerMatcher.matches(*Stmt, Finder, Builder))
      return true;
  return false;
}

AST_MATCHER(Stmt, isInsideOfRangeBeginEndStmt) {
  return stmt(hasAncestor(cxxForRangeStmt(
                  hasRangeBeginEndStmt(hasDescendant(equalsNode(&Node))))))
      .matches(Node, Finder, Builder);
}

AST_MATCHER_P(Expr, hasParentIgnoringImpCasts,
              ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
  const Expr *E = &Node;
  do {
    DynTypedNodeList Parents = Finder->getASTContext().getParents(*E);
    if (Parents.size() != 1)
      return false;
    E = Parents[0].get<Expr>();
    if (!E)
      return false;
  } while (isa<ImplicitCastExpr>(E));

  return InnerMatcher.matches(*E, Finder, Builder);
}
} // namespace

void ProBoundsArrayToPointerDecayCheck::registerMatchers(MatchFinder *Finder) {
  // The only allowed array to pointer decay
  // 1) just before array subscription
  // 2) inside a range-for over an array
  // 3) if it converts a string literal to a pointer
  Finder->addMatcher(
      implicitCastExpr(
          unless(hasParent(arraySubscriptExpr())),
          unless(hasParentIgnoringImpCasts(explicitCastExpr())),
          unless(isInsideOfRangeBeginEndStmt()),
          unless(hasSourceExpression(ignoringParens(stringLiteral()))))
          .bind("cast"),
      this);
}

void ProBoundsArrayToPointerDecayCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *MatchedCast = Result.Nodes.getNodeAs<ImplicitCastExpr>("cast");
  if (MatchedCast->getCastKind() != CK_ArrayToPointerDecay)
    return;

  diag(MatchedCast->getExprLoc(), "do not implicitly decay an array into a "
                                  "pointer; consider using gsl::array_view or "
                                  "an explicit cast instead");
}

} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang

redpajama_set_name: RedPajamaGithub


text:
$(function () {
    $('#UserForm').validate({
        rules: {
            Users_LoginId: { required:true },
            Users_Password: { required:true },
            Users_PasswordValidate: { required:true,equalTo:'#Users_Password' },
            Users_LastName: { required:true },
            Users_FirstName: { required:true }
        },
        messages: {
            Users_LoginId: { required: $('#Users_LoginId').attr('data-validate-required') },
            Users_Password: { required: $('#Users_Password').attr('data-validate-required') },
            Users_PasswordValidate: { required: $('#Users_PasswordValidate').attr('data-validate-required'),equalTo: $('#Users_PasswordValidate').attr('data-validate-equalTo') },
            Users_LastName: { required: $('#Users_LastName').attr('data-validate-required') },
            Users_FirstName: { required: $('#Users_FirstName').attr('data-validate-required') }
        }
    });
    $('#ChangePasswordForm').validate({
        rules: {
            Users_OldPassword: { required:true },
            Users_ChangedPassword: { required:true },
            Users_ChangedPasswordValidation: { required:true,equalTo:'#Users_ChangedPassword' }
        },
        messages: {
            Users_OldPassword: { required: $('#Users_OldPassword').attr('data-validate-required') },
            Users_ChangedPassword: { required: $('#Users_ChangedPassword').attr('data-validate-required') },
            Users_ChangedPasswordValidation: { required: $('#Users_ChangedPasswordValidation').attr('data-validate-required'),equalTo: $('#Users_ChangedPasswordValidation').attr('data-validate-equalTo') }
        }
    });
    $('#ResetPasswordForm').validate({
        rules: {
            Users_AfterResetPassword: { required:true },
            Users_AfterResetPasswordValidation: { required:true,equalTo:'#Users_AfterResetPassword' }
        },
        messages: {
            Users_AfterResetPassword: { required: $('#Users_AfterResetPassword').attr('data-validate-required') },
            Users_AfterResetPasswordValidation: { required: $('#Users_AfterResetPasswordValidation').attr('data-validate-required'),equalTo: $('#Users_AfterResetPasswordValidation').attr('data-validate-equalTo') }
        }
    });
});


text:
ColorOrder = [0 0 1.0000;
	 0 0.5000 0;
	1.0000         0         0;
	0    0.7500    0.7500;
	0.7500         0    0.7500;
	0.7500    0.7500         0;
	0.8000    0.8000    0.8000];

options = setSegmentationDefaults(options,params);

% if available, use params specified by the trained model
fieldNames = fieldnames(models.params);
for i = 1:length(fieldNames)
	setfield(collector.options,fieldNames{i},getfield(models.params,fieldNames{i}));
%	eval(sprintf('collector.options.%s = models.params.%s;',fieldNames{i},fieldNames{i}));
end

% name used in plots containing current parameter combination
names = fieldnames(params);
filename = '';
for i = 1:length(names)
    filename = [filename sprintf('_%s=%.6f',names{i},getfield(params,names{i}))];
end

% some standard variables
%numVolRegions = length(collector.options.labelIDs);
numVolRegions = 1;
% quick hack --> change for final version: check which model components are required and modify the model to fit these requirements;
% better --> just save an array of model indices and leave the model itself untouched
modelsTmp.appearanceModel = cell(size(models.appearanceModel));
if length(models.shapeModel) > 1
	for i = 1:numVolRegions
		% directly determine the scanID (i.e. the slice of the 3-D shape prior that is selected)
		if ~isfield(collector.options,'scanID')
			% calculate distance of i'th Bscan from the center scan in the volume (which is at zero px)
	%		dist = double((collector.options.labelIDs(i) - (floor(double(collector.options.numBScansPerVolume)/2)+1))*collector.options.distBScans/collector.options.clipFactor);
			% DEBUG? removed collector.options.clipFactor --> has nothing do to with z-direction
			dist = double((collector.options.labelIDs(i) - (floor(double(collector.options.numBScansPerVolume)/2)+1))*collector.options.distBScans);
			% find closest B-scan in the shape model
			[~,scanID] = min(abs(models.params.BScanPositions-dist));
			fprintf('DEBUG: Distance to central scan is %.2fmm, picked %d''th component of shape model\n',dist,scanID);
		else
			scanID = collector.options.scanID(i);
		end
		for model = 1:length(models.appearanceModel)
			modelTmp.appearanceModel{model}(i,1:size(models.appearanceModel{model},2),:) = models.appearanceModel{model}(scanID,1:size(models.appearanceModel{model},2),:);
		end
		modelTmp.shapeModel(i) = models.shapeModel(scanID);
		output.modelSelect{1}(i) = scanID;
	end
	% set modified model as the new model
	models = modelTmp;
else
	output.modelSelect{1}(1) = 1;
end
numBounds = length(collector.options.EdgesPred);

% adding simple shape structure to model pathologies
if isfield(options,'addDrusenMode')
	if options.addDrusenMode
		models.shapeModel.WML = [models.shapeModel.WML options.modesToAdd];
	end
end

if length(models.shapeModel) > 1
	error('Reimplement full 3D shape prior');
end

% ************** DETERMINE CONNECTION BETWEEN QB AND QC ******************
collector.options.columnsShape = cell(1,numVolRegions);
% cut shape model to subregion defined by columnsPred
for i = 1:numVolRegions
	minMaxColumns = [min(collector.options.columnsPred) max(collector.options.columnsPred)];
	subsetColumns = find(models.shapeModel(i).columnsShape>=minMaxColumns(1) & models.shapeModel(i).columnsShape<=minMaxColumns(2));
	numColumnsShape = length(models.shapeModel.columnsShape);
	subsetColumnsFull = reshape((repmat(subsetColumns,numBounds,1)+repmat((0:numBounds-1)'.*numColumnsShape,1,length(subsetColumns)))',1,[]);

	models.shapeModel(i).mu = models.shapeModel(i).mu(subsetColumnsFull);
	models.shapeModel(i).WML = models.shapeModel(i).WML(subsetColumnsFull,:);
	models.shapeModel(i).columnsShape = models.shapeModel(i).columnsShape(subsetColumns);
%	numColumns = length(models.shapeModel.columnsShape);

	collector.options.columnsShape{i} = models.shapeModel(i).columnsShape;
end

numRows = collector.options.Y;
numClasses = length(collector.options.EdgesPred) + length(collector.options.LayersPred);
numColumnsPred = length(collector.options.columnsPred);
for i = 1:numVolRegions
	numColumnsShape(i) = length(collector.options.columnsShape{i});
	% the mapping prediction-columns to each shape-columns
	for column = 1:numColumnsShape(i)
		[a b] = min(abs(collector.options.columnsShape{i}(column) - collector.options.columnsPred));
		columnsShapePred{i}(column) = b;
	end
	% the mapping shape-columns to prediction-columns
	for column=1:numColumnsPred
		[a b] = sort(abs(collector.options.columnsPred(column) - collector.options.columnsShape{i}));
		columnsPredShape{i}(:,column) = b(1:2);
		columnsPredShapeFactor{i}(:,column) = a(2:-1:1)./(a(1)+a(2));
	end
end

columnsPredShapeVec = [columnsPredShape{:}];
columnsPredShapeFactorVec = [columnsPredShapeFactor{:}];
numColumnsShapeTotal = sum(numColumnsShape);
% ******************** END *****************************************

output.prediction = cell(length(files),numVolRegions);
output.trueLabels = cell(length(files),numVolRegions);
options.positions = 1:numRows;

% indices for leaving out boundaries, used when accessing mu and W from the shapePrior
if isfield(options,'doNotPredict')
	% first, move from predColumns to shapeColumns
	options.doNotPredictShape = options.doNotPredict(:,columnsShapePred{1}(1,:));
    idx_a = find(reshape(options.doNotPredictShape',1,[]));
    idx_b = find(reshape(~options.doNotPredictShape',1,[]));
	idxPredictFull = ~options.doNotPredictShape;
else
	idx_a = [];
    idx_b = 1:numColumnsShape*numBounds;
	idxPredictFull = ones(numBounds,numColumnsShape);
end

% save for later use, save as short form for better code readability
WML = models.shapeModel.WML; sigmaML = models.shapeModel.sigmaML;
if isfield(options,'variance')
	sigmaML = sigmaML*options.variance;
end
if isfield(options,'windowSize')
	WML = [WML [options.windowModes{:}]];
end
M = inv(WML(idx_b,:)'*WML(idx_b,:) + sigmaML*eye(size(WML,2)));
prodWM = WML*M;
prodWMT = prodWM';

% calculate factors for mu_a_b where a and b are neighbouring boundaries in the same column : 2x2 conditional gaussian distributions
factorsPrecA = cell(1,numVolRegions);
factorsPrecB = cell(1,numVolRegions);
for volRegion = 1:numVolRegions
	if isfield(options,'doNotPredictShape')
		% for each image row detect preceding boundaries
		idxA = []; idxB = [];
		for j = 2:numBounds
			for i = 1:numColumnsShape
				if options.doNotPredictShape(j,i) == 0 && sum(~options.doNotPredictShape(1:j-1,i)) > 0
					idxB = [idxB (j-1)*numColumnsShape + i];
					idxA = [idxA (find(options.doNotPredictShape(1:j-1,i)==0,1,'last')-1)*numColumnsShape + i];
				end
			end
		end
	else
		idxA = (1:numColumnsShape(volRegion)*(numBounds-1)) + sum(numColumnsShape(1:volRegion-1))*numBounds;
		idxB = idxA + numColumnsShape(volRegion);
	end

	% calculate all entries of symmetric covariance matrix
	d = sum(WML(idxB,:).*WML(idxB,:),2) + sigmaML;
	b = sum(WML(idxB,:).*WML(idxA,:),2);
 	a = sum(WML(idxA,:).*WML(idxA,:),2) + sigmaML;

	% manual inversion of a 2x2 matrix
	tmp = 1./(a.*d - b.*b);
	factorsPrecA{volRegion} = zeros(1,numColumnsShape*(numBounds-1)); factorsPrecA{volRegion}(idxB-numColumnsShape) = (tmp.*a)';
	factorsPredB{volRegion} = zeros(1,numColumnsShape*(numBounds-1)); factorsPrecB{volRegion}(idxB-numColumnsShape) = (-tmp.*b)';
end

factorsPrecAVec = [factorsPrecA{:}];
factorsPrecBVec = [factorsPrecB{:}];

% for the c-sum-product
if ~isempty(predictionGlobal)
	if isfield(predictionGlobal,'hashTable')
		hashTable = predictionGlobal.hashTable;
	else
		hashTable = sort(exp(-1000:0.001:0),'descend');
	end
else
	hashTable = sort(exp(-1000:0.001:0),'descend');
end


text:
package org.diorite.inject;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;

/**
 * Identifies a type that the injector only instantiates once. Not inherited.
 *
 * @see Scope @Scope
 */
@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {}


text:
<?php

declare(strict_types=1);

namespace Linna\Authorization;

use Linna\DataMapper\DomainObjectAbstract;

/**
 * Permission domain object.
 */
class Permission extends DomainObjectAbstract
{
    /** @var string Permission name. */
    public string $name;

    /** @var string Permission description. */
    public string $description;

    /** @var int Id of the group from which the permission was inherited. */
    public int $inherited = 0;

    /**
     * Class Constructor.
     */
    public function __construct()
    {
        \settype($this->inherited, 'integer');
    }
}


text:
package org.la4j.factory;

import org.la4j.matrix.Matrices;
import org.la4j.matrix.Matrix;
import org.la4j.matrix.source.MatrixSource;
import org.la4j.matrix.sparse.CCSMatrix;
import org.la4j.matrix.sparse.CRSMatrix;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class CCSFactory extends CompressedFactory {

    private static final long serialVersionUID = 4071505L;

    @Override
    public Matrix createMatrix() {
        return new CCSMatrix();
    }

    @Override
    public Matrix createMatrix(int rows, int columns) {
        return new CCSMatrix(rows, columns);
    }

    @Override
    public Matrix createMatrix(int rows, int columns, double array[]) {
        return new CCSMatrix(rows, columns, array);
    }

    @Override
    public Matrix createMatrix(double[][] array) {
        return new CCSMatrix(array);
    }

    @Override
    public Matrix createMatrix(Matrix matrix) {
        return new CCSMatrix(matrix);
    }

    @Override
    public Matrix createMatrix(MatrixSource source) {
        return new CCSMatrix(source);
    }

    @Override
    public Matrix createConstantMatrix(int rows, int columns, double value) {

        int size = rows * columns;

        double values[] = new double[size];
        int rowIndices[] = new int[size];
        int columnPointers[] = new int[columns + 1];

        for (int j = 0; j < columns; j++) {
            for (int i = 0; i < rows; i++) {
                values[j * rows + i] = value;
                rowIndices[j * rows + i] = i;
            }
            columnPointers[j] = rows * j;
        }

        columnPointers[columns] = size;

        return new CCSMatrix(rows, columns, size, values, rowIndices,
                             columnPointers);
    }

    @Override
    public Matrix createRandomMatrix(int rows, int columns, Random random) {

        int cardinality = Math.max((rows * columns) / DENSITY, columns);

        double values[] = new double[cardinality];
        int rowIndices[] = new int[cardinality];
        int columnPointers[] = new int[columns + 1];

        int kk = cardinality / columns;
        int indices[] = new int[kk];

        int k = 0;
        for (int j = 0; j < columns; j++) {

            columnPointers[j] = k;

            for (int jj = 0; jj < kk; jj++) {
                indices[jj] = random.nextInt(rows);
            }

            Arrays.sort(indices);

            int previous = -1;
            for (int jj = 0; jj < kk; jj++) {

                if (indices[jj] == previous) {
                    continue;
                }

                values[k] = random.nextDouble();
                rowIndices[k++] = indices[jj];
                previous = indices[jj];
            }
        }

        columnPointers[columns] = cardinality;

        return new CCSMatrix(rows, columns, cardinality, values,
                             rowIndices, columnPointers);
    }

    @Override
    public Matrix createRandomSymmetricMatrix(int size, Random random) {

        // TODO: Issue 15

        int cardinality = (size * size) / DENSITY;

        Matrix matrix = new CCSMatrix(size, size, cardinality);

        for (int k = 0; k < cardinality / 2; k++) {
            int i = random.nextInt(size);
            int j = random.nextInt(size);
            double value = random.nextDouble();

            matrix.set(i, j, value);
            matrix.set(j, i, value);
        }

        return matrix;
    }

    @Override
    public Matrix createSquareMatrix(int size) {
        return new CCSMatrix(size, size);
    }

    @Override
    public Matrix createIdentityMatrix(int size) {

        double diagonal[] = new double[size];
        Arrays.fill(diagonal, 1.0);

        return createDiagonalMatrix(diagonal);
    }

    @Override
    public Matrix createBlockMatrix(Matrix a, Matrix b, Matrix c, Matrix d) {
        if ((a.rows() != b.rows()) || (a.columns() != c.columns()) ||
            (c.rows() != d.rows()) || (b.columns() != d.columns())) {
            throw new IllegalArgumentException("Sides of blocks are incompatible!");
        }

        int rows = a.rows() + c.rows(), cols = a.columns() + b.columns();
        ArrayList <Double> values = new ArrayList <Double> ();
        ArrayList <Integer> rowIndices = new ArrayList <Integer> ();
        int columnPointers[] = new int[rows + 1];

        int k = 0;
        columnPointers[0] = 0;
        double current = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if ((i < a.rows()) && (j < a.columns())) {
                    current = a.get(i, j);
                }
                if ((i < a.rows()) && (j > a.columns())) {
                    current = b.get(i, j);
                }
                if ((i > a.rows()) && (j < a.columns())) {
                    current = c.get(i, j);
                }
                if ((i > a.rows()) && (j > a.columns())) {
                    current = d.get(i, j);
                }
                if (Math.abs(current) > Matrices.EPS) {
                    values.add(current);
                    rowIndices.add(j);
                    k++;
                }
            }
            columnPointers[i + 1] = k;
        }
        double valuesArray[] = new double[values.size()];
        int rowIndArray[] = new int[rowIndices.size()];
        for (int i = 0; i < values.size(); i++) {
            valuesArray[i] = values.get(i);
            rowIndArray[i] = rowIndices.get(i);
        }

        return new CRSMatrix(rows, cols, k, valuesArray, rowIndArray, columnPointers);
    }

    @Override
    public Matrix createDiagonalMatrix(double[] diagonal) {

        int size = diagonal.length;
        int rowIndices[] = new int[size];
        int columnPointers[] = new int[size + 1];

        for (int i = 0; i < size; i++) {
            rowIndices[i] = i;
            columnPointers[i] = i;
        }
        columnPointers[size] = size;

        return new CCSMatrix(size, size, size, diagonal, rowIndices, columnPointers);
    }
}


text:
import { types as tt } from "./types";
import { lineBreak } from "../util/whitespace";

export class TokContext {
  constructor(
    token: string,
    isExpr?: boolean,
    preserveSpace?: boolean,
    override?: ?Function, // Takes a Tokenizer as a this-parameter, and returns void.
  ) {
    this.token = token;
    this.isExpr = !!isExpr;
    this.preserveSpace = !!preserveSpace;
    this.override = override;
  }

  token: string;
  isExpr: boolean;
  preserveSpace: boolean;
  override: ?Function;
}

export const types: {
  [key: string]: TokContext,
} = {
  braceStatement: new TokContext("{", false),
  braceExpression: new TokContext("{", true),
  templateQuasi: new TokContext("${", false),
  parenStatement: new TokContext("(", false),
  parenExpression: new TokContext("(", true),
  template: new TokContext("`", true, true, p => p.readTmplToken()),
  functionExpression: new TokContext("function", true),
  functionStatement: new TokContext("function", false),
};

// Token-specific context update code

tt.parenR.updateContext = tt.braceR.updateContext = function() {
  if (this.state.context.length === 1) {
    this.state.exprAllowed = true;
    return;
  }

  let out = this.state.context.pop();
  if (out === types.braceStatement && this.curContext().token === "function") {
    out = this.state.context.pop();
  }

  this.state.exprAllowed = !out.isExpr;
};

tt.name.updateContext = function(prevType) {
  let allowed = false;
  if (prevType !== tt.dot) {
    if (
      (this.state.value === "of" && !this.state.exprAllowed) ||
      (this.state.value === "yield" && this.scope.inGenerator)
    ) {
      allowed = true;
    }
  }
  this.state.exprAllowed = allowed;

  if (this.state.isIterator) {
    this.state.isIterator = false;
  }
};

tt.braceL.updateContext = function(prevType) {
  this.state.context.push(
    this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression,
  );
  this.state.exprAllowed = true;
};

tt.dollarBraceL.updateContext = function() {
  this.state.context.push(types.templateQuasi);
  this.state.exprAllowed = true;
};

tt.parenL.updateContext = function(prevType) {
  const statementParens =
    prevType === tt._if ||
    prevType === tt._for ||
    prevType === tt._with ||
    prevType === tt._while;
  this.state.context.push(
    statementParens ? types.parenStatement : types.parenExpression,
  );
  this.state.exprAllowed = true;
};

tt.incDec.updateContext = function() {
  // tokExprAllowed stays unchanged
};

tt._function.updateContext = tt._class.updateContext = function(prevType) {
  if (
    prevType.beforeExpr &&
    prevType !== tt.semi &&
    prevType !== tt._else &&
    !(
      prevType === tt._return &&
      lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))
    ) &&
    !(
      (prevType === tt.colon || prevType === tt.braceL) &&
      this.curContext() === types.b_stat
    )
  ) {
    this.state.context.push(types.functionExpression);
  } else {
    this.state.context.push(types.functionStatement);
  }

  this.state.exprAllowed = false;
};

tt.backQuote.updateContext = function() {
  if (this.curContext() === types.template) {
    this.state.context.pop();
  } else {
    this.state.context.push(types.template);
  }
  this.state.exprAllowed = false;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="cn.youngkaaa.yviewpagerdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IssueActivity">

        </activity>
        <activity android:name=".VerticalActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity android:name=".BannerActivity">

        </activity>

        <activity android:name=".MainActivity">

        </activity>
    </application>

</manifest>


text:
'use strict';

APP.controller('AppCtrl', ['$scope', '$rootScope', '$route', '$routeParams', '$location', '$http', '$timeout', '$q', 'GlobalService', 'AuthService',
					function ($scope, $rootScope, $route, $routeParams, $location, $http, $timeout, $q, GlobalService, AuthService) {

	//common public methods
	var currentController = null,
		lastUpdateRouteReload = 0,
		viewCallbackMap = {},
		errors = {},
		self = this;

	self.views = {};

	$scope._ = function (index) {
		return GlobalService.i18n($routeParams.nav, index);
	};

	$scope._e = function (index) {
		var message = "";
		if (errors[index]) {
			var splited = errors[index].split("|");
			var message = $scope._(splited[0] + (splited.length - 1 ? splited.length - 1 : ""));
			for (var i = 1; i < splited.length; i ++) {
				message = message.replace("{{" + i + "}}", splited[i]);
			}
		}
		return message;
	};

	$scope._l = function (link) {
		return history.pushState ? link : '#/' + link;
	};

	$scope.setErrors = function (newErrors) {
		errors = {};
		for (var i = 0; i < newErrors.length; i ++) {
			var error = newErrors[i];
			errors[error.path.split("arg")[1].substr(2)] = error.message;
		}
		//scroll to errors
		setTimeout(function () {
			var position = jQuery('label.error:visible').first().offset();
			if (position && position.top)
				jQuery("html, body").animate( {scrollTop: position.top - 50}, 800);
		}, 100);
	};

	$scope.getConfig = function (key) {
		return GlobalService.getConfig(key);
	}

	$scope.setConfig = function (key, value, storeInCookie) {
		return GlobalService.setConfig(key, value, storeInCookie);
	}

	$scope.updateRoute = function(name, value, replace) {
		//console.log("APP updateRoute", name, value);
		errors = {};
		//transform param to object
		var newParams = {};
		if (typeof name === 'object') {
			newParams = name;
		} else {
			newParams[name] = value;
		}
		var pathChangingParams = ['url', 'nav', 'view', 'id'];
		var urlNotChanged = true;
		//update search params
		for (var key in newParams) {
			if (pathChangingParams.indexOf(key) == -1 && $location.search()[key] != newParams[key]) {
				urlNotChanged = false;
				if (replace) {
					$location.search(key, newParams[key]).replace();
				} else {
					$location.search(key, newParams[key]);
				}
				$routeParams[key] = newParams[key];
			}
		}
		//update path if needed
		var newBuildPath = newParams.url || "/" + getRouteParam('nav', newParams) + "/"
			+ getRouteParam('view', newParams) + "/" + getRouteParam('id', newParams);
		if (newBuildPath.replace(/\//g, '') !== $location.path().replace(/\//g, '')) {
			urlNotChanged = false;
			if (replace) {
				$location.path(newBuildPath).replace();
			} else {
				$location.path(newBuildPath);
			}
		}
		if (urlNotChanged && lastUpdateRouteReload + 1000 < Date.now()) {
			lastUpdateRouteReload = Date.now();
			$route.reload();
		}
	};

	var getRouteParam = function (key, newParams) {
		if (typeof newParams[key] !== 'undefined') {
			return newParams[key];
		} else if ($routeParams[key]) {
			return $routeParams[key];
		} else {
			return '';
		}
	};

	$scope.showAjaxMessage = function(message, type) {
		$scope.ajax.message = null;
		$timeout(function () {
			$scope.ajax.message = $scope._(message);
			$scope.ajax.type = type || "info";
		}, 200);
	};

	$scope.setViewAnimation = function(ctrlFrom, ctrlTo, viewFrom, viewTo) {
		if (ctrlFrom === ctrlTo && (! viewFrom || viewFrom == viewTo)) {
			return;
		}
		if (ctrlFrom === ctrlTo && typeof animationClassMap[ctrlFrom] == 'object') {
			$scope.animationClass = typeof animationClassMap[ctrlFrom][viewFrom + '->' + viewTo] !== 'undefined'
				? animationClassMap[ctrlFrom][viewFrom + '->' + viewTo] : animationClassMap.default;
		} else {
			$scope.animationClass = typeof animationClassMap[ctrlFrom + '->' + ctrlTo] !== 'undefined'
				? animationClassMap[ctrlFrom + '->' + ctrlTo] : animationClassMap.default;
		}
	};

	$scope.overlayShow = function (overlayName) {
		$scope.isOverlayShowed = {};
		$scope.isOverlayShowed[overlayName] = jQuery(window).scrollTop() + 1;
		return true;
	};

	$scope.overlayHide = function () {
		$scope.isOverlayShowed = null;
	};

	$scope.registerView = function (controller, viewName, callback) {
		if (controller != currentController) {
			currentController = controller;
			viewCallbackMap = {};
		}
		viewCallbackMap[viewName ? viewName : '/'] = callback;
		if (viewName == $routeParams.view) {
			processViewChange();
		}
	};

	$scope.reload = function () {
		$route.reload();
	};

	var processViewChange = function () {
		var view = $routeParams.view ? $routeParams.view : '/';
		if (typeof viewCallbackMap[view] == 'function') { //is registered
			viewCallbackMap[view].call(currentController);
		}
	};

	var getCurrentMenu = function () {
		for (var i = 0; i < $scope.menu.length; i ++) {
			if ($routeParams.nav === $scope.menu[i].name) {
				return $scope.menu[i];
			}
		}
	};

	var setViews = function (views, viewsWithId) {
		if (views && self.views != views) {
			self.views = views;
			for (var key in $scope.views) { //release views
				setView(key, null);
			}
			$scope.views[$routeParams.nav] = [];
			setView($routeParams.nav, views || []);
			$scope.views['id' + $routeParams.nav] = [];
			setView('id' + $routeParams.nav, viewsWithId || []);
		}
	};

	var setView = function (key, views) {
		var release = views == null;
		if (release) {
			views = $scope.views[key];
		}
		for (var i = 0; i < views.length; i ++) {
			(function (i) {
				$timeout(function () {
					if (release) {
						views.splice(views.length - 1, 1);
					} else {
						$scope.views[key].push(views[i]);
					}
				}, 260 / views.length * i)
			} (i));
		}
	}

	$scope.setCookie = function (key, value) {
		return GlobalService.setCookie(key, value);
	};

	$scope.getCookie = function (key) {
		return GlobalService.getCookie(key);
	};

	$scope.getTitle = function () {
		return  $scope._($routeParams.nav) + " | " + $scope.getConfig('titlePostfix');
	};

	var routeUpdate = function () {

		// console.log("APP routeUpdate");
		// abort/cancel all connections when route is updated
		if ($rootScope.httpRequestTimeout) {
			$rootScope.httpRequestTimeout.resolve();
		}
		$rootScope.httpRequestTimeout = $q.defer();
		$scope.show.settings = false;
		$scope.ajax.message = "";
		//check if is route empty
		var path = $location.path();
		if (path === '/' && path !== '/' + $scope.getConfig('initCtrl')) {
			$location.path($scope.getConfig('initCtrl'));
		} else {
			var menu = getCurrentMenu();
			setViews(menu.sub || [], menu.subWithIds || []);
		}

	};

	$scope.$on('$routeChangeSuccess', function() {
		routeUpdate();
	});

	$scope.$on('$routeUpdate', function() {
		processViewChange();
	});

	//listners
	$scope.$on('responseError', function (e, rejection) {
		responseErrors.push(rejection);
		responseErrorLastTime = new Date().getTime();
		$timeout(function () {
			var messageStart = responseErrors.length + " resources has failed to load ("+ responseErrors[0].status
				+ " " + responseErrors[0].statusText + "). ";
			if (responseErrors.length > 2) {
				$scope.showAjaxMessage(messageStart + "There is probably an issue with server.", 'danger');
			} else {
				$scope.showAjaxMessage(messageStart + "Reload your page and try again, or continue when everything is OK.", 'warning');
			}
		}, 500);
		$timeout(function () {
			if (new Date().getTime() - responseErrorLastTime > 1990) {
				responseErrors = [];
			}
		}, 2000);
	});

	$scope.$on('xhrLoading', function(e, value) {
		$scope.loadings.global += value;
		if ($scope.loadings.global === 0) {
			document.getElementById("svg-small-circle-animation").setAttribute('dur', '1.5s');
			$scope.loadingClass = 'small';
			$scope.init = false;
		}
		$timeout(function () { // make loading noticable if it takes longer than 1 second
			if ($scope.loadings.global > 0) {
				$scope.loadingClass = 'big';
			}
		}, 1000);
	});

	//construct
	$scope.isOverlayShowed = null;
	$scope.ajax = {
		message: "",
		type: "success|info|warning|danger"
	};
	$scope.show = {};
	// var routeUpdateHit

	var animationClassMap = GlobalService.getConfig('animations');;
	var responseErrors = [];
	var responseErrorLastTime = 0;
	$scope.init = true;
	$scope.loadingClass = '';
	$scope.animationClass = animationClassMap.default;
	$scope.layout = GlobalService.getConfig('layout');
	$scope.color = GlobalService.getConfig('color');
	$scope.routeParams = $routeParams;
	$scope.loadings = {
		global: 0,
		delay: true
	};
	$scope.views = {};
	$scope.menu = GlobalService.getConfig('menu');
	// var locale = location.pathname.split("/")[1];
	// var locale = locale.length === 2 ? locale : 'en';

	console.log("AppCtrl", $scope);
}]);


text:
Package.describe({
  summary: "Allows you to define and run db migrations.",
  version: "0.8.7",
  name: "clinical:migrations",
  git: "https://github.com/awatson1978/clinical-migrations.git"
});

Package.on_use(function (api) {
  api.versionsFrom('METEOR@0.9.1.1');
  api.use(['underscore', 'check', 'mongo'], 'server');
  api.add_files(['migrations_server.js'], "server");
  api.export('Migrations', 'server');
});

Package.on_test(function (api) {
  api.use(['clinical:migrations', 'tinytest']);
  api.add_files('migrations_tests.js', ['server']);
});


text:
//////////////////////////////////////////////////////////////////////////////
/// Copyright (C) 2014 Gefu Tang <tanggefu@gmail.com>. All Rights Reserved.
///
/// This file is part of LSHBOX.
///
/// LSHBOX is free software: you can redistribute it and/or modify it under
/// the terms of the GNU General Public License as published by the Free
/// Software Foundation, either version 3 of the License, or(at your option)
/// any later version.
///
/// LSHBOX is distributed in the hope that it will be useful, but WITHOUT
/// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
/// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
/// more details.
///
/// You should have received a copy of the GNU General Public License along
/// with LSHBOX. If not, see <http://www.gnu.org/licenses/>.
///
/// @version 0.1
/// @author Gefu Tang & Zhifeng Xiao
/// @date 2014.6.30
//////////////////////////////////////////////////////////////////////////////

/**
 * @file thlsh.h
 *
 * @brief Locality-Sensitive Hashing Scheme Based on Thresholding.
 */
#pragma once
#include <map>
#include <vector>
#include <random>
#include <iostream>
#include <functional>
namespace lshbox
{
/**
 * Locality-Sensitive Hashing Scheme Based on Thresholding.
 *
 *
 * For more information on thresholding based LSH, see the following reference.
 *
 *     Zhe Wang, Wei Dong, William Josephson, Qin Lv, Moses Charikar, Kai Li.
 *     Sizing Sketches: A Rank-Based Analysis for Similarity Search. In
 *     Proceedings of the 2007 ACM SIGMETRICS International Conference on
 *     Measurement and Modeling of Computer Systems . San Diego, CA, USA. June
 *     2007.
 *
 *     Qin Lv, Moses Charikar, Kai Li. Image Similarity Search with Compact
 *     Data Structures. In Proceedings of ACM 13th Conference on Information
 *     and Knowledge Management (CIKM), Washington D.C., USA. November 2004.
 */
template<typename DATATYPE = float>
class thLsh
{
public:
    struct Parameter
    {
        /// Hash table size
        unsigned M;
        /// Number of hash tables
        unsigned L;
        /// Dimension of the vector, it can be obtained from the instance of Matrix
        unsigned D;
        /// Binary code bytes
        unsigned N;
        /// Upper bound of each dimension
        float Max;
        /// Lower bound of each dimension
        float Min;
    };
    thLsh() {}
    thLsh(const Parameter &param_)
    {
        reset(param_);
    }
    ~thLsh() {}
    /**
     * Reset the parameter setting
     *
     * @param param_ A instance of thLsh<DATATYPE>::Parametor, which contains
     * the necessary parameters
     */
    void reset(const Parameter &param_);
    /**
     * Hash the dataset.
     *
     * @param data A instance of Matrix<DATATYPE>, it is the search dataset.
     */
    void hash(Matrix<DATATYPE> &data);
    /**
     * Insert a vector to the index.
     *
     * @param key   The sequence number of vector
     * @param domin The pointer to the vector
     */
    void insert(unsigned key, const DATATYPE *domin);
    /**
     * Query the approximate nearest neighborholds.
     *
     * @param domin   The pointer to the vector
     * @param scanner Top-K scanner, use for scan the approximate nearest neighborholds
     */
    template<typename SCANNER>
    void query(const DATATYPE *domin, SCANNER &scanner);
    /**
     * get the hash value of a vector.
     *
     * @param k     The idx of the table
     * @param domin The pointer to the vector
     * @return      The hash value
     */
    unsigned getHashVal(unsigned k, const DATATYPE *domin);
    /**
     * Load the index from binary file.
     *
     * @param file The path of binary file.
     */
    void load(const std::string &file);
    /**
     * Save the index as binary file.
     *
     * @param file The path of binary file.
     */
    void save(const std::string &file);
private:
    Parameter param;
    std::vector<float> threadholds;
    std::vector<std::vector<unsigned> > rndBits;
    std::vector<std::vector<unsigned> > rndArray;
    std::vector<std::map<unsigned, std::vector<unsigned> > > tables;
};
}

// ------------------------- implementation -------------------------
template<typename DATATYPE>
void lshbox::thLsh<DATATYPE>::reset(const Parameter &param_)
{
    param = param_;
    tables.resize(param.L);
    rndBits.resize(param.L);
    rndArray.resize(param.L);
    std::mt19937 rng(unsigned(std::time(0)));
    std::uniform_int_distribution<unsigned> usBits(0, param.D - 1);
    std::uniform_int_distribution<unsigned> usArray(0, param.M - 1);
    std::uniform_real_distribution<float> urThreadholds(param.Min, param.Max);
    for (unsigned i = 0; i != param.L; ++i)
    {
        while (rndBits[i].size() != param.N)
        {
            unsigned target = usBits(rng);
            if (std::find(rndBits[i].begin(), rndBits[i].end(), target) == rndBits[i].end())
            {
                rndBits[i].push_back(target);
            }
        }
        std::sort(rndBits[i].begin(), rndBits[i].end());
        threadholds.push_back(urThreadholds(rng));
    }
    for (std::vector<std::vector<unsigned> >::iterator iter = rndArray.begin(); iter != rndArray.end(); ++iter)
    {
        for (unsigned i = 0; i != param.N; ++i)
        {
            iter->push_back(usArray(rng));
        }
    }
}
template<typename DATATYPE>
void lshbox::thLsh<DATATYPE>::hash(Matrix<DATATYPE> &data)
{
    progress_display pd(data.getSize());
    for (unsigned i = 0; i != data.getSize(); ++i)
    {
        insert(i, data[i]);
        ++pd;
    }
}
template<typename DATATYPE>
void lshbox::thLsh<DATATYPE>::insert(unsigned key, const DATATYPE *domin)
{
    for (unsigned k = 0; k != param.L; ++k)
    {
        unsigned hashVal = getHashVal(k, domin);
        tables[k][hashVal].push_back(key);
    }
}
template<typename DATATYPE>
template<typename SCANNER>
void lshbox::thLsh<DATATYPE>::query(const DATATYPE *domin, SCANNER &scanner)
{
    scanner.reset(domin);
    for (unsigned k = 0; k != param.L; ++k)
    {
        unsigned hashVal = getHashVal(k, domin);
        if (tables[k].find(hashVal) != tables[k].end())
        {
            for (std::vector<unsigned>::iterator iter = tables[k][hashVal].begin(); iter != tables[k][hashVal].end(); ++iter)
            {
                scanner(*iter);
            }
        }
    }
    scanner.topk().genTopk();
}
template<typename DATATYPE>
unsigned lshbox::thLsh<DATATYPE>::getHashVal(unsigned k, const DATATYPE *domin)
{
    unsigned sum(0), seq(0);
    for (std::vector<unsigned>::iterator it = rndBits[k].begin(); it != rndBits[k].end(); ++it)
    {
        if (domin[*it] > threadholds[seq])
        {
            sum += rndArray[k][seq];
        }
        ++seq;
    }
    unsigned hashVal = sum % param.M;
    return hashVal;
}
template<typename DATATYPE>
void lshbox::thLsh<DATATYPE>::load(const std::string &file)
{
    std::ifstream in(file, std::ios::binary);
    in.read((char *)&param.M, sizeof(unsigned));
    in.read((char *)&param.L, sizeof(unsigned));
    in.read((char *)&param.D, sizeof(unsigned));
    in.read((char *)&param.N, sizeof(unsigned));
    in.read((char *)&param.Max, sizeof(float));
    in.read((char *)&param.Min, sizeof(float));
    tables.resize(param.L);
    rndBits.resize(param.L);
    rndArray.resize(param.L);
    threadholds.resize(param.L);
    in.read((char *)&threadholds[0], sizeof(float) * param.L);
    for (unsigned i = 0; i != param.L; ++i)
    {
        rndBits[i].resize(param.N);
        rndArray[i].resize(param.N);
        in.read((char *)&rndBits[i][0], sizeof(unsigned) * param.N);
        in.read((char *)&rndArray[i][0], sizeof(unsigned) * param.N);
        unsigned count;
        in.read((char *)&count, sizeof(unsigned));
        for (unsigned j = 0; j != count; ++j)
        {
            unsigned target;
            in.read((char *)&target, sizeof(unsigned));
            unsigned length;
            in.read((char *)&length, sizeof(unsigned));
            tables[i][target].resize(length);
            in.read((char *) & (tables[i][target][0]), sizeof(unsigned) * length);
        }
    }
    in.close();
}
template<typename DATATYPE>
void lshbox::thLsh<DATATYPE>::save(const std::string &file)
{
    std::ofstream out(file, std::ios::binary);
    out.write((char *)&param.M, sizeof(unsigned));
    out.write((char *)&param.L, sizeof(unsigned));
    out.write((char *)&param.D, sizeof(unsigned));
    out.write((char *)&param.N, sizeof(unsigned));
    out.write((char *)&param.Max, sizeof(float));
    out.write((char *)&param.Min, sizeof(float));
    out.write((char *)&threadholds[0], sizeof(float) * param.L);
    for (int i = 0; i != param.L; ++i)
    {
        out.write((char *)&rndBits[i][0], sizeof(unsigned) * param.N);
        out.write((char *)&rndArray[i][0], sizeof(unsigned) * param.N);
        unsigned count = unsigned(tables[i].size());
        out.write((char *)&count, sizeof(unsigned));
        for (std::map<unsigned, std::vector<unsigned> >::iterator iter = tables[i].begin(); iter != tables[i].end(); ++iter)
        {
            unsigned target = iter->first;
            out.write((char *)&target, sizeof(unsigned));
            unsigned length = unsigned(iter->second.size());
            out.write((char *)&length, sizeof(unsigned));
            out.write((char *) & ((iter->second)[0]), sizeof(unsigned) * length);
        }
    }
    out.close();
}


text:
namespace content {
  class NavigationController;
}

namespace autofill {
  class AutofillDialogViewDelegate;
}

@class AutofillAccountChooser;
@class AutofillDialogWindowController;
@class AutofillMainContainer;
@class AutofillOverlayController;
@class AutofillSignInContainer;

namespace autofill {

class AutofillDialogCocoa : public AutofillDialogView,
                            public TestableAutofillDialogView,
                            public ConstrainedWindowMacDelegate {
 public:
  explicit AutofillDialogCocoa(AutofillDialogViewDelegate* delegate);
  virtual ~AutofillDialogCocoa();

  // AutofillDialogView implementation:
  virtual void Show() OVERRIDE;
  virtual void Hide() OVERRIDE;
  virtual void UpdatesStarted() OVERRIDE;
  virtual void UpdatesFinished() OVERRIDE;
  virtual void UpdateAccountChooser() OVERRIDE;
  virtual void UpdateButtonStrip() OVERRIDE;
  virtual void UpdateOverlay() OVERRIDE;
  virtual void UpdateDetailArea() OVERRIDE;
  virtual void UpdateForErrors() OVERRIDE;
  virtual void UpdateNotificationArea() OVERRIDE;
  virtual void UpdateSection(DialogSection section) OVERRIDE;
  virtual void UpdateErrorBubble() OVERRIDE;
  virtual void FillSection(DialogSection section,
                           const DetailInput& originating_input) OVERRIDE;
  virtual void GetUserInput(DialogSection section,
                            DetailOutputMap* output) OVERRIDE;
  virtual string16 GetCvc() OVERRIDE;
  virtual bool HitTestInput(const DetailInput& input,
                            const gfx::Point& screen_point) OVERRIDE;
  virtual bool SaveDetailsLocally() OVERRIDE;
  virtual const content::NavigationController* ShowSignIn() OVERRIDE;
  virtual void HideSignIn() OVERRIDE;
  virtual void ModelChanged() OVERRIDE;
  virtual TestableAutofillDialogView* GetTestableView() OVERRIDE;
  virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE;

  // TestableAutofillDialogView implementation:
  // TODO(groby): Create a separate class to implement the testable interface:
  // http://crbug.com/256864
  virtual void SubmitForTesting() OVERRIDE;
  virtual void CancelForTesting() OVERRIDE;
  virtual string16 GetTextContentsOfInput(const DetailInput& input) OVERRIDE;
  virtual void SetTextContentsOfInput(const DetailInput& input,
                                      const string16& contents) OVERRIDE;
  virtual void SetTextContentsOfSuggestionInput(
      DialogSection section,
      const base::string16& text) OVERRIDE;
  virtual void ActivateInput(const DetailInput& input) OVERRIDE;
  virtual gfx::Size GetSize() const OVERRIDE;
  virtual content::WebContents* GetSignInWebContents() OVERRIDE;
  virtual bool IsShowingOverlay() const OVERRIDE;

  // ConstrainedWindowMacDelegate implementation:
  virtual void OnConstrainedWindowClosed(
      ConstrainedWindowMac* window) OVERRIDE;

  AutofillDialogViewDelegate* delegate() { return delegate_; }

  // Posts a close request on the current message loop.
  void PerformClose();

 private:
  // Closes the sheet and ends the modal loop. Triggers cleanup sequence.
  void CloseNow();

  scoped_ptr<ConstrainedWindowMac> constrained_window_;
  base::scoped_nsobject<AutofillDialogWindowController> sheet_delegate_;

  // WeakPtrFactory for deferred close.
  base::WeakPtrFactory<AutofillDialogCocoa> close_weak_ptr_factory_;

  // The delegate |this| queries for logic and state.
  AutofillDialogViewDelegate* delegate_;
};

}  // autofill

@interface AutofillDialogWindowController :
    NSWindowController<NSWindowDelegate, AutofillLayout> {
 @private
  content::WebContents* webContents_;  // weak.
  autofill::AutofillDialogCocoa* autofillDialog_;  // weak.

  base::scoped_nsobject<AutofillMainContainer> mainContainer_;
  base::scoped_nsobject<AutofillSignInContainer> signInContainer_;
  base::scoped_nsobject<AutofillAccountChooser> accountChooser_;
  base::scoped_nsobject<AutofillOverlayController> overlayController_;
  base::scoped_nsobject<NSTextField> loadingShieldTextField_;
  base::scoped_nsobject<NSTextField> titleTextField_;
  base::scoped_nsobject<NSTextView> fieldEditor_;
}

// Designated initializer. The WebContents cannot be NULL.
- (id)initWithWebContents:(content::WebContents*)webContents
           autofillDialog:(autofill::AutofillDialogCocoa*)autofillDialog;

// A child view request re-layouting.
- (void)requestRelayout;

// Cancels all previous requests to re-layout.
- (void)cancelRelayout;

// Validate data. If it is valid, notify the delegate that the user would
// like to use the data.
- (IBAction)accept:(id)sender;

// User cancels dialog.
- (IBAction)cancel:(id)sender;

// Forwarding AutofillDialogView calls.
- (void)show;
- (void)hide;
- (void)updateNotificationArea;
- (void)updateAccountChooser;
- (void)updateButtonStrip;
- (void)updateSection:(autofill::DialogSection)section;
- (void)fillSection:(autofill::DialogSection)section
           forInput:(const autofill::DetailInput&)input;
- (void)getInputs:(autofill::DetailOutputMap*)outputs
       forSection:(autofill::DialogSection)section;
- (NSString*)getCvc;
- (BOOL)saveDetailsLocally;
- (content::NavigationController*)showSignIn;
- (void)hideSignIn;
- (void)modelChanged;
- (void)updateErrorBubble;
- (void)onSignInResize:(NSSize)size;

@end

// Mirrors the TestableAutofillDialogView API on the C++ side.
@interface AutofillDialogWindowController (TestableAutofillDialogView)

- (void)setTextContents:(NSString*)text
               forInput:(const autofill::DetailInput&)input;
- (void)setTextContents:(NSString*)text
 ofSuggestionForSection:(autofill::DialogSection)section;
- (void)activateFieldForInput:(const autofill::DetailInput&)input;
- (content::WebContents*)getSignInWebContents;
- (BOOL)IsShowingOverlay;

@end

#endif  // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_DIALOG_COCOA_H_


text:
"use strict";

const BaseTask = require( "./_task" );

const log    = require( "fm-log" ).module();
const utils  = require( "./utils" );

class UpdateTask extends BaseTask {
	// eslint-disable-next-line no-useless-constructor
	constructor( repository, options ) {
		super( repository, options );
	}

	process() {
		return this.checkWorkingDirectory();
	}

	checkWorkingDirectory() {
		return utils.isClean( this.repository )
			.then( repository => {

				if( !repository.isClean ) {
					log.error( `Working directory of '${repository.name}' isn't clean` );
				}

				return repository;
			} );
	}
}

function taskFactory( repository, options ) {
	const task = new UpdateTask( repository, options );
	return task.process();
}

module.exports = taskFactory;


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace WpfControlsLib.Controls.Palette
{
    /// <summary>
    /// Palette with elements of a visual language.
    /// </summary>
    public partial class Palette : UserControl
    {
        private bool isInDrag;
        private readonly PaletteViewModel paletteViewModel;
        private Point dragOriginPoint;

        /// <summary>
        /// Creates a new instance of the <see cref="Palette"/> class.
        /// </summary>
        public Palette()
        {
            this.InitializeComponent();
            this.paletteViewModel = new PaletteViewModel();
            this.DataContext = this.paletteViewModel;
        }

        /// <summary>
        /// Gets currently selected element, or null if there is none.
        /// </summary>
        public Repo.IElement SelectedElement => this.paletteViewModel.SelectedElement;

        /// <summary>
        /// Sets a model from which palette will be populated.
        /// </summary>
        /// <param name="model">A model with repository from which palette will take elements.</param>
        public void SetModel(WpfControlsLib.Model.Model model)
            => this.paletteViewModel.SetModel(model);

        /// <summary>
        /// Initializes palette with metamodel with given name. Note that a model shall be set before calling this.
        /// </summary>
        /// <param name="metamodelName">Name of the metamodel from which we shall populate the palette.</param>
        public void InitPalette(string metamodelName)
            => this.paletteViewModel.InitPalette(metamodelName);

        /// <summary>
        /// Clears selected element on a palette.
        /// </summary>
        public void ClearSelection()
            => this.paletteViewModel.SelectedElement = null;

        private void OnElementChecked(object sender, RoutedEventArgs e)
        {
            var selectedElement = ((sender as ToggleButton)?.DataContext as PaletteElement)?.Element;
            this.paletteViewModel.SelectedElement = selectedElement;
        }

        private void OnElementUnchecked(object sender, RoutedEventArgs e)
        {
            this.paletteViewModel.SelectedElement = null;
        }

        private void OnElementMouseMove(object sender, MouseEventArgs e)
        {
            bool IsMovedEnough()
            {
                if (this.dragOriginPoint == new Point())
                {
                    return false;
                }

                var currentMousePos = e.GetPosition(sender as ToggleButton);
                var xDistance = this.dragOriginPoint.X - currentMousePos.X;
                var yDistance = this.dragOriginPoint.Y - currentMousePos.Y;
                return xDistance * xDistance + yDistance * yDistance > 100;
            }

            if (this.isInDrag)
            {
                return;
            }

            if (!(sender is ToggleButton button) || e.LeftButton != MouseButtonState.Pressed)
            {
                return;
            }

            if (!IsMovedEnough())
            {
                return;
            }

            var paletteElement = button.DataContext as PaletteElement;

            var draggedElement = paletteElement?.Element;
            if (draggedElement == null)
            {
                return;
            }

            paletteElement.IsDragged = true;

            // Flagging that we are inside drag-and-drop operation. Despite this operation is blocking, it has its own
            // event loop inside, so we can get more events from a button.
            this.isInDrag = true;

            // Initiating blocking drag-and-drop operation.
            DragAndDropHelper.DoDragAndDrop(button, draggedElement, "REAL.NET palette element", paletteElement.Image);

            this.isInDrag = false;

            paletteElement.IsDragged = false;
        }

        private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            this.dragOriginPoint = e.GetPosition(sender as ToggleButton);
        }

        private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            this.dragOriginPoint = new Point();
        }
    }
}


text:
layout: tag
section-type: tag
title: google_calendar
---
## Tag


text:
package volmanfakes

import (
	sync "sync"

	dockerdriver "code.cloudfoundry.org/dockerdriver"
	lager "code.cloudfoundry.org/lager"
	voldiscoverers "code.cloudfoundry.org/volman/voldiscoverers"
)

type FakeDockerDriverFactory struct {
	DockerDriverStub        func(lager.Logger, string, string, string) (dockerdriver.Driver, error)
	dockerDriverMutex       sync.RWMutex
	dockerDriverArgsForCall []struct {
		arg1 lager.Logger
		arg2 string
		arg3 string
		arg4 string
	}
	dockerDriverReturns struct {
		result1 dockerdriver.Driver
		result2 error
	}
	dockerDriverReturnsOnCall map[int]struct {
		result1 dockerdriver.Driver
		result2 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeDockerDriverFactory) DockerDriver(arg1 lager.Logger, arg2 string, arg3 string, arg4 string) (dockerdriver.Driver, error) {
	fake.dockerDriverMutex.Lock()
	ret, specificReturn := fake.dockerDriverReturnsOnCall[len(fake.dockerDriverArgsForCall)]
	fake.dockerDriverArgsForCall = append(fake.dockerDriverArgsForCall, struct {
		arg1 lager.Logger
		arg2 string
		arg3 string
		arg4 string
	}{arg1, arg2, arg3, arg4})
	fake.recordInvocation("DockerDriver", []interface{}{arg1, arg2, arg3, arg4})
	fake.dockerDriverMutex.Unlock()
	if fake.DockerDriverStub != nil {
		return fake.DockerDriverStub(arg1, arg2, arg3, arg4)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.dockerDriverReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeDockerDriverFactory) DockerDriverCallCount() int {
	fake.dockerDriverMutex.RLock()
	defer fake.dockerDriverMutex.RUnlock()
	return len(fake.dockerDriverArgsForCall)
}

func (fake *FakeDockerDriverFactory) DockerDriverCalls(stub func(lager.Logger, string, string, string) (dockerdriver.Driver, error)) {
	fake.dockerDriverMutex.Lock()
	defer fake.dockerDriverMutex.Unlock()
	fake.DockerDriverStub = stub
}

func (fake *FakeDockerDriverFactory) DockerDriverArgsForCall(i int) (lager.Logger, string, string, string) {
	fake.dockerDriverMutex.RLock()
	defer fake.dockerDriverMutex.RUnlock()
	argsForCall := fake.dockerDriverArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}

func (fake *FakeDockerDriverFactory) DockerDriverReturns(result1 dockerdriver.Driver, result2 error) {
	fake.dockerDriverMutex.Lock()
	defer fake.dockerDriverMutex.Unlock()
	fake.DockerDriverStub = nil
	fake.dockerDriverReturns = struct {
		result1 dockerdriver.Driver
		result2 error
	}{result1, result2}
}

func (fake *FakeDockerDriverFactory) DockerDriverReturnsOnCall(i int, result1 dockerdriver.Driver, result2 error) {
	fake.dockerDriverMutex.Lock()
	defer fake.dockerDriverMutex.Unlock()
	fake.DockerDriverStub = nil
	if fake.dockerDriverReturnsOnCall == nil {
		fake.dockerDriverReturnsOnCall = make(map[int]struct {
			result1 dockerdriver.Driver
			result2 error
		})
	}
	fake.dockerDriverReturnsOnCall[i] = struct {
		result1 dockerdriver.Driver
		result2 error
	}{result1, result2}
}

func (fake *FakeDockerDriverFactory) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.dockerDriverMutex.RLock()
	defer fake.dockerDriverMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeDockerDriverFactory) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ voldiscoverers.DockerDriverFactory = new(FakeDockerDriverFactory)


text:
<?php

// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
	die("Direct initialization of this file is not allowed.

Please make sure IN_MYBB is defined.");
}

class Horde_Text_Diff_Mapped extends Horde_Text_Diff
{
    /**
     * Computes a diff between sequences of strings.
     *
     * This can be used to compute things like case-insensitve diffs, or diffs
     * which ignore changes in white-space.
     *
     * @param array $from_lines         An array of strings.
     * @param array $to_lines           An array of strings.
     * @param array $mapped_from_lines  This array should have the same size
     *                                  number of elements as $from_lines.  The
     *                                  elements in $mapped_from_lines and
     *                                  $mapped_to_lines are what is actually
     *                                  compared when computing the diff.
     * @param array $mapped_to_lines    This array should have the same number
     *                                  of elements as $to_lines.
     */
    public function __construct($from_lines, $to_lines,
                                $mapped_from_lines, $mapped_to_lines)
    {
        assert(count($from_lines) == count($mapped_from_lines));
        assert(count($to_lines) == count($mapped_to_lines));

        parent::__construct($mapped_from_lines, $mapped_to_lines);

        $xi = $yi = 0;
        for ($i = 0; $i < count($this->_edits); $i++) {
            $orig = &$this->_edits[$i]->orig;
            if (is_array($orig)) {
                $orig = array_slice($from_lines, $xi, count($orig));
                $xi += count($orig);
            }

            $final = &$this->_edits[$i]->final;
            if (is_array($final)) {
                $final = array_slice($to_lines, $yi, count($final));
                $yi += count($final);
            }
        }
    }
}


text:
function imshow4D(img)
    imshow3D(make_4d_maxinten(img));

end


text:
package com.sap.cloud.lm.sl.cf.core.model;

import java.util.List;

import javax.ws.rs.QueryParam;

public class OperationsBean {

    @QueryParam("last")
    private Integer lastRequestedOperationsCount;

    @QueryParam("status")
    private List<String> statusList;

    public OperationsBean() {
    }

    public OperationsBean(Integer last, List<String> statusList) {
        this.lastRequestedOperationsCount = last;
        this.statusList = statusList;
    }

    public Integer getLastRequestedOperationsCount() {
        return lastRequestedOperationsCount;
    }

    public void setLastRequestedOperations(int last) {
        this.lastRequestedOperationsCount = last;
    }

    public List<String> getStatusList() {
        return statusList;
    }

    public void setStatusList(List<String> statusList) {
        this.statusList = statusList;
    }

}


text:
package cuchaz.enigma.inputs.inheritanceTree;

// none/c extends none/a
public class SubclassB extends BaseClass {

	// a
	private int m_numThings;

	// <init>()V
	protected SubclassB() {
		// none/a.<init>(Ljava/lang/String;)V
		super("B");

		// access to a
		m_numThings = 4;
	}

	@Override
	// a()V
	public void doBaseThings() {
		// call to none/a.a()Ljava/lang/String;
		System.out.println("Base things by B! " + getName());
	}

	// b()V
	public void doBThings() {
		// access to a
		System.out.println("" + m_numThings + " B things!");
	}
}