text:
var winston = require('winston');

winston.emitErrs = true;

function logger(module) {

    return new winston.Logger({
        transports : [
            new winston.transports.File({
                level: 'debug',
                filename: process.cwd() + '/logs/all.log',
                handleException: true,
                json: true,
                maxSize: 5242880, //5mb
                maxFiles: 2,
                colorize: false
            }),
            new winston.transports.Console({
                level: 'debug',
                label: getFilePath(module),
                handleException: true,
                json: false,
                colorize: true
            })
        ],
        exitOnError: false
    });
}

function getFilePath (module ) {
    //using filename
    return module.filename.split('/').slice(-2).join('/');
}

module.exports = logger;


text:
<form name="catalogSelectModal.form" ng-submit="catalogSelectModal.submit()" novalidate autocomplete="off" oc-pretty-submit>

        <button type="button" class="close" aria-label="Close" ng-click="catalogSelectModal.cancel()">×</button>

Select a replacement catalog

                {{catalogSelectModal.buyers.Items[0].Name}} is using this as a default catalog.

                {{catalogSelectModal.buyers.Items[0].Name}} and {{catalogSelectModal.buyers.Items[1].Name}} are using this as a default catalog.

                {{catalogSelectModal.buyers.Items[0].Name}}, {{catalogSelectModal.buyers.Items[1].Name}} and {{catalogSelectModal.buyers.Items[2].Name}} are using this as a default catalog.

             3">
                {{catalogSelectModal.buyers.Items[0].Name}}, {{catalogSelectModal.buyers.Items[1].Name}} and {{catalogSelectModal.buyers.Items.length - 2}} other buyer organizations are using this as a default catalog.

            Please select a replacement before deleting the catalog.

        <fieldset class="form-group">
            Select a New Default Catalog

                <input placeholder="Select a catalog" class="form-control" id="SelectedDefaultCatalog" name="SelectedDefaultCatalog" type="text" ng-model="catalogSelectModal.replacementDefaultCatalog" required
                    ng-model-options="{debounce:300}"
                    typeahead-min-length="0"
                    typeahead-append-to="'.c-typeahead__results'"
                    typeahead-no-results="catalogSelectModal.noCatalogResults"
                    typeahead-loading="catalogSelectModal.catalogsLoading"
                    typeahead-template-url="oc-catalog-result.html"
                    uib-typeahead="catalog as catalog.Name for catalog in catalogSelectModal.searchCatalogs($viewValue)">

                        No matches found

        </fieldset>

        <button type="submit" class="btn btn-block btn-primary" ng-disabled="catalogSelectModal.form.$invalid" cg-busy="catalogSelectModal.loading">Confirm Replacement</button>

</form>

redpajama_set_name: RedPajamaGithub


text:
FROM ubuntu:14.04
MAINTAINER Marco Wise <marco.wise@stanford.edu>

RUN apt-get update && apt-get install -y \
  apache2 \
  build-essential \
  cpanminus \
  libapache2-mod-perl2 \
  mysql-server \
  perl \
  supervisor \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN ["cpanm", "Class::DBI", "Data::Dumper", "Data::FormValidator", "DateTime", "MIME::Lite", "Spreadsheet::WriteExcel", "Template",	"Text::CSV" ]

RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/mysqld /var/log/supervisor /var/cgi-bin

# enable cgi
RUN ln -s /etc/apache2/mods-available/cgid.load /etc/apache2/mods-enabled/
RUN ln -s /etc/apache2/mods-available/cgid.conf /etc/apache2/mods-enabled/

COPY docker/000-default.conf /etc/apache2/sites-available/000-default.conf

COPY . /var/www/html/

RUN cp /var/www/html/includes/config_sample.txt /var/www/html/includes/config.txt
RUN cp /var/www/html/.htaccess_sample /var/www/html/.htaccess

RUN chmod +x /var/www/html/includes/data/db_init.sh
RUN /var/www/html/includes/data/db_init.sh

COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

EXPOSE 80 3306

CMD ["/usr/bin/supervisord"]


text:
package ondrej.mejzlik.suntrail.configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ondrej.mejzlik.suntrail.R;

import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_CERES;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_EARTH;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_HALLEY;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_INTRO;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_JUPITER;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_MARS;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_MERCURY;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_MOON;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_NEPTUNE;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_SATURN;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_SUN;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_URANUS;
import static ondrej.mejzlik.suntrail.utilities.PlanetIdentifier.PLANET_ID_VENUS;

/**
 * This class holds public static constants used to influence the behavior of the game.
 *

 * GAME ALGORITHM EXPLANATION
 * 1. The player can start the game at any planet. If the game is started on the first or last
 * two planets the direction of the trip is automatically set towards the other end of the Sun
 * trail. Otherwise the player has to select one direction.
 *

 * 2. The player begins the game with a certain amount of credits (can be set in this file).
 * The player is given a small ship Icarus S. Other ships are available on the Moon and Jupiter.
 * The player can buy these ships. When new ship is bought, old ship is automatically sold.
 *

 * 3. There are 11 shops in the game. The first information board does not have a shop, scanning the
 * board opens the information fragment. First shop is on the Sun. Neptune does not have a shop
 * because it is the last planet there is no point in buying anything there. Or vice versa.
 *

 * 4. There are 33 items in the game. Each shop has 3. The number can be expanded but each shop
 * must always have equal amount of items. New items must be added in multiples of 11.
 *

 * 5. Items are assigned random prices from a range which can be configured in this file.
 * The price of each item can either rise or fall before it is sold in another shop. By how much %
 * the price will change can be set in this file. Prices of all items are set to rise initially.
 * Whether the price will fall or rise in the next shop is equally probable.
 * The next movement in price of a given item which is in the player's inventory is set randomly at
 * each stop.
 *

 * 6. In case the user makes many bad choices and the algorithm determines the user will not be
 * able to buy anything in a shop he arrived to, a price of one item is set low enough for the user
 * to be able to buy it. This takes into account what the user can sell in that shop.
 * (TODO: This safety feature can be disabled in a harder mode - not yet implemented.)
 *

 * 7. Different ships have different cargo bay size. This can be set in this file. The size of items
 * in shops is set randomly but a single item can not be larger than currently available maximum
 * cargo bay size.
 *

 * 8. On the last planet which is either the Neptune on the Sun everything is automatically sold.
 * Then based on how much credits the player has he/she is awarded.
 *

 * 9 GAMEPLAY MECHANICS
 * The user might play completely randomly not thinking about anything. In this case because of the
 * bad choices safety method the user is able to finish the game.
 * Otherwise the player is supposed to make choices whether to keep some items in the bay. If the
 * price of an item turns out to rise over more planets, it might be better to keep that item and
 * make more money but it will occupy some cargo space. Also the player should buy as many items
 * on a given planet as possible. The price of each of these item will rise in the next shop which
 * in turn makes more money than buying only one item. Here the user has to keep an eye on the
 * cargo space and money.
 *

 * Game method call sequence:
 *

 * OPENING GAME MODE ON A PLANET:
 * First planet:
 * GameDatabaseHelper databaseHelper = GameDatabaseHelper.getInstance(this.context);
 * databaseHelper.initializeDatabaseContents(direction, this.startPlanet, this.context);
 * databaseHelper.adaptItemSizes(this.startPlanet);
 *

 * Other planets:
 * databaseHelper.updateItems(this.currentPlanet);
 * databaseHelper.adaptItemSizes(this.currentPlanet);
 * databaseHelper.failSafe(this.currentPlanet, true);
 * databaseHelper.updateVisitedPlanets(this.currentPlanet);
 *

 * On each planet:
 * databaseHelper.buySellItem(item, true/false);
 * if ship is available:
 * databaseHelper.buyShip(ship);
 */
public final class Configuration {

    //----------------------------
    // Shop items:
    // The number of shop items must be X * PLANETS_WITH_SHOPS (each shop must have equal amount of
    // wares, otherwise a test will fail.
    // TODO write a test for this

    // Strings that the QR code must contain in order to verify which planet the user scanned
    public static final String SUN_TRAIL_NAME = "http://slunecnistezka.cz/app/";
    public static final String NAME_INTRO = "start";
    public static final String NAME_SUN = "slunce";
    public static final String NAME_MERCURY = "merkur";
    public static final String NAME_VENUS = "venuse";
    public static final String NAME_EARTH = "zeme";
    public static final String NAME_MOON = "mesic";
    public static final String NAME_MARS = "mars";
    public static final String NAME_CERES = "ceres";
    public static final String NAME_JUPITER = "jupiter";
    public static final String NAME_HALLEY = "halley";
    public static final String NAME_SATURN = "saturn";
    public static final String NAME_URANUS = "uran";
    public static final String NAME_NEPTUNE = "neptun";
    // Easteregg authors name shows up
    public static final String NAME_ATHWALE = "Athwale";
    // Strings that NFC NUID must contain to verify which planet the user scanned
    // Map is used to enable more IDs for each planet to make repair of stolen tags easy
    public static final Map<String, Integer> PLANET_TAGS = Collections.unmodifiableMap(
            new HashMap<String, Integer>() {{
                put("4a3e26", PLANET_ID_INTRO);
                put("4573726", PLANET_ID_SUN);
                put("349e3c26", PLANET_ID_MERCURY);
                put("846b3526", PLANET_ID_VENUS);
                put("14513526", PLANET_ID_EARTH);
                put("9473926", PLANET_ID_MOON);
                put("d4413b26", PLANET_ID_MARS);
                put("948e3526", PLANET_ID_CERES);
                put("34983526", PLANET_ID_JUPITER);
                put("b46c3326", PLANET_ID_HALLEY);
                put("e4e43626", PLANET_ID_SATURN);
                put("546c3926", PLANET_ID_URANUS);
                put("a4973526", PLANET_ID_NEPTUNE);
            }});
    // Contains planet Ids where shops are located. The Sun or Neptune is added to the list inside
    // GameDatabaseHelper depending on which trip direction is chosen.
    // If the player goes Sun -> Neptune, there is no shop on Neptune, since the game ends there and
    // vice versa.
    public static final List<Integer> PLANETS_WITH_SHOPS = Collections.unmodifiableList(
            new ArrayList<Integer>() {{
                add(PLANET_ID_MERCURY);
                add(PLANET_ID_VENUS);
                add(PLANET_ID_EARTH);
                add(PLANET_ID_MOON);
                add(PLANET_ID_MARS);
                add(PLANET_ID_CERES);
                add(PLANET_ID_JUPITER);
                add(PLANET_ID_HALLEY);
                add(PLANET_ID_SATURN);
                add(PLANET_ID_URANUS);
            }});
    // Initial game values
    public static final int FIRST_SHIP = R.string.ship_name_icarus;
    public static final int STARTING_CREDITS = 500;
    public static final int ICARUS_CARGO_SIZE = 10;
    public static final int LOKYS_CARGO_SIZE = 15;
    public static final int DAEDALUS_CARGO_SIZE = 25;
    // These are used to randomly assign the price of an item
    public static final int MIN_ITEM_PRICE = 40;
    public static final int MAX_ITEM_PRICE = 300;
    // In percent how much the price will raise or fall.
    public static final int MIN_ITEM_PRICE_MOVEMENT = 30;
    public static final int MAX_ITEM_PRICE_MOVEMENT = 60;
    // Prize limits
    public static final int FIRST_PLACE = 5500;
    public static final int SECOND_PLACE = 3500;

    // To prevent someone from accidentally instantiating this class, make the constructor private.
    private Configuration() {
    }

}


text:
package org.apache.heron.healthmgr.policy;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Named;

import com.microsoft.dhalion.core.Action;
import com.microsoft.dhalion.core.Diagnosis;
import com.microsoft.dhalion.core.Measurement;
import com.microsoft.dhalion.core.Symptom;
import com.microsoft.dhalion.policy.HealthPolicyImpl;

import org.apache.heron.api.generated.TopologyAPI;
import org.apache.heron.healthmgr.HealthPolicyConfig;
import org.apache.heron.healthmgr.common.InvalidStateException;
import org.apache.heron.healthmgr.common.PhysicalPlanProvider;

import static org.apache.heron.healthmgr.HealthPolicyConfig.CONF_POLICY_ID;

/**
 * This Policy class
 * 1. has a toggle switch
 * 2. works with runtime config
 */
public class ToggleablePolicy extends HealthPolicyImpl {
  private static final Logger LOG =
      Logger.getLogger(ToggleablePolicy.class.getName());

  protected PhysicalPlanProvider physicalPlanProvider;
  protected String policyId;
  private String policyIdRuntime;
  protected HealthPolicyConfig policyConfig;

  protected PolicyMode policyMode;

  public enum PolicyMode {
    activated,
    deactivated
  }

  @Inject
  public ToggleablePolicy(
      @Named(CONF_POLICY_ID) String policyId,
      HealthPolicyConfig policyConfig,
      PhysicalPlanProvider physicalPlanProvider) {
    this.physicalPlanProvider = physicalPlanProvider;
    this.policyId = policyId;
    this.policyConfig = policyConfig;

    policyMode = policyConfig.getPolicyMode();
    policyIdRuntime = policyId + ":runtime";
  }

  @Override
  public Collection<Measurement> executeSensors() {
    LOG.fine("--------- policy: " + policyId + " ---------");
    try {
      for (TopologyAPI.Config.KeyValue kv
          : physicalPlanProvider.get().getTopology().getTopologyConfig().getKvsList()) {
        if (kv.getKey().endsWith(":runtime")) {
          LOG.fine("kv:runtime " + kv.getKey() + " -> " + kv.getValue());
          if (kv.getKey().equals(policyIdRuntime)) {
            try {
              PolicyMode val = PolicyMode.valueOf(kv.getValue());
              if (!policyMode.equals(val)) {
                policyMode = val;
                LOG.info("policy " + policyId + " status changed to " + policyMode);
              } else {
                LOG.fine("policy " + policyId + " status remains same " + policyMode);
              }
              break;
            } catch (IllegalArgumentException e) {
              LOG.warning("policy " + policyId + " status does not change " + policyMode
                  + "; unknown input " + kv.getValue());
            }
          }
        }
      }
    } catch (InvalidStateException e) {
      LOG.warning(
          "failed to fetch the latest physical plan and skip policy toggle update: "
              + e.toString());
    }

    if (policyMode.equals(PolicyMode.activated)) {
      return super.executeSensors();
    } else {
      return Collections.EMPTY_LIST;
    }
  }

  @Override
  public Collection<Symptom> executeDetectors(Collection<Measurement> measurements) {
    if (policyMode.equals(PolicyMode.activated)) {
      return super.executeDetectors(measurements);
    } else {
      return Collections.EMPTY_LIST;
    }
  }

  @Override
  public Collection<Diagnosis> executeDiagnosers(Collection<Symptom> symptoms) {
    if (policyMode.equals(PolicyMode.activated)) {
      return super.executeDiagnosers(symptoms);
    } else {
      return Collections.EMPTY_LIST;
    }
  }

  @Override
  public Collection<Action> executeResolvers(Collection<Diagnosis> diagnosis) {
    if (policyMode.equals(PolicyMode.activated)) {
      return super.executeResolvers(diagnosis);
    } else {
      /*
       * TODO(dhalion):
       * If sub-class could access the `lastExecutionTimestamp`
       * and `oneTimeDelay`, avoid super method invocation.
       */
      return super.executeResolvers(new ArrayList<Diagnosis>());
    }
  }
}


text:
package org.eclipse.swt.snippets;

/*
 * Link example snippet: create a link widget
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 *
 * @since 3.1
 */
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.*;

public class Snippet182 {

	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		Link link = new Link(shell, SWT.BORDER);
		link.setText("This a very simple link widget.");
		Rectangle clientArea = shell.getClientArea();
		link.setBounds(clientArea.x, clientArea.y, 140, 40);
		shell.pack ();
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}


text:
@interface CQActionImageCollectionViewCell : UICollectionViewCell {

}
@property (nonatomic, copy) void(^deleteHandle)(CQActionImageCollectionViewCell * bCell);

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, assign) BOOL isAdd;
@property (nonatomic, assign) BOOL hiddenDelete;

@end


text:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
  Alert,
  FormGroup,
  Input,
  Button,
  Card,
  CardHeader,
  CardBody
} from 'reactstrap';

class EnsLookup extends Component {
  constructor(props) {
    super(props);

    this.state = {
      address: '',
      showResult: false
    };
  }

  handleChange(e) {
    this.setState({address: e.target.value, showResult: false});
  }

  handleLookup() {
    this.setState({showResult: true});
    this.props.lookup(this.state.address);
  }

  showResult() {
    let ensRecord = this.props.ensRecords.find((record) => record.address === this.state.address);
    if (ensRecord) {
      return <Alert className="mt-3" color="success">The name is: {ensRecord.name}</Alert>;
    } else {
      return <Alert className="mt-3" color="danger">We could not find a name for this address</Alert>;
    }
  }

  render(){
    return (
      <Card>
        <CardHeader>
          ENS Lookup
        </CardHeader>
        <CardBody>
          <FormGroup>
            <Input placeholder="Enter an address (0x...)" onChange={e => this.handleChange(e)}/>
          </FormGroup>
          <Button color="primary" onClick={() => this.handleLookup()}>Lookup</Button>
          {this.state.showResult && this.showResult()}
        </CardBody>
      </Card>
    );
  }
}

EnsLookup.propTypes = {
  lookup: PropTypes.func,
  ensRecords: PropTypes.arrayOf(PropTypes.object)
};

export default EnsLookup;


text:
namespace ash {

using TouchExplorationManagerTest = AshTestBase;

TEST_F(TouchExplorationManagerTest, AdjustSound) {
  RootWindowController* controller = Shell::GetPrimaryRootWindowController();
  TouchExplorationManager touch_exploration_manager(controller);
  chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();

  touch_exploration_manager.SetOutputLevel(10);
  EXPECT_EQ(audio_handler->GetOutputVolumePercent(), 10);
  EXPECT_FALSE(audio_handler->IsOutputMuted());

  touch_exploration_manager.SetOutputLevel(100);
  EXPECT_EQ(audio_handler->GetOutputVolumePercent(), 100);
  EXPECT_FALSE(audio_handler->IsOutputMuted());

  touch_exploration_manager.SetOutputLevel(0);
  EXPECT_EQ(audio_handler->GetOutputVolumePercent(), 0);
  EXPECT_TRUE(audio_handler->IsOutputMuted());

  touch_exploration_manager.SetOutputLevel(-10);
  EXPECT_EQ(audio_handler->GetOutputVolumePercent(), 0);
  EXPECT_TRUE(audio_handler->IsOutputMuted());
}

TEST_F(TouchExplorationManagerTest, HandleAccessibilityGesture) {
  RootWindowController* controller = Shell::GetPrimaryRootWindowController();
  TouchExplorationManager touch_exploration_manager(controller);
  TestAccessibilityControllerClient client;

  touch_exploration_manager.HandleAccessibilityGesture(
      ax::mojom::Gesture::kClick);
  EXPECT_EQ(ax::mojom::Gesture::kClick, client.last_a11y_gesture());

  touch_exploration_manager.HandleAccessibilityGesture(
      ax::mojom::Gesture::kSwipeLeft1);
  EXPECT_EQ(ax::mojom::Gesture::kSwipeLeft1, client.last_a11y_gesture());
}

}  //  namespace ash


text:
namespace eigutils{

    namespace eigSetting{
        enum class Form{SYMMETRIC, NONSYMMETRIC};       // Real Symmetric, Real General or Complex General
        enum class Storage {DENSE,SPARSE,STL};          // Eigen Dense or sparse, or std::vector for container
        enum class Shift {ON,OFF};                      // Enable or disable shift invert
        enum class Ritz {LA,SA,LM,SM,LR,SR,LI,SI,BE};   // Choice of eigenvalue. LA is largest algebraic, and so on.
        enum class Side {L,R};                          // Left or right eigenvectors
        enum class Type {REAL,CPLX};                    // Real or complex, i.e. double or std::complex<double> matrix

        inline Ritz stringToRitz(std::string_view ritzstring){
            if (ritzstring == "LA") return Ritz::LA;
            if (ritzstring == "SA") return Ritz::SA;
            if (ritzstring == "LM") return Ritz::LM;
            if (ritzstring == "SM") return Ritz::SM;
            if (ritzstring == "LR") return Ritz::LR;
            if (ritzstring == "SR") return Ritz::SR;
            if (ritzstring == "LI") return Ritz::LI;
            if (ritzstring == "SI") return Ritz::SI;
            if (ritzstring == "BE") return Ritz::BE;
            throw std::runtime_error("Wrong ritz string: " + std::string(ritzstring));
        }

        inline std::string_view RitzToString(Ritz ritz){
            if (ritz == Ritz::LA) return  "LA";
            if (ritz == Ritz::SA) return  "SA";
            if (ritz == Ritz::LM) return  "LM";
            if (ritz == Ritz::SM) return  "SM";
            if (ritz == Ritz::LR) return  "LR";
            if (ritz == Ritz::SR) return  "SR";
            if (ritz == Ritz::LI) return  "LI";
            if (ritz == Ritz::SI) return  "SI";
            if (ritz == Ritz::BE) return  "BE";
            throw std::runtime_error("Wrong ritz enum");
        }

    }

    class eigConfig{
    public:
        bool confOK = false;
        eigSetting::Form           form        = eigSetting::Form::NONSYMMETRIC;
        eigSetting::Storage        storage     = eigSetting::Storage::DENSE;
        eigSetting::Shift          shift       = eigSetting::Shift::OFF;
        eigSetting::Side           side        = eigSetting::Side::R;
        eigSetting::Ritz           ritz        = eigSetting::Ritz::LM;
        eigSetting::Type           type        = eigSetting::Type::REAL;
        bool    compute_eigvecs                = true;
        bool    remove_phase                   = false;
        double  eigThreshold                   = 1e-12;
        int     eigMaxIter                     = 2000;
        int     eigMaxNev                      = 1;
        int     eigMaxNcv                      = 16;
        std::complex<double>  sigma            = std::numeric_limits<std::complex<double>>::quiet_NaN();     // Sigma value for shift-invert mode.
        std::string get_ritz(){return std::string(eigutils::eigSetting::RitzToString(ritz));}
        void checkRitz()
        // Checks that ritz is valid for the given problem.
        // The valid ritzes are stated in the arpack++ manual page 78.
        {
            using namespace eigSetting;
            std::string suggestion;
            if (type==Type::CPLX or form==Form::NONSYMMETRIC){
                if (ritz==Ritz::LA or
                    ritz==Ritz::SA or
                    ritz==Ritz::BE)
                {
                    std::cerr << "WARNING: Invalid ritz for cplx or nonsym problem: " << RitzToString(ritz) << std::endl;
                    if (ritz==Ritz::LA) suggestion = "LR";
                    if (ritz==Ritz::SA) suggestion = "SR";
                    if (ritz==Ritz::BE) suggestion = "LM";
                    std::cerr << "         Suggested ritz: " << suggestion << std::endl;
                }
            }else if (type==Type::REAL and form==Form::SYMMETRIC) {
                if (ritz==Ritz::LR or
                    ritz==Ritz::SR or
                    ritz==Ritz::LI or
                    ritz==Ritz::SI)
                {
                    std::cerr << "WARNING: Invalid ritz for real and sym problem: " << RitzToString(ritz)<< std::endl;
                    if (ritz==Ritz::LR) suggestion = "LA";
                    if (ritz==Ritz::SR) suggestion = "SA";
                    if (ritz==Ritz::LI) suggestion = "LM";
                    if (ritz==Ritz::SI) suggestion = "SM";
                    std::cerr << "         Suggested ritz: " << suggestion << std::endl;
                }
            }
            if(not suggestion.empty())
                throw std::runtime_error("Invalid ritz");
            confOK = true;
        }

    };

    class eigSolution{
    public:
        using Scalar = std::complex<double>;
        // For symmetric problems
        std::vector<double> eigvecs_real;
        std::vector<Scalar> eigvecs_cplx;
        std::vector<double> eigvals_real;

        // For nonsymmetric problems
        std::vector<double> eigvecsR_real;
        std::vector<double> eigvecsL_real;
        std::vector<Scalar> eigvecsR_cplx;
        std::vector<Scalar> eigvecsL_cplx;
        std::vector<Scalar> eigvals_cplx;

        template<eigutils::eigSetting::Type   type,
                eigutils::eigSetting::Form   form,
                eigutils::eigSetting::Side   side = eigutils::eigSetting::Side::R >
        auto & get_eigvecs(){
            using namespace eigutils::eigSetting;
            if constexpr(form == Form::SYMMETRIC){
                if constexpr(type == Type::REAL)                    {return eigvecs_real;}
                if constexpr(type == Type::CPLX)                    {return eigvecs_cplx;}
            }else if constexpr(form == Form::NONSYMMETRIC and side == Side::R){
                if constexpr(type == Type::REAL and side == Side::R){return eigvecsR_cplx;}
                if constexpr(type == Type::CPLX and side == Side::R){return eigvecsR_cplx;}
            }else if constexpr(form == Form::NONSYMMETRIC and side == Side::L){
                if constexpr(type == Type::REAL and side == Side::L){return eigvecsL_cplx;}
                if constexpr(type == Type::CPLX and side == Side::L){return eigvecsL_cplx;}
            }
        }

        template<typename Scalar,
                eigutils::eigSetting::Form   form,
                eigutils::eigSetting::Side   side = eigutils::eigSetting::Side::R >
        auto & get_eigvecs(){
            using namespace eigutils::eigSetting;
            if constexpr (std::is_same<double, Scalar>::value){
                return get_eigvecs<Type::REAL,form,side>();
            }else if constexpr (std::is_same<std::complex<double>, Scalar>::value){
                return get_eigvecs<Type::CPLX,form,side>();
            }
        }

        template<eigutils::eigSetting::Form form>
        auto & get_eigvals(){
            using namespace eigutils::eigSetting;
            if constexpr(form == Form::SYMMETRIC)   {return eigvals_real;}
            if constexpr(form == Form::NONSYMMETRIC){return eigvals_cplx;}
        }

        struct Meta{
            int     rows            = 0;
            int     cols            = 0;
            int     iter            = 0;
            int     nev             = 0; // Found eigenvectors. aka cols.
            int     nev_converged   = 0;
            int     n               = 0; // Linear dimension of the input matrix to diagonalize, aka rows.
            int     counter         = 0;
            int     ncv_used        = 0;
            bool    eigvals_found   = false; // For all problems
            bool    eigvecs_found   = false; // For symmetric problems
            bool    eigvecsR_found  = false; // For nonsymmetric problems
            bool    eigvecsL_found  = false; // For nonsymmetric problems
            eigSetting::Form  form;
            eigSetting::Ritz  ritz;
            eigSetting::Type  type;
            eigSetting::Side  side;
        } meta;
        void reset(){
            eigvals_real.clear();
            eigvals_cplx.clear();
            eigvecs_real.clear();
            eigvecs_cplx.clear();
            eigvecsR_real.clear();
            eigvecsL_real.clear();
            eigvecsR_cplx.clear();
            eigvecsL_cplx.clear();
            meta = Meta();
        }
    };

    namespace eigLogger{

        inline std::shared_ptr<spdlog::logger> log;
        inline void enableTimeStamp(std::shared_ptr<spdlog::logger> &log){
            if(log != nullptr) {
                log->set_pattern("[%Y-%m-%d %H:%M:%S][%n]%^[%=8l]%$ %v");
            }
        }
        inline void disableTimeStamp(std::shared_ptr<spdlog::logger> &log){
            if(log != nullptr){
                log->set_pattern("[%n]%^[%=8l]%$ %v");
            }
        }

        inline void setLogLevel(size_t levelZeroToSix){
            if (levelZeroToSix > 6) {
                throw std::runtime_error("Expected verbosity level integer in [0-6]. Got: " + std::to_string(levelZeroToSix));
            }
            auto lvlEnum = static_cast<spdlog::level::level_enum>(levelZeroToSix);

            // Set console settings
            log->set_level(lvlEnum);
        }

        inline void setLogger(std::string name, size_t levelZeroToSix = 2, bool timestamp = true){
            if(spdlog::get(name) == nullptr){
                log = spdlog::stdout_color_mt(name);
                if (timestamp){enableTimeStamp(log);}
                else{disableTimeStamp(log); }
                setLogLevel(levelZeroToSix);
            }else{
                log = spdlog::get(name);
            }
        }

    }

}


text:
class GuestEvent < ActiveRecord::Base
	default_scope { order('created_at DESC') }
	belongs_to :guest, touch: true, class_name: "Guest"
	belongs_to :affected_work, class_name: "Work"

	def self.create_work_event!(current_guest, work)
		event = GuestEvent.new
		event.guest = current_guest
		event.affected_work = work
		event.save
	end

	def self.create_page_visit_event!(current_guest, page_name)
		event = GuestEvent.new
		event.guest = current_guest
		event.affected_page = page_name
		event.save
	end

	def self.group_all_for_graph
		grouped_hash = self.all.group_by{ |item| item.created_at.to_date }
		start_date = GuestEvent.last.created_at.to_date
		date = Time.now.to_date
		array_of_counts = []
		while (date >= start_date)
			count = grouped_hash[date].try(:count)
			if count.present?
				array_of_counts << count
			elsif count.nil?
				array_of_counts << 0
			end
			date -= 1.day
		end
		return array_of_counts.reverse
	end

	def self.group_all_statics_for_graph
		array_of_grouped_hashes = []
		["home","team","not_found"].each do |static_type|
			array_of_grouped_hashes << GuestEvent.where(affected_page: static_type).group_by{ |item| item.created_at.to_date }
		end
		array_of_arrays_of_counts = []
		array_of_grouped_hashes.each do |grouped_hash|
			start_date = GuestEvent.last.created_at.to_date
			date = Time.now.to_date
			array_of_counts = []
			while (date >= start_date)
				count = grouped_hash[date].try(:count)
				if count.present?
					array_of_counts << count
				elsif count.nil?
					array_of_counts << 0
				end
				date -= 1.day
			end
			array_of_arrays_of_counts << array_of_counts.reverse
		end
		return array_of_arrays_of_counts
		# array_of_arrays_of_counts[0] => "home" , [1] => "team", [2] => "not_found"
	end
end


text:
title: "Introduction to the MEAN stack - Part 1: MongoDB"
date: 2015-10-01 13:27:28
description: An introduction to the MEAN stack for full-stack developers. In this first chapter, we will introduce you to the Model part, MongoDB.
category: tutorials
author: Soufiane ELBAZ
---
# Introduction:

As we said in the description, we will start with the Model part and especially with the well known document based database (NoSQL) MongoDB.

If you are familiar with JSON you will rapidly notice the similarity between the two, it's (key : value) based, the values may contain a document, arrays, and arrays of documents the thing that can let you far from complex join relations that are also expensive in what we call performance ...

A MongoDB server can contain multiple databases and each database contains multiple collections that can be in relations (OneToOne, OneToMany, ManyToOne and ManyToMany).

An Example of a MongoDB collection :

{% codeblock lang:json %}
  [
    {
      "_id" : ObjectId("5608d1d84b77357a0c2cdad2"),
      "name" : "John DOE",
      "age" : 25,
      "address" : {
        "street" : "Broadway St.",
        "city" : "New York"
      }
    }
  ]
{% endcodeblock %}

# Installation:

First of all you need to install a MongoDB locally, here is a link in the official documentation that contains all the steps for all environnements :

 - {% link Linux http://docs.mongodb.org/manual/administration/install-on-linux/ true %}
 - {% link OS X http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ true %}
 - {% link Windows http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/ true %}

Now that we have MongoDB installed locally, we will install a tool that will help us to gather the data from a specific database in our server.

The tool is called Mongoose, it's the linker between the web server and the model server.

It's kind usefull and contain many features that will help us a lot, like tha callbacks features.

#### Mongoose installation using npm :

{% codeblock lang: bash %}
	npm install -g mongoose
{% endcodeblock %}

We will play around just to get used to it, first we type the following command:

{% codeblock lang:bash %}
	node
{% endcodeblock %}

Now we will declare a mongoose variable that contains the Mongoose module that also contains all the functions we need .
#### You should know that nodejs has a module loading systems, if you want to add functions or objects to your root module you should add them to module.exports

#### Types of modules :

 - Core modules like the 'http' module, they are contained in the /lib folder and are compiled to binary.
 - File module, files that end with .json , .js and finally .node .

{% codeblock lang:javascript %}
	var mongoose = require("mongoose");
{% endcodeblock %}

Then we connect it to the installed database :

{% codeblock lang:javascript %}
	var connectionCallBack = function(err){

		if(err)
		    {
		    	console.log("Error!");
		    }
	  	else
		    {
		    	console.log("Connected to the MongoDB server !");
		    }
	};

	mongoose.connect('mongodb://localhost/test3', connectionCallBack);
{% endcodeblock %}

Before creating our first Document we should design its Schema first, so we should create a Schema object :

{% codeblock lang:javascript %}
	var Schema = mongoose.Schema;
{% endcodeblock %}

We will create a User Schema :

{% codeblock lang:javascript %}
	var userSchema = new Schema({
		/*Key, Value*/
		"name" : { type : String, required : true},
		"age" : { type : Number, required : true}
		"address" : {
			"street" : { type : String, default: "none"},
			"city" : { type : String, default: "none"}
		}
		"created_at" : { type : Date, default : Data.now }
	});
{% endcodeblock %}

So our schema contains three properties : name, age and address .

The address is an Embedded Sub-document that contains : street and city, we did that because the little amount of data that can contain an address, if for example
we had a relation user<=>posts we shall not do this, we will store the posts in a distinct documents and we will set a ManyToOne relation.

An "_id" will be added automatically as a primary key with unique value, its type is ObjectId a type contained in "mongoose.Schema.Types.ObjectId".

Now that our Schema is ready, all that we have to do is to add it to the database.

{% codeblock lang:javascript %}
	/*in the first parameter we set the name of the document and in the the second one the the Schema we created*/
	var User = mongoose.model('User', userSchema);
{% endcodeblock %}

### CRUD Operations :

#### Create :

{% codeblock lang:javascript %}
	var userCallBack = function(err, user)
	{
		if(err)
		{
			throw new Error("An error occured while adding the user : "+err);
		}

		console.log("The user is successfully added .");
	};

	var firstUser = new User({});

	firstUser.name = "John DOE";
	firstUser.age = 23;
	firstUser.address.street = "Broadway St.";
	firstUser.address.city = "New York";

	/* We can get the _id of the user object before saving it */

	console.log(firstUser._id);

	firstUser.save(userCallBack);

{% endcodeblock %}

#### Read :

{% codeblock %}
	var usersCallBack = function(err, users)
	{
		if(err)
		{
			throw new Error("An error occured while reading the users : "+err);
		}

		console.log("The users  : "+users);
	};

	/* find(selections, callback); */
	/* Selecting all the users by "{}" */
	/* Similar to SELECT * FROM users */
	User.find({}, usersCallBack);

	/* Now let's select all the mature people ; the projection will only contain name and age*/
	/* Similar to SELECT name, age FROM users WHERE age > 21 */
	User.find({ age : { $gt : 21 } }).select('name age').exec(usersCallBack);

	/*http://mongoosejs.com/docs/api.html*/
{% endcodeblock %}

### Update :

{% codeblock lang:javascript %}
	var usersCallBack = function(err, users)
	{
		if(err)
		{
			throw new Error("An error occured while updating the users");
		}

		console.log("The users  : "+users);
	};
	/* Now let's let the immature people be mature and rename them as MoroccoJS */
	/* update(selections, updates, options, callback); */
	User.update({ age : { $lt : 21} } , { $set : { age : 21 , name : "MoroccoJS" } } , { multiple : true }, usersCallBack);

{% endcodeblock %}

### Delete :

{% codeblock lang:javascript %}
	var deletionCallBack = function(err)
	{
		if(err)
		{
			throw new Error("An error occured while deleting the users");
		}

		console.log("Deleted successfully!");
	};

	/* Now let's update all users with with "MoroccoJS" name */
	/* For multiple deletion we should add the option { multiple : true } */
	/* If we don't, the first user found with the setted criterias will be the only */
	/* one to be deleted */

	User.remove({ name : { $eq: "MoroccoJs"} }, deletionCallBack);

{% endcodeblock %}

You should take a look {% link here http://mongoosejs.com/docs/api.html true %} for more informations ;) .

That's it for the Model Part :D

## See you next time with "ExpressJS" and "NodeJS", until that we wish you all GoodLuck.

## Special thanks go to Youssef Kababe for his commitments in favor of the Moroccan JS and Ruby community (y).


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

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

    module.directive('stdDate',
        ['$filter', '$timeout', 'stdUtil',
            function ($filter, $timeout, util) {
                return {
                    require: 'ngModel',
                    link: function (scope, element, attrs, ngModelCtrl) {
                        var format = 'MM/dd/yyyy';
                        var timeZone = 0;
                        var formatParts = format.split('/');
                        var position1Format = formatParts[0].toLowerCase();
                        var position2Format = formatParts[1].toLowerCase();
                        var position3Format = formatParts[2].toLowerCase();

                        var range1Start = 0;
                        var range1End = position1Format.length;
                        var range2Start = range1End + 1;
                        var range2End = range2Start + position2Format.length;
                        var range3Start = range2End + 1;
                        var range3End = range3Start + position3Format.length;

                        var range1 = createRange(range1Start, range1End);
                        var range2 = createRange(range2Start, range2End);
                        var range3 = createRange(range3Start, range3End);

                        var selectedRange = [];
                        var rangeInitialized = false;

                        var mouseDown = new Date().getTime(),
                            previousMouseDown = mouseDown;

                        var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1
                        || navigator.userAgent.toLowerCase().indexOf("trident") != -1);

                        function getCaretPosition() {
                            var caretPos = 0;   // IE Support
                            if (document.selection) {
                                element[0].focus();
                                var selection = document.selection.createRange();
                                selection.moveStart('character', -element[0].value.length);
                                caretPos = selection.text.length;
                            }
                            // Firefox support
                            else if (element[0].selectionStart || element[0].selectionStart == '0')
                                caretPos = element[0].selectionStart;
                            return (caretPos);
                        }

                        function createRange(start, end) {
                            var array = [];
                            for (var i = start; i <= end; i++) {
                                array.push(i);
                            }
                            return array;
                        }

                        function getSelectedText() {
                            return element[0].value.substring(selectedRange[0], selectedRange[selectedRange.length - 1]);
                        }

                        function replaceRange(s, start, end, substitute) {
                            return s.substring(0, start) + substitute + s.substring(end);
                        }

                        function zeroPad(num, places) {
                            var zero = places - num.toString().length + 1;
                            return Array(+(zero > 0 && zero)).join("0") + num;
                        }

                        function setValue(value) {
                            ngModelCtrl.$setViewValue(replaceRange(element[0].value, selectedRange[0], selectedRange[selectedRange.length - 1], value));
                            ngModelCtrl.$render();
                        }

                        function setRange(rangeStart, rangeEnd, rangeToSelect, ri) {
                            element[0].setSelectionRange(rangeStart, rangeEnd);
                            selectedRange = rangeToSelect;
                            rangeInitialized = ri;
                        }

                        function getCharFromKeyCode(e) {
                            if(e.keyCode >= 96 && e.keyCode <= 105)
                                return parseInt(String.fromCharCode(e.keyCode - 48));

                            return parseInt(String.fromCharCode(e.keyCode));
                        }

                        function isNumber(n) {
                            return !isNaN(parseFloat(n)) && isFinite(n);
                        }

                        element.bind('keydown', function(e) {
                            if (e.keyCode === 37) {
                                if (selectedRange === range3) {
                                    setRange(range2Start, range2End, range2, true);
                                } else if (selectedRange === range2) {
                                    setRange(range1Start, range1End, range1, true);
                                }
                            }
                            if (e.keyCode === 39 || e.keyCode === 191) {
                                if (selectedRange === range1) {
                                    setRange(range2Start, range2End, range2, true);
                                } else if (selectedRange === range2) {
                                    setRange(range3Start, range3End, range3, true);
                                }
                            }

                            if (e.keyCode === 8) {
                                var selectedText = getSelectedText();
                                if (selectedRange === range1 && !isNaN(selectedText)) {
                                    setValue(position1Format);
                                    setRange(range1Start, range1End, range1, true);
                                }
                                else if (selectedRange === range1 && isNaN(selectedText)) {
                                    setRange(range3Start, range3End, range3, true);
                                    setValue(position3Format);
                                    setRange(range3Start, range3End, range3, true);
                                }
                                else if (selectedRange === range2 && !isNaN(selectedText)) {
                                    setValue(position2Format);
                                    setRange(range2Start, range2End, range2, true);
                                }
                                else if (selectedRange === range2 && isNaN(selectedText)) {
                                    setRange(range1Start, range1End, range1, true);
                                    setValue(position1Format);
                                    setRange(range1Start, range1End, range1, true);
                                }
                                else if (selectedRange === range3 && !isNaN(selectedText)) {
                                    setValue(position3Format);
                                    setRange(range3Start, range3End, range3, true);
                                }
                                else if (selectedRange === range3 && isNaN(selectedText)) {
                                    setRange(range2Start, range2End, range2, true);
                                    setValue(position2Format);
                                    setRange(range2Start, range2End, range2, true);
                                }
                            }

                            if (e.keyCode === 46) {
                                var selectedText = getSelectedText();
                                if (selectedRange === range1 && !isNaN(selectedText)) {
                                    setValue(position1Format);
                                    setRange(range1Start, range1End, range1, true);
                                }
                                else if (selectedRange === range1 && isNaN(selectedText)) {
                                    setRange(range2Start, range2End, range2);
                                    setValue(position2Format);
                                    setRange(range2Start, range2End, range2, true);
                                }
                                else if (selectedRange === range2 && !isNaN(selectedText)) {
                                    setValue(position2Format);
                                    setRange(range2Start, range2End, range2, true);
                                }
                                else if (selectedRange === range2 && isNaN(selectedText)) {
                                    setRange(range3Start, range3End, range3, true);
                                    setValue(position3Format);
                                    setRange(range3Start, range3End, range3, true);
                                }
                                else if (selectedRange === range3 && !isNaN(selectedText)) {
                                    setValue(position3Format);
                                    setRange(range3Start, range3End, range3, true);
                                }
                                else if (selectedRange === range3 && isNaN(selectedText)) {
                                    setRange(range1Start, range1End, range1, true);
                                    setValue(position1Format);
                                    setRange(range1Start, range1End, range1, true);
                                }
                            }

                            if (e.keyCode === 9 && !e.shiftKey) {
                                if (selectedRange === range1) {
                                    setRange(range2Start, range2End, range2, true);
                                    e.preventDefault();
                                } else if (selectedRange === range2) {
                                    setRange(range3Start, range3End, range3, true);
                                    e.preventDefault();
                                }
                            }
                            if (e.keyCode === 9 && e.shiftKey) {
                                if (selectedRange === range2) {
                                    setRange(range1Start, range1End, range1, true);
                                    e.preventDefault();
                                } else if (selectedRange === range3) {
                                    setRange(range2Start, range2End, range2, true);
                                    e.preventDefault();
                                }
                            }

                            if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
                                var newValue,
                                    oldValue,
                                    selectedText = getSelectedText();

                                if (selectedText === '') return;

                                oldValue = parseInt(selectedText);
                                newValue = getCharFromKeyCode(e);

                                if (selectedRange === range1) {
                                    if (position1Format === 'mm') {
                                        if (oldValue === 1 && [0, 1, 2].indexOf(newValue) > -1 && !rangeInitialized) {
                                            setValue(oldValue.toString() + newValue.toString());
                                            setRange(range2Start, range2End, range2, true);
                                        } else if (oldValue === 0 && [1, 2, 3, 4, 5, 6, 7, 8, 9].indexOf(newValue) > -1 && !rangeInitialized) {
                                            setValue(oldValue.toString() + newValue.toString());
                                            setRange(range2Start, range2End, range2, true);
                                        } else {
                                            if ((rangeInitialized || isNaN(oldValue)) && newValue <= 1) {
                                                setValue('0' + newValue.toString());
                                                setRange(range1Start, range1End, range1, false);
                                            } else if (rangeInitialized && [2, 3, 4, 5, 6, 7, 8, 9].indexOf(newValue) > -1) {
                                                setValue('0' + newValue.toString());
                                                setRange(range2Start, range2End, range2, true);
                                            }
                                            else {
                                                if ([4, 5, 6, 7, 8, 9].indexOf(newValue) > -1) {
                                                    setRange(range2Start, range2End, range2, false);
                                                    setValue('0' + newValue.toString());
                                                    setRange(range3Start, range3End, range3, true);
                                                } else {
                                                    setRange(range2Start, range2End, range2, true);
                                                    setValue('0' + newValue.toString());
                                                    setRange(range2Start, range2End, range2, false);
                                                }
                                            }
                                        }
                                    }
                                } else if (selectedRange === range2) {
                                    if (position2Format === 'dd') {
                                        if ([0, 1, 2].indexOf(oldValue) > -1 && [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].indexOf(newValue) > -1 && !rangeInitialized) {
                                            setValue(oldValue.toString() + newValue.toString());
                                            setRange(range3Start, range3End, range3, true);
                                        } else if (oldValue === 3 && [0, 1].indexOf(newValue) > -1 && !rangeInitialized) {
                                            setValue(oldValue.toString() + newValue.toString());
                                            setRange(range3Start, range3End, range3, true);
                                        } else if (oldValue === 3 && [2, 3, 4, 5, 6, 7, 8, 9].indexOf(newValue) > -1 && !rangeInitialized) {
                                            setRange(range3Start, range3End, range3, true);
                                            setValue(zeroPad(newValue, 4));
                                            setRange(range3Start, range3End, range3, false);
                                        } else {
                                            if ((rangeInitialized || isNaN(oldValue))) {
                                                setValue('0' + newValue.toString());
                                                if ([4, 5, 6, 7, 8, 9].indexOf(newValue) > -1)
                                                    setRange(range3Start, range3End, range3, true);
                                                else
                                                    setRange(range2Start, range2End, range2, false);
                                            } else {
                                                setRange(range3Start, range3End, range3, true);
                                                setValue(zeroPad(newValue, 4));
                                                setRange(range3Start, range3End, range3, false);
                                            }
                                        }
                                    }
                                } else if (selectedRange === range3) {
                                    if (position3Format === 'yyyy') {
                                        if (rangeInitialized) {
                                            newValue = getCharFromKeyCode(e);
                                            var numberStr = newValue.toString();
                                            newValue = parseInt('200' + numberStr);
                                        } else if ([2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009].indexOf(oldValue) > -1) {
                                            newValue = getCharFromKeyCode(e);
                                            var numberStr = newValue.toString();
                                            newValue = parseInt('20' + (oldValue % 10).toString() + numberStr);
                                        } else if (!isNaN(newValue) && selectedText.length >= 4) {
                                            var trimmedOldValue = selectedText.substring(1);
                                            newValue = trimmedOldValue + getCharFromKeyCode(e).toString();
                                        }
                                        setValue(zeroPad(newValue, 4));
                                        setRange(range3Start, range3End, range3, false);
                                    }
                                }
                            }
                            if (e.keyCode !== 9)
                                e.preventDefault();

                        });

                        element.bind('mouseup', function(e){
                            var caretPosition = getCaretPosition();
                            var sel = window.getSelection();
                            sel.removeAllRanges();

                            if (range1.indexOf(caretPosition) > -1)
                                setRange(range1Start, range1End, range1, true);

                            if (range2.indexOf(caretPosition) > -1)
                                setRange(range2Start, range2End, range2, true);

                            if (range3.indexOf(caretPosition) > -1)
                                setRange(range3Start, range3End, range3, true);
                        });

                        element.bind('mousemove', function(e){
                            if(e.stopPropagation) e.stopPropagation();
                            if(e.preventDefault) e.preventDefault();
                            e.cancelBubble = true;
                            e.returnValue = false;
                            return false;
                        });

                        element.bind('mousedown', function(e){
                            var time = new Date().getTime();

                            if((time - mouseDown) < 450)
                            {
                                previousMouseDown = mouseDown;
                                mouseDown = time;

                                e.preventDefault();
                                return false;
                            }

                            previousMouseDown = mouseDown;
                            mouseDown = time;
                        });

                        element.bind('copy', function(e) {
                            var textToPutOnClipboard = element[0].value;

                            if (isIe) {
                                window.clipboardData.setData('Text', textToPutOnClipboard);
                            } else {
                                e.clipboardData.setData('text/plain', textToPutOnClipboard);
                            }
                            e.preventDefault();
                        });

                        element.bind('cut', function(e){
                            e.preventDefault();
                        });

                        element.bind('paste', function(e){
                            e.preventDefault();
                        });

                        element.bind('focus', function(e){
                            $timeout(function() {
                                setRange(range1Start, range1End, range1, true);
                            }, 0)
                        });

                        element.bind('blur', function(e){
                            if (ngModelCtrl.$modelValue === null)
                                element[0].value = 'mm/dd/yyyy';
                        });

                        element.addClass('ttl-date-selection');

                        ngModelCtrl.$formatters.push(function (val) {
                            ngModelCtrl.$setValidity('invalid-date', true);
                            var date = Date.parse(val);
                            if (!isNaN(date)) {
                                var utc = new Date(val.getUTCFullYear(), val.getUTCMonth(), val.getUTCDate());
                                return $filter('date')(utc, 'MM/dd/yyyy');
                            } else {
                                return 'mm/dd/yyyy';
                            }
                        });

                        ngModelCtrl.$parsers.push(function (val) {
                            if (val === 'mm/dd/yyyy') {
                                ngModelCtrl.$setValidity('invalid-date', true);
                                return null;
                            }

                            var dateParts = val.split(/[\/]+/);
                            var datePartsJoined = dateParts.join('');
                            var isNumeric = isNumber(datePartsJoined);
                            if (!isNumeric) {
                                ngModelCtrl.$setValidity('invalid-date', false);
                                return new Date('Invalid');
                            }

                            var year = parseInt(dateParts[2]);
                            var month = parseInt(dateParts[0]);
                            var day = parseInt(dateParts[1]);
                            var feb = year % 4 === 0 && (year % 100 || year % 400 === 0) ? 29 : 28;
                            var monthDays = [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                            var numberOfDays = monthDays[month - 1];
                            day = (numberOfDays - day) >= 0 ? day : numberOfDays;
                            if (day !== parseInt(dateParts[1])) {
                                ngModelCtrl.$setViewValue(dateParts[0] + '/' + zeroPad(day, 2) + '/' + dateParts[2]);
                            }
                            ngModelCtrl.$setValidity('invalid-date', true);
                            return new Date(year, (month - 1), day);
                        });
                    }
                };
            }]);
})();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CertificationRequestInfo (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.asn1.pkcs

Class CertificationRequestInfo

java.lang.Object

org.bouncycastle.asn1.ASN1Object

org.bouncycastle.asn1.pkcs.CertificationRequestInfo

All Implemented Interfaces:

ASN1Encodable, Encodable

public class CertificationRequestInfo
extends ASN1Object

PKCS10 CertificationRequestInfo object.

  CertificationRequestInfo ::= SEQUENCE {
   version             INTEGER { v1(0) } (v1,...),
   subject             Name,
   subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
   attributes          [0] Attributes{{ CRIAttributes }}
  }

  Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}

  Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
    type    ATTRIBUTE.&id({IOSet}),
    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
  }

Constructor Summary

Constructors

Constructor and Description

CertificationRequestInfo(ASN1Sequence seq)

Deprecated.

use getInstance().

CertificationRequestInfo(X500Name subject,
                        SubjectPublicKeyInfo pkInfo,
                        ASN1Set attributes)

Basic constructor.

CertificationRequestInfo(X509Name subject,
                        SubjectPublicKeyInfo pkInfo,
                        ASN1Set attributes)

Deprecated.

use X500Name method.

Method Summary

Methods

Modifier and Type
Method and Description

ASN1Set
getAttributes()

static CertificationRequestInfo
getInstance(java.lang.Object obj)

X500Name
getSubject()

SubjectPublicKeyInfo
getSubjectPublicKeyInfo()

ASN1Integer
getVersion()

ASN1Primitive
toASN1Primitive()

Method providing a primitive representation of this object suitable for encoding.

Methods inherited from class org.bouncycastle.asn1.ASN1Object

equals, getEncoded, getEncoded, hasEncodedTagValue, hashCode, toASN1Object

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CertificationRequestInfo

public CertificationRequestInfo(X500Name subject,
                        SubjectPublicKeyInfo pkInfo,
                        ASN1Set attributes)

Basic constructor.

 Note: Early on a lot of CAs would only accept messages with attributes missing. As the ASN.1 def shows
 the attributes field is not optional so should always at least contain an empty set. If a fully compliant
 request is required, pass in an empty set, the class will otherwise interpret a null as it should
 encode the request with the field missing.

Parameters:

subject - subject to be associated with the public key

pkInfo - public key to be associated with subject

attributes - any attributes to be associated with the request.

CertificationRequestInfo

public CertificationRequestInfo(X509Name subject,
                        SubjectPublicKeyInfo pkInfo,
                        ASN1Set attributes)

Deprecated. use X500Name method.

CertificationRequestInfo

public CertificationRequestInfo(ASN1Sequence seq)

Deprecated. use getInstance().

Method Detail

getInstance

public static CertificationRequestInfo getInstance(java.lang.Object obj)

getVersion

public ASN1Integer getVersion()

getSubject

public X500Name getSubject()

getSubjectPublicKeyInfo

public SubjectPublicKeyInfo getSubjectPublicKeyInfo()

getAttributes

public ASN1Set getAttributes()

toASN1Primitive

public ASN1Primitive toASN1Primitive()

Description copied from class: ASN1Object

Method providing a primitive representation of this object suitable for encoding.

Specified by:

toASN1Primitive in interface ASN1Encodable

Specified by:

toASN1Primitive in class ASN1Object

Returns:

a primitive representation of this object.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace internal {

// Helper functions for AtMostOnceEnumUmaDeferrer
//
// These functions refers implementation details of
// base/metrics/histogram.cc. Keep them synchronized with that.

base::HistogramBase* GetHistogramExactLinear(const char* name,
                                             int exclusive_max);

// For getting an enumerated histogram.
template <typename T>
base::HistogramBase* GetHistogramEnumeration(const char* name) {
  static_assert(std::is_enum<T>::value, "T is not an enum.");
  // This also ensures that an enumeration that doesn't define kMaxValue fails
  // with a semi-useful error ("no member named 'kMaxValue' in ...").
  static_assert(static_cast<uintmax_t>(T::kMaxValue) <=
                    static_cast<uintmax_t>(INT_MAX) - 1,
                "Enumeration's kMaxValue is out of range of INT_MAX!");
  return GetHistogramExactLinear(name, static_cast<int>(T::kMaxValue) + 1);
}

template <typename T>
void UmaHistogramEnumeration(base::HistogramBase* histogram, T sample) {
  static_assert(std::is_enum<T>::value, "T is not an enum.");
  // This also ensures that an enumeration that doesn't define kMaxValue fails
  // with a semi-useful error ("no member named 'kMaxValue' in ...").
  static_assert(static_cast<uintmax_t>(T::kMaxValue) <=
                    static_cast<uintmax_t>(INT_MAX) - 1,
                "Enumeration's kMaxValue is out of range of INT_MAX!");
  DCHECK_LE(static_cast<uintmax_t>(sample),
            static_cast<uintmax_t>(T::kMaxValue));
  histogram->Add(static_cast<int>(sample));
}

}  // namespace internal

// A helper to defer UMA recording for prerendered pages for a UMA.
//
// A UMA has some options for prerendered pages:
//
// - Don't record any metrics.
// - Record metrics if the page is activated and discard them if cancelled.
// - Record metrics unconditionally.
//
// The first and third options are easy. For the second option, we have to defer
// recording metrics to a histogram. If only one sample per navigation is
// recorded, this is done by storing a sample in observer and recording in
// OnComplete. In more gerenal case, systematic deferrers help us and makes code
// simple. AtMostOnceEnumUmaDeferrer provides deferring mechanism with
// assumptions of UseCounterPageLoadMetricsObserver.
//
// This class has two states: deferred (initial) and non deferred.
// In deferred state, RecordOrDefer* methods collect samples into an inner
// bitset. DisableDeferAndFlush changes the state to non deferred and flush the
// collected samples. In non deferred state, RecordOrDefer bypass
// deferring and just record a sample.
//
// This class uses a bitset to ensure:
//
// - To record a value at most once, i.e. already recorded value is ignored.
// - To reduce memory usage.
template <typename T>
class AtMostOnceEnumUmaDeferrer {
 public:
  explicit AtMostOnceEnumUmaDeferrer(const char* histogram_name);

  AtMostOnceEnumUmaDeferrer(const AtMostOnceEnumUmaDeferrer&) = delete;
  AtMostOnceEnumUmaDeferrer& operator=(const AtMostOnceEnumUmaDeferrer&) =
      delete;

  ~AtMostOnceEnumUmaDeferrer();

  // Changes the state to deferred to non deferred and flush deferred samples.
  //
  // It is not ensured that the recorded order for samples before
  // DisableDeferAndFlush and the order of method calls coincides.
  // DisableDeferAndFlush records deferred samples by the order of valued as
  // int.
  void DisableDeferAndFlush();

  // Just record a sample or put it into internal buffer.
  //
  // Already recorded or deferred sample is ignored.
  void RecordOrDefer(T sample);

  // True iff RecordOrDefer is already involked for given sample.
  bool IsRecordedOrDeferred(T sample) const;

  // Provided only for DCHECK.
  std::bitset<static_cast<size_t>(T::kMaxValue) + 1> recorded_or_deferred()
      const {
    return recorded_or_deferred_;
  }

 private:
  raw_ptr<base::HistogramBase> histogram_;
  bool should_defer_ = true;
  std::bitset<static_cast<size_t>(T::kMaxValue) + 1> recorded_or_deferred_;
};

template <typename T>
AtMostOnceEnumUmaDeferrer<T>::AtMostOnceEnumUmaDeferrer(const char* name) {
  histogram_ = internal::GetHistogramEnumeration<T>(name);
}

template <typename T>
AtMostOnceEnumUmaDeferrer<T>::~AtMostOnceEnumUmaDeferrer() = default;

template <typename T>
void AtMostOnceEnumUmaDeferrer<T>::DisableDeferAndFlush() {
  if (!should_defer_) {
    return;
  }

  should_defer_ = false;

  for (int sample_value = 0; sample_value <= static_cast<int>(T::kMaxValue);
       ++sample_value) {
    if (recorded_or_deferred_.test(sample_value)) {
      internal::UmaHistogramEnumeration(histogram_,
                                        static_cast<T>(sample_value));
    }
  }
}

template <typename T>
void AtMostOnceEnumUmaDeferrer<T>::RecordOrDefer(T sample) {
  DCHECK_LE(static_cast<uintmax_t>(sample),
            static_cast<uintmax_t>(T::kMaxValue));

  int sample_value = static_cast<int>(sample);

  if (recorded_or_deferred_.test(sample_value)) {
    return;
  }

  recorded_or_deferred_.set(sample_value);

  if (!should_defer_) {
    internal::UmaHistogramEnumeration(histogram_, sample);
  }
}

template <typename T>
bool AtMostOnceEnumUmaDeferrer<T>::IsRecordedOrDeferred(T sample) const {
  DCHECK_LE(static_cast<uintmax_t>(sample),
            static_cast<uintmax_t>(T::kMaxValue));

  int sample_value = static_cast<int>(sample);
  return recorded_or_deferred_.test(sample_value);
}

#endif  // COMPONENTS_PAGE_LOAD_METRICS_BROWSER_OBSERVERS_USE_COUNTER_AT_MOST_ONCE_ENUM_UMA_DEFERRER_H_


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Microsoft.Azure.Mobile.Server.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class RResources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal RResources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.Mobile.Server.Properties.RResources", typeof(RResources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplyTo cannot be called multiple times on the same HttpConfiguration instance..
        /// </summary>
        internal static string ApplyTo_CalledTwice {
            get {
                return ResourceManager.GetString("ApplyTo_CalledTwice", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The '{0}' caused an error: {1}..
        /// </summary>
        internal static string CachePolicy_BadProvider {
            get {
                return ResourceManager.GetString("CachePolicy_BadProvider", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to A provider of type {0} has already been registered..
        /// </summary>
        internal static string ExtensionProvider_AlreadyExists {
            get {
                return ResourceManager.GetString("ExtensionProvider_AlreadyExists", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The request is invalid as submitted..
        /// </summary>
        internal static string HttpBadRequest {
            get {
                return ResourceManager.GetString("HttpBadRequest", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to No HTTP resource was found that matches the request URI '{0}'..
        /// </summary>
        internal static string HttpNotFound {
            get {
                return ResourceManager.GetString("HttpNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Authorization has been denied for this request..
        /// </summary>
        internal static string HttpUnauthorized {
            get {
                return ResourceManager.GetString("HttpUnauthorized", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to No service setting was found with key '{0}'. Please ensure that your service is initialized with the correct application settings and connection strings..
        /// </summary>
        internal static string Settings_KeyNotFound {
            get {
                return ResourceManager.GetString("Settings_KeyNotFound", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to No API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of '{0}'.  For more information and supported clients see: {1}.
        /// </summary>
        internal static string Version_Required {
            get {
                return ResourceManager.GetString("Version_Required", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to An invalid API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of '{0}'.  For more information and supported clients see: {1}.
        /// </summary>
        internal static string Version_Unsupported {
            get {
                return ResourceManager.GetString("Version_Unsupported", resourceCulture);
            }
        }
    }
}


text:
package com.lostagain.nl.GWTish;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector3;

/**
 * A GWTish event is represented by this class

 * This for the moment, represents some mouse and touch actions.

 * This class uses the same static numereicial representions of a few things as GWT does, but other then that does not sure
 * any functionality. It merely in a very broud sense repesents the same thing.

 *

 * The only real use of this class should be in the manager, where it creates a event to pass to objects to react too.

 *
 */
public class Event extends NativeEvent {

	private static String logstag="ME.NativeEvent";

	static Event currentEvent;

	private  Vector3 EventsCurrentLocation;

	//NOTE: this might move to the superclass? Not sure where it fits better
	/**
	 * The current 3d location this event just fired at
	 * @return (not a copy)
	 */
	  public Vector3 getEventsCurrentLocation() {
		return EventsCurrentLocation;
	}

	public static void setCurrentEvent(Event currentEvent) {;

		Event.currentEvent = currentEvent;
	}

	//event types
	public enum EventType {
		ClickEvent,
		MouseDownEvent,
		MouseUpEvent,
		BlurEvent,
		FocusEvent,
		KeyUpEvent,
		KeyDownEvent;
	}

	//This might be replaced with a more detailed system that mirrors GWTs way of identifying the type of the event
	EventType thisEventsType;

	/**
	   * Unlike GWT, we can create events directly
	   * (this class is not very similar)
	 * @param buttonTypeDown
	   */
	  public Event(EventButtonType buttonTypeDown, boolean altKeyWasPressed, boolean cntrKeyWasPressed, boolean shiftKeyWasPressed, int xpos,
			int ypos, int currentEventKeyCode) {

		super();

		ButtonTypeDown=buttonTypeDown;
		//we also keep a record of the last one down if its set to none
		//This lets us check the buttons that were just pressed when something has been released.
		if (ButtonTypeDown!=EventButtonType.None)
		{
			LastButtonTypeThatWasDown = ButtonTypeDown;
		}

		AltKeyWasPressed = altKeyWasPressed;
		CntrKeyWasPressed = cntrKeyWasPressed;
		ShiftKeyWasPressed = shiftKeyWasPressed;
		CurrentEventX = xpos;
		CurrentEventY = ypos;
		CurrentEventKeyCode = currentEventKeyCode;

		//TODO: work out how to deal with representing the type of the event as a number?
		//Using the bit-fields below and the button down fields in the superclass
		//

	}

//NOTE: most of the below isnt used, at least not yet
  /**
   * Fired when an element loses keyboard focus.
   */
  public static final int ONBLUR = 0x01000;

  /**
   * Fired when the value of an input element changes.
   */
  public static final int ONCHANGE = 0x00400;

  /**
   * Fired when the user clicks on an element.
   */
  public static final int ONCLICK = 0x00001;

  /**
   * Fired when the user double-clicks on an element.
   */
  public static final int ONDBLCLICK = 0x00002;

  /**
   * Fired when an image encounters an error.
   */
  public static final int ONERROR = 0x10000;

  /**
   * Fired when an element receives keyboard focus.
   */
  public static final int ONFOCUS = 0x00800;

  /**
   * Fired when the user gesture changes.
   */
  public static final int ONGESTURECHANGE = 0x2000000;

  /**
   * Fired when the user gesture ends.
   */
  public static final int ONGESTUREEND = 0x4000000;

  /**
   * Fired when the user gesture starts.
   */
  public static final int ONGESTURESTART = 0x1000000;

  /**
   * Fired when the user depresses a key.
   */
  public static final int ONKEYDOWN = 0x00080;

  /**
   * Fired when the a character is generated from a keypress (either directly or
   * through auto-repeat).
   */
  public static final int ONKEYPRESS = 0x00100;

  /**
   * Fired when the user releases a key.
   */
  public static final int ONKEYUP = 0x00200;

  /**
   * Fired when an element (normally an IMG) finishes loading.
   */
  public static final int ONLOAD = 0x08000;

  /**
   * Fired when an element that has mouse capture loses it.
   */
  public static final int ONLOSECAPTURE = 0x02000;

  /**
   * Fired when the user depresses a mouse button over an element.
   */
  public static final int ONMOUSEDOWN = 0x00004;

  /**
   * Fired when the mouse is moved within an element's area.
   */
  public static final int ONMOUSEMOVE = 0x00040;

  /**
   * Fired when the mouse is moved out of an element's area.
   */
  public static final int ONMOUSEOUT = 0x00020;

  /**
   * Fired when the mouse is moved into an element's area.
   */
  public static final int ONMOUSEOVER = 0x00010;

  /**
   * Fired when the user releases a mouse button over an element.
   */
  public static final int ONMOUSEUP = 0x00008;

  /**
   * Fired when the user scrolls the mouse wheel over an element.
   */
  public static final int ONMOUSEWHEEL = 0x20000;

  /**
   * Fired when the user pastes text into an input element.
   */
  public static final int ONPASTE = 0x80000;

  /**
   * Fired when a scrollable element's scroll offset changes.
   */
  public static final int ONSCROLL = 0x04000;

  /**
   * Fired when the user cancels touching an element.
   */
  public static final int ONTOUCHCANCEL = 0x800000;

  /**
   * Fired when the user ends touching an element.
   */
  public static final int ONTOUCHEND = 0x400000;

  /**
   * Fired when the user moves while touching an element.
   */
  public static final int ONTOUCHMOVE = 0x200000;

  /**
   * Fired when the user starts touching an element.
   */
  public static final int ONTOUCHSTART = 0x100000;
  /**
   * Fired when the user requests an element's context menu (usually by
   * right-clicking).
   */
  public static final int ONCONTEXTMENU = 0x40000;

  /**
   * A bit-mask covering both focus events (focus and blur).
   */
  public static final int FOCUSEVENTS = ONFOCUS | ONBLUR;

  /**
   * A bit-mask covering all keyboard events (down, up, and press).
   */
  public static final int KEYEVENTS = ONKEYDOWN | ONKEYPRESS | ONKEYUP;

  /**
   * A bit-mask covering all mouse events (down, up, move, over, and out), but
   * not click, dblclick, or wheel events.
   */
  public static final int MOUSEEVENTS = ONMOUSEDOWN | ONMOUSEUP | ONMOUSEMOVE
      | ONMOUSEOVER | ONMOUSEOUT;

  /**
   * A bit-mask covering all touch events (start, move, end, cancel).
   */
  public static final int TOUCHEVENTS = ONTOUCHSTART | ONTOUCHMOVE | ONTOUCHEND | ONTOUCHCANCEL;

  /**
   * A bit-mask covering all gesture events (start, change, end).
   */
  public static final int GESTUREEVENTS = ONGESTURESTART | ONGESTURECHANGE | ONGESTUREEND;

  /**
   * Value returned by accessors when the actual integer value is undefined. In
   * Development Mode, most accessors assert that the requested attribute is
   * reliable across all supported browsers.
   *
   * @see Event
   */
  @Deprecated
  public static final int UNDEFINED = 0;

  /**
   * Gets the current event that is being fired. The current event is only
   * available within the lifetime of the event function. Once the
   *  method returns, the current event is reset to null.
   *
   * @return the current event
   */
  public static Event getCurrentEvent() {
    return currentEvent;
  }

/**
 * Sets the 3d scene position that this event is triggered
 * This should only be called from Gwtishs Model Management class as part of its event fireing
 * @param atThis
 */
public void setCurrentEventLocation(Vector3 atThis) {
	EventsCurrentLocation = atThis;
}

}


text:
/*
 * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    /// <summary>
    /// Contains the response data from the DescribeInstanceAttribute operation.
    /// </summary>
    public partial class DescribeInstanceAttributeResult : AmazonWebServiceResponse
    {
        private InstanceAttribute _instanceAttribute;

        // Gets and sets the InstanceAttribute member
        public InstanceAttribute InstanceAttribute
        {
            get { return this._instanceAttribute; }
            set { this._instanceAttribute = value; }
        }

        // Check to see if InstanceAttribute property is set
        internal bool IsSetInstanceAttribute()
        {
            return this._instanceAttribute != null;
        }
    }
}


text:
package sun.tools.java;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FilterReader;
import java.io.UnsupportedEncodingException;

/**
 * An input stream for java programs. The stream treats either "\n", "\r"
 * or "\r\n" as the end of a line, it always returns \n. It also parses
 * UNICODE characters expressed as \uffff. However, if it sees "\\", the
 * second slash cannot begin a unicode sequence. It keeps track of the current
 * position in the input stream.
 *
 * WARNING: The contents of this source file are not part of any
 * supported API.  Code that depends on them does so at its own risk:
 * they are subject to change or removal without notice.
 *
 * @author      Arthur van Hoff
 */

public
class ScannerInputReader extends FilterReader implements Constants {
    // A note.  This class does not really properly subclass FilterReader.
    // Since this class only overrides the single character read method,
    // and not the multi-character read method, any use of the latter
    // will not work properly.  Any attempt to use this code outside of
    // the compiler should take that into account.
    //
    // For efficiency, it might be worth moving this code to Scanner and
    // getting rid of this class.

    Environment env;
    long pos;

    private long chpos;
    private int pushBack = -1;

    public ScannerInputReader(Environment env, InputStream in)
        throws UnsupportedEncodingException
    {
        // ScannerInputStream has been modified to no longer use
        // BufferedReader.  It now does its own buffering for
        // performance.
        super(env.getCharacterEncoding() != null ?
              new InputStreamReader(in, env.getCharacterEncoding()) :
              new InputStreamReader(in));

        // Start out the buffer empty.
        currentIndex = 0;
        numChars = 0;

        this.env = env;
        chpos = Scanner.LINEINC;
    }

    //------------------------------------------------------------
    // Buffering code.

    // The size of our buffer.
    private static final int BUFFERLEN = 10 * 1024;

    // A character buffer.
    private final char[] buffer = new char[BUFFERLEN];

    // The index of the next character to be "read" from the buffer.
    private int currentIndex;

    // The number of characters in the buffer.  -1 if EOF is reached.
    private int numChars;

    /**
     * Get the next character from our buffer.
     * Note: this method has been inlined by hand in the `read' method
     * below.  Any changes made to this method should be equally applied
     * to that code.
     */
    private int getNextChar() throws IOException {
        // Check to see if we have either run out of characters in our
        // buffer or gotten to EOF on a previous call.
        if (currentIndex >= numChars) {
            numChars = in.read(buffer);
            if (numChars == -1) {
                // We have reached EOF.
                return -1;
            }

            // No EOF.  currentIndex points to first char in buffer.
            currentIndex = 0;
        }

        return buffer[currentIndex++];
    }

    //------------------------------------------------------------

    public int read(char[] buffer, int off, int len) {
        throw new CompilerError(
                   "ScannerInputReader is not a fully implemented reader.");
    }

    public int read() throws IOException {
        pos = chpos;
        chpos += Scanner.OFFSETINC;

        int c = pushBack;
        if (c == -1) {
        getchar: try {
                // Here the call...
                //     c = getNextChar();
                // has been inlined by hand for performance.

                if (currentIndex >= numChars) {
                    numChars = in.read(buffer);
                    if (numChars == -1) {
                        // We have reached EOF.
                        c = -1;
                        break getchar;
                    }

                    // No EOF.  currentIndex points to first char in buffer.
                    currentIndex = 0;
                }
                c = buffer[currentIndex++];

            } catch (java.io.CharConversionException e) {
                env.error(pos, "invalid.encoding.char");
                // this is fatal error
                return -1;
            }
        } else {
            pushBack = -1;
        }

        // parse special characters
        switch (c) {
          case -2:
            // -2 is a special code indicating a pushback of a backslash that
            // definitely isn't the start of a unicode sequence.
            return '\\';

          case '\\':
            if ((c = getNextChar()) != 'u') {
                pushBack = (c == '\\' ? -2 : c);
                return '\\';
            }
            // we have a unicode sequence
            chpos += Scanner.OFFSETINC;
            while ((c = getNextChar()) == 'u') {
                chpos += Scanner.OFFSETINC;
            }

            // unicode escape sequence
            int d = 0;
            for (int i = 0 ; i < 4 ; i++, chpos += Scanner.OFFSETINC, c = getNextChar()) {
                switch (c) {
                  case '0': case '1': case '2': case '3': case '4':
                  case '5': case '6': case '7': case '8': case '9':
                    d = (d << 4) + c - '0';
                    break;

                  case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
                    d = (d << 4) + 10 + c - 'a';
                    break;

                  case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
                    d = (d << 4) + 10 + c - 'A';
                    break;

                  default:
                    env.error(pos, "invalid.escape.char");
                    pushBack = c;
                    return d;
                }
            }
            pushBack = c;

            // To read the following line, switch \ and /...
            // Handle /u000a, /u000A, /u000d, /u000D properly as
            // line terminators as per JLS 3.4, even though they are encoded
            // (this properly respects the order given in JLS 3.2).
            switch (d) {
                case '\n':
                   chpos += Scanner.LINEINC;
                    return '\n';
                case '\r':
                    if ((c = getNextChar()) != '\n') {
                        pushBack = c;
                    } else {
                        chpos += Scanner.OFFSETINC;
                    }
                    chpos += Scanner.LINEINC;
                    return '\n';
                default:
                    return d;
            }

          case '\n':
            chpos += Scanner.LINEINC;
            return '\n';

          case '\r':
            if ((c = getNextChar()) != '\n') {
                pushBack = c;
            } else {
                chpos += Scanner.OFFSETINC;
            }
            chpos += Scanner.LINEINC;
            return '\n';

          default:
            return c;
        }
    }
}


text:
require 'cucumber/rails'
require 'headless'

# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
Capybara.default_wait_time = 30
Capybara.javascript_driver = :webkit

# Set up headless once instead of for every single feature
AfterConfiguration do
  if "true" == ENV["USE_HEADLESS"]

    headless = Headless.new
    headless.start
    puts "<< Headless X server now running on #{headless.display} >>"
  end
end

# Shut down headless when you are done
at_exit do
    puts "<< Tearing down the headless instance >>"
    if ENV["USE_HEADLESS"] == "true" and @headless.present?
      puts "<< Destroying headless X server >>"
      headless.destroy
    end

    # Stop any workflows that have been instatiated or started running due to these tests
    # Make sure to only run tests against a test instance of Matterhorn and not production!!!
    ids = []
    workflows_json = Rubyhorn.client.instances_json({"state" => "RUNNING"})
    begin
      workflows_json["workflows"]["workflow"].each {|w| ids << w["id"]}
    rescue Exception
      puts "<< Exception caught when getting running workflows from Matterhorn >>"
    end
    workflows_json = Rubyhorn.client.instances_json({"state" => "INSTANTIATED"})
    begin
      workflows_json["workflows"]["workflow"].each {|w| ids << w["id"]}
    rescue Exception
      puts "<< Exception caught when getting instantiated workflows from Matterhorn >>"
    end
    ids.each {|id| Rubyhorn.client.stop id}

    # Also be sure to delete all objects so the repository is pristine. Only those
    # fixtures that are not numeric will be retained
    Video.find(:all).each do |video|
      if video.pid =~ /^hydrant:\d+$/
        puts "<< Deleting #{video.pid} from the Fedora repository >>"
        video.delete
      end
    end
end

# By default, any exception happening in your Rails application will bubble up
# to Cucumber so that your scenario will fail. This is a different from how
# your application behaves in the production environment, where an error page will
# be rendered instead.
#
# Sometimes we want to override this default behaviour and allow Rails to rescue
# exceptions and display an error page (just like when the app is running in production).
# Typical scenarios where you want to do this is when you test your error pages.
# There are two ways to allow Rails to rescue exceptions:
#
# 1) Tag your scenario (or feature) with @allow-rescue
#
# 2) Set the value below to true. Beware that doing this globally is not
# recommended as it will mask a lot of errors for you!
#
ActionController::Base.allow_rescue = false

# Remove this line if your app doesn't have a database.
# For some databases (like MongoDB and CouchDB) you may need to use :truncation instead.
#DatabaseCleaner.strategy = :transaction

# Stop endless errors like
# ~/.rvm/gems/ruby-1.9.2-p0@global/gems/rack-1.2.1/lib/rack/utils.rb:16:
# warning: regexp match /.../n against to UTF-8 string
$VERBOSE = nil


text:
/* ---------------- GroupUtils.js   ------------------
  Common Javascript group routines
  Created by Norm Thai - Enrich Consulting Inc.
  Created date: 06-25-2006
  Modified date:    by
 ---------------------------------------------------- */

function deselectOptions(the_Select) {
  var theOptions = the_Select.options;
  var idx_len = theOptions.length;
  var idx_cnt = 0;

  for (; idx_cnt < idx_len; idx_cnt++)
  {
    if (theOptions[idx_cnt].value == '')
      theOptions[idx_cnt].selected = false;
  }
}