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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Interface org.apache.hadoop.fs.PathFilter (Apache Hadoop Common 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.hadoop.fs.PathFilter

Packages that use PathFilter

org.apache.hadoop.fs
An abstract file system API.

Uses of PathFilter in org.apache.hadoop.fs

Classes in org.apache.hadoop.fs that implement PathFilter

 class
GlobFilter

          A filter for POSIX glob pattern with brace expansions.

Methods in org.apache.hadoop.fs with parameters of type PathFilter

 FileStatus[]
FileSystem.globStatus(Path pathPattern,
                     PathFilter filter)

          Return an array of FileStatus objects whose path names match pathPattern
 and is accepted by the user-supplied path filter.

 FileStatus[]
FileContext.Util.globStatus(Path pathPattern,
                     PathFilter filter)

          Return an array of FileStatus objects whose path names match pathPattern
 and is accepted by the user-supplied path filter.

protected  RemoteIterator<LocatedFileStatus>
FileSystem.listLocatedStatus(Path f,
                                   PathFilter filter)

          Listing a directory
 The returned results include its block location if it is a file
 The results are filtered by the given path filter

 FileStatus[]
FileSystem.listStatus(Path[] files,
                     PathFilter filter)

          Filter files/directories in the given list of paths using user-supplied
 path filter.

 FileStatus[]
FileContext.Util.listStatus(Path[] files,
                     PathFilter filter)

          Filter files/directories in the given list of paths using user-supplied
 path filter.

 FileStatus[]
FileSystem.listStatus(Path f,
                     PathFilter filter)

          Filter files/directories in the given path using the user-supplied path
 filter.

 FileStatus[]
FileContext.Util.listStatus(Path f,
                     PathFilter filter)

          Filter files/directories in the given path using the user-supplied path
 filter.

Constructors in org.apache.hadoop.fs with parameters of type PathFilter

GlobFilter(String filePattern,
                     PathFilter filter)

          Creates a glob filter with the specified file pattern and an user filter.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <TextView
        android:id="@+id/editTextFormField_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@style/Label"
        />

    <EditText
        android:id="@+id/editTextFormField_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
function [rgb,model,mosaicType] = nefRead(fname,sampleRate,returnMosaic,model)
%Decode image data from Nikon .NEF file, return rgb or full mosaic
%
%  [rgb,model,mosaicType] = nefRead(fname,sampleRate,returnMosaic)
%
% NOTE:  The returned data are uint16 as acquired by the camera.
%
% fname -- NEF file name.  If not supplied, you will be queried.
% sampleRate  - How to downsample the image.
%    if sampleRate = 2, then you leave out the missing samples from the Bayer
%    sampling mosaic.  If you downsample by 1, then the R,G,B fields have a
%    0 at the locations of the missing elements. Downsampling by higher
%    values (e.g. 4) skips every other value.
%
% returnMosaic:
%   0 (default) - the returned data are in RGB format with four color
%   dimensions: r,g1,b,g2.
%   1 - the data are returned in a  single plane, not an RGB image.  In
%   this case, no subsampling of the image data is allowed.
%   2 - the data are turned in a 3D RGB image in which the G field is
%   assigned the average of the two G fields.
%
%  model:  D70 (default) or D100 are currently supported
%
% The fname is normally a full path name.
%
% Examples:
%  pDir = 'C:\u\brian\Matlab\PDC\Applications\MultiCapture\Data\Images';
%  fName = 'macbeth_tg_nofil_3.NEF';
%  fullName = fullfile(pDir,fName);
%  [rgbg,model] = nefRead(fullName,1);
%
%  The full mosaic, not in RGB format, is returned like this
%
%  mosaic = nefRead(fullName,1,1);
%
%
% Author: FX, BW

if ieNotDefined('fname'),
    fname = vcSelectDataFile('stayput','r','nef','select NEF file');
    if isempty(fname), disp('Canceled'); end
end
if ieNotDefined('sampleRate'),   sampleRate = 2;   end
if ieNotDefined('returnMosaic'), returnMosaic = 0; end
if ieNotDefined('model'),        model = 'D70';    end

% We have started identifying the camera model based on a parameter.
% In the past, we used the size of the NEF file - TO MANUALLY COMPARE AND
% ADD FOR NEW MODELS such as the D200
% if(filesize > 4*(2^20) && filesize < 5*(2^20))
% between 4-5mb is the size of a D70 NEF file
switch(lower(model))
    case 'd70'
        [mosaic,model] = rawCamFileReadD70(fname);
    case 'd100'
        [mosaic,model] = rawCamFileReadD100(fname);
    case 'd2Xs'
        [mosaic,model] = rawCamFileReadD2Xs(fname);
    case 'd1'
%        [mosaic,model] = rawCamFileReadD1(fname);
end

% Different cameras have different dll files & mosaic formats (to
% add for D200)
switch lower(model)
    case 'd100'
        mosaicType = 'grbg';
    case 'd1'
        mosaicType = 'bggr';
    case 'd70'
        mosaicType = 'bggr';
%    case 'd2Xs'
%        mosaicType = ''%% find out
    otherwise
        error('Unknown camera type');

end

mosaic = mosaic';

if returnMosaic == 0
    % Default:  sends back an RGBG image in four planes
    rgb = mosaic2DenseRGBG(mosaic,mosaicType,sampleRate);
elseif (returnMosaic == 1)
    % Return in a single plane RGBG
    if (sampleRate == 1),
        warning('No subsampling in mosaic mode.');  %#ok<WNTAG>
    end
    rgb = mosaic;
elseif returnMosaic == 2
    % Returns a three plane RGB image with G1 and G2 averaged
    rgb = mosaic2DenseRGBG(mosaic,mosaicType,sampleRate);
    rgb(:,:,2) = rgb(:,:,2)/2 + rgb(:,:,4)/2;
    rgb(:,:,4) = [];   % Clears the fourth plane
end

return;

%-----------------------------
function rgb = mosaic2DenseRGBG(mosaic,mosaicType,sampleRate)
%Take the raw data into a reduced RGB style image.
%The reduction is based on the sampleRate and mosaicType
%
% rgb = mosaic2DenseRGBG(mosaic,mosaicType,sampleRate)
%
%Author:  BW, FX

% An alternative:  h = fspecial('gaussian',sampleRate,sampleRate/3)
switch lower(mosaicType)
    case 'grbg'
        % D100 case
        cPlane = [2 1 3 4];
    case 'bggr'
        % D70 case
        cPlane = [3 2 4 1];
    otherwise,
        disp('Unknown mosaic type');
end

if sampleRate > 1   % Average and copy into the RGBG order
    h = fspecial('average',sampleRate);
    cnt = 0;
    fprintf('Filtering and subsampling color planes.\n');
    for ii=1:2
        for jj=1:2
            tmp = imfilter(mosaic(ii:2:end,jj:2:end),h);
            cnt = cnt+1;
            rgb(:,:,cPlane(cnt)) = tmp(1:sampleRate:end,1:sampleRate:end);
        end
    end
else  % No filtering needed, just copy into the RGBG order
    cnt = 0;
    fprintf('Copying color planes.\n');
    for ii=1:2
        for jj=1:2
            cnt = cnt+1;
            rgb(:,:,cPlane(cnt)) = mosaic(ii:2:end,jj:2:end);
        end
    end
end

return;


text:
@implementation AssignPointModel

@end


text:
import { connect } from 'zefir/utils'
import Input from '../../components/ui/input'
import Button from '../../components/ui/button'
import InputList from '../../components/ui/input-list'

const SlackInviteForm = ({ email, sendInvitation, messages }) => (

    <form className='Form' onSubmit={sendInvitation}>
      <InputList errors={messages.get('slack.invite.errors')}>

          <Input {...email} full />
          <Button
            type='submit'
            disabled={messages.has('slack.invite.pending')}
            secondary
          >
            Send me an invite
          </Button>

      </InputList>
      {messages.has('slack.invite.success') ? (

{messages.get('slack.invite.success')}

      ) : ''}
    </form>

)

SlackInviteForm.form = {
  formName: 'SlackInviteFormForm',
  fields: {
    email: {
      required: 'true',
      type: 'email',
      placeholder: 'E-mail address'
    }
  }
}

SlackInviteForm.init = ({
  stores: { messages },
  services: { slackInvite: { sendInvitation } },
  form: { fields: { email }, submit }
}) => ({
  messages,
  email,
  sendInvitation: (e) => submit(e, sendInvitation)
})

export default connect(SlackInviteForm)


text:
/**
 * @class Oskari.mapframework.bundle.parcel.view.ParcelPrintForm2
 *
 * Shows a form for my place. For requests for name and description.
 */
Oskari.clazz.define("Oskari.mapframework.bundle.parcel.view.ParcelPrintForm2",

/**
 * @method create called automatically on construction
 * @static
 */
function(instance) {
    this.instance = instance;
    this.initialValues = undefined;
    this._formUi = undefined;
    this.isEnabled = false;
    this.pointCnt = 0;

    this.loc = instance.getLocalization('parcelprintform2');

    this.template = jQuery('
' +
        '
' +
        '
' + '
' + '

' + '
' + '
'+
        '
' +
        '

' +
        '

' +
        '

' +
        '

');
    this.pl_template = jQuery(
        '
' +
            '' +
            '<textarea name="pointx" class="with_placeholder" placeholder="' + this.loc.point.placeholder + '">' +
            '</textarea>' +
            '
');
    this.pl_template2 = jQuery(
        '
' +
            '' +
            '<textarea name="pointx">' +
            '</textarea>' +
            '
');

}, {

        /**
         * @method render
         * Renders view to given DOM element
         * @param {jQuery} container reference to DOM element this component will be
         * rendered to
         */
        render: function (container, mainview) {
            var me = this;
            var content = me._getForm();

            this.mainPanel = content;
            content.find('div.header h3').append(me.loc.title);

            container.append(content);

            // buttons
            container.find('div.header div.icon-close').bind('click', function () {
                me.instance.setParcelPrintBreak();
            });
            //Break
            var cancelButton = Oskari.clazz.create('Oskari.userinterface.component.Button');

            cancelButton.setTitle(me.loc.buttons['break']);
            cancelButton.setHandler(function () {
                me.instance.setParcelPrintBreak();
            });

            cancelButton.insertTo(content.find('div.buttons'));
            //Previous
            var previousButton = Oskari.clazz.create('Oskari.userinterface.component.Button');

            previousButton.setTitle(me.loc.buttons['previous']);
            previousButton.setHandler(function () {
                me.instance.setParcelPrintPrevious();
            });

            previousButton.insertTo(content.find('div.buttons'));

            //Continue
            var continueButton = Oskari.clazz.create('Oskari.userinterface.component.Button');
            continueButton.addClass('primary');
            continueButton.setTitle(me.loc.buttons['continue']);
            continueButton.setHandler(function () {
                me.instance.requestParcelPrintFinal();
            });
            continueButton.insertTo(content.find('div.buttons'));

            var inputs = me._formUi.find('input[type=text]');
            inputs.focus(function () {
                me.instance.sandbox.postRequestByName('DisableMapKeyboardMovementRequest');
            });
            inputs.blur(function () {
                me.instance.sandbox.postRequestByName('EnableMapKeyboardMovementRequest');
            });

            //IE 10 fix
            jQuery('textarea.with_placeholder').focus(function() {
                if (me.loc.point.placeholder === this.value) {
                    this.value = '';
                }
            }).blur(function(){
                if (this.value === '') {
                    this.attr("placeholder",me.loc.point.placeholder);
                }
            });
        },
        /**
         *
         * @param mainview
         */
        refreshData: function (mainview) {
            var new_points_cnt = this.instance.getDrawPlugin().getNewPointsCount();
            if(this.pointCnt !== new_points_cnt)
            {
                this._formUi.find('div.pointlist').empty();
                for (i = 1; i < new_points_cnt + 1 ; i++) {
                    if (i === 1) plui = this.pl_template.clone();
                    else plui = this.pl_template2.clone();
                    plui.find('label').append(this.loc.point.label+" "+i);
                    plui.find('textarea').attr("name","pnro_"+i);

                    this._formUi.find('div.pointlist').append(plui);
                }
                this.pointCnt = new_points_cnt;
            }

        },
            /**
     * @method getForm
     * @return {jQuery} jquery reference for the form
     */
        _getForm: function () {
                var ui = this.template.clone(),
                    plui = undefined,
                    i;

                var new_points_cnt = this.instance.getDrawPlugin().getNewPointsCount();
                for (i = 1; i < new_points_cnt + 1 ; i++) {
                    if (i === 1) plui = this.pl_template.clone();
                    else plui = this.pl_template2.clone();
                    plui.find('label').append(this.loc.point.label+" "+i);
                    plui.find('textarea').attr("name","Pnro "+i);

                    ui.find('div.pointlist').append(plui);
                }
                this.pointCnt = new_points_cnt;
                this._formUi = ui;
                return ui;
            },
    /**
     * @method getValues
     * Returns form values as an object
     * @return {Object}
     */
    getValues : function() {
        var values = [],
            table = {},
            titlerow = {};

        // infobox will make us lose our reference so search
        // from document using the form-class
        var onScreenForm = this._getOnScreenForm();

        if (onScreenForm.length > 0) {

            titlerow.col1 = this.loc.pointnumber;
            titlerow.col2 = this.loc.pointdesc;
            values.push(titlerow);

            // Loop boundary point descriptions
            jQuery('textarea').each(function(index) {
                var pnodata = {};
                pnodata.col1 = jQuery(this).attr('name');
                pnodata.col2 = jQuery(this).val();
                if (pnodata.col2 !== "") values.push(pnodata);
            });

            table.table1 = values;

        }
        return table;
    },

    /**
     * @method _getOnScreenForm
     * Returns reference to the on screen version shown by OpenLayers
     * @private
     */
    _getOnScreenForm : function() {
        // unbind live so
        return jQuery('div.parcelprintform1');
    },
        /**
         * @method destroy
         * Destroyes/removes this view from the screen.
         */
        destroy: function () {
            // unbind live bindings
            var onScreenForm = this._getOnScreenForm();
            this._formUi.remove();
        },
        hide: function () {
            this._formUi.hide();
        },
        show: function () {
            this._formUi.show();
        },
        setEnabled: function (e) {
            this.isEnabled = e;
        },
        getEnabled: function () {
            return this.isEnabled;
        }
});


text:
"""settings.py

Udacity conference server-side Python App Engine app user settings

$Id$

created/forked from conference.py by wesc on 2014 may 24

"""

# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '875880052520-vste5sntpb0jp7r3s273h79l0m6gobnj.apps.googleusercontent.com'


text:
package org.tearne.crosser.output.composition

import org.tearne.crosser.plant.Chromosome
import org.tearne.crosser.distribution.ChromosomeDistribution
import org.tearne.crosser.distribution.ChromosomeEmpirical

case class ChromosomeComposition(val left: TidComposition, val right: TidComposition)

trait ChromosomeCompositionBuilderComponent {
	this: TidCompositionBuilderComponent =>

	val chromosomeCompositionBuilder: ChromosomeCompositionBuilder

	class ChromosomeCompositionBuilder {
		def apply(cDist: ChromosomeEmpirical): ChromosomeComposition = {
			ChromosomeComposition(
				tidCompositionBuilder(cDist.samples.map(_.left)),
				tidCompositionBuilder(cDist.samples.map(_.right))
			)
		}
	}
}


text:
  __attribute__((visibility("default")))
#else
#define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT
#endif
#endif

#else  // defined(COMPONENT_BUILD)
#define VIEWS_EXAMPLES_WITH_CONTENT_EXPORT
#endif

#endif  // UI_VIEWS_EXAMPLES_VIEWS_EXAMPLES_WITH_CONTENT_EXPORT_H_


text:
"""Provides functions that are used when apps are finished.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import errno
import io
import json
import logging
import os
import shutil
import socket

from treadmill import appevents
from treadmill import appcfg
from treadmill import apphook
from treadmill import firewall
from treadmill import iptables
from treadmill import logcontext as lc
from treadmill import plugin_manager
from treadmill import runtime
from treadmill import rrdutils
from treadmill import services

from treadmill.appcfg import abort as app_abort
from treadmill.apptrace import events

_LOGGER = logging.getLogger(__name__)

def finish(tm_env, container_dir):
    """Frees allocated resources and mark then as available.
    """
    with lc.LogContext(_LOGGER, os.path.basename(container_dir),
                       lc.ContainerAdapter):
        _LOGGER.info('finishing %r', container_dir)

        data_dir = os.path.join(container_dir, 'data')

        app = runtime.load_app(data_dir)
        if app is not None:
            _cleanup(tm_env, data_dir, app)
        else:
            app = runtime.load_app(data_dir, appcfg.APP_JSON)

        if app is not None:
            # Check if application reached restart limit inside the container.
            #
            # The container directory will be moved, this check is done first.
            #
            # If restart limit was reached, application node will be removed
            # from Zookeeper at the end of the cleanup process, indicating to
            # the scheduler that the server is ready to accept new load.
            exitinfo, aborted, oom, terminated = _collect_exit_info(data_dir)

            # All resources are cleaned up. If the app terminated inside the
            # container, remove the node from Zookeeper, which will notify the
            # scheduler that it is safe to reuse the host for other load.
            if aborted is not None:
                app_abort.report_aborted(tm_env, app.name,
                                         why=aborted.get('why'),
                                         payload=aborted.get('payload'))

            elif oom:
                _post_oom_event(tm_env, app)

            elif terminated:
                # Terminated (or evicted).
                # Don't post event, this is handled by the master.
                _LOGGER.info('Terminated: %s', app.name)

            else:
                # Container finished because service exited.
                # It is important that this is checked last.
                if exitinfo is not None:
                    _post_exit_event(tm_env, app, exitinfo)

        # cleanup monitor with container information
        if app:
            apphook.cleanup(tm_env, app, container_dir)

def _collect_exit_info(container_dir):
    """Read exitinfo, aborted, oom and terminated files to check how container
    finished.

    :returns ``(exitinfo, aborted, oom, terminated)``:
        Returns a tuple of exitinfo, a ``(service_name,return_code,signal)`` if
        present or None otherwise, aborted reason if persent or None otherwise,
        oom (True if container was killed due to oom event or False otherwise),
        terminated (True if container was terminated/evicted, False otherwise).
    """
    exitinfo = aborted = None

    exitinfo_file = os.path.join(container_dir, 'exitinfo')
    try:
        with io.open(exitinfo_file) as f:
            exitinfo = json.load(f)
    except IOError:
        _LOGGER.debug('exitinfo file does not exist: %s', exitinfo_file)

    aborted_file = os.path.join(container_dir, 'aborted')
    try:
        with io.open(aborted_file) as f:
            try:
                aborted = json.load(f)
            except ValueError:
                _LOGGER.warning('Invalid json in aborted file: %s',
                                aborted_file)
                aborted = app_abort.ABORTED_UNKNOWN
    except IOError:
        _LOGGER.debug('aborted file does not exist: %s', aborted_file)

    oom_file = os.path.join(container_dir, 'oom')
    oom = os.path.exists(oom_file)
    if not oom:
        _LOGGER.debug('oom file does not exist: %s', oom_file)

    terminated_file = os.path.join(container_dir, 'terminated')
    terminated = os.path.exists(terminated_file)
    if not terminated:
        _LOGGER.debug('terminated file does not exist: %s', terminated_file)

    return exitinfo, aborted, oom, terminated

def _post_oom_event(tm_env, app):
    """Post oom as killed container."""
    appevents.post(
        tm_env.app_events_dir,
        events.KilledTraceEvent(
            instanceid=app.name,
            is_oom=True,
        )
    )

def _post_exit_event(tm_env, app, exitinfo):
    """Post exit event based on exit reason."""
    appevents.post(
        tm_env.app_events_dir,
        events.FinishedTraceEvent(
            instanceid=app.name,
            rc=exitinfo.get('return_code', 256),
            signal=exitinfo.get('signal', 256),
            payload=exitinfo
        )
    )

def _cleanup(tm_env, container_dir, app):
    """Cleanup a container that actually ran.
    """
    # Generate a unique name for the app
    unique_name = appcfg.app_unique_name(app)
    # Create service clients
    cgroup_client = tm_env.svc_cgroup.make_client(
        os.path.join(container_dir, 'resources', 'cgroups')
    )
    localdisk_client = tm_env.svc_localdisk.make_client(
        os.path.join(container_dir, 'resources', 'localdisk')
    )
    network_client = tm_env.svc_network.make_client(
        os.path.join(container_dir, 'resources', 'network')
    )
    presence_client = tm_env.svc_presence.make_client(
        os.path.join(container_dir, 'resources', 'presence')
    )

    # Unregister presence
    presence_client.delete(app.name)

    # Destroy the volume
    try:
        localdisk_client.delete(unique_name)
    except (IOError, OSError) as err:
        if err.errno == errno.ENOENT:
            pass
        else:
            raise

    if not app.shared_network:
        _cleanup_network(tm_env, container_dir, app, network_client)

    # Add metrics to archive
    rrd_file = os.path.join(
        tm_env.metrics_dir,
        'apps',
        '{name}-{instanceid}-{uniqueid}.rrd'.format(
            name=app.app,
            instanceid=app.task,
            uniqueid=app.uniqueid,
        )
    )
    rrdutils.flush_noexc(rrd_file)
    _copy_metrics(rrd_file, container_dir)

    # Cleanup our cgroup resources
    try:
        cgroup_client.delete(unique_name)
    except (IOError, OSError) as err:
        if err.errno == errno.ENOENT:
            pass
        else:
            raise

    try:
        runtime.archive_logs(tm_env, appcfg.app_unique_name(app),
                             container_dir)
    except Exception:  # pylint: disable=W0703
        _LOGGER.exception('Unexpected exception storing local logs.')

def _cleanup_network(tm_env, container_dir, app, network_client):
    """Cleanup the network part of a container.
    """
    # Generate a unique name for the app
    unique_name = appcfg.app_unique_name(app)

    try:
        app_network = network_client.get(unique_name)

    except services.ResourceServiceError:
        _LOGGER.warning('network never allocated')
        return

    if app_network is None:
        _LOGGER.info('Network resource already freed')
        return

    # Unconfigure passthrough
    if hasattr(app, 'passthrough'):
        _LOGGER.info('Deleting passthrough for: %r',
                     app.passthrough)
        # Resolve all the hosts
        # FIXME: There is no guarantie the hosts will resolve to
        #        the same IPs as they did during creation.
        ips = set([socket.gethostbyname(host)
                   for host in app.passthrough])
        for ip in ips:
            tm_env.rules.unlink_rule(
                chain=iptables.PREROUTING_PASSTHROUGH,
                rule=firewall.PassThroughRule(src_ip=ip,
                                              dst_ip=app_network['vip']),
                owner=unique_name,
            )

    if app.vring:
        # Mark the container's IP as VRing enabled
        _LOGGER.debug('removing %r from VRing set', app_network['vip'])
        iptables.rm_ip_set(
            iptables.SET_VRING_CONTAINERS,
            app_network['vip']
        )

    tm_env.endpoints.unlink_all(app.name, owner=unique_name)

    for endpoint in app.endpoints:
        tm_env.rules.unlink_rule(
            chain=iptables.PREROUTING_DNAT,
            rule=firewall.DNATRule(proto=endpoint.proto,
                                   dst_ip=app_network['external_ip'],
                                   dst_port=endpoint.real_port,
                                   new_ip=app_network['vip'],
                                   new_port=endpoint.port),
            owner=unique_name,
        )
        tm_env.rules.unlink_rule(
            chain=iptables.POSTROUTING_SNAT,
            rule=firewall.SNATRule(proto=endpoint.proto,
                                   src_ip=app_network['vip'],
                                   src_port=endpoint.port,
                                   new_ip=app_network['external_ip'],
                                   new_port=endpoint.real_port),
            owner=unique_name,
        )
        # See if this was an "infra" endpoint and if so remove it
        # from the whitelist set.
        if getattr(endpoint, 'type', None) == 'infra':
            _LOGGER.debug('removing %s:%s from infra services set',
                          app_network['vip'], endpoint.port)
            iptables.rm_ip_set(
                iptables.SET_INFRA_SVC,
                '{ip},{proto}:{port}'.format(
                    ip=app_network['vip'],
                    proto=endpoint.proto,
                    port=endpoint.port,
                )
            )

    _cleanup_ephemeral_ports(
        tm_env,
        unique_name,
        app_network['external_ip'],
        app_network['vip'],
        app.ephemeral_ports.tcp,
        'tcp'
    )
    _cleanup_ephemeral_ports(
        tm_env,
        unique_name,
        app_network['external_ip'],
        app_network['vip'],
        app.ephemeral_ports.udp,
        'udp'
    )

    _cleanup_exception_rules(tm_env, container_dir, app)

    # Terminate any entries in the conntrack table
    iptables.flush_cnt_conntrack_table(app_network['vip'])
    # Cleanup network resources
    network_client.delete(unique_name)

def _cleanup_ephemeral_ports(tm_env, unique_name,
                             external_ip, vip, ports, proto):
    """Cleanup firewall rules for ports."""
    for port in ports:
        # We treat ephemeral ports as infra, consistent with current
        # prodperim behavior.
        iptables.rm_ip_set(
            iptables.SET_INFRA_SVC,
            '{ip},{proto}:{port}'.format(ip=vip,
                                         proto=proto,
                                         port=port)
        )
        dnatrule = firewall.DNATRule(proto=proto,
                                     dst_ip=external_ip,
                                     dst_port=port,
                                     new_ip=vip,
                                     new_port=port)
        tm_env.rules.unlink_rule(
            chain=iptables.PREROUTING_DNAT,
            rule=dnatrule,
            owner=unique_name
        )

def _cleanup_exception_rules(tm_env, container_dir, app):
    """Clean up firewall exception rules"""
    try:
        firewall_plugin = plugin_manager.load(
            'treadmill.firewall.plugins', 'firewall'
        )
        firewall_plugin.cleanup_exception_rules(tm_env, container_dir, app)
    except Exception:  # pylint: disable=W0703
        _LOGGER.exception(
            'Error in firewall plugin, skip cleaning firewall exception rules.'
        )

def _copy_metrics(metrics_file, container_dir):
    """Safe copy metrics file to container directory."""
    _LOGGER.info('Copy metrics: %s to %s', metrics_file, container_dir)
    try:
        # TODO: We should factor out rrd specificities to a module
        shutil.copy(metrics_file, os.path.join(container_dir, 'metrics.rrd'))

    except IOError as err:
        if err.errno == errno.ENOENT:
            _LOGGER.info('metrics file not found: %s.', metrics_file)
        else:
            raise


text:
import argparse
import math
import re
import sys

REGEX_FLOAT = r'(?:[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)'

class GMM(object):
    def __init__(self):
        self._mixes = []

    @property
    def dimension(self):
        return (len(self._mixes[0][0]) if len(self._mixes) > 0 else None)

    @property
    def num_mixtures(self):
        return (len(self._mixes) if self._mixes is not None else None)

    def add_mixture(self, m, v, w):
        assert isinstance(w, float), 'Mixture weight must '
        if not isinstance(m, tuple): m = tuple(m)
        if not isinstance(v, tuple): v = tuple(v)
        assert len(m) == len(v), \
            'Dimension of mean and variance vectors must agree'
        self._mixes.append((m, v, w))
        if len(self._mixes) > 1:
            assert len(self._mixes[0][0]) == len(self._mixes[-1][0]), \
                'All mixtures in a GMM must have the same dimension'

    def write(self, f):
        f.write('<DiagGMM>\n')
        f.write('<WEIGHTS> [ %s ]\n' % ' '.join(
            map(lambda x: str(x[-1]), self._mixes)))
        f.write('<MEANS_INVVARS> [\n')
        for (m, v, _) in self._mixes:
            for mi, vi in zip(m, v):
                f.write(' %g' % (mi / vi))
            f.write('\n')
        f.write(']\n')
        f.write('<INV_VARS> [\n')
        for (_, v, _) in self._mixes:
            for vi in v:
                f.write(' %g' % (1.0 / vi))
            f.write('\n')
        f.write(']\n')

        f.write('</DiagGMM>\n')

class HMM(object):
    def __init__(self):
        self._states = []
        self._pinit = None

    @property
    def dimension(self):
        return self._states[0][0].dimension if len(self._states) > 0 \
            else None

    def add_state(self, gmm):
        self._states.append([gmm, []])

    def set_initial(self, pinit):
        self._pinit = pinit

    def set_transition(self, i, ptrans):
        assert i >= 0 and i < len(self._states), 'Unknown state %d' % i
        if not isinstance(ptrans, tuple): ptrans = tuple(ptrans)
        self._states[i][1] = ptrans

    def write_transitions(self, f):
        if self._pinit[1] < 1.0:
            # Initial State
            f.write('<State> 0\n')
            for j, p in enumerate(self._pinit):
                if p <= 0.0: continue
                f.write('<Transition> %d %g\n' % (j, p))
            # Emitting states
            for s, (_, trans) in enumerate(self._states):
                f.write('<State> %d <PdfClass> %d\n' % (s + 1, s))
                for j, p in enumerate(trans):
                    if p <= 0.0: continue
                    f.write('<Transition> %d %g\n' % (j, p))
                f.write('</State>\n')
            # Final state
            f.write('<State> %d\n' % (len(self._states) + 1))
            f.write('</State>\n')
        else:
            # Emitting states
            for s, (_, trans) in enumerate(self._states):
                f.write('<State> %d <PdfClass> %d\n' % (s, s))
                for j, p in enumerate(trans):
                    if p <= 0.0: continue
                    f.write('<Transition> %d %g\n' % (j - 1, p))
                f.write('</State>\n')
            # Final state
            f.write('<State> %d\n' % len(self._states))
            f.write('</State>\n')

    def write_pdfs(self, f):
        for (gmm, _) in self._states:
            gmm.write(f)

    def get_states_pdfs(self):
        if self._pinit[1] < 1.0:
            return map(lambda x: (x + 1, x), xrange(len(self._states)))
        else:
            return map(lambda x: (x, x), xrange(len(self._states)))

    def get_transition_logprobs(self):
        logprobs = []
        if self._pinit[1] < 1.0:
            for p in self._pinit:
                if p <= 0.0: continue
                logprobs.append(math.log(p))
        for (_, trans) in self._states:
            for p in trans:
                if p <= 0.0: continue
                logprobs.append(math.log(p))
        return logprobs

class Model(object):
    def __init__(self):
        self._dim = None
        self._hmm = {}

    @property
    def dimension(self):
        return self._dim

    @dimension.setter
    def dimension(self, value):
        assert isinstance(value, int)
        self._dim = value

    def add_hmm(self, i, hmm):
        assert isinstance(i, int)
        assert self._dim == hmm.dimension
        self._hmm[i] = hmm

    def write(self, f):
        if isinstance(f, str) or isinstance(f, unicode):
            f = open(f, 'w')
        f.write('<TransitionModel>\n')
        f.write('<Topology>\n')
        for hmm_id, hmm in self._hmm.iteritems():
            f.write('<TopologyEntry>\n')
            f.write('<ForPhones> %d </ForPhones>\n' % hmm_id)
            hmm.write_transitions(f)
            f.write('</TopologyEntry>\n')
        f.write('</Topology>\n')
        # Triples
        triples, logprobs = [], [0]
        for hmm_id, hmm in self._hmm.iteritems():
            base_pdfs = len(triples)
            for (s, pdf) in hmm.get_states_pdfs():
                triples.append((hmm_id, s, pdf + base_pdfs))
            logprobs.extend(hmm.get_transition_logprobs())
        f.write('<Triples> %d\n' % len(triples))
        for (h, s, p) in triples:
            f.write('%d %d %d\n' % (h, s, p))
        f.write('</Triples>\n')
        f.write('<LogProbs>\n[ %s ]\n</LogProbs>\n' % \
                ' '.join(map(lambda x: str(x), logprobs)))
        f.write('</TransitionModel>\n')
        num_pdfs = max(map(lambda x: x[-1], triples)) + 1
        f.write('<DIMENSION> %d <NUMPDFS> %d\n' % (self.dimension, num_pdfs))
        for hmm in self._hmm.itervalues():
            hmm.write_pdfs(f)
        f.close()

class HTKParser(object):
    def __init__(self, symbols_table):
        assert isinstance(symbols_table, dict)
        self._n = 0
        self._line = None
        self._data = None
        self._model = None
        self._symbols = symbols_table

    def _next(self):
        if not self._data:
            return False
        self._n += 1
        if self._n < len(self._data):
            self._line = self._data[self._n]
            return True
        else:
            self._line = None
            return False

    def _msg(self, s):
        return '%s at line %d: "%s"' % (s, self._n + 1, self._line)

    def _read_dim(self):
        assert self._line is not None, 'Unexpected EOF'
        m = re.match('^<STREAMINFO> 1 ([0-9]+)$', self._line)
        if not m: return False
        self._model.dimension = int(m.group(1))
        return self._next()

    def _read_hmm(self):
        assert self._line is not None, 'Unexpected EOF'
        m = re.match('^~h "([0-9A-Za-z]+)"$', self._line)
        if not m: return False
        hmm_sym = m.group(1)
        hmm_id = self._symbols.get(hmm_sym, None)
        assert hmm_id is not None, self._msg(
            'HMM symbol \"%s\" is not found in the symbols table' % hmm_sym)
        hmm = HMM()
        # Read <BEGINHMM>
        assert self._next(), 'Unexpected EOF'
        assert re.match('^<BEGINHMM>$', self._line), \
            self._msg('Expected "<BEGINHMM>"')
        # Read <NUMSTATES>
        assert self._next(), 'Unexpected EOF'
        m = re.match('^<NUMSTATES> ([0-9]+)$', self._line)
        assert m, self._msg('Expected "<NUMSTATES> %%d"')
        num_states = int(m.group(1))
        assert num_states > 2, self._msg('Unexpected number of states')
        # Process all <STATE>s
        assert self._next(), 'Unexpected EOF'
        for s in xrange(2, num_states):
            # Check state ID
            m = re.match('^<STATE> %d$' % s, self._line)
            assert m, self._msg('Expected "<STATE> %d"' % s)
            # Read number of mixtures
            assert self._next(), 'Unexpected EOF'
            m = re.match('^<NUMMIXES> ([0-9]+)$', self._line)
            gmm = GMM()
            if not m:
                ## Special case: 1 Gaussian
                num_mixes = 1
                weight = 1.0
                # Check <MEAN>
                m = re.match('^<MEAN> %d$' % self._model.dimension, self._line)
                assert m, self._msg('Expected "<MEAN> %d"' % \
                                    self._model.dimension)
                # Read mean vector
                assert self._next(), 'Unexpected EOF'
                mean = tuple([float(x) for x in self._line.split()])
                assert len(mean) == self._model.dimension, \
                    self._msg('Invalid mean vector')
                # Check <VARIANCE>
                assert self._next(), 'Unexpected EOF'
                m = re.match('^<VARIANCE> %d$' % self._model.dimension,
                             self._line)
                assert m, self._msg('Expected "<VARIANCE> %d"' % \
                                    self._model.dimension)
                # Read variance vector
                assert self._next(), 'Unexpected EOF'
                var = tuple([ float(x) for x in self._line.split() ])
                assert len(var) == self._model.dimension, \
                    self._msg('Invalid variance vector')
                # Read Gconst. It is not used, since it can be obtained from
                # the mean and the variance vectors.
                assert self._next(), 'Unexpected EOF'
                m = re.match('^<GCONST> (%s)$' % REGEX_FLOAT, self._line)
                assert m, self._msg('Expected "<GCONST> %%f"')
                # Add mixture to the gmm
                gmm.add_mixture(mean, var, weight)
                assert self._next(), 'Unexpected EOF'
            else:
                ## General case, Gaussian Mixture Model
                num_mixes = int(m.group(1))
                assert num_mixes > 0, self._msg('Invalid number of mixtures')
                # Process all <MIXTURE>s
                while True:
                    # Read mixture weight
                    assert self._next(), 'Unexpected EOF'
                    m = re.match('^<MIXTURE> \d+ (%s)$' % REGEX_FLOAT,
                                 self._line)
                    if not m: break
                    weight = float(m.group(1))
                    assert weight > 0.0 and weight <= 1.0, \
                        self._msg('Invalid mixture weight')
                    # Check <MEAN>
                    assert self._next(), 'Unexpected EOF'
                    m = re.match('^<MEAN> %d$' % self._model.dimension,
                                 self._line)
                    assert m, self._msg('Expected "<MEAN> %d"' % \
                                        self._model.dimension)
                    # Read mean vector
                    assert self._next(), 'Unexpected EOF'
                    mean = tuple([float(x) for x in self._line.split()])
                    assert len(mean) == self._model.dimension, \
                        self._msg('Invalid mean vector')
                    # Check <VARIANCE>
                    assert self._next(), 'Unexpected EOF'
                    m = re.match('^<VARIANCE> %d$' % self._model.dimension,
                                 self._line)
                    assert m, self._msg('Expected "<VARIANCE> %d"' % \
                                        self._model.dimension)
                    # Read variance vector
                    assert self._next(), 'Unexpected EOF'
                    var = tuple([ float(x) for x in self._line.split() ])
                    assert len(var) == self._model.dimension, \
                        self._msg('Invalid variance vector')
                    # Read Gconst. It is not used, since it can be obtained from
                    # the mean and the variance vectors.
                    assert self._next(), 'Unexpected EOF'
                    m = re.match('^<GCONST> (%s)$' % REGEX_FLOAT, self._line)
                    assert m, self._msg('Expected "<GCONST> %%f"')
                    # Add mixture to the gmm
                    gmm.add_mixture(mean, var, weight)
            # Add state to the HMM
            hmm.add_state(gmm)
        # Process transitions, Read <TRASNP>.
        #assert self._next(), 'Unexpected EOF'
        m = re.match('^<TRANSP> %d$' % num_states, self._line)
        assert m, self._msg('Expected "<TRANSP> %d"' % self._n)
        # Process initial state
        assert self._next(), 'Unexpected EOF'
        t = tuple([float(x) for x in self._line.split()])
        assert len(t) == num_states, \
            self._msg('Unexpected number of transitions')
        hmm.set_initial(t)
        # Process emitting states
        for i in range(num_states - 2):
            assert self._next(), 'Unexpected EOF'
            t = tuple([ float(x) for x in self._line.split() ])
            assert len(t) == num_states, \
                self._msg('Unexpected number of transitions' % self._n)
            hmm.set_transition(i, t)
        # Process final state (just ignore it)
        assert self._next(), 'Unexpected EOF'
        t = tuple([ float(x) for x in self._line.split() ])
        assert len(t) == num_states, \
            'Unexpected number of transitions at line %d' % self._n
        # Check <ENDHMM>
        assert self._next(), 'Unexpected EOF'
        m = re.match('^<ENDHMM>$', self._line)
        self._model.add_hmm(hmm_id, hmm)
        return True

    def parse(self, f):
        if isinstance(f, str) or isinstance(f, unicode):
            f = open(f, 'r')
        self._model = Model()
        self._data = [line.strip() for line in f]
        f.close()
        assert len(self._data) > 0, 'Unexpected EOF'
        self._n = -1
        while self._next():
            if not self._read_dim() and not self._read_hmm():
                sys.stderr.write('IGNORED LINE: \"%s\"\n' % self._line)
        return self._model

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Convert a HMM/GMM model file from HTK to Kaldi format.')
    parser.add_argument('symbols_table', type=argparse.FileType('r'),
                        help='HMM symbols table')
    parser.add_argument('input', type=argparse.FileType('r'),
                        nargs='?', default=sys.stdin,
                        help='Input model in HTK text format')
    parser.add_argument('output', type=argparse.FileType('w'),
                        nargs='?', default=sys.stdout,
                        help='Output model in Kaldi text format')
    args = parser.parse_args()

    # Read symbols table
    symbols_table = {}
    for line in args.symbols_table:
        line = line.split()
        assert len(line) == 2, 'Wrong symbols table format'
        symbols_table[line[0]] = int(line[1])

    htk_parser = HTKParser(symbols_table)
    model = htk_parser.parse(args.input)
    model.write(args.output)


text:
package com.oracle.webservices.api.message;

/**
 * Used to indicate that {@link PropertySet#put(String, Object)} failed
 * because a property is read-only.
 *
 * @author Kohsuke Kawaguchi
 */
public class ReadOnlyPropertyException extends IllegalArgumentException {

    private static final long serialVersionUID = -3328766024488469509L;

    private final String propertyName;

    public ReadOnlyPropertyException(String propertyName) {
        super(propertyName+" is a read-only property.");
        this.propertyName = propertyName;
    }

    /**
     * Gets the name of the property that was read-only.
     */
    public String getPropertyName() {
        return propertyName;
    }
}


text:
package com.badlogic.gdx.graphics.glutils;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.zip.GZIPInputStream;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Cubemap;
import com.badlogic.gdx.graphics.CubemapData;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.glutils.ETC1.ETC1Data;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.StreamUtils;

/** A KTXTextureData holds the data from a KTX (or zipped KTX file, aka ZKTX). That is to say an OpenGL ready texture data. The KTX
 * file format is just a thin wrapper around OpenGL textures and therefore is compatible with most OpenGL texture capabilities
 * like texture compression, cubemapping, mipmapping, etc.
 *
 * For example, KTXTextureData can be used for {@link Texture} or {@link Cubemap}.
 *
 * @author Vincent Bousquet */
public class KTXTextureData implements TextureData, CubemapData {

	// The file we are loading
	private FileHandle file;

	// KTX header (only available after preparing)
	private int glType;
	private int glTypeSize;
	private int glFormat;
	private int glInternalFormat;
	private int glBaseInternalFormat;
	private int pixelWidth = -1;
	private int pixelHeight = -1;
	private int pixelDepth = -1;
	private int numberOfArrayElements;
	private int numberOfFaces;
	private int numberOfMipmapLevels;
	private int imagePos;

	// KTX image data (only available after preparing and before consuming)
	private ByteBuffer compressedData;

	// Whether to generate mipmaps if they are not included in the file
	private boolean useMipMaps;

	public KTXTextureData (FileHandle file, boolean genMipMaps) {
		this.file = file;
		this.useMipMaps = genMipMaps;
	}

	@Override
	public TextureDataType getType () {
		return TextureDataType.Custom;
	}

	@Override
	public boolean isPrepared () {
		return compressedData != null;
	}

	@Override
	public void prepare () {
		if (compressedData != null) throw new GdxRuntimeException("Already prepared");
		if (file == null) throw new GdxRuntimeException("Need a file to load from");
		// We support normal ktx files as well as 'zktx' which are gzip ktx file with an int length at the beginning (like ETC1).
		if (file.name().endsWith(".zktx")) {
			byte[] buffer = new byte[1024 * 10];
			DataInputStream in = null;
			try {
				in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(file.read())));
				int fileSize = in.readInt();
				compressedData = BufferUtils.newUnsafeByteBuffer(fileSize);
				int readBytes = 0;
				while ((readBytes = in.read(buffer)) != -1)
					compressedData.put(buffer, 0, readBytes);
				compressedData.position(0);
				compressedData.limit(compressedData.capacity());
			} catch (Exception e) {
				throw new GdxRuntimeException("Couldn't load zktx file '" + file + "'", e);
			} finally {
				StreamUtils.closeQuietly(in);
			}
		} else {
			compressedData = ByteBuffer.wrap(file.readBytes());
		}
		if (compressedData.get() != (byte)0x0AB) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x04B) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x054) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x058) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x020) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x031) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x031) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x0BB) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x00D) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x00A) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x01A) throw new GdxRuntimeException("Invalid KTX Header");
		if (compressedData.get() != (byte)0x00A) throw new GdxRuntimeException("Invalid KTX Header");
		int endianTag = compressedData.getInt();
		if (endianTag != 0x04030201 && endianTag != 0x01020304) throw new GdxRuntimeException("Invalid KTX Header");
		if (endianTag != 0x04030201)
			compressedData.order(compressedData.order() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
		glType = compressedData.getInt();
		glTypeSize = compressedData.getInt();
		glFormat = compressedData.getInt();
		glInternalFormat = compressedData.getInt();
		glBaseInternalFormat = compressedData.getInt();
		pixelWidth = compressedData.getInt();
		pixelHeight = compressedData.getInt();
		pixelDepth = compressedData.getInt();
		numberOfArrayElements = compressedData.getInt();
		numberOfFaces = compressedData.getInt();
		numberOfMipmapLevels = compressedData.getInt();
		if (numberOfMipmapLevels == 0) {
			numberOfMipmapLevels = 1;
			useMipMaps = true;
		}
		int bytesOfKeyValueData = compressedData.getInt();
		imagePos = compressedData.position() + bytesOfKeyValueData;
		if (!compressedData.isDirect()) {
			int pos = imagePos;
			for (int level = 0; level < numberOfMipmapLevels; level++) {
				int faceLodSize = compressedData.getInt(pos);
				int faceLodSizeRounded = (faceLodSize + 3) & ~3;
				pos += faceLodSizeRounded * numberOfFaces + 4;
			}
			compressedData.limit(pos);
			compressedData.position(0);
			ByteBuffer directBuffer = BufferUtils.newUnsafeByteBuffer(pos);
			directBuffer.order(compressedData.order());
			directBuffer.put(compressedData);
			compressedData = directBuffer;
		}
	}

	private static final int GL_TEXTURE_1D = 0x1234;
	private static final int GL_TEXTURE_3D = 0x1234;
	private static final int GL_TEXTURE_1D_ARRAY_EXT = 0x1234;
	private static final int GL_TEXTURE_2D_ARRAY_EXT = 0x1234;

	@Override
	public void consumeCubemapData () {
		consumeCustomData(GL20.GL_TEXTURE_CUBE_MAP);
	}

	@Override
	public void consumeCustomData (int target) {
		if (compressedData == null) throw new GdxRuntimeException("Call prepare() before calling consumeCompressedData()");
		IntBuffer buffer = BufferUtils.newIntBuffer(16);

		// Check OpenGL type and format, detect compressed data format (no type & format)
		boolean compressed = false;
		if (glType == 0 || glFormat == 0) {
			if (glType + glFormat != 0) throw new GdxRuntimeException("either both or none of glType, glFormat must be zero");
			compressed = true;
		}

		// find OpenGL texture target and dimensions
		int textureDimensions = 1;
		int glTarget = GL_TEXTURE_1D;
		if (pixelHeight > 0) {
			textureDimensions = 2;
			glTarget = GL20.GL_TEXTURE_2D;
		}
		if (pixelDepth > 0) {
			textureDimensions = 3;
			glTarget = GL_TEXTURE_3D;
		}
		if (numberOfFaces == 6) {
			if (textureDimensions == 2)
				glTarget = GL20.GL_TEXTURE_CUBE_MAP;
			else
				throw new GdxRuntimeException("cube map needs 2D faces");
		} else if (numberOfFaces != 1) {
			throw new GdxRuntimeException("numberOfFaces must be either 1 or 6");
		}
		if (numberOfArrayElements > 0) {
			if (glTarget == GL_TEXTURE_1D)
				glTarget = GL_TEXTURE_1D_ARRAY_EXT;
			else if (glTarget == GL20.GL_TEXTURE_2D)
				glTarget = GL_TEXTURE_2D_ARRAY_EXT;
			else
				throw new GdxRuntimeException("No API for 3D and cube arrays yet");
			textureDimensions++;
		}
		if (glTarget == 0x1234)
			throw new GdxRuntimeException("Unsupported texture format (only 2D texture are supported in LibGdx for the time being)");

		int singleFace = -1;
		if (numberOfFaces == 6 && target != GL20.GL_TEXTURE_CUBE_MAP) {
			// Load a single face of the cube (should be avoided since the data is unloaded afterwards)
			if (!(GL20.GL_TEXTURE_CUBE_MAP_POSITIVE_X <= target && target <= GL20.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z))
				throw new GdxRuntimeException(
					"You must specify either GL_TEXTURE_CUBE_MAP to bind all 6 faces of the cube or the requested face GL_TEXTURE_CUBE_MAP_POSITIVE_X and followings.");
			singleFace = target - GL20.GL_TEXTURE_CUBE_MAP_POSITIVE_X;
			target = GL20.GL_TEXTURE_CUBE_MAP_POSITIVE_X;
		} else if (numberOfFaces == 6 && target == GL20.GL_TEXTURE_CUBE_MAP) {
			// Load the 6 faces
			target = GL20.GL_TEXTURE_CUBE_MAP_POSITIVE_X;
		} else {
			// Load normal texture
			if (target != glTarget
				&& !(GL20.GL_TEXTURE_CUBE_MAP_POSITIVE_X <= target && target <= GL20.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z && target == GL20.GL_TEXTURE_2D))
				throw new GdxRuntimeException("Invalid target requested : 0x" + Integer.toHexString(target) + ", expecting : 0x"
					+ Integer.toHexString(glTarget));
		}

		// KTX files require an unpack alignment of 4
		Gdx.gl.glGetIntegerv(GL20.GL_UNPACK_ALIGNMENT, buffer);
		int previousUnpackAlignment = buffer.get(0);
		if (previousUnpackAlignment != 4) Gdx.gl.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, 4);
		int glInternalFormat = this.glInternalFormat;
		int glFormat = this.glFormat;
		int pos = imagePos;
		for (int level = 0; level < numberOfMipmapLevels; level++) {
			int pixelWidth = Math.max(1, this.pixelWidth >> level);
			int pixelHeight = Math.max(1, this.pixelHeight >> level);
			int pixelDepth = Math.max(1, this.pixelDepth >> level);
			compressedData.position(pos);
			int faceLodSize = compressedData.getInt();
			int faceLodSizeRounded = (faceLodSize + 3) & ~3;
			pos += 4;
			for (int face = 0; face < numberOfFaces; face++) {
				compressedData.position(pos);
				pos += faceLodSizeRounded;
				if (singleFace != -1 && singleFace != face) continue;
				ByteBuffer data = compressedData.slice();
				data.limit(faceLodSizeRounded);
				if (textureDimensions == 1) {
					// if (compressed)
					// Gdx.gl.glCompressedTexImage1D(target + face, level, glInternalFormat, pixelWidth, 0, faceLodSize,
					// data);
					// else
					// Gdx.gl.glTexImage1D(target + face, level, glInternalFormat, pixelWidth, 0, glFormat, glType, data);
				} else if (textureDimensions == 2) {
					if (numberOfArrayElements > 0) pixelHeight = numberOfArrayElements;
					if (compressed) {
						if (glInternalFormat == ETC1.ETC1_RGB8_OES) {
							if (!Gdx.graphics.supportsExtension("GL_OES_compressed_ETC1_RGB8_texture")) {
								ETC1Data etcData = new ETC1Data(pixelWidth, pixelHeight, data, 0);
								Pixmap pixmap = ETC1.decodeImage(etcData, Format.RGB888);
								Gdx.gl.glTexImage2D(target + face, level, pixmap.getGLInternalFormat(), pixmap.getWidth(),
									pixmap.getHeight(), 0, pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
								pixmap.dispose();
							} else {
								Gdx.gl.glCompressedTexImage2D(target + face, level, glInternalFormat, pixelWidth, pixelHeight, 0,
									faceLodSize, data);
							}
						} else {
							// Try to load (no software unpacking fallback)
							Gdx.gl.glCompressedTexImage2D(target + face, level, glInternalFormat, pixelWidth, pixelHeight, 0,
								faceLodSize, data);
						}
					} else
						Gdx.gl.glTexImage2D(target + face, level, glInternalFormat, pixelWidth, pixelHeight, 0, glFormat, glType, data);
				} else if (textureDimensions == 3) {
					if (numberOfArrayElements > 0) pixelDepth = numberOfArrayElements;
					// if (compressed)
					// Gdx.gl.glCompressedTexImage3D(target + face, level, glInternalFormat, pixelWidth, pixelHeight, pixelDepth, 0,
					// faceLodSize, data);
					// else
					// Gdx.gl.glTexImage3D(target + face, level, glInternalFormat, pixelWidth, pixelHeight, pixelDepth, 0, glFormat,
					// glType, data);
				}
			}
		}
		if (previousUnpackAlignment != 4) Gdx.gl.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, previousUnpackAlignment);
		if (useMipMaps()) Gdx.gl.glGenerateMipmap(target);

		// dispose data once transfered to GPU
		disposePreparedData();
	}

	public void disposePreparedData () {
		if (compressedData != null) BufferUtils.disposeUnsafeByteBuffer(compressedData);
		compressedData = null;
	}

	@Override
	public Pixmap consumePixmap () {
		throw new GdxRuntimeException("This TextureData implementation does not return a Pixmap");
	}

	@Override
	public boolean disposePixmap () {
		throw new GdxRuntimeException("This TextureData implementation does not return a Pixmap");
	}

	@Override
	public int getWidth () {
		return pixelWidth;
	}

	@Override
	public int getHeight () {
		return pixelHeight;
	}

	public int getNumberOfMipMapLevels () {
		return numberOfMipmapLevels;
	}

	public int getNumberOfFaces () {
		return numberOfFaces;
	}

	public int getGlInternalFormat () {
		return glInternalFormat;
	}

	public ByteBuffer getData (int requestedLevel, int requestedFace) {
		int pos = imagePos;
		for (int level = 0; level < numberOfMipmapLevels; level++) {
			int faceLodSize = compressedData.getInt(pos);
			int faceLodSizeRounded = (faceLodSize + 3) & ~3;
			pos += 4;
			if (level == requestedLevel) {
				for (int face = 0; face < numberOfFaces; face++) {
					if (face == requestedFace) {
						compressedData.position(pos);
						ByteBuffer data = compressedData.slice();
						data.limit(faceLodSizeRounded);
						return data;
					}
					pos += faceLodSizeRounded;
				}
			} else {
				pos += faceLodSizeRounded * numberOfFaces;
			}
		}
		return null;
	}

	@Override
	public Format getFormat () {
		throw new GdxRuntimeException("This TextureData implementation directly handles texture formats.");
	}

	@Override
	public boolean useMipMaps () {
		return useMipMaps;
	}

	@Override
	public boolean isManaged () {
		return true;
	}

}


text:
import logging
import traceback
from unittest import mock

from .common import BuiltinTest
from bfg9000.builtins import core  # noqa: F401
from bfg9000 import exceptions
from bfg9000.path import Path, Root
from bfg9000.safe_str import safe_str, safe_format

class TestCore(BuiltinTest):
    def test_warning(self):
        with mock.patch('warnings.warn') as warn:
            self.context['warning']('message')
            warn.assert_called_once_with('message')

        with mock.patch('warnings.warn') as warn:
            self.context['warning']('message', 1, Path('path'), 'bar')
            warn.assert_called_once_with(
                'message 1 ' + repr(Path('path')) + ' bar'
            )

    def test_info(self):
        with mock.patch('logging.log') as log:
            self.context['info']('message')
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(logging.INFO, 'message', extra={
                'full_stack': tb, 'show_stack': False
            })

        with mock.patch('logging.log') as log:
            self.context['info']('message', 1, Path('path'), 'bar')
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(
                logging.INFO, 'message 1 ' + repr(Path('path')) + ' bar',
                extra={
                    'full_stack': tb, 'show_stack': False
                }
            )

        with mock.patch('logging.log') as log:
            self.context['info']('message', show_stack=True)
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(logging.INFO, 'message', extra={
                'full_stack': tb, 'show_stack': True
            })

    def test_debug(self):
        with mock.patch('logging.log') as log:
            self.context['debug']('message')
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(logging.DEBUG, 'message', extra={
                'full_stack': tb, 'show_stack': True
            })

        with mock.patch('logging.log') as log:
            self.context['debug']('message', 1, Path('path'), 'bar')
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(
                logging.DEBUG, 'message 1 ' + repr(Path('path')) + ' bar',
                extra={
                    'full_stack': tb, 'show_stack': True
                }
            )

        with mock.patch('logging.log') as log:
            self.context['debug']('message', show_stack=False)
            tb = traceback.extract_stack()[1:]
            tb[-1].lineno -= 1

            log.assert_called_once_with(logging.DEBUG, 'message', extra={
                'full_stack': tb, 'show_stack': False
            })

    def test_exceptions(self):
        for name in dir(exceptions):
            t = getattr(exceptions, name)
            if isinstance(t, type):
                self.assertIs(self.context[name], t)

    def test_safe_str(self):
        self.assertIs(self.context['safe_str'], safe_str)
        self.assertIs(self.context['safe_format'], safe_format)

    def test_submodule(self):
        def mock_execute(context, path):
            return context.PathEntry(path)

        with mock.patch('bfg9000.build.execute_file',
                        mock.MagicMock(wraps=mock_execute)) as m:
            self.assertEqual(self.context['submodule']('dir'), {})
            m.assert_called_once_with(self.context,
                                      Path('dir/build.bfg', Root.srcdir))

        with self.context.push_path(Path('dir/build.bfg', Root.srcdir)), \
             mock.patch('bfg9000.build.execute_file',
                        mock.MagicMock(wraps=mock_execute)) as m:
            self.assertEqual(self.context['submodule']('sub'), {})
            m.assert_called_once_with(self.context,
                                      Path('dir/sub/build.bfg', Root.srcdir))

    def test_export(self):
        with self.context.push_path(Path('foo/build.bfg', Root.srcdir)) as p:
            self.context['export'](foo='foo')
        self.assertEqual(p.exports, {'foo': 'foo'})
        self.assertRaises(ValueError, self.context['export'], bar='bar')


text:
require([
    'base',
    'core-ajax',
    'cookies'
], function($, ajax) {
    var jOldPwd = $("#oldPwd"),
        jNewPwd = $("#newPwd"),
        jConfirmPwd = $("#confirmPwd"),
        jSubmit = $("#submit");

    start();

    function start() {
        init();
        event();
    }

    function init() {

    }

    function event() {
        jOldPwd.add(jNewPwd).add(jConfirmPwd).on("keyup", function() {
            var str = $(this).val(),
                jGroup = $(this).closest(".form-group");
            if ($.trim(str).length === 0) {
                jGroup.addClass("has-error").find(".help-block").show();
            } else {
                jGroup.removeClass("has-error").find(".help-block").hide();
            }
        });
        jSubmit.on("click", function() {
            submit();
        })
    }

    function submit() {
        var OriginalPassword = jOldPwd.val(),
            NewPassword = jNewPwd.val(),
            ConfirmPassword = jConfirmPwd.val();
        var jGroup = $(".form-group");
        jGroup.find("input").keyup();
        if (jGroup.hasClass("has-error")) {
            return;
        }
        if (NewPassword !== ConfirmPassword) {
            alert("两次输入的新密码不一致!");
            return;
        }

        var user_data = $.cookies.get('USER-PROFILE');
        var request = {
            //id: user_data.user_id,
            old_pass: OriginalPassword,
            new_pass: NewPassword
        };

        ajax({
            url: '/elearning-account-h5/account/changePass',
            data: request,
            type: "post",
            success: function() {
                //jOldPwd.val("");
                //jNewPwd.val("");
                //jConfirmPwd.val("");
                alert("保存成功, 请使用新密码重新登录!");
                logout();
            },
            error: function(xhr, status, error) {
                var error = (xhr && xhr.responseJSON && xhr.responseJSON.message) || "服务器在开小差, 请联系管理员!";
                alert(error);
            }
        });
    }

    //退出
    function logout() {
        ajax({
            url: '/elearning-account-h5/certification/center/logout',
            success: function(data, status, xhr) {
                $.cookies.del('USER-TICKET');
                $.cookies.del("ALREADY_LOGIN");

                //TODO: https ?
                // window.location.href = $.__router.login;
                // window.location.href = 'https://'+ document.domain + ( (window.location.port)?':'+window.location.port:'' ) +"/login.html";
                //window.location.href = __root + "/login.html";
            },
            error: function(xhr, status, error) {
                // window.location.href = $.__router.login;
                console.error(arguments);
            }
        });
        window.location.href = $.__router.login;
    }

});


text:
using MySqlConnector.Utilities;

namespace MySqlConnector.Protocol.Serialization;

internal interface IByteHandler : IDisposable
{
	/// <summary>
	/// The remaining timeout (in milliseconds) for the next I/O read. Use <see cref="Constants.InfiniteTimeout"/> to represent no (or, infinite) timeout.
	/// </summary>
	int RemainingTimeout { get; set; }

	/// <summary>
	/// Reads data from this byte handler.
	/// </summary>
	/// <param name="buffer">The buffer to read into.</param>
	/// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when reading data.</param>
	/// <returns>A <see cref="ValueTask{Int32}"/> holding the number of bytes read. If reading failed, this will be zero.</returns>
	ValueTask<int> ReadBytesAsync(Memory<byte> buffer, IOBehavior ioBehavior);

	/// <summary>
	/// Writes data to this byte handler.
	/// </summary>
	/// <param name="data">The data to write.</param>
	/// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when writing.</param>
	ValueTask WriteBytesAsync(ReadOnlyMemory<byte> data, IOBehavior ioBehavior);
}


text:
Lodgefy 0.1 Beta

      Home
      Houses
      Configurations
      Logout


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <originChamber>House</originChamber>
    <latestAction>
      <links />
      <text>Referred to the House Committee on Ways and Means.</text>
      <actionDate>2017-01-04</actionDate>
    </latestAction>
    <laws />
    <recordedVotes />
    <committees>
      <billCommittees>
        <item>
          <chamber>House</chamber>
          <type>Standing</type>
          <activities>
            <item>
              <date>2017-01-04T15:02:45Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <subcommittees />
          <name>Ways and Means Committee</name>
          <systemCode>hswm00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <billType>HR</billType>
    <calendarNumbers />
    <notes />
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Income tax credits</name>
          </item>
          <item>
            <name>Sex and reproductive health</name>
          </item>
          <item>
            <name>Women's health</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Taxation</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <introducedDate>2017-01-04</introducedDate>
    <createDate>2017-01-05T04:47:33Z</createDate>
    <amendments />
    <cboCostEstimates />
    <policyArea>
      <name>Taxation</name>
    </policyArea>
    <congress>115</congress>
    <cosponsors>
      <item>
        <firstName>ZOE</firstName>
        <sponsorshipDate>2017-10-06</sponsorshipDate>
        <party>D</party>
        <middleName />
        <sponsorshipWithdrawnDate />
        <identifiers>
          <lisID>701</lisID>
          <gpoId>7821</gpoId>
          <bioguideId>L000397</bioguideId>
        </identifiers>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <bioguideId>L000397</bioguideId>
        <district>19</district>
        <lastName>LOFGREN</lastName>
        <fullName>Rep. Lofgren, Zoe [D-CA-19]</fullName>
        <state>CA</state>
      </item>
    </cosponsors>
    <committeeReports />
    <relatedBills />
    <title>Family Act of 2017</title>
    <actions>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
      <item>
        <actionCode>H11100</actionCode>
        <links />
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <actionDate>2017-01-04</actionDate>
        <committee>
          <name>Ways and Means Committee</name>
          <systemCode>hswm00</systemCode>
        </committee>
        <text>Referred to the House Committee on Ways and Means.</text>
      </item>
      <item>
        <actionCode>Intro-H</actionCode>
        <links />
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <actionDate>2017-01-04</actionDate>
        <committee />
        <text>Introduced in House</text>
      </item>
      <item>
        <actionCode>1000</actionCode>
        <links />
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <type>IntroReferral</type>
        <actionDate>2017-01-04</actionDate>
        <committee />
        <text>Introduced in House</text>
      </item>
      <actionTypeCounts>
        <introducedInHouse>1</introducedInHouse>
        <billReferrals>1</billReferrals>
        <introducedInTheHouse>1</introducedInTheHouse>
      </actionTypeCounts>
    </actions>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. LEWIS of Georgia:H.R. 273.Congress has the power to enact this legislation pursuantto the following:This bill is enacted pursuant to the power granted toCongress under Article I of the United States Constitutionand its subsequent amendments, and further clarified andinterpreted by the Supreme Court of the United States.[Page H97]
]]></constitutionalAuthorityStatementText>
    <summaries>
      <billSummaries>
        <item>
          <name>Introduced in House</name>
          <versionCode>00</versionCode>
          <text><![CDATA[
Family Act of 2017

This bill amends the Internal Revenue Code to allow a tax credit for 50% of an individual's qualified infertility treatment expenses, subject to specified limits based on dollar amounts and the taxpayer's adjusted gross income. Qualified infertility treatment expenses are amounts paid for the treatment of infertility via in vitro fertilization if such treatment is provided by a licensed physician, surgeon, or other medical practitioner and is administered with respect to a diagnosis of infertility by a physician licensed in the United States.
]]></text>
          <updateDate>2017-01-04T05:00:00Z</updateDate>
          <actionDesc>Introduced in House</actionDesc>
          <lastSummaryUpdateDate>2017-01-13T14:46:35Z</lastSummaryUpdateDate>
          <actionDate>2017-01-04</actionDate>
        </item>
      </billSummaries>
    </summaries>
    <version>1.0.0</version>
    <titles>
      <item>
        <parentTitleType />
        <chamberCode />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Family Act of 2017</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <chamberCode />
        <titleType>Short Titles as Introduced</titleType>
        <title>Family Act of 2017</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <title>To amend the Internal Revenue Code of 1986 to provide an income tax credit for the costs of certain infertility treatments.</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <chamberCode />
        <titleType>Display Title</titleType>
        <title>Family Act of 2017</title>
        <chamberName />
      </item>
    </titles>
    <updateDate>2017-10-07T07:15:24Z</updateDate>
    <sponsors>
      <item>
        <middleName />
        <firstName>JOHN</firstName>
        <fullName>Rep. Lewis, John [D-GA-5]</fullName>
        <bioguideId>L000287</bioguideId>
        <lastName>LEWIS</lastName>
        <party>D</party>
        <identifiers>
          <gpoId>7902</gpoId>
          <lisID>688</lisID>
          <bioguideId>L000287</bioguideId>
        </identifiers>
        <state>GA</state>
        <district>5</district>
        <byRequestType />
      </item>
    </sponsors>
    <billNumber>273</billNumber>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
package org.fraunhofer.cese.madcap.authentication;

/**
 * Interface that provides callback support for when the user accepts or declines the EULA.
 * <p>
 * Created by llayman on 4/6/2017.
 */
interface EULAListener {

    /**
     * The EULA pop-up shows Accept or Cancel. This method is called after the user presses the Accept button.
     */
    void onAccept();

    /**
     * The EULA pop-up shows Accept or Cancel. This method is called after the user presses the Cancel button.
     */
    void onCancel();

}


text: I don't have a favourite restaurant.


text:
package esiv1

/*
200 ok object */
type GetCorporationCorporationIdMiningObservers200Ok struct {
	/*
	 last_updated string */
	LastUpdated string `json:"last_updated,omitempty"`
	/*
	 The entity that was observing the asteroid field when it was mined.  */
	ObserverId int64 `json:"observer_id,omitempty"`
	/*
	 The category of the observing entity */
	ObserverType string `json:"observer_type,omitempty"`
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Microsoft.HDInsight
{
    using Microsoft.Azure.Management.HDInsight.Models;
    using Microsoft.Rest.Azure;
    using Models;
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ClustersOperations operations.
    /// </summary>
    public partial interface IClustersOperations
    {
        /// <summary>
        /// Creates a new HDInsight cluster with the specified parameters.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='parameters'>
        /// The cluster create request parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<Cluster>> CreateWithHttpMessagesAsync(string resourceGroupName, string clusterName, ClusterCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Resizes the specified HDInsight cluster to the specified size.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='targetInstanceCount'>
        /// The size to which to resize the cluster.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> ResizeAsync(string resourceGroupName, string clusterName, int targetInstanceCount, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Executes script actions on the specified HDInsight cluster.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='scriptActions'>
        /// The script actions to execute.
        /// </param>
        /// <param name="persistOnSuccess">
        /// Whether or not to persist the script action on success.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> ExecuteScriptActionsAsync(string resourceGroupName, string clusterName, IList<RuntimeScriptAction> scriptActions,
            bool persistOnSuccess, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Begins creating a new HDInsight cluster with the specified parameters.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='parameters'>
        /// The cluster create request parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<Cluster>> BeginCreatingAsync(string resourceGroupName, string clusterName, ClusterCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Begins resizing the specified HDInsight cluster to the specified size.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='targetInstanceCount'>
        /// The size to which to resize the cluster.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> BeginResizingAsync(string resourceGroupName, string clusterName, int targetInstanceCount, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Begins executing script actions on the specified HDInsight cluster.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the cluster.
        /// </param>
        /// <param name='scriptActions'>
        /// The script actions to execute.
        /// </param>
        /// <param name="persistOnSuccess">
        /// Whether or not to persist the script action on success.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> BeginExecuteScriptActionsAsync(string resourceGroupName, string clusterName, IList<RuntimeScriptAction> scriptActions,
            bool persistOnSuccess, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
#include <zephyr/kernel.h>
#include <zephyr/init.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/devicetree.h>
#include <zephyr/logging/log.h>
#include <hal/nrf_gpio.h>

LOG_MODULE_REGISTER(board_control, CONFIG_BOARD_NRF9160DK_LOG_LEVEL);

#define GET_CTLR(name, prop, idx) \
	DT_GPIO_CTLR_BY_IDX(DT_NODELABEL(name), prop, idx)
#define GET_PIN(name, prop, idx) \
	DT_GPIO_PIN_BY_IDX(DT_NODELABEL(name), prop, idx)
#define GET_PORT(name, prop, idx) \
	DT_PROP_BY_PHANDLE_IDX(DT_NODELABEL(name), prop, idx, port)
#define GET_FLAGS(name, prop, idx) \
	DT_GPIO_FLAGS_BY_IDX(DT_NODELABEL(name), prop, idx)
#define GET_DEV(name, prop, idx) DEVICE_DT_GET(GET_CTLR(name, prop, idx))

/* If the GPIO pin selected to be the reset line is actually the pin that
 * exposes the nRESET function (P0.18 in nRF52840), there is no need to
 * provide any additional GPIO configuration for it.
 */
#define RESET_INPUT_IS_PINRESET (IS_ENABLED(CONFIG_GPIO_AS_PINRESET) && \
				 GET_PORT(reset_input, gpios, 0) == 0 && \
				 GET_PIN(reset_input, gpios, 0) == 18)
#define USE_RESET_GPIO \
	(DT_NODE_HAS_STATUS(DT_NODELABEL(reset_input), okay) && \
	 !RESET_INPUT_IS_PINRESET)

struct switch_cfg {
	const struct device *gpio;
	gpio_pin_t pin;
	gpio_dt_flags_t flags;
	bool on;
#if IS_ENABLED(CONFIG_LOG)
	uint8_t port;
	bool info;
	const char *name;
#endif
};

#define ROUTING_ENABLED(_name) DT_NODE_HAS_STATUS(DT_NODELABEL(_name), okay)
#define SWITCH_CFG(_name, _idx)					\
{								\
	.gpio  = GET_DEV(_name, control_gpios, _idx),		\
	.pin   = GET_PIN(_name, control_gpios, _idx),		\
	.flags = GET_FLAGS(_name, control_gpios, _idx),		\
	.on    = ROUTING_ENABLED(_name),			\
	COND_CODE_1(CONFIG_LOG,					\
	(							\
		.port = GET_PORT(_name, control_gpios, _idx),	\
		.info = (_idx == 0),				\
		.name = #_name,					\
	), ())							\
}
#define HAS_TWO_PINS(_name) \
	DT_PHA_HAS_CELL_AT_IDX(DT_NODELABEL(_name), control_gpios, 1, pin)

#define ROUTING_SWITCH(_name)					\
	COND_CODE_1(DT_NODE_EXISTS(DT_NODELABEL(_name)),	\
	(							\
		COND_CODE_1(HAS_TWO_PINS(_name),		\
		(						\
			SWITCH_CFG(_name, 1),			\
		), ())						\
		SWITCH_CFG(_name, 0),				\
	), ())

static const struct switch_cfg routing_switches[] = {
	ROUTING_SWITCH(vcom0_pins_routing)
	ROUTING_SWITCH(vcom2_pins_routing)
	ROUTING_SWITCH(led1_pin_routing)
	ROUTING_SWITCH(led2_pin_routing)
	ROUTING_SWITCH(led3_pin_routing)
	ROUTING_SWITCH(led4_pin_routing)
	ROUTING_SWITCH(switch1_pin_routing)
	ROUTING_SWITCH(switch2_pin_routing)
	ROUTING_SWITCH(button1_pin_routing)
	ROUTING_SWITCH(button2_pin_routing)
	ROUTING_SWITCH(nrf_interface_pins_0_2_routing)
	ROUTING_SWITCH(nrf_interface_pins_3_5_routing)
	ROUTING_SWITCH(nrf_interface_pins_6_8_routing)
	ROUTING_SWITCH(nrf_interface_pin_9_routing)
	ROUTING_SWITCH(io_expander_pins_routing)
	ROUTING_SWITCH(external_flash_pins_routing)
};

#if USE_RESET_GPIO
static void chip_reset(const struct device *gpio,
		       struct gpio_callback *cb, uint32_t pins)
{
	const uint32_t stamp = k_cycle_get_32();

	printk("GPIO reset line asserted, device reset.\n");
	printk("Bye @ cycle32 %u\n", stamp);

	NVIC_SystemReset();
}

static void reset_pin_wait_inactive(const struct device *gpio, uint32_t pin)
{
	int val;

	/* Wait until the pin becomes inactive. */
	do {
		val = gpio_pin_get(gpio, pin);
	} while (val > 0);
}

static int reset_pin_configure(void)
{
	int rc;
	static struct gpio_callback gpio_ctx;

	const struct device *gpio = GET_DEV(reset_input, gpios, 0);
	gpio_pin_t pin = GET_PIN(reset_input, gpios, 0);
	gpio_dt_flags_t flags = GET_FLAGS(reset_input, gpios, 0);

	if (!device_is_ready(gpio)) {
		LOG_ERR("%s is not ready", gpio->name);
		return -ENODEV;
	}

	rc = gpio_pin_configure(gpio, pin, flags | GPIO_INPUT);
	if (rc) {
		LOG_ERR("Error %d while configuring pin P%d.%02d",
			rc, GET_PORT(reset_input, gpios, 0), pin);
		return rc;
	}

	gpio_init_callback(&gpio_ctx, chip_reset, BIT(pin));

	rc = gpio_add_callback(gpio, &gpio_ctx);
	if (rc) {
		return rc;
	}

	rc = gpio_pin_interrupt_configure(gpio, pin, GPIO_INT_EDGE_TO_ACTIVE);
	if (rc) {
		return rc;
	}

	LOG_INF("GPIO reset line enabled on pin P%d.%02d, holding...",
		GET_PORT(reset_input, gpios, 0), pin);

	/* Wait until the pin becomes inactive before continuing.
	 * This lets the other side ensure that they are ready.
	 */
	reset_pin_wait_inactive(gpio, pin);

	return 0;
}
#endif /* USE_RESET_GPIO */

static int init(const struct device *dev)
{
	int rc;

	for (int i = 0; i < ARRAY_SIZE(routing_switches); ++i) {
		const struct switch_cfg *cfg = &routing_switches[i];
		gpio_flags_t flags = cfg->flags;

		if (!device_is_ready(cfg->gpio)) {
			LOG_ERR("%s is not ready", cfg->gpio->name);
			return -ENODEV;
		}

		flags |= (cfg->on ? GPIO_OUTPUT_ACTIVE
				  : GPIO_OUTPUT_INACTIVE);
		rc = gpio_pin_configure(cfg->gpio, cfg->pin, flags);
#if IS_ENABLED(CONFIG_LOG)
		LOG_DBG("Configuring P%d.%02d with flags: 0x%08x",
			cfg->port, cfg->pin, flags);
		if (rc) {
			LOG_ERR("Error %d while configuring pin P%d.%02d (%s)",
				rc, cfg->port, cfg->pin, cfg->name);
		} else if (cfg->info) {
			LOG_INF("%s is %s",
				cfg->name, cfg->on ? "ENABLED" : "disabled");
		}
#endif
		if (rc) {
			return rc;
		}
	}

	/* Make sure to configure the switches before initializing
	 * the GPIO reset pin, so that we are connected to
	 * the nRF9160 before enabling our interrupt.
	 */

#if USE_RESET_GPIO
	rc = reset_pin_configure();
	if (rc) {
		LOG_ERR("Unable to configure reset pin, err %d", rc);
		return -EIO;
	}
#endif

	LOG_INF("Board configured.");

	return 0;
}

SYS_INIT(init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);

#define EXT_MEM_CTRL DT_NODELABEL(external_flash_pins_routing)
#if DT_NODE_EXISTS(EXT_MEM_CTRL)

static int early_init(const struct device *dev)
{
	/* As soon as possible after the system starts up, enable the analog
	 * switch that routes signals to the external flash. Otherwise, the
	 * HOLD line in the flash chip may not be properly pulled up internally
	 * and consequently the chip will not respond to any command.
	 * Later on, during the normal initialization performed above, this
	 * analog switch will get configured according to what is selected
	 * in devicetree.
	 */
	uint32_t psel = NRF_DT_GPIOS_TO_PSEL(EXT_MEM_CTRL, control_gpios);
	gpio_dt_flags_t flags = DT_GPIO_FLAGS(EXT_MEM_CTRL, control_gpios);

	if (flags & GPIO_ACTIVE_LOW) {
		nrf_gpio_pin_clear(psel);
	} else {
		nrf_gpio_pin_set(psel);
	}
	nrf_gpio_cfg_output(psel);

	return 0;
}

SYS_INIT(early_init, PRE_KERNEL_1, 0);
#endif


text:
namespace Memolap.Core
{
    using System;
    using System.Collections.Generic;

    public interface IQuery<T> : ITupleStream<T>
    {
        IQuery<T> Where(IDictionary<string, object> values);

        IQuery<T> Skip(int n);

        IQuery<T> Take(int n);
    }
}


text:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author Oleg Cherednik
 * @since 22.09.2017
 */
public class Main {
    static Iterator func(ArrayList mylist) {
        Iterator it = mylist.iterator();
        while (it.hasNext()) {
            Object element = it.next();
            if (element instanceof String)
                break;
        }
        return it;
    }

    @SuppressWarnings({ "unchecked" })
    public static void main(String... args) {
        ArrayList mylist = new ArrayList();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            mylist.add(sc.nextInt());
        }

        mylist.add("###");
        for (int i = 0; i < m; i++) {
            mylist.add(sc.next());
        }

        Iterator it = func(mylist);
        while (it.hasNext()) {
            Object element = it.next();
            System.out.println((String)element);
        }
    }

}


text:
package co.omise.models;

import co.omise.Endpoint;
import co.omise.requests.RequestBuilder;
import co.omise.requests.ResponseType;
import com.fasterxml.jackson.annotation.JsonProperty;
import okhttp3.HttpUrl;
import okhttp3.RequestBody;

import java.io.IOException;

/**
 * Forex object
 *
 * @see Forex API
 */
public class Forex extends Model {
    private String base;
    private String location;
    private String quote;
    private Double rate;

    public String getBase() {
        return this.base;
    }

    public void setBase(String base) {
        this.base = base;
    }

    public String getLocation() {
        return this.location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getQuote() {
        return this.quote;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    public Double getRate() {
        return this.rate;
    }

    public void setRate(Double rate) {
        this.rate = rate;
    }

    public static class GetRequestBuilder extends RequestBuilder<Forex> {
        private String currency;
        public GetRequestBuilder(String currency) {
            this.currency = currency;
        }

        @Override
        protected String method() {
            return GET;
        }

        @Override
        protected HttpUrl path() {
            return buildUrl(Endpoint.API, "forex", currency);
        }

        @Override
        protected ResponseType<Forex> type() {
            return new ResponseType<>(Forex.class);
        }
    }
}


text:
//
//  HYWebViewCommand.h
//  HYWebViewControlller
//
//  Created by Mert Dümenci on 10/07/13.
//  Copyright (c) 2013 Mert Dumenci. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "HYWebViewCommandProtocol.h"
#import "HYWebViewController.h"

/**
    `HYWebViewCommand` is the base class for creating new command handlers. Subclass this when you're creating a new command handler.
 */

@interface HYWebViewCommand : NSObject <HYWebViewCommand>
@property (nonatomic, assign) HYWebViewController *webViewController;
@end


text:
package org.camunda.bpm.engine.rest.application;

import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.authorization.MissingAuthorization;
import org.camunda.bpm.engine.rest.exception.RestException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response.Status;
import java.util.ArrayList;
import java.util.List;

/**
 * Does not declare produced media types.
 * @author Thorben Lindhauer
 *
 */
@Path("/unannotated")
public class UnannotatedResource {

  @GET
  @Path("/exception")
  public String throwAnException() throws Exception {
    throw new Exception("expected exception");
  }

  @GET
  @Path("/processEngineException")
  public String throwProcessEngineException() throws Exception {
    throw new ProcessEngineException("expected exception");
  }

  @GET
  @Path("/restException")
  public String throwRestException() throws Exception {
    throw new RestException(Status.BAD_REQUEST, "expected exception");
  }

  @GET
  @Path("/authorizationException")
  public String throwAuthorizationException() throws Exception {
    throw new AuthorizationException("someUser", "somePermission", "someResourceName", "someResourceId");
  }

  @GET
  @Path("/stackOverflowError")
  public String throwStackOverflowError() throws Throwable {
    throw new StackOverflowError("Stack overflow");
  }

  @GET
  @Path("/authorizationExceptionMultiple")
  public String throwAuthorizationExceptionMultiple() throws Exception {
    List<MissingAuthorization> missingAuthorizations = new ArrayList<>();

    missingAuthorizations.add(
        new MissingAuthorization("somePermission1", "someResourceName1", "someResourceId1"));
    missingAuthorizations.add(
        new MissingAuthorization("somePermission2", "someResourceName2", "someResourceId2"));
    throw new AuthorizationException("someUser", missingAuthorizations);
  }
}


text:
layout: post
title:  "Research Update"
date:   2015-02-26
# everything is a post.
# project
# courswork [classname]
# post [blog, nerd]
categories: research update
image:
  feature:
  teaser: python_code_teaser.png
tags: [data mining, machine learning, research update, blog, openscience]
published: true
excerpt: "Weekly update for the SSL lab. Progress?"
description: "something"
comments: true
---

Content Warning:
Boring Research Update

## Project ##
### Exascale Monitoring and Prediction
For those of you not aware of the project, we are using
data mining to increase knowledge about HPC resource monitoring systems with a
goal of increasing efficiency of monitoring operations and predicting failures.

Dorian, Mueen, and I met with LANL folks this week to get our project off of
the ground. They seem rather motivated to do this and it feels like we'll have
some great stuff come of this (eventually).

## Status ##
My LANL contact is working on find out how to handle administrativa -
accounts, access, security issues, etc. My main request from him was for a
sample of any of the data we'll be working with so we can inform our decisions
on data engineering early on. I won't be able to move much on this until this
stuff is resolved.

In previous weeks, I've acquainted myself with the current tools in use there,
at least at a high level - Splunk, Zenoss, RabbitMQ - by reviewing some of
LANL's open-source code and various posters /talks they have given on their
use. I also got to know Alireza's previous work and read papers related to our
project (I might suggest one to you, Dorian, as a reading group paper).

## Upcoming ##
I am following up with -contact person-, as he and I planned, on Monday. I will deliver
him a summary of our discussions as I took it as well as early justification
for using the suite of tools i proposed. -contact person-'s future information will
determine my work for the next week, which could go in two directions:

- He sends a sample of data and/or gives us some sort of remote access

    * I'll examine data and asses what the current format allows us to do

- He says we can't have anything (yet)

    * I'll sigh heavily.


text:
({

	doInit : function(cmp, evt, helper){
	  var inputCmp = cmp.find("myInputNumber");

	  if (inputCmp) {
        var value = inputCmp.get('v.value');
        inputCmp.set('v.errors',[{message : "This is an invalid value: " + value}]);
	  }
	}
})