text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef nsIDeviceContext_h___
#define nsIDeviceContext_h___

#include "nsISupports.h"
#include "nsCoord.h"
#include "nsRect.h"
#include "nsIRenderingContext.h"
// XXX we need only gfxTypes.h, but we cannot include it directly.
#include "gfxPoint.h"

class nsIView;
class nsIFontMetrics;
class nsIWidget;
class nsIDeviceContextSpec;
class nsIAtom;
class gfxUserFontSet;

struct nsFont;

//a cross platform way of specifying a native device context
typedef void * nsNativeDeviceContext;

/* error codes for printer device contexts */
#define NS_ERROR_GFX_PRINTER_BASE (1) /* adjustable :-) */
/* Unix: print command (lp/lpr) not found */
#define NS_ERROR_GFX_PRINTER_CMD_NOT_FOUND          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+1)
/* Unix: print command returned an error */
#define NS_ERROR_GFX_PRINTER_CMD_FAILURE            \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+2)
/* no printer available (e.g. cannot find _any_ printer) */
#define NS_ERROR_GFX_PRINTER_NO_PRINTER_AVAILABLE  \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+3)
/* _specified_ (by name) printer not found */
#define NS_ERROR_GFX_PRINTER_NAME_NOT_FOUND         \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+4)
/* access to printer denied */
#define NS_ERROR_GFX_PRINTER_ACCESS_DENIED          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+5)
/* invalid printer attribute (for example: unsupported paper size etc.) */
#define NS_ERROR_GFX_PRINTER_INVALID_ATTRIBUTE      \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+6)
/* printer not "ready" (offline ?) */
#define NS_ERROR_GFX_PRINTER_PRINTER_NOT_READY     \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+8)
/* printer out of paper */
#define NS_ERROR_GFX_PRINTER_OUT_OF_PAPER           \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+9)
/* generic printer I/O error */
#define NS_ERROR_GFX_PRINTER_PRINTER_IO_ERROR       \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+10)
/* print-to-file: could not open output file */
#define NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE    \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+11)
/* print-to-file: I/O error while printing to file */
#define NS_ERROR_GFX_PRINTER_FILE_IO_ERROR          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+12)
/* print preview: needs at least one printer */
#define NS_ERROR_GFX_PRINTER_PRINTPREVIEW          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+13)
/* print: starting document */
#define NS_ERROR_GFX_PRINTER_STARTDOC          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+14)
/* print: ending document */
#define NS_ERROR_GFX_PRINTER_ENDDOC          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+15)
/* print: starting page */
#define NS_ERROR_GFX_PRINTER_STARTPAGE          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+16)
/* print: ending page */
#define NS_ERROR_GFX_PRINTER_ENDPAGE          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+17)
/* print: print while in print preview */
#define NS_ERROR_GFX_PRINTER_PRINT_WHILE_PREVIEW          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+18)
/* requested page size not supported by printer */
#define NS_ERROR_GFX_PRINTER_PAPER_SIZE_NOT_SUPPORTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+19)
/* requested page orientation not supported */
#define NS_ERROR_GFX_PRINTER_ORIENTATION_NOT_SUPPORTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+20)
/* requested colorspace not supported (like printing "color" on a "grayscale"-only printer) */
#define NS_ERROR_GFX_PRINTER_COLORSPACE_NOT_SUPPORTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+21)
/* too many copies requested */
#define NS_ERROR_GFX_PRINTER_TOO_MANY_COPIES \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+22)
/* driver configuration error */
#define NS_ERROR_GFX_PRINTER_DRIVER_CONFIGURATION_ERROR \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+23)
/* The document is still being loaded, can't Print Preview */
#define NS_ERROR_GFX_PRINTER_DOC_IS_BUSY_PP \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+24)
/* The document was asked to be destroyed while we were preparing printing */
#define NS_ERROR_GFX_PRINTER_DOC_WAS_DESTORYED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+25)
/* Cannot Print or Print Preview XUL Documents */
#define NS_ERROR_GFX_PRINTER_NO_XUL \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+26)
/* The toolkit no longer supports the Print Dialog (for embedders) */
#define NS_ERROR_GFX_NO_PRINTDIALOG_IN_TOOLKIT \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+27)
/* The was wasn't any Print Prompt service registered (this shouldn't happen) */
#define NS_ERROR_GFX_NO_PRINTROMPTSERVICE \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+28)
/* requested plex mode not supported by printer */
#define NS_ERROR_GFX_PRINTER_PLEX_NOT_SUPPORTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+29)
/* The document is still being loaded */
#define NS_ERROR_GFX_PRINTER_DOC_IS_BUSY \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+30)
/* Printing is not implemented */
#define NS_ERROR_GFX_PRINTING_NOT_IMPLEMENTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+31)
/* Cannot load the matching print module */
#define NS_ERROR_GFX_COULD_NOT_LOAD_PRINT_MODULE \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+32)
/* requested resolution/quality mode not supported by printer */
#define NS_ERROR_GFX_PRINTER_RESOLUTION_NOT_SUPPORTED \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_PRINTER_BASE+33)

/**
 * Conts need for Print Preview
 */
#ifdef NS_PRINT_PREVIEW
const PRUint8 kUseAltDCFor_NONE            = 0x00; // Do not use the AltDC for anything
const PRUint8 kUseAltDCFor_FONTMETRICS     = 0x01; // Use it for only getting the font metrics
const PRUint8 kUseAltDCFor_CREATERC_REFLOW = 0x02; // Use when creating RenderingContexts for Reflow
const PRUint8 kUseAltDCFor_CREATERC_PAINT  = 0x04; // Use when creating RenderingContexts for Painting
const PRUint8 kUseAltDCFor_SURFACE_DIM     = 0x08; // Use it for getting the Surface Dimensions
#endif

#define NS_IDEVICE_CONTEXT_IID   \
{ 0x30a9d22f, 0x8e51, 0x40af, \
  { 0xa1, 0xf5, 0x48, 0xe3, 0x00, 0xaa, 0xa9, 0x27 } }

  typedef enum {
    eSystemFont_Caption,         // css2
    eSystemFont_Icon,
    eSystemFont_Menu,
    eSystemFont_MessageBox,
    eSystemFont_SmallCaption,
    eSystemFont_StatusBar,

    eSystemFont_Window,          // css3
    eSystemFont_Document,
    eSystemFont_Workspace,
    eSystemFont_Desktop,
    eSystemFont_Info,
    eSystemFont_Dialog,
    eSystemFont_Button,
    eSystemFont_PullDownMenu,
    eSystemFont_List,
    eSystemFont_Field,

    eSystemFont_Tooltips,        // moz
    eSystemFont_Widget
  } nsSystemFontID;

class nsIDeviceContext : public nsISupports
{
public:
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDEVICE_CONTEXT_IID)

  /**
   * Initialize the device context from a widget
   * @param aWidget a widget to initialize the device context from
   * @return error status
   */
  NS_IMETHOD  Init(nsIWidget* aWidget) = 0;

  /**
   * Initialize the device context from a device context spec
   * @param aDevSpec the specification of the printng device (platform-specific)
   * @return error status
   */
  NS_IMETHOD  InitForPrinting(nsIDeviceContextSpec* aDevSpec) = 0;

  /**
   * Create a rendering context and initialize it from an nsIView
   * @param aView view to initialize context from
   * @param aContext out parameter for new rendering context
   * @return error status
   */
  NS_IMETHOD  CreateRenderingContext(nsIView *aView, nsIRenderingContext *&aContext) = 0;

  /**
   * Create a rendering context and initialize it from an nsIWidget
   * @param aWidget widget to initialize context from
   * @param aContext out parameter for new rendering context
   * @return error status
   */
  NS_IMETHOD  CreateRenderingContext(nsIWidget *aWidget, nsIRenderingContext *&aContext) = 0;

  /**
   * Create a rendering context and initialize it.
   * @param aContext out parameter for new rendering context
   * @return error status
   */
  NS_IMETHOD  CreateRenderingContext(nsIRenderingContext *&aContext) = 0;

  /**
   * Create an uninitalised rendering context.
   * @param aContext out parameter for new rendering context
   * @return error status
   */
  NS_IMETHOD  CreateRenderingContextInstance(nsIRenderingContext *&aContext) = 0;

  /**
   * We are in the process of creating the native widget for aWidget.
   * Do any device-specific processing required to initialize the
   * native widget for this device. A pointer to some platform-specific data is
   * returned in aOut.
   *
   * GTK2 calls this to get the required visual for the window.
   */
  NS_IMETHOD PrepareNativeWidget(nsIWidget* aWidget, void** aOut) = 0;

  /**
   * Gets the number of app units in one CSS pixel; this number is global,
   * not unique to each device context.
   */
  static PRInt32 AppUnitsPerCSSPixel() { return 60; }

  /**
   * Convert app units to CSS pixels which is used in gfx/thebes.
   */
  static gfxFloat AppUnitsToGfxCSSPixels(nscoord aAppUnits)
  { return gfxFloat(aAppUnits) / AppUnitsPerCSSPixel(); }

  /**
   * Gets the number of app units in one device pixel; this number is usually
   * a factor of AppUnitsPerCSSPixel(), although that is not guaranteed.
   */
  PRInt32 AppUnitsPerDevPixel() const { return mAppUnitsPerDevPixel; }

  /**
   * Convert device pixels which is used for gfx/thebes to nearest (rounded)
   * app units
   */
  nscoord GfxUnitsToAppUnits(gfxFloat aGfxUnits) const
  { return nscoord(NS_round(aGfxUnits * AppUnitsPerDevPixel())); }

  /**
   * Convert app units to device pixels which is used for gfx/thebes.
   */
  gfxFloat AppUnitsToGfxUnits(nscoord aAppUnits) const
  { return gfxFloat(aAppUnits) / AppUnitsPerDevPixel(); }

  /**
   * Gets the number of app units in one physical inch; this is the
   * device's DPI times AppUnitsPerDevPixel().
   */
  PRInt32 AppUnitsPerPhysicalInch() const { return mAppUnitsPerPhysicalInch; }

  /**
   * Gets the number of app units in one CSS inch; this is the
   * 96 times AppUnitsPerCSSPixel.
   */
  static PRInt32 AppUnitsPerCSSInch() { return 96 * AppUnitsPerCSSPixel(); }

  /**
   * Fill in an nsFont based on the ID of a system font.  This function
   * may or may not fill in the size, so the size should be set to a
   * reasonable default before calling.
   *
   * @param aID    The system font ID.
   * @param aInfo  The font structure to be filled in.
   * @return error status
   */
  NS_IMETHOD  GetSystemFont(nsSystemFontID aID, nsFont *aFont) const = 0;

  /**
   * Get the nsIFontMetrics that describe the properties of
   * an nsFont.
   * @param aFont font description to obtain metrics for
   * @param aLanguage the language of the document
   * @param aMetrics out parameter for font metrics
   * @param aUserFontSet user font set
   * @return error status
   */
  NS_IMETHOD  GetMetricsFor(const nsFont& aFont, nsIAtom* aLanguage,
                            gfxUserFontSet* aUserFontSet,
                            nsIFontMetrics*& aMetrics) = 0;

  /**
   * Get the nsIFontMetrics that describe the properties of
   * an nsFont.
   * @param aFont font description to obtain metrics for
   * @param aMetrics out parameter for font metrics
   * @param aUserFontSet user font set
   * @return error status
   */
  NS_IMETHOD  GetMetricsFor(const nsFont& aFont, gfxUserFontSet* aUserFontSet,
                            nsIFontMetrics*& aMetrics) = 0;

  /**
   * Check to see if a particular named font exists.
   * @param aFontName character string of font face name
   * @return NS_OK if font is available, else font is unavailable
   */
  NS_IMETHOD CheckFontExistence(const nsString& aFaceName) = 0;
  NS_IMETHOD FirstExistingFont(const nsFont& aFont, nsString& aFaceName) = 0;

  NS_IMETHOD GetLocalFontName(const nsString& aFaceName, nsString& aLocalName,
                              PRBool& aAliased) = 0;

  /**
   * Notification when a font metrics instance created for this device is
   * about to be deleted
   */
  NS_IMETHOD FontMetricsDeleted(const nsIFontMetrics* aFontMetrics) = 0;

  /**
   * Attempt to free up resoruces by flushing out any fonts no longer
   * referenced by anything other than the font cache itself.
   * @return error status
   */
  NS_IMETHOD FlushFontCache(void) = 0;

  /**
   * Return the bit depth of the device.
   */
  NS_IMETHOD GetDepth(PRUint32& aDepth) = 0;

  /**
   * Get the size of the displayable area of the output device
   * in app units.
   * @param aWidth out parameter for width
   * @param aHeight out parameter for height
   * @return error status
   */
  NS_IMETHOD GetDeviceSurfaceDimensions(nscoord &aWidth, nscoord &aHeight) = 0;

  /**
   * Get the size of the content area of the output device in app units.
   * This corresponds on a screen device, for instance, to the entire screen.
   * @param aRect out parameter for full rect. Position (x,y) will be (0,0) or
   *              relative to the primary monitor if this is not the primary.
   * @return error status
   */
  NS_IMETHOD GetRect ( nsRect &aRect ) = 0;

  /**
   * Get the size of the content area of the output device in app units.
   * This corresponds on a screen device, for instance, to the area reported
   * by GetDeviceSurfaceDimensions, minus the taskbar (Windows) or menubar
   * (Macintosh).
   * @param aRect out parameter for client rect. Position (x,y) will be (0,0)
   *              adjusted for any upper/left non-client space if present or
   *              relative to the primary monitor if this is not the primary.
   * @return error status
   */
  NS_IMETHOD GetClientRect(nsRect &aRect) = 0;

  /**
   * This is enables the DeviceContext to anything it needs to do for Printing
   * before Reflow and BeginDocument is where work can be done after reflow.
   * @param aTitle - itle of Document
   * @param aPrintToFileName - name of file to print to, if NULL then don't print to file
   *
   * @return error status
   */
  NS_IMETHOD PrepareDocument(PRUnichar * aTitle,
                             PRUnichar*  aPrintToFileName) = 0;

  //XXX need to work out re-entrancy issues for these APIs... MMP
  /**
   * Inform the output device that output of a document is beginning
   * Used for print related device contexts. Must be matched 1:1 with
   * EndDocument().
   * XXX needs to take parameters so that feedback can be given to the
   * app regarding pagination progress and aborting print operations?
   *
   * @param aTitle - itle of Document
   * @param aPrintToFileName - name of file to print to, if NULL then don't print to file
   * @param aStartPage - starting page number (must be greater than zero)
   * @param aEndPage - ending page number     (must be less than or equal to number of pages)
   *
   * @return error status
   */
  NS_IMETHOD BeginDocument(PRUnichar*  aTitle,
                           PRUnichar*  aPrintToFileName,
                           PRInt32     aStartPage,
                           PRInt32     aEndPage) = 0;

  /**
   * Inform the output device that output of a document is ending.
   * Used for print related device contexts. Must be matched 1:1 with
   * BeginDocument()
   * @return error status
   */
  NS_IMETHOD EndDocument(void) = 0;

  /**
   * Inform the output device that output of a document is being aborted.
   * Must be matched 1:1 with BeginDocument()
   * @return error status
   */
  NS_IMETHOD AbortDocument(void) = 0;

  /**
   * Inform the output device that output of a page is beginning
   * Used for print related device contexts. Must be matched 1:1 with
   * EndPage() and within a BeginDocument()/EndDocument() pair.
   * @return error status
   */
  NS_IMETHOD BeginPage(void) = 0;

  /**
   * Inform the output device that output of a page is ending
   * Used for print related device contexts. Must be matched 1:1 with
   * BeginPage() and within a BeginDocument()/EndDocument() pair.
   * @return error status
   */
  NS_IMETHOD EndPage(void) = 0;

  /**
   * Clear cached system fonts (refresh from theme when
   * requested).  This method is effectively static,
   * and can be called on a new DeviceContext instance
   * without any initialization.  Only really used by
   * Gtk native theme stuff.
   */
  NS_IMETHOD ClearCachedSystemFonts() = 0;

  /**
   * Check to see if the DPI has changed
   * @return whether there was actually a change in the DPI
   *         (whether AppUnitsPerDevPixel() or AppUnitsPerPhysicalInch() changed)
  */
  virtual PRBool CheckDPIChange() = 0;

  /**
   * Set the pixel scaling factor: all lengths are multiplied by this factor
   * when we convert them to device pixels. Returns whether the ratio of
   * app units to dev pixels changed because of the scale factor.
   */
  virtual PRBool SetPixelScale(float aScale) = 0;

  /**
   * Get the pixel scaling factor; defaults to 1.0, but can be changed with
   * SetPixelScale.
   */
  float GetPixelScale() const { return mPixelScale; }

  /**
   * Get the unscaled ratio of app units to dev pixels; useful if something
   * needs to be converted from to unscaled pixels
   */
  PRInt32 UnscaledAppUnitsPerDevPixel() const { return mAppUnitsPerDevNotScaledPixel; }

protected:
  PRInt32 mAppUnitsPerDevPixel;
  PRInt32 mAppUnitsPerPhysicalInch;
  PRInt32 mAppUnitsPerDevNotScaledPixel;
  float  mPixelScale;
};

NS_DEFINE_STATIC_IID_ACCESSOR(nsIDeviceContext, NS_IDEVICE_CONTEXT_IID)

#endif /* nsIDeviceContext_h___ */


text:
export default function subscriptionPricing() {
  window.recurly.Pricing.Subscription()
    .plan('basic', { quantity: 1 })
    .then(x => x)
    .addon('addon1', { quantity: 2 })
    .address({
      first_name: 'dave',
      last_name: 'b'
    })
    .address({
      first_name: 'dave',
      last_name: 'b',
      address1: 'address1',
      address2: 'address2',
      city: 'city',
      state: 'state',
      postal_code: 'postal_code',
      country: 'country',
      phone: 'phone',
      vat_number: 'vat_number'
    })
    .shippingAddress({
      first_name: 'dave',
      last_name: 'b'
    })
    .shippingAddress({
      first_name: 'dave',
      last_name: 'b',
      address1: 'address1',
      address2: 'address2',
      city: 'city',
      state: 'state',
      postal_code: 'postal_code',
      country: 'country',
      phone: 'phone',
      vat_number: 'vat_number'
    })
    .coupon('coupon')
    .currency('USD')
    .giftcard('giftcard')
    .tax({
      tax_code: 'tax_code'
    })
    .tax({
      tax_code: 'tax_code',
      vat_number: 'vat_number',
      amounts: {
        now: 'now',
        next: 'next'
      }
    })
    .catch(e => {
      e.code;
      e.classification;
      e.message;
      e.name;
    })
    .done(pricing => {
      if (pricing) {
        // $ExpectType string
        pricing.price.now.subtotal;
        // $ExpectType string
        pricing.price.now.plan;
        // $ExpectType string
        pricing.price.now.addons;
        // $ExpectType string
        pricing.price.now.setup_fee;
        // $ExpectType string
        pricing.price.now.discount;
        // $ExpectType string
        pricing.price.now.tax;
        // $ExpectType string
        pricing.price.now.total;
        // $ExpectType string
        pricing.price.next.subtotal;
        // $ExpectType string
        pricing.price.next.plan;
        // $ExpectType string
        pricing.price.next.addons;
        // $ExpectType string
        pricing.price.next.setup_fee;
        // $ExpectType string
        pricing.price.next.discount;
        // $ExpectType string
        pricing.price.next.tax;
        // $ExpectType string
        pricing.price.next.total;
        // $ExpectType string
        pricing.price.base.plan.unit;
        // $ExpectType string
        pricing.price.base.plan.setup_fee;
        // $ExpectType string
        pricing.price.base.addons.myAddon;
        // $ExpectType string
        pricing.price.addons.myAddon;
        // $ExpectType string
        pricing.price.currency.code;
        // $ExpectType string
        pricing.price.currency.symbol;
        // $ExpectType string
        pricing.price.taxes[0].rate;
        // $ExpectType string
        pricing.price.taxes[0].region;
        // $ExpectType string
        pricing.price.taxes[0].tax_type;
      }
    });
}

redpajama_set_name: RedPajamaGithub


text:
import datetime

from django.core.management.base import BaseCommand
from django.core import exceptions
from importlib import import_module

import statsd

from zesty_metrics import conf

from zesty_metrics.models import DailyActivityRecord

class Command(BaseCommand):
    help = """Clean up old activity records."""

    def add_arguments(self, parser):
        parser.add_argument('--days',
                            dest='days',
                            type=int,
                            default=90,
                            help='Delete records older than this many days.')

    def delete_records(self, delete_before):
        DailyActivityRecord.objects.filter(when__lt=delete_before).delete()

    def handle(self, **options):
        days = options['days']
        today = datetime.date.today()
        delete_before = today - datetime.timedelta(days=days)

        self.delete_records(delete_before)


text:
layout: default
title: "CartoDB Workshops"
---
#### WELCOME!

Check out the side bar for featured workshop scripts (at Beginner, Intermediate, Advanced, and Special Topics levels).

Review the [`img/`](https://github.com/CartoDB/training/tree/gh-pages/img) and [`data/`](https://github.com/CartoDB/training/tree/gh-pages/data), and [`templates/`](https://github.com/CartoDB/training/tree/gh-pages/templates) directories for support images, data hardcopies, and code templates referenced in workshops.

Below you'll find a map of the places we've traveled to give trainings! If you [submit materials](http://cartodb.github.io/training/submit.html) from your event, ping [Andy](mailto:eschbacher@cartodb.com) to add your event details to the map!

<iframe width="100%" height="480px" src="workshops_map.html"></iframe>


text:
@interface ZhengCacheSQLite ()

@property (nonatomic, strong) FMDatabase *myDataBase;

@end

@implementation ZhengCacheSQLite

- (BOOL)cachePageJson:(NSArray *)cacheArray zhengPageRequest:(ZhengPageRequest *)zhengPageRequest{

    NSString *urlStr = zhengPageRequest.urlStr;
    CacheMethod cacheMethod = zhengPageRequest.cacheMethod;

    //缓存完整路径
    NSString *cachefullPath = [ZhengCacheDirectory cacheFullPathWithDirectory:urlStr cacheMethod:cacheMethod];

    //检查文件是否超出限制大小
    if ([ZhengCacheDirectory fileIsExistsAtPath:cachefullPath]) {
        long long fileSize = [ZhengCacheDirectory readFileSize:cachefullPath];
        if (fileSize > SqliteFileLimtSize) {
            [ZhengCacheDirectory deleteFileAtPath:cachefullPath];
        }
    }

    self.myDataBase = [FMDatabase databaseWithPath:cachefullPath];

    if ([self.myDataBase open]) {   //数据库打开成功

        // 创表  字段   id  dict_ID  my_respose_dict
        NSString *creatTableStr = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id integer PRIMARY KEY AUTOINCREMENT,%@ text NOT NULL,%@ blob NOT NULL);",SQTableName,SQDicID,SQDicFiledName];
        BOOL result = [self.myDataBase executeUpdate:creatTableStr];

        if (result) {      //创表成功
            for (NSDictionary *dic in cacheArray) {
                //取出字典唯一ID
                NSString *dicID = [NSString stringWithFormat:@"%@",dic[EachInfoID]];
                // 把cacheDic字典对象序列化成NSData二进制数据  存储数据库
                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];

                //插入数据之前先查询数据库有没有该条信息
                FMResultSet *resultSet = nil;
                NSString *selectStr = [NSString stringWithFormat:@"SELECT * FROM %@ where %@ = %@;",SQTableName,SQDicID,dicID];
                resultSet = [self.myDataBase executeQuery:selectStr];

                if (resultSet.next == NO) {  //插入数据

                    [self.myDataBase executeUpdate:@"INSERT INTO t_myTable (my_respose_dict,dict_ID) VALUES (?, ?);", data,dicID];

                }else{  //更新数据
                    [self.myDataBase executeUpdate:@"UPDATE t_myTable set my_respose_dict = ? where dict_ID = ?;", data,dicID];
                }
            }
            return [self.myDataBase close];
        } else {  //创表失败
            return NO;
        }
    }else{   //数据库打开失败
        return NO;
    }
}

- (NSArray *)readPageJson:(ZhengPageRequest *)zhengPageRequest{

    NSString *urlStr = zhengPageRequest.urlStr;
    CacheMethod cacheMethod = zhengPageRequest.cacheMethod;

    //缓存完整路径
    NSString *cachefullPath = [ZhengCacheDirectory cacheFullPathWithDirectory:urlStr cacheMethod:cacheMethod];

    //不存在文件直接返回空
    if (![ZhengCacheDirectory fileIsExistsAtPath:cachefullPath]){
        return nil;
    }
    //缓存过期
    if ([ZhengCacheDirectory fileIsExpiredAtPath:cachefullPath expiredTime:zhengPageRequest.expiredTime]) {
        return nil;
    }

    //设置页码 限制条数
    NSInteger page = zhengPageRequest.page;
    NSInteger limit = zhengPageRequest.limit.integerValue;

    self.myDataBase = [FMDatabase databaseWithPath:cachefullPath];

    if ([self.myDataBase open]) {
        //查询数据
        NSMutableArray *statuses = [NSMutableArray array];
        // 根据请求参数查询数据
        FMResultSet *resultSet = nil;
        NSString *selectStr = [NSString stringWithFormat:@"SELECT * FROM %@ order by %@ desc limit %ld, %ld;",SQTableName,SQDicID,limit * (page - 1),limit];
        resultSet = [self.myDataBase executeQuery:selectStr];

        // 遍历查询结果
        while (resultSet.next) {
            NSData *dictData = [resultSet objectForColumnName:SQDicFiledName];
            NSDictionary *getDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictData];
            [statuses addObject:getDict];
        }
        if (statuses == nil || statuses.count == 0) {
            return nil;
        }else{
            return statuses;
        }
    }
    return nil;
}

// 单例
static id _instance;
+ (instancetype)shareCacheSQLite{
    if (_instance == nil) {
        _instance = [[self alloc] init];
    }
    return _instance;
}

- (void)dealloc{

}

@end


text:
.PHONY: deps
deps:
	pip install -U -r requirements.txt

.PHONY: install
install:
	make deps
	rm -rf dist/*
	python setup.py sdist
	pip install dist/*

.PHONY: upload-pypi
upload-pypi:
	pip install --upgrade pip setuptools wheel
	pip install twine
	sh pypi_upload.sh


text:
cask 'webrecorder-player' do
  version '1.6.2'
  sha256 '7f67af03c0815797b8421d2da2dae1b69b3b75a47f74ae38194a66dba3b63d88'

  url "https://github.com/webrecorder/webrecorder-player/releases/download/v#{version}/webrecorder-player-#{version}.dmg"
  appcast 'https://github.com/webrecorder/webrecorderplayer-electron/releases.atom'
  name 'Webrecorder Player'
  homepage 'https://github.com/webrecorder/webrecorderplayer-electron'

  app 'Webrecorder Player.app'

  zap trash: [
               '~/Library/Application Support/Webrecorder Player',
               '~/Library/Preferences/org.webrecorder.webrecorderplayer.helper.plist',
               '~/Library/Preferences/org.webrecorder.webrecorderplayer.plist',
               '~/Library/Saved Application State/org.webrecorder.webrecorderplayer.savedState',
             ]
end


text:
package models;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import stats.Stat;
import stats.Subject;

public class SoccerTeam extends Team {

	private static final String FILEPATH = "resources/teams/";
    protected User owner;
    protected String teamName;
    protected double budget;
    private int amountOfPlayersAllowed;
    protected ArrayList<SoccerPlayer> selectPlayers = new ArrayList<SoccerPlayer>();
    protected HashMap<String, Integer> positions = new HashMap<>();
    protected Subject subject;
    protected int totalPoints = 0;

	public SoccerTeam(String teamname, User owner, Subject listener) {
		// Create empty team.
		this.teamName = teamname;
		this.owner = owner;
		this.subject = listener;

		setAmountOfPlayersAllowed(15);
		this.budget = 100.0;
		this.positions.put("G", 2);
		this.positions.put("D", 5);
		this.positions.put("M", 5);
		this.positions.put("F", 3);

		// update();
	}

	public SoccerTeam(String teamname, User owner, double budget, ArrayList<SoccerPlayer> players, int points, Subject listener) {
		// Load team from file.
		this.teamName = teamname;
		this.owner = owner;

		subject = listener;
		this.budget = budget;
		this.totalPoints = points;
		setAmountOfPlayersAllowed(15);
		positions.put("G", 2);
		positions.put("D", 5);
		positions.put("M", 5);
		positions.put("F", 3);

		selectPlayers.addAll(players);

	}

	public ArrayList<SoccerPlayer> getPlayerList() {
		return selectPlayers;
	}

	@Override
	public int getTotalPoints(){
		return totalPoints;
	}

	public int getAmountOfPlayersAllowed() {
		return amountOfPlayersAllowed;
	}

	public void setAmountOfPlayersAllowed(int amountOfPlayersAllowed) {
		this.amountOfPlayersAllowed = amountOfPlayersAllowed;
	}

	@Override
	public double getBudget() {
		return budget;
	}

	public void setBudget(double budget) {
		this.budget = budget;
	}

	public void decrementBudget(double a) {
		budget = budget - a;
	}

	@Override
	public User getOwner() {
		return this.owner;
	}

	@Override
	public String getTeamName() {
		return teamName;
	}

	public void setTeamName(String teamName) {
		this.teamName = teamName;
	}

	public void incrementBudget(String a) {
		for (int i = 0; i < selectPlayers.size(); i++)
			if (selectPlayers.get(i).getID().equals(a))
				budget = budget + selectPlayers.get(i).getValue();
	}

	public void removePlayer(String p) {
		for (int i = 0; i < selectPlayers.size(); i++)
			if (selectPlayers.get(i).getID().equals(p))
				selectPlayers.remove(i);
	}

	public boolean checkBudgetAmount(double amount) {
		if (budget - amount >= 0)
			return true;
		return false;
	}

	public boolean tryAddPlayer(SoccerPlayer nextPlayer) {
		if (isValidTeamAddition(nextPlayer, getNumberOfPlayersAtPosition(nextPlayer.getPosition()))) {
			selectPlayers.add(nextPlayer);
			return true;
		}
		return false;
	}

	public int getNumberOfPlayersAtPosition(String position) {
		int count = 0;
		for (int c = 0; c < selectPlayers.size(); c++)
			if ((selectPlayers.get(c).getPosition()).equals(position))
				count++;
		return count;
	}

	public boolean isValidTeamAddition(SoccerPlayer player, int count) {
		boolean nextStage = true;

		for (int i = 0; i < selectPlayers.size(); i++)
			if (player.getID().equals(selectPlayers.get(i).getID()))
				nextStage = false;

		if (checkBudgetAmount(player.getValue()) == false)
			nextStage = false;

		if (nextStage == true) {
			if (count < positions.get(player.getPosition())) {
				return true;
			} else
				return false;
		}
		return false;
	}

	 public synchronized boolean save() {
	    	/*Format: filename = teamname
	    	 * ownerName
	    	 * budget
	    	 * points
	    	 * player1
	    	 * player2...
	    	 */
	    	ArrayList<String> output = new ArrayList<String>();
	    	File saveFile = new File(FILEPATH + this.teamName);

	    	output.add(owner.getUserName());
	    	output.add(Double.toString(budget));
	    	output.add(Integer.toString(totalPoints));
	    	for(Player player: selectPlayers){
	    		output.add(player.getID());
	    	}
	    	try{
	    		AsyncWriteUtil writer = new AsyncWriteUtil(output, saveFile);
	    		writer.run();
	    	}
	    	catch(IOException e){
	    		return false;
	    	}
	    	return true;
	    }

		@Override
		public synchronized void update() {
			Map<Integer, List<Stat>> stats = (Map<Integer, List<Stat>>)subject.getState();
			for(Map.Entry<Integer, List<Stat>> statList : stats.entrySet()){
				for(Player player: selectPlayers)
					if(statList.getKey() == Integer.parseInt(player.getID())){
						for(Stat stat: statList.getValue())
							totalPoints += stat.getScore();
					}
			}
			save();
		}
}


text:
namespace mx
{
    namespace core
    {

        MX_FORWARD_DECLARE_ATTRIBUTES( GroupBarlineAttributes )

        struct GroupBarlineAttributes : public AttributesInterface
        {
        public:
            GroupBarlineAttributes();
            virtual bool hasValues() const;
            virtual std::ostream& toStream( std::ostream& os ) const;
            Color color;
            bool hasColor;

            private:
            virtual bool fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement );
        };
    }
}


text:
Modal Browser which can be used in the application

Link to blog: Design Studio SDK: In-App Modal Browser Popup


text:
#define __DBENTRY_MAIN__
#include "DBEntry.h"
#undef __DBENTRY_MAIN__

#include <string.h>

DBEntry *DBEntry_new() {
  DBEntry *dbe;

  if ((dbe = (DBEntry *)calloc(1,sizeof(DBEntry))) == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for dbe\n");
    return NULL;
  }

  dbe->objectType = CLASS_DBENTRY;

  dbe->funcs = &dBEntryFuncs;

  Object_incRefCount(dbe);
  return dbe;
}

char *DBEntry_setDisplayId(DBEntry *dbe, char *displayId) {
  if ((dbe->displayId = (char *)malloc(strlen(displayId)+1)) == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for displayId\n");
    return NULL;
  }

  strcpy(dbe->displayId,displayId);

  return dbe->displayId;
}

char *DBEntry_setPrimaryId(DBEntry *dbe, char *primaryId) {
  if ((dbe->primaryId = (char *)malloc(strlen(primaryId)+1)) == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for primaryId\n");
    return NULL;
  }

  strcpy(dbe->primaryId,primaryId);

  return dbe->primaryId;
}

// Not sure if this one should be char * or ECOSSTRING
char *DBEntry_setInfoText(DBEntry *dbe, char *infoText) {
  if ((dbe->infoText = (char *)malloc(strlen(infoText)+1)) == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for infoText\n");
    return NULL;
  }

  strcpy(dbe->infoText,infoText);

  return dbe->infoText;
}

char *DBEntry_setDescription(DBEntry *dbe, char *description) {
  if ((dbe->description = (char *)malloc(strlen(description)+1)) == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for description\n");
    return NULL;
  }

  strcpy(dbe->description,description);

  return dbe->description;
}

ECOSTRING DBEntry_setDbName(DBEntry *dbe, char *dbName) {
  EcoString_copyStr(ecoSTable, &(dbe->dbName),dbName,0);

  if (dbe->dbName == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for dbName\n");
    return NULL;
  }

  return dbe->dbName;
}

ECOSTRING DBEntry_setDbDisplayName(DBEntry *dbe, char *dbDisplayName) {
  EcoString_copyStr(ecoSTable, &(dbe->dbDisplayName),dbDisplayName,0);

  if (dbe->dbDisplayName == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for dbDisplayName\n");
    return NULL;
  }

  return dbe->dbDisplayName;
}

int DBEntry_addSynonym(DBEntry *dbe, char *syn) {
  if (!dbe->synonyms) {
    dbe->synonyms = Vector_new();
  }
  Vector_addElement(dbe->synonyms, syn);
  return 1;
}

ECOSTRING DBEntry_setStatus(DBEntry *dbe, char *status) {
  EcoString_copyStr(ecoSTable, &(dbe->status),status,0);

  if (dbe->status == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for status\n");
    return NULL;
  }

  return dbe->status;
}

ECOSTRING DBEntry_setVersion(DBEntry *dbe, char *version) {
  EcoString_copyStr(ecoSTable, &(dbe->version),version,0);

  if (dbe->version == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for version\n");
    return NULL;
  }

  return dbe->version;
}

ECOSTRING DBEntry_setRelease(DBEntry *dbe, char *release) {
  EcoString_copyStr(ecoSTable, &(dbe->release),release,0);

  if (dbe->release == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for release\n");
    return NULL;
  }

  return dbe->release;
}

ECOSTRING DBEntry_setInfoType(DBEntry *dbe, char *infoType) {
  EcoString_copyStr(ecoSTable, &(dbe->infoType),infoType,0);

  if (dbe->infoType == NULL) {
    fprintf(stderr,"ERROR: Failed allocating space for infoType\n");
    return NULL;
  }

  return dbe->infoType;
}

void DBEntry_free(DBEntry *dbe) {
  Object_decRefCount(dbe);

  if (Object_getRefCount(dbe) > 0) {
    return;
  } else if (Object_getRefCount(dbe) < 0) {
    fprintf(stderr,"Error: Negative reference count for DBEntry\n"
                   "       Freeing it anyway\n");
  }

  if (dbe->dbName) EcoString_freeStr(ecoSTable, dbe->dbName);
  if (dbe->dbDisplayName) EcoString_freeStr(ecoSTable, dbe->dbDisplayName);
  if (dbe->status) EcoString_freeStr(ecoSTable, dbe->status);
  if (dbe->version) EcoString_freeStr(ecoSTable, dbe->version);
  if (dbe->release) EcoString_freeStr(ecoSTable, dbe->release);
  if (dbe->infoType) EcoString_freeStr(ecoSTable, dbe->infoType);

  if (dbe->displayId)   free(dbe->displayId);
  if (dbe->description) free(dbe->description);
  if (dbe->primaryId)   free(dbe->primaryId);
  if (dbe->infoText)    free(dbe->infoText);

  if (dbe->synonyms) Vector_free(dbe->synonyms);

  if (dbe->idXref) IdentityXref_free(dbe->idXref);

  free(dbe);
}


text:
/***********************************************************************
    filename:   InjectedInputReceiver.h
    created:    Thu Feb 16 2012
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _CEGUIInjectedInputReceiver_h_
#define _CEGUIInjectedInputReceiver_h_

#include "CEGUI/InputEvent.h"

namespace CEGUI
{

//! Input injection interface to be inplemented by classes that take raw inputs
class CEGUIEXPORT InjectedInputReceiver
{
public:
    virtual ~InjectedInputReceiver() {}

    /*!
    \brief
        Function that injects a mouse movement event into the receiver.

    \param delta_x
        amount the mouse moved on the x axis.

    \param delta_y
        amount the mouse moved on the y axis.

    \return
        - true if the input was processed by the input receiver.
        - false if the input was not processed by the input receiver.
    */
    virtual bool injectMouseMove(float delta_x, float delta_y) = 0;

    /*!
    \brief
        Function that notifies that the mouse has left the host area that the
        receiver receives input for.

    \return
        - true if the event was handled.
        - false if the event was not handled.
    */
    virtual bool injectMouseLeaves() = 0;

    /*!
    \brief
        Function that injects a mouse button down event into the receiver.

    \param button
        One of the MouseButton values indicating which button was pressed.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectMouseButtonDown(MouseButton button) = 0;

    /*!
    \brief
        Function that injects a mouse button up event into the receiver.

    \param button
        One of the MouseButton values indicating which button was released.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectMouseButtonUp(MouseButton button) = 0;

    /*!
    \brief
        Function that injects a key down event into the receiver.

    \param key_code
        uint value indicating which key was pressed.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectKeyDown(Key::Scan scan_code) = 0;

    /*!
    \brief
        Function that injects a key up event into the receiver.

    \param key_code
        Key::Scan value indicating which key was released.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectKeyUp(Key::Scan scan_code) = 0;

    /*!
    \brief
        Function that injects a typed character event into the receiver.

    \param code_point
        Unicode or ASCII (depends on used String class) code point of the character that was typed.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectChar(String::value_type code_point) = 0;

    /*!
    \brief
        Function that injects a mouse-wheel / scroll-wheel event into the receiver.

    \param delta
        float value representing the amount the wheel moved.

    \return
        - true if the input was processed by the receiver.
        - false if the input was not processed by the receiver.
    */
    virtual bool injectMouseWheelChange(float delta) = 0;

    /*!
    \brief
        Function that injects a new position for the mouse cursor.

    \param x_pos
        New absolute pixel position of the mouse cursor on the x axis.

    \param y_pos
        New absolute pixel position of the mouse cursoe in the y axis.

    \return
        - true if the generated mouse move event was handled.
        - false if the generated mouse move event was not handled.
    */
    virtual bool injectMousePosition(float x_pos, float y_pos) = 0;

    /*!
    \brief
        Function to inject time pulses into the receiver.

    \param timeElapsed
        float value indicating the amount of time passed, in seconds, since the last time this method was called.

    \return
        Currently, this method always returns true.
    */
    virtual bool injectTimePulse(float timeElapsed) = 0;

    /*!
    \brief
        Function to directly inject a mouse button click event.

        Here 'click' means a mouse button down event followed by a mouse
        button up event.

    \note
        Under normal, default settings, this event is automatically generated by
        the system from the regular up and down events you inject.  You may use
        this function directly, though you'll probably want to disable the
        automatic click event generation first by using the
        setMouseClickEventGenerationEnabled function - this setting controls the
        auto-generation of events and also determines the default 'handled'
        state of the injected click events according to the rules used for
        mouse up/down events.

    \param button
        One of the MouseButton enumerated values.

    \return
        - true if some window or handler reported that it handled the event.
        - false if nobody handled the event.
    */
    virtual bool injectMouseButtonClick(const MouseButton button) = 0;

    /*!
    \brief
        Function to directly inject a mouse button double-click event.

        Here 'double-click' means a single mouse button had the sequence down,
        up, down within a predefined period of time.

    \note
        Under normal, default settings, this event is automatically generated by
        the system from the regular up and down events you inject.  You may use
        this function directly, though you'll probably want to disable the
        automatic click event generation first by using the
        setMouseClickEventGenerationEnabled function - this setting controls the
        auto-generation of events and also determines the default 'handled'
        state of the injected click events according to the rules used for
        mouse up/down events.

    \param button
        One of the MouseButton enumerated values.

    \return
        - true if some window or handler reported that it handled the event.
        - false if nobody handled the event.
    */
    virtual bool injectMouseButtonDoubleClick(const MouseButton button) = 0;

    /*!
    \brief
        Function to directly inject a mouse button triple-click event.

        Here 'triple-click' means a single mouse button had the sequence down,
        up, down, up, down within a predefined period of time.

    \note
        Under normal, default settings, this event is automatically generated by
        the system from the regular up and down events you inject.  You may use
        this function directly, though you'll probably want to disable the
        automatic click event generation first by using the
        setMouseClickEventGenerationEnabled function - this setting controls the
        auto-generation of events and also determines the default 'handled'
        state of the injected click events according to the rules used for
        mouse up/down events.

    \param button
        One of the MouseButton enumerated values.

    \return
        - true if some window or handler reported that it handled the event.
        - false if nobody handled the event.
    */
    virtual bool injectMouseButtonTripleClick(const MouseButton button) = 0;

    /*!
    \brief
        Tells the receiver to perform a clipboard copy operation.

    \return
        - true if the copy was successful
        - false if the copy was denied
    */
    virtual bool injectCopyRequest() = 0;

    /*!
    \brief
        Tells the system to perform a clipboard cut operation.

    \return
        - true if the cut was successful
        - false if the cut was denied
    */
    virtual bool injectCutRequest() = 0;

    /*!
    \brief
        Tells the system to perform a clipboard paste operation.

    \return
        - true if the paste was successful
        - false if the paste was denied
    */
    virtual bool injectPasteRequest() = 0;
};

}

#endif


text: <!doctype html>


text:
<!DOCTYPE html>

    <title>extendedArray.js by Greg Saive</title>

Watch your developer console ;)


text:
layout: default
nav: home
---
I'm Song Kong, a student from BUPT. This is my online home & blog, where I share thoughts about front-end development, my daily life and other insteresting topics. Feel free to contact me by email if you have any question.


text:
package org.trustedanalytics.das.store.cloud;

import java.util.Map;
import java.util.Optional;

import org.trustedanalytics.das.store.RequestStore;
import org.springframework.data.redis.core.BoundHashOperations;

import org.trustedanalytics.das.parser.Request;

public class RedisRequestRepository implements RequestStore {

    private final BoundHashOperations<String, String, Request> hashOps;

    public RedisRequestRepository(BoundHashOperations<String, String, Request> hashOps) {
        this.hashOps = hashOps;
    }

    @Override
    public void put(Request request) {
        hashOps.put(
            this.getOrgPrefixedKey(request.getOrgUUID(), request.getId()),
            request);
    }

    @Override
    public Optional<Request> get(String key) {
        return this.filterByKey(this.hashOps.entries(), key).values()
            .stream()
            .findFirst();
    }

    @Override
    public Map<String, Request> getAll(String orgUUID) {
        return this.filterByOrgId(this.hashOps.entries(), orgUUID);
    }

    @Override
    public void delete(String key) {
        String fullKey =
            this.filterByKey(this.hashOps.entries(), key).keySet().stream().findFirst().get();
        hashOps.delete(fullKey);
    }
}


text:
======
Mousey
======

.. image:: https://img.shields.io/badge/python-3.6-blue.svg
  :target: https://www.python.org/

.. image:: https://img.shields.io/badge/License-MIT-blue.svg
  :target: https://github.com/FrostLuma/Mousey/blob/master/LICENSE

.. image:: https://discordapp.com/api/guilds/288369367769677826/widget.png
  :target: http://discord.gg/Bd7BuGh

Mousey is a Discord Bot written by FrostLuma to provide powerful moderation and utility features.

------------
Using Mousey
------------

You can use Mousey by simply `inviting her to your Discord Server
<https://discordapp.com/oauth2/authorize?client_id=288369203046645761&scope=bot&permissions=500559095>`_.

-----------
Development
-----------

Running Mousey for development is really simple:

.. code-block :: bash

  git clone https://github.com/FrostLuma/Mousey.git

  cd Mousey

  cp example_config.yaml config.yaml
  # edit config.yaml to include your credentials

  docker-compose up

Running Mousey outside of Docker is also possible, it is however not recommended due to it being more work to set up.


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require my_admin/bootstrap
 *= require my_admin/bootstrap-responsive
 *= require my_admin/plugins/jquery-ui/smoothness/jquery-ui
 *= require my_admin/plugins/jquery-ui/smoothness/jquery.ui.theme
 *= require my_admin/plugins/pageguide/pageguide
 *= require my_admin/plugins/fullcalendar/fullcalendar
 *= require my_admin/plugins/fullcalendar/fullcalendar.print
 *= require my_admin/plugins/datatable/TableTools
 *= require my_admin/plugins/chosen/chosen
 *= require my_admin/plugins/select2/select2
 *= require my_admin/plugins/colorpicker/colorpicker
 *= require my_admin/plugins/datepicker/datepicker
 *= require my_admin/plugins/timepicker/bootstrap-timepicker.min
 *= require my_admin/plugins/xeditable/bootstrap-editable
 *= require my_admin/plugins/icheck/flat/_all
 *= require my_admin/plugins/sweetalert/sweetalert
 *= require my_admin/style
 *= require my_admin/themes
 *= require my_admin/loading
 *= require my_admin/my_admin
 *= require my_admin
 */


text:
- Using money for upvotes isn't really a feature. It's not necessary to
  decentralize reddit. What is wrong with reddit that money fixes?

- Subreddits, not tags. Tags mean one submission has several audiences with one
  comments section. Subreddits divide comments in very useful ways. The
  moderators define not just the submissions, but the culture of the comments.

- Users should be able to pick their own moderators for a subreddit. A
  subreddit is a topic and an ethos, but that's orthogonal to who the enforcers
  of the topic and ethos are.

- Maybe each moderator is effectively a publisher of the entire subreddit.
  Filtering out garbage content happens on their machine, assisted by rule sets
  like user bans, anonymity bans, trusted commenters, and trusted fellow
  moderators to import rule sets from. They publish their results to a
  decentralized content store, like IPFS or Swarm.

- I think it's going to be useful to think of the backends of decentralized
  applications as two parts: live data that users send to participate in the
  system, and servers that collect that data, index it in useful ways, and
  serve it over read -only APIs. It probably isn't feasible for each client to
  piece together all the votes and submissions to generate a subreddit, but as
  long as anyone can launch a server that does that, the promise of
  decentralization is maintained. If the server relays submissions of votes,
  comments and submissions to the decentralized backend that the system runs
  on, this also avoids the dependency on a local daemon that many decentralized
  tools. Hosting one of these servers is a small to medium opportunity for
  profit.

- Ethereum, Whisper and Swarm/IPFS. Using the best toolkit for decentralized
  applications is a huge advantage. It makes it less likely that someone will
  start a new decentralized reddit project that isn't a benevolent fork of this
  one. One of the huge advantages of decentralized apps is that if built right,
  the user base never splits even with competition. Each competitor builds on
  top of what already exists to benefit from the existing user base. That won't
  happen if your system is hard to build on.

- You probably only need a blockchain (Ethereum's, hopefully) for a tiny
  fraction of the functionality. The identity of each subreddit probably needs
  to be on a blockchain so it's easy to pull down all of them. Once you have a
  subreddit identity, you can just listen for people broadcasting data for that
  subreddit over Whisper: moderator candidates, new comments, posts and votes,
  the location of historical indices, etc.


text:
get '/' do
  @questions = Question.all
  # find top 10 questions with biggest total value of votes
  # @user = current_user
  erb :'index'
end


text:
<?php
namespace Album\Form;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\inputFilter;
use Zend\InputFilter\inputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class AlbumFilter implements InputFilterAwareInterface{
	protected $inputFilter;

	public function setInputFilter(InputFilterInterface $inputFilter){
		throw new \Exception("No implementado");
	}

	public function getInputFilter(){
		if(!$this->inputFilter){
			$inputFilter =new inputFilter();
			$factory = new InputFactory();

			$inputFilter->add($factory->createInput(array(
				'name' => 'id',
				'required' => true,
				'filters' => array(
						array('name'=>'Int')
					),
				)));

			$inputFilter->add($factory->createInput(array(
				'name' => 'artist',
				'required' => true,
				'filters' => array(
						array('name'=>'StripTags'),
						array('name'=>'StringTrim'),
					),
				 'validators' => array(
				 		array(
				 		   'name' => 'StringLength',
				 		   'options'=>array(
				 		   		'encoding' =>'UTF-8',
				 		   		'min'=>1,
				 		   		'max'=>100
				 		   	),
				 		),
				 	),
				)));

			$inputFilter->add($factory->createInput(array(
				'name' => 'title',
				'required' => true,
				'filters' => array(
						array('name'=>'StripTags'),
						array('name'=>'StringTrim'),
					),
				 'validators' => array(
				 		array(
				 		   'name' => 'StringLength',
				 		   'options'=>array(
				 		   		'encoding' =>'UTF-8',
				 		   		'min'=>1,
				 		   		'max'=>100
				 		   	),
				 		),
				 	),
				)));

			$this->inputFilter = $inputFilter;
		}
		return $this->inputFilter;
	}

}
?>


text:
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/h2non/bimg"
	"github.com/rs/cors"
	"gopkg.in/throttled/throttled.v2"
	"gopkg.in/throttled/throttled.v2/store/memstore"
)

func Middleware(fn func(http.ResponseWriter, *http.Request), o ServerOptions) http.Handler {
	next := http.Handler(http.HandlerFunc(fn))

	if len(o.Endpoints) > 0 {
		next = filterEndpoint(next, o)
	}
	if o.Concurrency > 0 {
		next = throttle(next, o)
	}
	if o.CORS {
		next = cors.Default().Handler(next)
	}
	if o.APIKey != "" {
		next = authorizeClient(next, o)
	}
	if o.HTTPCacheTTL >= 0 {
		next = setCacheHeaders(next, o.HTTPCacheTTL)
	}

	return validate(defaultHeaders(next), o)
}

func ImageMiddleware(o ServerOptions) func(Operation) http.Handler {
	return func(fn Operation) http.Handler {
		handler := validateImage(Middleware(imageController(o, fn), o), o)

		if o.EnableURLSignature {
			return validateURLSignature(handler, o)
		}

		return handler
	}
}

func filterEndpoint(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if o.Endpoints.IsValid(r) {
			next.ServeHTTP(w, r)
			return
		}
		ErrorReply(r, w, ErrNotImplemented, o)
	})
}

func throttleError(err error) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "throttle error: "+err.Error(), http.StatusInternalServerError)
	})
}

func throttle(next http.Handler, o ServerOptions) http.Handler {
	store, err := memstore.New(65536)
	if err != nil {
		return throttleError(err)
	}

	quota := throttled.RateQuota{MaxRate: throttled.PerSec(o.Concurrency), MaxBurst: o.Burst}
	rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
	if err != nil {
		return throttleError(err)
	}

	httpRateLimiter := throttled.HTTPRateLimiter{
		RateLimiter: rateLimiter,
		VaryBy:      &throttled.VaryBy{Method: true},
	}

	return httpRateLimiter.RateLimit(next)
}

func validate(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet && r.Method != http.MethodPost {
			ErrorReply(r, w, ErrMethodNotAllowed, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func validateImage(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if r.Method == http.MethodGet && isPublicPath(path) {
			next.ServeHTTP(w, r)
			return
		}

		if r.Method == http.MethodGet && o.Mount == "" && !o.EnableURLSource {
			ErrorReply(r, w, ErrGetMethodNotAllowed, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func authorizeClient(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := r.Header.Get("API-Key")
		if key == "" {
			key = r.URL.Query().Get("key")
		}

		if key != o.APIKey {
			ErrorReply(r, w, ErrInvalidAPIKey, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func defaultHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Server", fmt.Sprintf("imaginary %s (bimg %s)", Version, bimg.Version))
		next.ServeHTTP(w, r)
	})
}

func setCacheHeaders(next http.Handler, ttl int) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer next.ServeHTTP(w, r)

		if r.Method != http.MethodGet || isPublicPath(r.URL.Path) {
			return
		}

		ttlDiff := time.Duration(ttl) * time.Second
		expires := time.Now().Add(ttlDiff)

		w.Header().Add("Expires", strings.Replace(expires.Format(time.RFC1123), "UTC", "GMT", -1))
		w.Header().Add("Cache-Control", getCacheControl(ttl))
	})
}

func getCacheControl(ttl int) string {
	if ttl == 0 {
		return "private, no-cache, no-store, must-revalidate"
	}
	return fmt.Sprintf("public, s-maxage=%d, max-age=%d, no-transform", ttl, ttl)
}

func isPublicPath(path string) bool {
	return path == "/" || path == "/health" || path == "/form"
}

func validateURLSignature(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Retrieve and remove URL signature from request parameters
		query := r.URL.Query()
		sign := query.Get("sign")
		query.Del("sign")

		// Compute expected URL signature
		h := hmac.New(sha256.New, []byte(o.URLSignatureKey))
		_, _ = h.Write([]byte(r.URL.Path))
		_, _ = h.Write([]byte(query.Encode()))
		expectedSign := h.Sum(nil)

		urlSign, err := base64.RawURLEncoding.DecodeString(sign)
		if err != nil {
			ErrorReply(r, w, ErrInvalidURLSignature, o)
			return
		}

		if !hmac.Equal(urlSign, expectedSign) {
			ErrorReply(r, w, ErrURLSignatureMismatch, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}


text:
"""Contains the logic for `aq search system`."""

from aquilon.aqdb.model import DnsRecord
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.formats.list import StringAttributeList
from aquilon.worker.dbwrappers.system import search_system_query

class CommandSearchSystem(BrokerCommand):

    required_parameters = []

    def render(self, session, fullinfo, style, **arguments):
        self.deprecated_command("Command search_system is deprecated. Please "
                                "use search_hardware, search_host, or "
                                "search_dns instead.", **arguments)
        q = search_system_query(session, DnsRecord, **arguments)
        if fullinfo or style != "raw":
            return q.all()
        return StringAttributeList(q.all(), 'fqdn')