text:
angular.module("engbooster")
  .controller("SubjectsIndexController", ["$scope", "Subjects", "Auth", function($scope, Subjects, Auth) {
    Subjects.all()
      .then(function(res) {
        $scope.subjects = res.data;
      });

    $scope.treeOptions = {
      dropped: function(event) {
        var subject = event.source.nodeScope.$modelValue;
        var srcParentId = event.source.nodesScope.$parent.$modelValue._id;
        var destParentId = event.dest.nodesScope.$parent.$modelValue._id;
        if (srcParentId != destParentId) {
          subject.parent = destParentId;
          Subjects.update(subject);
        }
      }
    };

    $scope.removeSubject = function(scope) {
      Subjects.delete(scope.$modelValue)
        .then(function() {
          scope.remove();
        });
    };

    $scope.toggle = function(scope) {
      scope.toggle();
    };

    $scope.newSubItem = function(scope) {
      var nodeData = scope.$modelValue;
      nodeData.children = nodeData.children || [];
      var newSubject = {
        id: nodeData.id * 10 + nodeData.children.length,
        title: nodeData.title + '.' + (nodeData.children.length + 1),
        parent: nodeData._id,
        children: []
      };
      Subjects.create(newSubject)
        .then(function(res) {
          nodeData.children.push(res.data);
        });
    };

    $scope.editSubject = function(scope) {
      Subjects.update(scope.$modelValue);
    }

    $scope.checkUser = function() {
      var token = Auth.getToken();
      var username = Auth.parseJwt(token)
        ._doc.username;
      return username === "s.120@qq.com" || username === "admin";
      // return true;
    };

    $scope.isRootSubject = function(scope) {
      if (scope.$modelValue.title == "所有主题") {
        return true;
      }
      return false;
    };
  }]);


text:
/***************************************************************************
 *
 * $Id: StAntiBMesonZero.cc,v 1.1 1999/05/14 18:47:02 ullrich Exp $
 *
 * Author: Thomas Ullrich, May 99 (based on Geant4 code, see below)
 ***************************************************************************
 *
 * The design of the StParticleDefinition class and all concrete
 * classes derived from it is largely based on the design of the
 * G4ParticleDefinition class from Geant4 (RD44).
 * Although the code is in large parts different (modified or rewritten)
 * and adapted to the STAR framework the basic idea stays the same.
 *
 ***************************************************************************
 *
 * $Log: StAntiBMesonZero.cc,v $
 * Revision 1.1  1999/05/14 18:47:02  ullrich
 * Initial Revision
 *
 **************************************************************************/
#include "StAntiBMesonZero.hh"
#include "PhysicalConstants.h"

StAntiBMesonZero::StAntiBMesonZero(const string  &  aName,
				   double           mass,
				   double           width,
				   double           charge,
				   int              iSpin,
				   int              iParity,
				   int              iConjugation,
				   int              iIsospin,
				   int              iIsospinZ,
				   int              gParity,
				   const string  &  pType,
				   int              lepton,
				   int              baryon,
				   int              encoding,
				   bool             stable,
				   double           lifetime)
    : StMeson(aName, mass, width, charge, iSpin, iParity,
	      iConjugation, iIsospin, iIsospinZ, gParity,
	      pType, lepton, baryon, encoding, stable,
	      lifetime) {/* noop */}

// ......................................................................
// ...                 static member definitions                      ...
// ......................................................................
//
//    Arguments for constructor are as follows
//               name             mass          width         charge
//             2*spin           parity  C-conjugation
//          2*Isospin       2*Isospin3       G-parity
//               type    lepton number  baryon number   PDG encoding
//             stable         lifetime
//
StAntiBMesonZero StAntiBMesonZero::mAntiBMesonZero(
	    "anti_B0",      5.21792*GeV,       0.0*MeV,          0.,
		    0,              -1,             0,
		    1,              +1,             0,
	      "meson",               0,             0,        -511,
		false,      1.56e-3*nanosecond
);

redpajama_set_name: RedPajamaGithub


text:
(function(){
	'use strict';
	var app = angular.module('main', [ 'ngMaterial' ]);

    app.controller('AppController', [ '$http', '$scope', '$mdDialog', '$timeout', '$mdSidenav', '$q',
                    function($http, $scope, $mdDialog, $timeout, $mdSidenav, $q){
        var self = this;

        self.resources = resources;
        self.activeElement = {};
        self.activeResource = {};
        self.elements = [];
        self.hideContent = true;
        self.activeSearch = false;
        self.selectedItemSearch = null;
        self.searchText = null;
        self.categories = [];

        self.categoriesSearch = [];

        $scope.status = '';

        $scope.toggleLeft = buildToggler('left');
        $scope.isSidenavOpen = false;

		this.selectResource = function(resource) {
            self.loadCategories();
            self.activeResource = resource;
            self.listAll();
            self.hideContent = false;
            self.categoriesSearch = [];
            self.activeSearch = false;
		};

		this.isSelected = function(checkTab){
			return this.tab === checkTab;
		};

        this.listAll = function(){
            var url = self.activeResource.where;
            var name = self.activeResource.name;

            self.categoriesSearch = [];
            self.activeSearch = false;

            $http.get(url).success(function(data){
                self.elements = [];
                if (url == "job_positions") self.elements = data.job_positions;
                if (url == "skills") self.elements = data.skills;
                if (url == "categories") self.elements = data.categories;
                self.elements.sort(function(a,b){
                    return a.name.localeCompare(b.name);
                });
            });
        };

        this.clearElements = function (){
            self.elements = [];
            self.categoriesSearch = [];
            self.activeSearch = false;
        };

        this.toggleSearch = function (){
            self.activeSearch=!self.activeSearch;
        };

        this.addCategoryToElements = function (category){
            var url = self.activeResource.where + '/categories/' + category;
            $http.get(url).success(function(data){
                self.elements = self.elements.concat(data.job_positions);
            });
        };

        this.findByCategories = function (){
            self.elements = [];
            self.categoriesSearch.forEach(function(category){
                self.addCategoryToElements(category.name);
            });
        };

        this.loadCategories = function (){
            self.categories = [];
            $http.get('categories').success(function(data){
                self.categories = self.categories.concat(data.categories);
            });
        };

        this.queryCategorySearch = function(query){
            var results = query ? self.categories.filter(createFilterFor(query)) : [];
            return results;
        };

        function createFilterFor(query) {
                var lowercaseQuery = angular.lowercase(query);
            return function filterFn(category) {
                return (category.name.toLowerCase().indexOf(lowercaseQuery) === 0);
            };
        };

        $scope.showDelDialog = function(ev,res,elmnt){
            $mdDialog.show({
              controller: DeldialogController,
              controllerAs: 'deldialogCtrl',
              templateUrl: 'views/pages/delElement.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose:true,
              fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
              locals: {
                  resource: res,
                  element: elmnt
                  },

            })
            .then(function(answer) {
              $scope.status = 'You said the information was ' + answer + '.';
              console.log(answer);
            }, function() {
              console.log("I canceled");
            });
        };

        $scope.showModifyDialog = function(ev,res,elmnt){
            $mdDialog.show({
              controller: ModdialogController,
              controllerAs: 'moddialogCtrl',
              templateUrl: 'views/pages/modifyElement.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose:true,
              fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
              locals: {
                  resource: res,
                  element: elmnt
                  },

            })
            .then(function(answer) {
              $scope.status = 'You said the information was ' + answer + '.';
            }, function() {
              console.log('You cancelled the dialog.');
            });
        };

        $scope.showMoreDialog = function(ev,res,elmt) {
            $mdDialog.show({
              controller: ShowmoreController,
              controllerAs: 'moreCtrl',
              templateUrl: 'views/pages/showMore.html',
              parent: angular.element(document.body),
              targetEvent: ev,
              clickOutsideToClose:true,
              fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
              locals: {
                  resource: res,
                  element: elmt
                  }

            })
            .then(function(answer) {
              $scope.status = 'You said the information was "' + answer + '".';
            }, function() {
              $scope.status = 'You cancelled the dialog.';
            });
        };

        function ModdialogController ($scope, $mdDialog, $http, resource, element) {

            $scope.resource = resource;
            $scope.originalElement = angular.copy(element);
            $scope.element = element;
            $scope.clean = { };
            $scope.categories = [];

            $http.get('/categories').success(function(data){
                $scope.categories = data.categories;
            });

            if (resource.name === 'Categories') element.category = $scope.categories[0];

            $scope.cancel = function(answer) {
                $scope.element.name = $scope.originalElement.name;
                $scope.element.description = $scope.originalElement.description;
                $scope.element.category = $scope.originalElement.category;
                if (resource.name === 'Categories' && element.hasOwnProperty('category')) delete element.category;
                $mdDialog.cancel(answer);

            };

            $scope.refresh = function() {
                $scope.element = angular.copy($scope.clean);
            };

            $scope.confirm = function() {
                var url = $scope.resource.where + '/categories/' + $scope.originalElement.category + '/' + $scope.originalElement.name ;

                var data = {
                    name: $scope.element.name,
                    description: $scope.element.description,
                    category: $scope.element.category
                };

                if (resource.name === 'Categories'){
                    url = $scope.resource.where + '/' + $scope.originalElement.name;

                    data = {
                        name: $scope.element.name,
                        description: $scope.element.description,
                    };
                 }

                $http.put(url,data).success(function(data){
                    console.log(data);
                    $mdDialog.cancel();
                });
            };
        };

        function DeldialogController($scope, $mdDialog, $http, resource, element) {
            $scope.resource = resource;
            $scope.element = element;

            $scope.cancel = function(answer) {
                $mdDialog.cancel(answer);
            };

            $scope.del = function() {
                var url = $scope.resource.where + "/categories/" + $scope.element.category + "/" + $scope.element.name;
                if ($scope.resource.name === "Categories") url = $scope.resource.where + "/" + $scope.element.name;
                $http.delete(url).success(function(data){
                    $scope.satus = "Success";
                    var index = self.elements.indexOf($scope.element);
                    console.log(index);
                    self.elements.splice(index,1);
                    $mdDialog.cancel();
                });

            };
        };

        function ShowmoreController($scope, $mdDialog, resource, element){
            $scope.resource = resource;
            $scope.element = element;

            $scope.cancel = function(){
                $mdDialog.cancel();
            };
        };

        function buildToggler(componentId) {
            return function() {
            $mdSidenav(componentId).toggle();
            $scope.isSidenavOpen = !$scope.isSidenavOpen;
            };
        };

	}]);

    var resources = [
        {
            name: "Job Positions",
            image: "images/group.svg",
            where: "job_positions",
        },
        {
            name: "Skills",
            image: "images/suitcase.svg",
            where: "skills",
        },
        {
            name: "Categories",
            image: "images/hierarchy.svg",
            where: "categories",
        }
    ];

})();


text:
namespace version_info {
enum class Channel;
}

namespace extensions {

// Gets the current channel as seen by the Feature system.
version_info::Channel GetCurrentChannel();

// Sets the current channel as seen by the Feature system. In the browser
// process this should be chrome::GetChannel(), and in the renderer this will
// need to come from an IPC.
void SetCurrentChannel(version_info::Channel channel);

// Gets the default channel as seen by the Feature system.
version_info::Channel GetDefaultChannel();

// Scoped channel setter. Use for tests.
class ScopedCurrentChannel {
 public:
  explicit ScopedCurrentChannel(version_info::Channel channel);
  ~ScopedCurrentChannel();

 private:
  version_info::Channel original_channel_;

  DISALLOW_COPY_AND_ASSIGN(ScopedCurrentChannel);
};

}  // namespace extensions

#endif  // CHROME_COMMON_EXTENSIONS_FEATURES_FEATURE_CHANNEL_H_


text:
package Chapter8;
import java.util.*;

public class RandomAccessifier
{
  interface ListTransform
  {
    public void transform( List list );
  }

  static class RandomTransform implements ListTransform
  {
    private int count;
    private Random rand = new Random();

    public RandomTransform( int count ) {
      this.count = count;
    }

    public void transform( List list ) {
      for (int i=0; i<count; ++i) {
        int ai = rand.nextInt( list.size() );
        int bi = rand.nextInt( list.size() );
        Collections.swap( list, ai, bi );
      }
    }
  }

  public static void transform( List list,
                                ListTransform transform ) {
    List origList = list;
    boolean ra = (list instanceof RandomAccess);
    if (!ra) {
      System.out.println( "Converting to RA" );
      list = new ArrayList( origList.size() );
      for (Iterator it=origList.iterator(); it.hasNext();) {
        list.add( it.next() );
      }
    }
    transform.transform( list );
    if (!ra) {
      origList.clear();
      int size = list.size();
      for (Iterator it=list.iterator(); it.hasNext();) {
        origList.add( it.next() );
      }
    }
  }

  static public void main( String args[] ) {
    List list = new LinkedList();
    for (int i=0; i<100; ++i) {
      list.add( new Integer( i ) );
    }

    RandomTransform rt = new RandomTransform( 10000000 );
    transform( list, rt );

    for (Iterator it=list.iterator(); it.hasNext();) {
      System.out.print( it.next()+" " );
    }
    System.out.println( "" );
  }
}


text:
if [ $# -eq 0 ]
then
  echo "No arguments supplied"
  exit 1
fi

REPO=$1
DISTRIBUTION_SUFFIX=$(echo $REPO | sed 's/-conf//')
DISTRIBUTION="acme-${DISTRIBUTION_SUFFIX}"

if ! which fpm > /dev/null
then
  echo "Please install fpm"
  exit 0
fi

for arch in i386 amd64 noarch
do
  echo $arch
  rm -fr /var/tmp/fpm/dummy-$arch/src
  mkdir -p /var/tmp/fpm/dummy-$arch/src
  cd /var/tmp/fpm/dummy-$arch/
  echo "dummy package for arch $arch" > src/README-${arch}.md
  fpm -t deb -s dir --name dummy-package --version 0.0.1 --architecture $arch --maintainer "<rls-team@acme.com>" --description "dummy package arch $arch" --prefix /var/tmp/dummy -C src .
  aptly repo add $REPO /var/tmp/fpm/dummy-$arch/dummy-package*deb
  aptly publish update $DISTRIBUTION $REPO
done


text:
package com.google.devtools.mobileharness.platform.android.shared.constant;

import com.google.common.collect.ImmutableSet;

/**
 * Holds package related constants that are shared in Mobile Harness Lightning API
 * (go/mh-lightning-api).
 *
 * <p>Please keep all constants in this class sorted in alphabetical order by name.
 */
public final class PackageConstants {

  /** Package name of GMS core. */
  public static final String PACKAGE_NAME_GMS = "com.google.android.gms";

  /**
   * Package name for the androidx basic services apk at
   * //java/com/google/android/apps/common/testing/services:basic_services.apk
   */
  public static final String PACKAGE_NAME_BASIC_SERVICES_APK =
      "com.google.android.apps.common.testing.services";

  /**
   * Package name for the androidx test services apk at
   * //third_party/android/androidx_test/services:test_services.apk
   */
  public static final String PACKAGE_NAME_TEST_SERVICES_APK = "androidx.test.services";

  /**
   * List of package names for androidx services apks at
   * //java/com/google/android/apps/common/testing/services:basic_services.apk and
   * //third_party/android/androidx_test/services:test_services.apk
   */
  public static final ImmutableSet<String> ANDROIDX_SERVICES_APK_PACKAGE_NAMES =
      ImmutableSet.of(PACKAGE_NAME_BASIC_SERVICES_APK, PACKAGE_NAME_TEST_SERVICES_APK);

  private PackageConstants() {}
}


text:
object SequenceSum {

  def sum(numbers: List[Int]): Int = {
    numbers.sum
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
		<link rel="stylesheet" type="text/css" href="../styles.css"/>
		<script type="text/javascript" src="../js/jquery.1.10.2.min.js"></script>
		<script type="text/javascript" src="../js/jquery-ui-1.10.3.custom.min.js"></script>
		<script type="text/javascript" src="../js/jquery.browser.min.js"></script>
		<script type="text/javascript" src="../js/KB_Programmer_Dvorak.keymap.js"></script>
		<script type="text/javascript" src="../js/typingtutor/typingtutor.js"></script>
		<script type="text/javascript" src="../js/lessons.js"></script>
		<script type="text/javascript" src="../js/tutor.js"></script>
        <script type="text/javascript" src="../js/cookies.js"></script>

	        <script type="text/javascript">
            $(document).ready(function() {

			var lines1 = [

				'aaaa cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll mmmm nnnn oooo',
				'pppp qqqq rrrr ssss tttt uuuu vvvv wwww yyyy zzzz \'\'\'\' ,,,, .... ;;;;',
				'aaaa cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll mmmm nnnn oooo',
				'pppp qqqq rrrr ssss tttt uuuu vvvv wwww yyyy zzzz \'\'\'\' ,,,, .... ;;;;'

];
			var lines2 = [

				'Zachary MacKenzie froze in amazement; on the radio in his Mazda he heard',
				'pizzicato stanzas of Mozart.',
				'Carmen Rodriguez is a citizen of Venezuela; her former spouse, Inigo Martinez,',
				'and his new wife, Anna Vasquez, have moved to Swaziland or Tanzania.',
				'The prizewinning paper on immunization against schizophrenia was delivered in',
				'Czechoslovakia; this technique was deemphasized in Switzerland.',
				'A crazed gazelle was whizzing around the zoo; a quizzical giraffe guzzled down',
				'pizzas through his muzzle; another one merely grazed and dozed; several',
				'chimpanzees started zigging and zagging; the reptile zone was oozing with',
				'activity; several lizards hazarded the freezing waters and capsized the fish',
				'tanks; a dozen grizzlies were waltzing in the plaza.'

];
            makeup(27, lines1, lines2);

            cp();
            });
        </script>
	</head>

	<body>
		<div class="content">

		</div>
	</body>
</html>


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed 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.
package com.google.devtools.build.lib.query2.cquery;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.BuildOptionsView;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.analysis.config.transitions.SplitTransition;
import com.google.devtools.build.lib.analysis.util.DummyTestFragment.DummyTestOptions;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.QueryFunction;
import com.google.devtools.build.lib.query2.testutil.PostAnalysisQueryTest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link ConfiguredTargetQueryEnvironment}. */
@RunWith(JUnit4.class)
public abstract class ConfiguredTargetQueryTest
    extends PostAnalysisQueryTest<KeyedConfiguredTarget> {

  @Override
  protected QueryHelper<KeyedConfiguredTarget> createQueryHelper() {
    if (helper != null) {
      getHelper().cleanUp();
    }
    helper = new ConfiguredTargetQueryHelper();
    return helper;
  }

  @Override
  public HashMap<String, QueryFunction> getDefaultFunctions() {
    ImmutableList<QueryFunction> defaultFunctions =
        ImmutableList.copyOf(ConfiguredTargetQueryEnvironment.FUNCTIONS);
    HashMap<String, QueryFunction> functions = new HashMap<>();
    for (QueryFunction queryFunction : defaultFunctions) {
      functions.put(queryFunction.getName(), queryFunction);
    }
    return functions;
  }

  @Override
  protected final BuildConfiguration getConfiguration(KeyedConfiguredTarget kct) {
    return getHelper()
        .getSkyframeExecutor()
        .getConfiguration(getHelper().getReporter(), kct.getConfigurationKey());
  }

  /** SplitTransition on --foo */
  protected static class FooSplitTransition implements SplitTransition {
    String toOption1;
    String toOption2;

    public FooSplitTransition(String toOption1, String toOptions2) {
      this.toOption1 = toOption1;
      this.toOption2 = toOptions2;
    }

    @Override
    public ImmutableSet<Class<? extends FragmentOptions>> requiresOptionFragments() {
      return ImmutableSet.of(DummyTestOptions.class);
    }

    @Override
    public Map<String, BuildOptions> split(BuildOptionsView options, EventHandler eventHandler) {
      BuildOptionsView result1 = options.clone();
      BuildOptionsView result2 = options.clone();
      result1.get(DummyTestOptions.class).foo = toOption1;
      result2.get(DummyTestOptions.class).foo = toOption2;
      return ImmutableMap.of("result1", result1.underlying(), "result2", result2.underlying());
    }
  }

  @Override
  @Test
  public void testMultipleTopLevelConfigurations_nullConfigs() throws Exception {
    writeFile("test/BUILD", "java_library(name='my_java',", "  srcs = ['foo.java'],", ")");

    Set<KeyedConfiguredTarget> result = eval("//test:my_java+//test:foo.java");

    assertThat(result).hasSize(2);

    Iterator<KeyedConfiguredTarget> resultIterator = result.iterator();
    KeyedConfiguredTarget first = resultIterator.next();
    if (first.getLabel().toString().equals("//test:foo.java")) {
      assertThat(getConfiguration(first)).isNull();
      assertThat(getConfiguration(resultIterator.next())).isNotNull();
    } else {
      assertThat(getConfiguration(first)).isNotNull();
      assertThat(getConfiguration(resultIterator.next())).isNull();
    }
  }

  @Override
  public void testMultipleTopLevelConfigurations_multipleConfigsPrefersTopLevel() {
    // When the same target exists in multiple configurations, cquery doesn't guarantee which
    // instance is evaluated first. So disable this test.
  }
}


text:
/*	$OpenBSD: rf_diskqueue.c,v 1.2 1999/02/16 00:02:39 niklas Exp $	*/
/*	$NetBSD: rf_diskqueue.c,v 1.6 1999/02/05 00:06:09 oster Exp $	*/
/*
 * Copyright (c) 1995 Carnegie-Mellon University.
 * All rights reserved.
 *
 * Author: Mark Holland
 *
 * Permission to use, copy, modify and distribute this software and
 * its documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */

/****************************************************************************************
 *
 * rf_diskqueue.c -- higher-level disk queue code
 *
 * the routines here are a generic wrapper around the actual queueing
 * routines.  The code here implements thread scheduling, synchronization,
 * and locking ops (see below) on top of the lower-level queueing code.
 *
 * to support atomic RMW, we implement "locking operations".  When a locking op
 * is dispatched to the lower levels of the driver, the queue is locked, and no further
 * I/Os are dispatched until the queue receives & completes a corresponding "unlocking
 * operation".  This code relies on the higher layers to guarantee that a locking
 * op will always be eventually followed by an unlocking op.  The model is that
 * the higher layers are structured so locking and unlocking ops occur in pairs, i.e.
 * an unlocking op cannot be generated until after a locking op reports completion.
 * There is no good way to check to see that an unlocking op "corresponds" to the
 * op that currently has the queue locked, so we make no such attempt.  Since by
 * definition there can be only one locking op outstanding on a disk, this should
 * not be a problem.
 *
 * In the kernel, we allow multiple I/Os to be concurrently dispatched to the disk
 * driver.  In order to support locking ops in this environment, when we decide to
 * do a locking op, we stop dispatching new I/Os and wait until all dispatched I/Os
 * have completed before dispatching the locking op.
 *
 * Unfortunately, the code is different in the 3 different operating states
 * (user level, kernel, simulator).  In the kernel, I/O is non-blocking, and
 * we have no disk threads to dispatch for us.  Therefore, we have to dispatch
 * new I/Os to the scsi driver at the time of enqueue, and also at the time
 * of completion.  At user level, I/O is blocking, and so only the disk threads
 * may dispatch I/Os.  Thus at user level, all we can do at enqueue time is
 * enqueue and wake up the disk thread to do the dispatch.
 *
 ***************************************************************************************/

#include "rf_types.h"
#include "rf_threadstuff.h"
#include "rf_threadid.h"
#include "rf_raid.h"
#include "rf_diskqueue.h"
#include "rf_alloclist.h"
#include "rf_acctrace.h"
#include "rf_etimer.h"
#include "rf_configure.h"
#include "rf_general.h"
#include "rf_freelist.h"
#include "rf_debugprint.h"
#include "rf_shutdown.h"
#include "rf_cvscan.h"
#include "rf_sstf.h"
#include "rf_fifo.h"

static int init_dqd(RF_DiskQueueData_t *);
static void clean_dqd(RF_DiskQueueData_t *);
static void rf_ShutdownDiskQueueSystem(void *);
/* From rf_kintf.c */
int     rf_DispatchKernelIO(RF_DiskQueue_t *, RF_DiskQueueData_t *);

#define Dprintf1(s,a)         if (rf_queueDebug) rf_debug_printf(s,(void *)((unsigned long)a),NULL,NULL,NULL,NULL,NULL,NULL,NULL)
#define Dprintf2(s,a,b)       if (rf_queueDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),NULL,NULL,NULL,NULL,NULL,NULL)
#define Dprintf3(s,a,b,c)     if (rf_queueDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),NULL,NULL,NULL,NULL,NULL)
#define Dprintf4(s,a,b,c,d)   if (rf_queueDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),NULL,NULL,NULL,NULL)
#define Dprintf5(s,a,b,c,d,e) if (rf_queueDebug) rf_debug_printf(s,(void *)((unsigned long)a),(void *)((unsigned long)b),(void *)((unsigned long)c),(void *)((unsigned long)d),(void *)((unsigned long)e),NULL,NULL,NULL)

#define SIGNAL_DISK_QUEUE(_q_,_wh_)
#define WAIT_DISK_QUEUE(_q_,_wh_)

/*****************************************************************************************
 *
 * the disk queue switch defines all the functions used in the different queueing
 * disciplines
 *    queue ID, init routine, enqueue routine, dequeue routine
 *
 ****************************************************************************************/

static RF_DiskQueueSW_t diskqueuesw[] = {
	{"fifo",		/* FIFO */
		rf_FifoCreate,
		rf_FifoEnqueue,
		rf_FifoDequeue,
		rf_FifoPeek,
	rf_FifoPromote},

	{"cvscan",		/* cvscan */
		rf_CvscanCreate,
		rf_CvscanEnqueue,
		rf_CvscanDequeue,
		rf_CvscanPeek,
	rf_CvscanPromote},

	{"sstf",		/* shortest seek time first */
		rf_SstfCreate,
		rf_SstfEnqueue,
		rf_SstfDequeue,
		rf_SstfPeek,
	rf_SstfPromote},

	{"scan",		/* SCAN (two-way elevator) */
		rf_ScanCreate,
		rf_SstfEnqueue,
		rf_ScanDequeue,
		rf_ScanPeek,
	rf_SstfPromote},

	{"cscan",		/* CSCAN (one-way elevator) */
		rf_CscanCreate,
		rf_SstfEnqueue,
		rf_CscanDequeue,
		rf_CscanPeek,
	rf_SstfPromote},

#if !defined(_KERNEL) && RF_INCLUDE_QUEUE_RANDOM > 0
	/* to make a point to Chris :-> */
	{"random",		/* random */
		rf_FifoCreate,
		rf_FifoEnqueue,
		rf_RandomDequeue,
		rf_RandomPeek,
	rf_FifoPromote},
#endif				/* !KERNEL && RF_INCLUDE_QUEUE_RANDOM > 0 */
};
#define NUM_DISK_QUEUE_TYPES (sizeof(diskqueuesw)/sizeof(RF_DiskQueueSW_t))

static RF_FreeList_t *rf_dqd_freelist;

#define RF_MAX_FREE_DQD 256
#define RF_DQD_INC       16
#define RF_DQD_INITIAL   64

#include <sys/buf.h>

static int
init_dqd(dqd)
	RF_DiskQueueData_t *dqd;
{
	/* XXX not sure if the following malloc is appropriate... probably not
	 * quite... */
	dqd->bp = (struct buf *) malloc(sizeof(struct buf), M_RAIDFRAME, M_NOWAIT);
	if (dqd->bp == NULL) {
		return (ENOMEM);
	}
	memset(dqd->bp, 0, sizeof(struct buf));	/* if you don't do it, nobody
						 * else will.. */
	return (0);
}

static void
clean_dqd(dqd)
	RF_DiskQueueData_t *dqd;
{
	free(dqd->bp, M_RAIDFRAME);
}
/* configures a single disk queue */
static int
config_disk_queue(
    RF_Raid_t * raidPtr,
    RF_DiskQueue_t * diskqueue,
    RF_RowCol_t r,		/* row & col -- debug only.  BZZT not any
				 * more... */
    RF_RowCol_t c,
    RF_DiskQueueSW_t * p,
    RF_SectorCount_t sectPerDisk,
    dev_t dev,
    int maxOutstanding,
    RF_ShutdownList_t ** listp,
    RF_AllocListElem_t * clList)
{
	int     rc;

	diskqueue->row = r;
	diskqueue->col = c;
	diskqueue->qPtr = p;
	diskqueue->qHdr = (p->Create) (sectPerDisk, clList, listp);
	diskqueue->dev = dev;
	diskqueue->numOutstanding = 0;
	diskqueue->queueLength = 0;
	diskqueue->maxOutstanding = maxOutstanding;
	diskqueue->curPriority = RF_IO_NORMAL_PRIORITY;
	diskqueue->nextLockingOp = NULL;
	diskqueue->unlockingOp = NULL;
	diskqueue->numWaiting = 0;
	diskqueue->flags = 0;
	diskqueue->raidPtr = raidPtr;
	diskqueue->rf_cinfo = &raidPtr->raid_cinfo[r][c];
	rc = rf_create_managed_mutex(listp, &diskqueue->mutex);
	if (rc) {
		RF_ERRORMSG3("Unable to init mutex file %s line %d rc=%d\n", __FILE__,
		    __LINE__, rc);
		return (rc);
	}
	rc = rf_create_managed_cond(listp, &diskqueue->cond);
	if (rc) {
		RF_ERRORMSG3("Unable to init cond file %s line %d rc=%d\n", __FILE__,
		    __LINE__, rc);
		return (rc);
	}
	return (0);
}

static void
rf_ShutdownDiskQueueSystem(ignored)
	void   *ignored;
{
	RF_FREELIST_DESTROY_CLEAN(rf_dqd_freelist, next, (RF_DiskQueueData_t *), clean_dqd);
}

int
rf_ConfigureDiskQueueSystem(listp)
	RF_ShutdownList_t **listp;
{
	int     rc;

	RF_FREELIST_CREATE(rf_dqd_freelist, RF_MAX_FREE_DQD,
	    RF_DQD_INC, sizeof(RF_DiskQueueData_t));
	if (rf_dqd_freelist == NULL)
		return (ENOMEM);
	rc = rf_ShutdownCreate(listp, rf_ShutdownDiskQueueSystem, NULL);
	if (rc) {
		RF_ERRORMSG3("Unable to add to shutdown list file %s line %d rc=%d\n",
		    __FILE__, __LINE__, rc);
		rf_ShutdownDiskQueueSystem(NULL);
		return (rc);
	}
	RF_FREELIST_PRIME_INIT(rf_dqd_freelist, RF_DQD_INITIAL, next,
	    (RF_DiskQueueData_t *), init_dqd);
	return (0);
}

int
rf_ConfigureDiskQueues(
    RF_ShutdownList_t ** listp,
    RF_Raid_t * raidPtr,
    RF_Config_t * cfgPtr)
{
	RF_DiskQueue_t **diskQueues, *spareQueues;
	RF_DiskQueueSW_t *p;
	RF_RowCol_t r, c;
	int     rc, i;

	raidPtr->maxQueueDepth = cfgPtr->maxOutstandingDiskReqs;

	for (p = NULL, i = 0; i < NUM_DISK_QUEUE_TYPES; i++) {
		if (!strcmp(diskqueuesw[i].queueType, cfgPtr->diskQueueType)) {
			p = &diskqueuesw[i];
			break;
		}
	}
	if (p == NULL) {
		RF_ERRORMSG2("Unknown queue type \"%s\".  Using %s\n", cfgPtr->diskQueueType, diskqueuesw[0].queueType);
		p = &diskqueuesw[0];
	}
	RF_CallocAndAdd(diskQueues, raidPtr->numRow, sizeof(RF_DiskQueue_t *), (RF_DiskQueue_t **), raidPtr->cleanupList);
	if (diskQueues == NULL) {
		return (ENOMEM);
	}
	raidPtr->Queues = diskQueues;
	for (r = 0; r < raidPtr->numRow; r++) {
		RF_CallocAndAdd(diskQueues[r], raidPtr->numCol + ((r == 0) ? raidPtr->numSpare : 0), sizeof(RF_DiskQueue_t), (RF_DiskQueue_t *), raidPtr->cleanupList);
		if (diskQueues[r] == NULL)
			return (ENOMEM);
		for (c = 0; c < raidPtr->numCol; c++) {
			rc = config_disk_queue(raidPtr, &diskQueues[r][c], r, c, p,
			    raidPtr->sectorsPerDisk, raidPtr->Disks[r][c].dev,
			    cfgPtr->maxOutstandingDiskReqs, listp, raidPtr->cleanupList);
			if (rc)
				return (rc);
		}
	}

	spareQueues = &raidPtr->Queues[0][raidPtr->numCol];
	for (r = 0; r < raidPtr->numSpare; r++) {
		rc = config_disk_queue(raidPtr, &spareQueues[r],
		    0, raidPtr->numCol + r, p,
		    raidPtr->sectorsPerDisk,
		    raidPtr->Disks[0][raidPtr->numCol + r].dev,
		    cfgPtr->maxOutstandingDiskReqs, listp,
		    raidPtr->cleanupList);
		if (rc)
			return (rc);
	}
	return (0);
}
/* Enqueue a disk I/O
 *
 * Unfortunately, we have to do things differently in the different
 * environments (simulator, user-level, kernel).
 * At user level, all I/O is blocking, so we have 1 or more threads/disk
 * and the thread that enqueues is different from the thread that dequeues.
 * In the kernel, I/O is non-blocking and so we'd like to have multiple
 * I/Os outstanding on the physical disks when possible.
 *
 * when any request arrives at a queue, we have two choices:
 *    dispatch it to the lower levels
 *    queue it up
 *
 * kernel rules for when to do what:
 *    locking request:  queue empty => dispatch and lock queue,
 *                      else queue it
 *    unlocking req  :  always dispatch it
 *    normal req     :  queue empty => dispatch it & set priority
 *                      queue not full & priority is ok => dispatch it
 *                      else queue it
 *
 * user-level rules:
 *    always enqueue.  In the special case of an unlocking op, enqueue
 *    in a special way that will cause the unlocking op to be the next
 *    thing dequeued.
 *
 * simulator rules:
 *    Do the same as at user level, with the sleeps and wakeups suppressed.
 */
void
rf_DiskIOEnqueue(queue, req, pri)
	RF_DiskQueue_t *queue;
	RF_DiskQueueData_t *req;
	int     pri;
{
	int     tid;

	RF_ETIMER_START(req->qtime);
	rf_get_threadid(tid);
	RF_ASSERT(req->type == RF_IO_TYPE_NOP || req->numSector);
	req->priority = pri;

	if (rf_queueDebug && (req->numSector == 0)) {
		printf("Warning: Enqueueing zero-sector access\n");
	}
	/*
         * kernel
         */
	RF_LOCK_QUEUE_MUTEX(queue, "DiskIOEnqueue");
	/* locking request */
	if (RF_LOCKING_REQ(req)) {
		if (RF_QUEUE_EMPTY(queue)) {
			Dprintf3("Dispatching pri %d locking op to r %d c %d (queue empty)\n", pri, queue->row, queue->col);
			RF_LOCK_QUEUE(queue);
			rf_DispatchKernelIO(queue, req);
		} else {
			queue->queueLength++;	/* increment count of number
						 * of requests waiting in this
						 * queue */
			Dprintf3("Enqueueing pri %d locking op to r %d c %d (queue not empty)\n", pri, queue->row, queue->col);
			req->queue = (void *) queue;
			(queue->qPtr->Enqueue) (queue->qHdr, req, pri);
		}
	}
	/* unlocking request */
	else
		if (RF_UNLOCKING_REQ(req)) {	/* we'll do the actual unlock
						 * when this I/O completes */
			Dprintf3("Dispatching pri %d unlocking op to r %d c %d\n", pri, queue->row, queue->col);
			RF_ASSERT(RF_QUEUE_LOCKED(queue));
			rf_DispatchKernelIO(queue, req);
		}
	/* normal request */
		else
			if (RF_OK_TO_DISPATCH(queue, req)) {
				Dprintf3("Dispatching pri %d regular op to r %d c %d (ok to dispatch)\n", pri, queue->row, queue->col);
				rf_DispatchKernelIO(queue, req);
			} else {
				queue->queueLength++;	/* increment count of
							 * number of requests
							 * waiting in this queue */
				Dprintf3("Enqueueing pri %d regular op to r %d c %d (not ok to dispatch)\n", pri, queue->row, queue->col);
				req->queue = (void *) queue;
				(queue->qPtr->Enqueue) (queue->qHdr, req, pri);
			}
	RF_UNLOCK_QUEUE_MUTEX(queue, "DiskIOEnqueue");
}

/* get the next set of I/Os started, kernel version only */
void
rf_DiskIOComplete(queue, req, status)
	RF_DiskQueue_t *queue;
	RF_DiskQueueData_t *req;
	int     status;
{
	int     done = 0;

	RF_LOCK_QUEUE_MUTEX(queue, "DiskIOComplete");

	/* unlock the queue: (1) after an unlocking req completes (2) after a
	 * locking req fails */
	if (RF_UNLOCKING_REQ(req) || (RF_LOCKING_REQ(req) && status)) {
		Dprintf2("DiskIOComplete: unlocking queue at r %d c %d\n", queue->row, queue->col);
		RF_ASSERT(RF_QUEUE_LOCKED(queue) && (queue->unlockingOp == NULL));
		RF_UNLOCK_QUEUE(queue);
	}
	queue->numOutstanding--;
	RF_ASSERT(queue->numOutstanding >= 0);

	/* dispatch requests to the disk until we find one that we can't. */
	/* no reason to continue once we've filled up the queue */
	/* no reason to even start if the queue is locked */

	while (!done && !RF_QUEUE_FULL(queue) && !RF_QUEUE_LOCKED(queue)) {
		if (queue->nextLockingOp) {
			req = queue->nextLockingOp;
			queue->nextLockingOp = NULL;
			Dprintf3("DiskIOComplete: a pri %d locking req was pending at r %d c %d\n", req->priority, queue->row, queue->col);
		} else {
			req = (queue->qPtr->Dequeue) (queue->qHdr);
			if (req != NULL) {
				Dprintf3("DiskIOComplete: extracting pri %d req from queue at r %d c %d\n", req->priority, queue->row, queue->col);
			} else {
				Dprintf1("DiskIOComplete: no more requests to extract.\n", "");
			}
		}
		if (req) {
			queue->queueLength--;	/* decrement count of number
						 * of requests waiting in this
						 * queue */
			RF_ASSERT(queue->queueLength >= 0);
		}
		if (!req)
			done = 1;
		else
			if (RF_LOCKING_REQ(req)) {
				if (RF_QUEUE_EMPTY(queue)) {	/* dispatch it */
					Dprintf3("DiskIOComplete: dispatching pri %d locking req to r %d c %d (queue empty)\n", req->priority, queue->row, queue->col);
					RF_LOCK_QUEUE(queue);
					rf_DispatchKernelIO(queue, req);
					done = 1;
				} else {	/* put it aside to wait for
						 * the queue to drain */
					Dprintf3("DiskIOComplete: postponing pri %d locking req to r %d c %d\n", req->priority, queue->row, queue->col);
					RF_ASSERT(queue->nextLockingOp == NULL);
					queue->nextLockingOp = req;
					done = 1;
				}
			} else
				if (RF_UNLOCKING_REQ(req)) {	/* should not happen:
								 * unlocking ops should
								 * not get queued */
					RF_ASSERT(RF_QUEUE_LOCKED(queue));	/* support it anyway for
										 * the future */
					Dprintf3("DiskIOComplete: dispatching pri %d unl req to r %d c %d (SHOULD NOT SEE THIS)\n", req->priority, queue->row, queue->col);
					rf_DispatchKernelIO(queue, req);
					done = 1;
				} else
					if (RF_OK_TO_DISPATCH(queue, req)) {
						Dprintf3("DiskIOComplete: dispatching pri %d regular req to r %d c %d (ok to dispatch)\n", req->priority, queue->row, queue->col);
						rf_DispatchKernelIO(queue, req);
					} else {	/* we can't dispatch it,
							 * so just re-enqueue
							 * it.  */
						/* potential trouble here if
						 * disk queues batch reqs */
						Dprintf3("DiskIOComplete: re-enqueueing pri %d regular req to r %d c %d\n", req->priority, queue->row, queue->col);
						queue->queueLength++;
						(queue->qPtr->Enqueue) (queue->qHdr, req, req->priority);
						done = 1;
					}
	}

	RF_UNLOCK_QUEUE_MUTEX(queue, "DiskIOComplete");
}
/* promotes accesses tagged with the given parityStripeID from low priority
 * to normal priority.  This promotion is optional, meaning that a queue
 * need not implement it.  If there is no promotion routine associated with
 * a queue, this routine does nothing and returns -1.
 */
int
rf_DiskIOPromote(queue, parityStripeID, which_ru)
	RF_DiskQueue_t *queue;
	RF_StripeNum_t parityStripeID;
	RF_ReconUnitNum_t which_ru;
{
	int     retval;

	if (!queue->qPtr->Promote)
		return (-1);
	RF_LOCK_QUEUE_MUTEX(queue, "DiskIOPromote");
	retval = (queue->qPtr->Promote) (queue->qHdr, parityStripeID, which_ru);
	RF_UNLOCK_QUEUE_MUTEX(queue, "DiskIOPromote");
	return (retval);
}

RF_DiskQueueData_t *
rf_CreateDiskQueueData(
    RF_IoType_t typ,
    RF_SectorNum_t ssect,
    RF_SectorCount_t nsect,
    caddr_t buf,
    RF_StripeNum_t parityStripeID,
    RF_ReconUnitNum_t which_ru,
    int (*wakeF) (void *, int),
    void *arg,
    RF_DiskQueueData_t * next,
    RF_AccTraceEntry_t * tracerec,
    void *raidPtr,
    RF_DiskQueueDataFlags_t flags,
    void *kb_proc)
{
	RF_DiskQueueData_t *p;

	RF_FREELIST_GET_INIT(rf_dqd_freelist, p, next, (RF_DiskQueueData_t *), init_dqd);

	p->sectorOffset = ssect + rf_protectedSectors;
	p->numSector = nsect;
	p->type = typ;
	p->buf = buf;
	p->parityStripeID = parityStripeID;
	p->which_ru = which_ru;
	p->CompleteFunc = wakeF;
	p->argument = arg;
	p->next = next;
	p->tracerec = tracerec;
	p->priority = RF_IO_NORMAL_PRIORITY;
	p->AuxFunc = NULL;
	p->buf2 = NULL;
	p->raidPtr = raidPtr;
	p->flags = flags;
	p->b_proc = kb_proc;
	return (p);
}

RF_DiskQueueData_t *
rf_CreateDiskQueueDataFull(
    RF_IoType_t typ,
    RF_SectorNum_t ssect,
    RF_SectorCount_t nsect,
    caddr_t buf,
    RF_StripeNum_t parityStripeID,
    RF_ReconUnitNum_t which_ru,
    int (*wakeF) (void *, int),
    void *arg,
    RF_DiskQueueData_t * next,
    RF_AccTraceEntry_t * tracerec,
    int priority,
    int (*AuxFunc) (void *,...),
    caddr_t buf2,
    void *raidPtr,
    RF_DiskQueueDataFlags_t flags,
    void *kb_proc)
{
	RF_DiskQueueData_t *p;

	RF_FREELIST_GET_INIT(rf_dqd_freelist, p, next, (RF_DiskQueueData_t *), init_dqd);

	p->sectorOffset = ssect + rf_protectedSectors;
	p->numSector = nsect;
	p->type = typ;
	p->buf = buf;
	p->parityStripeID = parityStripeID;
	p->which_ru = which_ru;
	p->CompleteFunc = wakeF;
	p->argument = arg;
	p->next = next;
	p->tracerec = tracerec;
	p->priority = priority;
	p->AuxFunc = AuxFunc;
	p->buf2 = buf2;
	p->raidPtr = raidPtr;
	p->flags = flags;
	p->b_proc = kb_proc;
	return (p);
}

void
rf_FreeDiskQueueData(p)
	RF_DiskQueueData_t *p;
{
	RF_FREELIST_FREE_CLEAN(rf_dqd_freelist, p, next, clean_dqd);
}


text:
using crostini::mojom::InstallerState;

namespace extensions {

namespace {

const char kCursorHide[] = "\x1b[?25l";
const char kCursorShow[] = "\x1b[?25h";
const char kColor0Normal[] = "\x1b[0m";  // Default.
const char kColor1RedBright[] = "\x1b[1;31m";
const char kColor2GreenBright[] = "\x1b[1;32m";
const char kColor3Yellow[] = "\x1b[33m";
const char kColor5Purple[] = "\x1b[35m";
const char kEraseInLine[] = "\x1b[K";
const char kSpinner[] = "|/-\\";
const int kMaxStage = 9;

std::string MoveForward(int i) {
  return base::StringPrintf("\x1b[%dC", i);
}

}  // namespace

CrostiniStartupStatus::CrostiniStartupStatus(
    base::RepeatingCallback<void(const std::string&)> print,
    bool verbose)
    : print_(std::move(print)), verbose_(verbose) {
}

CrostiniStartupStatus::~CrostiniStartupStatus() = default;

void CrostiniStartupStatus::OnCrostiniRestarted(
    crostini::CrostiniResult result) {
  if (result != crostini::CrostiniResult::SUCCESS) {
    PrintAfterStage(
        kColor1RedBright,
        base::StringPrintf("Error starting penguin container: %d\r\n", result));
  } else {
    if (verbose_) {
      stage_index_ = kMaxStage + 1;  // done.
      PrintStage(kColor2GreenBright,
                 base::StrCat({l10n_util::GetStringUTF8(
                                   IDS_CROSTINI_TERMINAL_STATUS_READY),
                               "\r\n"}));
    }
  }
  Print(
      base::StringPrintf("\r%s%s%s", kEraseInLine, kColor0Normal, kCursorShow));
}

void CrostiniStartupStatus::ShowProgressAtInterval() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  // Wait one interval before showing progress.
  if (spinner_index_ > 0) {
    PrintProgress();
  }
  ++spinner_index_;
  base::PostDelayedTask(
      FROM_HERE, {content::BrowserThread::UI},
      base::BindOnce(&CrostiniStartupStatus::ShowProgressAtInterval,
                     weak_factory_.GetWeakPtr()),
      base::TimeDelta::FromMilliseconds(300));
}

void CrostiniStartupStatus::OnStageStarted(InstallerState stage) {
  stage_ = stage;
  if (stage_index_ < kMaxStage) {
    ++stage_index_;
  }
  if (!verbose_) {
    return;
  }
  static base::NoDestructor<base::flat_map<InstallerState, std::string>>
      kStartStrings({
          {InstallerState::kStart,
           l10n_util::GetStringUTF8(IDS_CROSTINI_TERMINAL_STATUS_START)},
          {InstallerState::kInstallImageLoader,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_INSTALL_IMAGE_LOADER)},
          {InstallerState::kStartConcierge,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_START_CONCIERGE)},
          {InstallerState::kCreateDiskImage,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_CREATE_DISK_IMAGE)},
          {InstallerState::kStartTerminaVm,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_START_TERMINA_VM)},
          {InstallerState::kCreateContainer,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_CREATE_CONTAINER)},
          {InstallerState::kSetupContainer,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_SETUP_CONTAINER)},
          {InstallerState::kStartContainer,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_START_CONTAINER)},
          {InstallerState::kFetchSshKeys,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_FETCH_SSH_KEYS)},
          {InstallerState::kMountContainer,
           l10n_util::GetStringUTF8(
               IDS_CROSTINI_TERMINAL_STATUS_MOUNT_CONTAINER)},
      });
  const std::string& stage_string = (*kStartStrings)[stage];
  PrintStage(kColor3Yellow, stage_string);
}

void CrostiniStartupStatus::OnContainerDownloading(int32_t download_percent) {
  if (download_percent % 8 == 0) {
    PrintAfterStage(kColor3Yellow, ".");
  }
}

void CrostiniStartupStatus::Print(const std::string& output) {
  print_.Run(output);
}

void CrostiniStartupStatus::InitializeProgress() {
  if (progress_initialized_) {
    return;
  }
  progress_initialized_ = true;
  Print(base::StringPrintf("%s%s[%s] ", kCursorHide, kColor5Purple,
                           std::string(kMaxStage, ' ').c_str()));
}

void CrostiniStartupStatus::PrintProgress() {
  InitializeProgress();
  Print(base::StringPrintf("\r%s%s%c", MoveForward(stage_index_).c_str(),
                           kColor5Purple, kSpinner[spinner_index_ & 0x3]));
}

void CrostiniStartupStatus::PrintStage(const char* color,
                                       const std::string& output) {
  DCHECK_GE(stage_index_, 1);
  InitializeProgress();
  std::string progress(stage_index_ - 1, '=');
  Print(base::StringPrintf("\r%s[%s%s%s%s%s ", kColor5Purple, progress.c_str(),
                           MoveForward(3 + (kMaxStage - stage_index_)).c_str(),
                           kEraseInLine, color, output.c_str()));
  end_of_line_index_ = 4 + kMaxStage + output.size();
}

void CrostiniStartupStatus::PrintAfterStage(const char* color,
                                            const std::string& output) {
  InitializeProgress();
  Print(base::StringPrintf("\r%s%s%s", MoveForward(end_of_line_index_).c_str(),
                           color, output.c_str()));
  end_of_line_index_ += output.size();
}

}  // namespace extensions


text:
TcpConnection::TcpConnection(boost::asio::io_service& io_service) :
  m_socket(io_service)
{
}

//-----------------------------------------------------------------------------
// Interface


text:
package com.netbrasoft.gnuob.application.page;

import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.netbrasoft.gnuob.application.panel.LoginPanel;

public class SignInPage extends BasePage {

  private static final String SIGN_IN_PANEL_ID = "signInPanel";

  private static final long serialVersionUID = -8080808937122686622L;

  private final LoginPanel loginPanel;

  public SignInPage() {
    this(null);
  }

  public SignInPage(final PageParameters parameters) {
    loginPanel = new LoginPanel(SIGN_IN_PANEL_ID);
  }

  @Override
  protected void onInitialize() {
    add(loginPanel.setOutputMarkupId(true));
    super.onInitialize();
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<entity class-name="ejb_generated.CfIndicName" label="Indicator Name" name="CFINDICNAME">
<attributes>
<column-attribute field-name="id" hidden="true" key="true" label="ID" length="50" name="id" type="java.lang.Long"/>
<column-attribute field-name="a_name" hidden="false" key="false" label="Name" length="255" name="a_name" precision="0" type="java.lang.String"/>
<zoom-attribute class-name="ejb_generated.CfLang" field-name="cfindicname_language" label="Language" name="cfindicname_language" zoomed-by="id">
<column-ref label="Language ID" name="id"/>
</zoom-attribute>
<zoom-attribute class-name="ejb_generated.CfIndic" field-name="cfindicname_indicator" label="Indicator" name="cfindicname_indicator" zoomed-by="id">
<column-ref label="Indicator ID" name="id"/>
</zoom-attribute>
<column-attribute enum="TranslationKindIndicator_nameEnum" field-name="a_translation_kind" hidden="false" key="false" label="Translation Kind" length="1" name="a_translation_kind" precision="0" type="java.lang.String"/>
</attributes>
</entity>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Cirrious.MvvmCross.ViewModels;
using MvvmCross.Plugins.Messenger;
using MyHealth.Client.Core.Model;
using MyHealth.Client.Core.ServiceAgents;
using MyHealth.Client.Core.Extensions;
using System.Globalization;
using MyHealth.Client.Core.Services;

namespace MyHealth.Client.Core
{
    public class NewAppointmentViewModel : BaseViewModel
    {
        static readonly int AmountOfDoctors = 10;
        static readonly string ValidationMessage = "Please, choose speciality, Doctor, date and hour.";
        static readonly string ValidationTitle = "Missing information";
        static readonly string OkText = "OK";

        readonly IMyHealthClient client;
        readonly IDialogService dialogService;

        Doctor _selectedDoctor;
        DateTime _selectedDate;
        int _waitingTimeAvg;
        DateTime _selectedAppointmentDateAndHour;
        ObservableCollection<Doctor> _doctors;
        ObservableCollection<string> _possibleHours;
        string _selectedHour;
        Specialities _selectedSpeciality;
        List<Specialities> _availableSpecialities;
        bool _isEverythingCorrectlyFilled;
        Random _random;
        IEnumerable<Office365.Event> _patientEvents;

        #region Properties

        public Doctor SelectedDoctor
        {
            get { return _selectedDoctor; }
            set
            {
                if (value != _selectedDoctor)
                {
                    _selectedDoctor = value;
                    RaisePropertyChanged(() => SelectedDoctor);

                    SelectedDate = DateTime.Today;
                }
            }
        }

        public ObservableCollection<string> PossibleHours
        {
            get { return _possibleHours; }
            set { _possibleHours = value; RaisePropertyChanged(() => PossibleHours); }
        }

        public string SelectedHour
        {
            get { return _selectedHour; }
            set
            {
                if (value != _selectedHour)
                {
                    _selectedHour = value;
                    _selectedAppointmentDateAndHour = SelectedDate.WithTime(_selectedHour);
                    IsEverythingCorrectlyFilled = !string.IsNullOrWhiteSpace(_selectedHour);
                    RaisePropertyChanged(() => SelectedHour);
                }
            }
        }

        public List<Specialities> AvailableSpecialities
        {
            get { return _availableSpecialities; }
        }

        public Specialities SelectedSpeciality
        {
            get { return _selectedSpeciality; }
            set
            {
                if (value != _selectedSpeciality)
                {
                    _selectedSpeciality = value;

                    RaisePropertyChanged(() => SelectedSpeciality);

                    SelectedDoctor = null;
                    GetDoctorsForSpecialtyAsync(_selectedSpeciality).Forget();
                }
            }
        }

        public ObservableCollection<Doctor> Doctors
        {
            get { return _doctors; }
            set { _doctors = value; RaisePropertyChanged(() => Doctors); }
        }

        public DateTime SelectedDate
        {
            get
            {
                return _selectedDate;
            }
            set
            {
                _selectedDate = value;
                GetAppointmentTimesAsync().Forget();
            }
        }

        public int WaitingTimeAvg
        {
            get
            {
                return _waitingTimeAvg;
            }
            set
            {
                _waitingTimeAvg = value;
                RaisePropertyChanged(() => WaitingTimeAvg);
            }
        }

        public bool IsEverythingCorrectlyFilled
        {
            get { return _isEverythingCorrectlyFilled; }
            set
            {
                _isEverythingCorrectlyFilled = value;
                RaisePropertyChanged(() => IsEverythingCorrectlyFilled);
            }
        }

        public IEnumerable<Office365.Event> PatientEvents
        {
            get { return _patientEvents; }
            set
            {
                _patientEvents = value;
                RaisePropertyChanged(() => PatientEvents);
            }
        }

        #endregion Properties

        #region Commands

        public IMvxCommand AcceptCommand
        {
            get
            {
                return new MvxCommand(async () =>
                    {
                        if (SelectedDoctor == null || SelectedDate == null || SelectedHour == null)
                        {
                            await dialogService.AlertAsync(ValidationMessage,
                                ValidationTitle,
                                OkText);
                            return;
                        }

                        await CreateNewAppointmentAsync();

                        Close(this);
                    });
            }
        }

        public IMvxCommand CancelCommand
        {
            get { return new MvxCommand(() => Close(this)); }
        }

        public IMvxCommand BackCommand
        {
            get { return new MvxCommand(() => Close(this)); }
        }

        #endregion Commands

        public NewAppointmentViewModel(IMyHealthClient client, IMvxMessenger messenger, IDialogService dlgSvc)
            : base(messenger)
        {
            this.client = client;
            this.dialogService = dlgSvc;

            var specialities = Enum.GetValues(typeof(Specialities));
            // Let's give our user the specialities ordered alphabetically :-)
            _availableSpecialities = specialities.OfType<Specialities>()
                 .OrderBy(s => s.ToString())
                 .ToList();

            Doctors = new ObservableCollection<Doctor>();

            _random = new Random();
        }

        public override void Start()
        {
            base.Start();

            ReloadDataAsync().Forget();
        }

        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            SelectedSpeciality = Specialities.Cardiologist;
            PossibleHours = new ObservableCollection<string>();

            var tenant = await client.TenantsService.GetAsync();
            WaitingTimeAvg = tenant.WaitTimeAvg;
        }

        async Task CreateNewAppointmentAsync()
        {
            try
            {
                IsBusy = true;

                var patient = await client.PatientsService.GetAsync(
                    AppSettings.CurrentPatientId);
                int roomNumber = _random.Next(AppSettings.MinimumRoomNumber,
                        AppSettings.MaximumRoomNumber);
                var appointment = new ClinicAppointment
                {
                    PatientId = patient.PatientId,
                    DoctorId = _selectedDoctor.DoctorId,
                    TenantId = _selectedDoctor.TenantId,
                    Speciality = _selectedDoctor.Speciality,
                    DateTime = _selectedAppointmentDateAndHour,
                    Description = AppSettings.DefaultAppointmentDescription,
                    RoomNumber = roomNumber
                };

                await client.AppointmentsService.PostAsync(appointment);

                if (AppSettings.OutlookIntegration)
                {
                    // Add the event to the patient's calendar
                    await MicrosoftGraphService.AddEventAsync(
                        subject: "Clinic Appointment with " + _selectedDoctor.Name,
                        startTime: _selectedAppointmentDateAndHour,
                        endTime: _selectedAppointmentDateAndHour + TimeSpan.FromMinutes(45),
                        attendeeEmails: new string[0],
                        description: AppSettings.DefaultAppointmentDescription,
                        locationDisplayName: $"Room {roomNumber}");

                    // Add the events to the doctor's calendar.
                    var @event = new Office365.Appointment
                    {
                        DoctorPrincipalName = _selectedDoctor.Email,
                        Subject = "Clinic Appointment with " + patient.Name,
                        Description = AppSettings.DefaultAppointmentDescription,
                        PatientEmail = patient.Email,
                        Start = _selectedAppointmentDateAndHour,
                        LengthInMinutes = 45,
                        Location = $"Room {roomNumber}"
                    };

                    //TODO: Uncomment to enable doctor calendar integration.
                    //await client.DoctorCalendarService.PostAsync(@event);

                }

                await dialogService.AlertAsync("The appointment was created successfully.",
                    "New appointment", OkText);
            }
            finally
            {
                IsBusy = false;
            }
        }

        async Task GetDoctorsForSpecialtyAsync(Specialities speciality)
        {
            try
            {
                IsBusy = true;

                Doctors.Clear();

                var doctors = await client.DoctorsService.GetBySpecialityAsync(
                    speciality,
                    AmountOfDoctors);

                Doctors.AddRange(doctors);
            }
            finally
            {
                IsBusy = false;
            }
        }

        void AddFixedHoursForDemo()
        {
            var hours = new List<string>(3);
            hours.Add("9:00 am");
            hours.Add("9:15 am");
            hours.Add("9:30 am");
            PossibleHours.AddRange(hours);
        }

        async Task AddHoursRetrievedFromAPIAsync()
        {
            var hours = new List<DateTime>();
            hours = await client.DoctorsService.GetAvailableHoursAsync(_selectedDoctor.DoctorId, _selectedDate.Day, _selectedDate.Month, _selectedDate.Year);
            var fi = new DateTimeFormatInfo {
                AMDesignator = "am",
                PMDesignator = "pm"
            };
            var actualHours = new List<string>();
            foreach (var hour in hours)
            {
                var date = hour.ToLocalTime().ToString("h:mm tt", fi);
                actualHours.Add(date);
            }
            // Remove times that are conflicting with doctor's calendar.
            if (AppSettings.OutlookIntegration)
            {
                // Get patient events from calendar.
                //TODO: Use Rest api instead to workaround issue. Revert to Microsoft Graph Service after the issue is resolved.
                //events = await MicrosoftGraphService.GetEventsAsync(_selectedDate);
                PatientEvents = await MicrosoftGraphService.GetEventsAsync(_selectedDate);
                //TODO: uncomment the following to enable doctor calendar integration.
                //if (_selectedDoctor != null)
                //{
                //    var doctorEvents = await client.DoctorCalendarService.GetDoctorEventsByDayAsync(_selectedDoctor.Email, _selectedDate);
                //    var filteredHours = RemoveConflictingHours(hours, doctorEvents, fi);
                //    actualHours.Clear();
                //    actualHours.AddRange(filteredHours);
                //}
            }
            PossibleHours.AddRange(actualHours);
        }

        async Task GetAppointmentTimesAsync()
        {
            if (_selectedDoctor == null || PossibleHours == null)
                return;

            try
            {
                IsBusy = true;

                PossibleHours.Clear();

                if (_selectedDate.Year == 2015 &&
                    _selectedDate.Month == 11 &&
                    _selectedDate.Day == 19)
                {
                    AddFixedHoursForDemo();
                }
                else
                {
                    await AddHoursRetrievedFromAPIAsync();
                }
            }
            finally
            {
                SelectedHour = PossibleHours.FirstOrDefault();
                IsBusy = false;
            }
        }

        private IEnumerable<string> RemoveConflictingHours(IEnumerable<DateTime> originalHours, IEnumerable<Office365.Event_Beta> doctorEvents, DateTimeFormatInfo fi)
        {
            var filteredHours = new List<string>();
            // Some doctors are not in the Azure AD so the above api could not find any info about their calendars.
            if (doctorEvents.Count() != 0)
            {
                foreach (var hourStart in originalHours)
                {
                    var hourEnd = hourStart + TimeSpan.FromMinutes(15);
                    bool conflicting = false;
                    foreach (var @event in doctorEvents)
                    {
                        if ((@event.Start.DateTime <= hourStart && hourStart <= @event.End.DateTime) ||
                            (@event.Start.DateTime <= hourEnd && hourEnd <= @event.End.DateTime))
                        {
                            conflicting = true;
                            break;
                        }
                    }
                    if (!conflicting)
                    {
                        var date = hourStart.ToString("h:mm tt", fi);
                        filteredHours.Add(date);
                    }
                }
            }
            else
            {
                filteredHours.AddRange(PossibleHours);
            }

            return filteredHours;
        }
    }
}


text:
/**
 * Astrid data model classes and ContentResolver data access objects
 */
package com.todoroo.astrid.data;


text:
package com.alwaysallthetime.messagebeast.db;

import android.net.Uri;

import com.alwaysallthetime.adnlib.data.File;

/**
 * A PendingFile represents a local File that is pending upload to App.net.
 *
 * @see http://developers.app.net/docs/resources/file/
 */
public class PendingFile {
    private String mId;
    private Uri mUri;
    private String mType;
    private String mName;
    private String mMimeType;
    private String mKind;
    private boolean mIsPublic;
    private int mNumSendAttempts;

    /**
     * Construct a new PendingFile.
     *
     * @param id the id of the PendingFile, typically a UUID. This is unrelated to the id of the
     *           File that will be assigned to the File by the App.net servers upon successful
     *           upload.
     * @param uri the Uri corresponding to the file's location on disk
     * @param type the type to be set on the App.net File's "type" field.
     * @param name the name of the App.net File
     * @param mimeType the MIME type of the file
     * @param kind the kind of the App.net file
     * @param isPublic true if the File is public, false otherwise
     * @param sendAttempts the number of times we have attempted to send the PendingFile with this id
     */
    public PendingFile(String id, Uri uri, String type, String name, String mimeType, String kind, boolean isPublic, int sendAttempts) {
        mId = id;
        mUri = uri;
        mType = type;
        mName = name;
        mMimeType = mimeType;
        mKind = kind;
        mIsPublic = isPublic;
        mNumSendAttempts = sendAttempts;
    }

    /**
     * Get the id of the PendingFile. This is unrelated to the id of the
     * File that will be assigned to the File by the App.net servers upon successful
     * upload.
     *
     * @return the id of the PendingFile, typically a UUID
     */
    public String getId() {
        return mId;
    }

    /**
     * Get the Uri corresponding to the file's location on disk.
     *
     * @return the Uri corresponding to the file's location on disk.
     */
    public Uri getUri() {
        return mUri;
    }

    /**
     * Get the type to be set on the App.net File's "type" field.
     *
     * @return the type to be set on the App.net File's "type" field.
     */
    public String getType() {
        return mType;
    }

    /**
     * Get the name to be assigned to the App.net File object
     *
     * @return the name to be assigned to the App.net File object
     */
    public String getName() {
        return mName;
    }

    /**
     * Get the MIME type of the file.
     *
     * @return the MIME type of the file.
     */
    public String getMimeType() {
        return mMimeType;
    }

    /**
     * Get the File kind
     *
     * @return the File kind
     */
    public String getKind() {
        return mKind;
    }

    /**
     * @return true if the File should be public, false otherwise.
     */
    public boolean isPublic() {
        return mIsPublic;
    }

    /**
     * Get a File object to use when sending the POST request to App.net
     *
     * @return a File object to use when sending the POST request to App.net
     */
    public File getFile() {
        return new File(mKind, mType, mName, mIsPublic);
    }

    /**
     * Get the number of times that we have attempted and failed to upload this PendingFile.
     *
     * @return the number of times that we have attempted and failed to upload this PendingFile
     */
    public int getNumSendAttempts() {
        return mNumSendAttempts;
    }

    /**
     * Increment the number of send attempts.
     *
     * @return the number of times (post-increment) that we have attempted and failed to upload this PendingFile
     */
    public int incrementSendAttempts() {
        mNumSendAttempts++;
        return mNumSendAttempts;
    }
}


text:
<?php
if ($this->session->flashdata('success') != '') {
    ?>

        <?php echo $this->session->flashdata('success'); ?>

    <?php
}
?>
<?php
if ($this->session->flashdata('error') != '') {
    ?>

        <?php
        echo $this->session->flashdata('error');
        ?>

    <?php
}
?>

 Login to your Account

 Creat New Account

                <form id="LoginForm" method="POST">

                        Your Email
                        <input type="text" name="user_name" id="user_name" placeholder="Email" placeholder="johndoe@yourmail.com" />

                        Your Password
                        <input type="password" name="password" id="password" placeholder="password" />

                            <input id="check1" type="checkbox" name="check" value="check1">
                            Remember Me

                        Forgot my Password

                        <button type="submit" name="">Login</button>

Don't you have an account? Register Now! it's really simple and you can start enjoying all the benefits!

                </form>

                <form id="RegisterForm" method="POST" action="<?php echo base_url() . 'register'; ?>">

                            First Name
                            <input type="text" name="first_name" id="first_name" placeholder="First Name" />

                            Last Name
                            <input type="text" name="last_name" id="last_name" placeholder="Last Name" />

                        Your Email
                        <input type="text"  name="email" id="email" placeholder="johndoe@yourmail.com" />

                        Password
                        <input type="password" name="password" id="password" placeholder="Your Password" />

                            <input id="terms_check" type="checkbox" name="terms" value="1">
                            I accept the Terms and Conditions of the website

                        <button id="register" type="submit" name="">Complete Registration!</button>

                </form>


text:
package p2p

const Version = "0.3.5" // minor fixes


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Mesembryanthemum bicolor L.

### Remarks
null


text:
<?php

namespace Hubzero\Session\Storage;

use Hubzero\Session\Store;
use Exception;

/**
 * APC session storage handler
 *
 * Inspired by Joomla's JSessionStorageApc class
 */
class Apc extends Store
{
	/**
	 * Key prefix
	 *
	 * @var  string
	 */
	private $prefix  = 'sess_';

	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters
	 * @return  void
	 */
	public function __construct($options = array())
	{
		if (!self::isAvailable())
		{
			throw new Exception(\Lang::txt('JLIB_SESSION_APC_EXTENSION_NOT_AVAILABLE'));
		}

		if (isset($options['prefix']))
		{
			$this->prefix = $options['prefix'];
		}

		parent::__construct($options);
	}

	/**
	 * Read the data for a particular session identifier from the
	 * SessionHandler backend.
	 *
	 * @param   string  $session_id  The session identifier.
	 * @return  string  The session data.
	 */
	public function read($session_id)
	{
		return (string) apc_fetch($this->key($session_id));
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string   $session_id    The session identifier.
	 * @param   string   $session_data  The session data.
	 * @return  boolean  True on success, false otherwise.
	 */
	public function write($session_id, $session_data)
	{
		return apc_store($this->key($session_id), $session_data, ini_get("session.gc_maxlifetime"));
	}

	/**
	 * Destroy the data for a particular session identifier in the SessionHandler backend.
	 *
	 * @param   string   $id  The session identifier.
	 * @return  boolean  True on success, false otherwise.
	 */
	public function destroy($session_id)
	{
		return apc_delete($this->key($session_id));
	}

	/**
	 * Build the storage key
	 *
	 * @param   string  $id  The session identifier.
	 * @return  string
	 */
	protected function key($id)
	{
		return $this->prefix . $id;
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 */
	public static function isAvailable()
	{
		return extension_loaded('apc');
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="cctags" default="build">
	<description>CC NFC Tags</description>

	<target name="build" depends="copy-to-mcp, recompile, reobfuscate, build-jar, clean-mcp" />

	<target name="buildenvsetup">
		<property environment="env" />
		<property name="modname" value="cctags" />
		<property file="local.properties" />

		<fail message="mcp.home not defined in 'local.properties'" unless="mcp.home" />
		<fail message="cc-api.src not defined in 'local.properties'" unless="cc-api.src" />

		<condition property="python.exe" value="${mcp.home}/runtime/bin/python/python_mcp" else="python">
			<os family="Windows" />
		</condition>
		<property name="mcp.obfoutput" location="${mcp.home}/reobf" />
		<property name="mcp.obfoutput.classes" location="${mcp.obfoutput}/minecraft" />
		<property name="mcp.src.dir" location="${mcp.home}/src/minecraft" />
		<property name="mcp.bin.dir" location="${mcp.home}/bin/minecraft" />
		<property name="deploy.dir" location="${user.home}/.minecraft/mods" />
		<property name="resource.dir" location="${basedir}/resources" />
		<property name="jar.dir" location="${basedir}/target" />
		<property name="lua.dir" location="${basedir}/lua" />

		<property name="icon.package" value="assets/cctags/textures/items" />
		<property name="icon.dir" value="${resource.dir}/${icon.package}" />

		<property name="lua.package" value="boq/cctags/lua" />
		<property name="lua.files.dir" value="${lua.dir}/${lua.package}" />
	</target>

	<target name="copy-to-mcp" depends="buildenvsetup">
		<copy todir="${mcp.src.dir}" overwrite="true" verbose="true">
			<fileset dir="${basedir}/core" includes="**/*.java" />
			<fileset dir="${basedir}/utils" includes="**/*.java" />
			<fileset dir="${cc-api.src}" includes="**/*.java" />
		</copy>
	</target>

	<target name="recompile" depends="buildenvsetup">
		<exec executable="${python.exe}" dir="${mcp.home}" failonerror="true">
			<arg value="${mcp.home}/runtime/recompile.py" />
		</exec>
	</target>

	<target name="reobfuscate" depends="buildenvsetup">
		<exec executable="${python.exe}" dir="${mcp.home}">
			<arg value="${mcp.home}/runtime/reobfuscate.py" />
			<arg value="--srgnames" />
		</exec>
	</target>

	<target name="run-python-generate" depends="buildenvsetup">
		<exec executable="${python.exe}" dir="${basedir}" failonerror="true">
			<arg value="${basedir}/generate.py" />
			<arg value="${mcp.home}" />
			<arg value="${jar.dir}" />
			<arg value="${modname}" />
		</exec>
	</target>

	<target name="run-python-update" depends="buildenvsetup">
		<exec executable="${python.exe}" dir="${basedir}" failonerror="true">
			<arg value="${basedir}/update.py" />
			<arg value="${icon.dir}" />
			<arg value="${lua.files.dir}" />
		</exec>
	</target>

	<target name="build-jar" depends="buildenvsetup">
		<delete dir="${jar.dir}" />
		<mkdir dir="${jar.dir}" />

		<antcall target="run-python-update" />
		<antcall target="run-python-generate" />

	    <property file="version.properties" />
	    <property name="jarname" value="${modname}-${cctags.version.tag}" />

		<jar destfile="${basedir}/target/${jarname}.jar">
			<fileset dir="${mcp.obfoutput.classes}" includes="boq/**/*.class" excludes="net/**/*" />
			<fileset dir="${basedir}/core" includes="mcmod.info" />
			<fileset dir="${basedir}" includes="version.properties" />

			<fileset dir="${lua.dir}"  />
			<fileset dir="${resource.dir}">
				<include name="**/*.png" />
				<include name="**/*.lang" />
				<include name="**/*.mcmeta" />
				<include name="**/*.txt" />
			</fileset>
		</jar>
	</target>

	<target name="clean-mcp" depends="buildenvsetup">
		<delete verbose="true" includeEmptyDirs="true" failonerror="false">
			<fileset dir="${mcp.src.dir}/boq" />
			<fileset dir="${mcp.src.dir}/dan200" />
			<fileset dir="${mcp.bin.dir}/boq" />
			<fileset dir="${mcp.bin.dir}/dan200" />
		</delete>
	</target>
</project>


text:
function createUUID() {
    var dt = new Date().getTime();
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (dt + Math.random() * 16) % 16 | 0;
        dt = Math.floor(dt / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

// Set 'default' hrid on the default organization.
organization = db.getCollection('organizations').findOne({"_id": "DEFAULT"});

if (!organization.hrids || organization.hrids.length === 0) {
    organization.hrids = ['default'];
    db.getCollection('organizations').update({"_id": "DEFAULT"}, organization);
}

// Set 'default' hrid on the default environment.
environment = db.getCollection('environments').findOne({"_id": "DEFAULT"});

if (!environment.hrids || environment.hrids.length === 0) {
    environment.hrids = ['default'];
    db.getCollection('environments').update({"_id": "DEFAULT"}, environment);
}

// Update ORGANIZATION_USER role adding the ENVIRONMENT['LIST'] permission.
organizationUserRole = db.getCollection("roles")
    .findOne({"name": "ORGANIZATION_USER", "referenceType": "ORGANIZATION", "referenceId": "DEFAULT"});

if (organizationUserRole != null) {
    if (!organizationUserRole.permissionAcls['ENVIRONMENT']) {
        organizationUserRole.permissionAcls['ENVIRONMENT'] = ['LIST']
    } else if (!organizationUserRole.permissionAcls['ENVIRONMENT'].includes('LIST')) {
        organizationUserRole.permissionAcls['ENVIRONMENT'].push('LIST');
    }
    db.getCollection("roles").update({'_id': organizationUserRole._id}, organizationUserRole);
}

// Create ENVIRONMENT_USER role if not already exists.
environmentUserRole = db.getCollection("roles")
    .findOne({"name": "ENVIRONMENT_USER", "referenceType": "ORGANIZATION", "referenceId": "DEFAULT"});

if (environmentUserRole == null) {
    let environmentUserRoleId = createUUID();
    db.getCollection("roles").insert({
        _id: environmentUserRoleId,
        assignableType: "ENVIRONMENT",
        createdAt: ISODate(),
        defaultRole: true,
        name: "ENVIRONMENT_USER",
        permissionAcls: {
            DOMAIN: ["LIST"],
            ENVIRONMENT: ["READ"],
        },
        referenceId: "DEFAULT",
        referenceType: "ORGANIZATION",
        system: false,
        updatedAt: ISODate(),
    });

    // Assign ENVIRONMENT_USER role to all existing users.
    db.getCollection('users')
        .find({"referenceType": "ORGANIZATION", "referenceId": "DEFAULT"})
        .forEach(function (user) {
            db.getCollection("memberships").insert({
                "_id": createUUID(),
                "createdAt": ISODate(),
                "memberId": user._id,
                "memberType": "USER",
                "referenceId": "DEFAULT",
                "referenceType": "ENVIRONMENT",
                "role": environmentUserRoleId,
                "updatedAt": ISODate()
            });
        });
}

// Create ENVIRONMENT_OWNER role if not already exists.
environmentOwnerRole = db.getCollection("roles")
    .findOne({"name": "ENVIRONMENT_OWNER", "referenceType": "ORGANIZATION", "referenceId": "DEFAULT"});

if (environmentOwnerRole == null) {
    db.getCollection("roles").insert({
        _id: createUUID(),
        assignableType: "ENVIRONMENT",
        createdAt: ISODate(),
        defaultRole: true,
        name: "ENVIRONMENT_OWNER",
        permissionAcls: {
            DOMAIN_MEMBER: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_SCIM: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_IDENTITY_PROVIDER: [
                "UPDATE",
                "LIST",
                "READ",
                "DELETE",
                "CREATE",
            ],
            APPLICATION_SETTINGS: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            ENVIRONMENT: ["READ"],
            APPLICATION_EMAIL_TEMPLATE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_REPORTER: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_FORM: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_EXTENSION_GRANT: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_FORM: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_SCOPE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_SETTINGS: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_ROLE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_IDENTITY_PROVIDER: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_ANALYTICS: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_UMA_SCOPE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_EXTENSION_POINT: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_CERTIFICATE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_GROUP: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_USER: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_OPENID: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_AUDIT: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_FACTOR: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_MEMBER: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_OPENID: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_CERTIFICATE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_UMA: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_FACTOR: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            DOMAIN_EMAIL_TEMPLATE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
            APPLICATION_RESOURCE: ["UPDATE", "LIST", "READ", "DELETE", "CREATE"],
        },
        referenceId: "DEFAULT",
        referenceType: "ORGANIZATION",
        system: false,
        updatedAt: ISODate(),
    });
}


text:
#include "Camera2D.h"
#include <lucid/math/Matrix.h>
#include <lucid/core/Reader.h>

namespace /* anonymous */
{

	enum TYPE
	{
		TYPE_PERSPECTIVE = 0,
		TYPE_ORTHOGRAPHIC,
	};

	template<class T> inline T read(::lucid::core::Reader &reader)
	{
		T value = T();
		reader.read(&value, sizeof(T));
		return value;
	}

}

namespace lucid {
namespace gigl {

	Camera2D::Camera2D()
	{
	}

	Camera2D::Camera2D(::lucid::core::Reader &reader)
	{
		TYPE type;
		reader.read(&type, sizeof(TYPE));

		if (TYPE_PERSPECTIVE == type)
		{
			float32_t fov = read<float32_t>(reader);
			float32_t aspect = read<float32_t>(reader);
			float32_t znear = read<float32_t>(reader);
			float32_t zfar = read<float32_t>(reader);

			initPerspective(fov, aspect, znear, zfar);
		}
		else
		{
			float32_t width = read<float32_t>(reader);
			float32_t height = read<float32_t>(reader);
			float32_t znear = read<float32_t>(reader);
			float32_t zfar = read<float32_t>(reader);

			initOrthographic(width, height, znear, zfar);
		}

		::lucid::gal::Vector3 position = read<::lucid::gal::Vector3>(reader);
		::lucid::gal::Vector3 target = read<::lucid::gal::Vector3>(reader);
		::lucid::gal::Vector3 up = read<::lucid::gal::Vector3>(reader);

		look(position, target, up);
	}

	Camera2D::~Camera2D()
	{
	}

	void Camera2D::initOrthographic(float32_t width, float32_t height, float32_t znear, float32_t zfar)
	{
		_projMatrix = ::lucid::math::orthographic(width, height, znear, zfar);
		_viewProjMatrix = _projMatrix * _viewMatrix;
	}

	void Camera2D::initOrthographic(float32_t left, float32_t right, float32_t bottom, float32_t top, float32_t znear, float32_t zfar)
	{
		_projMatrix = ::lucid::math::orthographic(left, right, bottom, top, znear, zfar);
		_viewProjMatrix = _projMatrix * _viewMatrix;
	}

	void Camera2D::initPerspective(float32_t fov, float32_t aspect, float32_t znear, float32_t zfar)
	{
		_projMatrix = ::lucid::math::perspective(fov, aspect, znear, zfar);
		_viewProjMatrix = _projMatrix * _viewMatrix;
	}

	void Camera2D::initPerspective(float32_t left, float32_t right, float32_t bottom, float32_t top, float32_t znear, float32_t zfar)
	{
		_projMatrix = ::lucid::math::perspective(left, right, bottom, top, znear, zfar);
		_viewProjMatrix = _projMatrix * _viewMatrix;
	}

	void Camera2D::look(::lucid::gal::Vector3 const &eye, ::lucid::gal::Vector3 const &target, ::lucid::gal::Vector3 const &up)
	{
		_position = eye;

		_viewMatrix = ::lucid::math::look(_position, target, up);
		_viewProjMatrix = _projMatrix * _viewMatrix;
	}

}	///	gigl
}	///	lucid


text:
<bill session="115" type="h" number="579" updated="2017-09-26T07:15:42Z">
  <state datetime="2017-01-13">REFERRED</state>
  <status>
    <introduced datetime="2017-01-13"/>
  </status>
  <introduced datetime="2017-01-13"/>
  <titles>
    <title type="short" as="introduced">Muhammad Ali Commemorative Coin Act</title>
    <title type="short" as="introduced">Muhammad Ali Commemorative Coin Act</title>
    <title type="official" as="introduced">To require the Secretary of the Treasury to mint coins in commemoration of Muhammad Ali.</title>
    <title type="display">Muhammad Ali Commemorative Coin Act</title>
  </titles>
  <sponsor bioguide_id="Y000062"/>
  <cosponsors>
    <cosponsor bioguide_id="B001281" joined="2017-06-23"/>
    <cosponsor bioguide_id="B001251" joined="2017-06-28"/>
    <cosponsor bioguide_id="C001072" joined="2017-09-25"/>
    <cosponsor bioguide_id="C001049" joined="2017-06-28"/>
    <cosponsor bioguide_id="C001068" joined="2017-09-25"/>
    <cosponsor bioguide_id="D000627" joined="2017-06-28"/>
    <cosponsor bioguide_id="D000624" joined="2017-06-23"/>
    <cosponsor bioguide_id="E000296" joined="2017-03-28"/>
    <cosponsor bioguide_id="H000324" joined="2017-06-28"/>
    <cosponsor bioguide_id="J000126" joined="2017-06-23"/>
    <cosponsor bioguide_id="K000381" joined="2017-06-23"/>
    <cosponsor bioguide_id="L000551" joined="2017-06-23"/>
    <cosponsor bioguide_id="M001137" joined="2017-03-24"/>
    <cosponsor bioguide_id="M001190" joined="2017-04-06"/>
    <cosponsor bioguide_id="N000147" joined="2017-06-23"/>
    <cosponsor bioguide_id="R000588" joined="2017-06-28"/>
    <cosponsor bioguide_id="R000515" joined="2017-06-23"/>
    <cosponsor bioguide_id="S001183" joined="2017-01-13"/>
    <cosponsor bioguide_id="T000468" joined="2017-06-23"/>
  </cosponsors>
  <actions>
    <action datetime="2017-01-13">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-01-13" state="REFERRED">
      <text>Referred to the House Committee on Financial Services.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSBA" name="House Financial Services" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="s" session="115" relation="identical" number="166"/>
  </relatedbills>
  <subjects>
    <term name="Finance and financial sector"/>
    <term name="Athletes"/>
    <term name="Currency"/>
    <term name="Professional sports"/>
  </subjects>
  <amendments/>
  <summary date="2017-01-13T05:00:00Z" status="Introduced in House">Muhammad Ali Commemorative Coin Act

This bill requires the Department of the Treasury to mint and issue commemorative coins that emblemize the life and legacy of Muhammad Ali.

Surcharges received from the sale of these coins shall be paid to: (1) the Muhammad Ali Center in Louisville, Kentucky; (2) the Muhammad Ali Institute for Peace and Justice at the University of Louisville; and (3) the Muhammad Ali Parkinson Center and Movement Disorder Clinic.</summary>
  <committee-reports/>
</bill>


text:
package org.intellij.images.thumbnail.actions;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;

public interface ThemeFilter {
  ExtensionPointName<ThemeFilter> EP_NAME = ExtensionPointName.create("com.intellij.images.themeFilter");

  String getDisplayName();
  boolean accepts(VirtualFile file);
  boolean isApplicableToProject(Project project);
}


text:
class CalendarController < ApplicationController
  before_action :authenticate_user!
end


text:
from flask.ext.assets import Bundle

common_css = Bundle(
    "../bower_components/bootstrap/dist/css/bootstrap.min.css",
    "css/style.css",
    filters="cssmin",
    output="public/css/common.css"
)

common_js = Bundle(
    "../bower_components/jquery/dist/jquery.min.js",
    "../bower_components/bootstrap/dist/js/bootstrap.min.js",
    "../bower_components/bootbox/bootbox.js",
    Bundle(
        "js/script.js",
        filters="jsmin"
    ),
    output="public/js/common.js"
)


text:
#ifndef DANGDAL_NDV_H
#define DANGDAL_NDV_H

#include <string>
#include <utility>
#include <vector>
#include <complex>

#include <boost/foreach.hpp>

#include <gdal.h>

#include "datatype_conversion.h"

namespace dangdal {

struct NdvInterval : std::pair<double, double> {
	NdvInterval() { }
	NdvInterval(double _min, double _max) :
		std::pair<double, double>(_min, _max) { }
	explicit NdvInterval(const std::string &s);

	template <typename T>
	bool contains(T v) const {
		return v >= first && v <= second;
	}

	template <typename T>
	bool contains(std::complex<T> v) const {
		return v.real() >= first && v.real() <= second;
	}

	bool contains(const void *, GDALDataType) const;
};

struct NdvSlab {
	NdvSlab() { }
	explicit NdvSlab(const std::string &s);

	// an interval for each band, or a single interval for all bands
	std::vector<NdvInterval> range_by_band;
};

class NdvDef {
public:
	static void printUsage();
	explicit NdvDef(std::vector<std::string> &arg_list);
	NdvDef(const GDALDatasetH ds, const std::vector<size_t> &bandlist);
	void debugPrint() const;
	bool empty() const { return slabs.empty(); }
	bool isInvert() const { return invert; }

	void getNdvMask(
		const void *band, GDALDataType dt,
		uint8_t *mask_out, size_t num_pixels
	) const;

	void getNdvMask(
		const std::vector<const void *> &bands,
		const std::vector<GDALDataType> &dt_list,
		uint8_t *mask_out, size_t num_pixels
	) const;

	template <typename T>
	void getNdvMask(
		const std::vector<std::vector<T> > &bands,
		uint8_t *mask_out, size_t num_pixels
	) const {
		GDALDataType dt = GetGDALDataTypeFor<T>::t;

		std::vector<const void *> band_p;
		std::vector<GDALDataType> dt_list;
		BOOST_FOREACH(const std::vector<T> &v, bands) {
			band_p.push_back(reinterpret_cast<const void *>(&v[0]));
			dt_list.push_back(dt);
		}
		getNdvMask(band_p, dt_list, mask_out, num_pixels);
	}

	// For this one, it doesn't matter what T is, it is the GDALDataType that determines how
	// the data will be read from memory (i.e. we cast &bands[i][0] to (void *)).
	template <typename T>
	void getNdvMask(
		const std::vector<std::vector<T> > &bands,
		const std::vector<GDALDataType> &dt_list,
		uint8_t *mask_out, size_t num_pixels
	) const {
		std::vector<const void *> band_p;
		BOOST_FOREACH(const std::vector<T> &v, bands) {
			band_p.push_back(reinterpret_cast<const void *>(&v[0]));
		}
		getNdvMask(band_p, dt_list, mask_out, num_pixels);
	}

	bool invert;
	std::vector<NdvSlab> slabs;
};

} // namespace dangdal

#endif // DANGDAL_NDV_H