text:
package com.github.xdcrafts.swarm.javaz.either;

import org.junit.Test;

import java.util.function.Function;

import static com.github.xdcrafts.swarm.javaz.either.EitherOps.left;
import static com.github.xdcrafts.swarm.javaz.either.EitherOps.right;

import static org.junit.Assert.assertEquals;

/**
 * Created by vdubs
 * on 8/22/14.
 */
@SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
public class EitherTest {

    @Test
    public void fmapTest() {
        final Function<String, String> function = s -> s + "two";
        final IEither<String, String> left = left("one");
        assertEquals(left("one"), left.map(function));
        assertEquals(right("onetwo"), right("one").map(function));
    }

    @Test
    public void amapTest() {
        final Function<String, String> function = s -> s + "two";
        final IEither<?, Function<String, String>> rightF = EitherOps.ID.pure(function);
        final IEither<String, Function<String, String>> leftF = left("nofun");
        final IEither<String, String> left = left("one");
        assertEquals(left("one"), left.applicativeMap(rightF));
        assertEquals(left("nofun"), left.applicativeMap(leftF));
        assertEquals(right("onetwo"), right("one").applicativeMap(rightF));
        assertEquals(left("nofun"), right("one").applicativeMap(leftF));
    }

    @Test
    public void mmapTest() {
        final Function<String, IEither<String, String>> rightFunction = s -> right(s + "right");
        final Function<String, IEither<String, String>> leftFunction = s -> left(s + "left");
        final IEither<String, String> left = left("one");
        assertEquals(left("one"), left.flatMap(rightFunction));
        assertEquals(left("one"), left.flatMap(leftFunction));
        assertEquals(right("oneright"), right("one").flatMap(rightFunction));
        assertEquals(left("oneleft"), right("one").flatMap(leftFunction));
    }

    @Test
    public void yieldForTestRight() {
        final Either<String, Integer> either = EitherOps.ID.yieldFor(
            right("first"), right("second"), right("third").map(String::length),
            (s1, s2, i3) -> s1.length() + s2.length() + i3
        );
        assertEquals(right(16), either);
    }

    @Test
    public void yieldForTestLeft() {
        final Either<String, Integer> either = EitherOps.ID.yieldFor(
            right("first"), left("fail"), right("third").map(String::length),
            (String s1, String s2, Integer i3) -> s1.length() + s2.length() + i3
        );
        assertEquals(left("fail"), either);
    }
}


text:
package me.jaxbot.wear.leafstatus;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.URLEncoder;

/**
 * Created by jonathan on 9/21/14.
 */
public class Carwings {
    static String TAG = "Carwings";

    public static String[] PortalURL = {
        "https://owners.nissanusa.com/nowners/", // US
        "https://carwings.mynissan.ca/", // CA
        "http://www.nissan.co.uk/GB/en/YouPlus/welcome_pack_leaf.html/" // UK
    };

    private String username;
    private String password;
    private String vin;

    public int currentBattery;
    public String range;
    public String chargeTime;
    public boolean currentHvac;
    public String lastUpdateTime;
    public String chargerType;
    public boolean charging;
    public boolean autoUpdate;
    public boolean showPermanent;
    public boolean useMetric;
    public boolean noNightUpdates;
    public boolean notifyOnlyWhenCharging;
    public boolean alwaysShowStartHVAC;

    // Endpoint url for this instance
    String url;

    SharedPreferences settings;

    // Disgusting, but we're using the web frontend, and thus will pretend
    String UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";

    public Carwings(Context context)
    {
        settings = context.getSharedPreferences("U", 0);
        this.username = settings.getString("username", "");
        this.password = settings.getString("password", "");
        this.vin = settings.getString("vin", "");
        this.currentBattery = settings.getInt("currentBattery", 0);
        this.chargeTime = settings.getString("chargeTime", "");
        this.range = settings.getString("range", "");
        this.lastUpdateTime = settings.getString("lastupdate", "");
        this.url = "https://gdcportalgw.its-mo.com/orchestration_1021/gdc/";
        this.chargerType = settings.getString("chargerType", "L1");
        this.charging = settings.getBoolean("charging", false);
        this.autoUpdate = settings.getBoolean("autoupdate", true);
        this.showPermanent = settings.getBoolean("showPermanent", false);
        this.useMetric = settings.getBoolean("useMetric", false);
        this.noNightUpdates = settings.getBoolean("noNightUpdates", true);
        this.notifyOnlyWhenCharging = settings.getBoolean("notifyOnlyWhenCharging", false);
        this.alwaysShowStartHVAC = settings.getBoolean("alwaysShowStartHVAC", false);
        Configuration.init(context);
    }
    private CookieStore login() {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        if (username.equals("")) return null;
        try {
            String result = getHTTPString(url + "/UserLoginRequest.php?UserId=" + URLEncoder.encode(username, "utf-8") + "&cartype=&tz=&lg=en-US&DCMID=&VIN=&RegionCode=NNA&Password=" + URLEncoder.encode(password, "utf-8"));
            JSONObject jObject = new JSONObject(result);
            String vin = jObject.getJSONObject("CustomerInfo").getJSONObject("VehicleInfo").getString("VIN");
            System.out.println("Your VIN is " + vin);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("vin", vin);
            editor.commit();

        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

        return null;
    }

    public boolean trylogin() {
        return !getCarId(login()).equals("");
    }

    private String getCarId(CookieStore jar) {
        // Check if we have already grabbed this
        String cachedCarID = settings.getString("vin", "");
        if (!cachedCarID.equals(""))
            return cachedCarID;

        // This is a particularly bad and non-future-safe operation,
        // but so is the entire application, since Nissan's API is internal
        String vehicleHTML = getHTTPString(url + "user/home");
        System.out.println(vehicleHTML);
        Pattern pattern = Pattern.compile("(.*)var vinId = \"([a-zA-Z0-9]+)\"(.*)");
        Matcher m = pattern.matcher(vehicleHTML);
        if (m.matches()) {
            cachedCarID = m.group(2);

            // Save it, since it is unlikely to change
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("vin", cachedCarID);
            editor.commit();

            return cachedCarID;
        } else {
            Log.e(TAG, "Failed to find vehicle id");
            return "";
        }
    }

    public boolean update() {
        try {
            String encodedUsername = "";
            try {
               encodedUsername = URLEncoder.encode(username, "utf-8");
            } catch (Exception e) {
            }

            String request = getHTTPString(url + "BatteryStatusCheckRequest.php?UserId=" + encodedUsername + "&cartype=&VIN=" + vin + "&RegionCode=NNA&tz=America%2FNew_York&lg=en-US");
            JSONObject requestResults = new JSONObject(request);
            final String resultKey = requestResults.getString("resultKey");

            final Timer poller = new Timer();
            final String finalEncodedUsername = encodedUsername;
            poller.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("checking bat status");
                    try {
                        String request = getHTTPString(url + "BatteryStatusCheckResultRequest.php?UserId=" + URLEncoder.encode(username, "utf-8") + "&cartype=&resultKey=" + resultKey + "&tz=America%2FNew_York&lg=en-US&VIN=" + vin + "&RegionCode=NNA");
                        JSONObject requestResults = new JSONObject(request);
                        if (requestResults.has("chargeMode")) {
                            poller.cancel();

                            System.out.println("We got the data we need. It is: " + request);
                            String recordsRequest = getHTTPString(url + "BatteryStatusRecordsRequest.php?UserId=" + finalEncodedUsername + "&cartype=&tz=America%2FNew_York&lg=en-US&VIN=" + vin + "&RegionCode=NNA");
                            System.out.println("records: " + recordsRequest);
                            JSONObject records = new JSONObject(recordsRequest).getJSONObject("BatteryStatusRecords");

                            currentBattery = records.getJSONObject("BatteryStatus").getInt("BatteryRemainingAmount");

                            String l1Time = "null";
                            String l2Time = "null";
                            String l3Time = "null";

                            try {
                                l1Time = records.getJSONObject("TimeRequiredToFull").getString("HourRequiredToFull");
                            } catch (Exception e) {}
                            try {
                            l2Time = records.getJSONObject("TimeRequiredToFull200").getString("HourRequiredToFull");
                            } catch (Exception e) {}
                            try {
                                l3Time = records.getJSONObject("TimeRequiredToFull200_6kW").getString("HourRequiredToFull");
                            } catch (Exception e) {}

                            chargeTime = l1Time;
                            chargerType = "L1";

                            int defaultCharger = settings.getInt("defaultChargeLevel", 0);
                            Log.d(TAG, "def: " + defaultCharger);

                            if (chargeTime.equals("null") || (!l2Time.equals("null") && defaultCharger == 1)) {
                                chargeTime = l2Time;
                                chargerType = "L2";
                            }

                            if (chargeTime.equals("null") || (!l3Time.equals("null") && defaultCharger == 2)) {
                                chargeTime = l3Time;
                                chargerType = "L2+";
                            }

                            if (chargeTime.equals("null")) {
                                chargeTime = "Unknown";
                                chargerType = "?";
                            }

                            charging = !requestResults.getString("chargeMode").equals("NOT_CHARGING");

                            int range_km = (int)Float.parseFloat(records.getString("CruisingRangeAcOff")) / 1000;
                            System.out.println("rangekm: " + range_km);
                            if (useMetric)
                                range = Math.round(range_km) + " km";
                            else
                                range = Math.round(range_km * 0.621371) + " mi";

                            Time today = new Time(Time.getCurrentTimezone());
                            today.setToNow();
                            lastUpdateTime = today.format("%Y-%m-%d %H:%M:%S");

                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("range", range);
                            editor.putString("chargeTime", chargeTime);
                            editor.putBoolean("charging", charging);
                            editor.putString("chargerType", chargerType);
                            editor.putString("lastupdate", lastUpdateTime);
                            editor.putInt("currentBattery", currentBattery);
                            editor.commit();

                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.toString());
                    }
                }
            }, 0, 10000);

            return true;
        } catch (Exception e) {
            System.out.println("Failure!!!");
            System.out.println(e);
        }

        return false;
    }

    public boolean startAC(boolean desired) {
        String endpoint = desired ? "ACRemoteRequest" : "ACRemoteOffRequest";

        try {
            String output = getHTTPString(url + endpoint + ".php?UserId=" + URLEncoder.encode(this.username, "utf-8") + "&cartype=&VIN=" + this.vin + "&RegionCode=NNA&tz=America%2FNew_York&lg=en-US");
            if (!output.contains("success")) {
                Log.e(TAG, "Start AC failed. Output: " + output);
                return false;
            }

        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

        return true;
    }

    private String getHTTPString(String url) {
        System.out.println("Starting GET " + url);
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("User-Agent", UA);

            HttpResponse response = httpclient.execute(httpget);

            InputStream inputStream = response.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            String result = "";

            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }

            inputStream.close();

            System.out.println("Done GET " + url);
            return result;
        } catch (Exception e) {
            System.out.println(e);
        }

        return "";

    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Dotdigitalgroup\Email\Model\Coupon;

use DateTime;
use Dotdigitalgroup\Email\Api\Data\CouponAttributeInterface;
use Dotdigitalgroup\Email\Model\DateTimeFactory;
use Magento\Framework\Api\AttributeValueFactory;
use Magento\Framework\Api\ExtensionAttributesFactory;
use Magento\Framework\Model\AbstractExtensibleModel;

/**
 * Class CouponAttributeRepository
 */
class CouponAttribute extends AbstractExtensibleModel implements CouponAttributeInterface
{
    /**
     * @var DateTimeFactory
     */
    private $dateTimeFactory;

    /**
     * @param DateTimeFactory $dateTimeFactory
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param ExtensionAttributesFactory $extensionFactory
     * @param AttributeValueFactory $customAttributeFactory
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
     * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
     * @param array $data
     */
    public function __construct(
        DateTimeFactory $dateTimeFactory,
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        ExtensionAttributesFactory $extensionFactory,
        AttributeValueFactory $customAttributeFactory,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        $this->dateTimeFactory = $dateTimeFactory;

        parent::__construct(
            $context,
            $registry,
            $extensionFactory,
            $customAttributeFactory,
            $resource,
            $resourceCollection,
            $data
        );
    }

    protected function _construct()
    {
        $this->_init(\Dotdigitalgroup\Email\Model\ResourceModel\CouponAttribute::class);
    }

    /**
     * {@inheritdoc}
     */
    public function getCouponId()
    {
        return $this->getData(self::SALESRULE_COUPON_ID);
    }

    /**
     * {@inheritdoc}
     */
    public function setCouponId($coupon_id)
    {
        return $this->setData(self::SALESRULE_COUPON_ID, $coupon_id);
    }

    /**
     * {@inheritdoc}
     */
    public function getEmail()
    {
        return $this->getData(self::EMAIL);
    }

    /**
     * {@inheritdoc}
     */
    public function setEmail($email)
    {
        return $this->setData(self::EMAIL, $email);
    }

    /**
     * {@inheritdoc}
     */
    public function getExpiresAt()
    {
        return $this->getData(self::EXPIRES_AT);
    }

    /**
     * {@inheritdoc}
     */
    public function setExpiresAt(string $expiresAt)
    {
        return $this->setData(self::EXPIRES_AT, $expiresAt);
    }

    /**
     * @return DateTime|null
     */
    public function getExpiresAtDate()
    {
        $expiresAt = $this->getExpiresAt();
        if ($expiresAt) {
            return $this->dateTimeFactory->create(['time' => $expiresAt])
                ->getUtcDate();
        }
        return null;
    }

    /**
     * @param CouponAttributeInterface $couponAttribute
     * @return CouponAttribute
     */
    public function setExtensionAttributes(CouponAttributeInterface $couponAttribute)
    {
        return $this->_setExtensionAttributes($couponAttribute);
    }

    /**
     * @return \Magento\Framework\Api\ExtensionAttributesInterface
     */
    public function getExtensionAttributes()
    {
        return parent::_getExtensionAttributes();
    }
}


text:
'''
Created on 05/10/2012

@author: Alex Ip
'''
import os
import sys
import argparse
import logging
import re
import psycopg2
import numpy
import shutil
from osgeo import gdal,osr
from math import floor, ceil
from datetime import datetime
from copy import copy
import time
import numexpr
from scipy import ndimage

from EOtools.bodies.vincenty import vinc_dist
from EOtools.blrb import interpolate_grid

from EOtools.utils import log_multiline
from EOtools.execute import execute

from agdc import DataCube

# Set top level standard output
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(console_formatter)

logger = logging.getLogger(__name__)
if not logger.level:
    logger.setLevel(logging.DEBUG) # Default logging level for all modules
    logger.addHandler(console_handler)

CONTIGUITY_BIT_INDEX = 8
nan = numpy.float32(numpy.NaN) # Smoothed DSM should have all valid data values - need this for edges only
RADIANS_PER_DEGREE = 0.01745329251994329576923690768489

class earth(object):

    # Mean radius
    RADIUS = 6371009.0  # (metres)

    # WGS-84
    #RADIUS = 6378135.0  # equatorial (metres)
    #RADIUS = 6356752.0  # polar (metres)

    # Length of Earth ellipsoid semi-major axis (metres)
    SEMI_MAJOR_AXIS = 6378137.0

    # WGS-84
    A = 6378137.0           # equatorial radius (metres)
    B = 6356752.3142        # polar radius (metres)
    F = (A - B) / A         # flattening
    ECC2 = 1.0 - B**2/A**2  # squared eccentricity

    MEAN_RADIUS = (A*2 + B) / 3

    # Earth ellipsoid eccentricity (dimensionless)
    #ECCENTRICITY = 0.00669438
    #ECC2 = math.pow(ECCENTRICITY, 2)

    # Earth rotational angular velocity (radians/sec)
    OMEGA = 0.000072722052

class DEMTiler(DataCube):

    def getFileSizekB(self, path):
        """Gets the size of a file (megabytes).

        Arguments:
            path: file path

        Returns:
            File size (MB)

        Raises:
            OSError [Errno=2] if file does not exist
        """
        return os.path.getsize(path) / 1024

    def getFileSizeMB(self, path):
        """Gets the size of a file (megabytes).

        Arguments:
            path: file path

        Returns:
            File size (MB)

        Raises:
            OSError [Errno=2] if file does not exist
        """
        return self.getFileSizekB(path) / 1024

    def parse_args(self):
        """Overrides Datacube function to parse the command line arguments.

        Returns:
            argparse namespace object
        """
        logger.debug('  Calling parse_args()')

        _arg_parser = argparse.ArgumentParser('datacube')

        _arg_parser.add_argument('-C', '--config', dest='config_file',
            default=os.path.join(self.agdc_root, 'agdc_default.conf'),
            help='DataCube configuration file')
        _arg_parser.add_argument('-d', '--debug', dest='debug',
            default=False, action='store_const', const=True,
            help='Debug mode flag')
        _arg_parser.add_argument('--refresh', dest='refresh',
            default=True, action='store_const', const=True,
            help='Refresh mode flag to force updating of existing records')
        _arg_parser.add_argument('-t', '--tile_type', dest='default_tile_type_id',
            required=False, default=None,
            help='Tile type ID of tile to be stacked')
        _arg_parser.add_argument('-f', '--file', dest='filename',
            default='/g/data/v27/dem/dsm1sv1_0_Clean.img',
            help='Input DTM/DSM file to tile')
        _arg_parser.add_argument('-l', '--level', dest='level_name',
            default='DSM',
            help='Processing level of file')

        return _arg_parser.parse_args()

    def get_pixel_size(self, dataset, (x, y)):
        """
        Returns X & Y sizes in metres of specified pixel as a tuple.
        N.B: Pixel ordinates are zero-based from top left
        """
        logger.debug('(x, y) = (%f, %f)', x, y)

        spatial_reference = osr.SpatialReference()
        spatial_reference.ImportFromWkt(dataset.GetProjection())

        geotransform = dataset.GetGeoTransform()
        logger.debug('geotransform = %s', geotransform)

        latlong_spatial_reference = spatial_reference.CloneGeogCS()
        coord_transform_to_latlong = osr.CoordinateTransformation(spatial_reference, latlong_spatial_reference)

        # Determine pixel centre and edges in georeferenced coordinates
        xw = geotransform[0] + x * geotransform[1]
        yn = geotransform[3] + y * geotransform[5]
        xc = geotransform[0] + (x + 0.5) * geotransform[1]
        yc = geotransform[3] + (y + 0.5) * geotransform[5]
        xe = geotransform[0] + (x + 1.0) * geotransform[1]
        ys = geotransform[3] + (y + 1.0) * geotransform[5]

        logger.debug('xw = %f, yn = %f, xc = %f, yc = %f, xe = %f, ys = %f', xw, yn, xc, yc, xe, ys)

        # Convert georeferenced coordinates to lat/lon for Vincenty
        lon1, lat1, _z = coord_transform_to_latlong.TransformPoint(xw, yc, 0)
        lon2, lat2, _z = coord_transform_to_latlong.TransformPoint(xe, yc, 0)
        logger.debug('For X size: (lon1, lat1) = (%f, %f), (lon2, lat2) = (%f, %f)', lon1, lat1, lon2, lat2)
        x_size, _az_to, _az_from = vinc_dist(earth.F, earth.A,
                                             lat1 * RADIANS_PER_DEGREE, lon1 * RADIANS_PER_DEGREE,
                                             lat2 * RADIANS_PER_DEGREE, lon2 * RADIANS_PER_DEGREE)

        lon1, lat1, _z = coord_transform_to_latlong.TransformPoint(xc, yn, 0)
        lon2, lat2, _z = coord_transform_to_latlong.TransformPoint(xc, ys, 0)
        logger.debug('For Y size: (lon1, lat1) = (%f, %f), (lon2, lat2) = (%f, %f)', lon1, lat1, lon2, lat2)
        y_size, _az_to, _az_from = vinc_dist(earth.F, earth.A,
                                             lat1 * RADIANS_PER_DEGREE, lon1 * RADIANS_PER_DEGREE,
                                             lat2 * RADIANS_PER_DEGREE, lon2 * RADIANS_PER_DEGREE)

        logger.debug('(x_size, y_size) = (%f, %f)', x_size, y_size)
        return (x_size, y_size)

    def get_pixel_size_grids(self, dataset):
        """ Returns two grids with interpolated X and Y pixel sizes for given datasets"""

        def get_pixel_x_size(x, y):
            return self.get_pixel_size(dataset, (x, y))[0]

        def get_pixel_y_size(x, y):
            return self.get_pixel_size(dataset, (x, y))[1]

        x_size_grid = numpy.zeros((dataset.RasterXSize, dataset.RasterYSize)).astype(numpy.float32)
        interpolate_grid(depth=1, shape=x_size_grid.shape, eval_func=get_pixel_x_size, grid=x_size_grid)

        y_size_grid = numpy.zeros((dataset.RasterXSize, dataset.RasterYSize)).astype(numpy.float32)
        interpolate_grid(depth=1, shape=y_size_grid.shape, eval_func=get_pixel_y_size, grid=y_size_grid)

        return (x_size_grid, y_size_grid)

    def __init__(self, source_datacube=None, default_tile_type_id=1):
        """Constructor
        Arguments:
            source_datacube: Optional DataCube object whose connection and data will be shared
            tile_type_id: Optional tile_type_id value (defaults to config file value = 1)
        """

        if source_datacube:
            # Copy values from source_datacube and then override command line args
            self.__dict__ = copy(source_datacube.__dict__)

            args = self.parse_args()
            # Set instance attributes for every value in command line arguments file
            for attribute_name in args.__dict__.keys():
                attribute_value = args.__dict__[attribute_name]
                self.__setattr__(attribute_name, attribute_value)

        else:
            DataCube.__init__(self); # Call inherited constructor

        if self.debug:
            console_handler.setLevel(logging.DEBUG)

        # Turn autocommit OFF so that transaction can cover all queries for each dataset
        self.db_connection.autocommit = False
        self.db_connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)

        # Attempt to parse dates from command line arguments or config file
        try:
            self.default_tile_type_id = int(self.default_tile_type_id)
        except:
            self.default_tile_type_id = default_tile_type_id
        try:
            self.start_date = datetime.strptime(self.start_date, '%d/%m/%Y').date()
        except:
            self.start_date = None
        try:
            self.end_date = datetime.strptime(self.end_date, '%d/%m/%Y').date()
        except:
            self.end_date = None
        try:
            self.min_path = int(self.min_path)
        except:
            self.min_path = None
        try:
            self.max_path = int(self.max_path)
        except:
            self.max_path = None
        try:
            self.min_row = int(self.min_row)
        except:
            self.min_row = None
        try:
            self.max_row = int(self.max_row)
        except:
            self.max_row = None

    def create_tiles(self, filename=None, level_name=None, tile_type_id=None):
        # Set default values to instance values
        filename = filename or self.filename
        level_name = level_name or self.level_name
        tile_type_id = tile_type_id or self.default_tile_type_id
        nodata_value = None

        tile_type_info = self.tile_type_dict[tile_type_id]

        dem_band_info = self.bands[tile_type_id].get(('DERIVED', level_name))
        assert dem_band_info, 'No band level information defined for level %s' % level_name

        def find_tiles(x_index = None, y_index = None):
            """Find any tile records for current dataset
            returns dict of tile information keyed by tile_id
            """
            db_cursor2 = self.db_connection.cursor()

            sql = """-- Check for any existing tiles
select
tile_id,
x_index,
y_index,
tile_type_id,
tile_pathname,
dataset_id,
tile_class_id,
tile_size
from tile_footprint
inner join tile using(x_index, y_index, tile_type_id)
inner join dataset using(dataset_id)
inner join processing_level using(level_id)
where tile_type_id = %(tile_type_id)s
and (%(x_index)s is null or x_index = %(x_index)s)
and (%(y_index)s is null or y_index = %(y_index)s)
and level_name = %(level_name)s
and ctime is not null
;
"""
            params = {'x_index': x_index,
                  'y_index': y_index,
                  'tile_type_id': tile_type_info['tile_type_id'],
                  'level_name': level_name}

            log_multiline(logger.debug, db_cursor2.mogrify(sql, params), 'SQL', '\t')
            db_cursor2.execute(sql, params)
            tile_info = {}
            for record in db_cursor2:
                tile_info_dict = {
                    'x_index': record[1],
                    'y_index': record[2],
                    'tile_type_id': record[3],
                    'tile_pathname': record[4],
                    'dataset_id': record[5],
                    'tile_class_id': record[6],
                    'tile_size': record[7]
                    }
                tile_info[record[0]] = tile_info_dict # Keyed by tile_id

            log_multiline(logger.debug, tile_info, 'tile_info', '\t')
            return tile_info

        # Function create_tiles starts here
        db_cursor = self.db_connection.cursor()

        dataset = gdal.Open(filename)
        assert dataset, 'Unable to open dataset %s' % filename
        spatial_reference = osr.SpatialReference()
        spatial_reference.ImportFromWkt(dataset.GetProjection())
        geotransform = dataset.GetGeoTransform()
        logger.debug('geotransform = %s', geotransform)

        latlong_spatial_reference = spatial_reference.CloneGeogCS()
        coord_transform_to_latlong = osr.CoordinateTransformation(spatial_reference, latlong_spatial_reference)

        tile_spatial_reference = osr.SpatialReference()
        s = re.match('EPSG:(\d+)', tile_type_info['crs'])
        if s:
            epsg_code = int(s.group(1))
            logger.debug('epsg_code = %d', epsg_code)
            assert tile_spatial_reference.ImportFromEPSG(epsg_code) == 0, 'Invalid EPSG code for tile projection'
        else:
            assert tile_spatial_reference.ImportFromWkt(tile_type_info['crs']), 'Invalid WKT for tile projection'

        logger.debug('Tile WKT = %s', tile_spatial_reference.ExportToWkt())

        coord_transform_to_tile = osr.CoordinateTransformation(spatial_reference, tile_spatial_reference)

        # Need to keep tile and lat/long references separate even though they may be equivalent
        # Upper Left
        ul_x, ul_y = geotransform[0], geotransform[3]
        ul_lon, ul_lat, _z = coord_transform_to_latlong.TransformPoint(ul_x, ul_y, 0)
        tile_ul_x, tile_ul_y, _z = coord_transform_to_tile.TransformPoint(ul_x, ul_y, 0)
        # Upper Right
        ur_x, ur_y = geotransform[0] + geotransform[1] * dataset.RasterXSize, geotransform[3]
        ur_lon, ur_lat, _z = coord_transform_to_latlong.TransformPoint(ur_x, ur_y, 0)
        tile_ur_x, tile_ur_y, _z = coord_transform_to_tile.TransformPoint(ur_x, ur_y, 0)
        # Lower Right
        lr_x, lr_y = geotransform[0] + geotransform[1] * dataset.RasterXSize, geotransform[3] + geotransform[5] * dataset.RasterYSize
        lr_lon, lr_lat, _z = coord_transform_to_latlong.TransformPoint(lr_x, lr_y, 0)
        tile_lr_x, tile_lr_y, _z = coord_transform_to_tile.TransformPoint(lr_x, lr_y, 0)
        # Lower Left
        ll_x, ll_y = geotransform[0], geotransform[3] + geotransform[5] * dataset.RasterYSize
        ll_lon, ll_lat, _z = coord_transform_to_latlong.TransformPoint(ll_x, ll_y, 0)
        tile_ll_x, tile_ll_y, _z = coord_transform_to_tile.TransformPoint(ll_x, ll_y, 0)

        tile_min_x = min(tile_ul_x, tile_ll_x)
        tile_max_x = max(tile_ur_x, tile_lr_x)
        tile_min_y = min(tile_ll_y, tile_lr_y)
        tile_max_y = max(tile_ul_y, tile_ur_y)

        tile_index_range = (int(floor((tile_min_x - tile_type_info['x_origin']) / tile_type_info['x_size'])),
                    int(floor((tile_min_y - tile_type_info['y_origin']) / tile_type_info['y_size'])),
                    int(ceil((tile_max_x - tile_type_info['x_origin']) / tile_type_info['x_size'])),
                    int(ceil((tile_max_y - tile_type_info['y_origin']) / tile_type_info['y_size'])))

        sql = """-- Find dataset_id for given path
select dataset_id
from dataset
where dataset_path like '%%' || %(basename)s
"""
        params = {'basename': os.path.basename(filename)}
        log_multiline(logger.debug, db_cursor.mogrify(sql, params), 'SQL', '\t')
        db_cursor.execute(sql, params)
        result = db_cursor.fetchone()
        if result: # Record already exists
            dataset_id = result[0]
            if self.refresh:
                logger.info('Updating existing record for %s', filename)

                sql = """
update dataset
  set level_id = (select level_id from processing_level where upper(level_name) = upper(%(processing_level)s)),
  datetime_processed = %(datetime_processed)s,
  dataset_size = %(dataset_size)s,
  crs = %(crs)s,
  ll_x = %(ll_x)s,
  ll_y = %(ll_y)s,
  lr_x = %(lr_x)s,
  lr_y = %(lr_y)s,
  ul_x = %(ul_x)s,
  ul_y = %(ul_y)s,
  ur_x = %(ur_x)s,
  ur_y = %(ur_y)s,
  x_pixels = %(x_pixels)s,
  y_pixels = %(y_pixels)s
where dataset_id = %(dataset_id)s;

select %(dataset_id)s
"""
            else:
                logger.info('Skipping existing record for %s', filename)
                return
        else: # Record doesn't already exist
            logger.info('Creating new record for %s', filename)
            dataset_id = None

            sql = """-- Create new dataset record
insert into dataset(
  dataset_id,
  acquisition_id,
  dataset_path,
  level_id,
  datetime_processed,
  dataset_size,
  crs,
  ll_x,
  ll_y,
  lr_x,
  lr_y,
  ul_x,
  ul_y,
  ur_x,
  ur_y,
  x_pixels,
  y_pixels
  )
select
  nextval('dataset_id_seq') as dataset_id,
  null as acquisition_id,
  %(dataset_path)s,
  (select level_id from processing_level where upper(level_name) = upper(%(processing_level)s)),
  %(datetime_processed)s,
  %(dataset_size)s,
  %(crs)s,
  %(ll_x)s,
  %(ll_y)s,
  %(lr_x)s,
  %(lr_y)s,
  %(ul_x)s,
  %(ul_y)s,
  %(ur_x)s,
  %(ur_y)s,
  %(x_pixels)s,
  %(y_pixels)s
where not exists
  (select dataset_id
  from dataset
  where dataset_path = %(dataset_path)s
  );

select dataset_id
from dataset
where dataset_path = %(dataset_path)s
;
"""
        dataset_size = self.getFileSizekB(filename) # Need size in kB to match other datasets

        # same params for insert or update
        params = {'dataset_id': dataset_id,
            'dataset_path': filename,
            'processing_level': level_name,
            'datetime_processed': None,
            'dataset_size': dataset_size,
            'll_lon': ll_lon,
            'll_lat': ll_lat,
            'lr_lon': lr_lon,
            'lr_lat': lr_lat,
            'ul_lon': ul_lon,
            'ul_lat': ul_lat,
            'ur_lon': ur_lon,
            'ur_lat': ur_lat,
            'crs': dataset.GetProjection(),
            'll_x': ll_x,
            'll_y': ll_y,
            'lr_x': lr_x,
            'lr_y': lr_y,
            'ul_x': ul_x,
            'ul_y': ul_y,
            'ur_x': ur_x,
            'ur_y': ur_y,
            'x_pixels': dataset.RasterXSize,
            'y_pixels': dataset.RasterYSize,
            'gcp_count': None,
            'mtl_text': None,
            'cloud_cover': None
            }

        log_multiline(logger.debug, db_cursor.mogrify(sql, params), 'SQL', '\t')
        db_cursor.execute(sql, params)
        result = db_cursor.fetchone() # Retrieve new dataset_id if required
        dataset_id = dataset_id or result[0]

        tile_output_root = os.path.join(self.tile_root,
                                        tile_type_info['tile_directory'],
                                        level_name,
                                        os.path.basename(filename)
                                        )
        logger.debug('tile_output_root = %s', tile_output_root)
        self.create_directory(tile_output_root)

        work_directory = os.path.join(self.temp_dir,
                                      os.path.basename(filename)
                                      )
        logger.debug('work_directory = %s', work_directory)
        self.create_directory(work_directory)

        for x_index in range(tile_index_range[0], tile_index_range[2]):
            for y_index in range(tile_index_range[1], tile_index_range[3]):

                tile_info = find_tiles(x_index, y_index)

                if tile_info:
                    logger.info('Skipping existing tile (%d, %d)', x_index, y_index)
                    continue

                tile_basename = '_'.join([level_name,
                                          re.sub('\+', '', '%+04d_%+04d' % (x_index, y_index))]) + tile_type_info['file_extension']

                tile_output_path = os.path.join(tile_output_root, tile_basename)

                # Check whether this tile has already been processed
                if not self.lock_object(tile_output_path):
                    logger.warning('Tile  %s already being processed - skipping.', tile_output_path)
                    continue

                try:
                    self.remove(tile_output_path)

                    temp_tile_path = os.path.join(self.temp_dir, tile_basename)

                    tile_extents = (tile_type_info['x_origin'] + x_index * tile_type_info['x_size'],
                                tile_type_info['y_origin'] + y_index * tile_type_info['y_size'],
                                tile_type_info['x_origin'] + (x_index + 1) * tile_type_info['x_size'],
                                tile_type_info['y_origin'] + (y_index + 1) * tile_type_info['y_size'])
                    logger.debug('tile_extents = %s', tile_extents)

                    command_string = 'gdalwarp'
                    if not self.debug:
                        command_string += ' -q'
                    command_string += ' -t_srs %s -te %f %f %f %f -tr %f %f -tap -tap -r %s' % (
                        tile_type_info['crs'],
                        tile_extents[0], tile_extents[1], tile_extents[2], tile_extents[3],
                        tile_type_info['x_pixel_size'], tile_type_info['y_pixel_size'],
                        dem_band_info[10]['resampling_method']
                        )

                    if nodata_value is not None:
                        command_string += ' -srcnodata %d -dstnodata %d' % (nodata_value, nodata_value)

                    command_string += ' -of %s' % tile_type_info['file_format']

                    if tile_type_info['format_options']:
                        for format_option in tile_type_info['format_options'].split(','):
                            command_string += ' -co %s' % format_option

                    command_string += ' -overwrite %s %s' % (
                        filename,
                        temp_tile_path
                        )

                    logger.debug('command_string = %s', command_string)

                    result = execute(command_string=command_string)

                    if result['stdout']:
                        log_multiline(logger.info, result['stdout'], 'stdout from ' + command_string, '\t')

                    if result['returncode']:
                        log_multiline(logger.error, result['stderr'], 'stderr from ' + command_string, '\t')
                        raise Exception('%s failed', command_string)

                    temp_dataset = gdal.Open(temp_tile_path)

                    gdal_driver = gdal.GetDriverByName(tile_type_info['file_format'])
                    #output_dataset = gdal_driver.Create(output_tile_path,
                    #                                    nbar_dataset.RasterXSize, nbar_dataset.RasterYSize,
                    #                                    1, nbar_dataset.GetRasterBand(1).DataType,
                    #                                    tile_type_info['format_options'].split(','))
                    output_dataset = gdal_driver.Create(tile_output_path,
                                                        temp_dataset.RasterXSize, temp_dataset.RasterYSize,
                                                        len(dem_band_info),
                                                        temp_dataset.GetRasterBand(1).DataType,
                                                        tile_type_info['format_options'].split(','))
                    assert output_dataset, 'Unable to open output dataset %s'% output_dataset
                    output_geotransform = temp_dataset.GetGeoTransform()
                    output_dataset.SetGeoTransform(output_geotransform)
                    output_dataset.SetProjection(temp_dataset.GetProjection())

                    elevation_array = temp_dataset.GetRasterBand(1).ReadAsArray()
                    del temp_dataset
                    self.remove(temp_tile_path)

                    pixel_x_size = abs(output_geotransform[1])
                    pixel_y_size = abs(output_geotransform[5])
                    x_m_array, y_m_array = self.get_pixel_size_grids(output_dataset)

                    dzdx_array = ndimage.sobel(elevation_array, axis=1)/(8. * abs(output_geotransform[1]))
                    dzdx_array = numexpr.evaluate("dzdx_array * pixel_x_size / x_m_array")
                    del x_m_array

                    dzdy_array = ndimage.sobel(elevation_array, axis=0)/(8. * abs(output_geotransform[5]))
                    dzdy_array = numexpr.evaluate("dzdy_array * pixel_y_size / y_m_array")
                    del y_m_array

                    for band_file_number in sorted(dem_band_info.keys()):
                        output_band_number = dem_band_info[band_file_number]['tile_layer']
                        output_band = output_dataset.GetRasterBand(output_band_number)

                        if band_file_number == 10: # Elevation
                            output_band.WriteArray(elevation_array)
                            del elevation_array

                        elif band_file_number == 20: # Slope
                            hypotenuse_array = numpy.hypot(dzdx_array, dzdy_array)
                            slope_array = numexpr.evaluate("arctan(hypotenuse_array) / RADIANS_PER_DEGREE")
                            del hypotenuse_array
                            output_band.WriteArray(slope_array)
                            del slope_array

                        elif band_file_number == 30: # Aspect
                            # Convert angles from conventional radians to compass heading 0-360
                            aspect_array = numexpr.evaluate("(450 - arctan2(dzdy_array, -dzdx_array) / RADIANS_PER_DEGREE) % 360")
                            output_band.WriteArray(aspect_array)
                            del aspect_array

                        if nodata_value is not None:
                            output_band.SetNoDataValue(nodata_value)
                        output_band.FlushCache()

                    #===========================================================
                    # # This is not strictly necessary - copy metadata to output dataset
                    # output_dataset_metadata = temp_dataset.GetMetadata()
                    # if output_dataset_metadata:
                    #    output_dataset.SetMetadata(output_dataset_metadata)
                    #    log_multiline(logger.debug, output_dataset_metadata, 'output_dataset_metadata', '\t')
                    #===========================================================

                    output_dataset.FlushCache()
                    del output_dataset
                    logger.info('Finished writing dataset %s', tile_output_path)

                    tile_size = self.getFileSizeMB(tile_output_path)

                    sql = """-- Insert new tile_footprint record if necessary
    insert into tile_footprint (
      x_index,
      y_index,
      tile_type_id,
      x_min,
      y_min,
      x_max,
      y_max
      )
    select
      %(x_index)s,
      %(y_index)s,
      %(tile_type_id)s,
      %(x_min)s,
      %(y_min)s,
      %(x_max)s,
      %(y_max)s
    where not exists
      (select
        x_index,
        y_index,
        tile_type_id
      from tile_footprint
      where x_index = %(x_index)s
        and y_index = %(y_index)s
        and tile_type_id = %(tile_type_id)s);

    -- Update any existing tile record
    update tile
    set
      tile_pathname = %(tile_pathname)s,
      tile_class_id = %(tile_class_id)s,
      tile_size = %(tile_size)s,
      ctime = now()
    where
      x_index = %(x_index)s
      and y_index = %(y_index)s
      and tile_type_id = %(tile_type_id)s
      and dataset_id = %(dataset_id)s;

    -- Insert new tile record if necessary
    insert into tile (
      tile_id,
      x_index,
      y_index,
      tile_type_id,
      dataset_id,
      tile_pathname,
      tile_class_id,
      tile_size,
      ctime
      )
    select
      nextval('tile_id_seq'::regclass),
      %(x_index)s,
      %(y_index)s,
      %(tile_type_id)s,
      %(dataset_id)s,
      %(tile_pathname)s,
      %(tile_class_id)s,
      %(tile_size)s,
      now()
    where not exists
      (select tile_id
      from tile
      where
        x_index = %(x_index)s
        and y_index = %(y_index)s
        and tile_type_id = %(tile_type_id)s
        and dataset_id = %(dataset_id)s
      );
    """
                    params = {'x_index': x_index,
                              'y_index': y_index,
                              'tile_type_id': tile_type_info['tile_type_id'],
                              'x_min': tile_extents[0],
                              'y_min': tile_extents[1],
                              'x_max': tile_extents[2],
                              'y_max': tile_extents[3],
                              'dataset_id': dataset_id,
                              'tile_pathname': tile_output_path,
                              'tile_class_id': 1,
                              'tile_size': tile_size
                              }

                    log_multiline(logger.debug, db_cursor.mogrify(sql, params), 'SQL', '\t')
                    db_cursor.execute(sql, params)

                    self.db_connection.commit()
                finally:
                    self.unlock_object(tile_output_path)

        logger.info('Finished creating all tiles')

if __name__ == '__main__':
    dem_tiler = DEMTiler()

    dem_tiler.create_tiles()


text:
/** @jsxRuntime classic */
/** @jsx jsx */

import { ReactNode, useContext } from 'react';
import { forwardRefWithAs, jsx } from '@keystone-ui/core';
import { LoadingDots } from '@keystone-ui/loading';

import { ButtonContext } from './context';
import type { WeightKey, ToneKey, SizeKey } from './hooks/button';

type ButtonProps = {
  /** The Button label content. */
  children: ReactNode;
  /** Whether the Button should display as a block */
  isBlock?: boolean;
  /** Whether the Button should be disabled */
  isDisabled?: boolean;
  /** Whether the Button should be in a loading state */
  isLoading?: boolean;
  /** The size of the Button. */
  size?: SizeKey;
  /** The tone of the Button. */
  tone?: ToneKey;
  /** The weight of the Button. */
  weight?: WeightKey;
};

const loadingContainerStyles = {
  left: '50%',
  position: 'absolute',
  transform: 'translateX(-50%)',
} as const;

export const Button = forwardRefWithAs<'button', ButtonProps>(
  (
    { as: Tag = 'button', children, isDisabled, isLoading, size, tone, weight, ...otherProps },
    ref
  ) => {
    const { useButtonStyles, useButtonTokens, defaults } = useContext(ButtonContext);
    const tokens = useButtonTokens({
      size: size || defaults.size,
      tone: tone || defaults.tone,
      weight: weight || defaults.weight,
    });
    const styles = useButtonStyles({
      isDisabled,
      tokens,
    });

    return (
      <Tag type={Tag === 'button' ? 'button' : undefined} css={styles} ref={ref} {...otherProps}>
        {children}
        {isLoading && (

            <LoadingDots size={size || defaults.size} label="Button loading indicator" />

        )}
      </Tag>
    );
  }
);


text:
from qsrrep_hmms.qtc_hmm_abstractclass import QTCHMMAbstractclass
from qsrrep_hmms.qtcb_hmm import QTCBHMM
from qsrrep_hmms.qtcc_hmm import QTCCHMM
import numpy as np

class QTCBCHMM(QTCHMMAbstractclass):

    def __init__(self):
        super(QTCBCHMM, self).__init__()
        self.num_possible_states = 92 # Setting number of possible states: QTCBC + start and end
        self.qtcb = QTCBHMM()
        self.qtcc = QTCCHMM()

    def _create_transition_matrix(self, size, **kwargs):
        """Creates a Conditional Neighbourhood Diagram for QTCBC as a basis for the HMM.

        :param kwargs:
            * qtc: list of lists containing all possible qtc states. Different for all 3 qtc versions.

        :return: The transition matrix only allowing transitions according to the CND
        """

        qtc = []
        # creating list of possible states
        for i in xrange(1, 4):
            for j in xrange(1, 4):
                qtc.append([i-2, j-2, np.NaN, np.NaN])
        for i in xrange(1, 4):
            for j in xrange(1, 4):
                for k in xrange(1, 4):
                    for l in xrange(1, 4):
                        qtc.append([i-2, j-2, k-2, l-2])

        # Calling parent to generate actual matrix
        return super(QTCBCHMM, self)._create_transition_matrix(size=size, qtc=qtc)

    def _symbol_to_qsr(self, symbols):
        """Transforming alphabet symbols to QTCBC states.

        :param symbols: A list of symbols

        :return: The list of corresponding qtc symbols
        """

        ret = []
        for s in symbols:
            qtc = []
            for c in s[1:-1]:
                if c <= 9: # QTCB
                    qtc.append(self.qtcb.symbol_to_qsr(c))
                else:
                    qtc.append(self.qtcc.symbol_to_qsr(c-9))

            ret.append(self._qtc_num_to_str(qtc))

        return ret

    def _qsr_to_symbol(self, qsr_data):
        """Transforms a qtc state chain to a list of numbers

        :param qsr_data: The list of lists of qtc strings or numpy array states
            E.g.: [['++++','+++0','+++-,]] or [[[1,1,1,1],[1,1,1,0],[1,1,1,-1]]]

        :return: A lists of lists of alphabet symbols corresponding to the given state chains
        """
        qsr_data = np.array(qsr_data)
        state_rep = []
        for idx, element in enumerate(qsr_data):
            if all(isinstance(x, str) or isinstance(x, unicode) for x in element):
                element = self._qtc_str_to_num(element) # check if content is string instead of numbers and convert
            element = np.array(element)
            try:
                d = element.shape[1]
            except IndexError: # Not a list of lists of lists
                return self._qsr_to_symbol([qsr_data])
            state_num = np.array([0]) # Start symbol
            #Not ellegant at all but necessary due to the nan values and the different multipliers for qtcb and qtcc
            for x in element:
                x = x[~np.isnan(x)]
                d = x.shape[0]
                mult = 3**np.arange(d-1, -1, -1)
                num = ((x + 1)*mult).sum() + 1
                state_num = np.append(
                    state_num,
                    num if d == 2 else num + 9 # Adding a 9 when the state is qtcc
                )
            state_num = np.append(state_num, self.num_possible_states-1) # End symbol
            state_char = ''
            for n in state_num:
                state_char += chr(int(n)+32)
            state_rep.append(state_num.tolist())

        return state_rep


text:
package com.netflix.zuul.scriptManager;

import java.util.List;

/**
 * Interface for data access to persist filters in a persistent store
 * @author Mikey Cohen
 * Date: 6/12/12
 * Time: 1:45 PM
 */
public interface ZuulFilterDAO {
    /**
     *
     * @return a list of all filterIds
     */
    List<String> getAllFilterIDs();

    /**
     * returns all filter revisions for the given filter_id
     * @param filter_id
     * @return returns all filter revisions for the given filter_id
     */
    List<FilterInfo> getZuulFiltersForFilterId(String filter_id);

    /**
     *
     * @param filter_id
     * @param revision
     * @return returns a specific revision for a filter
     */
    FilterInfo getFilterInfo(String filter_id, int revision);

    /**
     *
     * @param filter_id
     * @param revision
     * @return returns a specific revision for a filter
     */
    FilterInfo getFilterInfoForFilter(String filter_id, int revision);

    /**
     *
     * @param filter_id
     * @return returns the latest version of a given filter
     */
    FilterInfo getLatestFilterInfoForFilter(String filter_id);

    /**
     * returns the active filter for a given filter_id
     * @param filter_id
     * @return
     */
    FilterInfo getActiveFilterInfoForFilter(String filter_id);

    /**
     *
     * @return all filters active in the "canary" mode
     */
    List<FilterInfo> getAllCanaryFilters();

    /**
     *
     * @return all active filters
     */
    List<FilterInfo> getAllActiveFilters();

    /**
     * sets a filter and revison as active in a "canary"
     * @param filter_id
     * @param revision
     * @return the filter
     */
    FilterInfo setCanaryFilter(String filter_id, int revision);

    /**
     * sets a filter and revision as active
     * @param filter_id
     * @param revision
     * @return the filter
     * @throws Exception
     */
    FilterInfo setFilterActive(String filter_id, int revision) throws Exception;

    /**
     * Deactiviates a filter; removes it from being active.
     * @param filter_id
     * @param revision
     * @return the filter
     * @throws Exception
     */
    FilterInfo deActivateFilter(String filter_id, int revision) throws Exception;

    /**
     * adds a new filter to the persistent store
     * @param filtercode
     * @param filter_type
     * @param filter_name
     * @param disableFilterPropertyName
     * @param filter_order
     * @return the filter
     */
    FilterInfo addFilter(String filtercode, String filter_type, String filter_name, String disableFilterPropertyName, String filter_order);

    /**
     *
     * @param index
     * @return all filter_ids for a given index as a | delimited list
     */
    String getFilterIdsRaw(String index);

    /**
     *
     * @param index
     * @return returns filter_ids for a given index as a parsed list
     */
    List<String> getFilterIdsIndex(String index);

    }


text:
class Solution(object):
    # def lowestCommonAncestor(self, root, p, q):
    #     """
    #     :type root: TreeNode
    #     :type p: TreeNode
    #     :type q: TreeNode
    #     :rtype: TreeNode
    #     """
    #     self.ans = None

    #     def lowestCommonAncestorHelper(node):
    #         if not node:
    #             return False
    #         left = lowestCommonAncestorHelper(node.left)
    #         right = lowestCommonAncestorHelper(node.right)
    #         mid = node == p or node == q
    #         if mid + left + right >= 2:
    #             self.ans = node
    #         return mid or left or right
    #     lowestCommonAncestorHelper(root)
    #     return self.ans

    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        # Stack for tree traversal
        stack = [root]
        # Dictionary for parent pointers
        parent = {root: None}
        # Iterate until we find both the nodes p and q
        while p not in parent or q not in parent:

            node = stack.pop()

            # While traversing the tree, keep saving the parent pointers.
            if node.left:
                parent[node.left] = node
                stack.append(node.left)
            if node.right:
                parent[node.right] = node
                stack.append(node.right)

        # Ancestors set() for node p.
        ancestors = set()

        # Process all ancestors for node p using parent pointers.
        while p:
            ancestors.add(p)
            p = parent[p]

        # The first ancestor of q which appears in
        # p's ancestor set() is their lowest common ancestor.
        while q not in ancestors:
            q = parent[q]
        return q


text:
id: 5f5b969a05380d2179fe6e18
title: Impara Bash e SQL costruendo uno shop di noleggio biciclette
challengeType: 12
helpCategory: Relational Databases
url: https://github.com/freeCodeCamp/learn-bash-and-sql-by-building-a-bike-rental-shop
dashedName: learn-bash-and-sql-by-building-a-bike-rental-shop
---

# --instructions--

# --hints--

# --seed--

# --solutions--


text:
using System;

using IBatisNet.DataMapper.TypeHandlers;

namespace IBatisNet.DataMapper.Test.Domain
{
	/// <summary>
	/// Description résumée de CustomInheritance.
	/// </summary>
	public class CustomInheritance : ITypeHandlerCallback
	{

		#region ITypeHandlerCallback members

		public object ValueOf(string nullValue)
		{
			throw new NotImplementedException();
		}

		public object GetResult(IResultGetter getter)
		{
			string type = getter.Value.ToString();

			if (type=="Monograph" || type=="Book")
			{
				return "Book";
			}
			else if (type=="Tabloid" || type=="Broadsheet" || type=="Newspaper")
			{

				return "Newspaper";
			}
			else
			{
				return "Document";
			}

		}

		public void SetParameter(IParameterSetter setter, object parameter)
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}


text:
local readmeURL = "https://github.com/openwrt/packages/tree/master/net/vpn-policy-routing/files/README.md"

local packageName = "vpn-policy-routing"
local uci = require "luci.model.uci".cursor()
local sys = require "luci.sys"
local util = require "luci.util"
local ip = require "luci.ip"
local fs = require "nixio.fs"
local jsonc = require "luci.jsonc"
local http = require "luci.http"
local nutil = require "nixio.util"
local dispatcher = require "luci.dispatcher"
local enabledFlag = uci:get(packageName, "config", "enabled")
local enc

local ubusStatus = util.ubus("service", "list", { name = packageName })
if ubusStatus and ubusStatus[packageName] and
	 ubusStatus[packageName]["instances"] and
	 ubusStatus[packageName]["instances"]["main"] and
	 ubusStatus[packageName]["instances"]["main"]["data"] and
	 ubusStatus[packageName]["instances"]["main"]["data"]["status"] and
	 ubusStatus[packageName]["instances"]["main"]["data"]["status"][1] then
	serviceGateways = ubusStatus[packageName]["instances"]["main"]["data"]["status"][1]["gateway"]
	serviceGateways = serviceGateways and serviceGateways:gsub('\\n', '\n')
	serviceGateways = serviceGateways and serviceGateways:gsub('\\033%[0;32m%[\\xe2\\x9c\\x93%]\\033%[0m', '✓')
	serviceErrors = ubusStatus[packageName]["instances"]["main"]["data"]["status"][1]["error"]
	serviceErrors = serviceErrors and serviceErrors:gsub('\\n', '\n')
	serviceErrors = serviceErrors and serviceErrors:gsub('\\033%[0;31mERROR\\033%[0m: ', '')
	serviceWarnings = ubusStatus[packageName]["instances"]["main"]["data"]["status"][1]["warning"]
	serviceWarnings = serviceWarnings and serviceWarnings:gsub('\\n', '\n')
	serviceWarnings = serviceWarnings and serviceWarnings:gsub('\\033%[0;33mWARNING\\033%[0m: ', '')
	serviceMode = ubusStatus[packageName]["instances"]["main"]["data"]["status"][1]["mode"]
end

local serviceRunning, statusText = false, nil
local packageVersion = tostring(util.trim(sys.exec("opkg list-installed " .. packageName .. " | awk '{print $3}'"))) or ""
if packageVersion == "" then
	statusText = translatef("%s is not installed or not found", packageName)
end
if sys.call("iptables -t mangle -L | grep -q VPR_PREROUTING") == 0 then
	serviceRunning = true
	statusText = translate("Running")
	if serviceMode and serviceMode == "strict" then
		statusText = translatef("%s (strict mode)", statusText)
	end
else
	statusText = translate("Stopped")
	if uci:get(packageName, "config", "enabled") ~= "1" then
		statusText = translatef("%s (disabled)", statusText)
	end
end

local t = uci:get("vpn-policy-routing", "config", "supported_interface")
if not t then
	supportedIfaces = ""
elseif type(t) == "table" then
	for key,value in pairs(t) do supportedIfaces = supportedIfaces and supportedIfaces .. ' ' .. value or value end
elseif type(t) == "string" then
	supportedIfaces = t
end

t = uci:get("vpn-policy-routing", "config", "ignored_interface")
if not t then
	ignoredIfaces = ""
elseif type(t) == "table" then
	for key,value in pairs(t) do ignoredIfaces = ignoredIfaces and ignoredIfaces .. ' ' .. value or value end
elseif type(t) == "string" then
	ignoredIfaces = t
end

local lanIPAddr = uci:get("network", "lan", "ipaddr")
local lanNetmask = uci:get("network", "lan", "netmask")
-- if multiple ip addresses on lan interface, will be returned as table of CIDR notations i.e. {"10.0.0.1/24","10.0.0.2/24"}
if (type(lanIPAddr) == "table") then
				first = true
				for i,line in ipairs(lanIPAddr) do
								lanIPAddr = lanIPAddr[i]
								break
				end
				lanIPAddr = lanIPAddr:match("[0-9.]+")
end
if lanIPAddr and lanNetmask then
	laPlaceholder = ip.new(lanIPAddr .. "/" .. lanNetmask )
end

function is_wan(name)
	return name:sub(1,3) == "wan" or name:sub(-3) == "wan"
end

function is_supported_interface(arg)
	local name=arg['.name']
	local proto=arg['proto']
	local ifname=arg['ifname']

	if name and is_wan(name) then return true end
	if name and supportedIfaces:match('%f[%w]' .. name .. '%f[%W]') then return true end
	if name and not ignoredIfaces:match('%f[%w]' .. name .. '%f[%W]') then
		if type(ifname) == "table" then
			for key,value in pairs(ifname) do
				if value and value:sub(1,3) == "tun" then return true end
				if value and value:sub(1,3) == "tap" then return true end
				if value and value:sub(1,3) == "tor" then return true end
				if value and fs.access("/sys/devices/virtual/net/" .. value .. "/tun_flags") then return true end
			end
		elseif type(ifname) == "string" then
			if ifname and ifname:sub(1,3) == "tun" then return true end
			if ifname and ifname:sub(1,3) == "tap" then return true end
			if ifname and ifname:sub(1,3) == "tor" then return true end
			if ifname and fs.access("/sys/devices/virtual/net/" .. ifname .. "/tun_flags") then return true end
		end
		if proto and proto:sub(1,11) == "openconnect" then return true end
		if proto and proto:sub(1,4) == "pptp" then return true end
		if proto and proto:sub(1,4) == "l2tp" then return true end
		if proto and proto:sub(1,9) == "wireguard" then return true end
	end
end

m = Map("vpn-policy-routing", translate("VPN and WAN Policy-Based Routing"))

h = m:section(NamedSection, "config", packageName, translatef("Service Status [%s %s]", packageName, packageVersion))
status = h:option(DummyValue, "_dummy", translate("Service Status"))
status.template = "vpn-policy-routing/status"
status.value = statusText
if serviceRunning and serviceGateways and serviceGateways ~= "" then
	gateways = h:option(DummyValue, "_dummy", translate("Service Gateways"))
	gateways.template = packageName .. "/status-gateways"
	gateways.value = serviceGateways
end
if serviceErrors and serviceErrors ~= "" then
	errors = h:option(DummyValue, "_dummy", translate("Service Errors"))
	errors.template = packageName .. "/status-textarea"
	errors.value = serviceErrors
end
if serviceWarnings and serviceWarnings ~= "" then
	warnings = h:option(DummyValue, "_dummy", translate("Service Warnings"))
	warnings.template = packageName .. "/status-textarea"
	warnings.value = serviceWarnings
end
if packageVersion ~= "" then
	buttons = h:option(DummyValue, "_dummy")
	buttons.template = packageName .. "/buttons"
end

-- General Options
config = m:section(NamedSection, "config", "vpn-policy-routing", translate("Configuration"))
config.override_values = true
config.override_depends = true

-- Basic Options
config:tab("basic", translate("Basic Configuration"))

verb = config:taboption("basic", ListValue, "verbosity", translate("Output verbosity"), translate("Controls both system log and console output verbosity."))
verb:value("0", translate("Suppress/No output"))
verb:value("1", translate("Condensed output"))
verb:value("2", translate("Verbose output"))
verb.default = 2

se = config:taboption("basic", ListValue, "strict_enforcement", translate("Strict enforcement"),
	translatef("See the %sREADME%s for details.", "", ""))
se:value("0", translate("Do not enforce policies when their gateway is down"))
se:value("1", translate("Strictly enforce policies when their gateway is down"))
se.default = 1

dest_ipset = config:taboption("basic", ListValue, "dest_ipset", translate("The ipset option for remote policies"),
	translatef("Please check the %sREADME%s before changing this option.", "", ""))
dest_ipset:value("", translate("Disabled"))
dest_ipset:value("ipset", translate("Use ipset command"))
dest_ipset:value("dnsmasq.ipset", translate("Use DNSMASQ ipset"))
dest_ipset.default = ""
dest_ipset.rmempty = true

src_ipset = config:taboption("basic", ListValue, "src_ipset", translate("The ipset option for local policies"),
	translatef("Please check the %sREADME%s before changing this option.", "", ""))
src_ipset:value("0", translate("Disabled"))
src_ipset:value("1", translate("Use ipset command"))

ipv6 = config:taboption("basic", ListValue, "ipv6_enabled", translate("IPv6 Support"))
ipv6:value("0", translate("Disabled"))
ipv6:value("1", translate("Enabled"))

-- Advanced Options
config:tab("advanced", translate("Advanced Configuration"),
	translatef("%sWARNING:%s Please make sure to check the %sREADME%s before changing anything in this section! Change any of the settings below with extreme caution!%s" , "
    ", "", "", "", "

"))

supportedIface = config:taboption("advanced", DynamicList, "supported_interface", translate("Supported Interfaces"), translate("Allows to specify the list of interface names (in lower case) to be explicitly supported by the service. Can be useful if your OpenVPN tunnels have dev option other than tun* or tap*."))
supportedIface.optional = false

ignoredIface = config:taboption("advanced", DynamicList, "ignored_interface", translate("Ignored Interfaces"), translate("Allows to specify the list of interface names (in lower case) to be ignored by the service. Can be useful if running both VPN server and VPN client on the router."))
ignoredIface.optional = false

timeout = config:taboption("advanced", Value, "boot_timeout", translate("Boot Time-out"), translate("Time (in seconds) for service to wait for WAN gateway discovery on boot."))
timeout.optional = false
timeout.rmempty = true

insert = config:taboption("advanced", ListValue, "iptables_rule_option", translate("IPTables rule option"), translate("Select Append for -A and Insert for -I."))
insert:value("append", translate("Append"))
insert:value("insert", translate("Insert"))
insert.default = "append"

iprule = config:taboption("advanced", ListValue, "iprule_enabled", translate("IP Rules Support"), translate("Add an ip rule, not an iptables entry for policies with just the local address. Use with caution to manipulte policies priorities."))
iprule:value("0", translate("Disabled"))
iprule:value("1", translate("Enabled"))

icmp = config:taboption("advanced", ListValue, "icmp_interface", translate("Default ICMP Interface"), translate("Force the ICMP protocol interface."))
icmp:value("", translate("No Change"))
icmp:value("wan", translate("WAN"))
uci:foreach("network", "interface", function(s)
	local name=s['.name']
	if is_supported_interface(s) then icmp:value(name, name:upper()) end
end)
icmp.rmempty = true

append_local = config:taboption("advanced", Value, "append_src_rules", translate("Append local IP Tables rules"), translate("Special instructions to append iptables rules for local IPs/netmasks/devices."))
append_local.rmempty = true

append_remote = config:taboption("advanced", Value, "append_dest_rules", translate("Append remote IP Tables rules"), translate("Special instructions to append iptables rules for remote IPs/netmasks."))
append_remote.rmempty = true

wantid = config:taboption("advanced", Value, "wan_tid", translate("WAN Table ID"), translate("Starting (WAN) Table ID number for tables created by the service."))
wantid.rmempty = true
wantid.placeholder = "201"
wantid.datatype    = 'and(uinteger, min(201))'

wanmark = config:taboption("advanced", Value, "wan_mark", translate("WAN Table FW Mark"), translate("Starting (WAN) FW Mark for marks used by the service. High starting mark is used to avoid conflict with SQM/QoS. Change with caution together with") .. " " .. translate("Service FW Mask") .. ".")
wanmark.rmempty = true
wanmark.placeholder = "0x010000"
wanmark.datatype    = "hex(8)"

fwmask = config:taboption("advanced", Value, "fw_mask", translate("Service FW Mask"), translate("FW Mask used by the service. High mask is used to avoid conflict with SQM/QoS. Change with caution together with") .. " " .. translate("WAN Table FW Mark") .. ".")
fwmask.rmempty = true
fwmask.placeholder = "0xff0000"
fwmask.datatype    = "hex(8)"

config:tab("webui", translate("Web UI Configuration"))

webui_enable_column = config:taboption("webui", ListValue, "webui_enable_column", translate("Show Enable Column"), translate("Shows the enable checkbox column for policies, allowing you to quickly enable/disable specific policy without deleting it."))
webui_enable_column:value("0", translate("Disabled"))
webui_enable_column:value("1", translate("Enabled"))

webui_protocol_column = config:taboption("webui", ListValue, "webui_protocol_column", translate("Show Protocol Column"), translate("Shows the protocol column for policies, allowing you to assign a specific protocol to a policy."))
webui_protocol_column:value("0", translate("Disabled"))
webui_protocol_column:value("1", translate("Enabled"))

webui_supported_protocol = config:taboption("webui", DynamicList, "webui_supported_protocol", translate("Supported Protocols"), translate("Display these protocols in protocol column in Web UI."))
webui_supported_protocol.optional = false

webui_chain_column = config:taboption("webui", ListValue, "webui_chain_column", translate("Show Chain Column"), translate("Shows the chain column for policies, allowing you to assign a PREROUTING, FORWARD, INPUT or OUTPUT chain to a policy."))
webui_chain_column:value("0", translate("Disabled"))
webui_chain_column:value("1", translate("Enabled"))

webui_sorting = config:taboption("webui", ListValue, "webui_sorting", translate("Show Up/Down Buttons"), translate("Shows the Up/Down buttons for policies, allowing you to move a policy up or down in the list."))
webui_sorting:value("0", translate("Disabled"))
webui_sorting:value("1", translate("Enabled"))
webui_sorting.default = "1"

-- Policies
p = m:section(TypedSection, "policy", translate("Policies"), translate("Comment, interface and at least one other field are required. Multiple local and remote addresses/devices/domains and ports can be space separated. Placeholders below represent just the format/syntax and will not be used if fields are left blank."))
p.template = "cbi/tblsection"
enc = tonumber(uci:get("vpn-policy-routing", "config", "webui_sorting"))
if not enc or enc ~= 0 then
	p.sortable  = true
end
p.anonymous = true
p.addremove = true

enc = tonumber(uci:get("vpn-policy-routing", "config", "webui_enable_column"))
if enc and enc ~= 0 then
	le = p:option(Flag, "enabled", translate("Enabled"))
	le.default = "1"
end

local comment = uci:get_first("vpn-policy-routing", "policy", "comment")
if comment then
	p:option(Value, "comment", translate("Comment"))
else
	p:option(Value, "name", translate("Name"))
end

la = p:option(Value, "src_addr", translate("Local addresses / devices"))
if laPlaceholder then
	la.placeholder = laPlaceholder
end
la.rmempty = true
la.datatype    = 'list(neg(or(host,network,macaddr,string)))'

lp = p:option(Value, "src_port", translate("Local ports"))
lp.datatype    = 'list(neg(or(portrange, string)))'
lp.placeholder = "0-65535"
lp.rmempty = true

ra = p:option(Value, "dest_addr", translate("Remote addresses / domains"))
ra.datatype    = 'list(neg(host))'
ra.placeholder = "0.0.0.0/0"
ra.rmempty = true

rp = p:option(Value, "dest_port", translate("Remote ports"))
rp.datatype    = 'list(neg(or(portrange, string)))'
rp.placeholder = "0-65535"
rp.rmempty = true

enc = tonumber(uci:get("vpn-policy-routing", "config", "webui_protocol_column"))
if enc and enc ~= 0 then
	proto = p:option(ListValue, "proto", translate("Protocol"))
	proto:value("", "AUTO")
	proto.default = ""
	proto.rmempty = true
	enc = uci:get_list("vpn-policy-routing", "config", "webui_supported_protocol")
	local count = 0
	for key, value in pairs(enc) do
		count = count + 1
		proto:value(value:lower(), value:gsub(" ", "/"):upper())
	end
	if count == 0 then
		enc = { "tcp", "udp", "tcp udp", "icmp", "all" }
		for key,value in pairs(enc) do
			proto:value(value:lower(), value:gsub(" ", "/"):upper())
		end
	end
end

enc = tonumber(uci:get("vpn-policy-routing", "config", "webui_chain_column"))
if enc and enc ~= 0 then
	chain = p:option(ListValue, "chain", translate("Chain"))
	chain:value("", "PREROUTING")
	chain:value("FORWARD", "FORWARD")
	chain:value("INPUT", "INPUT")
	chain:value("OUTPUT", "OUTPUT")
	chain.default = ""
	chain.rmempty = true
end

gw = p:option(ListValue, "interface", translate("Interface"))
gw.datatype = "network"
gw.rmempty = false
uci:foreach("network", "interface", function(s)
	local name=s['.name']
	if is_wan(name) then
		gw:value(name, name:upper())
		if not gw.default then gw.default = name end
	elseif is_supported_interface(s) then
		gw:value(name, name:upper())
	end
end)

dscp = m:section(NamedSection, "config", "vpn-policy-routing", translate("DSCP Tagging"),
	translatef("Set DSCP tags (in range between 1 and 63) for specific interfaces. See the %sREADME%s for details.", "", ""))
uci:foreach("network", "interface", function(s)
	local name=s['.name']
	if is_supported_interface(s) then
		local x = dscp:option(Value, name .. "_dscp", name:upper() .. " " .. translate("DSCP Tag"))
		x.rmempty = true
		x.datatype = "range(1,63)"
	end
end)

-- Includes
inc = m:section(TypedSection, "include", translate("Custom User File Includes"),
	translatef("Run the following user files after setting up but before restarting DNSMASQ. See the %sREADME%s for details.", "", ""))
inc.template = "cbi/tblsection"
inc.sortable  = true
inc.anonymous = true
inc.addremove = true

finc = inc:option(Flag, "enabled", translate("Enabled"))
finc.optional = false
finc.default = "1"
inc:option(Value, "path", translate("Path")).optional = false

return m


text:
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Services;
#endregion

namespace WaveEngine.Components.Transitions
{
    /// <summary>
    /// Transition effect where each square of the image appears at a different time.
    /// </summary>
    public class ZoomTransition : ScreenTransition
    {
        /// <summary>
        /// The sprite batch
        /// </summary>
        private SpriteBatch spriteBatch;

        /// <summary>
        /// Initializes a new instance of the <see cref="ZoomTransition"/> class.
        /// </summary>
        /// <param name="duration">The duration.</param>
        public ZoomTransition(TimeSpan duration)
            : base(duration)
        {
            this.spriteBatch = new SpriteBatch(this.graphicsDevice);
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        protected override void Initialize()
        {
        }

        /// <summary>
        /// Updates the specified game time.
        /// </summary>
        /// <param name="gameTime">The game time.</param>
        protected override void Update(TimeSpan gameTime)
        {
            this.UpdateSources(gameTime);
            this.UpdateTarget(gameTime);
        }

        /// <summary>
        /// Draws the specified game time.
        /// </summary>
        /// <param name="gameTime">The game time.</param>
        protected override void Draw(TimeSpan gameTime)
        {
            var sourceRenderTarget = this.graphicsDevice.RenderTargets.GetTemporalRenderTarget(this.platform.ScreenWidth, this.platform.ScreenHeight);
            var targetRenderTarget = this.graphicsDevice.RenderTargets.GetTemporalRenderTarget(this.platform.ScreenWidth, this.platform.ScreenHeight);

            this.DrawSources(gameTime, sourceRenderTarget);
            this.DrawTarget(gameTime, targetRenderTarget);

            this.SetRenderState();
            this.graphicsDevice.RenderTargets.SetRenderTarget(null);
            this.graphicsDevice.Clear(ref this.BackgroundColor, ClearFlags.Target | ClearFlags.DepthAndStencil, 1);
            Vector2 center = new Vector2(sourceRenderTarget.Width / 2, sourceRenderTarget.Height / 2);

            this.spriteBatch.Draw(
                sourceRenderTarget,
                center,
                null,
                Color.White * (1 - this.Lerp),
                0f,
                center,
                new Vector2(this.Lerp + 1),
                SpriteEffects.None,
                0.5f);

            this.spriteBatch.Draw(
                targetRenderTarget,
                center,
                null,
                Color.White * this.Lerp,
                0f,
                center,
                new Vector2(this.Lerp),
                SpriteEffects.None,
                0f);

            this.spriteBatch.Render();

            this.graphicsDevice.RenderTargets.ReleaseTemporalRenderTarget(sourceRenderTarget);
            this.graphicsDevice.RenderTargets.ReleaseTemporalRenderTarget(targetRenderTarget);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.spriteBatch.Dispose();
                }

                this.disposed = true;
            }
        }
    }
}


text:
@ExportPackage
package com.yahoo.compress;

import com.yahoo.osgi.annotation.ExportPackage;


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

namespace Pumpkin {

    [AttributeUsage(AttributeTargets.Method)]
    public class MethodPatch: Attribute {
        public string ClassName;
        public string MethodName;
        public bool IsStatic = false;
    }
}


text:
namespace blink {

namespace {

ScriptValue Eval(V8TestingScope* scope, const char* script_as_string) {
  v8::Local<v8::String> source;
  v8::Local<v8::Script> script;
  v8::MicrotasksScope microtasks(scope->GetIsolate(),
                                 scope->GetContext()->GetMicrotaskQueue(),
                                 v8::MicrotasksScope::kDoNotRunMicrotasks);
  // TODO(ricea): Can this actually fail? Should it be a DCHECK?
  if (!v8::String::NewFromUtf8(scope->GetIsolate(), script_as_string,
                               v8::NewStringType::kNormal)
           .ToLocal(&source)) {
    ADD_FAILURE();
    return ScriptValue();
  }
  if (!v8::Script::Compile(scope->GetContext(), source).ToLocal(&script)) {
    ADD_FAILURE() << "Compilation fails";
    return ScriptValue();
  }
  return ScriptValue(scope->GetIsolate(), script->Run(scope->GetContext()));
}

}  // namespace

ScriptValue EvalWithPrintingError(V8TestingScope* scope, const char* script) {
  v8::TryCatch block(scope->GetIsolate());
  ScriptValue r = Eval(scope, script);
  if (block.HasCaught()) {
    ADD_FAILURE() << ToCoreString(
        block.Exception()->ToString(scope->GetContext()).ToLocalChecked());
    block.ReThrow();
  }
  return r;
}

}  // namespace blink


text:
import React, { useState, useEffect } from 'react';
import AceEditor from 'react-ace';
import 'brace/theme/tomorrow';
import 'brace/ext/language_tools';

import Style from './CodeEditor.less';
import Dialog from '../../components/Dialog';
import { Select, Option } from '../../components/Select';
import Button from '../../components/Button';

const languages = [
    'javascript',
    'typescript',
    'text',
    'java',
    'c_cpp',
    'python',
    'ruby',
    'php',
    'golang',
    'csharp',
    'html',
    'css',
    'sql',
    'json',
];

interface LoadedLanguage {
    [key: string]: boolean;
}
const loadedLanguage: LoadedLanguage = {};

interface CodeEditorProps {
    visible: boolean;
    onClose: () => void;
    onSend: (language: string, code: string) => void;
}

function CodeEditor(props: CodeEditorProps) {
    const { visible, onClose, onSend } = props;

    const [language, setLanguage] = useState('javascript');
    const [value, setValue] = useState('');
    const [timestamp, setTimestamp] = useState(0);

    useEffect(() => {
        if (visible) {
            setValue('');
        }
    }, [visible]);

    useEffect(() => {
        (async () => {
            // 动态加载语言包
            if (visible && !loadedLanguage[language]) {
                /**
                 * 为了减小打包产物体积, 这里是逐个引入所需的语音包
                 * 如果直接用变量路径, 会将该目录下的文件全部打包
                 * 另外不单个引入也不好设置 webpackChunkName
                 */
                switch (language) {
                    case 'javascript': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-javascript" */ 'brace/mode/javascript'
                        );
                        break;
                    }
                    case 'typescript': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-typescript" */ 'brace/mode/typescript'
                        );
                        break;
                    }
                    case 'java': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-java" */ 'brace/mode/java'
                        );
                        break;
                    }
                    case 'c_cpp': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-c_cpp" */ 'brace/mode/c_cpp'
                        );
                        break;
                    }
                    case 'python': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-python" */ 'brace/mode/python'
                        );
                        break;
                    }
                    case 'ruby': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-ruby" */ 'brace/mode/ruby'
                        );
                        break;
                    }
                    case 'php': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-php" */ 'brace/mode/php'
                        );
                        break;
                    }
                    case 'golang': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-golang" */ 'brace/mode/golang'
                        );
                        break;
                    }
                    case 'csharp': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-csharp" */ 'brace/mode/csharp'
                        );
                        break;
                    }
                    case 'html': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-html" */ 'brace/mode/html'
                        );
                        break;
                    }
                    case 'css': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-css" */ 'brace/mode/css'
                        );
                        break;
                    }
                    case 'text': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-text" */ 'brace/mode/markdown'
                        );
                        break;
                    }
                    case 'sql': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-sql" */ 'brace/mode/sql'
                        );
                        break;
                    }
                    case 'json': {
                        // @ts-ignore
                        await import(
                            /* webpackChunkName: "react-ace-mode-json" */ 'brace/mode/json'
                        );
                        break;
                    }
                    default: {
                        console.warn('不支持的语言包', language);
                    }
                }
                loadedLanguage[language] = true;
                setTimestamp(Date.now());
            }
        })();
    }, [visible, language]);

    function renderEditor() {
        if (!loadedLanguage[language]) {
            return null;
        }

        const editorProps = {
            theme: 'tomorrow',
            value,
            onChange: (newValue: string) => setValue(newValue),
            fontSize: 12,
            width: '100%',
            height: '100%',
            showPrintMargin: true,
            showGutter: true,
            highlightActiveLine: true,
            setOptions: {
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                enableSnippets: false,
                showLineNumbers: true,
                tabSize: 4,
            },
        };

        return (
            <AceEditor
                mode={language === 'text' ? 'markdown' : language}
                {...editorProps}
            />
        );
    }

    return (
        <>
            <Dialog
                className={Style.codeEditor}
                title="请输入要发送的代码"
                visible={visible}
                onClose={onClose}
            >

编程语言:

                        <Select
                            className={Style.languageSelect}
                            defaultValue={languages[0]}
                            // @ts-ignore
                            onSelect={(lang: string) => setLanguage(lang)}
                        >
                            {languages.map((lang) => (
                                <Option value={lang} key={lang}>
                                    {lang}
                                </Option>
                            ))}
                        </Select>

                        {renderEditor()}

                    <Button
                        className={Style.sendButton}
                        onClick={() => onSend(language, value)}
                    >
                        发送
                    </Button>

            </Dialog>
            {timestamp}
        </>
    );
}

export default CodeEditor;


text:
package words.images;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Picture;

public class ApacheExtractImages
{
	public static void main(String[] args) throws Exception
	{
		HWPFDocument doc = new HWPFDocument(new FileInputStream(
				"data/document.doc"));
		List<Picture> pics = doc.getPicturesTable().getAllPictures();

		for (int i = 0; i < pics.size(); i++)
		{
			Picture pic = (Picture) pics.get(i);

			FileOutputStream outputStream = new FileOutputStream(
					"data/apacheImages/" + "Apache_"
							+ pic.suggestFullFileName());
			outputStream.write(pic.getContent());
			outputStream.close();
		}
	}
}


text: A REST service for creating text pastes


text:
GMSMarker-InformationDictionary
===============================

This simple category helps you to assign a NSDictionary of information for specific GMSMarker


text:
import React, { Component } from 'react';
import { Text, View, Navigator,TextInput, Image, TouchableHighlight, StyleSheet, AppRegistry }  from 'react-native';

import SecondPageComponent from './SecondPageComponent';

var TouchableButton = require('./TouchableButton');

class FirstPageComponent extends React.Component {

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

    _pressButton() {
        const { navigator } = this.props;
        //或者写成 const navigator = this.props.navigator;
        //为什么这里可以取得 props.navigator?请看上文:
        //<Component {...route.params} navigator={navigator} />
        //这里传递了navigator作为props
        if(navigator) {
            navigator.push({
                name: 'SecondPageComponent',
                component: SecondPageComponent,
                params:{
                    user:this.state.user,
                    pwd:this.state.pwd
                }
            })
        }
    }

    render() {
        return (
            <View style={{backgroundColor:'#f4f4f4',flex:1}}>
                <Image
                    style={styles.style_image}
                    source={require('./../imgs/favicon.png')}/>
                <TextInput
                    style={styles.style_user_input}
                    placeholder='QQ号/手机号/邮箱'
                    numberOfLines={1}
                    autoFocus={true}
                    underlineColorAndroid={'transparent'}
                    onChangeText={(text) => this.setState({user: text})}
                    textAlignVertical='center'
                    textAlign='center'/>
                <View style={{height:1,backgroundColor:'#f4f4f4'}}/>
                <TextInput
                    style={styles.style_pwd_input}
                    placeholder='密码'
                    numberOfLines={1}
                    underlineColorAndroid={'transparent'}
                    onChangeText={(text) => this.setState({pwd: text})}
                    secureTextEntry={true}
                    textAlignVertical='center'
                    textAlign='center'
                />

                <View  style={styles.style_view_commit}>
                    <Text style={{color:'#fff'}}>
                       登录
                    </Text>
                </View>

                <View>
                    <TouchableButton
                        underlayColor='#4169e1'
                        style={styles.style_view_button}
                        onPress={this._pressButton.bind(this)}
                        text='登录有点击效果-跳转页面'>
                    </TouchableButton>
                </View>

                <View style={{flex:1,flexDirection:'row',alignItems: 'flex-end',bottom:10}}>
                     <Text style={styles.style_view_unlogin}>
                         无法登录?
                    </Text>
                    <Text style={styles.style_view_register}>
                         新用户
                    </Text>
                </View>
          </View>
        );
    }
}

const styles = StyleSheet.create({
  style_image:{
    borderRadius:45,
    height:70,
    width:70,
    marginTop:40,
    alignSelf:'center',
  },
  style_user_input:{
      backgroundColor:'#fff',
      marginTop:10,
      height:45,
  },
  style_pwd_input:{
      backgroundColor:'#fff',
      height:45,
  },
  style_view_commit:{
      marginTop:15,
      marginLeft:10,
      marginRight:10,
      backgroundColor:'#63B8FF',
      borderColor:'#5bc0de',
      height:45,
      borderRadius:5,
      justifyContent: 'center',
      alignItems: 'center',
  },
  style_view_button:{
      marginTop:15,
      marginLeft:10,
      marginRight:10,
      backgroundColor:'#63B8FF',
      borderColor:'#5bc0de',
      height:45,
      borderRadius:5,
      justifyContent: 'center',
      alignItems: 'center',
  },
  style_view_unlogin:{
    fontSize:15,
    color:'#63B8FF',
    marginLeft:10,
  },
  style_view_register:{
    fontSize:15,
    color:'#63B8FF',
    marginRight:10,
    alignItems:'flex-end',
    flex:1,
    flexDirection:'row',
    textAlign:'right',
  }
});

export default FirstPageComponent


text:
using namespace Microsoft::Graphics::Canvas::DirectX::Direct3D11;
using namespace Microsoft::WRL;

TEST_CLASS(SurfaceTests)
{
    TEST_METHOD(RoundtripDxgiSurface)
    {
        ComPtr<ID3D11Texture2D> texture = CreateTexture2D();

        ComPtr<IDXGISurface> dxgiSurface;
        ThrowIfFailed(texture.As(&dxgiSurface));

        //
        // Create a Direct3DSurface based on this
        //
        IDirect3DSurface^ graphicsSurface = CreateDirect3DSurface(dxgiSurface.Get());

        //
        // Convert it back to a DXGI surface
        //
        ComPtr<IDXGISurface> roundTrippedDxgiSurface;
        ThrowIfFailed(GetDXGIInterface(
            graphicsSurface,
            roundTrippedDxgiSurface.GetAddressOf()));

        Assert::AreEqual(dxgiSurface.Get(), roundTrippedDxgiSurface.Get());

        //
        // Convert it directly to a D3D texture
        //
        ComPtr<ID3D11Texture2D> roundTrippedTexture;
        ThrowIfFailed(GetDXGIInterface(
            graphicsSurface,
            roundTrippedTexture.GetAddressOf()));

        Assert::AreEqual(texture.Get(), roundTrippedTexture.Get());
    }

    TEST_METHOD(CreateDirect3DSurfaceFailsOnNullDxgiSurface)
    {
        Assert::ExpectException<Platform::InvalidArgumentException^>(
            []
            {
                CreateDirect3DSurface(nullptr);
            });
    }

    TEST_METHOD(Direct3DSurfaceImplementsClosableCorrectly)
    {
        //
        // Create a mock IDXGISurface implementation.  The token is used so we
        // can tell when the IDXGISurface instance is destroyed.
        //

        class DxgiSurfaceWithToken : public MockDxgiSurface
        {
            std::shared_ptr<bool> m_Token;

        public:
            DxgiSurfaceWithToken(std::shared_ptr<bool> token)
                : m_Token(token)
            {
            }
        };

        std::shared_ptr<bool> strongToken = std::make_shared<bool>(true);
        std::weak_ptr<bool> weakToken(strongToken);

        ComPtr<IDXGISurface> mockDxgiSurface = Make<DxgiSurfaceWithToken>(strongToken);
        strongToken.reset();

        Assert::IsFalse(weakToken.expired());

        //
        // Wrap a Direct3DSurface around mockDxgiSurface.  This takes ownership
        // of the mockDxgiSurface, so we release our reference to it.
        //
        IDirect3DSurface^ graphicsSurface = CreateDirect3DSurface(mockDxgiSurface.Get());
        mockDxgiSurface.Reset();
        Assert::IsFalse(weakToken.expired());

        //
        // Now explicitly close the Direct3DSurface ('delete foo' in C++/CX
        // calls Close()).  This should release the token, making our weakToken
        // invalid.
        //
        delete graphicsSurface;
        Assert::IsTrue(weakToken.expired());

        //
        // Attempting to close a second time is a no-op
        //
        delete graphicsSurface;

        //
        // Attempting to call any other method gives RO_E_CLOSED
        //
        Assert::ExpectException<Platform::ObjectDisposedException^>(
            [&]
            {
                graphicsSurface->Description;
            });
    }

    TEST_METHOD(Direct3DSurfaceGetDescriptionCallsGetDesc)
    {
        //
        // Create a mock DXGI surface that tracks whether or not GetDesc is
        // called and can return a pre-canned DXGI_SURFACE_DESC.
        //

        ComPtr<MockDxgiSurface> mockDxgiSurface = Make<MockDxgiSurface>();

        bool getDescCalled = false;
        DXGI_SURFACE_DESC expectedDesc = {};
        expectedDesc.Width = 123;
        expectedDesc.Height = 456;
        expectedDesc.Format = DXGI_FORMAT_BC3_UNORM_SRGB; // 78
        expectedDesc.SampleDesc.Count = 9;
        expectedDesc.SampleDesc.Quality = 10;

        mockDxgiSurface->MockGetDesc =
            [&]
            {
                Assert::IsFalse(getDescCalled);
                getDescCalled = true;
                return expectedDesc;
            };

        //
        // Wrap a Direct3DSurface around it
        //
        IDirect3DSurface^ graphicsSurface = CreateDirect3DSurface(mockDxgiSurface.Get());

        //
        // Get the Description property and compare that with what we expected.
        //
        Direct3DSurfaceDescription actualDesc = graphicsSurface->Description;

        Assert::IsTrue(getDescCalled);
        Assert::AreEqual<int>(expectedDesc.Width, actualDesc.Width);
        Assert::AreEqual<int>(expectedDesc.Height, actualDesc.Height);
        Assert::AreEqual(static_cast<int>(expectedDesc.Format), static_cast<int>(actualDesc.Format));
        Assert::AreEqual<int>(expectedDesc.SampleDesc.Count, actualDesc.MultisampleDescription.Count);
        Assert::AreEqual<int>(expectedDesc.SampleDesc.Quality, actualDesc.MultisampleDescription.Quality);
    }

    TEST_METHOD(Direct3DSurfaceGetDescriptionFailsIfPassedNull)
    {
        ComPtr<IDXGISurface> mockDxgiSurface = Make<MockDxgiSurface>();
        IDirect3DSurface^ graphicsSurface = CreateDirect3DSurface(mockDxgiSurface.Get());

        ABI::Microsoft::Graphics::Canvas::DirectX::Direct3D11::IDirect3DSurface* rawDirect3DSurface =
            reinterpret_cast<ABI::Microsoft::Graphics::Canvas::DirectX::Direct3D11::IDirect3DSurface*>(graphicsSurface);

        Assert::AreEqual(E_INVALIDARG, rawDirect3DSurface->get_Description(nullptr));
    }

private:
    ComPtr<ID3D11Texture2D> CreateTexture2D()
    {
        //
        // Create a texture that will be the surface that gets roundtripped
        //
        ComPtr<ID3D11Device> d3dDevice = CreateD3DDevice();

        CD3D11_TEXTURE2D_DESC textureDesc(DXGI_FORMAT_R32G32B32_FLOAT, 1, 1);

        ComPtr<ID3D11Texture2D> texture;
        ThrowIfFailed(d3dDevice->CreateTexture2D(
            &textureDesc,
            nullptr,
            &texture));

        return texture;
    }
};

#endif  // USE_LOCALLY_EMULATED_UAP_APIS