text:
'use strict';

/**
 * @typedef {object} DebugAgentConfig
 */

module.exports = {
  // FIXME(ofrobots): presently this is dependent what cwd() is at the time this
  // file is first required. We should make the default config static.
  /**
   * @property {?string}
   * @memberof DebugAgentConfig
   * @default
   */
  workingDirectory: process.cwd(),

  /**
   * @property {?string} A user specified way of identifying the service
   * that the debug agent is monitoring.
   * @memberof DebugAgentConfig
   * @default
   */
  description: null,

  /**
   * @property {boolean} Whether or not it is permitted to evaluate expressions.
   * Locals and arguments are not displayed and watch expressions and conditions
   * are dissallowed when this is `false`.
   * @memberof DebugAgentConfig
   * @default
   */
  allowExpressions: false,

  // FIXME(ofrobots): today we prioritize GAE_MODULE_NAME/GAE_MODULE_VERSION
  // over the user specified config. We should reverse that.
  /**
   * @property {object} Identifies the context of the running service -
   * [ServiceContext](https://cloud.google.com/error-reporting/reference/rest/v1beta1/ServiceContext?authuser=2).
   * This information is utilized in the UI to identify all the running
   * instances of your service. This is discovered automatically when your
   * application is running on Google Cloud Platform. You may optionally choose
   * to provide this information yourself to identify your service differently
   * from the default mechanism.
   * @memberof DebugAgentConfig
   * @default
   */
  serviceContext: {
    /**
     * @property {?string} the service name
     * @default
     */
    service: null,

    /**
     * @property {?string} the service version
     * @default
     */
    version: null,

    /**
     * @property {?string} a unique deployment identifier. This is used
     * internally only.
     * @private
     */
    minorVersion_: null
  },

  /**
   * @property {?string}   The path within your repository to the directory
   * containing the package.json for your deployed application. This should be
   * provided if your deployed application appears as a subdirectory of your
   * repository. Usually this is unnecessary, but may be useful in cases where
   * the debug agent is unable to resolve breakpoint locations unambiguously.
   * @memberof DebugAgentConfig
   * @default
   */
  appPathRelativeToRepository: null,

  /**
   * @property {number} agent log level 0-disabled, 1-error, 2-warn, 3-info,
   * 4-debug
   * @memberof DebugAgentConfig
   * @default
   */
  logLevel: 1,

  /**
   * @property {number} How frequently should the list of breakpoints be
   * refreshed from the cloud debug server.
   * @memberof DebugAgentConfig
   * @default
   */
  breakpointUpdateIntervalSec: 10,

  /**
   * @property {number} breakpoints and logpoints older than this number of
   * seconds will be expired on the server.
   * @memberof DebugAgentConfig
   * @default
   */
  breakpointExpirationSec: 60 * 60 * 24,  // 24 hours

  /**
   * @property {object} configuration options on what is captured on a
   * snapshot.
   * @memberof DebugAgentConfig
   */
  capture: {
    /**
     * @property {boolean} Whether to include details about stack frames
     * belonging to node-core.
     * @default
     */
    includeNodeModules: false,

    /**
     * @property {number} Maximum number of stack frames to capture data for.
     * The limit is aimed to reduce overall capture time.
     * @default
     */
    maxFrames: 20,

    /**
     * @property {number} We collect locals and arguments on a few top frames.
     * For the rest only collect the source location
     * @default
     */
    maxExpandFrames: 5,

    /**
     * @property {number} To reduce the overall capture time, limit the number
     * of properties gathered on large objects. A value of 0 disables the limit.
     * @default
     */
    maxProperties: 10,

    /**
     * @property {number} Total 'size' of data to gather. This is NOT the
     * number of bytes of data that are sent over the wire, but instead a very
     * very coarse approximation based on the length of names and values of the
     * properties. This should be somewhat proportional to the amount of
     * processing needed to capture the data and subsequently the network
     * traffic. A value of 0 disables the limit.
     * @default
     */
    maxDataSize: 20000,

    /**
     * @property {number} To limit the size of the buffer, we truncate long
     * strings. A value of 0 disables truncation.
     * @default
     */
    maxStringLength: 100
  },

  /**
   * @property {object} options affecting log points.
   * @memberof DebugAgentConfig
   */
  log: {
    /**
     * @property {number} The maximum number of logs to record per second per
     * logpoint.
     * @memberof DebugAgentConfig
     * @default
     */
    maxLogsPerSecond: 50,

    /**
     * @property {number} Number of seconds to wait after the
     * `maxLogsPerSecond` rate is hit before logging resumes per logpoint.
     * @default
     */
    logDelaySeconds: 1
  },

  /**
   * @property {object} These configuration options are for internal
   * experimentation only.
   * @memberof DebugAgentConfig
   * @private
   */
  internal: {
    registerDelayOnFetcherErrorSec: 300,  // 5 minutes.
    maxRegistrationRetryDelay: 40
  },

  /**
   * @property {boolean} Used by tests to force loading of a new agent if one
   * exists already
   * @memberof DebugAgentConfig
   * @private
   */
  forceNewAgent_: false,

  /**
   * @property {boolean} Uses by tests to cause the start() function to return
   * the debuglet.
   * @memberof DebugAgentConfig
   * @private
   */
  testMode_: false
};


text:
package org.apache.hadoop.fs.slive;

import org.apache.hadoop.fs.slive.Constants.Distribution;

/**
 * This class holds the data representing what an operations distribution and
 * its percentage is (between 0 and 1) and provides operations to access those
 * types and parse and unparse from and into strings
 */
class OperationData {

  private static final String SEP = ",";

  private Distribution distribution;
  private Double percent;

  OperationData(Distribution d, Double p) {
    this.distribution = d;
    this.percent = p;
  }

  /**
   * Expects a comma separated list (where the first element is the ratio
   * (between 0 and 100)) and the second element is the distribution (if
   * non-existent then uniform will be selected). If an empty list is passed in
   * then this element will just set the distribution (to uniform) and leave the
   * percent as null.
   */
  OperationData(String data) {
    String pieces[] = Helper.getTrimmedStrings(data);
    distribution = Distribution.UNIFORM;
    percent = null;
    if (pieces.length == 1) {
      percent = (Double.parseDouble(pieces[0]) / 100.0d);
    } else if (pieces.length >= 2) {
      percent = (Double.parseDouble(pieces[0]) / 100.0d);
      distribution = Distribution.valueOf(pieces[1].toUpperCase());
    }
  }

  /**
   * Gets the distribution this operation represents
   *
   * @return Distribution
   */
  Distribution getDistribution() {
    return distribution;
  }

  /**
   * Gets the 0 - 1 percent that this operations run ratio should be
   *
   * @return Double (or null if not given)
   */
  Double getPercent() {
    return percent;
  }

  /**
   * Returns a string list representation of this object (if the percent is
   * null) then NaN will be output instead. Format is percent,distribution.
   */
  public String toString() {
    StringBuilder str = new StringBuilder();
    if (getPercent() != null) {
      str.append(getPercent() * 100.0d);
    } else {
      str.append(Double.NaN);
    }
    str.append(SEP);
    str.append(getDistribution().lowerName());
    return str.toString();
  }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
// TODO: deprecated methods by modules! check dependencies/alternatives for compatibility with jQuery 3.3.*
//= require /node_modules/air-datepicker/dist/js/datepicker.min.js
//= require /node_modules/air-datepicker/dist/js/i18n/datepicker.en.js
//= require /node_modules/moment/min/moment.min.js
//= require_self

var OpenSpeedMonitor = OpenSpeedMonitor || {};

OpenSpeedMonitor.timeRangePicker = function (timeRangePickerElement) {
    var containerElement = $(timeRangePickerElement);
    var pickerFrom = null;
    var pickerTo = null;
    var userInputFromElement = containerElement.find(".timerange-userinput-from");
    var userInputToElement = containerElement.find(".timerange-userinput-to");
    var valueFromElement = containerElement.find(".timerange-value-from");
    var valueToElement = containerElement.find(".timerange-value-to");
    var dateTo = null;
    var dateFrom = null;
    var datePicker = $.fn.datepicker.Constructor;
    var eventsEnabled = false;
    var defaultDateFormat = "dd.mm.yyyy";
    var wasManualChange = false;
    var datePickerOptions = {
        language: "en",
        timepicker: true,
        timeFormat: "hh:ii",
        minutesStep: 1,
        offset: 5,
        autoClose: false,
        toggleSelected: false
    };

    var init = function() {
        initRangeFrom();
        initRangeTo();

        registerEvents();
        eventsEnabled = true;
    };

    var initRangeFrom = function () {
        dateFrom = convertToDateOrDefault(valueFromElement.val(), new Date());
        pickerFrom = userInputFromElement.datepicker($.extend({}, datePickerOptions, {
            startDate: dateFrom,
            maxDate: new Date(),
            dateFormat: userInputFromElement.data("date-format") || defaultDateFormat,
            onSelect: function (formatted, date) {
                dateFrom = date;
                valueFromElement.val(date.toISOString());
                pickerTo.update("minDate", date);
                if (!pickerFrom.timepickerIsActive && !wasManualChange) {
                    pickerFrom.hide();
                    userInputToElement.trigger('focus');
                }
                wasManualChange = false;
                triggerRangeChanged();
            }
        })).data("datepicker");
        pickerFrom.$datepicker.on('mouseenter', '.datepicker--cell', function () {
            pickerFrom.views[pickerFrom.currentView]._update();
        });
        pickerFrom.update("onRenderCell", pickerFromOnRenderCell);
        userInputFromElement.on('click', function () {
            pickerTo.hide();
        });
    };

    var initRangeTo = function () {
        dateTo = convertToDateOrDefault(valueToElement.val(), new Date());
        var maxDate = new Date();
        maxDate.setHours(23, 59, 59, 999);
        pickerTo = userInputToElement.datepicker($.extend({}, datePickerOptions, {
            startDate: dateTo,
            maxDate: maxDate,
            minDate: dateFrom,
            dateFormat: userInputFromElement.data("date-format") || defaultDateFormat,
            onSelect: function (formatted, date) {
                dateTo = date;
                valueToElement.val(date.toISOString());
                pickerFrom.update("maxDate", date);
                if (!pickerTo.timepickerIsActive && !wasManualChange) {
                    pickerTo.hide();
                }
                wasManualChange = false;
                triggerRangeChanged();
            }
        })).data("datepicker");
        pickerTo.$datepicker.on('mouseenter', '.datepicker--cell', function () {
            pickerTo.views[pickerTo.currentView]._update();
        });
        pickerTo.update("onRenderCell", pickerToOnRenderCell);
        userInputToElement.on('click', function () {
            pickerFrom.hide();
        });
    };

    var registerEvents = function () {
        userInputFromElement.on("change keyup", function () { onManualChange(pickerFrom, $(this).val()); });
        userInputFromElement.on("blur", function () { onBlur(pickerFrom, dateFrom)});
        userInputToElement.on("change keyup", function () { onManualChange(pickerTo, $(this).val()); });
        userInputToElement.on("blur", function () { onBlur(pickerTo, dateTo)});
    };

    var onBlur = function (pickerInstance, resetDate) {
        if (pickerInstance.$el.hasClass("has-error")) {
            wasManualChange = true;
            pickerInstance.selectDate(resetDate);
            pickerInstance.$el.removeClass("has-error");
        }
    };

    var onManualChange = function (pickerInstance, value) {
        var selected = moment(value, getMomentDateTimeFormat(pickerInstance), true);
        var valid = !isNaN(selected.valueOf());
        pickerInstance.$el.toggleClass("has-error", !valid);
        if (valid) {
            wasManualChange = true;
            pickerInstance.selectDate(new Date(selected.valueOf()));
        }
    };

    var getMomentDateTimeFormat = function (pickerInstance) {
        var format = pickerInstance.opts.dateFormat + pickerInstance.opts.dateTimeSeparator + pickerInstance.opts.timeFormat;
        return format.replace(/y/g, "Y").replace(/m/g, "M").replace(/d/g, "D")
                     .replace(/h/g, "H").replace(/i/g, "m").replace(/@/g, "S");
    };

    var convertToDateOrDefault = function (isoDate, defaultValue) {
        if (Object.prototype.toString.call(isoDate) === '[object Date]' && !isNaN(isoDate.valueOf())) {
            return isoDate;
        }
        if (!isoDate) {
            return defaultValue;
        }
        var parsedDate = new Date(isoDate);
        return !isNaN(parsedDate.valueOf()) ? parsedDate : defaultValue;
    };

    var cellRenderCommonClassNames = function (date, focused) {
        var classes = datePicker.isSame(dateFrom, date) ? ' -range-from- -selected-' : '';
        classes += datePicker.isSame(dateTo, date) ? ' -range-to- -selected-' : '';
        classes += (!focused && datePicker.bigger(dateFrom, date) && datePicker.less(dateTo, date)) ? ' -in-range-' : '';
        return classes;
    };

    var pickerToOnRenderCell = function (date) {
        var focused = pickerTo.focused;
        var classes = cellRenderCommonClassNames(date, focused);

        if (focused) {
            var isInRange = datePicker.bigger(dateFrom, date) && datePicker.less(focused, date) && datePicker.less(pickerTo.maxDate, date);
            var isRangeEnd = datePicker.bigger(dateFrom, date) && datePicker.isSame(focused, date);
            classes += isInRange ? " -in-range-" : "";
            classes += isRangeEnd ? " -range-to-" : "";
        }

        return {
            html: '',
            classes: classes,
            disabled: false
        };
    };

    var pickerFromOnRenderCell = function (date) {
        var focused = pickerFrom.focused;
        var classes = cellRenderCommonClassNames(date, focused);

        if (focused) {
            var isInRange = datePicker.less(dateTo, date) && datePicker.bigger(focused, date) && datePicker.bigger(pickerFrom.minDate, date);
            var isRangeStart = datePicker.less(dateTo, date) && datePicker.isSame(focused, date);
            classes += isInRange ? " -in-range-" : "";
            classes += isRangeStart ? " -range-from-" : "";
        }

        return {
            html: '',
            classes: classes,
            disabled: false
        };
    };

    var triggerRangeChanged = function () {
        if (eventsEnabled) {
            containerElement.trigger("rangeChanged", getRange());
        }
    };

    var getStart = function () {
        return new Date(dateFrom.valueOf());
    };

    var getEnd = function () {
        return new Date(dateTo.valueOf());
    };

    var getRange = function () {
        return [getStart(), getEnd()];
    };

    var setRange = function (from, to) {
        var eventsWereEnabled = enableEvents(false);
        pickerFrom.selectDate(convertToDateOrDefault(from, dateFrom));
        pickerTo.selectDate(convertToDateOrDefault(to, dateTo));
        enableEvents(eventsWereEnabled);
    };

    var enableEvents = function(enable) {
        var wereEnabled = eventsEnabled;
        eventsEnabled = enable;
        return wereEnabled;
    };

    init();
    return {
        getStart: getStart,
        getEnd: getEnd,
        getRange: getRange,
        setRange: setRange
    };
};


text:
This is an attempt to standardize on namespacing API routes, for the consistency sake. The rules set here can be changed if there is a god reason for it, otherwise please follow these rules.

# Top level routes #

Top level routes limited to following ones, no new routes will be added.

* /_config
* /_objects
* /_status
* /_api
* /_runtime
* /

## Implemented

"PUT":

- /_status
- /_status/:host_name
- /_status/:host_name/_services
- /_status/:host_name/_services/:service_description
- /_status/:host_name/_services/:service_description/_return_code/:return_code/_plugin_output/:plugin_output

Deprecated to be removed:
- /_host_status/:host_name

## Future additions

Host and service properties (notifications, checks enabled/disabled) are nested under the host and service endpoints correspondingly.

### Host

- PUT /_status/:host_name/_active_checks
- PUT /_status/:host_name/_passive_checks
- PUT /_status/:host_name/_notifications

### Service

- PUT /_status/:host_name/_services/:service_description/_notifications/

    - Params
          - notifications_enabled
          - notification_options

- PUT /_status/:host_name/_services/:service_description/_active_checks
- PUT /_status/:host_name/_services/:service_description/_passive_checks
- PUT /_status/:host_name/_services/:service_description/_flap_detection


text:
package ca.uhn.fhir.jpa.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

//@formatter:off
@Entity()
@Table(name = "HFJ_FORCED_ID", uniqueConstraints = {
		@UniqueConstraint(name = "IDX_FORCEDID", columnNames = {"FORCED_ID"})
})
@NamedQueries(value = {
		@NamedQuery(name = "Q_GET_FORCED_ID", query = "SELECT f FROM ForcedId f WHERE myForcedId = :ID")
})
//@formatter:on
public class ForcedId {

	public static final int MAX_FORCED_ID_LENGTH = 100;

	@Column(name = "FORCED_ID", nullable = false, length = MAX_FORCED_ID_LENGTH, updatable = false)
	private String myForcedId;

	@GeneratedValue(strategy = GenerationType.AUTO)
	@Id
	@Column(name = "PID")
	private Long myId;

	@JoinColumn(name = "RESOURCE_PID", nullable = false, updatable = false)
	@OneToOne()
	private ResourceTable myResource;

	@Column(name = "RESOURCE_PID", nullable = false, updatable = false, insertable=false)
	private Long myResourcePid;

	public String getForcedId() {
		return myForcedId;
	}

	public ResourceTable getResource() {
		return myResource;
	}

	public Long getResourcePid() {
		if (myResourcePid==null) {
			return myResource.getId();
		}
		return myResourcePid;
	}

	public void setForcedId(String theForcedId) {
		myForcedId = theForcedId;
	}

	public void setResource(ResourceTable theResource) {
		myResource = theResource;
	}

	public void setResourcePid(Long theResourcePid) {
		myResourcePid = theResourcePid;
	}

	public void setResourcePid(ResourceTable theResourcePid) {
		myResource = theResourcePid;
	}

}


text:
import os
import urllib.request

pagina = open("index.html", "w", encoding="utf-8")
pagina.write("""<!DOCTYPE html>

    <meta charset="UTF-8"><title>Arquivos</title>
 """)

for raiz, diretorios, arquivos in os.walk("/home/laenderoliveira/Python/livro_nilo/"):
    pagina.write(f"
{raiz}
")
    pagina.write("
")
    for a in arquivos:
        caminho = os.path.join(raiz, a)
        tamanho = os.path.getsize(caminho)
        link = urllib.request.pathname2url(caminho)
        pagina.write(f"
{a} ({tamanho} bytes)
")
    pagina.write("
")
pagina.write("")
pagina.close()


text:
def runstrip(arg):
    # Function to strip a single file, called from split_and_strip_files below
    # A working 'file' (one which works on the target architecture)
    #
    # The elftype is a bit pattern (explained in split_and_strip_files) to tell
    # us what type of file we're processing...
    # 4 - executable
    # 8 - shared library
    # 16 - kernel module

    import commands, stat, subprocess

    (file, elftype, strip) = arg

    newmode = None
    if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
        origmode = os.stat(file)[stat.ST_MODE]
        newmode = origmode | stat.S_IWRITE | stat.S_IREAD
        os.chmod(file, newmode)

    extraflags = ""

    # kernel module
    if elftype & 16:
        extraflags = "--strip-debug --remove-section=.comment --remove-section=.note --preserve-dates"
    # .so and shared library
    elif ".so" in file and elftype & 8:
        extraflags = "--remove-section=.comment --remove-section=.note --strip-unneeded"
    # shared or executable:
    elif elftype & 8 or elftype & 4:
        extraflags = "--remove-section=.comment --remove-section=.note"

    stripcmd = "'%s' %s '%s'" % (strip, extraflags, file)
    bb.debug(1, "runstrip: %s" % stripcmd)

    ret = subprocess.call(stripcmd, shell=True)

    if newmode:
        os.chmod(file, origmode)

    if ret:
        bb.error("runstrip: '%s' strip command failed" % stripcmd)

    return

def file_translate(file):
    ft = file.replace("@", "@at@")
    ft = ft.replace(" ", "@space@")
    ft = ft.replace("\t", "@tab@")
    ft = ft.replace("[", "@openbrace@")
    ft = ft.replace("]", "@closebrace@")
    ft = ft.replace("_", "@underscore@")
    return ft

def filedeprunner(arg):
    import re, subprocess, shlex

    (pkg, pkgfiles, rpmdeps, pkgdest) = arg
    provides = {}
    requires = {}

    r = re.compile(r'[<>=]+ +[^ ]*')

    def process_deps(pipe, pkg, pkgdest, provides, requires):
        for line in pipe:
            f = line.split(" ", 1)[0].strip()
            line = line.split(" ", 1)[1].strip()

            if line.startswith("Requires:"):
                i = requires
            elif line.startswith("Provides:"):
                i = provides
            else:
                continue

            file = f.replace(pkgdest + "/" + pkg, "")
            file = file_translate(file)
            value = line.split(":", 1)[1].strip()
            value = r.sub(r'(\g<0>)', value)

            if value.startswith("rpmlib("):
                continue
            if value == "python":
                continue
            if file not in i:
                i[file] = []
            i[file].append(value)

        return provides, requires

    try:
        dep_popen = subprocess.Popen(shlex.split(rpmdeps) + pkgfiles, stdout=subprocess.PIPE)
        provides, requires = process_deps(dep_popen.stdout, pkg, pkgdest, provides, requires)
    except OSError as e:
        bb.error("rpmdeps: '%s' command failed, '%s'" % (shlex.split(rpmdeps) + pkgfiles, e))
        raise e

    return (pkg, provides, requires)


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum HistoryStatus {

        /**
         * Some health information is known and captured, but not complete - see notes for details.
         */
        PARTIAL,
        /**
         * All available related health information is captured as of the date (and possibly time) when the family member history was taken.
         */
        COMPLETED,
        /**
         * This instance should not have been part of this patient's medical record.
         */
        ENTEREDINERROR,
        /**
         * Health information for this individual is unavailable/unknown.
         */
        HEALTHUNKNOWN,
        /**
         * added to help the parsers
         */
        NULL;
        public static HistoryStatus fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("partial".equals(codeString))
          return PARTIAL;
        if ("completed".equals(codeString))
          return COMPLETED;
        if ("entered-in-error".equals(codeString))
          return ENTEREDINERROR;
        if ("health-unknown".equals(codeString))
          return HEALTHUNKNOWN;
        throw new FHIRException("Unknown HistoryStatus code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case PARTIAL: return "partial";
            case COMPLETED: return "completed";
            case ENTEREDINERROR: return "entered-in-error";
            case HEALTHUNKNOWN: return "health-unknown";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/history-status";
        }
        public String getDefinition() {
          switch (this) {
            case PARTIAL: return "Some health information is known and captured, but not complete - see notes for details.";
            case COMPLETED: return "All available related health information is captured as of the date (and possibly time) when the family member history was taken.";
            case ENTEREDINERROR: return "This instance should not have been part of this patient's medical record.";
            case HEALTHUNKNOWN: return "Health information for this individual is unavailable/unknown.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case PARTIAL: return "Partial";
            case COMPLETED: return "Completed";
            case ENTEREDINERROR: return "Entered in error";
            case HEALTHUNKNOWN: return "Health unknown";
            default: return "?";
          }
    }

}


text:
Compass.add_project_configuration('..\..\..\..\..\sass\config.rb')
cache_path = 'C:\wamp\www\electic\MyApp/build/.sass-cache'


text:
import os

import falcon
import magic

import model
from db import session
from endpoint.admin.diploma import get_diploma_path
from util.config import backend_url

class Diploma:
    def on_get(self, req, resp, user):
        diplomas = session.query(model.Diploma)\
            .filter(model.Diploma.user_id == user)

        req.context['result'] = {
            'diplomas': [{
                'year': diploma.year_id,
                'revoked': diploma.revoked,
                'url': f"{backend_url()}/diplomas/{user}/{diploma.year_id}/show"
            } for diploma in diplomas]
        }

class DiplomaDownload:
    def on_get(self, req, resp, user, year):
        user_id = user
        year_id = year

        diploma = session.query(model.Diploma)\
            .filter(model.Diploma.user_id == user_id, model.Diploma.year_id == year_id).first()

        if diploma is None:
            resp.status = falcon.HTTP_404
            req.context['result'] = {
                'errors': [{
                    'status': '404',
                    'title': 'Not found',
                    'detail': 'No diploma for this user & year combination found'
                }]
            }
            return

        path = get_diploma_path(year_id, user_id)
        resp.content_type = magic.Magic(mime=True).from_file(f"{path}")
        resp.stream_len = os.path.getsize(path)
        resp.stream = open(path, 'rb')


text:
<?php

class VideoGallery extends Page {
    private static $allowed_children = array('VideoPage');
}

class VideoGallery_Controller extends Page_Controller {
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd">
  <page name="OrderShipmentNew" area="Adminhtml" mca="admin/order_shipment/new" module="Magento_Shipping">
    <block name="shipItemsBlock" class="Magento\Shipping\Test\Block\Adminhtml\Create\Items" locator="#ship_items_container" strategy="css selector"/>
    <block name="formBlock" class="Magento\Shipping\Test\Block\Adminhtml\Form" locator="#edit_form" strategy="css selector"/>
  </page>
</config>


text:
package com.autonomy.aci.client.annotations.testobjects.controller;

public abstract class MonitorItem {

    protected String id;
    protected int count;
    protected long start;
    protected String end = "";
    protected String value;

    public int getCount() {
        return count;
    }

    public abstract void setCount(final int count);

    public String getEnd() {
        return end;
    }

    public abstract void setEnd(final String end);

    public String getId() {
        return id;
    }

    public abstract void setId(final String id);

    public long getStart() {
        return start;
    }

    public abstract void setStart(final long start);

    public String getValue() {
        return value;
    }

    public abstract void setValue(final String value);

}


text:
package com.ebay.hackathon.controllers

import com.ebay.hackathon.dao.NeedyDAO
import com.ebay.hackathon.endpoints.BaseController
import com.ebay.hackathon.entity.Needy
import org.bson.types.ObjectId

/**
 * Author sreejith on 09/11/14 6:41 AM.
 */
class NeedyController(signedInUser: String) extends BaseController(signedInUser) {

  def createNeedy(name: String,
                  address: String,
                  totalPeople: Int,
                  lat: Double,
                  lng: Double) = {
    respond("createNeedy") {
      val needy = new Needy()
      needy.name = name
      needy.address = address
      needy.totalPeople = totalPeople
      needy.loc = List(lat, lng)
      NeedyDAO.createNeedy(needy)
    }
  }

  def getNeedy = {
    respond("getNeedy") {
      NeedyDAO.getNeedy
    }
  }

  def getNeedyBasedOnAssignment(volId: String) = {
    respond("getNeedyBasedOnAssignment") {
      NeedyDAO.getNeedyBasedOnAssignment(volId)
    }
  }

  def assignVolunteerToNeedy(volId: String, id: String) = {
    respond("assignVolunteerToNeedy") {
      NeedyDAO.assignVolunteerToNeedy(volId, new ObjectId(id))
    }
  }

}


text:
require 'gocdtools/version'
require 'rexml/document'
require 'openssl'
require 'base64'
require 'fileutils'

module GocdTools
  # Provides secrets for environment variables by looking up their name in a directory on disk,
  # assuming the file contents is the decrypted secret to provide.
  class SecretsProvider
    ANY = '_any-pipeline_'

    def initialize(root_directory)
      throw ArgumentError::new "#{root_directory} does not exist" unless File::directory? root_directory
      @root = root_directory
    end

    def secret_for(opts={})
      if (variable = opts[:variable]).nil?
        throw ArgumentError::new "need :variable"
      end

      subdirs_to_check = [ANY]
      unless (pipeline = opts[:pipeline]).nil?
        subdirs_to_check.unshift pipeline
      end

      paths = []
      subdirs_to_check.each do |sd|
        path = File::join @root, sd, variable
        paths.push path
        begin
          return File::read path
        rescue
        end
      end

      msg = "No secret found for '#{variable}' in pipeline '#{pipeline || 'unspecified'}'"
      msg += "\nTried paths: \n#{paths.join '\n'}"
      throw StandardError::new msg
    end
  end

  def self.sanitize(xml_doc)
    xml_doc.delete_element '//agent'
    xml_doc.delete_element '//environment'
  end

  def self.des_encrypt(value, iv)
    c = OpenSSL::Cipher::new('des')
    c.encrypt
    c.iv = iv
    res = c.update value
    res << c.final
  end

  M = '<ARGUMENT MUST BE SET>'
  def self.reencrypt_secure_variables(in_xml: M, with_cipher_key: M, and_provider: M)
    xml, iv, get = in_xml, with_cipher_key, and_provider
    xml.elements.each "//variable[@secure='true']" do |e|
      name = e.attribute 'name'
      secret = get.secret_for variable: name.to_s

      e.elements.each '//encryptedValue' do |encrypted_value|
        encrypted_value.text = Base64.encode64 des_encrypt secret, iv
      end
    end
  end

  def self.reencrypt_cruise_config_with_autocleanup(at: M, and_provider: M, into: M)
    if File::directory? into
      throw ArgumentError::new "directory '#{into}' must not exist"
    end

    FileUtils::mkdir into

    f = File::open at
    xml = REXML::Document::new f
    f.close

    iv = OpenSSL::Cipher::new('des').random_iv
    sanitize xml
    reencrypt_secure_variables in_xml: xml, with_cipher_key: iv, and_provider: and_provider

    cfp = File::join into, 'cipher'
    cf = File::new cfp, 'w'
    cf.write iv.each_byte.map { |b| b.to_s 16 }.join
    cf.close

    ccfp = File::join into, 'cruise-config.xml'
    ccf = File::new ccfp, 'w'
    xml.write ccf
    ccf.close

    at_exit { FileUtils::rm_rf into }

    [cfp, ccfp]
  end
end


text:
<?php

namespace RunOpenCode\ExchangeRate\Contract;

/**
 * Interface ExceptionInterface
 *
 * @package RunOpenCode\ExchangeRate\Contract
 */
interface ExceptionInterface
{

}


text:
module.exports = {
  title: 'Multistores',        // Your website title
  url: 'https://multistores-35b17.firebaseapp.com/',          // Your website URL
  project: 'multistores-35b17',      // Firebase project. See README.md -> How to Deploy
  trackingID: 'UA-XXXXX-Y',                 // Google Analytics Site's ID
};


text:
"""
This Python module contains utilities to validate user input parameters
parsed in a PyRate configuration file.
"""
import re
from configparser import ConfigParser
from pathlib import Path, PurePath
from typing import Union

import pyrate.constants as C
from pyrate.constants import NO_OF_PARALLEL_PROCESSES, sixteen_digits_pattern, twelve_digits_pattern, ORB_ERROR_DIR, \
    DEM_ERROR_DIR, TEMP_MLOOKED_DIR
from pyrate.core import ifgconstants as ifg
from pyrate.default_parameters import PYRATE_DEFAULT_CONFIGURATION
from pyrate.core.algorithm import factorise_integer
from pyrate.core.shared import extract_epochs_from_filename, InputTypes, get_tiles

def set_parameter_value(data_type, input_value, default_value, required, input_name):
    if len(input_value) < 1:
        input_value = None
        if required:  # pragma: no cover
            raise ValueError("A required parameter is missing value in input configuration file: " + str(input_name))

    if input_value is not None:
        if str(data_type) in "path":
            return Path(input_value)
        return data_type(input_value)
    return default_value

def validate_parameter_value(input_name, input_value, min_value=None, max_value=None, possible_values=None):
    if isinstance(input_value, PurePath):
        if not Path.exists(input_value):  # pragma: no cover
            raise ValueError("Given path: " + str(input_value) + " does not exist.")
    if input_value is not None:
        if min_value is not None:
            if input_value < min_value:  # pragma: no cover
                raise ValueError(
                    "Invalid value for " + str(input_name) + " supplied: " + str(
                        input_value) + ". Provide a value greater than or equal to " + str(min_value) + ".")
    if input_value is not None:
        if max_value is not None:
            if input_value > max_value:  # pragma: no cover
                raise ValueError(
                    "Invalid value for " + str(input_name) + " supplied: " + str(
                        input_value) + ". Provide a value less than or equal to " + str(max_value) + ".")

    if possible_values is not None:
        if input_value not in possible_values:  # pragma: no cover
            raise ValueError(
                "Invalid value for " + str(input_name) + " supplied: " + str(
                    input_value) + ". Provide one of these values: " + str(possible_values) + ".")
    return True

def validate_file_list_values(file_list, no_of_epochs):
    if file_list is None:  # pragma: no cover
        raise ValueError("No value supplied for input file list: " + str(file_list))

    files = parse_namelist(file_list)

    for f in files:
        if not Path(f).exists():  # pragma: no cover
            raise ConfigException(f"{f} does not exist")
        else:
            matches = extract_epochs_from_filename(filename_with_epochs=f)
            if len(matches) < no_of_epochs:  # pragma: no cover
                raise ConfigException(f"the number of epochs in {f} names are less the required number: {no_of_epochs}")

class MultiplePaths:
    def __init__(self, file_name: str, params: dict, input_type: InputTypes = InputTypes.IFG):

        self.input_type = input_type
        out_dir = params[C.OUT_DIR]
        tempdir = params[C.TEMP_MLOOKED_DIR]
        if isinstance(tempdir, str):
            tempdir = Path(tempdir)
        b = Path(file_name)
        if input_type in [InputTypes.IFG, InputTypes.COH]:
            d = re.search(sixteen_digits_pattern, b.stem)
            if d is None:  # could be 6 digit epoch dates
                d = re.search(twelve_digits_pattern, b.stem)
            if d is None:
                raise ValueError(f"{input_type.value} filename does not contain two 8- or 6-digit date strings")
            filestr = d.group() + '_'
        else:
            filestr = ''

        dir_exists = input_type.value in InputTypes.dir_map.value.keys()
        anchoring_dir = Path(out_dir).joinpath(InputTypes.dir_map.value[input_type.value]) \
            if dir_exists else Path(out_dir)

        if b.suffix == ".tif":
            self.unwrapped_path = None
            converted_path = b  # original file
            self.sampled_path = anchoring_dir.joinpath(filestr + input_type.value + '.tif')
        else:
            self.unwrapped_path = b.as_posix()
            converted_path = anchoring_dir.joinpath(b.stem.split('.')[0] + '_' + b.suffix[1:]).with_suffix('.tif')
            self.sampled_path = converted_path.with_name(filestr + input_type.value + '.tif')

        # tmp_sampled_paths are used after prepifg, during correct steps
        self.tmp_sampled_path = tempdir.joinpath(self.sampled_path.name).as_posix()
        self.converted_path = converted_path.as_posix()
        self.sampled_path = self.sampled_path.as_posix()

    @staticmethod
    def orb_error_path(ifg_path: Union[str, Path], params) -> Path:
        if isinstance(ifg_path, str):
            ifg_path = Path(ifg_path)
        return Path(params[C.OUT_DIR], C.ORB_ERROR_DIR,
                    ifg_path.stem + '_' +
                    '_'.join([str(params[C.ORBITAL_FIT_METHOD]),
                              str(params[C.ORBITAL_FIT_DEGREE]),
                              str(params[C.ORBITAL_FIT_LOOKS_X]),
                              str(params[C.ORBITAL_FIT_LOOKS_Y])]) +
                    '_orbfit.npy')

    @staticmethod
    def dem_error_path(ifg_path: Union[str, Path], params) -> Path:
        if isinstance(ifg_path, str):
            ifg_path = Path(ifg_path)
        return Path(params[C.OUT_DIR], C.DEM_ERROR_DIR,
                    ifg_path.stem + '_' + str(params[C.DE_PTHR]) + '_dem_error.npy')

    @staticmethod
    def aps_error_path(ifg_path: Union[str, Path], params) -> Path:
        if isinstance(ifg_path, str):
            ifg_path = Path(ifg_path)
        return Path(params[C.OUT_DIR], C.APS_ERROR_DIR,
                    ifg_path.stem + '_' +
                    '_'.join([str(x) for x in [
                        params[C.SLPF_CUTOFF],
                        params[C.SLPF_NANFILL],
                        params[C.SLPF_NANFILL_METHOD],
                        params[C.TLPF_CUTOFF],
                        params[C.TLPF_PTHR]
                    ]
                              ]) + '_aps_error.npy')

    def __str__(self):  # pragma: no cover
        st = ""
        if self.unwrapped_path is not None:
            st += """\nunwrapped_path = """ + self.unwrapped_path
        else:
            st += """\nunwrapped_path = None"""
        st += """
            converted_path = """ + self.converted_path + """
            sampled_path = """ + self.sampled_path + """
            tmp_sampled_path = """ + self.tmp_sampled_path + """
            """
        return st

class Configuration:

    def __init__(self, config_file_path):

        parser = ConfigParser()
        parser.optionxform = str
        # mimic header to fulfil the requirement for configparser
        with open(config_file_path) as stream:
            parser.read_string("[root]\n" + stream.read())

        for key, value in parser["root"].items():
            self.__dict__[key] = value

        # make output path, if not provided will error
        Path(self.outdir).mkdir(exist_ok=True, parents=True)

        # custom correct sequence if 'correct' section is provided in config
        if 'correct' in parser and 'steps' in parser['correct']:
            self.__dict__['correct'] = list(filter(None, parser['correct'].get('steps').splitlines()))
        else:
            self.__dict__['correct'] = [
                'orbfit',
                'refphase',
                'demerror',
                'phase_closure',
                'mst',
                'apscorrect',
                'maxvar',
            ]

        # Validate required parameters exist.

        required = {k for k, v in PYRATE_DEFAULT_CONFIGURATION.items() if v['Required']}

        if not required.issubset(self.__dict__):  # pragma: no cover
            raise ValueError("Required configuration parameters: " + str(
                required.difference(self.__dict__)) + " are missing from input config file.")

        # handle control parameters
        for parameter_name in PYRATE_DEFAULT_CONFIGURATION:
            param_value = self.__dict__[parameter_name] if parameter_name in required or \
                                                           parameter_name in self.__dict__ else ''

            self.__dict__[parameter_name] = set_parameter_value(
                PYRATE_DEFAULT_CONFIGURATION[parameter_name]["DataType"],
                param_value,
                PYRATE_DEFAULT_CONFIGURATION[parameter_name]["DefaultValue"],
                PYRATE_DEFAULT_CONFIGURATION[parameter_name]["Required"],
                parameter_name)
            validate_parameter_value(parameter_name, self.__dict__[parameter_name],
                                     PYRATE_DEFAULT_CONFIGURATION[parameter_name]["MinValue"],
                                     PYRATE_DEFAULT_CONFIGURATION[parameter_name]["MaxValue"],
                                     PYRATE_DEFAULT_CONFIGURATION[parameter_name]["PossibleValues"])

        # bespoke parameter validation
        if self.refchipsize % 2 != 1:  # pragma: no cover
            if self.refchipsize - 1 > 1:
                # Configuration parameters refchipsize must be odd
                # values too large (>101) will slow down the process without significant gains in results.
                self.refchipsize = self.refchipsize - 1

        # calculate rows and cols if not supplied
        if hasattr(self, 'rows') and hasattr(self, 'cols'):
            self.rows, self.cols = int(self.rows), int(self.cols)
        else:
            if NO_OF_PARALLEL_PROCESSES > 1:  # i.e. mpirun
                self.rows, self.cols = [int(num) for num in factorise_integer(NO_OF_PARALLEL_PROCESSES)]
            else:
                if self.parallel:  # i.e. joblib parallelism
                    self.rows, self.cols = [int(num) for num in factorise_integer(self.processes)]
                else:  # i.e. serial
                    self.rows, self.cols = 1, 1

        # create a temporary directory if not supplied
        if not hasattr(self, 'tmpdir'):
            self.tmpdir = Path(self.outdir).joinpath("tmpdir")
        else:
            self.tmpdir = Path(self.tmpdir)

        self.tmpdir.mkdir(parents=True, exist_ok=True)

        # create orbfit error dir
        self.orb_error_dir = Path(self.outdir).joinpath(ORB_ERROR_DIR)
        self.orb_error_dir.mkdir(parents=True, exist_ok=True)

        self.interferogram_dir = Path(self.outdir).joinpath(C.INTERFEROGRAM_DIR)
        self.interferogram_dir.mkdir(parents=True, exist_ok=True)

        # create DEM error dir
        self.dem_error_dir = Path(self.outdir).joinpath(DEM_ERROR_DIR)
        self.dem_error_dir.mkdir(parents=True, exist_ok=True)

        # create aps error dir
        self.aps_error_dir = Path(self.outdir).joinpath(C.APS_ERROR_DIR)
        self.aps_error_dir.mkdir(parents=True, exist_ok=True)

        # create mst dir
        self.mst_dir = Path(self.outdir).joinpath(C.MST_DIR)
        self.mst_dir.mkdir(parents=True, exist_ok=True)

        self.phase_closure_dir = Path(self.outdir).joinpath(C.PHASE_CLOSURE_DIR)
        self.phase_closure_dir.mkdir(parents=True, exist_ok=True)

        self.coherence_dir = Path(self.outdir).joinpath(C.COHERENCE_DIR)
        self.coherence_dir.mkdir(parents=True, exist_ok=True)

        self.geometry_dir = Path(self.outdir).joinpath(C.GEOMETRY_DIR)
        self.geometry_dir.mkdir(parents=True, exist_ok=True)

        self.timeseries_dir = Path(self.outdir).joinpath(C.TIMESERIES_DIR)
        self.timeseries_dir.mkdir(parents=True, exist_ok=True)

        self.velocity_dir = Path(self.outdir).joinpath(C.VELOCITY_DIR)
        self.velocity_dir.mkdir(parents=True, exist_ok=True)

        # create temp multilooked files dir
        self.temp_mlooked_dir = Path(self.outdir).joinpath(TEMP_MLOOKED_DIR)
        self.temp_mlooked_dir.mkdir(parents=True, exist_ok=True)

        self.ref_pixel_file = self.ref_pixel_path(self.__dict__)

        # var no longer used
        self.APS_ELEVATION_EXT = None
        self.APS_INCIDENCE_EXT = None
        self.apscorrect = 0
        self.apsmethod = 0
        self.elevationmap = None
        self.incidencemap = None

        # define parallel processes that will run
        self.NUMEXPR_MAX_THREADS = str(NO_OF_PARALLEL_PROCESSES)

        # Validate file names supplied in list exist and contain correct epochs in file names
        if self.cohfilelist is not None:
            # if self.processor != 0:  # not roipac
            validate_file_list_values(self.cohfilelist, 1)
            self.coherence_file_paths = self.__get_files_from_attr('cohfilelist', input_type=InputTypes.COH)

        if self.basefilelist is not None:
            # if self.processor != 0:  # not roipac
            validate_file_list_values(self.basefilelist, 1)
            self.baseline_file_paths = self.__get_files_from_attr('basefilelist', input_type=InputTypes.BASE)

        self.header_file_paths = self.__get_files_from_attr('hdrfilelist', input_type=InputTypes.HEADER)

        self.interferogram_files = self.__get_files_from_attr('ifgfilelist')

        self.dem_file = MultiplePaths(self.demfile, self.__dict__, input_type=InputTypes.DEM)

        # backward compatibility for string paths
        for key in self.__dict__:
            if isinstance(self.__dict__[key], PurePath):
                self.__dict__[key] = str(self.__dict__[key])

    @staticmethod
    def ref_pixel_path(params):
        return Path(params[C.OUT_DIR]).joinpath(
            '_'.join(
                [str(x) for x in [
                    'ref_pixel', params[C.REFX], params[C.REFY], params[
                        C.REFNX], params[C.REFNY],
                    params[C.REF_CHIP_SIZE], params[C.REF_MIN_FRAC], '.npy'
                ]
                 ]
            )
        )

    @staticmethod
    def mst_path(params, index) -> Path:
        return Path(params[C.OUT_DIR], C.MST_DIR).joinpath(f'mst_mat_{index}.npy')

    @staticmethod
    def preread_ifgs(params: dict) -> Path:
        return Path(params[C.TMPDIR], 'preread_ifgs.pk')

    @staticmethod
    def vcmt_path(params):
        return Path(params[C.OUT_DIR], C.VCMT).with_suffix('.npy')

    @staticmethod
    def phase_closure_filtered_ifgs_list(params):
        return Path(params[C.TEMP_MLOOKED_DIR]).joinpath('phase_closure_filtered_ifgs_list')

    def refresh_ifg_list(self, params):  # update params dict
        filtered_ifgs_list = self.phase_closure_filtered_ifgs_list(params)
        files = parse_namelist(filtered_ifgs_list.as_posix())
        params[C.INTERFEROGRAM_FILES] = [MultiplePaths(p, self.__dict__, input_type=InputTypes.IFG) for p in files]
        return params

    @staticmethod
    def ref_phs_file(params):
        ref_pixel_path = Configuration.ref_pixel_path(params)
        # add ref pixel path as when ref pixel changes - ref phs path should also change
        return Path(params[C.OUT_DIR]).joinpath(
            ref_pixel_path.stem + '_' +
            '_'.join(['ref_phs', str(params[C.REF_EST_METHOD]), '.npy'])
        )

    @staticmethod
    def get_tiles(params):
        ifg_path = params[C.INTERFEROGRAM_FILES][0].sampled_path
        rows, cols = params['rows'], params['cols']
        return get_tiles(ifg_path, rows, cols)

    def __get_files_from_attr(self, attr, input_type=InputTypes.IFG):
        val = self.__getattribute__(attr)
        files = parse_namelist(val)
        return [MultiplePaths(p, self.__dict__, input_type=input_type) for p in files]

    def closure(self):
        closure_d = Path(self.phase_closure_dir)

        class Closure:
            def __init__(self):
                self.closure = closure_d.joinpath('closure.npy')
                self.ifgs_breach_count = closure_d.joinpath('ifgs_breach_count.npy')
                self.num_occurences_each_ifg = closure_d.joinpath('num_occurrences_each_ifg.npy')
                self.loops = closure_d.joinpath('loops.npy')

        return Closure()

    @staticmethod
    def coherence_stats(params):
        coh_d = Path(params[C.COHERENCE_DIR])
        return {k: coh_d.joinpath(k.lower() + '.tif').as_posix() for k in [ifg.COH_MEDIAN, ifg.COH_MEAN, ifg.COH_STD]}

    @staticmethod
    def geometry_files(params):
        geom_dir = Path(params[C.GEOMETRY_DIR])
        return {k: geom_dir.joinpath(k.lower() + '.tif').as_posix() for k in C.GEOMETRY_OUTPUT_TYPES}

def write_config_parser_file(conf: ConfigParser, output_conf_file: Union[str, Path]):
    """replacement function for write_config_file which uses dict instead of a ConfigParser instance"""
    with open(output_conf_file, 'w') as configfile:
        conf.write(configfile)

def write_config_file(params, output_conf_file):
    """
    Takes a param object and writes the config file. Reverse of get_conf_params.

    :param dict params: parameter dictionary
    :param str output_conf_file: output file name

    :return: config file
    :rtype: list
    """
    with open(output_conf_file, 'w') as f:
        for k, v in params.items():
            if v is not None:
                if k == 'correct':
                    f.write(''.join(['[', k, ']' ':\t', '', '\n']))
                    f.write(''.join(['steps = ', '\n']))
                    for vv in v:
                        f.write(''.join(['\t' + str(vv), '\n']))
                elif isinstance(v, list):
                    continue
                else:
                    if isinstance(v, MultiplePaths):
                        if v.unwrapped_path is None:
                            vv = v.converted_path
                        else:
                            vv = v.unwrapped_path
                    else:
                        vv = v
                    f.write(''.join([k, ':\t', str(vv), '\n']))
            else:
                f.write(''.join([k, ':\t', '', '\n']))

def parse_namelist(nml):
    """
    Parses name list file into array of paths

    :param str nml: interferogram file list

    :return: list of interferogram file names
    :rtype: list
    """
    with open(nml) as f_in:
        lines = [line.rstrip() for line in f_in]
    return filter(None, lines)

class ConfigException(Exception):
    """
    Default exception class for configuration errors.
    """


text:
@import UIKit;

NS_ASSUME_NONNULL_BEGIN

@protocol OBADrawerPresenter<NSObject>
- (void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated;
@end

NS_ASSUME_NONNULL_END


text:
namespace ginkgo
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Utils
//
////////////////////////////////////////////////////////////////////////////////////////////////////

size_t findMatchingRightParenthesis(const std::string &string, size_t leftParenthesisPosition);
bool isNumeric(char c);
bool isAlphanumeric(char c);

auto identity =
	[](auto predicate)
	{
		return predicate;
	};

auto logicalNot =
	[](auto predicate)
	{
		return [&predicate](auto... args)
		{
			return !predicate(args...);
		};
	};

auto toString =
	[](const auto &x, size_t precision = 0)
	{
		std::stringstream s;
		s << std::fixed << std::setprecision(precision) << x;

		return s.str();
	};

template<typename T>
T fromString(const std::string &x)
{
	T result;

	std::stringstream s(x);
	s >> result;

	return result;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

}

#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdmin.Actions;
using XenAPI;

namespace XenAdmin.Alerts
{
    public class XenServerVersionAlert : XenServerUpdateAlert
    {
        public XenServerVersion Version;

        public XenServerVersionAlert(XenServerVersion version)
        {
            Version = version;
            _timestamp = version.TimeStamp;
        }

        public override string WebPageLabel
        {
            get { return Messages.AVAILABLE_UPDATES_DOWNLOAD_TEXT; }
        }

        public override string Name
        {
            get { return Version.Name; }
        }

        public override string Title
        {
            get { return string.Format(Messages.DOWLOAD_LATEST_XS_TITLE, Version.Name); }
        }

        public override string Description
        {
            get { return string.Format(Messages.DOWNLOAD_LATEST_XS_BODY, Version.Name); }
        }

        public override string FixLinkText
        {
            get
            {
                return Messages.ALERT_NEW_VERSION_DOWNLOAD;
            }
        }

        public override AlertPriority Priority
        {
            get { return AlertPriority.Priority5; }
        }

        public override Action FixLinkAction
        {
            get { return () => Program.OpenURL(Version.Url); }
        }

        public override string HelpID
        {
            get
            {
                return "XenServerUpdateAlert";
            }
        }

        public override bool IsDismissed()
        {
            foreach (var connection in connections)
                if (IsDismissed(connection))
                    return true;

            return false;
        }

        private bool IsDismissed(IXenConnection connection)
        {
            Pool pool = Helpers.GetPoolOfOne(connection);
            if (pool == null)
                return false;

            Dictionary<string, string> other_config = pool.other_config;

            if (other_config.ContainsKey(IgnoreServerAction.LAST_SEEN_SERVER_VERSION_KEY))
            {
                List<string> current = new List<string>(other_config[IgnoreServerAction.LAST_SEEN_SERVER_VERSION_KEY].Split(','));
                if (current.Contains(Version.VersionAndOEM))
                    return true;
            }
            return false;
        }

        public override bool Equals(Alert other)
        {
            if (other is XenServerVersionAlert)
            {
                return Version.VersionAndOEM == ((XenServerVersionAlert)other).Version.VersionAndOEM;
            }
            return base.Equals(other);
        }
    }
}


text:
#include "NFProjectView.h"
#include "NFUIModule.h"

NFProjectView::NFProjectView(NFIPluginManager* p, NFViewType vt) : NFIView(p, vt, GET_CLASS_NAME(NFProjectView))
{

}

bool NFProjectView::Execute()
{
	//1. the project root folder is NFDataCfg

	return false;
}


text:
namespace views {

class DialogClientView;
class Window;

///////////////////////////////////////////////////////////////////////////////
// ClientView
//
//  A ClientView is a View subclass that is used to occupy the "client area"
//  of a window. It provides basic information to the window that contains it
//  such as non-client hit testing information, sizing etc. Sub-classes of
//  ClientView are used to create more elaborate contents, e.g.
//  "DialogClientView".
class ClientView : public View {
 public:
  // Constructs a ClientView object for the specified window with the specified
  // contents. Since this object is created during the process of creating
  // |window|, |contents_view| must be valid if you want the initial size of
  // the window to be based on |contents_view|'s preferred size.
  ClientView(Window* window, View* contents_view);
  virtual ~ClientView() {}

  // Manual RTTI ftw.
  virtual DialogClientView* AsDialogClientView();

  // Returns true to signal that the Window can be closed. Specialized
  // ClientView subclasses can override this default behavior to allow the
  // close to be blocked until the user corrects mistakes, accepts a warning
  // dialog, etc.
  virtual bool CanClose();

  // Notification that the window is closing.  The default implementation
  // forwards the notification to the delegate.
  virtual void WindowClosing();

  // Tests to see if the specified point (in view coordinates) is within the
  // bounds of this view. If so, it returns HTCLIENT in this default
  // implementation. If it is outside the bounds of this view, this must return
  // HTNOWHERE to tell the caller to do further processing to determine where
  // in the non-client area it is (if it is).
  // Subclasses of ClientView can extend this logic by overriding this method
  // to detect if regions within the client area count as parts of the "non-
  // client" area. A good example of this is the size box at the bottom right
  // corner of resizable dialog boxes.
  virtual int NonClientHitTest(const gfx::Point& point);

  // Overridden from View:
  virtual gfx::Size GetPreferredSize() OVERRIDE;
  virtual void Layout() OVERRIDE;

 protected:
  // Overridden from View:
  virtual void ViewHierarchyChanged(
      bool is_add, View* parent, View* child) OVERRIDE;
  virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE;
  virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;

  // Accessors for private data members.
  Window* window() const { return window_; }
  void set_window(Window* window) { window_ = window; }
  View* contents_view() const { return contents_view_; }
  void set_contents_view(View* contents_view) {
    contents_view_ = contents_view;
  }

 private:
  // The Window that hosts this ClientView.
  Window* window_;

  // The View that this ClientView contains.
  View* contents_view_;
};

}  // namespace views

#endif  // #ifndef VIEWS_WINDOW_CLIENT_VIEW_H_


text:
package compilercommon

import (
	"fmt"
	"strings"

	"github.com/emirpasic/gods/trees/redblacktree"
)

// SourcePositionMapper defines a helper struct for cached, faster lookup of rune position <->
// (line, column) for a specific source file.
type SourcePositionMapper struct {
	// rangeTree holds a tree that maps from rune position to a line and start position.
	rangeTree *redblacktree.Tree

	// lineMap holds a map from line number to rune positions for that line.
	lineMap map[int]inclusiveRange
}

// EmptySourcePositionMapper returns an empty source position mapper.
func EmptySourcePositionMapper() SourcePositionMapper {
	rangeTree := redblacktree.NewWith(inclusiveComparator)
	return SourcePositionMapper{rangeTree, map[int]inclusiveRange{}}
}

// CreateSourcePositionMapper returns a source position mapper for the contents of a source file.
func CreateSourcePositionMapper(contents []byte) SourcePositionMapper {
	lines := strings.Split(string(contents), "\n")
	rangeTree := redblacktree.NewWith(inclusiveComparator)
	lineMap := map[int]inclusiveRange{}

	var currentStart = int(0)
	for index, line := range lines {
		lineEnd := currentStart + int(len(line))
		rangeTree.Put(inclusiveRange{currentStart, lineEnd}, lineAndStart{int(index), currentStart})
		lineMap[int(index)] = inclusiveRange{currentStart, lineEnd}
		currentStart = lineEnd + 1
	}

	return SourcePositionMapper{rangeTree, lineMap}
}

type inclusiveRange struct {
	start int
	end   int
}

type lineAndStart struct {
	lineNumber    int
	startPosition int
}

func inclusiveComparator(a, b interface{}) int {
	i1 := a.(inclusiveRange)
	i2 := b.(inclusiveRange)

	if i1.start >= i2.start && i1.end <= i2.end {
		return 0
	}

	diff := int64(i1.start) - int64(i2.start)

	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// RunePositionToLineAndCol returns the line number and column position of the rune position in source.
func (spm SourcePositionMapper) RunePositionToLineAndCol(runePosition int) (int, int, error) {
	ls, found := spm.rangeTree.Get(inclusiveRange{runePosition, runePosition})
	if !found {
		return 0, 0, fmt.Errorf("Unknown rune position %v in source file", runePosition)
	}

	las := ls.(lineAndStart)
	return las.lineNumber, runePosition - las.startPosition, nil
}

// LineAndColToRunePosition returns the rune position of the line number and column position in source.
func (spm SourcePositionMapper) LineAndColToRunePosition(lineNumber int, colPosition int) (int, error) {
	lineRuneInfo, hasLine := spm.lineMap[lineNumber]
	if !hasLine {
		return 0, fmt.Errorf("Unknown line %v in source file", lineNumber)
	}

	if colPosition > lineRuneInfo.end-lineRuneInfo.start {
		return 0, fmt.Errorf("Column position %v not found on line %v in source file", colPosition, lineNumber)
	}

	return lineRuneInfo.start + colPosition, nil
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

/**
 * This package contains the base classes for resource models.
 */
package com.microsoft.azure.management.resources.fluentcore.arm.models;


text:
<TITLE>Review for Paper, The (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Paper, The (1994)

reviewed by
Dragan Antulov

THE PAPER
A Film Review
Copyright Dragan Antulov 2000

In today's world of journalism, dominated by television,
Internet and "news as entertainment" business philosophy,
printed newspapers are considered to be the thing of the
past. Same thing happened to the perception of journalists
as fearless crusaders for truth and justice in this cynical
age. As a result, once thriving subgenre of journalism
movies almost disappeared from Hollywood. THE PAPER, 1994
drama by Ron Howard, represents one of those precious films
that deal with realities of life of modern newspaper
reporters.

The screenplay of THE PAPER, written by brother David and
Stephen Koepp, follows 24 hours in lives of reporters and
editors in "New York Sun" tabloid newspaper. The nominal
protagonist of the film is Henry Hackett (played by Michael
Keaton), workaholic editor who loves his job. But long
hours, low pay and uncertain future of the tabloid lead him
to think about new career. His pregnant wife Martha (played
by Marisa Tomei) urges him to think about better-paid but
more boring job in respectable "New York Sentinel"
newspaper. In the meantime, rapidly developing story about
two black teenagers being arrested for racially motivated
murders would represent another opportunity for Hackett to
use his skills of investigative reporter. Results of his
investigation, on the other hand, would later lead to
dramatic confrontations with bullish managing editor Alicia
Clark (played by Glenn Close).

Judging by some of American newspaper movie reviews, Koepp
brothers in their screenplay managed to paint rather
convincing picture of the life in modern editorial offices.
According to medical statistics in many countries, news
reporters and editors have shorter average lifespan than
those belonging to other professions and THE PAPER explains
the causes of this phenomenon - deadline, editorial
pressures and consequent stress that leads to chain-smoking
and alcoholism, and, naturally, all that has devastating
effects on reporters' personal lives. Ron Howard is faithful
to this gritty picture laced with black humour, but he
nevertheless adds some Hollywood touch with few moralising
scenes and melodramatic finale that went over the top with
some of the cliches (including notorious "Stop the presses!"
line). However, THE PAPER compensates these flaws with truly
great ensemble cast that relies more on character actors
like Keaton, Tomei, Close, Robert Duvall and Randy Quaid
Tomei than standard Hollywood stars. Because of them,
realistic atmosphere of modern-day editorial offices isn't
lost. THE PAPER, therefore, is a film that should be
recommended as skillfully done example of almost forgotten
dramatic subgenre.

RATING: 7/10 (+++)

Review written on July 19th 2000

Dragan Antulov a.k.a. Drax
Fido: 2:381/100
E-mail: dragan.antulov@st.tel.hr
E-mail: drax@purger.com
E-mail: dragan.antulov@altbbs.fido.hr

Filmske recenzije na hrvatskom/Movie Reviews in Croatian
http://film.purger.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
Les colonnes sèches sont modélisées à l'aide d'une famille de la catégorie Appareils sanitaires de {{logiciel}}.

Le nom du type de colonne sèche doit suivre le schéma suivant :

> PLO-PI-RES-BOU


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Calculator</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/stylesheets/app.min.css">

  <link href='https://fonts.googleapis.com/css?family=Roboto:100,300' rel='stylesheet' type='text/css'>

7

8

9

4

5

6

1

2

3

.

0

=

DEL

/

X

-

+


text:
<?php

use Orchestra\Testbench\TestCase;

class TestBase extends TestCase {

    public function setUp()
    {
        parent::setUp();

        $this->resetDatabase();
    }

    protected function getEnvironmentSetUp($app)
    {
        $app['path.base'] = __DIR__ . '/..';

        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => ''
        ]);
    }

    protected function resetDatabase()
    {
        // Relative to the testbench app folder: vendors/orchestra/testbench/src/fixture
        $migrationsPath = 'tests/migrations';
        $artisan = $this->app->make('Illuminate\Contracts\Console\Kernel');

        // Migrate
        $artisan->call('migrate', [
            '--database' => 'sqlite',
            '--path'     => $migrationsPath,
        ]);
    }

    protected function getPackageProviders($app)
    {
        return ['Kenarkose\Tracker\TrackerServiceProvider'];
    }

}


text:
package com.google.acre.servlet;

public class OneTrueConfigException extends Exception {

	private static final long serialVersionUID = -8340646020783187865L;

	public OneTrueConfigException(String message) {
        super(message);
    }

}


text:
package au.com.outware.cavemanapp.presentation.viewmodel;

import android.support.annotation.VisibleForTesting;

import java.util.List;

import javax.inject.Inject;

import au.com.outware.caveman.data.model.Environment;
import au.com.outware.cavemanapp.domain.interactor.GetCurrentEnvironment;
import au.com.outware.cavemanapp.domain.interactor.GetEnvironments;
import au.com.outware.cavemanapp.domain.interactor.RemoveEnvironment;
import au.com.outware.cavemanapp.domain.interactor.SetCurrentEnvironment;

public class MainActivityViewModel {
    @VisibleForTesting
    @Inject
    GetEnvironments getEnvironments;
    @VisibleForTesting
    @Inject
    GetCurrentEnvironment getCurrentEnvironment;
    @VisibleForTesting
    @Inject
    SetCurrentEnvironment setCurrentEnvironment;
    @VisibleForTesting
    @Inject
    RemoveEnvironment removeEnvironment;

    @Inject
    public MainActivityViewModel() { }

    public int getSelectedItemPosition() {
        int pos = getEnvironments().indexOf(getCurrentEnvironment());
        return (pos != -1) ? pos : 0;
    }

    public Environment getCurrentEnvironment() {
        return getCurrentEnvironment.execute();
    }

    public List<Environment> getEnvironments() {
        return getEnvironments.execute();
    }

    public void setCurrentEnvironment(Environment environment) {
        setCurrentEnvironment.setEnvironment(environment).execute();
    }

    public void removeCurrentEnvironment() {
        removeEnvironment.setEnvironment(getCurrentEnvironment()).execute();
        for (Environment environment : getEnvironments.execute()) {
            if (environment.isProduction()) {
                setCurrentEnvironment.setEnvironment(environment).execute();
                break;
            }
        }
    }

    public boolean shouldEnableButtons() {
        return !getCurrentEnvironment().isProduction();
    }
}


text:
import shutil
import tempfile
import unittest

from pkgsetcomp import pkgsetcomp

class Test_pkgsetcomp(unittest.TestCase):

    def setUp(self):
        self.output_dir = tempfile.mkdtemp(prefix='compare_paths_')

    def tearDown(self):
        shutil.rmtree(self.output_dir)

    def test_00_pkgsetcomp(self):
        manifest = ['orange', 'carrot', 'corn']
        installed = ['apple', 'orange', 'peach']

        comparison = pkgsetcomp.compare_package_lists(manifest, installed)

        comparison.print_string()

        self.assertEqual(comparison.uninstalled, ['carrot', 'corn'])
        self.assertEqual(comparison.installed, installed)
        self.assertEqual(comparison.manifest, manifest)
        self.assertEqual(comparison.also_installed, ['apple', 'peach'])

        # self.assertEqual(comparison.minimal, ['...'])

        comparison.write_package_scripts(self.output_dir)

        # raise Exception()

    def test_10_get_package_lists(self):
        installed, manifest = pkgsetcomp.get_package_lists(
            output_dir=self.output_dir)
        assert isinstance(installed, list)
        assert isinstance(manifest, list)
        self.assertTrue(len(installed))
        self.assertTrue(len(manifest))

    def test_20_compare_live_system(self):
        comparison = pkgsetcomp.pkgsetcomp_packages_with_manifest(
            pkgsetcomp.MANIFEST_URL,
            self.output_dir)

        self.assertTrue(comparison.manifest)
        self.assertTrue(comparison.installed)
        self.assertTrue(len(comparison.manifest))
        self.assertTrue(len(comparison.installed))

        # self.assertTrue(len(comparison.also_installed))
        # self.assertTrue(len(comparison.minimal))
        # self.assertTrue(len(comparison.uninstalled))

if __name__ == "__main__":
    import sys
    sys.exit(unittest.main())


text:
A collection of abstract base "classes" for the widgets of the Abstract editor.

The ``Abstract.Widgets.Base`` object also takes care of maintaining a map id → widget for the benefit of look-up.
This is not really the right place, but is convenient for now.

Implementation code has to obey the following pattern:
<pre>
this.NewWidget = function(data) {

	this.htmlElt = function() {
		return ...;
	};

	...all non-overridden stuff...

	Abstract.Widgets.Base.AbstractWidget.call(this, "NewWidget", data);

	...all overridden stuff...

};
oo.util.extend(Abstract.Widgets.Base.AbstractWidget, Abstract.Widgets.Layout.NewWidget);
</pre>

## Interface (of variant nature) of widgets

Functions associated to the editor asking what the appropriate (associated) action for events (under polymorphism) would be.
Note that the names and signatures of these methods correspond 1-to-1 with those described for ``Abstract.EventHandler``.
* ``this.actionForLeftMouseClick(event : jQuery DOMEvent)``:	asks the widget what it wants to do with the given event
* ``this.actionForTyping(character : 1-character String)``:	ditto
* ``this.actionForSpecialKeyPress(eventLiteral : Abstract.EventTypes.SpecialKeyPress, originalEvent : jQuery DOMEvent)``:	ditto
* ``this.actionForSpecialKeyDown(eventLiteral : Abstract.EventTypes.SpecialKeyPress, originalEvent : jQuery DOMEvent)``:	ditto

Functions associated with performing the actions themselves.
Note that these correspond directly to actions.
* ``this.focus()``:		signals to the widget to visualize being focused
* ``this.enterEdit()``:	signals to the widget that it should enter edit mode
* ``this.exitEdit()``:	signals to the widget that editing should be broken off
* ``this.finishEdit()``:	signals to the widget that editing should be finished up
* ``this.input(character : 1-character String)``:	handle typing of 1 character

Also, we have the following function(s) in the interface:
* ``this.unfocus()``:	signals to the widget that it should yield focus and do required clean-up

## Enumeration of the possible responses for ``AbstractWidget#actionFor``:

* nil			<=> ignore + don't change state
* focus			<=> (re-)assign focus to this widget
* enterEdit		<=> enter edit state
* exitEdit		<=> exit edit state abnormally/prematurely
* finishEdit	<=> finish edit state normally/regularly
* input			<=> simple input (i.e., alphanumeric input)
* collapse		<=> collapse a visual element
* expand		<=> expand a visual element
* bubbleUp		<=> bubble event up
* custom		<=> do something custom...
* (navigation actions:)
* goRight
* goLeft
* goUp
* goDown
* goTreeUp
* goTreeDown


text:
module PayU
  module PaymentsHelper
    def pay_u_new_payment_url(payment)
      PayU.new_payment_url + '/?' + payment.to_hash.to_query
    end

    def pay_u_payment_status_url(payment)
      PayU::PaymentStatus.url(payment)
    end
  end
end


text:
from .application import Application
from .commands import Command
from .formatters import *
from .helpers import *
from .inputs import *
from .outputs import *
from .testers import *

__all__ = [
    'Application',
    'Command',
    'OutputFormatter',
    'OutputFormatterStyle',
    'OutputFormatterStyleStack',
    'Helper',
    'DialogHelper',
    'ProgressHelper',
    'TableHelper',
    'HelperSet',
    'FormatterHelper',
    'Input',
    'InputDefinition',
    'InputArgument',
    'InputOption',
    'ArgvInput',
    'ListInput',
    'Output',
    'ConsoleOutput',
    'StreamOutput',
    'ApplicationTester',
    'CommandTester'
]


text:
package com.jonathanfinerty.expandabletextview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import com.jonathanfinerty.lib.R;

public class ExpandableTextViewToggle extends TextView implements com.jonathanfinerty.expandabletextview.ExpandableTextView.Listener {

    private String expandText;
    private Drawable expandDrawable;

    private String collapseText;
    private Drawable collapseDrawable;

    private int collapsibleTextViewId;

    public ExpandableTextViewToggle(Context context) {
        super(context);
        init(null);
    }

    public ExpandableTextViewToggle(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public ExpandableTextViewToggle(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableTextViewToggle);
        collapsibleTextViewId = typedArray.getResourceId(R.styleable.ExpandableTextViewToggle_collapsibleTextView, -1);
        expandText = typedArray.getString(R.styleable.ExpandableTextViewToggle_expandText);
        expandDrawable = typedArray.getDrawable(R.styleable.ExpandableTextViewToggle_expandDrawable);
        collapseText = typedArray.getString(R.styleable.ExpandableTextViewToggle_collapseText);
        collapseDrawable = typedArray.getDrawable(R.styleable.ExpandableTextViewToggle_collapseDrawable);
        typedArray.recycle();

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        final ExpandableTextView expandableTextView = (ExpandableTextView) this.getRootView().findViewById(collapsibleTextViewId);
        expandableTextView.setListener(this);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                expandableTextView.toggleExpansion();
            }
        });
    }

    @Override
    public void expandableChanged(boolean expandable) {
        if (expandable) {
            this.setVisibility(View.VISIBLE);
        } else {
            this.setVisibility(View.GONE);
        }
    }

    @Override
    public void expandedChanged(boolean expanded) {
        if (expanded) {
            setText(collapseText);
            setCompoundDrawablesWithIntrinsicBounds(null, null, collapseDrawable, null);
        } else {
            setText(expandText);
            setCompoundDrawablesWithIntrinsicBounds(null, null, expandDrawable, null);
        }
    }
}


text:
<?php
class Kwc_Form_Dynamic_Admin extends Kwc_Abstract_Composite_Admin
{
}