text:
namespace XPlat.Services.Maps
{
    using System.Collections.Generic;
    using System.Linq;

    /// Represents an address.
    public class MapAddress : IMapAddress
    {
        ///
        /// Initializes a new instance of the <see cref="MapAddress"/> class.
        ///
        public MapAddress()
        {
        }

#if WINDOWS_UWP
        ///
        /// Initializes a new instance of the <see cref="MapAddress"/> class.
        ///
        public MapAddress(Windows.Services.Maps.MapAddress mapAddress)
        {
            this.BuildingName = mapAddress.BuildingName;
            this.BuildingFloor = mapAddress.BuildingFloor;
            this.BuildingRoom = mapAddress.BuildingRoom;
            this.BuildingWing = mapAddress.BuildingWing;
            this.StreetNumber = mapAddress.StreetNumber;
            this.Street = mapAddress.Street;
            this.Neighborhood = mapAddress.Neighborhood;
            this.District = mapAddress.District;
            this.Town = mapAddress.Town;
            this.Region = mapAddress.Region;
            this.RegionCode = mapAddress.RegionCode;
            this.Country = mapAddress.Country;
            this.CountryCode = mapAddress.CountryCode;
            this.PostCode = mapAddress.PostCode;
            this.Continent = mapAddress.Continent;
        }

        public static implicit operator MapAddress(Windows.Services.Maps.MapAddress mapAddress)
        {
            return new MapAddress(mapAddress);
        }
#elif __ANDROID__
        ///
        /// Initializes a new instance of the <see cref="MapAddress"/> class.
        ///
        public MapAddress(Android.Locations.Address mapLocation)
        {
            this.StreetNumber = mapLocation.SubThoroughfare;
            this.Street = mapLocation.Thoroughfare;
            this.Neighborhood = mapLocation.SubLocality;
            this.District = mapLocation.SubAdminArea;
            this.Town = mapLocation.Locality;
            this.Region = mapLocation.AdminArea;
            this.Country = mapLocation.CountryName;
            this.CountryCode = mapLocation.CountryCode;
            this.PostCode = mapLocation.PostalCode;
        }

        public static implicit operator MapAddress(Android.Locations.Address mapAddress)
        {
            return new MapAddress(mapAddress);
        }
#elif __IOS__
        ///
        /// Initializes a new instance of the <see cref="MapAddress"/> class.
        ///
        public MapAddress(CoreLocation.CLPlacemark mapLocation)
        {
            this.StreetNumber = mapLocation.SubThoroughfare;
            this.Street = mapLocation.Thoroughfare;
            this.Neighborhood = mapLocation.SubLocality;
            this.District = mapLocation.SubAdministrativeArea;
            this.Town = mapLocation.Locality;
            this.Region = mapLocation.AdministrativeArea;
            this.Country = mapLocation.Country;
            this.CountryCode = mapLocation.IsoCountryCode;
            this.PostCode = mapLocation.PostalCode;
        }

        public static implicit operator MapAddress(CoreLocation.CLPlacemark mapAddress)
        {
            return new MapAddress(mapAddress);
        }
#endif

        /// Gets the building name of an address.
        public string BuildingName { get; internal set; }

        /// Gets the building floor of an address.
        public string BuildingFloor { get; internal set; }

        /// Gets the building room of an address.
        public string BuildingRoom { get; internal set; }

        /// Gets the building wing of an address.
        public string BuildingWing { get; internal set; }

        /// Gets the street number of an address.
        public string StreetNumber { get; internal set; }

        /// Gets the street of an address.
        public string Street { get; internal set; }

        /// Gets the neighborhood of an address.
        public string Neighborhood { get; internal set; }

        /// Gets the district of an address.
        public string District { get; internal set; }

        /// Gets the town or city of an address.
        public string Town { get; internal set; }

        /// Gets the region (for example, the state or province) of an address.
        public string Region { get; internal set; }

        /// Gets the code for the region (for example, the state or province) of an address.
        public string RegionCode { get; internal set; }

        /// Gets the country of an address.
        public string Country { get; internal set; }

        /// Gets the country code of an address.
        public string CountryCode { get; internal set; }

        /// Gets the postal code of an address.
        public string PostCode { get; internal set; }

        /// Gets the continent of an address.
        public string Continent { get; internal set; }

        /// Returns a string that represents the current object.
        /// <returns>A string that represents the current object.</returns>
        /// <filterpriority>2</filterpriority>
        public override string ToString()
        {
            string address = string.Empty;
            var addressList = new List<string>();

            if (!string.IsNullOrWhiteSpace(this.StreetNumber))
            {
                address = !string.IsNullOrWhiteSpace(this.BuildingName)
                              ? string.Format("{0} {1},", this.StreetNumber, this.BuildingName)
                              : string.Format("{0}", this.StreetNumber);
            }
            else if (!string.IsNullOrWhiteSpace(this.BuildingName))
            {
                address = string.Format("{0},", this.BuildingName);
            }

            if (!string.IsNullOrWhiteSpace(this.Street))
            {
                address = string.Format("{0} {1}", address, this.Street);
            }

            addressList.Add(address);

            if (!string.IsNullOrWhiteSpace(this.Town))
            {
                addressList.Add(this.Town);
            }

            if (!string.IsNullOrWhiteSpace(this.District))
            {
                addressList.Add(this.District);
            }

            if (!string.IsNullOrWhiteSpace(this.PostCode))
            {
                addressList.Add(this.PostCode);
            }

            string toString = string.Join(", ", addressList.Where(x => !string.IsNullOrWhiteSpace(x)));
            return toString.Trim();
        }
    }
}


text:
 * Link to Mocha fork (@backspace)
 * Add generator (@notmessenger)

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.bigtable.mirroring.core.utils.mirroringmetrics;

import com.google.api.core.InternalApi;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;

@InternalApi("For internal usage only")
public class MirroringSpanConstants {
  public static final MeasureLong PRIMARY_LATENCY =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/primary/latency",
          "Distribution of operation latency on primary database",
          "ms");

  public static final MeasureLong SECONDARY_LATENCY =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/secondary/latency",
          "Distribution of operation latency on secondary database",
          "ms");

  public static final MeasureLong MIRRORING_LATENCY =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/mirroring/latency",
          "Distribution of operation latency on secondary database.",
          "ms");

  public static final MeasureLong PRIMARY_ERRORS =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/primary/error_rate",
          "Count of errors on primary database.",
          "1");

  public static final MeasureLong SECONDARY_ERRORS =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/secondary/error_rate",
          "Count of errors on secondary database.",
          "1");

  public static final MeasureLong READ_MATCHES =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/read_verification/matches",
          "Count of successfully verified reads.",
          "1");

  public static final MeasureLong READ_MISMATCHES =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/read_verification/mismatches",
          "Count of read mismatches detected.",
          "1");

  public static final MeasureLong SECONDARY_WRITE_ERRORS =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/secondary/write_error_rate",
          "Count of write errors on secondary database.",
          "1");

  public static final MeasureLong FLOW_CONTROL_LATENCY =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/flow_control_latency",
          "Distribution of latency of acquiring flow controller resources.",
          "ms");

  public static final MeasureLong SECONDARY_WRITE_ERROR_HANDLER_LATENCY =
      MeasureLong.create(
          "com/google/cloud/bigtable/mirroring/secondary_write_error_handler_latency",
          "Distribution of secondary write error handling latency.",
          "ms");

  public static TagKey OPERATION_KEY = TagKey.create("operation");

  public enum HBaseOperation {
    GET("get"),
    GET_LIST("getList"),
    EXISTS("exists"),
    EXISTS_ALL("existsAll"),
    PUT("put"),
    PUT_LIST("putList"),
    DELETE("delete"),
    DELETE_LIST("deleteList"),
    NEXT("next"),
    NEXT_MULTIPLE("nextMultiple"),
    CHECK_AND_PUT("checkAndPut"),
    CHECK_AND_DELETE("checkAndDelete"),
    CHECK_AND_MUTATE("checkAndMutate"),
    MUTATE_ROW("mutateRow"),
    APPEND("append"),
    INCREMENT("increment"),
    GET_SCANNER("getScanner"),
    BATCH("batch"),
    BATCH_CALLBACK("batchCallback"),
    TABLE_CLOSE("close"),
    GET_TABLE("getTable"),
    BUFFERED_MUTATOR_FLUSH("flush"),
    BUFFERED_MUTATOR_MUTATE("mutate"),
    BUFFERED_MUTATOR_MUTATE_LIST("mutateList"),
    MIRRORING_CONNECTION_CLOSE("MirroringConnection.close"),
    MIRRORING_CONNECTION_ABORT("MirroringConnection.abort"),
    BUFFERED_MUTATOR_CLOSE("BufferedMutator.close");

    private final String string;
    private final TagValue tagValue;

    public String getString() {
      return string;
    }

    public TagValue getTagValue() {
      return tagValue;
    }

    HBaseOperation(String name) {
      this.string = name;
      this.tagValue = TagValue.create(name);
    }
  }
}


text:
<?php

class VideoPeer extends BaseVideoPeer
{
  const ITEMS_PER_PAGE = 12;
  const TITLE_LENGTH   = 55; //38;

  /**
   * Проверка есть ли контент на определённом языке
   *
   * @param unknown_type $item_id
   * @param unknown_type $item_lang
   */
  public static function hasCultureContent($item_id, $item_lang)
  {
    $c = new Criteria();
    $c->add( VideoPeer::ID, $item_id );
    $c->addJoin( VideoPeer::ID, VideoI18nPeer::ID );
    $c->add( VideoI18nPeer::CULTURE, $item_lang );
    //$c->add( VideoI18nPeer::CODE, '', Criteria::NOT_EQUAL );
    self::addVisibleCriteria($c);

    $video_list = VideoPeer::doSelect($c);

    if (count($video_list)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Добавляет условие, при котором элемент отображается на языке пользователя
   *
   * @param unknown_type $c
   */
  public static function addVisibleCriteria($c)
  {
    $c->add( VideoPeer::SHOW, 1 );

    $c_all_cultueres = $c->getNewCriterion(VideoI18nPeer::CODE, '', Criteria::NOT_EQUAL);
    $c_all_cultueres->addOr($c->getNewCriterion(VideoI18nPeer::TITLE, '', Criteria::NOT_EQUAL));
    $c_all_cultueres->addOr( $c->getNewCriterion(VideoPeer::ALL_CULTURES, 1) );

    $culture = sfContext::getInstance()->getUser()->getCulture();

    $c_extra = $c->getNewCriterion(VideoPeer::ALL_CULTURES, 1);

    $c_code = $c->getNewCriterion(VideoI18nPeer::CODE, '', Criteria::NOT_EQUAL);
    $c_code->addAnd( $c->getNewCriterion(VideoI18nPeer::CULTURE, $culture) );
    $c_extra->addOr( $c_code );

    // in default culture (en) title must be always set
    if ($culture != sfConfig::get('sf_default_culture')) {
      $c_title = $c->getNewCriterion(VideoI18nPeer::TITLE, '', Criteria::NOT_EQUAL);
      $c_title->addAnd( $c->getNewCriterion(VideoI18nPeer::CULTURE, $culture) );

      $c_extra->addOr( $c_title );
    }

	$c->add($c_extra);
  }

  /**
   * Для RSS: добавляет условие, при котором элемент отображается на языке пользователя
   *
   * @param unknown_type $c
   */
  public static function addRssVisibleCriteria($c)
  {
    self::addVisibleCriteria($c);
  }

  /**
   * Get URL by ID
   */
  public static function getUrl($id)
  {
    $item = VideoPeer::retrieveByPk( $id );
    if ($item) {
        return $item->getUrl();
    } else {
        return '';
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>P4.Net Copyright</title>
    <link rel="stylesheet" type="text/css" href="../styles/presentation.css" />
    <link rel="stylesheet" type="text/css" href="ms-help://Hx/HxRuntime/HxLink.css" />

                    P4.Net -- Managed API for Perforce

                    P4.Net Copyright

                Copyright © 2007 Shawn Hladky

                Permission is hereby granted, free of charge, to any person obtaining a copy of
                this software and associated documentation files (the "Software"), to deal in the
                Software without restriction, including without limitation the rights to use, copy,
                modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
                and to permit persons to whom the Software is furnished to do so, subject to the
                following conditions:

                The above copyright notice and this permission notice shall be included in all copies
                or substantial portions of the Software.

                THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
                INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
                PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
                BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
                TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
                USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/sched.h>

#include "iss.h"
#include "iss_regs.h"
#include "iss_resizer.h"

static const unsigned int resizer_fmts[] = {
	MEDIA_BUS_FMT_UYVY8_1X16,
	MEDIA_BUS_FMT_YUYV8_1X16,
};

/*
 * resizer_print_status - Print current RESIZER Module register values.
 * @resizer: Pointer to ISS ISP RESIZER device.
 *
 * Also prints other debug information stored in the RESIZER module.
 */
#define RSZ_PRINT_REGISTER(iss, name)\
	dev_dbg(iss->dev, "###RSZ " #name "=0x%08x\n", \
		iss_reg_read(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_##name))

#define RZA_PRINT_REGISTER(iss, name)\
	dev_dbg(iss->dev, "###RZA " #name "=0x%08x\n", \
		iss_reg_read(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_##name))

static void resizer_print_status(struct iss_resizer_device *resizer)
{
	struct iss_device *iss = to_iss_device(resizer);

	dev_dbg(iss->dev, "-------------RESIZER Register dump-------------\n");

	RSZ_PRINT_REGISTER(iss, SYSCONFIG);
	RSZ_PRINT_REGISTER(iss, IN_FIFO_CTRL);
	RSZ_PRINT_REGISTER(iss, FRACDIV);
	RSZ_PRINT_REGISTER(iss, SRC_EN);
	RSZ_PRINT_REGISTER(iss, SRC_MODE);
	RSZ_PRINT_REGISTER(iss, SRC_FMT0);
	RSZ_PRINT_REGISTER(iss, SRC_FMT1);
	RSZ_PRINT_REGISTER(iss, SRC_VPS);
	RSZ_PRINT_REGISTER(iss, SRC_VSZ);
	RSZ_PRINT_REGISTER(iss, SRC_HPS);
	RSZ_PRINT_REGISTER(iss, SRC_HSZ);
	RSZ_PRINT_REGISTER(iss, DMA_RZA);
	RSZ_PRINT_REGISTER(iss, DMA_RZB);
	RSZ_PRINT_REGISTER(iss, DMA_STA);
	RSZ_PRINT_REGISTER(iss, GCK_MMR);
	RSZ_PRINT_REGISTER(iss, GCK_SDR);
	RSZ_PRINT_REGISTER(iss, IRQ_RZA);
	RSZ_PRINT_REGISTER(iss, IRQ_RZB);
	RSZ_PRINT_REGISTER(iss, YUV_Y_MIN);
	RSZ_PRINT_REGISTER(iss, YUV_Y_MAX);
	RSZ_PRINT_REGISTER(iss, YUV_C_MIN);
	RSZ_PRINT_REGISTER(iss, YUV_C_MAX);
	RSZ_PRINT_REGISTER(iss, SEQ);

	RZA_PRINT_REGISTER(iss, EN);
	RZA_PRINT_REGISTER(iss, MODE);
	RZA_PRINT_REGISTER(iss, 420);
	RZA_PRINT_REGISTER(iss, I_VPS);
	RZA_PRINT_REGISTER(iss, I_HPS);
	RZA_PRINT_REGISTER(iss, O_VSZ);
	RZA_PRINT_REGISTER(iss, O_HSZ);
	RZA_PRINT_REGISTER(iss, V_PHS_Y);
	RZA_PRINT_REGISTER(iss, V_PHS_C);
	RZA_PRINT_REGISTER(iss, V_DIF);
	RZA_PRINT_REGISTER(iss, V_TYP);
	RZA_PRINT_REGISTER(iss, V_LPF);
	RZA_PRINT_REGISTER(iss, H_PHS);
	RZA_PRINT_REGISTER(iss, H_DIF);
	RZA_PRINT_REGISTER(iss, H_TYP);
	RZA_PRINT_REGISTER(iss, H_LPF);
	RZA_PRINT_REGISTER(iss, DWN_EN);
	RZA_PRINT_REGISTER(iss, SDR_Y_BAD_H);
	RZA_PRINT_REGISTER(iss, SDR_Y_BAD_L);
	RZA_PRINT_REGISTER(iss, SDR_Y_SAD_H);
	RZA_PRINT_REGISTER(iss, SDR_Y_SAD_L);
	RZA_PRINT_REGISTER(iss, SDR_Y_OFT);
	RZA_PRINT_REGISTER(iss, SDR_Y_PTR_S);
	RZA_PRINT_REGISTER(iss, SDR_Y_PTR_E);
	RZA_PRINT_REGISTER(iss, SDR_C_BAD_H);
	RZA_PRINT_REGISTER(iss, SDR_C_BAD_L);
	RZA_PRINT_REGISTER(iss, SDR_C_SAD_H);
	RZA_PRINT_REGISTER(iss, SDR_C_SAD_L);
	RZA_PRINT_REGISTER(iss, SDR_C_OFT);
	RZA_PRINT_REGISTER(iss, SDR_C_PTR_S);
	RZA_PRINT_REGISTER(iss, SDR_C_PTR_E);

	dev_dbg(iss->dev, "-----------------------------------------------\n");
}

/*
 * resizer_enable - Enable/Disable RESIZER.
 * @enable: enable flag
 *
 */
static void resizer_enable(struct iss_resizer_device *resizer, u8 enable)
{
	struct iss_device *iss = to_iss_device(resizer);

	iss_reg_update(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_EN,
		       RSZ_SRC_EN_SRC_EN, enable ? RSZ_SRC_EN_SRC_EN : 0);

	/* TODO: Enable RSZB */
	iss_reg_update(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_EN, RSZ_EN_EN,
		       enable ? RSZ_EN_EN : 0);
}

/* -----------------------------------------------------------------------------
 * Format- and pipeline-related configuration helpers
 */

/*
 * resizer_set_outaddr - Set memory address to save output image
 * @resizer: Pointer to ISP RESIZER device.
 * @addr: 32-bit memory address aligned on 32 byte boundary.
 *
 * Sets the memory address where the output will be saved.
 */
static void resizer_set_outaddr(struct iss_resizer_device *resizer, u32 addr)
{
	struct iss_device *iss = to_iss_device(resizer);
	struct v4l2_mbus_framefmt *informat, *outformat;

	informat = &resizer->formats[RESIZER_PAD_SINK];
	outformat = &resizer->formats[RESIZER_PAD_SOURCE_MEM];

	/* Save address splitted in Base Address H & L */
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_BAD_H,
		      (addr >> 16) & 0xffff);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_BAD_L,
		      addr & 0xffff);

	/* SAD = BAD */
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_SAD_H,
		      (addr >> 16) & 0xffff);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_SAD_L,
		      addr & 0xffff);

	/* Program UV buffer address... Hardcoded to be contiguous! */
	if ((informat->code == MEDIA_BUS_FMT_UYVY8_1X16) &&
	    (outformat->code == MEDIA_BUS_FMT_YUYV8_1_5X8)) {
		u32 c_addr = addr + (resizer->video_out.bpl_value *
				     (outformat->height - 1));

		/* Ensure Y_BAD_L[6:0] = C_BAD_L[6:0]*/
		if ((c_addr ^ addr) & 0x7f) {
			c_addr &= ~0x7f;
			c_addr += 0x80;
			c_addr |= addr & 0x7f;
		}

		/* Save address splitted in Base Address H & L */
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_BAD_H,
			      (c_addr >> 16) & 0xffff);
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_BAD_L,
			      c_addr & 0xffff);

		/* SAD = BAD */
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_SAD_H,
			      (c_addr >> 16) & 0xffff);
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_SAD_L,
			      c_addr & 0xffff);
	}
}

static void resizer_configure(struct iss_resizer_device *resizer)
{
	struct iss_device *iss = to_iss_device(resizer);
	struct v4l2_mbus_framefmt *informat, *outformat;

	informat = &resizer->formats[RESIZER_PAD_SINK];
	outformat = &resizer->formats[RESIZER_PAD_SOURCE_MEM];

	/* Disable pass-through more. Despite its name, the BYPASS bit controls
	 * pass-through mode, not bypass mode.
	 */
	iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_FMT0,
		    RSZ_SRC_FMT0_BYPASS);

	/* Select RSZ input */
	iss_reg_update(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_FMT0,
		       RSZ_SRC_FMT0_SEL,
		       resizer->input == RESIZER_INPUT_IPIPEIF ?
		       RSZ_SRC_FMT0_SEL : 0);

	/* RSZ ignores WEN signal from IPIPE/IPIPEIF */
	iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_MODE,
		    RSZ_SRC_MODE_WRT);

	/* Set Resizer in free-running mode */
	iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_MODE,
		    RSZ_SRC_MODE_OST);

	/* Init Resizer A */
	iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_MODE,
		    RZA_MODE_ONE_SHOT);

	/* Set size related things now */
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_VPS, 0);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_HPS, 0);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_VSZ,
		      informat->height - 2);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SRC_HSZ,
		      informat->width - 1);

	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_I_VPS, 0);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_I_HPS, 0);

	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_O_VSZ,
		      outformat->height - 2);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_O_HSZ,
		      outformat->width - 1);

	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_V_DIF, 0x100);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_H_DIF, 0x100);

	/* Buffer output settings */
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_PTR_S, 0);
	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_PTR_E,
		      outformat->height - 1);

	iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_Y_OFT,
		      resizer->video_out.bpl_value);

	/* UYVY -> NV12 conversion */
	if ((informat->code == MEDIA_BUS_FMT_UYVY8_1X16) &&
	    (outformat->code == MEDIA_BUS_FMT_YUYV8_1_5X8)) {
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_420,
			      RSZ_420_CEN | RSZ_420_YEN);

		/* UV Buffer output settings */
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_PTR_S,
			      0);
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_PTR_E,
			      outformat->height - 1);

		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_SDR_C_OFT,
			      resizer->video_out.bpl_value);
	} else {
		iss_reg_write(iss, OMAP4_ISS_MEM_ISP_RESIZER, RZA_420, 0);
	}
}

/* -----------------------------------------------------------------------------
 * Interrupt handling
 */

static void resizer_isr_buffer(struct iss_resizer_device *resizer)
{
	struct iss_buffer *buffer;

	/* The whole resizer needs to be stopped. Disabling RZA only produces
	 * input FIFO overflows, most probably when the next frame is received.
	 */
	resizer_enable(resizer, 0);

	buffer = omap4iss_video_buffer_next(&resizer->video_out);
	if (buffer == NULL)
		return;

	resizer_set_outaddr(resizer, buffer->iss_addr);

	resizer_enable(resizer, 1);
}

/*
 * omap4iss_resizer_isr - Configure resizer during interframe time.
 * @resizer: Pointer to ISP RESIZER device.
 * @events: RESIZER events
 */
void omap4iss_resizer_isr(struct iss_resizer_device *resizer, u32 events)
{
	struct iss_device *iss = to_iss_device(resizer);
	struct iss_pipeline *pipe =
			     to_iss_pipeline(&resizer->subdev.entity);

	if (events & (ISP5_IRQ_RSZ_FIFO_IN_BLK_ERR |
		      ISP5_IRQ_RSZ_FIFO_OVF)) {
		dev_dbg(iss->dev, "RSZ Err: FIFO_IN_BLK:%d, FIFO_OVF:%d\n",
			events & ISP5_IRQ_RSZ_FIFO_IN_BLK_ERR ? 1 : 0,
			events & ISP5_IRQ_RSZ_FIFO_OVF ? 1 : 0);
		omap4iss_pipeline_cancel_stream(pipe);
	}

	if (omap4iss_module_sync_is_stopping(&resizer->wait,
					     &resizer->stopping))
		return;

	if (events & ISP5_IRQ_RSZ_INT_DMA)
		resizer_isr_buffer(resizer);
}

/* -----------------------------------------------------------------------------
 * ISS video operations
 */

static int resizer_video_queue(struct iss_video *video,
			       struct iss_buffer *buffer)
{
	struct iss_resizer_device *resizer = container_of(video,
				struct iss_resizer_device, video_out);

	if (!(resizer->output & RESIZER_OUTPUT_MEMORY))
		return -ENODEV;

	resizer_set_outaddr(resizer, buffer->iss_addr);

	/*
	 * If streaming was enabled before there was a buffer queued
	 * or underrun happened in the ISR, the hardware was not enabled
	 * and DMA queue flag ISS_VIDEO_DMAQUEUE_UNDERRUN is still set.
	 * Enable it now.
	 */
	if (video->dmaqueue_flags & ISS_VIDEO_DMAQUEUE_UNDERRUN) {
		resizer_enable(resizer, 1);
		iss_video_dmaqueue_flags_clr(video);
	}

	return 0;
}

static const struct iss_video_operations resizer_video_ops = {
	.queue = resizer_video_queue,
};

/* -----------------------------------------------------------------------------
 * V4L2 subdev operations
 */

/*
 * resizer_set_stream - Enable/Disable streaming on the RESIZER module
 * @sd: ISP RESIZER V4L2 subdevice
 * @enable: Enable/disable stream
 */
static int resizer_set_stream(struct v4l2_subdev *sd, int enable)
{
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct iss_device *iss = to_iss_device(resizer);
	struct iss_video *video_out = &resizer->video_out;
	int ret = 0;

	if (resizer->state == ISS_PIPELINE_STREAM_STOPPED) {
		if (enable == ISS_PIPELINE_STREAM_STOPPED)
			return 0;

		omap4iss_isp_subclk_enable(iss, OMAP4_ISS_ISP_SUBCLK_RSZ);

		iss_reg_set(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_GCK_MMR,
			    RSZ_GCK_MMR_MMR);
		iss_reg_set(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_GCK_SDR,
			    RSZ_GCK_SDR_CORE);

		/* FIXME: Enable RSZB also */
		iss_reg_set(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SYSCONFIG,
			    RSZ_SYSCONFIG_RSZA_CLK_EN);
	}

	switch (enable) {
	case ISS_PIPELINE_STREAM_CONTINUOUS:

		resizer_configure(resizer);
		resizer_print_status(resizer);

		/*
		 * When outputting to memory with no buffer available, let the
		 * buffer queue handler start the hardware. A DMA queue flag
		 * ISS_VIDEO_DMAQUEUE_QUEUED will be set as soon as there is
		 * a buffer available.
		 */
		if (resizer->output & RESIZER_OUTPUT_MEMORY &&
		    !(video_out->dmaqueue_flags & ISS_VIDEO_DMAQUEUE_QUEUED))
			break;

		atomic_set(&resizer->stopping, 0);
		resizer_enable(resizer, 1);
		iss_video_dmaqueue_flags_clr(video_out);
		break;

	case ISS_PIPELINE_STREAM_STOPPED:
		if (resizer->state == ISS_PIPELINE_STREAM_STOPPED)
			return 0;
		if (omap4iss_module_sync_idle(&sd->entity, &resizer->wait,
					      &resizer->stopping))
			ret = -ETIMEDOUT;

		resizer_enable(resizer, 0);
		iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_SYSCONFIG,
			    RSZ_SYSCONFIG_RSZA_CLK_EN);
		iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_GCK_SDR,
			    RSZ_GCK_SDR_CORE);
		iss_reg_clr(iss, OMAP4_ISS_MEM_ISP_RESIZER, RSZ_GCK_MMR,
			    RSZ_GCK_MMR_MMR);
		omap4iss_isp_subclk_disable(iss, OMAP4_ISS_ISP_SUBCLK_RSZ);
		iss_video_dmaqueue_flags_clr(video_out);
		break;
	}

	resizer->state = enable;
	return ret;
}

static struct v4l2_mbus_framefmt *
__resizer_get_format(struct iss_resizer_device *resizer,
		     struct v4l2_subdev_pad_config *cfg, unsigned int pad,
		     enum v4l2_subdev_format_whence which)
{
	if (which == V4L2_SUBDEV_FORMAT_TRY)
		return v4l2_subdev_get_try_format(&resizer->subdev, cfg, pad);
	return &resizer->formats[pad];
}

/*
 * resizer_try_format - Try video format on a pad
 * @resizer: ISS RESIZER device
 * @cfg: V4L2 subdev pad config
 * @pad: Pad number
 * @fmt: Format
 */
static void
resizer_try_format(struct iss_resizer_device *resizer,
		   struct v4l2_subdev_pad_config *cfg, unsigned int pad,
		   struct v4l2_mbus_framefmt *fmt,
		   enum v4l2_subdev_format_whence which)
{
	u32 pixelcode;
	struct v4l2_mbus_framefmt *format;
	unsigned int width = fmt->width;
	unsigned int height = fmt->height;
	unsigned int i;

	switch (pad) {
	case RESIZER_PAD_SINK:
		for (i = 0; i < ARRAY_SIZE(resizer_fmts); i++) {
			if (fmt->code == resizer_fmts[i])
				break;
		}

		/* If not found, use UYVY as default */
		if (i >= ARRAY_SIZE(resizer_fmts))
			fmt->code = MEDIA_BUS_FMT_UYVY8_1X16;

		/* Clamp the input size. */
		fmt->width = clamp_t(u32, width, 1, 8192);
		fmt->height = clamp_t(u32, height, 1, 8192);
		break;

	case RESIZER_PAD_SOURCE_MEM:
		pixelcode = fmt->code;
		format = __resizer_get_format(resizer, cfg, RESIZER_PAD_SINK,
					      which);
		memcpy(fmt, format, sizeof(*fmt));

		if ((pixelcode == MEDIA_BUS_FMT_YUYV8_1_5X8) &&
		    (fmt->code == MEDIA_BUS_FMT_UYVY8_1X16))
			fmt->code = pixelcode;

		/* The data formatter truncates the number of horizontal output
		 * pixels to a multiple of 16. To avoid clipping data, allow
		 * callers to request an output size bigger than the input size
		 * up to the nearest multiple of 16.
		 */
		fmt->width = clamp_t(u32, width, 32, (fmt->width + 15) & ~15);
		fmt->width &= ~15;
		fmt->height = clamp_t(u32, height, 32, fmt->height);
		break;

	}

	fmt->colorspace = V4L2_COLORSPACE_JPEG;
	fmt->field = V4L2_FIELD_NONE;
}

/*
 * resizer_enum_mbus_code - Handle pixel format enumeration
 * @sd     : pointer to v4l2 subdev structure
 * @cfg: V4L2 subdev pad config
 * @code   : pointer to v4l2_subdev_mbus_code_enum structure
 * return -EINVAL or zero on success
 */
static int resizer_enum_mbus_code(struct v4l2_subdev *sd,
			       struct v4l2_subdev_pad_config *cfg,
			       struct v4l2_subdev_mbus_code_enum *code)
{
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct v4l2_mbus_framefmt *format;

	switch (code->pad) {
	case RESIZER_PAD_SINK:
		if (code->index >= ARRAY_SIZE(resizer_fmts))
			return -EINVAL;

		code->code = resizer_fmts[code->index];
		break;

	case RESIZER_PAD_SOURCE_MEM:
		format = __resizer_get_format(resizer, cfg, RESIZER_PAD_SINK,
					      code->which);

		if (code->index == 0) {
			code->code = format->code;
			break;
		}

		switch (format->code) {
		case MEDIA_BUS_FMT_UYVY8_1X16:
			if (code->index == 1)
				code->code = MEDIA_BUS_FMT_YUYV8_1_5X8;
			else
				return -EINVAL;
			break;
		default:
			if (code->index != 0)
				return -EINVAL;
		}

		break;

	default:
		return -EINVAL;
	}

	return 0;
}

static int resizer_enum_frame_size(struct v4l2_subdev *sd,
				struct v4l2_subdev_pad_config *cfg,
				struct v4l2_subdev_frame_size_enum *fse)
{
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct v4l2_mbus_framefmt format;

	if (fse->index != 0)
		return -EINVAL;

	format.code = fse->code;
	format.width = 1;
	format.height = 1;
	resizer_try_format(resizer, cfg, fse->pad, &format, fse->which);
	fse->min_width = format.width;
	fse->min_height = format.height;

	if (format.code != fse->code)
		return -EINVAL;

	format.code = fse->code;
	format.width = -1;
	format.height = -1;
	resizer_try_format(resizer, cfg, fse->pad, &format, fse->which);
	fse->max_width = format.width;
	fse->max_height = format.height;

	return 0;
}

/*
 * resizer_get_format - Retrieve the video format on a pad
 * @sd : ISP RESIZER V4L2 subdevice
 * @cfg: V4L2 subdev pad config
 * @fmt: Format
 *
 * Return 0 on success or -EINVAL if the pad is invalid or doesn't correspond
 * to the format type.
 */
static int resizer_get_format(struct v4l2_subdev *sd,
			      struct v4l2_subdev_pad_config *cfg,
			      struct v4l2_subdev_format *fmt)
{
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct v4l2_mbus_framefmt *format;

	format = __resizer_get_format(resizer, cfg, fmt->pad, fmt->which);
	if (format == NULL)
		return -EINVAL;

	fmt->format = *format;
	return 0;
}

/*
 * resizer_set_format - Set the video format on a pad
 * @sd : ISP RESIZER V4L2 subdevice
 * @cfg: V4L2 subdev pad config
 * @fmt: Format
 *
 * Return 0 on success or -EINVAL if the pad is invalid or doesn't correspond
 * to the format type.
 */
static int resizer_set_format(struct v4l2_subdev *sd,
			      struct v4l2_subdev_pad_config *cfg,
			      struct v4l2_subdev_format *fmt)
{
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct v4l2_mbus_framefmt *format;

	format = __resizer_get_format(resizer, cfg, fmt->pad, fmt->which);
	if (format == NULL)
		return -EINVAL;

	resizer_try_format(resizer, cfg, fmt->pad, &fmt->format, fmt->which);
	*format = fmt->format;

	/* Propagate the format from sink to source */
	if (fmt->pad == RESIZER_PAD_SINK) {
		format = __resizer_get_format(resizer, cfg,
					      RESIZER_PAD_SOURCE_MEM,
					      fmt->which);
		*format = fmt->format;
		resizer_try_format(resizer, cfg, RESIZER_PAD_SOURCE_MEM, format,
				fmt->which);
	}

	return 0;
}

static int resizer_link_validate(struct v4l2_subdev *sd,
				 struct media_link *link,
				 struct v4l2_subdev_format *source_fmt,
				 struct v4l2_subdev_format *sink_fmt)
{
	/* Check if the two ends match */
	if (source_fmt->format.width != sink_fmt->format.width ||
	    source_fmt->format.height != sink_fmt->format.height)
		return -EPIPE;

	if (source_fmt->format.code != sink_fmt->format.code)
		return -EPIPE;

	return 0;
}

/*
 * resizer_init_formats - Initialize formats on all pads
 * @sd: ISP RESIZER V4L2 subdevice
 * @fh: V4L2 subdev file handle
 *
 * Initialize all pad formats with default values. If fh is not NULL, try
 * formats are initialized on the file handle. Otherwise active formats are
 * initialized on the device.
 */
static int resizer_init_formats(struct v4l2_subdev *sd,
				struct v4l2_subdev_fh *fh)
{
	struct v4l2_subdev_format format;

	memset(&format, 0, sizeof(format));
	format.pad = RESIZER_PAD_SINK;
	format.which = fh ? V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE;
	format.format.code = MEDIA_BUS_FMT_UYVY8_1X16;
	format.format.width = 4096;
	format.format.height = 4096;
	resizer_set_format(sd, fh ? fh->pad : NULL, &format);

	return 0;
}

/* V4L2 subdev video operations */
static const struct v4l2_subdev_video_ops resizer_v4l2_video_ops = {
	.s_stream = resizer_set_stream,
};

/* V4L2 subdev pad operations */
static const struct v4l2_subdev_pad_ops resizer_v4l2_pad_ops = {
	.enum_mbus_code = resizer_enum_mbus_code,
	.enum_frame_size = resizer_enum_frame_size,
	.get_fmt = resizer_get_format,
	.set_fmt = resizer_set_format,
	.link_validate = resizer_link_validate,
};

/* V4L2 subdev operations */
static const struct v4l2_subdev_ops resizer_v4l2_ops = {
	.video = &resizer_v4l2_video_ops,
	.pad = &resizer_v4l2_pad_ops,
};

/* V4L2 subdev internal operations */
static const struct v4l2_subdev_internal_ops resizer_v4l2_internal_ops = {
	.open = resizer_init_formats,
};

/* -----------------------------------------------------------------------------
 * Media entity operations
 */

/*
 * resizer_link_setup - Setup RESIZER connections
 * @entity: RESIZER media entity
 * @local: Pad at the local end of the link
 * @remote: Pad at the remote end of the link
 * @flags: Link flags
 *
 * return -EINVAL or zero on success
 */
static int resizer_link_setup(struct media_entity *entity,
			   const struct media_pad *local,
			   const struct media_pad *remote, u32 flags)
{
	struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
	struct iss_resizer_device *resizer = v4l2_get_subdevdata(sd);
	struct iss_device *iss = to_iss_device(resizer);

	switch (local->index | media_entity_type(remote->entity)) {
	case RESIZER_PAD_SINK | MEDIA_ENT_T_V4L2_SUBDEV:
		/* Read from IPIPE or IPIPEIF. */
		if (!(flags & MEDIA_LNK_FL_ENABLED)) {
			resizer->input = RESIZER_INPUT_NONE;
			break;
		}

		if (resizer->input != RESIZER_INPUT_NONE)
			return -EBUSY;

		if (remote->entity == &iss->ipipeif.subdev.entity)
			resizer->input = RESIZER_INPUT_IPIPEIF;
		else if (remote->entity == &iss->ipipe.subdev.entity)
			resizer->input = RESIZER_INPUT_IPIPE;

		break;

	case RESIZER_PAD_SOURCE_MEM | MEDIA_ENT_T_DEVNODE:
		/* Write to memory */
		if (flags & MEDIA_LNK_FL_ENABLED) {
			if (resizer->output & ~RESIZER_OUTPUT_MEMORY)
				return -EBUSY;
			resizer->output |= RESIZER_OUTPUT_MEMORY;
		} else {
			resizer->output &= ~RESIZER_OUTPUT_MEMORY;
		}
		break;

	default:
		return -EINVAL;
	}

	return 0;
}

/* media operations */
static const struct media_entity_operations resizer_media_ops = {
	.link_setup = resizer_link_setup,
	.link_validate = v4l2_subdev_link_validate,
};

/*
 * resizer_init_entities - Initialize V4L2 subdev and media entity
 * @resizer: ISS ISP RESIZER module
 *
 * Return 0 on success and a negative error code on failure.
 */
static int resizer_init_entities(struct iss_resizer_device *resizer)
{
	struct v4l2_subdev *sd = &resizer->subdev;
	struct media_pad *pads = resizer->pads;
	struct media_entity *me = &sd->entity;
	int ret;

	resizer->input = RESIZER_INPUT_NONE;

	v4l2_subdev_init(sd, &resizer_v4l2_ops);
	sd->internal_ops = &resizer_v4l2_internal_ops;
	strlcpy(sd->name, "OMAP4 ISS ISP resizer", sizeof(sd->name));
	sd->grp_id = 1 << 16;	/* group ID for iss subdevs */
	v4l2_set_subdevdata(sd, resizer);
	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;

	pads[RESIZER_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
	pads[RESIZER_PAD_SOURCE_MEM].flags = MEDIA_PAD_FL_SOURCE;

	me->ops = &resizer_media_ops;
	ret = media_entity_init(me, RESIZER_PADS_NUM, pads, 0);
	if (ret < 0)
		return ret;

	resizer_init_formats(sd, NULL);

	resizer->video_out.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	resizer->video_out.ops = &resizer_video_ops;
	resizer->video_out.iss = to_iss_device(resizer);
	resizer->video_out.capture_mem = PAGE_ALIGN(4096 * 4096) * 3;
	resizer->video_out.bpl_alignment = 32;
	resizer->video_out.bpl_zero_padding = 1;
	resizer->video_out.bpl_max = 0x1ffe0;

	ret = omap4iss_video_init(&resizer->video_out, "ISP resizer a");
	if (ret < 0)
		return ret;

	/* Connect the RESIZER subdev to the video node. */
	ret = media_entity_create_link(&resizer->subdev.entity,
				       RESIZER_PAD_SOURCE_MEM,
				       &resizer->video_out.video.entity, 0, 0);
	if (ret < 0)
		return ret;

	return 0;
}

void omap4iss_resizer_unregister_entities(struct iss_resizer_device *resizer)
{
	v4l2_device_unregister_subdev(&resizer->subdev);
	omap4iss_video_unregister(&resizer->video_out);
}

int omap4iss_resizer_register_entities(struct iss_resizer_device *resizer,
	struct v4l2_device *vdev)
{
	int ret;

	/* Register the subdev and video node. */
	ret = v4l2_device_register_subdev(vdev, &resizer->subdev);
	if (ret < 0)
		goto error;

	ret = omap4iss_video_register(&resizer->video_out, vdev);
	if (ret < 0)
		goto error;

	return 0;

error:
	omap4iss_resizer_unregister_entities(resizer);
	return ret;
}

/* -----------------------------------------------------------------------------
 * ISP RESIZER initialisation and cleanup
 */

/*
 * omap4iss_resizer_init - RESIZER module initialization.
 * @iss: Device pointer specific to the OMAP4 ISS.
 *
 * TODO: Get the initialisation values from platform data.
 *
 * Return 0 on success or a negative error code otherwise.
 */
int omap4iss_resizer_init(struct iss_device *iss)
{
	struct iss_resizer_device *resizer = &iss->resizer;

	resizer->state = ISS_PIPELINE_STREAM_STOPPED;
	init_waitqueue_head(&resizer->wait);

	return resizer_init_entities(resizer);
}

/*
 * omap4iss_resizer_cleanup - RESIZER module cleanup.
 * @iss: Device pointer specific to the OMAP4 ISS.
 */
void omap4iss_resizer_cleanup(struct iss_device *iss)
{
	struct iss_resizer_device *resizer = &iss->resizer;

	media_entity_cleanup(&resizer->subdev.entity);
}


text:
python-news-digest
==================

[![Build Status](https://travis-ci.org/pythondigest/pythondigest.svg?branch=master)](https://travis-ci.org/pythondigest/pythondigest)
[![Requirements Status](https://requires.io/github/pythondigest/pythondigest/requirements.svg?branch=master)](https://requires.io/github/pythondigest/pythondigest/requirements/?branch=master)
[![Coverage Status](https://coveralls.io/repos/github/pythondigest/pythondigest/badge.svg?branch=master)](https://coveralls.io/github/pythondigest/pythondigest?branch=master)
[![Code Health](https://landscape.io/github/pythondigest/pythondigest/master/landscape.svg?style=flat)](https://landscape.io/github/pythondigest/pythondigest/master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/pythondigest/pythondigest/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/pythondigest/pythondigest/?branch=master)
[![Code Issues](https://www.quantifiedcode.com/api/v1/project/965ef841bdca428492ec06d4f018d360/badge.svg)](https://www.quantifiedcode.com/app/project/965ef841bdca428492ec06d4f018d360)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org)

What is it?
-----------

It is the repo with sources of project Python Digest (site - https://pythondigest.ru/ )
Python Digest is an aggregator of Python News
We aggregator many different links from Python World:

- books
- articles
- meetups
- releases
- etc

PythonDigest is a `Open Source` project!
We use `Python 3`

Contributing
------------

In general, we follow the "fork-and-pull" Git workflow.

> We develop in `develop` branch

 1. **Fork** the repo on GitHub
 2. **Clone** the project to your own machine
 3. **Commit** changes to your own branch
 4. **Push** your work back up to your fork
 5. Submit a **Pull request** so that we can review your changes

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

> We recommend to use `git-flow`

How to start
------------

Clone project

```
git clone https://github.com/pythondigest/pythondigest.git
```

Create `virtualenv` and install dependencies:

```
virtualenv --python=python3 ./env
source ./env/bin/activate
cd pythondigest
pip install -r requirements.txt
```

Init database and install some fixtures:

```
python manage.py migrate
python manage.py migrate --run-syncdb
python manage.py loaddata digest/fixtures/sections.yaml
python manage.py loaddata digest/fixtures/parsing_rules.json
```

Create super user
```
python manage.py createsuperuser
```

Ok! You are ready for work with Python Digest! (runserver...)

For developers:

```
python manage.py loaddata digest/fixtures/dev_issues.yaml
python manage.py loaddata digest/fixtures/dev_resource.yaml
python manage.py loaddata digest/fixtures/dev_items.yaml
```

Run tests
---------

```
python manage.py test
```


text:
import { AlloySpec, SimpleSpec } from '@ephox/alloy';

const promotionMessage = '⚡Upgrade';
const promotionLink = 'https://www.tiny.cloud/tinymce-self-hosted-premium-features/?utm_source=TinyMCE&utm_medium=SPAP&utm_campaign=SPAP&utm_id=editorreferral';

const renderPromotion = (spec: SimpleSpec): AlloySpec => {
  return {
    uid: spec.uid,
    dom: spec.dom,

    components: [
      {
        dom: {
          tag: 'a',
          attributes: {
            'href': promotionLink,
            'rel': 'noopener',
            'target': '_blank',
            'aria-hidden': 'true'
          },
          classes: [ 'tox-promotion-link' ],
          innerHtml: promotionMessage
        }
      }
    ]
  };
};

export { renderPromotion };


text:
apt_package "postfix" do
  response_file 'postfix.preseed'
  supports :restart => true, :reload => true
  action :install
end

apt_package "mailutils" do
  action :install
end

service 'postfix' do
  action [ :enable, :start ]
end

bash "postconf_interfaces_localhost" do
  user "root"
  code <<-EOS
  postconf -e inet_interfaces=localhost
  EOS
  not_if "egrep -q '^inet_interfaces.*localhost' /etc/postfix/main.cf"
  notifies :restart, 'service[postfix]'
end

bash "root_alias" do
  user "root"
  code <<-EOS
  printf "root:\t%s@systems.everyware.ch\n" "linux" >> /etc/aliases
  newaliases
  EOS
  not_if "egrep -q 'linux.*systems.everyware.ch' /etc/aliases"
  notifies :reload, 'service[postfix]'
end


text:
module KktShoppe
  class DeliveryService < ActiveRecord::Base

    self.table_name = 'kkt_shoppe_delivery_services'

    # Validations
    validates :name, :presence => true
    validates :courier, :presence => true

    # Orders which are assigned to this delivery service
    has_many :orders, :dependent => :restrict_with_exception, :class_name => 'KktShoppe::Order'

    # Prices for the different levels of service within this delivery service
    has_many :delivery_service_prices, :dependent => :destroy, :class_name => 'KktShoppe::DeliveryServicePrice'

    # All active delivery services
    scope :active, -> { where(:active => true)}

    # Returns a tracking URL for the passed order
    #
    # @param order [KktShoppe::Order]
    # @return [String] the full URL for the order.
    def tracking_url_for(order)
      return nil if self.tracking_url.blank?
      tracking_url = self.tracking_url.dup
      tracking_url.gsub!("{{consignment_number}}", CGI.escape(order.consignment_number.to_s))
      tracking_url.gsub!("{{delivery_postcode}}", CGI.escape(order.delivery_postcode.to_s))
      tracking_url.gsub!("{{billing_postcode}}", CGI.escape(order.billing_postcode.to_s))
      tracking_url
    end

  end
end


text:
@interface FLLTest1ViewController : UIViewController

@end


text:
package io.ganguo.app.basic.util;

import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 加密解密工具包
 *
 * @author Winter Lau
 * @date 2011-12-26
 * <p/>
 * http://git.oschina.net/oschina/android-app/blob/master/src/net/oschina/app/common/CyptoUtils.java
 * http://javarevisited.blogspot.com/2013/03/generate-md5-hash-in-java-string-byte-array-example-tutorial.html
 */
public class CyptoUtils {

    /**
     * 加密私钥,长度不能够小于8位
     */
    public static final String DES_KEY = "12345678";
    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
    private static final MessageDigest digest;

    static {
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * DES算法,加密
     *
     * @param data 待加密字符串
     * @param key  加密私钥,长度不能够小于8位
     * @return 加密后的字节数组,一般结合Base64编码使用
     * @throws Exception
     */
    public static String encodeDES(String key, String data) {
        if (data == null)
            return null;
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(DES_KEY.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return byte2hex(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * DES算法,解密
     *
     * @param data 待解密字符串
     * @param key  解密私钥,长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception 异常
     */
    public static String decodeDES(String key, String data) {
        if (data == null)
            return null;
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            //key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(DES_KEY.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return new String(cipher.doFinal(hex2byte(data.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * 二行制转字符串
     *
     * @param b
     * @return
     */
    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    /**
     * hex to bytes
     *
     * @param b
     * @return
     */
    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException();
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    /**
     * md5算法
     *
     * @param toEncrypt
     * @return
     */
    public static String md5(final String toEncrypt) {
        try {
            digest.update(toEncrypt.getBytes());
            final byte[] bytes = digest.digest();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(String.format("%02X", bytes[i]));
            }
            return sb.toString().toLowerCase();
        } catch (Exception exc) {
            return ""; // Impossibru!
        }
    }
}


text:
This project provides a set of Python packages that make it easy to access
the Microsoft Azure storage and queue services. For documentation on how
to host Python applications on Microsoft Azure, please see the
[Microsoft Azure](http://www.windowsazure.com/en-us/develop/python/)
Python Developer Center.

The SDK supports Python 2.7, 3.3, 3.4.

# Features

* Tables
    * create and delete tables
    * create, query, insert, update, merge, and delete entities
* Blobs
    * create, list, and delete containers, work with container metadata and permissions, list blobs in container
    * create block and page blobs (from a stream, a file, or a string), work with blob blocks and pages, delete blobs
    * work with blob properties, metadata, leases, snapshot a blob
* Storage Queues
    * create, list, and delete queues, and work with queue metadata
    * create, get, peek, update, delete messages
* Service Bus
    * Queues: create, list and delete queues; create, list, and delete subscriptions; send, receive, unlock and delete messages
    * Topics: create, list, and delete topics; create, list, and delete rules
* Service Management
    * storage accounts: create, update, delete, list, regenerate keys
    * affinity groups: create, update, delete, list, get properties
    * locations: list
    * hosted services: create, update, delete, list, get properties
    * deployment: create, get, delete, swap, change configuration, update status, upgrade, rollback
    * role instance: reboot, reimage
    * discover addresses and ports for the endpoints of other role instances in your service
    * get configuration settings and access local resources
    * get role instance information for current role and other role instances
    * query and set the status of the current role

# Getting Started
## Download Source Code

To get the source code of the SDK via **git** just type:

    git clone https://github.com/Azure/azure-sdk-for-python.git
    cd ./azure-sdk-for-python

## Download Package

Alternatively, to get the source code via the Python Package Index (PyPI), type

    %SystemDrive%\Python27\Scripts\pip.exe install azure

You can use these packages against the cloud Microsoft Azure Services, or against
the local Storage Emulator (with the exception of Service Bus features).

1. To use the cloud services, you need to first create an account with Microsoft Azure. To use the storage services, you need to set the AZURE_STORAGE_ACCOUNT and the AZURE_STORAGE_ACCESS_KEY environment variables to the storage account name and primary access key you obtain from the Azure Portal. To use Service Bus, you need to set the AZURE_SERVICEBUS_NAMESPACE and the AZURE_SERVICEBUS_ACCESS_KEY environment variables to the service bus namespace and the default key you obtain from the Azure Portal.
2. To use the Storage Emulator, make sure the latest version of the Microsoft Azure SDK is installed on the machine, and set the EMULATED environment variable to any value ("true", "1", etc.)

# Usage
## Table Storage

To ensure a table exists, call **create\_table**:

```Python
from azure.storage import TableService
ts = TableService(account_name, account_key)
ts.create_table('tasktable')
```

A new entity can be added by calling **insert\_entity**:

```Python
from datetime import datetime
ts = TableService(account_name, account_key)
ts.create_table('tasktable')
ts.insert_entity(
     'tasktable',
     {
        'PartitionKey' : 'tasksSeattle',
        'RowKey': '1',
        'Description': 'Take out the trash',
        'DueDate': datetime(2011, 12, 14, 12)
    }
)
```

The method **get\_entity** can then be used to fetch the entity that was just inserted:

```Python
ts = TableService(account_name, account_key)
entity = ts.get_entity('tasktable', 'tasksSeattle', '1')
```

## Blob Storage

The **create\_container** method can be used to create a
container in which to store a blob:

```Python
from azure.storage import BlobService
blob_service = BlobService(account_name, account_key)
blob_service.create_container('images')
```

To upload a file 'uploads/image.png' from disk to a blob named 'image.png', the method **put\_block\_blob\_from\_path** can be used:

```Python
from azure.storage import BlobService
blob_service = BlobService(account_name, account_key)
blob_service.put_block_blob_from_path('images', 'image.png', 'uploads/image.png')
```

To upload an already opened file to a blob named 'image.png', the method **put\_block\_blob\_from\_file** can be used instead:

```Python
with open('uploads/image.png') as file:
  blob_service.put_block_blob_from_file('images', 'image.png', file)
```

To upload unicode text, use **put\_block\_blob\_from\_text** which will do the conversion to bytes using the specified encoding.

To upload bytes, use **put\_block\_blob\_from\_bytes**.

To download a blob named 'image.png' to a file on disk 'downloads/image.png', where the 'downloads' folder already exists, the **get\_blob\_to\_path** method can be used:

```Python
from azure.storage import BlobService
blob_service = BlobService(account_name, account_key)
blob = blob_service.get_blob_to_path('images', 'image.png', 'downloads/image.png')
```

To download to an already opened file, use **get\_blob\_to\_file**.

To download to an array of bytes, use **get\_blob\_to\_bytes**.

To download to unicode text, use **get\_blob\_to\_text**.

## Storage Queues

The **create\_queue** method can be used to ensure a queue exists:

```Python
from azure.storage import QueueService
queue_service = QueueService(account_name, account_key)
queue_service.create_queue('taskqueue')
```

The **put\_message** method can then be called to insert the message into the queue:

```Python
from azure.storage import QueueService
queue_service = QueueService(account_name, account_key)
queue_service.put_message('taskqueue', 'Hello world!')
```

It is then possible to call the **get\_messages** method, process the message and then call **delete\_message** with the message id and receipt. This two-step process ensures messages don't get lost when they are removed from the queue.

```Python
from azure.storage import QueueService
queue_service = QueueService(account_name, account_key)
messages = queue_service.get_messages('taskqueue')
queue_service.delete_message('taskqueue', messages[0].message_id, messages[0].pop_receipt)
```

## ServiceBus Queues

ServiceBus Queues are an alternative to Storage Queues that might be useful in scenarios where more advanced messaging features are needed (larger message sizes, message ordering, single-operaiton destructive reads, scheduled delivery) using push-style delivery (using long polling).

The **create\_queue** method can be used to ensure a queue exists:

```Python
from azure.servicebus import ServiceBusService
sbs = ServiceBusService(service_namespace, account_key, 'owner')
sbs.create_queue('taskqueue')
```

The **send\_queue\_message** method can then be called to insert the message into the queue:

```Python
from azure.servicebus import ServiceBusService, Message
sbs = ServiceBusService(service_namespace, account_key, 'owner')
msg = Message('Hello World!')
sbs.send_queue_message('taskqueue', msg)
```

It is then possible to call the **receive\_queue\_message** method to dequeue the message.

```Python
from azure.servicebus import ServiceBusService
sbs = ServiceBusService(service_namespace, account_key, 'owner')
msg = sbs.receive_queue_message('taskqueue')
```

## ServiceBus Topics

ServiceBus topics are an abstraction on top of ServiceBus Queues that make pub/sub scenarios easy to implement.

The **create\_topic** method can be used to create a server-side topic:

```Python
from azure.servicebus import ServiceBusService
sbs = ServiceBusService(service_namespace, account_key, 'owner')
sbs.create_topic('taskdiscussion')
```

The **send\_topic\_message** method can be used to send a message to a topic:

```Python
from azure.servicebus import ServiceBusService, Message
sbs = ServiceBusService(service_namespace, account_key, 'owner')
msg = Message('Hello World!')
sbs.send_topic_message('taskdiscussion', msg)
```

A client can then create a subscription and start consuming messages by calling the **create\_subscription** method followed by the **receive\_subscription\_message** method. Please note that any messages sent before the subscription is created will not be received.

```Python
from azure.servicebus import ServiceBusService, Message
sbs = ServiceBusService(service_namespace, account_key, 'owner')
sbs.create_subscription('taskdiscussion', 'client1')
msg = Message('Hello World!')
sbs.send_topic_message('taskdiscussion', msg)
msg = sbs.receive_subscription_message('taskdiscussion', 'client1')
```

## Service Management

### Set-up certificates

You  need to create two certificates, one for the server (a .cer file) and one for the client (a .pem file). To create the .pem file using [OpenSSL](http://www.openssl.org), execute this:

  openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem

To create the .cer certificate, execute this:

  openssl x509 -inform pem -in mycert.pem -outform der -out mycert.cer

After you have created the certificate, you will need to upload the .cer file to Microsoft Azure via the "Upload" action of the "Settings" tab of the [management portal](http://manage.windows.com).

To initialize the management service, pass in your subscription id and the path to the .pem file.

```Python
from azure.servicemanagement import ServiceManagementService
subscription_id = '00000000-0000-0000-0000-000000000000'
cert_file = 'mycert.pem'
sms = ServiceManagementService(subscription_id, cert_file)
```

### List Available Locations

```Python
locations = sms.list_locations()
for location in locations:
    print(location.name)
```

### Create a Storage Service

To create a storage service, you need a name for the service (between 3 and 24 lowercase characters and unique within Microsoft Azure), a label (up to 100 characters, automatically encoded to base-64), and either a location or an affinity group.

```Python
name = "mystorageservice"
desc = name
label = name
location = 'West US'

result = sms.create_storage_account(name, desc, label, location=location)
```

### Create a Cloud Service

A cloud service is also known as a hosted service (from earlier versions of Microsoft Azure).  The **create_hosted_service** method allows you to create a new hosted service by providing a hosted service name (which must be unique in Microsoft Azure), a label (automatically encoded to base-64), and the location *or* the affinity group for your service.

```Python
name = "myhostedservice"
desc = name
label = name
location = 'West US'

result = sms.create_hosted_service(name, label, desc, location=location)
```

### Create a Deployment

To make a new deployment to Azure you must store the package file in a Microsoft Azure Blob Storage account under the same subscription as the hosted service to which the package is being uploaded. You can create a deployment package with the [Microsoft Azure PowerShell cmdlets](https://www.windowsazure.com/en-us/develop/php/how-to-guides/powershell-cmdlets/), or with the [cspack commandline tool](http://msdn.microsoft.com/en-us/library/wingg432988.aspx).

```Python
service_name = "myhostedservice"
deployment_name = "v1"
slot = 'Production'
package_url = "URL_for_.cspkg_file"
configuration = base64.b64encode(open(file_path, 'rb').read('path_to_.cscfg_file'))
label = service_name

result = sms.create_deployment(service_name,
                     slot,
                     deployment_name,
                     package_url,
                     label,
                     configuration)

operation = sms.get_operation_status(result.request_id)
print('Operation status: ' + operation.status)
```

** For more examples please see the [Microsoft Azure Python Developer Center](http://www.windowsazure.com/en-us/develop/python) **

# Need Help?

Be sure to check out the Microsoft Azure [Developer Forums on Stack Overflow](http://go.microsoft.com/fwlink/?LinkId=234489) if you have trouble with the provided code.

# Contribute Code or Provide Feedback

If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://windowsazure.github.com/guidelines.html).

If you encounter any bugs with the library please file an issue in the [Issues](https://github.com/WindowsAzure/azure-sdk-for-python/issues) section of the project.

# Learn More
[Microsoft Azure Python Developer Center](http://www.windowsazure.com/en-us/develop/python/)


text:
//
//  HoistObject.h
//  Hoist
//
//  Created by Will Townsend on 20/02/14.
//  Copyright (c) 2014 Will Townsend. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "Hoist.h"

@interface HoistObject : NSObject

/**
 The default Hoist _createdDate property
 */
@property (strong, nonatomic) NSDate *createdDate;
/**
 The default Hoist _updatedAt property
 */
@property (strong, nonatomic) NSDate *updatedDate;
/**
 The default Hoist _id property
 */
@property (strong, nonatomic) NSString *objectId;
/**
 The default Hoist _rev property
 */
@property (strong, nonatomic) NSString *rev;
/**
 The default Hoist _type property
 */
@property (strong, nonatomic) NSString *type;

/**
 Fetch all of the object type.

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes two arguments: an array of decoded objects and the HoistResponseCode.
 */
+ (void)fetchAllWithCompletion:(void (^)(NSArray *objects, HoistResponseStatusCode responseCode))completion;

/**
 Fetch the object by id.

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes two arguments: the decoded HoistObject object and the HoistResponseCode.
 */
+ (void)fetchByObjectId:(NSString *)objectId completion:(void (^)(id object, HoistResponseStatusCode responseCode))completion;

/**
 Delete all of the HoistObjects
 */
+ (void)deleteAll;

/**
 Delete all of the HoistObject(s) with a callback

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes one arguments: the HoistResponseCode.
 */
+ (void)deleteAllWithCompletion:(void (^)(HoistResponseStatusCode responseCode))completion;

/**
 Save the HoistObject

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes one arguments: the HoistResponseCode.
 */
- (void)save;

/**
 Save the HoistObject with a callback

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes one arguments: the HoistResponseCode.
 */
- (void)saveWithCompletion:(void (^)(HoistResponseStatusCode responseCode))completion;

/**
 Delete the HoistObject
 */
- (void)delete;

/**
 Delete the HoistObject with a callback

 @param completion The completion block to be executed when the task finishes. This block has no return value and takes one arguments: the HoistResponseCode.
 */
- (void)deleteWithCompletion:(void (^)(HoistResponseStatusCode responseCode))completion;

/**
 Configure the HoistObject from an NSDictionary

 @param dictionary The NSDictionary containing the keys and values that will map to the HoistObject
 */
- (void)configureWithDictionary:(NSDictionary *)dictionary;

/**
 Dictionary of Object Properties to JSON Mappings

 Subclasses of HoistObject can override this to provide custom mappings. Make sure to add to the [super configureWithDictionary]
*/
- (NSMutableDictionary *)propertyToJSONMappings;

@end


text:
VirtualBox Hypervisor is used to build a local vm and then imported as an AMI using
the amazon import service https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html.

## Requirements

* Set your aws credentials on the default location `~/.aws/credentials`. https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
* Packer 1.2.3+. https://www.packer.io/downloads.html
* S3 Bucket with the necessary permissions. Set the `AWS_S3_BUCKET` environment variable.
* If you use SAML authentication make sure you set `profile` in the amazon-import post-processor.
* `vm-guest-tools` provisioner is removed.


text:
import logging
import threading
import time
import queue

# Parent class for every sensor
# Schedules measurements in a separate thread
class Sensor(threading.Thread):
    def __init__(self, interval, name):
        self.interval = interval
        self.queue = queue.Queue(1)
        super().__init__(name=name, daemon=True)

    def run(self):
        logger = logging.getLogger('hiverize.{}'.format(self.name))
        logger.debug('Started a new measurement thread')
        exit = threading.Event()
        while not exit.is_set():
            now = time.time()
            data = self.get_data()
            self.queue.put(data)
            waittime = (now - time.time() + self.interval)
            logger.debug('Wait for {:.2f} seconds'.format(waittime))
            exit.wait(waittime)

    def get_data(self):
        pass


text:
'''
demandimport - automatic demandloading of modules

To enable this module, do:

  import demandimport; demandimport.enable()

Imports of the following forms will be demand-loaded:

  import a, b.c
  import a.b as c
  from a import b,c # a will be loaded immediately

These imports will not be delayed:

  from a import *
  b = __import__(a)
'''

_origimport = __import__

class _demandmod(object):
    """module demand-loader and proxy"""
    def __init__(self, name, globals, locals):
        if '.' in name:
            head, rest = name.split('.', 1)
            after = [rest]
        else:
            head = name
            after = []
        object.__setattr__(self, "_data", (head, globals, locals, after))
        object.__setattr__(self, "_module", None)
    def _extend(self, name):
        """add to the list of submodules to load"""
        self._data[3].append(name)
    def _load(self):
        if not self._module:
            head, globals, locals, after = self._data
            mod = _origimport(head, globals, locals)
            # load submodules
            def subload(mod, p):
                h, t = p, None
                if '.' in p:
                    h, t = p.split('.', 1)
                if not hasattr(mod, h):
                    setattr(mod, h, _demandmod(p, mod.__dict__, mod.__dict__))
                elif t:
                    subload(getattr(mod, h), t)

            for x in after:
                subload(mod, x)

            # are we in the locals dictionary still?
            if locals and locals.get(head) == self:
                locals[head] = mod
            object.__setattr__(self, "_module", mod)

    def __repr__(self):
        if self._module:
            return "<proxied module '%s'>" % self._data[0]
        return "<unloaded module '%s'>" % self._data[0]
    def __call__(self, *args, **kwargs):
        raise TypeError("%s object is not callable" % repr(self))
    def __getattribute__(self, attr):
        if attr in ('_data', '_extend', '_load', '_module'):
            return object.__getattribute__(self, attr)
        self._load()
        return getattr(self._module, attr)
    def __setattr__(self, attr, val):
        self._load()
        setattr(self._module, attr, val)

def _demandimport(name, globals=None, locals=None, fromlist=None, level=None):
    if not locals or name in ignore or fromlist == ('*',):
        # these cases we can't really delay
        return _origimport(name, globals, locals, fromlist)
    elif not fromlist:
        # import a [as b]
        if '.' in name: # a.b
            base, rest = name.split('.', 1)
            # email.__init__ loading email.mime
            if globals and globals.get('__name__', None) == base:
                return _origimport(name, globals, locals, fromlist)
            # if a is already demand-loaded, add b to its submodule list
            if base in locals:
                if isinstance(locals[base], _demandmod):
                    locals[base]._extend(rest)
                return locals[base]
        return _demandmod(name, globals, locals)
    else:
        if level is not None:
            # from . import b,c,d or from .a import b,c,d
            return _origimport(name, globals, locals, fromlist, level)
        # from a import b,c,d
        mod = _origimport(name, globals, locals)
        # recurse down the module chain
        for comp in name.split('.')[1:]:
            if not hasattr(mod, comp):
                setattr(mod, comp, _demandmod(comp, mod.__dict__, mod.__dict__))
            mod = getattr(mod, comp)
        for x in fromlist:
            # set requested submodules for demand load
            if not(hasattr(mod, x)):
                setattr(mod, x, _demandmod(x, mod.__dict__, locals))
        return mod

ignore = [
    '_hashlib',
    '_xmlplus',
    'fcntl',
    'win32com.gen_py',
    # imported by tarfile, not available under Windows
    'pwd',
    'grp',
    # imported by profile, itself imported by hotshot.stats,
    # not available under Windows
    'resource',
    ]

def enable():
    "enable global demand-loading of modules"
    __builtins__["__import__"] = _demandimport

def disable():
    "disable global demand-loading of modules"
    __builtins__["__import__"] = _origimport


text:
import argparse

import numpy as np
try:
  import pygame
except ImportError:
  print('Please install the pygame package to use the GUI.')
  raise
from PIL import Image

import crafter

def main():
  boolean = lambda x: bool(['False', 'True'].index(x))
  parser = argparse.ArgumentParser()
  parser.add_argument('--seed', type=int, default=None)
  parser.add_argument('--area', nargs=2, type=int, default=(64, 64))
  parser.add_argument('--view', type=int, nargs=2, default=(9, 9))
  parser.add_argument('--length', type=int, default=None)
  parser.add_argument('--health', type=int, default=9)
  parser.add_argument('--window', type=int, nargs=2, default=(600, 600))
  parser.add_argument('--size', type=int, nargs=2, default=(0, 0))
  parser.add_argument('--record', type=str, default=None)
  parser.add_argument('--fps', type=int, default=5)
  parser.add_argument('--wait', type=boolean, default=False)
  parser.add_argument('--death', type=str, default='reset', choices=[
      'continue', 'reset', 'quit'])
  args = parser.parse_args()

  keymap = {
      pygame.K_a: 'move_left',
      pygame.K_d: 'move_right',
      pygame.K_w: 'move_up',
      pygame.K_s: 'move_down',
      pygame.K_SPACE: 'do',
      pygame.K_TAB: 'sleep',

      pygame.K_r: 'place_stone',
      pygame.K_t: 'place_table',
      pygame.K_f: 'place_furnace',
      pygame.K_p: 'place_plant',

      pygame.K_1: 'make_wood_pickaxe',
      pygame.K_2: 'make_stone_pickaxe',
      pygame.K_3: 'make_iron_pickaxe',
      pygame.K_4: 'make_wood_sword',
      pygame.K_5: 'make_stone_sword',
      pygame.K_6: 'make_iron_sword',
  }
  print('Actions:')
  for key, action in keymap.items():
    print(f'  {pygame.key.name(key)}: {action}')

  crafter.constants.items['health']['max'] = args.health
  crafter.constants.items['health']['initial'] = args.health

  size = list(args.size)
  size[0] = size[0] or args.window[0]
  size[1] = size[1] or args.window[1]

  env = crafter.Env(
      area=args.area, view=args.view, length=args.length, seed=args.seed)
  env = crafter.Recorder(env, args.record)
  env.reset()
  achievements = set()
  duration = 0
  return_ = 0
  was_done = False
  print('Diamonds exist:', env._world.count('diamond'))

  pygame.init()
  screen = pygame.display.set_mode(args.window)
  clock = pygame.time.Clock()
  running = True
  while running:

    # Rendering.
    image = env.render(size)
    if size != args.window:
      image = Image.fromarray(image)
      image = image.resize(args.window, resample=Image.NEAREST)
      image = np.array(image)
    surface = pygame.surfarray.make_surface(image.transpose((1, 0, 2)))
    screen.blit(surface, (0, 0))
    pygame.display.flip()
    clock.tick(args.fps)

    # Keyboard input.
    action = None
    pygame.event.pump()
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        running = False
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
        running = False
      elif event.type == pygame.KEYDOWN and event.key in keymap.keys():
        action = keymap[event.key]
    if action is None:
      pressed = pygame.key.get_pressed()
      for key, action in keymap.items():
        if pressed[key]:
          break
      else:
        if args.wait and not env._player.sleeping:
          continue
        else:
          action = 'noop'

    # Environment step.
    _, reward, done, _ = env.step(env.action_names.index(action))
    duration += 1

    # Achievements.
    unlocked = {
        name for name, count in env._player.achievements.items()
        if count > 0 and name not in achievements}
    for name in unlocked:
      achievements |= unlocked
      total = len(env._player.achievements.keys())
      print(f'Achievement ({len(achievements)}/{total}): {name}')
    if env._step > 0 and env._step % 100 == 0:
      print(f'Time step: {env._step}')
    if reward:
      print(f'Reward: {reward}')
      return_ += reward

    # Episode end.
    if done and not was_done:
      was_done = True
      print('Episode done!')
      print('Duration:', duration)
      print('Return:', return_)
      if args.death == 'quit':
        running = False
      if args.death == 'reset':
        print('\nStarting a new episode.')
        env.reset()
        achievements = set()
        was_done = False
        duration = 0
        return_ = 0
      if args.death == 'continue':
        pass

  pygame.quit()

if __name__ == '__main__':
  main()


text:
/*
 * Use and distribution licensed under the Apache license version 2.
 *
 * See the COPYING file in the root project directory for full text.
 */

#include "sqltoast/sqltoast.h"

#include "parser/compare.h"
#include "parser/keyword.h"
#include "parser/symbol.h"

namespace sqltoast {

// NOTE(jaypipes): These keywords are inserted in order of FREQUENCY of
// appearance in SQL statements, not alphabetically.
kw_jump_table_t _init_kw_jump_table(char lead_char) {
    kw_jump_table_t t;

    switch (lead_char) {
        case 'a':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_AND, "AND"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_AS, "AS"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_AVG, "AVG"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ALTER, "ALTER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ALL, "ALL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ANY, "ANY"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ACTION, "ACTION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_AT, "AT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ADD, "ADD"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_AUTHORIZATION, "AUTHORIZATION"));
            return t;
        case 'b':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_BETWEEN, "BETWEEN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_BY, "BY"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_BIT, "BIT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_BIT_LENGTH, "BIT_LENGTH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_BOTH, "BOTH"));
            return t;
        case 'c':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COUNT, "COUNT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COMMIT, "COMMIT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CREATE, "CREATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CURRENT_DATE, "CURRENT_DATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CURRENT_TIME, "CURRENT_TIME"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CURRENT_TIMESTAMP, "CURRENT_TIMESTAMP"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CURRENT_USER, "CURRENT_USER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COALESCE, "COALESCE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CASE, "CASE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CROSS, "CROSS"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CONVERT, "CONVERT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CHAR_LENGTH, "CHAR_LENGTH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CHARACTER_LENGTH, "CHARACTER_LENGTH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CHAR, "CHAR"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CHARACTER, "CHARACTER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CASCADE, "CASCADE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CHECK, "CHECK"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COLUMN, "COLUMN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COLLATE, "COLLATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_COLLATION, "COLLATION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CONSTRAINT, "CONSTRAINT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_CASCADED, "CASCADED"));
            return t;
        case 'd':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DELETE, "DELETE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DISTINCT, "DISTINCT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DATE, "DATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DAY, "DAY"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DEC, "DEC"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DECIMAL, "DECIMAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DEFAULT, "DEFAULT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DROP, "DROP"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DOUBLE, "DOUBLE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_DOMAIN, "DOMAIN"));
            return t;
        case 'e':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_EXISTS, "EXISTS"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_END, "END"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ELSE, "ELSE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_EXTRACT, "EXTRACT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ESCAPE, "ESCAPE"));
            return t;
        case 'f':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_FROM, "FROM"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_FOR, "FOR"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_FLOAT, "FLOAT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_FULL, "FULL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_FOREIGN, "FOREIGN"));
            return t;
        case 'g':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_GROUP, "GROUP"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_GLOBAL, "GLOBAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_GRANT, "GRANT"));
            return t;
        case 'h':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_HAVING, "HAVING"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_HOUR, "HOUR"));
            return t;
        case 'i':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_IN, "IN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INSERT, "INSERT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INTO, "INTO"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_IS, "IS"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INNER, "INNER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INTERVAL, "INTERVAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INT, "INT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_INTEGER, "INTEGER"));
            return t;
        case 'j':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_JOIN, "JOIN"));
            return t;
        case 'k':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_KEY, "KEY"));
            return t;
        case 'l':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_LIKE, "LIKE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_LEFT, "LEFT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_LOWER, "LOWER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_LOCAL, "LOCAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_LEADING, "LEADING"));
            return t;
        case 'm':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_MAX, "MAX"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_MIN, "MIN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_MATCH, "MATCH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_MINUTE, "MINUTE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_MONTH, "MONTH"));
            return t;
        case 'n':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NOT, "NOT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NO, "NO"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NULL, "NULL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NULLIF, "NULLIF"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NATURAL, "NATURAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NATIONAL, "NATIONAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NCHAR, "NCHAR"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_NUMERIC, "NUMERIC"));
            return t;
        case 'o':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_OR, "OR"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ON, "ON"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_OUTER, "OUTER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_OCTET_LENGTH, "OCTET_LENGTH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_OPTION, "OPTION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_OVERLAPS, "OVERLAPS"));
            return t;
        case 'p':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_POSITION, "POSITION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_PRECISION, "PRECISION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_PRIMARY, "PRIMARY"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_PARTIAL, "PARTIAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_PRIVILEGES, "PRIVILEGES"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_PUBLIC, "PUBLIC"));
            return t;
        case 'r':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ROLLBACK, "ROLLBACK"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_RIGHT, "RIGHT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_REAL, "REAL"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_REFERENCES, "REFERENCES"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_RESTRICT, "RESTRICT"));
            return t;
        case 's':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SELECT, "SELECT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SET, "SET"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SUM, "SUM"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SCHEMA, "SCHEMA"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SECOND, "SECOND"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SUBSTRING, "SUBSTRING"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SMALLINT, "SMALLINT"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SESSION_USER, "SESSION_USER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SYSTEM_USER, "SYSTEM_USER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_SOME, "SOME"));
            return t;
        case 't':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TABLE, "TABLE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TIME, "TIME"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TIMESTAMP, "TIMESTAMP"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TEMPORARY, "TEMPORARY"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TRIM, "TRIM"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_THEN, "THEN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TO, "TO"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TRAILING, "TRAILING"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TRANSLATE, "TRANSLATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_TRANSLATION, "TRANSLATION"));
            return t;
        case 'u':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_UPDATE, "UPDATE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_UPPER, "UPPER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_USING, "USING"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_UNION, "UNION"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_USER, "USER"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_UNIQUE, "UNIQUE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_USAGE, "USAGE"));
            return t;
        case 'v':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_VALUES, "VALUES"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_VARCHAR, "VARCHAR"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_VARYING, "VARYING"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_VIEW, "VIEW"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_VALUE, "VALUE"));
            return t;
        case 'w':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_WHERE, "WHERE"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_WITH, "WITH"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_WHEN, "WHEN"));
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_WORK, "WORK"));
            return t;
        case 'y':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_YEAR, "YEAR"));
            return t;
        case 'z':
            t.emplace_back(kw_jump_table_entry_t(SYMBOL_ZONE, "ZONE"));
            return t;
    }
    return t;
}

kw_jump_table_t kw_jump_tables::a = _init_kw_jump_table('a');
kw_jump_table_t kw_jump_tables::b = _init_kw_jump_table('b');
kw_jump_table_t kw_jump_tables::c = _init_kw_jump_table('c');
kw_jump_table_t kw_jump_tables::d = _init_kw_jump_table('d');
kw_jump_table_t kw_jump_tables::e = _init_kw_jump_table('e');
kw_jump_table_t kw_jump_tables::f = _init_kw_jump_table('f');
kw_jump_table_t kw_jump_tables::g = _init_kw_jump_table('g');
kw_jump_table_t kw_jump_tables::h = _init_kw_jump_table('h');
kw_jump_table_t kw_jump_tables::i = _init_kw_jump_table('i');
kw_jump_table_t kw_jump_tables::j = _init_kw_jump_table('j');
kw_jump_table_t kw_jump_tables::k = _init_kw_jump_table('k');
kw_jump_table_t kw_jump_tables::l = _init_kw_jump_table('l');
kw_jump_table_t kw_jump_tables::m = _init_kw_jump_table('m');
kw_jump_table_t kw_jump_tables::n = _init_kw_jump_table('n');
kw_jump_table_t kw_jump_tables::o = _init_kw_jump_table('o');
kw_jump_table_t kw_jump_tables::p = _init_kw_jump_table('p');
kw_jump_table_t kw_jump_tables::r = _init_kw_jump_table('r');
kw_jump_table_t kw_jump_tables::s = _init_kw_jump_table('s');
kw_jump_table_t kw_jump_tables::t = _init_kw_jump_table('t');
kw_jump_table_t kw_jump_tables::u = _init_kw_jump_table('u');
kw_jump_table_t kw_jump_tables::v = _init_kw_jump_table('v');
kw_jump_table_t kw_jump_tables::w = _init_kw_jump_table('w');
kw_jump_table_t kw_jump_tables::y = _init_kw_jump_table('y');
kw_jump_table_t kw_jump_tables::z = _init_kw_jump_table('z');

tokenize_result_t token_keyword(
        parse_position_t cursor,
        const parse_position_t end) {
    kw_jump_table_t* jump_tbl;
    switch (*cursor) {
        case 'a':
        case 'A':
            jump_tbl = &kw_jump_tables::a;
            break;
        case 'b':
        case 'B':
            jump_tbl = &kw_jump_tables::b;
            break;
        case 'c':
        case 'C':
            jump_tbl = &kw_jump_tables::c;
            break;
        case 'd':
        case 'D':
            jump_tbl = &kw_jump_tables::d;
            break;
        case 'e':
        case 'E':
            jump_tbl = &kw_jump_tables::e;
            break;
        case 'f':
        case 'F':
            jump_tbl = &kw_jump_tables::f;
            break;
        case 'g':
        case 'G':
            jump_tbl = &kw_jump_tables::g;
            break;
        case 'h':
        case 'H':
            jump_tbl = &kw_jump_tables::h;
            break;
        case 'i':
        case 'I':
            jump_tbl = &kw_jump_tables::i;
            break;
        case 'j':
        case 'J':
            jump_tbl = &kw_jump_tables::j;
            break;
        case 'k':
        case 'K':
            jump_tbl = &kw_jump_tables::k;
            break;
        case 'l':
        case 'L':
            jump_tbl = &kw_jump_tables::l;
            break;
        case 'm':
        case 'M':
            jump_tbl = &kw_jump_tables::m;
            break;
        case 'n':
        case 'N':
            jump_tbl = &kw_jump_tables::n;
            break;
        case 'o':
        case 'O':
            jump_tbl = &kw_jump_tables::o;
            break;
        case 'p':
        case 'P':
            jump_tbl = &kw_jump_tables::p;
            break;
        case 'r':
        case 'R':
            jump_tbl = &kw_jump_tables::r;
            break;
        case 's':
        case 'S':
            jump_tbl = &kw_jump_tables::s;
            break;
        case 't':
        case 'T':
            jump_tbl = &kw_jump_tables::t;
            break;
        case 'u':
        case 'U':
            jump_tbl = &kw_jump_tables::u;
            break;
        case 'v':
        case 'V':
            jump_tbl = &kw_jump_tables::v;
            break;
        case 'w':
        case 'W':
            jump_tbl = &kw_jump_tables::w;
            break;
        case 'y':
        case 'Y':
            jump_tbl = &kw_jump_tables::y;
            break;
        case 'z':
        case 'Z':
            jump_tbl = &kw_jump_tables::z;
            break;
        default:
            return tokenize_result_t(TOKEN_NOT_FOUND);
    }

    parse_position_t start = cursor;
    // Find the next delimiter character...
    while (cursor != end && (std::isalnum(*cursor) || *cursor == '_'))
        cursor++;

    const std::string lexeme(start, cursor);
    const size_t lexeme_len = cursor - start;
    size_t entry_len;
    for (auto entry : *jump_tbl) {
        entry_len = entry.kw_str.size();
        if (lexeme_len != entry_len)
            continue;
        if (ci_find_substr(lexeme, entry.kw_str) == 0) {
            return tokenize_result_t(entry.symbol, start, cursor);
        }
    }
    return tokenize_result_t(TOKEN_NOT_FOUND);
}

} // namespace sqltoast


text:
class TestDelegate < ProMotion::Delegate
  status_bar false

  def on_load(app, options)
  end
end