text:
import ejb.Catalogue;
import ejb.CatalogueBean;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import persistence.FileProductListLoader;
import persistence.FileProductPercentageDiscountLoader;

public class ShowCatalogueCommand extends FrontCommand {

    @Override
    public void process() {
        checkAttribute();
        updateParameters();
        initCatalogue();

        RequestDispatcher dispatcher = context.getRequestDispatcher("/catalogueView.jsp");
        try {
            dispatcher.forward(request, response);
        } catch (ServletException | IOException ex) {
            Logger.getLogger(ShowInvoiceCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void initCatalogue() {
        Catalogue catalogue;
        try {
            catalogue = (Catalogue) new InitialContext().lookup("java:app/sMarketplaceE2-ejb/CatalogueBean");
            new FileProductListLoader("V:/Proyectos/Espacio de trabajo personal/NetBeans/sMarketplace/Entrega 2/sMarketplace/data/products.txt",
                    (Integer) request.getSession().getAttribute("firstItemNumber"),
                    (Integer) request.getSession().getAttribute("lastItemNumber"),
                    catalogue).load();
            new FileProductPercentageDiscountLoader("V:/Proyectos/Espacio de trabajo personal/NetBeans/sMarketplace/Entrega 2/sMarketplace/data/productsPercentageDiscounts.txt", catalogue).load();
        } catch (NamingException ex) {
            Logger.getLogger(AddToCartCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void checkAttribute() {
        if (request.getSession().getAttribute("firstItemNumber") == null) {
            request.getSession().setAttribute("firstItemNumber", 0);
        }
        if (request.getSession().getAttribute("lastItemNumber") == null) {
            request.getSession().setAttribute("lastItemNumber", 5);
        }
    }

    private void updateParameters() {
        if (request.getParameter("increase") != null) {
            increasePage();
        }
        if (request.getParameter("decrease") != null) {
            decreasePage();
        }
    }

    private boolean canToBeIncreased() {
        Catalogue checkerCatalogue = new CatalogueBean();
        new FileProductListLoader("V:/Proyectos/Espacio de trabajo personal/NetBeans/sMarketplace/Entrega 2/sMarketplace/data/products.txt",
                (Integer) request.getSession().getAttribute("firstItemNumber") + 5,
                (Integer) request.getSession().getAttribute("lastItemNumber") + 5,
                checkerCatalogue).load();
        if (checkerCatalogue.getProducts().size() > 0) {
            return true;
        }
        return false;
    }

    private boolean canToBeDecreased() {
        Catalogue checkerCatalogue = new CatalogueBean();
        new FileProductListLoader("V:/Proyectos/Espacio de trabajo personal/NetBeans/sMarketplace/Entrega 2/sMarketplace/data/products.txt",
                (Integer) request.getSession().getAttribute("firstItemNumber") - 5,
                (Integer) request.getSession().getAttribute("lastItemNumber") - 5,
                checkerCatalogue).load();
        if (checkerCatalogue.getProducts().size() > 0) {
            return true;
        }
        return false;
    }

    private void increasePage() {
        if (!canToBeIncreased()) {
            return;
        }
        request.getSession().setAttribute("firstItemNumber", (Integer) request.getSession().getAttribute("firstItemNumber") + 5);
        request.getSession().setAttribute("lastItemNumber", (Integer) request.getSession().getAttribute("lastItemNumber") + 5);
    }

    private void decreasePage() {
        if (!canToBeDecreased()) {
            return;
        }
        request.getSession().setAttribute("firstItemNumber", (Integer) request.getSession().getAttribute("firstItemNumber") - 5);
        request.getSession().setAttribute("lastItemNumber", (Integer) request.getSession().getAttribute("lastItemNumber") - 5);
    }
}


text:
import numpy
import itertools

from dagpype._core import sources
from dagpype._csv_utils import array_read as _csv_utils_array_read

__all__ = []

def _stream_chunk(reader, dtype_, max_elems, num_cols):
    s = reader.read(dtype_().itemsize * max_elems * num_cols)
    if not s:
        return None
    a = numpy.fromstring(s, dtype = dtype_)
    if num_cols > 1:
        a = a.reshape(len(a) / num_cols, num_cols)
    return a

__all__ += ['chunk_stream_bytes']
def chunk_stream_bytes(stream, max_elems = 8192, dtype = numpy.float64, num_cols = 1):
    """
    Reads a binary file containing a numpy.array, and emits a series of chunks. Each chunk
        is a numpy array with num_cols columns.

    Arguments:
        stream -- Either the name of a file or a *binary* stream.

    Keyword Arguments:
        max_elems -- Number of rows per chunk (last might have less) (default 8192).
        dtype -- Underlying element type (default numpy.float64)
        num_cols -- Number of columns in the chunks' arrays (default 1).

    See Also:
        :func:`dagpype.np.chunk_stream_vals`
        :func:`dagpype.np.chunks_to_stream_bytes`

    Example:

    >>> # Reads from a binary file, and writes the cumulative average to a different one.
    >>> np.chunk_stream_bytes('meteo.dat') | np.cum_ave() | np.chunks_to_stream_bytes('wind_ave.dat')
    5
    """

    @sources
    def _dagpype_internal_fn_act():
        assert num_cols >= 1
        assert max_elems > 0

        reader = open(stream, 'rb') if isinstance(stream, str) else stream

        while True:
            a = _stream_chunk(reader, dtype, max_elems, num_cols)
            if a is None:
                break
            yield a

        if isinstance(stream, str):
            reader.close()

    return _dagpype_internal_fn_act

__all__ += ['chunk_stream_vals']
def chunk_stream_vals(stream,
    cols,
    types_ = None,
    missing_vals = None,
    delimit = b',',
    comment = None,
    skip_init_space = True,
    max_elems = 8192):

    """
    Streams delimited (e.g., by commas for CSV files, or by tabs for TAB files) values as tuples of
        numpy.arrays.

    Arguments:
        stream -- Either the name of a file or a *binary* stream.
        cols -- Indication of which columns to read. If either an integer or a tuple of integers,
            the corresponding columns will be read. If either a string or a tuple of strings, the
            columns whose first rows have these string names (excluding the first row) will be
            read.

    Keyword Arguments:
        types_ -- Either None, a type, or a tuple of types (must correspond to cols). The read values will
            be cast to these types. If None, this is a tuple of floats.
        missing_vals -- Either None, a value, or a tuple of values (must correspond to cols). Missing values will be filled from
            this parameter. If None, this is a tuple of 0s cast to types_.
        delimit -- Delimiting binary character (default b',').
        comment -- Comment-starting binary character or ``None`` (default).
            Any character starting from this one until the line end will be ignored.
        skip_init_space -- Whether spaces starting a field will be ignored (default True).
        max_elems -- Number of rows per chunk (last might have less) (default 8192).

    See Also:
        :func:`dagpype.stream_vals`
        :func:`dagpype.np.chunk_stream_bytes`

    Examples:

    >>> # Find the correlation between two named columns.
    >>> np.chunk_stream_vals('meteo.csv', (b'day', b'wind'), (float, float), (0, 0)) | np.corr()
    0.019720323758326334
    >>> #Equivalent to:
    >>> np.chunk_stream_vals('meteo.csv', (b'day', b'wind')) | np.corr()
    0.019720323758326334

    >>> # Find the correlation between two indexed columns.
    >>> np.chunk_stream_vals('neat_data.csv', (3, 0)) | np.corr()
    -0.084075296393769511
    """

    def _is_it_t(type_):
        return isinstance(type_, list) or isinstance(type_, tuple)

    if types_ is None:
        types_ = tuple(float for _ in cols) if _is_it_t(cols) else float
    if missing_vals is None:
        missing_vals = tuple(type_(0) for type_ in types_) if _is_it_t(types_) else types_(0)
    @sources
    def _dagpype_internal_fn_act():
        assert max_elems > 0

        stream_ = open(stream, 'rb') if isinstance(stream, str) else stream

        for t in _csv_utils_array_read(stream_, cols, types_, missing_vals, delimit, comment, skip_init_space, max_elems):
            yield t

        if isinstance(stream, str):
            stream_.close()

    return _dagpype_internal_fn_act

__all__ += ['chunk_source']
def chunk_source(seq, max_elems = 1024):
    """
    Streams stream elements as lists.

    Arguments:
        seq -- Some sequence.

    Keyword Arguments:
        max_elems -- Number of rows per chunk (last might have less) (default 1024).

    See Also:
        :func:`dagpype.source`
    """

    @sources
    def _dagpype_internal_fn_act():
        def _next_batch(it):
            return [l for l in itertools.islice(it, max_elems)]

        it = iter(seq)
        items = _next_batch(it)
        while items:
            yield items
            items = _next_batch(it)

    return _dagpype_internal_fn_act

redpajama_set_name: RedPajamaGithub


text:
define('view', ['moduleLoaderUtils'], function (utils) {
	'use strict';

	return {
		normalize: function(name, normalize){
			return utils.normalizeInsider(name, normalize, 'view');
		},
		load: function (name, req, onload) {
			req([name], function (value) {
				onload(value);
			});
		}
	};
});


text:
/** Image Annotation Grid Class

    This is where most of the action happens:
    this class tracks/edits which Annotation Texts are connected to areas of the image.
    It requires a Image Event Handler, an Annotation Text Manager,
    and an Annotation Text Displayer be provided in the constructor.

    Rules:
    - A Source Code Line Manager, an Annotation Text Manager, and an
      Annotation Text Displayer must be provided in the constructor
*/

var HORIZONTAL_SCROLLBAR_COMPENSATION = 21;
var VERTICAL_SCROLLBAR_COMPENSATION   = 4;

function ImageAnnotationGrid(image_event_handler, annotation_text_manager, annotation_text_displayer) {
  this.image_event_handler       = image_event_handler;
  this.annotation_text_manager   = annotation_text_manager;
  this.annotation_text_displayer = annotation_text_displayer;

  this.process_grid();
  this.share_grid_with_event_handler();
  this.draw_holders();

  image_event_handler.init_listeners(document.getElementById('enable_annotations?').value);
  document.getElementById('codeviewer').onmousemove = this.draw_holders.bind(this);
}

ImageAnnotationGrid.prototype.getAnnotationTextManager = function() {
  return this.annotation_text_manager;
}

ImageAnnotationGrid.prototype.getImageEventHandler = function() {
  return this.image_event_handler;
}

ImageAnnotationGrid.prototype.getAnnotationTextDisplayer = function() {
  return this.annotation_text_displayer;
}

ImageAnnotationGrid.prototype.get_annotation_grid = function() {
  return this.annotation_grid;
}

ImageAnnotationGrid.prototype.process_grid = function() {
  this.annotation_grid = JSON.parse(document.getElementById('annotation_grid').value);
  var annot_grid = this.get_annotation_grid();
}

ImageAnnotationGrid.prototype.draw_holders = function() {
  var annot_grid = this.get_annotation_grid();
  var holder, annot_text_id, horiz_range, vert_range, holder_width,
      holder_height, holder_left, holder_top;

  // Edges of the image
  var image_preview   = document.getElementById('image_preview');
  var image_container = document.getElementById('image_container');
  var codeviewer      = document.getElementById('codeviewer');

  var top_edge    = image_preview.offsetTop + codeviewer.scrollTop;
  var left_edge   = image_preview.offsetLeft + image_container.scrollLeft;
  var right_edge  = image_preview.offsetLeft + image_container.scrollLeft + codeviewer.offsetWidth;
  var bottom_edge = image_preview.offsetTop + codeviewer.scrollTop + codeviewer.offsetHeight;

  for (var i = 0; i < annot_grid.length; i++) {
    var grid_element = annot_grid[i];

    annot_text_id = grid_element.id;
    horiz_range   = grid_element.x_range;
    vert_range    = grid_element.y_range;
    holder = document.getElementById('annotation_holder_' + annot_text_id);

    // Left offset of the holder
    holder_left = image_preview.offsetLeft + parseInt(horiz_range.start, 10);
    // Top offset of the holder
    holder_top  = image_preview.offsetTop + parseInt(vert_range.start, 10);

    holder_width  = parseInt(horiz_range.end, 10) - parseInt(horiz_range.start, 10);
    holder_height = parseInt(vert_range.end, 10) - parseInt(vert_range.start, 10);

    holder.style.left = Math.max(0, holder_left - left_edge) + image_preview.offsetLeft + 'px';
    holder.style.top  = Math.max(0, holder_top - top_edge) + image_preview.offsetTop + 'px';

    if (holder_left > right_edge || holder_top > bottom_edge || holder_left + holder_width < left_edge ||
        holder_top + holder_height < top_edge) {
      // Draw nothing, as holder is out of bounds of codeviewer
      holder.style.display = 'none';
    } else {
      // Holder within codeviewer, draw as much of it as fits.
      holder.style.display = 'block';
      holder.style.width  = Math.min(Math.min(holder_width, (holder_left + holder_width) - left_edge),
                                     right_edge - holder_left - VERTICAL_SCROLLBAR_COMPENSATION) + 'px';
      holder.style.height = Math.min(Math.min(holder_height, (holder_top + holder_height) - top_edge),
                                     bottom_edge - holder_top - HORIZONTAL_SCROLLBAR_COMPENSATION) + 'px';
    }
  }
}

ImageAnnotationGrid.prototype.add_to_grid = function(extracted_coords) {
  // extracted_coords.x_range = { start: extracted_coords.x_range.start, end: extracted_coords.x_range.end };
  // extracted_coords.y_range = { start: extracted_coords.y_range.start, end: extracted_coords.y_range.end };

  this.annotation_grid.push(extracted_coords);
  this.share_grid_with_event_handler();

  var new_holder = document.createElement('div');
  new_holder.id = 'annotation_holder_' + extracted_coords.id;
  new_holder.addClass('annotation_holder');
  new_holder.onmousemove = this.getImageEventHandler().check_for_annotations.bind(this.getImageEventHandler());
  new_holder.onmousedown = this.getImageEventHandler().start_select_box.bind(this.getImageEventHandler());

  var image_preview = document.getElementById('image_preview');
  image_preview.parentNode.insertBefore(new_holder, image_preview);

  this.draw_holders();
}

ImageAnnotationGrid.prototype.remove_annotation = function(unused_param1, unused_param2, annotation_text_id) {
  if (this.getAnnotationTextManager().annotationTextExists(annotation_text_id)) {
    this.getAnnotationTextManager().removeAnnotationText(annotation_text_id);
    var holder = document.getElementById('annotation_holder_' + annotation_text_id);
    if (holder != null) {
      holder.parentElement.removeChild(holder);
    }
  }

  var annot_grid = this.get_annotation_grid();
  for (var i = 0; i < annot_grid.length; i++) {
    if (annot_grid[i].id == annotation_text_id) {
      annot_grid.splice(i, 1);
      break;
    }
  }
  this.share_grid_with_event_handler();
}

ImageAnnotationGrid.prototype.registerAnnotationText = function(annotation_text) {
  // If the Annotation Text is already in the manager, we don't need to re-add it
  if (this.getAnnotationTextManager().annotationTextExists(annotation_text.getId())) {
    return;
  }

  this.getAnnotationTextManager().addAnnotationText(annotation_text);
}

// Call this any time the annotation_grid gets modified
ImageAnnotationGrid.prototype.share_grid_with_event_handler = function() {
  this.getImageEventHandler().set_annotation_grid(this.annotation_grid);
}

// Display the text associated with the annotation text id's inside annots_to_display.
// annots_to_display is an array of annotation text ids, and x and y are the
// coordinates relative to the page where the display box should pop up.
ImageAnnotationGrid.prototype.display_image_annotation = function(annots_to_display, x, y) {
  var collection = [];
  for (var i = 0; i < annots_to_display.length; i++) {
    collection.push(this.getAnnotationTextManager().getAnnotationText(annots_to_display[i]));
  }
  this.getAnnotationTextDisplayer().displayCollection(collection, x, y);
}


text:
#pragma once
#include <aws/globalaccelerator/GlobalAccelerator_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/globalaccelerator/model/Listener.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace GlobalAccelerator
{
namespace Model
{
  class AWS_GLOBALACCELERATOR_API ListListenersResult
  {
  public:
    ListListenersResult();
    ListListenersResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListListenersResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The list of listeners for an accelerator.

     */
    inline const Aws::Vector<Listener>& GetListeners() const{ return m_listeners; }

    /**
     *
The list of listeners for an accelerator.

     */
    inline void SetListeners(const Aws::Vector<Listener>& value) { m_listeners = value; }

    /**
     *
The list of listeners for an accelerator.

     */
    inline void SetListeners(Aws::Vector<Listener>&& value) { m_listeners = std::move(value); }

    /**
     *
The list of listeners for an accelerator.

     */
    inline ListListenersResult& WithListeners(const Aws::Vector<Listener>& value) { SetListeners(value); return *this;}

    /**
     *
The list of listeners for an accelerator.

     */
    inline ListListenersResult& WithListeners(Aws::Vector<Listener>&& value) { SetListeners(std::move(value)); return *this;}

    /**
     *
The list of listeners for an accelerator.

     */
    inline ListListenersResult& AddListeners(const Listener& value) { m_listeners.push_back(value); return *this; }

    /**
     *
The list of listeners for an accelerator.

     */
    inline ListListenersResult& AddListeners(Listener&& value) { m_listeners.push_back(std::move(value)); return *this; }

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline ListListenersResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline ListListenersResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token for the next set of results. You receive this token from a previous
     * call.

     */
    inline ListListenersResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Listener> m_listeners;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace GlobalAccelerator
} // namespace Aws


text:
import {Component, OnDestroy, OnInit, TemplateRef} from '@angular/core';
import {Utils} from '../../../../../common/Utils';
import {GalleryService} from '../gallery.service';
import {ContentWrapper} from '../../../../../common/entities/ConentWrapper';
import {Config} from '../../../../../common/config/public/Config';
import {NotificationService} from '../../../model/notification.service';
import {DirectoryDTO} from '../../../../../common/entities/DirectoryDTO';
import {I18n} from '@ngx-translate/i18n-polyfill';
import {BsModalService} from 'ngx-bootstrap/modal';
import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service';
import {OrientationType, RandomQueryDTO} from '../../../../../common/entities/RandomQueryDTO';
import {NetworkService} from '../../../model/network/network.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-gallery-random-query-builder',
  templateUrl: './random-query-builder.gallery.component.html',
  styleUrls: ['./random-query-builder.gallery.component.css'],
})
export class RandomQueryBuilderGalleryComponent implements OnInit, OnDestroy {

  enabled = true;
  url = '';

  data: RandomQueryDTO = {
    orientation: OrientationType.any,
    directory: '',
    recursive: true,
    minResolution: null,
    maxResolution: null,
    toDate: null,
    fromDate: null
  };
  contentSubscription: Subscription = null;

  readonly OrientationType: typeof OrientationType;
  modalRef: BsModalRef;

  text = {
    Yes: 'Yes',
    No: 'No'
  };

  constructor(public _galleryService: GalleryService,
              private  _notification: NotificationService,
              public i18n: I18n,
              private modalService: BsModalService) {
    this.OrientationType = OrientationType;
    this.text.Yes = i18n('Yes');
    this.text.No = i18n('No');
  }

  ngOnInit() {
    this.contentSubscription = this._galleryService.content.subscribe((content: ContentWrapper) => {
      this.enabled = !!content.directory;
      if (!this.enabled) {
        return;
      }
      this.data.directory = Utils.concatUrls((<DirectoryDTO>content.directory).path, (<DirectoryDTO>content.directory).name);
    });
  }

  ngOnDestroy() {
    if (this.contentSubscription !== null) {
      this.contentSubscription.unsubscribe();
    }
  }

  update() {
    setTimeout(() => {
      const data = Utils.clone(this.data);
      for (const key of Object.keys(data)) {
        if (!(<any>data)[key]) {
          delete (<any>data)[key];
        }
      }
      this.url = NetworkService.buildUrl(Config.Client.publicUrl + '/api/gallery/random/', data);
    }, 0);
  }

  openModal(template: TemplateRef<any>) {
    if (!this.enabled) {
      return;
    }
    if (this.modalRef) {
      this.modalRef.hide();
    }
    this.modalRef = this.modalService.show(template);
    document.body.style.paddingRight = '0px';
    this.update();
    return false;
  }

  onCopy() {
    this._notification.success(this.i18n('Url has been copied to clipboard'));
  }

  public hideModal() {
    this.modalRef.hide();
    this.modalRef = null;
  }

}


text:
package org.killbill.billing.invoice.model;

import java.math.BigDecimal;
import java.util.UUID;

import javax.annotation.Nullable;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.util.UUIDs;

import com.google.common.base.MoreObjects;

public class ItemAdjInvoiceItem extends AdjInvoiceItem {

    public ItemAdjInvoiceItem(final InvoiceItem linkedInvoiceItem, final LocalDate effectiveDate,
                              final BigDecimal amount, final Currency currency) {
        this(UUIDs.randomUUID(), null, linkedInvoiceItem.getInvoiceId(), linkedInvoiceItem.getAccountId(), effectiveDate,
             linkedInvoiceItem.getDescription(), amount, currency, linkedInvoiceItem.getId(), null);
    }

    public ItemAdjInvoiceItem(final UUID id, @Nullable final DateTime createdDate, final UUID invoiceId, final UUID accountId, final LocalDate startDate,
                              @Nullable final String description, final BigDecimal amount, final Currency currency, final UUID linkedItemId, @Nullable final String itemDetails) {
        super(id, createdDate, invoiceId, accountId, startDate, startDate, description, amount, currency, linkedItemId, itemDetails, InvoiceItemType.ITEM_ADJ);
    }

    public ItemAdjInvoiceItem(final UUID id, @Nullable final DateTime createdDate, final UUID invoiceId, final UUID accountId, final LocalDate startDate,
                              @Nullable final String description, final BigDecimal amount, @Nullable final BigDecimal rate, final Currency currency, final UUID linkedItemId, @Nullable final Integer quantity, @Nullable final String itemDetails) {
        super(id, createdDate, invoiceId, accountId, startDate, startDate, description, amount, rate, currency, linkedItemId, quantity, itemDetails, InvoiceItemType.ITEM_ADJ);
    }

    @Override
    public String getDescription() {
        return MoreObjects.firstNonNull(description, "Invoice item adjustment");
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, minimal-ui">
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="../../css/style.css">
    <title>Help</title>

Help

This is a placeholder page / dummy file for the Help  navigation link.
        The purpose of this page is simply to show an example of using a link in a breadcrumb trail. Close this Window to return to the G71 Example 1.


text:
"""Integrated collection of utilities that assist in internationalizing and
localizing applications.

This package is basically composed of two major parts:

 * tools to build and work with ``gettext`` message catalogs
 * a Python interface to the CLDR (Common Locale Data Repository), providing
   access to various locale display names, localized number and date
   formatting, etc.

:see: http://www.gnu.org/software/gettext/
:see: http://docs.python.org/lib/module-gettext.html
:see: http://www.unicode.org/cldr/
"""

from babel.core import *

__docformat__ = 'restructuredtext en'
try:
    from pkg_resources import get_distribution, ResolutionError
    try:
        __version__ = get_distribution('Babel').version
    except ResolutionError:
        __version__ = None # unknown
except ImportError:
    __version__ = None # unknown


text:
/*!
 * numbro.js language configuration
 * language : Italian
 * locale: Switzerland
 * author : Tim McIntosh (StayinFront NZ)
 */
(function(){"use strict";var a={langLocaleCode:"it-CH",cultureCode:"it-CH",delimiters:{thousands:"'",decimal:"."},abbreviations:{thousand:"mila",million:"mil",billion:"b",trillion:"t"},ordinal:function(){return"°"},currency:{symbol:"CHF",code:"CHF"}};
// Node
"undefined"!=typeof module&&module.exports&&(module.exports=a),
// Browser
"undefined"!=typeof window&&window.numbro&&window.numbro.culture&&window.numbro.culture("it-CH",a)}).call("undefined"==typeof window?this:window);


text:
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Rush
{
	internal class BroadcastSender<T> : ISendingStream<T>
	{
		private readonly IEnumerable<ISendingChannel<T>> _channels;
		private readonly ILogger<BroadcastSender<T>> _logger;

		public BroadcastSender(IEnumerable<ISendingChannel<T>> channels, ILogger<BroadcastSender<T>> logger)
		{
			_channels = channels;
			_logger = logger;
		}

		public Task SendAsync(T message) => SendAsync(message, CancellationToken.None);

		public Task SendAsync(T message, CancellationToken cancellationToken)
		{
			if (message == null) throw new ArgumentNullException(nameof(message));

			_logger.LogInformation($"Sending message of type {typeof(T)}.");
			return Send(message, cancellationToken);
		}

		private Task Send(T message, CancellationToken cancellationToken)
		{
			var sends = new List<Task<bool>>();

			foreach (var channel in _channels)
				sends.Add(SendToChannel(message, channel, cancellationToken));

			return Task.WhenAll(sends).ContinueWith(tasks =>
			{
				if (tasks.Result.All(sent => !sent))
					throw new InvalidOperationException("There are no operational message channels.");
			}, cancellationToken);
		}

		private async Task<bool> SendToChannel(T message, ISendingChannel<T> channel, CancellationToken cancellationToken)
		{
			if (!channel.Operational)
				return false;

			try
			{
				await channel.SendAsync(message, cancellationToken).ConfigureAwait(false);
				return true;
			}
			catch (Exception ex) when (ex.GetType() != typeof(OperationCanceledException))
			{
				_logger.LogWarning($"Operational channel faulted when sending message of type {typeof(T)}.", ex);
				return await SendToChannel(message, channel, cancellationToken).ConfigureAwait(false);
			}
		}
	}
}


text:
<link rel="import" href="../polymer/polymer.html">

<dom-module id="chops-tree-status">
  <template>

      Error fetching tree status from [[statusUrl]]

      Tree status: [[_message]] by
      [[_username]]
      on [[_time]]
      (More)

  </template>

</dom-module>


text:
using System;
using System.Text.RegularExpressions;

class ExtractInSentance
{
    //Write a program that extracts from a given text all sentences containing given word.
    //Example: The word is "in". The text is:
    //We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight.
    //So we are drinking all the day. We will move out of it in 5 days.
    //The expected result is:
    //We are living in a yellow submarine.
    //We will move out of it in 5 days.
    //Consider that the sentences are separated by "." and the words – by non-letter symbols.

    static void Main()
    {
        string text = @"We are living in a yellow submarine. We don't have anything else.
            Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";

        string[] sentences = text.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < sentences.Length; i++)
        {
            if (Regex.IsMatch(sentences[i], @"\bin\b"))
            {
                Console.WriteLine(sentences[i].Trim() + ".");
            }
        }
    }
}


text:
.class public Ljc;
.super Ljava/lang/Object;
.source "SourceFile"

# interfaces
.implements Landroid/view/View$OnTouchListener;

# instance fields
.field final synthetic a:Lnet/londatiga/android/PopupWindows;

# direct methods
.method public constructor <init>(Lnet/londatiga/android/PopupWindows;)V
    .registers 2
    .parameter

    .prologue
    .line 1
    iput-object p1, p0, Ljc;->a:Lnet/londatiga/android/PopupWindows;

    .line 37
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onTouch(Landroid/view/View;Landroid/view/MotionEvent;)Z
    .registers 5
    .parameter
    .parameter

    .prologue
    .line 40
    invoke-virtual {p2}, Landroid/view/MotionEvent;->getAction()I

    move-result v0

    const/4 v1, 0x4

    if-ne v0, v1, :cond_10

    .line 41
    iget-object v0, p0, Ljc;->a:Lnet/londatiga/android/PopupWindows;

    iget-object v0, v0, Lnet/londatiga/android/PopupWindows;->mWindow:Landroid/widget/PopupWindow;

    invoke-virtual {v0}, Landroid/widget/PopupWindow;->dismiss()V

    .line 43
    const/4 v0, 0x1

    .line 46
    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method


text:
/* eslint-env node */
'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  const options = {
    vendorFiles: { 'jquery.js': null }
  };

  const app = new EmberAddon(defaults, options);

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};


text:
import React, { Component, PropTypes } from 'react';
import {
  isLoaded as isLoadedQuestions,
  load as loadQuestions } from 'redux/modules/questions';
import {
  isLoaded as isLoadedAnswers,
  load as loadAnswers,
  storeAnswer } from 'redux/modules/answers';
import { Carcas, QuestionInformation, Buttons } from '..';
import { pushState } from 'redux-router';
import { connect } from 'react-redux';

@connect(
  state => ({
    questions: state.questions.questions,
    answers: state.answers
  }),
  {pushState, isLoadedQuestions, loadQuestions,
   storeAnswer, isLoadedAnswers, loadAnswers })
export default class Question extends Component {

  static propTypes = {
    params: PropTypes.object,
    questions: PropTypes.object,
    answers: PropTypes.object,
    pushState: PropTypes.func.isRequired,
    storeAnswer: PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);
    this.state = this.constructParams(props);
  }

  componentDidMount() {
    this.changeQuestion();
    this.refs.carcas.showLine();
  }

  componentWillReceiveProps(nextProps) {
    if (parseInt(nextProps.params.questionId, 10) - 1 !== this.state.questionId) {
      this.lock = false;
      this.setState(this.constructParams(nextProps), () => {
        this.changeQuestion();
      });
    } else {
      const questionId = parseInt(nextProps.params.questionId, 10) - 1;
      const answer = nextProps.answers &&
                     nextProps.answers.answers &&
                     nextProps.answers.answers[questionId];
      this.setState({
        answer: answer
      });
    }
  }

  constructParams(props) {
    const { questions } = props;
    const questionId = parseInt(props.params.questionId, 10) - 1;
    const questionsCount = questions.count;
    const question = questions[questionId];
    const back = props.params.back && true;
    const prevQuestion = questionId > 0 && questions[questionId - 1];
    const prev = prevQuestion && questionId;
    const nextQuestion = questionsCount - 1 > questionId && questions[questionId + 1];
    const next = nextQuestion && questionId + 2;
    const answer = props.answers &&
                   props.answers.answers &&
                   props.answers.answers[questionId];
    return {
      questionsCount, questionId, question, next,
      nextQuestion, prev, prevQuestion, back, answer
    };
  }

  changeQuestion() {
    if (window) {
      ga('send', 'event', 'question', 'question_' + this.props.params.questionId); // eslint-disable-line
    }
    const { carcas } = this.refs;
    const { question, questionId, back, nextQuestion } = this.state;
    const topOfLine = question.firstOfType ?
      carcas.hideTopOfLine() :
      carcas.showTopOfLine();
    const bottomOfLine = !nextQuestion || nextQuestion.firstOfType ?
      carcas.hideBottomOfLine() :
      carcas.showBottomOfLine();
    const animation = back ?
      carcas.topToCenter() :
      carcas.bottomToCenter();
    carcas.setLineColor(question.color, 200);
    carcas.setBackgroundClass(questionId);
    carcas.showLine();
    return { topOfLine, bottomOfLine, animation };
  }

  static fetchData(getState, dispatch) {
    const promises = [];
    if (!isLoadedQuestions(getState())) {
      promises.push(dispatch(loadQuestions()));
    }
    if (!isLoadedAnswers(getState())) {
      promises.push(dispatch(loadAnswers()));
    }
    return Promise.all(promises);
  }

  storeValue(value) {
    const storedVal = value === 0 ? 'no' : 'yes';
    this.props.storeAnswer({
      id: this.state.questionId,
      value: storedVal
    });
  }

  handleButtonWithTimeout(button) {
    this.storeValue(button);
    setTimeout(() => {
      this.handleButton();
    }, 300);
  }

  handleButton() {
    const { carcas } = this.refs;
    const { next, nextQuestion } = this.state;
    if (next) {
      if (nextQuestion && nextQuestion.firstOfType) {
        carcas.setLineColor('transparent', 0);
        carcas.animateToTop(
          () => this.props.pushState(null, '/subresults/' + next)
        );
      } else {
        carcas.animateToTop(
          () => this.props.pushState(null, '/questions/' + next)
        );
      }
    } else {
      carcas.animateToTop(
        () => this.props.pushState(null, '/name')
      );
    }
  }

  handleBack() {
    if (!this.lock) {
      this.lock = true;
      const { carcas } = this.refs;
      const { question, prev } = this.state;
      if (this.state.prev) {
        if (question.firstOfType) {
          carcas.setLineColor('transparent', 0);
        }
        carcas.animateToBottom(
          () => this.props.pushState(null, '/questions/' + prev + '/back')
        );
      }
    }
  }

  handleWheel(event) {
    const { answer } = this.state;
    if (event.deltaY < -100) {
      this.handleBack();
    }
    if (event.deltaY > 100 && answer) {
      this.handleButton();
    }
  }

  render() {
    const { question, questionsCount, prev, answer } = this.state;
    const backId = this.state.questionId - 1;

    return (
      <Carcas ref="carcas" backId = {backId}>
        <div onWheel={::this.handleWheel}>
          <QuestionInformation
            handleBack={::this.handleBack}
            handleNext={::this.handleButton}
            back={prev}
            next={answer}
            questionsCount={questionsCount}
            {...question}
          />
          <Buttons
            answer={answer}
            handleYes={::this.handleButtonWithTimeout}
            handleNo={::this.handleButtonWithTimeout}
          />
        </div>
      </Carcas>
    );
  }

}


text:
<?php

namespace Customize\View\Helper;

use Zend\ServiceManager\AbstractPluginManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ActiveFactory implements FactoryInterface
{

    /**
     * @param ServiceLocatorInterface|AbstractPluginManager $serviceLocator
     * @return Active
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @noinspection PhpParamsInspection */
        return new Active(
            $serviceLocator->getServiceLocator()->get('router'),
            $serviceLocator->getServiceLocator()->get('request')
        );
    }

}


text:
<?php

  namespace ReportHacker;

  use pocketmine\plugin\PluginBase;
  use pocketmine\event\Listener;
  use pocketmine\utils\TextFormat as TF;
  use pocketmine\Player;
  use pocketmine\command\Command;
  use pocketmine\command\CommandSender;

  class Main extends PluginBase implements Listener {

    public function onEnable() {

      $this->getServer()->getPluginManager()->registerEvents($this, $this);

    }

    public function onCommand(CommandSender $sender, Command $cmd, $label, array $args) {

      if(strtolower($cmd->getName()) === "reporthacker") {

        if(!(isset($args[0]))) {

          $sender->sendMessage(TF::RED . "Error: not enough args. Usage: /reporthacker <player>");

          return true;

        } else {

          $sender_name = $sender->getName();

          $sender_display_name = $sender->getDisplayName();

          $name = $args[0];

          $player = $this->getServer()->getPlayer($name);

          if($player === null) {

            foreach($this->getServer()->getOnlinePlayers() as $p) {

              if($p->isOp()) {

                $p->sendMessage(TF::YELLOW . $sender_name . " reported " . $name . " for using hacks/mods!");

              }

            }

            $sender->sendMessage(TF::GREEN . "Sent report to all op(s).");

            return true;

          } else {

            foreach($this->getServer()->getOnlinePlayers() as $p) {

              if($p->isOp()) {

                $p->sendMessage(TF::YELLOW . $sender_name . " reported " . $name . " for using hacks/mods!");

              }

            }

            $player->sendMessage(TF::YELLOW . $sender_name . " has reported you for using hacks/mods!");

            $sender->sendMessage(TF::GREEN . "Sent report to all op(s).");

            return true;

          }

        }

      }

    }

  }

?>


text:
The time resource allows an application to read the current EVE time with 10 second precision.

### Route
`/time/`

### GET
- Cache: 10 seconds

```json
{
  "time": "2016-06-06T22:00:00"
}
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Toth</title>

    <link href="css/base.css" rel="stylesheet">
    <link href="tools/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

Odontograma

                                        <input type="radio" name="options" id="option1" autocomplete="off" checked>Fractura

                                        <input type="radio" name="options" id="option2" autocomplete="off"> Obturación

                                        <input type="radio" name="options" id="option3" autocomplete="off"> Extracción

                                        <input type="radio" name="options" id="option4" autocomplete="off"> A Extraer

                                        <input type="radio" name="options" id="option5" autocomplete="off"> Puente

                                        <input type="radio" name="options" id="option6" autocomplete="off"> Borrar

 = Fractura/Carie

 = Puente Entre Piezas

 = Obturación

                                     Pieza Extraída =

 Idicada Para Extracción =


text:
require("requirish")._(module);

var deprecated_trim = function (str) {
    return str.replace(/^\s+|\s+$/g, "");
};

function inlineText(f) {

    var k = f.toString().
        replace(/^[^\/]+\/\*!?/, '').
        replace(/\*\/[^\/]+$/, '');
    k = k.split("\n").map(function(t){  t = t.trim(); return t; }).join("\n");
    return k;
}
var makebuffer = require("lib/misc/utils").makebuffer;

var hexString = function (str) {

    var hexline = "";
    var lines = str.split("\n");
    lines.forEach(function (line) {

        line = line.trim();
        if (line.length > 80) {
            line = line.substr(10, 98).trim();
            hexline = hexline ? hexline + " " + line : line;
        } else if (line.length > 60) {
            line = line.substr(7, 48).trim();
            hexline = hexline ? hexline + " " + line : line;
        }
    });
    return hexline;
};

function makebuffer_from_trace(func) {
    return makebuffer(hexString(inlineText(func)));
}
exports.inlineText = inlineText;
exports.makebuffer_from_trace = makebuffer_from_trace;


text:
<?xml version="1.0"?>
<!--
  set de
  -> install locale(de) packages
-->
<test>
<setup>
  <channel name="beta52" file="beta52-i386-packages.xml.gz"/>
  <locale name="de_DE"/>
</setup>
<trial>
  <install channel="beta52" name="OpenOffice_org"/>
</trial>
</test>


text:
using System;
using System.Linq;
using System.Text;
using Eto.Drawing;
using Eto.Forms;
using swi = Windows.UI.Xaml.Input;
using swm = Windows.UI.Xaml.Media;
using wf = Windows.Foundation;
using sw = Windows.UI.Xaml;
//using sp = System.Printing;
using swc = Windows.UI.Xaml.Controls;
using swmi = Windows.UI.Xaml.Media.Imaging;
using wu = Windows.UI;
using wuc = Windows.UI.Core;
using wut = Windows.UI.Text;
using System.Text.RegularExpressions;
using Eto.Direct2D.Drawing;
//using Eto.WinRT.Drawing;

namespace Eto.WinRT
{
	/// <summary>
	/// Xaml conversions.
	/// </summary>
	/// <copyright>(c) 2014 by Vivek Jhaveri</copyright>
	/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
	/// <license type="BSD-3">See LICENSE for full terms</license>
	public static partial class Conversions
	{
		public const float WheelDelta = 120f;

		public static readonly wf.Size PositiveInfinitySize = new wf.Size(double.PositiveInfinity, double.PositiveInfinity);
		public static readonly wf.Size ZeroSize = new wf.Size(0, 0);

		public static wu.Color ToWpf(this Color value)
		{

			return wu.Color.FromArgb((byte)(value.A * byte.MaxValue), (byte)(value.R * byte.MaxValue), (byte)(value.G * byte.MaxValue), (byte)(value.B * byte.MaxValue));
		}

		public static swm.Brush ToWpfBrush(this Color value, swm.Brush brush = null)
		{
			var solidBrush = brush as swm.SolidColorBrush;
			if (solidBrush == null
#if TODO_XAML
				|| solidBrush.IsSealed
#endif
				)
			{
				solidBrush = new swm.SolidColorBrush();
			}
			solidBrush.Color = value.ToWpf();
			return solidBrush;
		}

		public static Color ToEto(this wu.Color value)
		{
			return new Color { A = value.A / 255f, R = value.R / 255f, G = value.G / 255f, B = value.B / 255f };
		}

		public static Color ToEtoColor(this swm.Brush brush)
		{
			var solidBrush = brush as swm.SolidColorBrush;
			if (solidBrush != null)
				return solidBrush.Color.ToEto();
			return Colors.Transparent;
		}

		public static Padding ToEto(this sw.Thickness value)
		{
			return new Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom);
		}

		public static sw.Thickness ToWpf(this Padding value)
		{
			return new sw.Thickness(value.Left, value.Top, value.Right, value.Bottom);
		}

		public static Rectangle ToEto(this wf.Rect value)
		{
			return new Rectangle((int)value.X, (int)value.Y, (int)value.Width, (int)value.Height);
		}

		public static RectangleF ToEtoF(this wf.Rect value)
		{
			return new RectangleF((float)value.X, (float)value.Y, (float)value.Width, (float)value.Height);
		}

		public static wf.Rect ToWpf(this Rectangle value)
		{
			return new wf.Rect(value.X, value.Y, value.Width, value.Height);
		}

#if TODO_XAML
		public static sw.Int32Rect ToWpfInt32(this Rectangle value)
		{
			return new sw.Int32Rect(value.X, value.Y, value.Width, value.Height);
		}
#endif

		public static wf.Rect ToWpf(this RectangleF value)
		{
			return new wf.Rect(value.X, value.Y, value.Width, value.Height);
		}

		public static SizeF ToEto(this wf.Size value)
		{
			return new SizeF((float)value.Width, (float)value.Height);
		}

		public static Size ToEtoSize(this wf.Size value)
		{
			return new Size((int)(double.IsNaN(value.Width) ? -1 : value.Width), (int)(double.IsNaN(value.Height) ? -1 : value.Height));
		}

		public static wf.Size ToWpf(this Size value)
		{
			return new wf.Size(value.Width == -1 ? double.NaN : value.Width, value.Height == -1 ? double.NaN : value.Height);
		}

		public static wf.Size ToWpf(this SizeF value)
		{
			return new wf.Size(value.Width, value.Height);
		}

		public static PointF ToEto(this wf.Point value)
		{
			return new PointF((float)value.X, (float)value.Y);
		}

		public static Point ToEtoPoint(this wf.Point value)
		{
			return new Point((int)value.X, (int)value.Y);
		}

		public static wf.Point ToWpf(this Point value)
		{
			return new wf.Point(value.X, value.Y);
		}

		public static wf.Point ToWpf(this PointF value)
		{
			return new wf.Point(value.X, value.Y);
		}

		public static string ToWpfMneumonic(this string value)
		{
			if (value == null)
				return string.Empty;
			value = value.Replace("_", "__");
			var match = Regex.Match(value, @"(?<=([^&](?:[&]{2})*)|^)[&](?![&])");
			if (match.Success)
			{
				var sb = new StringBuilder(value);
				sb[match.Index] = '_';
				sb.Replace("&&", "&");
				return sb.ToString();
			}
			return value.Replace("&&", "&");
		}

		public static string ToEtoMneumonic(this string value)
		{
			if (value == null)
				return null;
			var match = Regex.Match(value, @"(?<=([^_](?:[_]{2})*)|^)[_](?![_])");
			if (match.Success)
			{
				var sb = new StringBuilder(value);
				sb[match.Index] = '&';
				sb.Replace("__", "_");
				return sb.ToString();
			}
			value = value.Replace("__", "_");
			return value;
		}

#if TODO_XAML
		public static KeyEventArgs ToEto(this wuc.KeyEventArgs e, KeyEventType keyType)
		{
			var key = KeyMap.Convert(e.Key, swi.Keyboard.Modifiers);
			return new KeyEventArgs(key, keyType) { Handled = e.Handled };
		}
#endif

#if TODO_XAML
		public static MouseEventArgs ToEto(this swi.MouseButtonEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed)
		{
			var buttons = MouseButtons.None;
			if (e.ChangedButton == swi.MouseButton.Left && e.LeftButton == buttonState)
				buttons |= MouseButtons.Primary;
			if (e.ChangedButton == swi.MouseButton.Right && e.RightButton == buttonState)
				buttons |= MouseButtons.Alternate;
			if (e.ChangedButton == swi.MouseButton.Middle && e.MiddleButton == buttonState)
				buttons |= MouseButtons.Middle;
			var modifiers = Keys.None;
			var location = e.GetPosition(control).ToEto();

			return new MouseEventArgs(buttons, modifiers, location);
		}

		public static MouseEventArgs ToEto(this swi.MouseEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed)
		{
			var buttons = MouseButtons.None;
			if (e.LeftButton == buttonState)
				buttons |= MouseButtons.Primary;
			if (e.RightButton == buttonState)
				buttons |= MouseButtons.Alternate;
			if (e.MiddleButton == buttonState)
				buttons |= MouseButtons.Middle;
			var modifiers = Keys.None;
			var location = e.GetPosition(control).ToEto();

			return new MouseEventArgs(buttons, modifiers, location);
		}

		public static MouseEventArgs ToEto(this swi.MouseWheelEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed)
		{
			var buttons = MouseButtons.None;
			if (e.LeftButton == buttonState)
				buttons |= MouseButtons.Primary;
			if (e.RightButton == buttonState)
				buttons |= MouseButtons.Alternate;
			if (e.MiddleButton == buttonState)
				buttons |= MouseButtons.Middle;
			var modifiers = Keys.None;
			var location = e.GetPosition(control).ToEto();
			var delta = new SizeF(0, (float)e.Delta / WheelDelta);

			return new MouseEventArgs(buttons, modifiers, location, delta);
		}
#endif

#if TODO_XAML
		public static swm.BitmapScalingMode ToWpf(this ImageInterpolation value)
		{
			switch (value)
			{
				case ImageInterpolation.Default:
					return swm.BitmapScalingMode.Unspecified;
				case ImageInterpolation.None:
					return swm.BitmapScalingMode.NearestNeighbor;
				case ImageInterpolation.Low:
					return swm.BitmapScalingMode.LowQuality;
				case ImageInterpolation.Medium:
					return swm.BitmapScalingMode.HighQuality;
				case ImageInterpolation.High:
					return swm.BitmapScalingMode.HighQuality;
				default:
					throw new NotSupportedException();
			}
		}

		public static ImageInterpolation ToEto(this swm.BitmapScalingMode value)
		{
			switch (value)
			{
				case swm.BitmapScalingMode.HighQuality:
					return ImageInterpolation.High;
				case swm.BitmapScalingMode.LowQuality:
					return ImageInterpolation.Low;
				case swm.BitmapScalingMode.NearestNeighbor:
					return ImageInterpolation.None;
				case swm.BitmapScalingMode.Unspecified:
					return ImageInterpolation.Default;
				default:
					throw new NotSupportedException();
			}
		}

		public static sp.PageOrientation ToSP(this PageOrientation value)
		{
			switch (value)
			{
				case PageOrientation.Portrait:
					return sp.PageOrientation.Portrait;
				case PageOrientation.Landscape:
					return sp.PageOrientation.Landscape;
				default:
					throw new NotSupportedException();
			}
		}

		public static PageOrientation ToEto(this sp.PageOrientation? value)
		{
			if (value == null)
				return PageOrientation.Portrait;
			switch (value.Value)
			{
				case sp.PageOrientation.Landscape:
					return PageOrientation.Landscape;
				case sp.PageOrientation.Portrait:
					return PageOrientation.Portrait;
				default:
					throw new NotSupportedException();
			}
		}

		public static swc.PageRange ToPageRange(this Range range)
		{
			return new swc.PageRange(range.Start, range.End);
		}

		public static Range ToEto(this swc.PageRange range)
		{
			return new Range(range.PageFrom, range.PageTo - range.PageFrom + 1);
		}

		public static swc.PageRangeSelection ToSWC(this PrintSelection value)
		{
			switch (value)
			{
				case PrintSelection.AllPages:
					return swc.PageRangeSelection.AllPages;
				case PrintSelection.SelectedPages:
					return swc.PageRangeSelection.UserPages;
				default:
					throw new NotSupportedException();
			}
		}

		public static PrintSelection ToEto(this swc.PageRangeSelection value)
		{
			switch (value)
			{
				case swc.PageRangeSelection.AllPages:
					return PrintSelection.AllPages;
				case swc.PageRangeSelection.UserPages:
					return PrintSelection.SelectedPages;
				default:
					throw new NotSupportedException();
			}
		}
#endif
		public static Size GetSize(this sw.FrameworkElement element)
		{
#if TODO_XAML
			if (element.IsVisible && (!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight)))
				return new Size((int)element.ActualWidth, (int)element.ActualHeight);
			return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height));
#else
			if ((!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight)))
				return new Size((int)element.ActualWidth, (int)element.ActualHeight);
			return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height));
#endif
		}

		public static void SetSize(this sw.FrameworkElement element, Size size)
		{
			element.Width = size.Width == -1 ? double.NaN : size.Width;
			element.Height = size.Height == -1 ? double.NaN : size.Height;
		}

		public static void SetSize(this sw.FrameworkElement element, wf.Size size)
		{
			element.Width = size.Width;
			element.Height = size.Height;
		}

		public static FontStyle Convert(wut.FontStyle fontStyle, wut.FontWeight fontWeight)
		{
			var style = FontStyle.None;
			if (fontStyle == wut.FontStyle.Italic)
				style |= FontStyle.Italic;
			if (fontStyle == wut.FontStyle.Oblique)
				style |= FontStyle.Italic;
			if (ReferenceEquals(fontWeight, wut.FontWeights.Bold))
				style |= FontStyle.Bold;
			return style;
		}

#if TODO_XAML
		public static FontDecoration Convert(sw.TextDecorationCollection decorations)
		{
			var decoration = FontDecoration.None;
			if (decorations != null)
			{
				if (sw.TextDecorations.Underline.All(decorations.Contains))
					decoration |= FontDecoration.Underline;
				if (sw.TextDecorations.Strikethrough.All(decorations.Contains))
					decoration |= FontDecoration.Strikethrough;
			}
			return decoration;
		}
#endif

		public static swmi.BitmapSource ToWpf(this Image image, int? size = null)
		{
#if TODO_XAML
			if (image == null)
				return null;
			var imageHandler = image.Handler as IWpfImage;
			if (imageHandler != null)
				return imageHandler.GetImageClosestToSize(size);
			return image.ControlObject as swmi.BitmapSource;
#else
			return image.ControlObject as swmi.BitmapSource;
#endif
		}

		public static swc.Image ToWpfImage(this Image image, int? size = null)
		{
			var source = image.ToWpf(size);
			if (source == null)
				return null;
			var swcImage = new swc.Image { Source = source };
			if (size != null)
			{
				swcImage.MaxWidth = size.Value;
				swcImage.MaxHeight = size.Value;
			}
			return swcImage;
		}

#if TODO_XAML
		public static swm.Pen ToWpf(this Pen pen, bool clone = false)
		{
			var p = (swm.Pen)pen.ControlObject;
			if (clone)
				p = p.Clone();
			return p;
		}
#endif

		public static swm.PenLineJoin ToWpf(this PenLineJoin value)
		{
			switch (value)
			{
				case PenLineJoin.Miter:
					return swm.PenLineJoin.Miter;
				case PenLineJoin.Bevel:
					return swm.PenLineJoin.Bevel;
				case PenLineJoin.Round:
					return swm.PenLineJoin.Round;
				default:
					throw new NotSupportedException();
			}
		}

		public static PenLineJoin ToEto(this swm.PenLineJoin value)
		{
			switch (value)
			{
				case swm.PenLineJoin.Bevel:
					return PenLineJoin.Bevel;
				case swm.PenLineJoin.Miter:
					return PenLineJoin.Miter;
				case swm.PenLineJoin.Round:
					return PenLineJoin.Round;
				default:
					throw new NotSupportedException();
			}
		}

		public static swm.PenLineCap ToWpf(this PenLineCap value)
		{
			switch (value)
			{
				case PenLineCap.Butt:
					return swm.PenLineCap.Flat;
				case PenLineCap.Round:
					return swm.PenLineCap.Round;
				case PenLineCap.Square:
					return swm.PenLineCap.Square;
				default:
					throw new NotSupportedException();
			}
		}

		public static PenLineCap ToEto(this swm.PenLineCap value)
		{
			switch (value)
			{
				case swm.PenLineCap.Flat:
					return PenLineCap.Butt;
				case swm.PenLineCap.Round:
					return PenLineCap.Round;
				case swm.PenLineCap.Square:
					return PenLineCap.Square;
				default:
					throw new NotSupportedException();
			}
		}

		public static swm.Brush ToWpf(this Brush brush, bool clone = false)
		{
			var b = (swm.Brush)brush.ControlObject;
			if (clone)
			{
#if TODO_XAML
				b = b.Clone();
#else
				throw new NotImplementedException();
#endif
			}
			return b;
		}

		public static swm.Matrix ToWpf(this IMatrix matrix)
		{
			return (swm.Matrix)matrix.ControlObject;
		}

		public static swm.Transform ToWpfTransform(this IMatrix matrix)
		{
			return new swm.MatrixTransform { Matrix = matrix.ToWpf() };
		}

#if TODO_XAML
		public static IMatrix ToEtoMatrix(this swm.Transform transform)
		{
			return new MatrixHandler(transform.Value);
		}
#endif

		public static swm.PathGeometry ToWpf(this IGraphicsPath path)
		{
			return (swm.PathGeometry)path.ControlObject;
		}

		public static swm.GradientSpreadMethod ToWpf(this GradientWrapMode wrap)
		{
			switch (wrap)
			{
				case GradientWrapMode.Reflect:
					return swm.GradientSpreadMethod.Reflect;
				case GradientWrapMode.Repeat:
					return swm.GradientSpreadMethod.Repeat;
				default:
					throw new NotSupportedException();
			}
		}

		public static GradientWrapMode ToEto(this swm.GradientSpreadMethod spread)
		{
			switch (spread)
			{
				case swm.GradientSpreadMethod.Reflect:
					return GradientWrapMode.Reflect;
				case swm.GradientSpreadMethod.Repeat:
					return GradientWrapMode.Repeat;
				default:
					throw new NotSupportedException();
			}
		}

		public static TextAlignment ToEto(this sw.TextAlignment align)
		{
			switch (align)
			{
				case sw.TextAlignment.Left:
					return TextAlignment.Left;
				case sw.TextAlignment.Right:
					return TextAlignment.Right;
				case sw.TextAlignment.Center:
					return TextAlignment.Center;
				default:
					throw new NotSupportedException();
			}
		}

		public static sw.TextAlignment ToWpfTextAlignment(this TextAlignment align)
		{
			switch (align)
			{
				case TextAlignment.Center:
					return sw.TextAlignment.Center;
				case TextAlignment.Left:
					return sw.TextAlignment.Left;
				case TextAlignment.Right:
					return sw.TextAlignment.Right;
				default:
					throw new NotSupportedException();
			}
		}

#if TODO_XAML
		public static WindowStyle ToEto(this sw.WindowStyle style)
		{
			switch (style)
			{
				case sw.WindowStyle.None:
					return WindowStyle.None;
				case sw.WindowStyle.ThreeDBorderWindow:
					return WindowStyle.Default;
				default:
					throw new NotSupportedException();
			}
		}

		public static sw.WindowStyle ToWpf(this WindowStyle style)
		{
			switch (style)
			{
				case WindowStyle.None:
					return sw.WindowStyle.None;
				case WindowStyle.Default:
					return sw.WindowStyle.ThreeDBorderWindow;
				default:
					throw new NotSupportedException();
			}
		}
#endif
	}
}


text:
from __future__ import division, print_function
import warnings
import numpy as np
import scipy.sparse as sparse

import lintable as lin

class Model:
    """
    Defines some Bose-Hubbard model by specifying the onsite energies (omegas),
    the links between sites on the network, and
    the onsite interaction strength (U)

    Parameters
    ----------
    H1E : ndarray
        Diagonal matrix storing the onsite energies.
    H1T : ndarray
        The single particle hopping matrix (no diagonal part).
    H1U : ndarray
        The single particle interaction strength between electrons on different
        sites.
    """
    def __init__(self, H1E, H1T, H1U):
        self.n = H1E.shape[0]
        self.H1T = H1T
        self.H1E = H1E
        self.H1U = H1U

    @property
    def HU(self):
        return Model.HU_factory(self.H1U)

    @staticmethod
    def HU_factory(H1U):
        HUii = np.diag(H1U)
        HUij = H1U - np.diag(HUii)

        fcn = lambda statesu, statesd: \
            np.sum(.5 * ((statesu + statesd - 1).dot(HUij))*(statesu + statesd - 1), axis=1) \
            + ((statesu - .5)*(statesd - .5)).dot(HUii)

        return fcn

    @property
    def real(self):
        return np.sum(np.abs(np.imag(self.H1T))) < 1e-10

    def numbersector(self, ne):
        """
        Returns a specific particle number sector object based on this model.
        """

        return NumberSector(self, ne)

class NumberSector:
    """
    Defines a specific particle number sector of a given Fermi-Hubbard model.
    """
    def __init__(self, model, ne):
        self.model = model  # model
        self.ne = ne  # number of particle
        # cache
        self._cache = dict()

    def szsector(self, ds):
        """
        Returns a specific spin state indexed by the excess of spin up
        particles compared to spin down.

        Caches the result for later use.

        The difference must be commensurate with the number of particles.
        E.g. a difference ds = 2 is not "commensurate" with ne=3 particles.

        Parameters
        ----------
        ds : int
            ds = n(spin up) - n(spin down).
        """
        if ds % 2 != self.ne % 2:
            warnings.warn('Particle difference "{0}" not commensurate with total particle number'.format(ds))
            return False

        nu = int((ds + self.ne)/2)
        nd = self.ne - nu
        return SzSector(self.model, nu, nd)

class SzSector:
    """
    SpinState corresponding to a specific number of spin-up electrons,
    and spin-down electrons.

    Conventionially the many-electrons states are always built in the basis:
          basis[0]    = basisu[0] basisd[0]
          basis[1]    = basisu[1] basisd[0]
          basis[2]    = basisu[2] basisd[0]
          ...
          basis[Nu-1] = basisu[Nu-1] basisd[0]
          basis[Nu]   = basisu[0] basisd[1]
          basis[Nu+1] = basisu[1] basisd[1]
          ...
    and basis states have create_up operators before create_down operators.
    """
    def __init__(self, model, nu, nd):
        self.n = model.n
        self.model = model
        self.nu = nu
        self.nd = nd
        self.sz = nu - nd

    @property
    def hamiltonian(self):
        """
        Returns the Hamiltonian and caches the result for later retrieval.

        Returns
        -------
        A 3-tuple (H1Tu, H1Td, HU)
        """
        if not hasattr(self, '_hamiltonian'):
            self._lintable, self._hamiltonian = SzSector.generate_hamiltonian(self.model, self.nu + self.nd, self.nu)

        return self._hamiltonian

    @staticmethod
    def generate_hamiltonian(model, ne, nu):
        """
        Generates all the parts of the Hamiltonian
        in the specific Sz-spin state.

        Parameters
        ----------
        model : Model object
            A FermiHubbard Model
        ne : int
            Total number of electrons
        nu : int
            Total number of spin up electrons
        """
        n = model.n
        nd = ne - nu

        lita = lin.Table(n, nu, nd)  # create the lin table for this szstate

        if nu > n or nd > n:
            H = np.zeros((1, 1))
            return lita, (H, H, np.zeros((1,)))

        # hopping for spin up
        HTu = SzSector.hopping_hamiltonian(lita.basisu, lita.Juv, model.H1T,
                                           real=model.real)

        # hopping for spin down
        HTd = SzSector.hopping_hamiltonian(lita.basisd, lita.Jdv, model.H1T,
                                           real=model.real)

        HU = SzSector.interaction_hamiltonian(model, ne, nu)

        return lita, (HTu, HTd, HU)

    @staticmethod
    def interaction_hamiltonian(model, ne, nu, real=True):
        """
        The Coulomb energy of each states in our specific
        Sz subspace.

        Parameters
        ----------
        model : Model object
            FermiHubbard model object.
        ne : int
            Total number of electrons.
        nu : int
            Number of spin up electrons.
        real : boolean
            Whether or not the system has only real parameters.
        """
        n = model.n
        nd = ne-nu

        if nu > n or nd > n:
            return np.zeros((1,), dtype=np.float64 if real else np.complex128)

        lita = lin.Table(n, nu, nd)
        Nu, Nd = lita.Ns

        HU = model.HU  # the interaction function

        # The coulomb energy
        HUv = np.zeros(
            (Nd*Nu,),
            dtype=np.float64 if real else np.complex128)

        for cN in xrange(Nd):

            index = cN*Nu + np.arange(Nu)

            statesu, statesd = lin.index2state(
                index,
                n=n,
                Juv=lita.Juv,
                Jdv=lita.Jdv)   # get all states

            HUv[index] = HU(statesu, statesd) + \
                np.sum(statesd.dot(model.H1E), axis=1) + \
                np.sum(statesu.dot(model.H1E), axis=1)

        return HUv

    @staticmethod
    def hopping_hamiltonian(states, Jv, H1T, real=True):
        """
        The kinetic part of the Hamiltonian for a all electrons
        of a specific spin specie.

        Parameters
        ----------
        states: list
            List of many-electron states in each Sz spin sector.
        Jv : list
            List of Lin indices
        H1T : ndarray
            The hopping Hamiltonian.
        real : boolean
            Whether or not the system has only real parameters.
        """
        if len(Jv) == 1:
            return np.array([1, 1, 0])

        n = H1T.shape[0]                        # number of site

        ne = np.sum(states[0, :])               # number of electrons

        # only the upper triangular part
        H1T = np.triu(H1T)
        # count number of hopping elements
        nH1T = np.sum(H1T != 0)
        ts = np.transpose(np.nonzero(H1T))      # ts

        # J = {J: i for i, J in enumerate(Jv)}   # create a reverse index
        NJ = len(Jv)
        HS = sparse.dok_matrix(
            (NJ, NJ),
            dtype=np.float64 if real else np.complex128)

        for c in xrange(nH1T):

            H1H = np.eye(n, dtype=int)
            i = ts[c, 0]
            j = ts[c, 1]

            H1H[j, j] = 0
            H1H[i, i] = 0
            H1H[i, j] = 1

            vouts = states.dot(H1H).astype(int)
            vouts[states[:, i]+states[:, j] == 0, :] = 0
            vouts[states[:, i]+states[:, j] == 2, :] = 0

            idx = np.flatnonzero(np.sum(vouts, axis=1) == ne)

            if len(idx) > 0:
                touts = (-1)**np.mod(
                    np.sum(states[idx, min(i, j):max(i, j)], axis=1) - 1,
                    2)*H1T[i, j]
                HS[idx, lin.state2index(vouts[idx, :], Jv)] = touts

        return HS.tocsr() + HS.tocsr().H

#     $$\   $$\   $$\     $$\ $$\
#     $$ |  $$ |  $$ |    \__|$$ |
#     $$ |  $$ |$$$$$$\   $$\ $$ |
#     $$ |  $$ |\_$$  _|  $$ |$$ |
#     $$ |  $$ |  $$ |    $$ |$$ |
#     $$ |  $$ |  $$ |$$\ $$ |$$ |
#     \$$$$$$  |  \$$$$  |$$ |$$ |
#      \______/    \____/ \__|\__|

def choose(n, k):
    """
    A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
    """
    n = int(n)
    k = int(k)

    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0


text:
directive_module.directive('showtextmodal', showTextModalDirective)
    .filter('jsonBigIntFilter', function () {
        return function (text) {
            if (typeof(text) === "undefined" || typeof JSON.parse(text) !== "object"
                || !text) {
                return;
            }

            const numberRegex = /"\|+\d+\|+"/g;
            const splitRegex = /"\|+\d+\|+"/;
            const splitArray = text.split(splitRegex);
            const matchResult = text.match(numberRegex);
            const borderRegex = /"\|\d+\|"/;
            if (!matchResult || 0 === splitArray.length) {
                return text;
            } else {
                Object.keys(matchResult).forEach(function (key) {
                    if (matchResult[key].includes('"\|')) {
                        if (borderRegex.test(matchResult[key])) {
                            matchResult[key] = matchResult[key].replaceAll('"\|', '');
                            matchResult[key] = matchResult[key].replaceAll('|\"', '');
                        } else {
                            matchResult[key] = matchResult[key].replaceAll('"\|', '"');
                            matchResult[key] = matchResult[key].replaceAll('|\"', '"');
                        }
                    }
                });
            }

            let resultStr = '';
            let index = 0;

            const isJsonText = resultStr => {
                try {
                    return typeof JSON.parse(resultStr) === "object";
                } catch (e) {
                    return false;
                }
            };

            Object.keys(splitArray).forEach(function (key) {
                resultStr = resultStr.concat(splitArray[key]);
                if (typeof(matchResult[index]) !== "undefined"
                    && !isJsonText(resultStr)) {
                    resultStr = resultStr.concat(matchResult[index++])
                }
            })

            return resultStr;
        }
    });

function showTextModalDirective(AppUtil) {
    return {
        restrict: 'E',
        templateUrl: AppUtil.prefixPath() + '/views/component/show-text-modal.html',
        transclude: true,
        replace: true,
        scope: {
            text: '='
        },
        link: function (scope) {
            scope.$watch('text', init);

            function init() {
                scope.jsonObject = undefined;
                if (isJsonText(scope.text)) {
                    scope.jsonObject = parseBigInt(scope.text);
                }
            }

            function isJsonText(text) {
                try {
                    return typeof JSON.parse(text) === "object";
                } catch (e) {
                    return false;
                }
            }

            function parseBigInt(str) {
                if (/\d+/.test(str)) {
                    let replaceMap = [];
                    let n = 0;
                    str = str.replace(/"\|+\d+\|+"/g, function (match) {
                        return match.replace('"\|', '"\||').replace('|"', '||"');
                    })
                    .replace(/"(\\?[\s\S])*?"/g, function (match) {
                        if (/\d+/.test(match)) {
                            replaceMap.push(match);
                            return '"""';
                        }
                        return match;
                    }).replace(/[+\-\d.eE]+/g, function (match) {
                        if (/^\d+$/.test(match)) {
                            return '"|' + match + '|"';
                        }
                        return match;
                    }).replace(/"""/g, function () {
                        return replaceMap[n++];
                    })
                }
                return JSON.parse(str);
            }
        }
    }
}


text:
A script to convert a WebExtension for Chrome to run on Firefox.

### Usage
Its default expected use is as a submodule in a chrome extension's repo.
Run without args to create a firefox-compatible ```.xpi``` archive of the parent directory's contents, named using keys
from the manifest.

You can also specify which directory to package, and the new values to add to the gecko part of the manifest.
Run with ```-h``` or ```--help``` for more information.

### Installation as submodule
The script ignores hidden directories; to avoid packing itself, best hide the submodule dir.
```git submodule add git@github.com:Steven-Eardley/chrome-to-firefox.git .build```


text:
import os
import codecs
from setuptools import setup

def read(fname):
    file_path = os.path.join(os.path.dirname(__file__), fname)
    return codecs.open(file_path, encoding='utf-8').read()

setup(
    name='pytest-{{cookiecutter.plugin_name}}',
    version='{{cookiecutter.version}}',
    author='{{cookiecutter.full_name}}',
    author_email='{{cookiecutter.email}}',
    maintainer='{{cookiecutter.full_name}}',
    maintainer_email='{{cookiecutter.email}}',
    license='{{cookiecutter.license}}',
    url='https://github.com/{{cookiecutter.github_username}}/pytest-{{cookiecutter.plugin_name}}',
    description='{{cookiecutter.short_description}}',
    long_description=read('README.rst'),
    py_modules=['pytest_{{cookiecutter.plugin_name}}'],
    install_requires=['pytest>={{cookiecutter.pytest_version}}'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Testing',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Operating System :: OS Independent',
        {% if cookiecutter.license == "MIT" -%}
        'License :: OSI Approved :: MIT License',
        {%- elif cookiecutter.license == "BSD-3" -%}
        'License :: OSI Approved :: BSD License',
        {%- elif cookiecutter.license == "GNU GPL v3.0" -%}
        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
        {%- elif cookiecutter.license == "Apache Software License 2.0" -%}
        'License :: OSI Approved :: Apache Software License',
        {%- endif %}
    ],
    entry_points={
        'pytest11': [
            '{{cookiecutter.plugin_name}} = pytest_{{cookiecutter.plugin_name}}',
        ],
    },
)


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

// Create express app to serve application
var app = express();
app.use( express.static( __dirname + '/webapp'));
app.listen( process.env.PORT || 4000);


text:
import moment from 'moment';

export default function isSameMonth(a, b) {
  if (!moment.isMoment(a) || !moment.isMoment(b)) return false;
  // Compare least significant, most likely to change units first
  // Moment's isSame clones moment inputs and is a tad slow
  return a.month() === b.month()
    && a.year() === b.year();
}


text:
I upgrade kernel from 3.0.6 to 3.2.0-r1.

* check http://packages.gentoo.org/package/sys-kernel/gentoo-sources
* `echo "sys-kernel/gentoo-sources ~x86" >> /etc/portage/package.accept_keywords`
* add "symlink" to USE
* `emerge -S gentoo-sources`
* `emerge -u gentoo-sources`

```
make menuconfig
make && make modules_install
cp arch/x86/boot/bzImage /boot/kernel-3.2.0-r1
```

* edit /boot/grub/grub.conf

```
emerge module-rebuild
module-rebuild populate
module-rebuild rebuild
```


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Home

Products

Services

Blog

Contact

The standard Lorem Ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The standard Lorem Ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The standard Lorem Ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

            inteligence meets imagination

                call-800-1234...or

         <button type="button" class="btn btn-primary pull-right">Request Queue</button>

About our company and service

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words,

        <address>

Contact Us:

           Address: 795 Folsom Ave, Suite 600

            Telephone:123-12546

            Cotact:(123) 456-7890
            Email:mukta@yahoo.com
        </address>

            copyright@ mukta rani biswas


text:
python-mailgun
==============

[![Build Status](https://travis-ci.org/getupcloud/python-mailgunlog.png?branch=master)](https://travis-ci.org/getupcloud/python-mailgunlog)

Python Package to retrieve Mailgun logs for a given domain.

## Install

```
pip install mailgunlog
```

## Usage

### Command line tool

As a command line tool (use -h for help):

```
$ mailgunlog <domain> <api-key> --begin 2015/01/01 --end 2015/01/31 --json
```

If your prefer, call it as an executable module:

```
$ python -m mailgunlog <domain> <api-key> --begin 2015/01/01 --end 2015/01/31
```

In order to keep it a little bit secure, define your API Key and Domain from environment variables:

```
$ export MAILGUN_DOMAIN=example.com
$ export MAILGUN_API_KEY=<mailgunapi-key-goes-here>
```

Now it's possible to dump logs from an specific number of days ago:

```
$ python -m mailgunlog <domain> <api-key> --days 5
```

### Module

You can use it inside your project, as a python module:

```python
import mailgunlog

for log in mailgunlog.logs():
    print json.dumps(log, indent=3)
```

## License

Written by [Getup Cloud](https://getupcloud.com).

Released under the Apache License 2.0: http://opensource.org/licenses/Apache-2.0


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProgramingStudy.Study
{
    class Delegaty
    {
        public delegate int hd(int x);

        public Delegaty()
        {
            hd helloDelegate = HelloDelegate;

            helloDelegate += HelloDelegate2;

        }

        public int HelloDelegate(int x)
        {
            return x;
        }

        public int HelloDelegate2(int x)
        {
            return x;
        }

    }
}


text:
package filesystem;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.sutkowski.api.FileStorageImplementor;
import pl.sutkowski.storageconnector.filesystem.FileSystemFileStorageImplementor;
import sample.filesystem.SampleFileSystemFileStorageApplication;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleFileSystemFileStorageApplication.class)
@TestPropertySource("classpath:application.yml")
public class SampleFileSystemFileStorageImplementorRestControllerTest {

    @Autowired
    FileStorageImplementor fileStorageImplementor;

    @Test
    public void contextLoads() {
    }

    @Test
    public void fileStorageShouldBeInstanceOfFileSystem() {
        Assertions.assertThat(fileStorageImplementor).isNotNull();
        Assertions.assertThat(fileStorageImplementor instanceof FileSystemFileStorageImplementor).isTrue();
    }

}


text:
package io.tchepannou.academy.service.quiz;

import java.util.ArrayList;
import java.util.List;

public class MarkdownAnswerValidator extends TextAnswerValidator {
    @Override
    protected String normalize(final String str) {
        final String[] lines = str.split("[\\r\\n]+");
        final List<String> result = new ArrayList();
        for (int i=0 ; i<lines.length ; i++){
            final String line = lines[i]
                    .replaceAll("\\s+$", "");   // right trim
            if (line.length() > 0){
                result.add(line);
            }
        }
        return String.join("\n", result);
    }
}


text:
mkdir -p dist
javac -d dist src/*.java
cd dist
java w1.p2.Main


text:
<?php
namespace SeanMorris\Form\Validator;
/**
 * Validates that field value is an email address.
 */
class Email extends Validator
{
	protected $rules;

	public function __construct($errorMessage)
	{
		$this->errorMessage = $errorMessage;
	}

	public function validate($form, $field = NULL)
	{
		parent::validate($form, $field);

		$value = $field->value();

		if(!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL))
		{
			$this->errors[] = $this->errorMessage;
		}

		return !$this->errors;
	}
}


text:
package org.apache.spark.examples.mllib;

import java.util.ArrayList;

// $example on$
import com.google.common.collect.Lists;
// $example off$
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
// $example on$
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.mllib.clustering.BisectingKMeans;
import org.apache.spark.mllib.clustering.BisectingKMeansModel;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
// $example off$

/**
 * Java example for bisecting k-means clustering.
 */
public class JavaBisectingKMeansExample {
  public static void main(String[] args) {
    SparkConf sparkConf = new SparkConf().setAppName("JavaBisectingKMeansExample");
    JavaSparkContext sc = new JavaSparkContext(sparkConf);

    // $example on$
    ArrayList<Vector> localData = Lists.newArrayList(
      Vectors.dense(0.1, 0.1),   Vectors.dense(0.3, 0.3),
      Vectors.dense(10.1, 10.1), Vectors.dense(10.3, 10.3),
      Vectors.dense(20.1, 20.1), Vectors.dense(20.3, 20.3),
      Vectors.dense(30.1, 30.1), Vectors.dense(30.3, 30.3)
    );
    JavaRDD<Vector> data = sc.parallelize(localData, 2);

    BisectingKMeans bkm = new BisectingKMeans()
      .setK(4);
    BisectingKMeansModel model = bkm.run(data);

    System.out.println("Compute Cost: " + model.computeCost(data));

    Vector[] clusterCenters = model.clusterCenters();
    for (int i = 0; i < clusterCenters.length; i++) {
      Vector clusterCenter = clusterCenters[i];
      System.out.println("Cluster Center " + i + ": " + clusterCenter);
    }
    // $example off$

    sc.stop();
  }
}


text:
package com.tesshu.subsonic.client.fx.command.logic;

import com.tesshu.subsonic.client.controller.GetMusicDirectoryController;
import com.tesshu.subsonic.client.fx.command.param.SimpleObjectParam;
import com.tesshu.subsonic.client.fx.view.ComponentUtil;
import com.tesshu.subsonic.client.fx.view.browsing.BrowsingContainer;
import com.tesshu.subsonic.client.fx.view.browsing.BrowsingRow;
import com.tesshu.subsonic.client.fx.view.browsing.TitleContainer;
import com.tesshu.subsonic.client.model.Directory;
import com.tesshu.subsonic.client.model.IMusicDirectory;

import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javafx.application.Platform;
import javafx.collections.FXCollections;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Scope("prototype")
@Component
@Lazy
public final class ShowMusicDirectoryLogicImpl extends AbstractLogic<SimpleObjectParam<IMusicDirectory>>
    implements ShowMusicDirectoryLogic {

  @Resource
  private GetMusicDirectoryController getMusicDirectory;

  @Resource
  private ComponentUtil               util;

  @Override
  public void invoke(BrowsingContainer browsingContainer) {

    if (null == getParameter() || null == getParameter().getObject()) {
      return;
    }

    Directory directory = null;
    Optional<Directory> dir = getMusicDirectory.getOf(getParameter().getObject());
    directory = dir.isPresent() ? dir.get() : null;
    if (null == directory) {
      return;
    }

    // create [title]
    TitleContainer container = util.createTitleContainer(directory);
    Platform.runLater(() -> browsingContainer.set(container));

    // create [rows]
    List<BrowsingRow> rows = new ArrayList<>();

    // parent reference if exists
    Optional<Directory> parent = getMusicDirectory.getParentOf(directory);
    parent.ifPresent(p -> rows.add(util.createParentBrowsingRow(p)));

    // child rows
    directory.getChildren().stream().map(c -> util.createBrowsingRow(c)).forEach(l -> rows.add(l));

    browsingContainer.getBrowsingControll()
        .setItems(FXCollections.observableArrayList(FXCollections.observableArrayList(rows)));
  }

  @PostConstruct
  private void initialize() {
    setDelay(1);
  }

}


text:
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {Post} from './model_post';

declare var process: any;

@Injectable()
export class PostService {
  posts: Post[];
  //private postsUrl = 'http://localhost:8080/posts/' + encodeURI('ラーメン');
  private postsUrl = process.env.POST_URL + encodeURI('ラーメン');

  constructor(private http: Http) {};

  getPosts(): Observable<Post[]> {
    console.log(this.postsUrl);
    return this.http.get(this.postsUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

  extractData(res: Response) {
    let body = res.json();
    console.log(body);
    return body || {};
  }

  handleError(error: Response | any) {
    console.error('error occured', error);
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(error);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }

    return Observable.throw(errMsg);
  }
}


text:
"""Test that the contrib module shows up properly."""

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

import inspect
from tensorflow.python.platform import googletest

class ContribTest(googletest.TestCase):

  def testContrib(self):
    # pylint: disable=g-import-not-at-top
    import tensorflow as tf
    assert inspect.ismodule(tf.contrib)

if __name__ == '__main__':
  googletest.main()


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createProxyMiddleware = void 0;
const http_proxy_middleware_1 = require("./http-proxy-middleware");
function createProxyMiddleware(context, options) {
    const { middleware } = new http_proxy_middleware_1.HttpProxyMiddleware(context, options);
    return middleware;
}
exports.createProxyMiddleware = createProxyMiddleware;
__exportStar(require("./handlers"), exports);


text:
class MazeGen : public SC::Application
{

protected:

    virtual bool OnInitialized() override;

private:

    friend class SC::Application;

    MazeGen();

    SC::ResourceManager Resources;

    SC::SceneGraph Scene;

    Maze TheMaze;

};


text:
header {
    margin-top: 60px;
    position: relative;
    min-height: auto;
    text-align: center;
    color: #fff;
    width: 100%;
    background-color: #c9c9c9;
    background-image: url('../../assets/bg.jpg');
    background-position: center;
    background-size: cover;
}

header .header-content {
    position: relative;
    width: 100%;
    padding: 100px 15px;
    text-align: center;
    z-index: 2;
}

header .header-content .inner h1 {
    margin-top: 0;
    margin-bottom: 0;
    text-shadow: 2px 2px 5px #111;
}

header .header-content .inner h4 {
    text-shadow: 2px 2px 5px #111;
}

header .header-content .inner p {
    margin-bottom: 50px;
    font-size: 16px;
    font-weight: 300;
    color: #fff;
}

@media(min-width:768px) {
    .icon-lg {
        font-size: 80px;
    }
    header {
        min-height: 100%;
    }
    header .header-content {
        position: absolute;
        top: 50%;
        padding: 0 50px;
        transform: translateY(-50%);
    }
    header .header-content .inner {
        margin-right: auto;
        margin-left: auto;
        max-width: 1000px;
    }
    header .header-content .inner h1 {
        font-size: 100px;
    }
    header .header-content .inner p {
        margin-right: auto;
        margin-left: auto;
        max-width: 80%;
        font-size: 18px;
    }
}


text:
{% comment %}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
{% endcomment %}

  Student:
    {{ duplicate.student.name }}

  {{ duplicate.student.email }}

  {% for key, org in orgs.items %}

Organization:
    {{ org.name }}
    Admins: {% for oa in org.admins %}
    '"{{ oa.name }}" <{{ oa.email }}>'
    {% endfor %}

    {% for proposal in org.proposals %}

Proposal:

          {{ proposal.title }}

    {% endfor %}

  {% endfor %}


text:
import { $each } from 'core/dom';
import { _doc } from 'core/variables';
import { _slice } from 'core/types';
import { $addClass, $removeClass } from 'dom/index';
import { warn } from 'core/warn';

/**
 * Detect what transition property to listen for
 *
 * @returns {*}
 * @private
 */
function _whichTransitionEvent() {
    const el = document.createElement('meta');
    const animations = {
        transition: 'transitionend',
        OTransition: 'oTransitionEnd',
        MozTransition: 'transitionend',
        WebkitTransition: 'webkitTransitionEnd',
    };

    for (const t in animations) {
        if (el.style[t] !== undefined) {
            return animations[t];
        }
    }
}

const transitionEvent = _whichTransitionEvent();
const supportsTransitionEvent = !!transitionEvent;

export default class Transition {
    constructor(config) {
        this.transitionEvent = transitionEvent;
        this.target = config.target || null;
        this.class = config.class || null;
        this.enterCallback = config.enter || null;
        this.leaveCallback = config.leave || null;
        this.timeout = typeof config.timeout === 'number' ? config.timeout : null;
        this.countEvents = null;
        this.completed = 0;
    }

    /**
     * Select DOM element(s)
     *
     * @param {string} target
     * @returns {*}
     * @private
     */
    _select(target) {
        return _slice.call(_doc.querySelectorAll(target));
    }

    /**
     * Remove class from target/execute enterCallback
     *
     * @param {Object} to
     * @param {Object} from
     */
    enter(to, from) {
        if (this.class && this.target) {
            const elements = this._select(this.target);

            if (! elements.length) {
                warn('routes', 'no elements found - cannot apply enter transition');
            }

            elements.forEach((el) => {
                if (supportsTransitionEvent) {
                    el.removeEventListener(this.transitionEvent, this.countEvents);
                }

                $removeClass(el, this.class);
            });
        }

        if (this.enterCallback) {
            this.enterCallback(to, from);
        }
    }

    /**
     * Apply class to target/execute leaveCallback
     *
     * @param {Object} to
     * @param {Object} from
     * @returns {Promise}
     */
    leave(to, from) {
        const scope = this;

        return new Promise((resolve, reject) => {
            if (this.class && this.target) {
                const elements = this._select(this.target);

                if (! elements.length) {
                    warn('routes', 'no elements found - cannot apply leave transition');
                    return resolve(scope);
                }

                this.countEvents = function countEvents() {
                    scope.completed += 1;

                    if (elements.length === scope.completed) {
                        resolve(scope);
                    }
                };

                // Add class to targets
                $each(elements, (el) => {
                    if (supportsTransitionEvent) {
                        el.addEventListener(this.transitionEvent, this.countEvents);
                    }

                    $addClass(el, this.class);
                });

                if (! supportsTransitionEvent) {
                    resolve(scope);
                }
            } else if (this.leaveCallback) {
                this.leaveCallback(to, from, (error) => {
                    if (error instanceof Error) {
                        return reject(error);
                    }

                    resolve(scope);
                });
            }

            if (this.timeout !== null) {
                setTimeout(() => {
                    resolve(scope);
                }, this.timeout);
            }
        });
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phlegmacium claricolor var. siparium M.M. Moser

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/iteminfo" android:orientation="vertical"
	android:layout_width="wrap_content" android:layout_height="wrap_content"
	android:layout_marginTop="5dp"
	android:weightSum="1">
	<LinearLayout android:id="@+id/linearLayout1"
			android:layout_height="wrap_content"
			android:layout_width="match_parent"
			android:orientation="vertical"
			android:layout_weight="0.06">
		<RelativeLayout android:layout_height="wrap_content"
			android:layout_width="match_parent">
		<Button android:text="支出信息"
			android:id="@+id/btnoutinfo"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:textSize="20dp"
			android:textColor="#8C6931"
		/>
		<Button android:text="收入信息"
			android:id="@+id/btnininfo"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_toRightOf="@id/btnoutinfo"
			android:textSize="20dp"
			android:textColor="#8C6931"
			/>
		<Button android:text="便签信息"
			android:id="@+id/btnflaginfo"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_toRightOf="@id/btnininfo"
			android:textSize="20dp"
			android:textColor="#8C6931"
			/>
		</RelativeLayout>
		</LinearLayout>
		<LinearLayout android:id="@+id/linearLayout2"
			android:layout_height="wrap_content"
			android:layout_width="match_parent"
			android:orientation="vertical"
			android:layout_weight="0.94">
		<ListView android:id="@+id/lvinfo"
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:scrollbarAlwaysDrawVerticalTrack="true"
			/>
	</LinearLayout>
</LinearLayout>


text:
namespace ash {

FakeNetworkActivationHandler::ActivationParams::ActivationParams(
    const std::string& service_path,
    base::OnceClosure success_callback,
    network_handler::ErrorCallback error_callback)
    : service_path_(service_path),
      success_callback_(std::move(success_callback)),
      error_callback_(std::move(error_callback)) {}

FakeNetworkActivationHandler::ActivationParams::ActivationParams(
    ActivationParams&& other) = default;

FakeNetworkActivationHandler::ActivationParams::~ActivationParams() = default;

void FakeNetworkActivationHandler::ActivationParams::InvokeSuccessCallback() {
  std::move(success_callback_).Run();
}

void FakeNetworkActivationHandler::ActivationParams::InvokeErrorCallback(
    const std::string& error_name) {
  std::move(error_callback_).Run(error_name);
}

FakeNetworkActivationHandler::FakeNetworkActivationHandler() = default;

FakeNetworkActivationHandler::~FakeNetworkActivationHandler() = default;

void FakeNetworkActivationHandler::CompleteActivation(
    const std::string& service_path,
    base::OnceClosure success_callback,
    network_handler::ErrorCallback error_callback) {
  complete_activation_calls_.emplace_back(
      service_path, std::move(success_callback), std::move(error_callback));
}

}  // namespace ash