text:
package cz.ivoa.vocloud.view;

import cz.ivoa.vocloud.downloader.DownloadManager;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

/**
 *
 * @author radio.koza
 */
@Named
@ViewScoped
public class RemoteDownloadBean implements Serializable {

    private String targetFolder;
    private String resourceUrl;

    private boolean showAuth = false;

    //authorization fields
    private String username;
    private String password;

    @EJB
    private DownloadManager manager;

    @PostConstruct
    protected void init() {
        targetFolder = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("targetFolder");
    }

    public String getTargetFolder() {
        return targetFolder;
    }

    public void setTargetFolder(String targetFolder) {
        this.targetFolder = targetFolder;
    }

    public String getResourceUrl() {
        return resourceUrl;
    }

    public void setResourceUrl(String resourceUrl) {
        this.resourceUrl = resourceUrl;
    }

    public boolean isShowAuth() {
        return showAuth;
    }

    public void setShowAuth(boolean showAuth) {
        this.showAuth = showAuth;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void download() {
        //validate username and pass if authorization mode is chosen
        if (showAuth) {
            if (username == null || username.trim().isEmpty() || password == null || password.isEmpty()){
                //show error message
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,  "Authorization error", "You must enter non empty username and password"));
                return;
            }
        }
        boolean result;
        if (showAuth){
            result = manager.enqueueNewURLDownload(resourceUrl, targetFolder, username.trim(), password);
        } else {
            result = manager.enqueueNewURLDownload(resourceUrl, targetFolder);
        }
        if (result){
            resourceUrl = "";
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New download was successfully enqueued"));
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,  "Download enqueue was unsuccessful", "URL address or used protocol is invalid"));
        }
    }

}


text:
import { shallow } from "enzyme";
import Immutable from "immutable";
import { formFields } from "testUtil";
import { cloneDeep } from "lodash/lang";

import { createReflectionFormValues } from "utils/accelerationUtils";

import { FormBody, ModalForm } from "components/Forms";
//import Button from '../Buttons/Button';
import { AccelerationForm } from "./AccelerationForm";

describe("AccelerationForm", () => {
  let minimalProps;
  let commonProps;
  let values;

  beforeEach(() => {
    values = {
      version: 1,
      aggregationReflections: [
        // WARNING: this might not be exactly accurate - but it's enough for the test
        createReflectionFormValues({
          id: "a",
          measureFields: [{ name: "cm1", measureTypeList: ["SUM", "COUNT"] }],
          dimensionFields: ["cd1"],
          type: "AGGREGATION",
          tag: "a",
          enabled: true,
        }),
        createReflectionFormValues({
          id: "c",
          measureFields: [{ name: "cm1", measureTypeList: ["SUM", "COUNT"] }],
          dimensionFields: ["cd1"],
          type: "AGGREGATION",
          tag: null,
          enabled: true,
        }),
      ],
      rawReflections: [
        // WARNING: this might not be exactly accurate - but it's enough for the test
        createReflectionFormValues({
          id: "b",
          displayFields: ["cm1"],
          type: "RAW",
          tag: "a",
          enabled: true,
        }),
        createReflectionFormValues({
          id: "d",
          displayFields: ["cm1"],
          type: "RAW",
          tag: null,
          enabled: true,
        }),
      ],
      columnsDimensions: [{ column: "cd1" }],
      columnsMeasures: [{ column: "cm1" }],
    };

    minimalProps = {
      handleSubmit: sinon.stub().returns(sinon.spy()),
      onSubmitSuccess: sinon.spy(),
      onCancel: sinon.spy(),
      location: {},
      dataset: Immutable.Map(),
      reflections: Immutable.Map(),
      values,
      fields: formFields(values),
      updateFormDirtyState: sinon.stub(),

      putReflection: sinon.stub().resolves(),
      postReflection: sinon.stub().resolves(),
      deleteReflection: sinon.stub().resolves(),
      lostFieldsByReflection: {},
    };
    commonProps = {
      showConfirmationDialog: sinon.stub(),
      fullPath: "",
      location: {},
      errors: {},
      submitFailed: false,
      ...minimalProps,
    };
  });

  it("should render with minimal props without exploding", () => {
    const wrapper = shallow(<AccelerationForm {...minimalProps} />);
    expect(wrapper).to.have.length(1);
  });

  it("should render with common props without exploding", () => {
    const wrapper = shallow(<AccelerationForm {...commonProps} />);
    expect(wrapper).to.have.length(1);
  });

  it("should render ModalForm with common props", () => {
    const wrapper = shallow(<AccelerationForm {...commonProps} />);
    expect(wrapper.find(ModalForm)).to.have.length(1);
  });

  it("should render FormBody with common props", () => {
    const wrapper = shallow(<AccelerationForm {...commonProps} />);
    expect(wrapper.find(FormBody)).to.have.length(1);
  });

  describe("#prepare", function () {
    let props;
    let expectedValues;
    beforeEach(() => {
      props = {
        ...commonProps,
      };
      expectedValues = [
        ...values.aggregationReflections,
        ...values.rawReflections,
      ];
    });

    it("should remove disabled RAW in BASIC (only)", function () {
      values.rawReflections[0].enabled = false;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      let result = instance.prepare(cloneDeep(values));
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });

      instance.setState({
        mode: "BASIC",
      });
      result = instance.prepare(cloneDeep(values));
      values.rawReflections[0].shouldDelete = true;
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });
    });

    it("should remove disabled AGGREGATION in BASIC (only) if unconfigured", function () {
      values.aggregationReflections[0].enabled = false;
      values.aggregationReflections[0].measureFields.length = 0;
      values.aggregationReflections[0].dimensionFields.length = 0;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      let result = instance.prepare(cloneDeep(values));
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });

      instance.setState({
        mode: "BASIC",
      });
      result = instance.prepare(cloneDeep(values));
      values.aggregationReflections[0].shouldDelete = true;
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });
    });

    it("should not remove disabled AGGREGATION in BASIC if configured", function () {
      values.aggregationReflections[0].enabled = false;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      instance.setState({
        mode: "BASIC",
      });
      const result = instance.prepare(cloneDeep(values));
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });
    });

    it("should validate raw reflection (missing display)", function () {
      values.rawReflections[0].displayFields.length = 0;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      expect(instance.prepare(cloneDeep(values))).to.be.eql({
        errors: {
          b: "At least one display field per raw Reflection is required.",
        },
        reflections: expectedValues,
      });
    });

    it("should validate aggregation reflection (missing measure and dimension)", function () {
      values.aggregationReflections[0].dimensionFields.length = 0;
      values.aggregationReflections[0].measureFields.length = 0;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      expect(instance.prepare(cloneDeep(values))).to.be.eql({
        errors: {
          a: "At least one dimension or measure field per aggregation Reflection is required.",
        },
        reflections: expectedValues,
      });
    });

    it("should not validate disabled aggregation reflection", function () {
      values.aggregationReflections[0].enabled = false;
      values.aggregationReflections[0].measureFields.length = 0;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      expect(instance.prepare(cloneDeep(values))).to.be.eql({
        errors: {},
        reflections: expectedValues,
      });
    });

    it("should filter new reflections that have been deleted", function () {
      values.rawReflections[1].displayFields.shouldDelete = true;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      values.rawReflections.length = 1;
      expect(instance.prepare(cloneDeep(values))).to.be.eql({
        errors: {},
        reflections: [
          ...values.aggregationReflections,
          ...values.rawReflections,
        ],
      });
    });

    it("all good", function () {
      const instance = shallow(<AccelerationForm {...props} />).instance();
      const result = instance.prepare(cloneDeep(values));
      expect(result).to.be.eql({ errors: {}, reflections: expectedValues });
    });
  });

  describe("#submitForm", function () {
    let props;
    beforeEach(() => {
      props = {
        ...commonProps,
      };
    });

    it("should ultimately reject if there is a client-side validation error", function () {
      values.rawReflections[0].displayFields.length = 0;
      const instance = shallow(<AccelerationForm {...props} />).instance();
      return expect(instance.submitForm(values)).to.be.rejected;
    });

    it("should ultimately reject if there is a server-side validation error", function () {
      commonProps.putReflection.rejects();
      const instance = shallow(<AccelerationForm {...props} />).instance();
      return expect(instance.submitForm(values)).to.be.rejected;
    });

    it.skip("all good", function () {
      const instance = shallow(<AccelerationForm {...props} />).instance();
      values.rawReflections.length = 1;
      values.rawReflections[0].shouldDelete = true;
      return instance.submitForm(values).then(() => {
        expect(commonProps.putReflection).to.have.been.calledWith(
          values.aggregationReflections[0]
        );
        expect(commonProps.postReflection).to.have.been.calledWith(
          values.aggregationReflections[1]
        );
        expect(commonProps.deleteReflection).to.have.been.calledWith(
          values.rawReflections[0]
        );
        return null;
      });
    });
  });

  describe("#renderExtraErrorMessages", () => {
    it("nothing", () => {
      const wrapper = shallow(<AccelerationForm {...commonProps} />);
      const instance = wrapper.instance();
      expect(instance.renderExtraErrorMessages().length).to.equal(0);
    });

    it("should render without nav warning if layout found", () => {
      const wrapper = shallow(<AccelerationForm {...commonProps} />);
      const instance = wrapper.instance();
      wrapper.setProps({
        location: { state: { layoutId: "a" } },
        reflections: Immutable.fromJS({
          a: Immutable.fromJS(values.aggregationReflections[0]).set(
            "status",
            Immutable.fromJS({})
          ),
        }),
      });
      expect(instance.renderExtraErrorMessages().length).to.equal(0);
    });

    it("should render just nav warning as needed", () => {
      const wrapper = shallow(<AccelerationForm {...commonProps} />);
      const instance = wrapper.instance();
      wrapper.setProps({
        location: { state: { layoutId: "foo" } },
        reflections: Immutable.fromJS({
          a: Immutable.fromJS(values.aggregationReflections[0]).set(
            "status",
            Immutable.fromJS({})
          ),
        }),
      });
      expect(instance.renderExtraErrorMessages().length).to.equal(1);
    });

    it("should render just INVALID warning as needed", () => {
      const wrapper = shallow(<AccelerationForm {...commonProps} />);
      const instance = wrapper.instance();
      wrapper.setProps({
        reflections: Immutable.fromJS({
          a: Immutable.fromJS(values.aggregationReflections[0]).set(
            "status",
            Immutable.fromJS({ config: "INVALID" })
          ),
        }),
      });
      expect(instance.renderExtraErrorMessages().length).to.equal(1);
    });

    it("should render all messages as needed", () => {
      const wrapper = shallow(<AccelerationForm {...commonProps} />);
      const instance = wrapper.instance();
      wrapper.setProps({
        location: { state: { layoutId: "foo" } },
        reflections: Immutable.fromJS({
          a: Immutable.fromJS(values.aggregationReflections[0]).set(
            "status",
            Immutable.fromJS({ config: "INVALID" })
          ),
        }),
      });
      expect(instance.renderExtraErrorMessages().length).to.equal(2);
    });
  });

  describe("formIsDirty", () => {
    it("should be initially set to false", () => {
      const instance = shallow(
        <AccelerationForm {...commonProps} />
      ).instance();
      expect(instance.state.formIsDirty).to.equal(false);
    });
    it("should be true after value change", () => {
      const instance = shallow(
        <AccelerationForm {...commonProps} />
      ).instance();
      instance.componentWillReceiveProps({
        ...commonProps,
        values: { ...values, rawReflections: [] },
      });
      expect(instance.state.formIsDirty).to.equal(true);
    });
    it("should be false after revert&submit/updateInitialValues", () => {
      const instance = shallow(
        <AccelerationForm {...commonProps} />
      ).instance();
      instance.componentWillReceiveProps({
        ...commonProps,
        values: { ...values, rawReflections: [] },
      });
      expect(instance.state.formIsDirty).to.equal(true);
      instance.updateInitialValues();
      setTimeout(() => {
        expect(instance.state.formIsDirty).to.equal(false);
      }, 1);
    });
  });
});

redpajama_set_name: RedPajamaGithub


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

			<title>Docs for page ex4.php</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

/ex4.php

Description

					Description |
									Includes

example 4  demonstrates recursive parse

link: $HeadURL:

version: $Id: ex4.php 16 2007-01-11 03:02:49Z cocomp $

filesource: Source Code for this file

see: license.txt LGPL / BSD license

copyright: Barnabas Debreceni 2000-2001

author: Barnabas Debreceni [cranx@users.sourceforge.net]

copyright: Jeremy Coates 2002-2007

author: Jeremy Coates [cocomp@users.sourceforge.net]

Includes

			Description |
						Includes

			include_once
			('./xtemplate.class.php')
			(line 17)

		Documentation generated on Tue, 29 May 2007 19:29:34 +0100 by phpDocumentor 1.3.0RC3


text:
#import <SalesforceSDKCore/SalesforceSDKCore.h>

@class CSFNetwork;
@interface SFUserAccount (SalesforceNetwork)

@property (nonatomic, strong, readonly) CSFNetwork *network;

@end


text:
package model;

import java.util.HashMap;

public class JudgingOutcomes {

	HashMap<Integer, InitialSubmission> initialSubmissions = new HashMap<Integer, InitialSubmission>();
	HashMap<InitialSubmission, TestCaseExecution> failedCase = new HashMap<InitialSubmission, TestCaseExecution>();

	public void newSubmission(InitialSubmission sub) {
		initialSubmissions.put(sub.id, sub);
	}

	public InitialSubmission getSubmission(Integer id) {
		return initialSubmissions.get(id);
	}

	public void testCaseRun(TestCaseExecution testCase) {
		if (!testCase.solved) {
			failedCase.put(testCase.submission, testCase);
		}
	}

	public TestCaseExecution getFailureInfo(InitialSubmission sub) {
		return failedCase.get(sub);
	}

}


text:
use std::{
    cmp::Ordering::{
        Equal,
        Greater,
        Less,
    },
    fs::File,
    io::BufReader,
    path::Path,
};

use serde::{
    Deserialize,
    Serialize,
};

use itertools::Itertools;
use sorted_iter::{
    assume::*,
    SortedPairIterator,
};

use anyhow::{
    anyhow,
    Result,
};

use polars::prelude::*;

#[derive(Serialize, Deserialize, Debug)]
pub struct UrsEntry {
    id: usize,
    urs: String,
    release: usize,
}

fn entries(path: &Path) -> Result<impl Iterator<Item = UrsEntry>> {
    let file = File::open(path)?;
    let buf = BufReader::new(file);
    let reader = csv::ReaderBuilder::new().has_headers(false).from_reader(buf);

    let records = reader.into_deserialize().filter_map(Result::ok);

    Ok(records)
}

pub fn write_max(filename: &Path, output: &Path) -> Result<()> {
    let out = rnc_utils::buf_writer(output)?;
    let mut writer = csv::Writer::from_writer(out);

    let results = entries(filename)?.group_by(|e: &UrsEntry| e.id);

    for (_, entries) in &results {
        let max = entries.max_by(|l, r| l.release.cmp(&r.release));
        match max {
            Some(v) => writer.serialize(v)?,
            None => (),
        }
    }
    writer.flush()?;

    Ok(())
}

pub fn select_new(xrefs: &Path, known: &Path, output: &Path) -> Result<()> {

    let mut xref_records : DataFrame = CsvReader::from_path(xrefs)?.has_header(false).finish().unwrap();
    xref_records.rename("column_1", "id").ok();
    xref_records.rename("column_2", "upi").ok();
    xref_records.rename("column_3", "last").ok();
    let mut known_records : DataFrame = CsvReader::from_path(known)?.has_header(false).finish().unwrap();
    known_records.rename("column_1", "id").ok();
    known_records.rename("column_2", "upi").ok();
    known_records.rename("column_3", "last").ok();
    // Run groupby, sort and max on xref (because the DB doesn't have the memory to do it)
    xref_records = xref_records.groupby(["id", "upi"])?
                .select(["last"])
                .max()?
                .sort(["id"], false)
                .unwrap();

    // Join the frames on id, then filter to select those where xref > known (?)
    let mut selection = xref_records.join(&known_records, ["id", "upi"], ["id", "upi"], JoinType::Outer, None)?;
    let mask = selection.column("last_max")?.gt(selection.column("last")?)?;
    let mut selected_upis = selection.filter(&mask).unwrap()
                                 .select(["upi"])?
                                 .unique(None, UniqueKeepStrategy::First)?;

    let out_stream : File = File::create(output).unwrap();
    CsvWriter::new(out_stream)
        .has_header(false)
        .finish(&mut selected_upis);

    Ok(())
}


text:
import Types from "../constants/ActionTypes";
<% actions.forEach(actionName => { %>
export function <%= actionName %>() {
  return {
    type: Types.<%= constantize(actionName) %>
  };
}
<% }); %>


text:
import os
from datetime import timedelta

from environ import Env
from raven import fetch_git_sha
from raven.exceptions import InvalidGitRepository

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
assert os.path.isfile(os.path.join(BASE_DIR, 'manage.py'))

#####################
# Local environment #
#####################
env = Env()
env.read_env(os.path.join(BASE_DIR, '.env'))

########################
# Django core settings #
########################
DEBUG = env.bool('DEBUG', default=False)
SECRET_KEY = env.str('SECRET_KEY', default=('' if not DEBUG else 'xxx'))
ALLOWED_HOSTS = ['*']

#########
# Paths #
#########
default_var_root = os.path.join(BASE_DIR, 'var')
user_var_root = os.path.expanduser('~/var')
if os.path.isdir(user_var_root):
    default_var_root = user_var_root
VAR_ROOT = env.str('VAR_ROOT', default_var_root)

# Create var root if it doesn't exist
if not os.path.isdir(VAR_ROOT):
    print('Creating var root %s' % VAR_ROOT)
    os.makedirs(VAR_ROOT)

MEDIA_ROOT = os.path.join(VAR_ROOT, 'media')
MEDIA_URL = '/media/'
ROOT_URLCONF = 'parkkihubi.urls'
STATIC_ROOT = os.path.join(VAR_ROOT, 'static')
STATIC_URL = '/static/'

############
# Database #
############
if os.environ.get('CI'):
    default_database_url = 'postgis://postgres:@localhost/parkkihubi'
else:
    default_database_url = 'postgis://parkkihubi:parkkihubi@localhost/parkkihubi'

DATABASES = {
    'default': env.db_url(
        default=default_database_url
    )
}

##########
# Caches #
##########
CACHES = {'default': env.cache_url(default='locmemcache://')}

##################
# Installed apps #
##################
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'raven.contrib.django.raven_compat',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_gis',
    'parkkihubi',
    'parkings',
]

if DEBUG:
    # shell_plus and other goodies
    INSTALLED_APPS.append("django_extensions")

##############
# Middleware #
##############
MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
]

#############
# Templates #
#############
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

##########
# Sentry #
##########
try:
    git_sha = fetch_git_sha(BASE_DIR)
except InvalidGitRepository:
    git_sha = None
RAVEN_CONFIG = {
    'dsn': env.str('SENTRY_DSN', default=None),
    'release': git_sha,
}

############################
# Languages & Localization #
############################
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Europe/Helsinki'
USE_I18N = True
USE_L10N = True
USE_TZ = True

########
# WSGI #
########
WSGI_APPLICATION = 'parkkihubi.wsgi.application'

##########
# Mailer #
##########
vars().update(env.email_url(
    default=('consolemail://' if DEBUG else 'smtp://localhost:25')
))

#########################
# Django REST Framework #
#########################
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
    'ALLOWED_VERSIONS': ('v1',),
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'EXCEPTION_HANDLER': 'parkings.exception_handler.parkings_exception_handler',
    'PAGE_SIZE': 20,
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}

##############
# Parkkihubi #
##############
PARKKIHUBI_TIME_EDITABLE = timedelta(minutes=2)
PARKKIHUBI_PUBLIC_API_ENABLED = env.bool('PARKKIHUBI_PUBLIC_API_ENABLED', True)
PARKKIHUBI_OPERATOR_API_ENABLED = env.bool('PARKKIHUBI_OPERATOR_API_ENABLED', True)
PARKKIHUBI_INTERNAL_API_ENABLED = env.bool('PARKKIHUBI_INTERNAL_API_ENABLED', False)


text:
var express = require('express');
var router = express.Router();

var Msg91uModel = require('../model/msg91u_model');
var UserModel = require('../model/user_model');

router.get('/', checkUserId);
router.get('/', function (req, res) {
  Msg91uModel
    .findAll({
      where: {receiver: req.query.user_id},
      offset: req.query.offset || 0,
      limit: req.query.size || 10,
      order: 'id DESC'
    })
    .then(function (msgs) {
      res.json(msgs);
    });
});

function checkUserId(req, res, next) {
  UserModel
    .findById(req.query.user_id)
    .then(function (user) {
      if (user) {
        req.user = user;
        next();
      } else {
        res.status(400);
        res.json({msg: '用户不存在'});
      }
    });
}

module.exports = router;


text:
package org.wso2.carbon.event.input.adaptor.email.internal;

import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.InOnlyAxisOperation;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEvent;
import org.apache.axis2.transport.mail.MailConstants;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.event.input.adaptor.core.InputEventAdaptorListener;
import org.wso2.carbon.event.input.adaptor.core.config.InputEventAdaptorConfiguration;
import org.wso2.carbon.event.input.adaptor.core.message.config.InputEventAdaptorMessageConfiguration;
import org.wso2.carbon.event.input.adaptor.email.internal.util.EmailEventAdaptorConstants;

import javax.xml.namespace.QName;
import java.util.List;

public class Axis2Util {

    private Axis2Util() {
    }

    public static AxisService registerAxis2EmailService(
            InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
            InputEventAdaptorListener eventAdaptorListener,
            InputEventAdaptorConfiguration inputEventAdaptorConfiguration,
            AxisConfiguration axisConfiguration, String subscriptionId) throws AxisFault {
        //first create an Axis2 service to receive the messages to this broker
        //operation name can not have
        String axisServiceName = inputEventAdaptorConfiguration.getName() + "Service";
        AxisService axisService = axisConfiguration.getService(axisServiceName);
        if (axisService == null) {
            // create a new axis service
            axisService = new AxisService(axisServiceName);
            axisService.addParameter(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_ADDRESS, inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_ADDRESS));
            axisService.addParameter(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_PROTOCOL, inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_PROTOCOL));
            axisService.addParameter(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_POLL_INTERVAL, inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_POLL_INTERVAL));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".host", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_PROTOCOL_HOST));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".port", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_PROTOCOL_PORT));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".user", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_USERNAME));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".password", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_PASSWORD));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".socketFactory.class", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_SOCKET_FACTORY_CLASS));
            axisService.addParameter("mail." + inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.BROKER_CONF_EMAIL_PROTOCOL) + ".socketFactory.fallback", inputEventAdaptorConfiguration.getInputProperties().get(EmailEventAdaptorConstants.ADAPTOR_CONF_RECEIVING_EMAIL_SOCKET_FACTORY_FALLBACK));
            axisService.addParameter("transport.mail.ContentType", "text/plain");

//            axisService = new AxisService(axisServiceName);
//            axisService.addParameter("transport.mail.Address", "wso2cep.demo@gmail.com");
//            axisService.addParameter("transport.mail.Protocol", "pop3");
//            axisService.addParameter("transport.PollInterval", "5");
//            axisService.addParameter("mail.pop3.host", "pop.gmail.com");
//            axisService.addParameter("mail.pop3.port", "995");
//            axisService.addParameter("mail.pop3.user", "suhothayan");
//            axisService.addParameter("mail.pop3.password", "hhjhkjjlkj");
//            axisService.addParameter("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//            axisService.addParameter("mail.pop3.socketFactory.fallback", "false");
////            axisService.addParameter("transport.mail.ContentType","application/xml");
//            axisService.addParameter("transport.mail.ContentType", "text/plain");
////            axisService.setEPRs(new String[]{"wso2cep.demo@gmail.com"});

//            <parameter name="transport.mail.Address">synapse.demo.1@gmail.com</parameter>
//            <parameter name="transport.mail.Protocol">pop3</parameter>
//            <parameter name="transport.PollInterval">5</parameter>
//            <parameter name="mail.pop3.host">pop.gmail.com</parameter>
//            <parameter name="mail.pop3.port">995</parameter>
//            <parameter name="mail.pop3.user">synapse.demo.1</parameter>
//            <parameter name="mail.pop3.password">mailpassword</parameter>
//            <parameter name="mail.pop3.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
//            <parameter name="mail.pop3.socketFactory.fallback">false</parameter>
//            <parameter name="mail.pop3.socketFactory.port">995</parameter>
//            <parameter name="transport.mail.ContentType">application/xml</parameter>

            axisConfiguration.addService(axisService);
            axisService.getAxisServiceGroup().addParameter(CarbonConstants.DYNAMIC_SERVICE_PARAM_NAME, "true");
        }

        String operationName = inputEventAdaptorMessageConfiguration.getInputMessageProperties().get(EmailEventAdaptorConstants.ADAPTOR_MESSAGE_RECEIVING_EMAIL_SUBJECT);
        AxisOperation axisOperation = axisService.getOperation(new QName("", operationName));
        if (axisOperation == null) {
            axisOperation = new InOnlyAxisOperation(new QName("", operationName));
            axisOperation.setMessageReceiver(new SubscriptionEmailMessageReceiver());
            axisOperation.setSoapAction("urn:" + operationName);

            axisConfiguration.getPhasesInfo().setOperationPhases(axisOperation);
            axisService.addOperation(axisOperation);
        }
        List<String> transports = axisService.getExposedTransports();
        transports.clear();
        transports.add(MailConstants.TRANSPORT_NAME);
        axisService.setExposedTransports(transports);

        SubscriptionEmailMessageReceiver messageReceiver =
                (SubscriptionEmailMessageReceiver) axisOperation.getMessageReceiver();
        messageReceiver.addEventAdaptorListener(subscriptionId, eventAdaptorListener);

//        AxisEvent serviceUpdateEvent = new AxisEvent(AxisEvent.SERVICE_DEPLOY,axisService);
        axisConfiguration.notifyObservers(new AxisEvent(AxisEvent.SERVICE_REMOVE, axisService), axisService);
        axisConfiguration.notifyObservers(new AxisEvent(AxisEvent.SERVICE_DEPLOY, axisService), axisService);

        return axisService;
    }

    /**
     * removes the operation from the Axis service.
     *
     * @param inputEventAdaptorMessageConfiguration
     *
     * @param inputEventAdaptorConfiguration
     * @param axisConfiguration
     * @param subscriptionId
     * @throws AxisFault
     */
    public static void removeEmailServiceOperation(
            InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
            InputEventAdaptorConfiguration inputEventAdaptorConfiguration,
            AxisConfiguration axisConfiguration, String subscriptionId) throws AxisFault {

        String axisServiceName = inputEventAdaptorConfiguration.getName() + "Service";
        AxisService axisService = axisConfiguration.getService(axisServiceName);

        if (axisService == null) {
            throw new AxisFault("There is no service with the name ==> " + axisServiceName);
        }
        String operationName = inputEventAdaptorMessageConfiguration.getInputMessageProperties().get(EmailEventAdaptorConstants.ADAPTOR_MESSAGE_RECEIVING_EMAIL_SUBJECT);
        AxisOperation axisOperation = axisService.getOperation(new QName("", operationName));
        if (axisOperation == null) {
            throw new AxisFault("There is no operation with the name ==> " + operationName);
        }
        SubscriptionEmailMessageReceiver messageReceiver =
                (SubscriptionEmailMessageReceiver) axisOperation.getMessageReceiver();
        if (messageReceiver == null) {
            throw new AxisFault("There is no message receiver for operation with name ==> " + operationName);
        }
        if (messageReceiver.removeEventAdaptorListener(subscriptionId)) {
            axisService.removeOperation(new QName("", operationName));
        }

        AxisEvent serviceUpdateEvent = new AxisEvent(AxisEvent.SERVICE_DEPLOY, axisService);
        axisConfiguration.notifyObservers(serviceUpdateEvent, axisService);

    }

}


text:
#Region "Microsoft.VisualBasic::baf821cd73bf8a39b2116cbce1d583ea, src\mzmath\TargetedMetabolomics\GCMS\mzMLReader\TimeScanMatrix.vb"

    ' Author:
    '
    '       xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
    '
    ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
    '
    '
    ' MIT License
    '
    '
    ' Permission is hereby granted, free of charge, to any person obtaining a copy
    ' of this software and associated documentation files (the "Software"), to deal
    ' in the Software without restriction, including without limitation the rights
    ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    ' copies of the Software, and to permit persons to whom the Software is
    ' furnished to do so, subject to the following conditions:
    '
    ' The above copyright notice and this permission notice shall be included in all
    ' copies or substantial portions of the Software.
    '
    ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    ' SOFTWARE.

    ' /********************************************************************************/

    ' Summaries:

    '     Class TimeScanMatrix
    '
    '         Constructor: (+1 Overloads) Sub New
    '         Function: CreateMatrixHelper, TimeScan
    '
    '
    ' /********************************************************************************/

#End Region

Imports stdNum = System.Math

Namespace GCMS

    Public Class TimeScanMatrix

        ReadOnly mz_scanList As List(Of ms1_scan)()
        ReadOnly mzList As Double()

        Private Sub New(mzScans As ms1_scan()())
            mzList = mzScans.Select(Function(mzi) mzi(Scan0).mz).ToArray
            mz_scanList = mzScans.Select(Function(mz) mz.ToList).ToArray
        End Sub

        Public Iterator Function TimeScan(time As Double) As IEnumerable(Of ms1_scan)
            For i As Integer = 0 To mz_scanList.Length - 1
                Dim list = mz_scanList(i)
                Dim tick As ms1_scan = list _
                    .Where(Function(t) stdNum.Abs(t.scan_time - time) <= 0.5) _
                    .FirstOrDefault

                If tick Is Nothing Then
                    Yield New ms1_scan With {
                        .intensity = 0,
                        .mz = mzList(i),
                        .scan_time = time
                    }
                Else
                    list.Remove(tick)
                    Yield tick
                End If
            Next
        End Function

        Friend Shared Function CreateMatrixHelper(mzScans As ms1_scan()()) As TimeScanMatrix
            Return New TimeScanMatrix(mzScans)
        End Function
    End Class
End Namespace


text:
var Counter, should, _chai;

if (typeof require !== "undefined" && require !== null) {
  console.log('require exists and is a function.  Going to assume we are in a Node.js environment.');
  _chai = require('chai');
  Counter = require('../src/counter')["class"];
  should = _chai.should();
} else {
  should = this['chai'].should();
}

describe('Counter', function() {
  describe('contructor', function() {
    return it('should set defaults correctly', function() {
      var _counter;
      _counter = new Counter(3);
      _counter.expected.should.be.a.Number;
      _counter.expected.should.equal(3);
      _counter.actual.should.be.a.Number;
      return _counter.actual.should.equal(0);
    });
  });
  describe('#add()', function() {
    return it('should add correctly', function() {
      var _counter;
      _counter = new Counter(3);
      _counter.add();
      _counter.add();
      _counter.actual.should.be.a.Number;
      return _counter.actual.should.equal(2);
    });
  });
  return describe('#assert()', function() {
    it('should not throw when @actual == @expected', function() {
      var _counter;
      _counter = new Counter(1);
      _counter.add();
      return _counter.assert.should.not["throw"];
    });
    return it('should throw when @actual != @expected', function() {
      var _counter;
      _counter = new Counter(5);
      _counter.add();
      return _counter.assert.should["throw"](Error);
    });
  });
});


text:
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>Role Space</title>
	<link rel="stylesheet" href="rolespace.css">

			</img


text:
/**
 * @fileoverview FirebaseUI app builder.
 * This helps support multiple instances of FirebaseUI configuration.
 */

goog.provide('firebaseui.auth.AuthUI');

goog.require('firebaseui.auth.EventDispatcher');
goog.require('firebaseui.auth.log');
goog.require('firebaseui.auth.storage');
goog.require('firebaseui.auth.util');
goog.require('firebaseui.auth.widget.Config');
goog.require('firebaseui.auth.widget.dispatcher');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleCallback');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleEmailChangeRevocation');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleEmailMismatch');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleEmailVerification');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleFederatedLinking');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleFederatedSignIn');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePasswordLinking');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePasswordRecovery');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePasswordReset');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePasswordSignIn');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePasswordSignUp');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePhoneSignInFinish');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handlePhoneSignInStart');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleProviderSignIn');
/** @suppress {extraRequire} */
goog.require('firebaseui.auth.widget.handler.handleSignIn');
goog.require('firebaseui.auth.widget.handler.startSignIn');
goog.require('goog.Promise');
goog.require('goog.array');
goog.require('goog.events');
goog.require('goog.events.EventType');

/**
 * @param {!firebase.auth.Auth} auth The Firebase Auth instance.
 * @param {string=} opt_appId The optional app id.
 * @constructor
 */
firebaseui.auth.AuthUI = function(auth, opt_appId) {
  /** @private {boolean} Whether the current instance is deleted. */
  this.deleted_ = false;
  // Check if an instance with the same key exists. If so, throw an error,
  // otherwise, save that instance.
  // Get the instance get.
  var key = firebaseui.auth.AuthUI.getInstanceKey_(opt_appId);
  if (firebaseui.auth.AuthUI.instances_[key]) {
    // An instance exists for this key. Throw an error.
    throw new Error(
        'An AuthUI instance already exists for the key "' + key + '"');
  } else {
    // New instance, save reference to it.
    firebaseui.auth.AuthUI.instances_[key] = this;
  }
  /** @private {!firebase.auth.Auth} The Firebase Auth instance. */
  this.auth_ = auth;
  var tempApp = firebase.initializeApp({
    'apiKey': auth['app']['options']['apiKey'],
    'authDomain': auth['app']['options']['authDomain']
  }, auth['app']['name'] + firebaseui.auth.AuthUI.TEMP_APP_NAME_SUFFIX_);
  /**
   * @private {!firebase.auth.Auth} The temporary internal Firebase Auth
   *     instance.
   */
  this.tempAuth_ = tempApp.auth();
  /** @private {string|undefined} The optional app id. */
  this.appId_ = opt_appId;
  /** @private {!firebaseui.auth.widget.Config} The AuthUI configuration. */
  this.config_ = new firebaseui.auth.widget.Config();
  /**
   * @private {?firebaseui.auth.EventDispatcher} The event dispatcher for
   *     triggering custom events on DOM objects.
   */
  this.widgetEventDispatcher_ = null;
  /**
   * @private {?goog.Promise<!firebase.auth.UserCredential>} The result from
   *     any pending sign in with redirect operation.
   */
  this.getRedirectResult_ = null;
  /**
   * @private {?Element} The current widget element container. Only one widget
   *     instance can be created per page.
   */
  this.widgetElement_ = null;
  /**
   * @private {?firebaseui.auth.ui.page.Base} The currently rendered component.
   */
  this.currentComponent_ = null;
  /**
   * @private {!Array<!goog.Promise|!firebase.Promise|!function()>} The array of
   *     pending promises or reset functions.
   */
  this.pending_ = [];
};

/** Resets all internal globals. Used for testing only. */
firebaseui.auth.AuthUI.resetAllInternals = function() {
  firebaseui.auth.AuthUI.instances_ = {};
  firebaseui.auth.AuthUI.widgetElement_ = null;
};

/**
 * @private {!Object.<!string, !firebaseui.auth.AuthUI>} Map containing the
 *     firebaseui.auth.AuthUI instances keyed by their app IDs.
 */
firebaseui.auth.AuthUI.instances_ = {};

/**
 * Returns the instance key corresponding the appId provided.
 * @param {?string=} opt_appId The optional app ID whose instance is to be
 *     provided.
 * @return {string} The key corresponding to the provided app ID.
 * @private
 */
firebaseui.auth.AuthUI.getInstanceKey_ = function(opt_appId) {
  return opt_appId || firebaseui.auth.AuthUI.DEFAULT_INSTANCE_KEY_;
};

/**
 * Returns the AuthUI instance corresponding to the appId provided.
 * @param {?string=} opt_appId The optional app ID whose instance is to be
 *     provided.
 * @return {?firebaseui.auth.AuthUI} The AuthUI instance corresponding to the
 *     app ID provided.
 */
firebaseui.auth.AuthUI.getInstance = function(opt_appId) {
  var key = firebaseui.auth.AuthUI.getInstanceKey_(opt_appId);
  if (firebaseui.auth.AuthUI.instances_[key]) {
    return firebaseui.auth.AuthUI.instances_[key];
  }
  return null;
};

/**
 * The suffix of the temp Auth instance app name.
 * @const {string}
 * @private
 */
firebaseui.auth.AuthUI.TEMP_APP_NAME_SUFFIX_ = '-firebaseui-temp';

/**
 * The default instance key when no app ID is provided.
 * @const {string}
 * @private
 */
firebaseui.auth.AuthUI.DEFAULT_INSTANCE_KEY_ = '[DEFAULT]';

/**
 * If sign-in succeeded, returns the signed in user. If sign-in was
 * unsuccessful, fails with an error. If no redirect operation was called,
 * returns a UserCredential with a null User.
 *
 * @return {!goog.Promise<!firebase.auth.UserCredential>} a UserCredential
 *     from the redirect-based sign-in flow.
 */
firebaseui.auth.AuthUI.prototype.getRedirectResult = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  if (!this.getRedirectResult_) {
    this.getRedirectResult_ = goog.Promise.resolve(
        this.getAuth().getRedirectResult());
  }
  return this.getRedirectResult_;
};

/**
 * @param {!firebaseui.auth.ui.page.Base} component The current rendered
 *     component.
 */
firebaseui.auth.AuthUI.prototype.setCurrentComponent = function(component) {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  this.currentComponent_ = component;
};

/**
 * The description of the error message raised when the widget element is not
 * found during initialization.
 * @const {string}
 * @private
 */
firebaseui.auth.AuthUI.ELEMENT_NOT_FOUND_ = 'Could not find the FirebaseUI ' +
    'widget element on the page.';

/**
 * @private {?firebaseui.auth.AuthUI} The current widget AuthUI instance. Only
 *     one authui widget instance can be created per page.
 */
firebaseui.auth.AuthUI.widgetAuthUi_ = null;

/** @return {?firebaseui.auth.AuthUI} The current widget AuthUI instance. */
firebaseui.auth.AuthUI.getAuthUi = function() {
  return firebaseui.auth.AuthUI.widgetAuthUi_;
};

/**
 * @return {!firebase.auth.Auth} The temporary internal Firebase Auth instance.
 *     This is used to avoid triggering onAuthStateChanged observer on the
 *     developer provided Auth instance.
 */
firebaseui.auth.AuthUI.prototype.getAuth = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return this.tempAuth_;
};

/**
 * @return {!firebase.auth.Auth} The original developer provided Firebase auth
 *     instance.
 */
firebaseui.auth.AuthUI.prototype.getExternalAuth = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return this.auth_;
};

/**
 * @return {string|undefined} The app id if provided.
 */
firebaseui.auth.AuthUI.prototype.getAppId = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return this.appId_;
};

/**
 * Returns true if there is any pending operations to be resolved by the widget.
 * It is required in some cases like linking flows, where the user can become
 * signed in and the widget still has to perform some operations (linking)
 * before the sign-in state can be displayed in the app.
 * When this flag is true, the widget HAS to be rendered.
 * @return {boolean} Whether the app has pending operations to be performed.
 */
firebaseui.auth.AuthUI.prototype.isPending = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return firebaseui.auth.storage.hasPendingEmailCredential(this.getAppId());
};

/**
 * Handles the FirebaseUI operation.
 * An {@code Error} is thrown if the the developer tries to run this operation
 * more than once.
 *
 * @param {string|!Element} element The container element or the query selector.
 * @param {Object} config The configuration for sign-in button.
 */
firebaseui.auth.AuthUI.prototype.start = function(element, config) {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  var self = this;

  // There is a problem when config in second call modifies accountchooser.com
  // related config. eg. acUiConfig
  // These changes will be ignored as only the first accountchooser.com related
  // config will be applied.
  this.setConfig(config);

  var doc = goog.global.document;
  // Wrap it in a onload callback to wait for the DOM element is rendered.
  // If document already loaded, render immediately.
  if (doc.readyState == 'complete') {
    this.initElement_(element);
  } else {
    // Document not ready, wait for load before rendering.
    goog.events.listenOnce(window, goog.events.EventType.LOAD, function() {
      self.initElement_(element);
    });
  }
};

/**
 * Initializes the FirebaseUI element.
 * @param {string|!Element} element The container element or the query selector.
 * @private
 */
firebaseui.auth.AuthUI.prototype.initElement_ = function(element) {
  // Confirm element exists.
  var container = firebaseui.auth.util.getElement(
      element, firebaseui.auth.AuthUI.ELEMENT_NOT_FOUND_);

  // Set the "lang" attribute; without this, there are subtle rendering errors
  // like vowel capitalization in Turkish.

  // Make sure the locale uses hyphens instead of strings.
  var locale = goog.LOCALE.replace(/_/g, '-');
  container.setAttribute('lang', locale);

  // Only one auth instance can be rendered per page. This is because
  // accountchooser.com callbacks are set once to the AuthUI instance that
  // first calls them.
  if (firebaseui.auth.AuthUI.widgetAuthUi_) {
    // Already rendered, automatically reset.
    // First check if there is a pending operation on that widget, if so,
    // log a reset warning to the console.
    if (firebaseui.auth.AuthUI.widgetAuthUi_.isPending()) {
      var resetWarning = 'UI Widget is already rendered on the page and is ' +
          'pending some user interaction. Only one widget instance can be ' +
          'rendered per page. The previous instance has been automatically ' +
          'reset.';
      firebaseui.auth.log.warning(resetWarning);
    }
    firebaseui.auth.AuthUI.widgetAuthUi_.reset();
  }

  // Set widget AuthUI as current instance.
  firebaseui.auth.AuthUI.widgetAuthUi_ = this;

  this.widgetElement_ = container;
  // Initialize widget page change listener.
  this.initPageChangeListener_(container);
  // Document already loaded, render on demand.
  firebaseui.auth.widget.dispatcher.dispatchOperation(this, element);
};

/**
 * Registers a pending promise or reset function.
 * @param {?goog.Promise|?firebase.Promise|?function()} p The pending promise.
 */
firebaseui.auth.AuthUI.prototype.registerPending = function(p) {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  var self = this;
  if (p) {
    this.pending_.push(p);
    var remove = function() {
      goog.array.removeAllIf(self.pending_, function(ele) {
        return ele == p;
      });
    };
    // Remove pending promise on resolve or reject.
    if (typeof p != 'function') {
      p.then(remove, remove);
    }
  }
};

/**
 * @return {function():?firebaseui.auth.AuthUI} The Firebase Auth instance
 *     getter.
 */
firebaseui.auth.AuthUI.prototype.getAuthUiGetter = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return firebaseui.auth.AuthUI.getAuthUi;
};

/** Reset rendered widget and removes it from display. */
firebaseui.auth.AuthUI.prototype.reset = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  // Remove the "lang" attribute that we set in start().
  if (this.widgetElement_) {
    this.widgetElement_.removeAttribute('lang');
  }

  // After reset, if the sign-in widget callback is called again, it should not
  // resolve with the previous redirect result.
  this.getRedirectResult_ =
      /** @type {!goog.Promise<!firebase.auth.UserCredential>} */ (
      goog.Promise.resolve({
        'user': null,
        'credential': null
      }));
  // Reset widget AuthUI if it is the current instance.
  if (firebaseui.auth.AuthUI.widgetAuthUi_ == this) {
    firebaseui.auth.AuthUI.widgetAuthUi_ = null;
  }
  this.widgetElement_ = null;
  // Cancel all pending promises or run reset functions.
  for (var i = 0; i < this.pending_.length; i++) {
    if (typeof this.pending_[i] == 'function') {
      /** @type{!function()} */ (this.pending_[i])();
    } else {
      // firebase.Promise may use the native Promise which does not have a
      // cancel method. Only goog.Promise offers that.
      if (this.pending_[i].cancel) {
        this.pending_[i].cancel();
      }
    }
  }
  // Clear all pending promises and reset functions.
  this.pending_ = [];
  // Remove pending email credential.
  firebaseui.auth.storage.removePendingEmailCredential(this.getAppId());
  // Dispose any remaining widget UI.
  if (this.currentComponent_) {
    this.currentComponent_.dispose();
    this.currentComponent_ = null;
  }
  // Reset current page id.
  this.currentPageId_ = null;
};

/**
 * Initializes the widget page change listener. On page change, triggers the UI
 * changed callback if provided.
 *
 * @param {Element} element The widget container element.
 * @private
 */
firebaseui.auth.AuthUI.prototype.initPageChangeListener_ = function(element) {
  var self = this;
  /** @private {?string} Current page id. */
  this.currentPageId_ = null;
  // Initialize the event dispatcher on the widget element.
  this.widgetEventDispatcher_ = new firebaseui.auth.EventDispatcher(element);
  // Register event dispatcher.
  this.widgetEventDispatcher_.register();
  // Listen to the pageEnter events.
  goog.events.listen(
      this.widgetEventDispatcher_,
      'pageEnter',
      function(event) {
        // Get new page id.
        var newPageId = event && event.pageId;
        // If page change detected.
        if (self.currentPageId_ != newPageId) {
          // Get UI changed callback.
          var uiChangedCallback = self.getConfig().getUiChangedCallback();
          if (uiChangedCallback) {
            // If UI changed callback provided, trigger it.
            uiChangedCallback(self.currentPageId_, newPageId);
          }
          // Update current page id.
          self.currentPageId_ = newPageId;
        }
      });
};

/**
 * Updates the configuration and its descendants with the given value.
 *
 * @param {string} name The name of the configuration.
 * @param {*} value The value of the configuration.
 */
firebaseui.auth.AuthUI.prototype.updateConfig = function(name, value) {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  this.config_.update(name, value);
};

/**
 * Sets the app configuration.
 * @param {Object} config The application configuration.
 */
firebaseui.auth.AuthUI.prototype.setConfig = function(config) {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  this.config_.setConfig(config);
};

/**
 * @return {firebaseui.auth.widget.Config} The application configuration.
 */
firebaseui.auth.AuthUI.prototype.getConfig = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  return this.config_;
};

/**
 * Triggers the sign-in flow.
 */
firebaseui.auth.AuthUI.prototype.signIn = function() {
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  firebaseui.auth.widget.handler.startSignIn(this);
};

/**
 * Checks if the instance is destroyed. If so, throws an error.
 * @private
 */
firebaseui.auth.AuthUI.prototype.checkIfDestroyed_ = function() {
  if (this.deleted_) {
    throw new Error('AuthUI instance is deleted!');
  }
};

/**
 * Destroys the AuthUI instance.
 * @return {!firebase.Promise} The promise that resolves when the instance
 *     is successfully deleted.
 */
firebaseui.auth.AuthUI.prototype.delete = function() {
  var self = this;
  // Check if instance is already destroyed.
  this.checkIfDestroyed_();
  // Delete the temporary app instance.
  return this.tempAuth_.app.delete().then(function() {
    // Get instance key.
    var key = firebaseui.auth.AuthUI.getInstanceKey_(self.getAppId());
    // Delete any saved AuthUI instance.
    delete firebaseui.auth.AuthUI.instances_[key];
    // Reset current instance.
    self.reset();
    // Mark as deleted.
    self.deleted_ = true;
  });
};


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.07 at 08:01:35 PM IST
//

package com.mozu.qbintegration.model.qbmodel.allgen;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for TxnVoidRqType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="TxnVoidRqType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <group ref="{}TxnVoid"/>
 *       </sequence>
 *       <attribute name="requestID" type="{}STRTYPE" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TxnVoidRqType", propOrder = {
    "txnVoidType",
    "txnID"
})
public class TxnVoidRqType {

    @XmlElement(name = "TxnVoidType", required = true)
    protected String txnVoidType;
    @XmlElement(name = "TxnID", required = true)
    protected String txnID;
    @XmlAttribute(name = "requestID")
    protected String requestID;

    /**
     * Gets the value of the txnVoidType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTxnVoidType() {
        return txnVoidType;
    }

    /**
     * Sets the value of the txnVoidType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTxnVoidType(String value) {
        this.txnVoidType = value;
    }

    /**
     * Gets the value of the txnID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTxnID() {
        return txnID;
    }

    /**
     * Sets the value of the txnID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTxnID(String value) {
        this.txnID = value;
    }

    /**
     * Gets the value of the requestID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRequestID() {
        return requestID;
    }

    /**
     * Sets the value of the requestID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRequestID(String value) {
        this.requestID = value;
    }

}


text:
  //= link_tree ../images
  //= link_directory ../javascripts .js
  //= link_directory ../stylesheets .css


text:
{% extends "weixin_base.html" %}
{% block link %}
    <link href="/static/css/weixin_text.css" rel="stylesheet" media="screen">
{% endblock %}

{% block header %}

{% endblock %}

{% block body %}

{{ rich_text.title }}

                {% autoescape off %}
                    {{ rich_text.html }}
                {% endautoescape %}

    {% autoescape off %}
        {{ rich_text.footer_templates }}
    {% endautoescape %}

{% endblock %}


text:
- Before you can pitch, your submissions are due at 5pm MTN on April 15, 2018.
- Pitching begins for Challenge Weekend at 6pm.
- Each team will get 5 minutes to pitch and 5 minutes for Q&A from the judges.

## Presentation Best Practices

Get meta and check out this presentation https://docs.google.com/presentation/d/1ksjDX7LkUIXim6dUrLQ_YfWBRSrGA3nsbLDaGuaj1QM/edit#slide=id.g35bec98cf8_0_35


text:
package tonius.neiintegration.mods.forestry36;

import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import tonius.neiintegration.PositionedFluidTank;
import tonius.neiintegration.RecipeHandlerBase;
import tonius.neiintegration.Utils;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.API;
import forestry.api.fuels.FermenterFuel;
import forestry.api.fuels.FuelManager;
import forestry.api.recipes.IVariableFermentable;
import forestry.factory.gadgets.MachineFermenter;

public class RecipeHandlerFermenter extends RecipeHandlerBase {

    private static Class<? extends GuiContainer> guiClass;

    @Override
    public void prepare() {
        guiClass = Utils.getClass("forestry.factory.gui.GuiFermenter");
        API.setGuiOffset(guiClass, 5, 15);
    }

    public class CachedFermenterRecipe extends CachedBaseRecipe {

        public List<PositionedFluidTank> tanks = new ArrayList<PositionedFluidTank>();
        public PositionedStack resource;
        public List<PositionedStack> inputItems = new ArrayList<PositionedStack>();

        public CachedFermenterRecipe(MachineFermenter.Recipe recipe, ItemStack fermentable, boolean genPerms) {
            if (recipe.liquid != null) {
                FluidStack input = recipe.liquid.copy();
                input.amount = recipe.fermentationValue;
                this.tanks.add(new PositionedFluidTank(input, 10000, new Rectangle(30, 4, 16, 58), RecipeHandlerFermenter.this.getGuiTexture(), new Point(176, 0)));
            }
            if (recipe.output != null) {
                FluidStack output = recipe.output.copy();
                if (fermentable.getItem() instanceof IVariableFermentable) {
                    output.amount = (int) (recipe.fermentationValue * recipe.modifier * ((IVariableFermentable) fermentable.getItem()).getFermentationModifier(fermentable));
                } else {
                    output.amount = (int) (recipe.fermentationValue * recipe.modifier);
                }
                this.tanks.add(new PositionedFluidTank(output, 10000, new Rectangle(120, 4, 16, 58), RecipeHandlerFermenter.this.getGuiTexture(), new Point(176, 0)));
            }

            this.inputItems.add(new PositionedStack(fermentable, 80, 8));
            List<ItemStack> fuels = new ArrayList<ItemStack>();
            for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) {
                fuels.add(fuel.item);
            }
            this.inputItems.add(new PositionedStack(fuels, 70, 42));

            if (genPerms) {
                this.generatePermutations();
            }
        }

        public CachedFermenterRecipe(MachineFermenter.Recipe recipe, ItemStack fermentable) {
            this(recipe, fermentable, false);
        }

        public CachedFermenterRecipe(MachineFermenter.Recipe recipe) {
            this(recipe, recipe.resource, true);
        }

        @Override
        public List<PositionedStack> getIngredients() {
            return this.getCycledIngredients(RecipeHandlerFermenter.this.cycleticks / 40, this.inputItems);
        }

        @Override
        public PositionedStack getResult() {
            return null;
        }

        @Override
        public List<PositionedFluidTank> getFluidTanks() {
            return this.tanks;
        }

        public void generatePermutations() {
            for (PositionedStack p : this.inputItems) {
                p.generatePermutations();
            }
        }

    }

    @Override
    public String getRecipeID() {
        return "forestry.fermenter";
    }

    @Override
    public String getRecipeName() {
        return Utils.translate("tile.for.factory.3.name", false);
    }

    @Override
    public String getGuiTexture() {
        return "forestry:textures/gui/fermenter.png";
    }

    @Override
    public void loadTransferRects() {
        this.addTransferRect(76, 27, 14, 12);
    }

    @Override
    public Class<? extends GuiContainer> getGuiClass() {
        return guiClass;
    }

    @Override
    public void drawBackground(int recipe) {
        this.changeToGuiTexture();
        GuiDraw.drawTexturedModalRect(25, 0, 30, 15, 116, 65);
    }

    @Override
    public void drawExtras(int recipe) {
        this.drawProgressBar(69, 17, 176, 60, 4, 18, 40, 11);
        this.drawProgressBar(93, 31, 176, 78, 4, 18, 80, 11);
    }

    private List<CachedFermenterRecipe> getCachedRecipes(MachineFermenter.Recipe recipe, boolean generatePermutations) {
        if (recipe.resource != null && recipe.resource.getItem() instanceof IVariableFermentable) {
            List<CachedFermenterRecipe> crecipes = new ArrayList<CachedFermenterRecipe>();
            for (ItemStack stack : Utils.getItemVariations(recipe.resource)) {
                crecipes.add(new CachedFermenterRecipe(recipe, stack, generatePermutations));
            }
            return crecipes;
        }
        return Collections.singletonList(new CachedFermenterRecipe(recipe, recipe.resource, generatePermutations));
    }

    @Override
    public void loadAllRecipes() {
        for (MachineFermenter.Recipe recipe : MachineFermenter.RecipeManager.recipes) {
            this.arecipes.addAll(this.getCachedRecipes(recipe, true));
        }
    }

    @Override
    public void loadCraftingRecipes(FluidStack result) {
        for (MachineFermenter.Recipe recipe : MachineFermenter.RecipeManager.recipes) {
            if (Utils.areFluidsSameType(recipe.output, result)) {
                this.arecipes.addAll(this.getCachedRecipes(recipe, true));
            }
        }
    }

    @Override
    public void loadUsageRecipes(ItemStack ingred) {
        super.loadUsageRecipes(ingred);
        for (MachineFermenter.Recipe recipe : MachineFermenter.RecipeManager.recipes) {
            if (recipe.resource != null) {
                for (ItemStack stack : Utils.getItemVariations(recipe.resource)) {
                    if (stack.hasTagCompound() && NEIServerUtils.areStacksSameType(stack, ingred) || !stack.hasTagCompound() && Utils.areStacksSameTypeCraftingSafe(stack, ingred)) {
                        CachedFermenterRecipe crecipe = new CachedFermenterRecipe(recipe, stack, true);
                        crecipe.setIngredientPermutationNBT(crecipe.inputItems, ingred);
                        this.arecipes.add(crecipe);
                    }
                }
            }
            for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) {
                if (Utils.areStacksSameTypeCraftingSafe(fuel.item, ingred)) {
                    for (CachedFermenterRecipe crecipe : this.getCachedRecipes(recipe, true)) {
                        crecipe.setIngredientPermutation(crecipe.inputItems, ingred);
                        this.arecipes.add(crecipe);
                    }
                }
            }
        }
    }

    @Override
    public void loadUsageRecipes(FluidStack ingred) {
        for (MachineFermenter.Recipe recipe : MachineFermenter.RecipeManager.recipes) {
            if (Utils.areFluidsSameType(recipe.liquid, ingred)) {
                this.arecipes.addAll(this.getCachedRecipes(recipe, true));
            }
        }
    }

}


text:
require 'test_helper'

class StopsControllerTest < ActionController::TestCase

  test "should be able to fetch stops" do
  	get(:fetch_stops, { 'lngMin' => 1.0, 'lngMax' => 5.0, 'latMin' => 1.0, 'latMax' => 5.0})
  	assert_response :success
  end

  test "fetches correct stop" do
  	get(:fetch_stops, { 'lngMin' => 1.0, 'lngMax' => 1.0, 'latMin' => 1.0, 'latMax' => 1.0})
  	assert_response :success
  	json_response = ActiveSupport::JSON.decode @response.body
  	assert_equal "stop1", json_response[0]['stop_name']
  	assert_equal "1", json_response[0]['stop_id']
  end

  test "fetches correct number of stops" do
    get(:fetch_stops, { 'lngMin' => 1.0, 'lngMax' => 10.0, 'latMin' => 1.0, 'latMax' => 10.0})
    assert_response :success
    json_response = ActiveSupport::JSON.decode @response.body
    assert_equal 10, json_response.count
  end

end


text:
FROM rgardler/acs-logging-test-base

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

EXPOSE 5000

COPY src src

CMD [ "python", "src/batch.py" ]


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>WebGL texture clear conformance test.</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="example" width="4" height="4" style="width: 40px; height: 30px;"></canvas>


text:
<!doctype html>

    <title>Aurelia</title>

    <link rel="stylesheet" href="jspm_packages/npm/foundation-sites@6.2.1/dist/foundation-flex.css">
    <link rel="stylesheet" href="jspm_packages/npm/font-awesome@4.6.1/css/font-awesome.css">
    <link rel="stylesheet" href="styles/main.css">

Loading...


text:
package com.github.games647.fastlogin.velocity.listener;

import com.github.games647.craftapi.UUIDAdapter;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.antibot.AntiBotService;
import com.github.games647.fastlogin.core.antibot.AntiBotService.Action;
import com.github.games647.fastlogin.core.shared.LoginSession;
import com.github.games647.fastlogin.velocity.FastLoginVelocity;
import com.github.games647.fastlogin.velocity.VelocityLoginSession;
import com.github.games647.fastlogin.velocity.task.AsyncPremiumCheck;
import com.github.games647.fastlogin.velocity.task.ForceLoginTask;
import com.velocitypowered.api.event.Continuation;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent.PreLoginComponentResult;
import com.velocitypowered.api.event.player.GameProfileRequestEvent;
import com.velocitypowered.api.event.player.ServerConnectedEvent;
import com.velocitypowered.api.proxy.InboundConnection;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.util.GameProfile;
import com.velocitypowered.api.util.GameProfile.Property;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;

public class ConnectListener {

    private final FastLoginVelocity plugin;
    private final AntiBotService antiBotService;

    public ConnectListener(FastLoginVelocity plugin, AntiBotService antiBotService) {
        this.plugin = plugin;
        this.antiBotService = antiBotService;
    }

    @Subscribe
    public void onPreLogin(PreLoginEvent preLoginEvent, Continuation continuation) {
        if (!preLoginEvent.getResult().isAllowed()) {
            return;
        }

        InboundConnection connection = preLoginEvent.getConnection();
        String username = preLoginEvent.getUsername();
        InetSocketAddress address = connection.getRemoteAddress();
        plugin.getLog().info("Incoming login request for {} from {}", username, address);

        Action action = antiBotService.onIncomingConnection(address, username);
        switch (action) {
            case Ignore:
                // just ignore
                return;
            case Block:
                String message = plugin.getCore().getMessage("kick-antibot");
                TextComponent messageParsed = LegacyComponentSerializer.legacyAmpersand().deserialize(message);

                PreLoginComponentResult reason = PreLoginComponentResult.denied(messageParsed);
                preLoginEvent.setResult(reason);
                break;
            case Continue:
            default:
                Runnable asyncPremiumCheck = new AsyncPremiumCheck(
                    plugin, connection, username, continuation, preLoginEvent
                );
                plugin.getScheduler().runAsync(asyncPremiumCheck);
                break;
        }
    }

    @Subscribe
    public void onGameprofileRequest(GameProfileRequestEvent event) {
        if (event.isOnlineMode()) {
            LoginSession session = plugin.getSession().get(event.getConnection().getRemoteAddress());

            UUID verifiedUUID = event.getGameProfile().getId();
            String verifiedUsername = event.getUsername();
            session.setUuid(verifiedUUID);
            session.setVerifiedUsername(verifiedUsername);

            StoredProfile playerProfile = session.getProfile();
            playerProfile.setId(verifiedUUID);
            if (!plugin.getCore().getConfig().get("premiumUuid", true)) {
                UUID offlineUUID = UUIDAdapter.generateOfflineId(playerProfile.getName());
                event.setGameProfile(event.getGameProfile().withId(offlineUUID));
                plugin.getLog().info("Overridden UUID from {} to {} (based of {}) on {}",
                        verifiedUUID, offlineUUID, verifiedUsername, event.getConnection());
            }

            if (!plugin.getCore().getConfig().get("forwardSkin", true)) {
                List<Property> newProp = removeSkin(event.getGameProfile().getProperties());
                event.setGameProfile(event.getGameProfile().withProperties(newProp));
            }
        }
    }

    private List<GameProfile.Property> removeSkin(Collection<Property> oldProperties) {
        List<GameProfile.Property> newProperties = new ArrayList<>(oldProperties.size());
        for (GameProfile.Property property : oldProperties) {
            if (!"textures".equals(property.getName())) {
                newProperties.add(property);
            }
        }

        return newProperties;
    }

    @Subscribe
    public void onServerConnected(ServerConnectedEvent serverConnectedEvent) {
        Player player = serverConnectedEvent.getPlayer();
        RegisteredServer server = serverConnectedEvent.getServer();

        VelocityLoginSession session = plugin.getSession().get(player.getRemoteAddress());
        if (session == null) {
            return;
        }

        // delay sending force command, because Paper will process the login event asynchronously
        // In this case it means that the force command (plugin message) is already received and processed while
        // player is still in the login phase and reported to be offline.
        Runnable loginTask = new ForceLoginTask(plugin.getCore(), player, server, session);
        plugin.getProxy().getScheduler()
                .buildTask(plugin, () -> plugin.getScheduler().runAsync(loginTask))
                .delay(1L, TimeUnit.SECONDS) // Delay at least one second, otherwise the login command can be missed
                .schedule();
    }

    @Subscribe
    public void onDisconnect(DisconnectEvent disconnectEvent) {
        Player player = disconnectEvent.getPlayer();
        plugin.getCore().getPendingConfirms().remove(player.getUniqueId());
    }
}


text:
package org.kuali.kra.bo;

import org.apache.commons.lang.StringUtils;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.maintenance.KraMaintainableImpl;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.maintenance.Maintainable;
import org.kuali.rice.kns.web.ui.Field;
import org.kuali.rice.kns.web.ui.Row;
import org.kuali.rice.kns.web.ui.Section;
import org.kuali.rice.krad.service.SequenceAccessorService;

import java.util.List;
import java.util.Map;

public class SponsorSpecialMaintainableImpl extends KraMaintainableImpl {

    private static final long serialVersionUID = -781344301441320810L;

    public static final String SPONSOR_CODE_SEQUENCE_NAME = "SEQ_SPONSOR_CODE";
    public static final String AUTO_GEN_SPONSOR_CODE_PARM = "AUTO_GENERATE_SPONSOR_CODE";
    public static final String SECTION_ID = "Edit Sponsor";
    public static final String SPONSOR_CODE_NAME = "sponsorCode";

    private transient ParameterService parameterService;
    private transient SequenceAccessorService sequenceAccessorService;

    /**
     *
     * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#setGenerateDefaultValues(java.lang.String)
     */
    @Override
    public void setGenerateDefaultValues(String docTypeName) {
        super.setGenerateDefaultValues(docTypeName);
        Sponsor sponsor = (Sponsor) getBusinessObject();
        if (isAutoGenerateCode()) {
            sponsor.setSponsorCode(getSequenceAccessorService().getNextAvailableSequenceNumber(SPONSOR_CODE_SEQUENCE_NAME, Sponsor.class).toString());
        }
    }

    /**
     *
     * @see org.kuali.kra.maintenance.KraMaintainableImpl#getSections(org.kuali.rice.kns.document.MaintenanceDocument, org.kuali.rice.kns.maintenance.Maintainable)
     */
    @SuppressWarnings("unchecked")
    public List<Section> getSections(MaintenanceDocument document, Maintainable oldMaintainable) {
        List<Section> sections = super.getSections(document, oldMaintainable);
        if (isAutoGenerateCode()) {
            disableSponsorCode(sections);
        }
        return sections;
    }

    protected void disableSponsorCode(List<Section> sections) {
        for (Section section : sections) {
            if (StringUtils.equals(section.getSectionId(), SECTION_ID)) {
                for (Row row : section.getRows()) {
                    for (Field field : row.getFields()) {
                        if (StringUtils.equals(field.getPropertyName(), SPONSOR_CODE_NAME)) {
                            field.setReadOnly(true);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void processAfterCopy(MaintenanceDocument document, Map<String, String[]> parameters) {
        super.processAfterCopy(document, parameters);
        setGenerateDefaultValues(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
    }

    protected boolean isAutoGenerateCode() {
        return getParameterService().getParameterValueAsBoolean(Constants.KC_GENERIC_PARAMETER_NAMESPACE,
                Constants.KC_ALL_PARAMETER_DETAIL_TYPE_CODE, AUTO_GEN_SPONSOR_CODE_PARM);
    }

    protected ParameterService getParameterService() {
        if (parameterService == null) {
            parameterService = KraServiceLocator.getService(ParameterService.class);
        }
        return parameterService;
    }

    public void setParameterService(ParameterService parameterService) {
        this.parameterService = parameterService;
    }

    protected SequenceAccessorService getSequenceAccessorService() {
        if(sequenceAccessorService == null) {
            sequenceAccessorService = KraServiceLocator.getService(SequenceAccessorService.class);
        }
        return sequenceAccessorService;
    }

    public void setSequenceAccessorService(SequenceAccessorService sequenceAccessorService) {
        this.sequenceAccessorService = sequenceAccessorService;
    }

}


text:
package org.cloudfoundry.community.servicebroker.datalifecycle.aws;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.cloudfoundry.community.servicebroker.datalifecycle.utils.HostUtils;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;

import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.AssociateAddressRequest;
import com.amazonaws.services.ec2.model.CreateImageRequest;
import com.amazonaws.services.ec2.model.CreateImageResult;
import com.amazonaws.services.ec2.model.DeleteSnapshotRequest;
import com.amazonaws.services.ec2.model.DeleteVolumeRequest;
import com.amazonaws.services.ec2.model.DeregisterImageRequest;
import com.amazonaws.services.ec2.model.DescribeAddressesResult;
import com.amazonaws.services.ec2.model.DescribeImagesRequest;
import com.amazonaws.services.ec2.model.DescribeImagesResult;
import com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest;
import com.amazonaws.services.ec2.model.DescribeInstanceStatusResult;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeSnapshotsResult;
import com.amazonaws.services.ec2.model.DescribeVolumesRequest;
import com.amazonaws.services.ec2.model.DescribeVolumesResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Snapshot;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.ec2.model.Volume;

public class AWSHelper {
	private Logger log = Logger.getLogger(AWSHelper.class);

	private AmazonEC2Client ec2Client;

	private String subnetId;

	private String sourceInstanceId;

	private HostUtils hostUtils;

	private int bootCheckPort;

	public AWSHelper(AmazonEC2Client ec2Client, String subnetId,
			String sourceInstanceId, HostUtils hostUtils, int bootCheckPort) {
		this.ec2Client = ec2Client;
		this.subnetId = subnetId;
		this.sourceInstanceId = sourceInstanceId;
		this.hostUtils = hostUtils;
		this.bootCheckPort = bootCheckPort;
	}

	public String getEC2InstancePublicIp(String instance) {
		DescribeInstancesResult result = ec2Client
				.describeInstances(new DescribeInstancesRequest()
						.withInstanceIds(instance));
		return result.getReservations().get(0).getInstances().get(0)
				.getPublicIpAddress();
	}

	public void deregisterAMI(String ami) {
		log.info("Deregistering AMI " + ami);
		ec2Client
				.deregisterImage(new DeregisterImageRequest().withImageId(ami));
	}

	public void terminateEc2Instance(String ec2Instance) {
		log.info("Terminating instance " + ec2Instance);
		ec2Client.terminateInstances(new TerminateInstancesRequest()
				.withInstanceIds(Collections.singletonList(ec2Instance)));
	}

	/**
	 * Given an AMI start an EC2 Instance.
	 *
	 * @param amiId
	 *            to start
	 * @return the id of the running instance.
	 * @throws ServiceBrokerException
	 */
	public String startEC2Instance(String amiId) throws ServiceBrokerException {
		RunInstancesResult instance = ec2Client
				.runInstances(new RunInstancesRequest().withImageId(amiId)
						.withInstanceType("m1.small").withMinCount(1)
						.withMaxCount(1).withSubnetId(subnetId)
						.withInstanceType(InstanceType.T2Micro));

		String instanceId = getInstanceId(instance);
		addElasticIp(instanceId);
		log.info("Instance " + instanceId + " started successfully");
		return instanceId;
	}

	/**
	 * Associate the next available elastic IP with an instance.
	 *
	 * @param instanceId
	 * @throws ServiceBrokerException
	 */
	public void addElasticIp(String instanceId) throws ServiceBrokerException {
		AssociateAddressRequest addressRequest = new AssociateAddressRequest()
				.withInstanceId(instanceId).withPublicIp(
						getAvaliableElasticIp());
		log.info("Associating " + addressRequest.getPublicIp()
				+ " with instance " + instanceId);
		if (waitForInstance(instanceId)) {
			ec2Client.associateAddress(addressRequest);
		} else {
			throw new ServiceBrokerException(
					"Instance did not transition to 'running' in alotted time.");
		}
		// We need the machine to boot before this will work.
		if (!hostUtils.waitForBoot(addressRequest.getPublicIp(), bootCheckPort)) {
			throw new ServiceBrokerException(
					"Host failed to boot in time alotted");
		}
	}

	/**
	 * Pull back a list of the elastic ip's that aren't attached to anything and
	 * return the first one.
	 *
	 * @return the first available IP.
	 * @throws ServiceBrokerException
	 */
	public String getAvaliableElasticIp() throws ServiceBrokerException {
		DescribeAddressesResult result = ec2Client.describeAddresses();
		log.info("Found " + result.getAddresses().size() + " addresses!");
		return result
				.getAddresses()
				.stream()
				.filter(a -> null == a.getInstanceId())
				.findAny()
				.orElseThrow(
						() -> new ServiceBrokerException(
								"No elastic IP's avaliable!")).getPublicIp();

	}

	/**
	 * Build an AMI of a running EC2Instance. Creates a snap which is
	 * disassociated and tracked via a the description.
	 *
	 * @param sourceInstance
	 *            the EC2 instance to create an AMI from
	 * @param description
	 *            to shove in the console so you know what your looking at
	 * @return id of the ami
	 * @throws TimeoutException
	 *             if the ami isn't available in time.
	 *
	 * @see #deleteStorageArtifacts(String)
	 */
	public String createAMI(String sourceInstance, String description)
			throws TimeoutException {
		CreateImageResult imageResult = ec2Client
				.createImage(new CreateImageRequest()
						.withInstanceId(sourceInstance)
						.withDescription(description)
						.withName(
								sourceInstance + "-"
										+ System.currentTimeMillis())
						.withNoReboot(true));

		String amiId = imageResult.getImageId();
		if (!waitForImage(amiId)) {
			throw new TimeoutException(
					"Timed out waiting for amazon to create AMI " + amiId);
		}
		log.info("Created new AMI with ID: " + amiId);
		return amiId;
	}

	/**
	 * Find the snap & volumes associated with the AMI we used and delete it.
	 * AWS doesn't help us out much and the only relationship (as of 2/14/2015)
	 * we can leverage is the description field.
	 *
	 * @param ami
	 *            to find associated snaps for
	 * @throws ServiceBrokerExceptions
	 */
	public void deleteStorageArtifacts(String ami)
			throws ServiceBrokerException {

		DescribeSnapshotsResult desc = ec2Client.describeSnapshots();
		if (null == desc.getSnapshots()) {
			return;
		}
		List<Snapshot> snapshots = desc.getSnapshots();

		// The only way I can find to track the snaps that get created (but not
		// cleaned up) as part of the ami creation is by the description. This
		// code is brittle and will probably fail in unexpected and glamorous
		// ways.
		String amiDesc = "Created by CreateImage(" + sourceInstanceId
				+ ") for " + ami + " from vol";

		// Would be nice if the aws client return optionals...
		List<Snapshot> matching = snapshots.stream()
				.filter(s -> safeContains(s::getDescription, amiDesc))
				.collect(Collectors.toList());

		switch (matching.size()) {
		case 0:
			// Should this throw? Might have been manually cleaned up...but it
			// may orphan the volume. It's done this way to allow people to
			// create their own instances in AWS and not jack them up by
			// deleting the volume
			log.error("No snapshots found for AMI " + ami);
			break;
		case 1:
			String snap = matching.get(0).getSnapshotId();
			log.info("Deleting snapshot " + snap);
			ec2Client.deleteSnapshot(new DeleteSnapshotRequest()
					.withSnapshotId(snap));

			deleteVolumeForSnap(snap);
			break;
		default:
			throw new ServiceBrokerException(
					"Found too many snapshots for AMI " + ami);
		}
	}

	private void deleteVolumeForSnap(String snap) {

		waitForVolume(snap);
		String volId = getVolume(snap).getVolumeId();
		log.info("Deleting volume " + volId);
		ec2Client.deleteVolume(new DeleteVolumeRequest().withVolumeId(volId));
	}

	private void waitForVolume(String snap) {
		int retries = 0;
		Volume vol = getVolume(snap);
		while ("in-use".equals(vol.getState()) && retries < 5) {
			log.error("Volume is still in use, sleeping 30");
			sleep();
			retries++;
			vol = getVolume(snap);
		}
	}

	private Volume getVolume(String snap) {
		DescribeVolumesResult volumes = ec2Client
				.describeVolumes(new DescribeVolumesRequest()
						.withFilters(new Filter().withName("snapshot-id")
								.withValues(snap)));

		return volumes.getVolumes().stream().findFirst().get();
	}

	private boolean safeContains(Callable<String> s, String c) {
		try {
			return (null != s.call()) && s.call().contains(c);
		} catch (Exception e) {
			log.error(e);
		}
		return false;
	}

	private boolean waitForInstance(String instanceId) {
		log.info("Waiting for instance to transition to running");
		for (int i = 0; i < 5; ++i) {

			DescribeInstanceStatusResult result = ec2Client
					.describeInstanceStatus(new DescribeInstanceStatusRequest()
							.withInstanceIds(instanceId));
			if (!result.getInstanceStatuses().isEmpty()) {
				String state = result.getInstanceStatuses().get(0)
						.getInstanceState().getName();

				log.info("Instance state is " + state);

				if (state.equals("running")) {
					return true;
				}
			}

			sleep();

		}
		return false;
	}

	private boolean waitForImage(String imageId) {
		for (int i = 0; i < 5; i++) {
			String imageState = getImageState(imageId);
			log.info("Image state is " + imageState);
			switch (imageState) {
			case "available":
				return true;
			case "failed":
				return false;
			default:
				log.info("Waiting 30s for AMI " + imageId);
				sleep();
			}
		}
		return false;
	}

	private void sleep() {
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			log.error(e);
		}
	}

	private String getInstanceId(RunInstancesResult instance) {
		return instance.getReservation().getInstances().get(0).getInstanceId();
	}

	private String getImageState(String imageId) {
		String state = "failed";
		DescribeImagesResult result = ec2Client
				.describeImages(new DescribeImagesRequest()
						.withImageIds(imageId));
		if (null != result && null != result.getImages()
				&& !result.getImages().isEmpty()) {
			state = result.getImages().get(0).getState();
		}
		return state;
	}
}


text:
package de.unistuttgart.ipvs.pmp.gui.setting;

import android.content.Context;
import android.widget.LinearLayout;

/**
 *
 * @author Marcus Vetter
 *
 */
public class SettingListItem extends LinearLayout {

    /**
     * Constructor
     *
     * @param context
     *            the context
     * @param setting
     *            the current {@link SettingAbstract}
     */
    public SettingListItem(Context context, SettingAbstract<?> setting) {
        super(context);
        addView(setting.getView(context));
    }

}


text:
<?php

namespace Kanboard\Model;

use Kanboard\Event\TaskEvent;

/**
 * Task Position
 *
 * @package  model
 * @author   Frederic Guillot
 */
class TaskPosition extends Base
{
    /**
     * Move a task to another column or to another position
     *
     * @access public
     * @param  integer    $project_id        Project id
     * @param  integer    $task_id           Task id
     * @param  integer    $column_id         Column id
     * @param  integer    $position          Position (must be >= 1)
     * @param  integer    $swimlane_id       Swimlane id
     * @param  boolean    $fire_events       Fire events
     * @return boolean
     */
    public function movePosition($project_id, $task_id, $column_id, $position, $swimlane_id = 0, $fire_events = true)
    {
        $result = false;

        if ($position < 1) {
            return $result;
        }

        $task = $this->taskFinder->getById($task_id);

        if ($task['is_active'] == Task::STATUS_CLOSED) {
            return true;
        }

        $this->db->startTransaction();

        if ($task['swimlane_id'] != $swimlane_id || $task['column_id'] != $column_id) {
            $result = $this->moveTaskToAnotherColumn($task, $swimlane_id, $column_id, $position);
        } elseif ($task['position'] != $position) {
            $result = $this->moveTaskWithinSameColumn($task, $position);
        }

        if (! $result) {
            $this->db->cancelTransaction();
            return false;
        }

        $this->db->closeTransaction();

        if ($fire_events) {
            $this->fireEvents($task, $column_id, $position, $swimlane_id);
        }

        return $result;
    }

    /**
     * Move a task to another column/swimlane
     *
     * @access private
     * @param  array   $task
     * @param  integer $swimlane_id
     * @param  integer $column_id
     * @param  integer $position
     * @return boolean
     */
    private function moveTaskToAnotherColumn(array $task, $swimlane_id, $column_id, $position)
    {
        $results = array();
        $max = $this->getQuery($task['project_id'], $swimlane_id, $column_id)->count();
        $position = $max > 0 && $position > $max ? $max + 1 : $position;

        $results[] = $this->getQuery($task['project_id'], $task['swimlane_id'], $task['column_id'])->gt('position', $task['position'])->decrement('position', 1);
        $results[] = $this->getQuery($task['project_id'], $swimlane_id, $column_id)->gte('position', $position)->increment('position', 1);
        $results[] = $this->updateTaskPosition($task['id'], $swimlane_id, $column_id, $position);

        return !in_array(false, $results, true);
    }

    /**
     * Move a task within the same column
     *
     * @access private
     * @param  array   $task
     * @param  integer $position
     * @return boolean
     */
    private function moveTaskWithinSameColumn(array $task, $position)
    {
        $results = array();
        $max = $this->getQuery($task['project_id'], $task['swimlane_id'], $task['column_id'])->count();
        $position = $max > 0 && $position > $max ? $max : $position;

        if ($position >= $max) {
            $results[] = $this->getQuery($task['project_id'], $task['swimlane_id'], $task['column_id'])->lte('position', $position)->decrement('position', 1);
        } else {
            $results[] = $this->getQuery($task['project_id'], $task['swimlane_id'], $task['column_id'])->gte('position', $position)->increment('position', 1);
        }

        $results[] = $this->updateTaskPosition($task['id'], $task['swimlane_id'], $task['column_id'], $position);

        return !in_array(false, $results, true);
    }

    /**
     * Update final task position
     *
     * @access private
     * @param  integer $task_id
     * @param  integer $swimlane_id
     * @param  integer $column_id
     * @param  integer $position
     * @return boolean
     */
    private function updateTaskPosition($task_id, $swimlane_id, $column_id, $position)
    {
        return $this->db->table(Task::TABLE)
            ->eq('id', $task_id)
            ->eq('is_active', 1)
            ->update(array('position' => $position, 'column_id' => $column_id, 'swimlane_id' => $swimlane_id, 'date_modification' => time()));
    }

    /**
     * Get common query
     *
     * @access private
     * @param  integer $project_id
     * @param  integer $swimlane_id
     * @param  integer $column_id
     * @return \PicoDb\Table
     */
    private function getQuery($project_id, $swimlane_id, $column_id)
    {
        return $this->db->table(Task::TABLE)
            ->eq('project_id', $project_id)
            ->eq('swimlane_id', $swimlane_id)
            ->eq('column_id', $column_id)
            ->eq('is_active', 1);
    }

    /**
     * Fire events
     *
     * @access private
     * @param  array     $task
     * @param  integer   $new_column_id
     * @param  integer   $new_position
     * @param  integer   $new_swimlane_id
     */
    private function fireEvents(array $task, $new_column_id, $new_position, $new_swimlane_id)
    {
        $event_data = array(
            'task_id' => $task['id'],
            'project_id' => $task['project_id'],
            'position' => $new_position,
            'column_id' => $new_column_id,
            'swimlane_id' => $new_swimlane_id,
            'src_column_id' => $task['column_id'],
            'dst_column_id' => $new_column_id,
            'date_moved' => $task['date_moved'],
            'recurrence_status' => $task['recurrence_status'],
            'recurrence_trigger' => $task['recurrence_trigger'],
        );

        if ($task['swimlane_id'] != $new_swimlane_id) {
            $this->container['dispatcher']->dispatch(Task::EVENT_MOVE_SWIMLANE, new TaskEvent($event_data));
        } elseif ($task['column_id'] != $new_column_id) {
            $this->container['dispatcher']->dispatch(Task::EVENT_MOVE_COLUMN, new TaskEvent($event_data));
        } elseif ($task['position'] != $new_position) {
            $this->container['dispatcher']->dispatch(Task::EVENT_MOVE_POSITION, new TaskEvent($event_data));
        }
    }
}