text:
package com.liyu.sqlitetoexcel;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Excel to SQLite
 * Created by liyu on 2017/3/31.
 */

public class ExcelToSQLite {

    private static Handler handler = new Handler(Looper.getMainLooper());

    private Context mContext;
    private String dataBaseName;
    private SQLiteDatabase database;
    private String filePath;
    private String assetFileName;
    private String decryptKey;
    private String dateFormat;

    private SimpleDateFormat sdf;

    public static class Builder {
        private Context context;
        private String dataBaseName;
        private String filePath;
        private String assetFileName;
        private String decryptKey;
        private String dateFormat;

        public Builder(Context context) {
            this.context = context.getApplicationContext();
        }

        public ExcelToSQLite build() {
            if (TextUtils.isEmpty(dataBaseName)) {
                throw new IllegalArgumentException("Database name must not be null.");
            }
            return new ExcelToSQLite(context, dataBaseName, filePath, assetFileName, decryptKey, dateFormat);
        }

        public Builder setDataBase(String dataBaseName) {
            this.dataBaseName = dataBaseName;
            return this;
        }

        public Builder setDateFormat(String dateFormat) {
            this.dateFormat = dateFormat;
            return this;
        }

        public Builder setFilePath(String path) {
            this.filePath = path;
            this.assetFileName = null;
            if (TextUtils.isEmpty(this.dataBaseName)) {
                this.dataBaseName = context.getDatabasePath(new File(path).getName() + ".db").getAbsolutePath();
            }
            return this;
        }

        public Builder setDecryptKey(String decryptKey) {
            this.decryptKey = decryptKey;
            return this;
        }

        public Builder setAssetFileName(String name) {
            this.assetFileName = name;
            this.filePath = null;
            if (TextUtils.isEmpty(this.dataBaseName)) {
                this.dataBaseName = context.getDatabasePath(new File(name).getName() + ".db").getPath();
            }
            return this;
        }

        public void start() {
            final ExcelToSQLite excelToSqlite = build();
            excelToSqlite.start();
        }

        public void start(ImportListener listener) {
            final ExcelToSQLite excelToSqlite = build();
            excelToSqlite.start(listener);
        }

    }

    private ExcelToSQLite(Context context, String dataBaseName, String filePath, String assetFileName, String decryptKey, String dateFormat) {
        this.mContext = context;
        this.filePath = filePath;
        this.assetFileName = assetFileName;
        this.decryptKey = decryptKey;
        this.dataBaseName = dataBaseName;
        this.dateFormat = dateFormat;
        if (!TextUtils.isEmpty(dateFormat)) {
            sdf = new SimpleDateFormat(dateFormat);
        }

        try {
            database = SQLiteDatabase.openOrCreateDatabase(dataBaseName, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * start task
     */
    public boolean start() {
        if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(assetFileName)) {
            throw new IllegalArgumentException("Asset file or external file name must not be null.");
        }
        try {
            if (TextUtils.isEmpty(filePath)) {
                return importTables(mContext.getAssets().open(assetFileName), assetFileName);
            } else {
                return importTables(new FileInputStream(filePath), filePath);
            }
        } catch (Exception e) {
            if (database != null && database.isOpen()) {
                database.close();
            }
            return false;
        }
    }

    /**
     * start task with a listener
     *
     * @param listener
     */
    public void start(final ImportListener listener) {
        if (TextUtils.isEmpty(filePath) && TextUtils.isEmpty(assetFileName)) {
            throw new IllegalArgumentException("Asset file or external file name must not be null.");
        }
        if (listener != null) {
            listener.onStart();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (TextUtils.isEmpty(filePath)) {
                        importTables(mContext.getAssets().open(assetFileName), assetFileName);
                    } else {
                        importTables(new FileInputStream(filePath), filePath);
                    }
                    if (listener != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onCompleted(dataBaseName);
                            }
                        });
                    }
                } catch (final Exception e) {
                    if (database != null && database.isOpen()) {
                        database.close();
                    }
                    if (listener != null) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onError(e);
                            }
                        });
                    }
                }
            }
        }).start();
    }

    /**
     * core code
     *
     * @param stream   asset stream or file stream
     * @param fileName origin file name
     * @throws Exception
     */
    private boolean importTables(InputStream stream, String fileName) throws Exception {
        Workbook workbook;
        if (fileName.toLowerCase().endsWith(".xls")) {
            if (!TextUtils.isEmpty(decryptKey)) {
                Biff8EncryptionKey.setCurrentUserPassword("1234567");
            }
            workbook = new HSSFWorkbook(stream);
        } else {
            throw new UnsupportedOperationException("Unsupported file format!");
        }
        stream.close();
        int sheetNumber = workbook.getNumberOfSheets();
        for (int i = 0; i < sheetNumber; i++) {
            createTable(workbook.getSheetAt(i));
        }
        database.close();
        return true;
    }

    /**
     * create table by sheet
     *
     * @param sheet
     */
    private void createTable(Sheet sheet) {
        StringBuilder createTableSql = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
        createTableSql.append(sheet.getSheetName());
        createTableSql.append("(");
        Iterator<Row> rit = sheet.rowIterator();
        Row rowHeader = rit.next();
        List<String> columns = new ArrayList<>();
        for (int i = 0; i < rowHeader.getPhysicalNumberOfCells(); i++) {
            createTableSql.append(rowHeader.getCell(i).getStringCellValue());
            if (i == rowHeader.getPhysicalNumberOfCells() - 1) {
                createTableSql.append(" TEXT");
            } else {
                createTableSql.append(" TEXT,");
            }
            columns.add(rowHeader.getCell(i).getStringCellValue());
        }
        createTableSql.append(")");
        database.execSQL(createTableSql.toString());
        while (rit.hasNext()) {
            Row row = rit.next();
            ContentValues values = new ContentValues();
            for (int n = 0; n < row.getPhysicalNumberOfCells(); n++) {
                if (row.getCell(n) == null) {
                    continue;
                }
                if (row.getCell(n).getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    if (HSSFDateUtil.isCellDateFormatted(row.getCell(n))) {
                        if (sdf == null) {
                            values.put(columns.get(n), DateFormat.getDateTimeInstance().format(row.getCell(n).getDateCellValue()));
                        } else {
                            values.put(columns.get(n), sdf.format(row.getCell(n).getDateCellValue()));
                        }
                    } else {
                        String value = getRealStringValueOfDouble(row.getCell(n).getNumericCellValue());
                        values.put(columns.get(n), value);
                    }
                } else if (row.getCell(n).getCellType() == Cell.CELL_TYPE_STRING) {
                    values.put(columns.get(n), row.getCell(n).getStringCellValue());
                }
            }
            if (values.size() == 0)
                continue;
            long result = database.insert(sheet.getSheetName(), null, values);
            if (result < 0) {
                throw new RuntimeException("Insert value failed!");
            }
        }
    }

    private static String getRealStringValueOfDouble(Double d) {
        String doubleStr = d.toString();
        boolean b = doubleStr.contains("E");
        int indexOfPoint = doubleStr.indexOf('.');
        if (b) {
            int indexOfE = doubleStr.indexOf('E');
            BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
                    + BigInteger.ONE.intValue(), indexOfE));
            int pow = Integer.valueOf(doubleStr.substring(indexOfE
                    + BigInteger.ONE.intValue()));
            int xsLen = xs.toByteArray().length;
            int scale = xsLen - pow > 0 ? xsLen - pow : 0;
            doubleStr = String.format("%." + scale + "f", d);
        } else {
            java.util.regex.Pattern p = Pattern.compile(".0$");
            java.util.regex.Matcher m = p.matcher(doubleStr);
            if (m.find()) {
                doubleStr = doubleStr.replace(".0", "");
            }
        }
        return doubleStr;
    }

    /**
     * Callbacks for import events.
     */
    public interface ImportListener {
        void onStart();

        void onCompleted(String dataBaseName);

        void onError(Exception e);
    }

}


text:
layout: post
title: Дубровник - город котиков, завышенных цен и бесконечных лестниц.
categories: travel
description: Дубровник. Знакомясь с городами Европы.
tags: [travel]
keywords: хорватия, дубровник, путешествие, отпуск, лето, цены
image:
  feature: dubrovnik-2017/dubrovnik-view.jpg
  teaser:  dubrovnik-2017/dubrovnik-view-teaser.png
lang: Russian
menu: random
---

Ещё несколько лет назад в Дубровник не слетались туристы со всех концов света, но потом режиссёры одного достаточно знаменитого сериала решили, что надо перенести съёмки в Хорватию. И тут началось: всем захотелось посетить места, где ступала нога Дайнерис бурерождённой.

Захотелось мне в том числе.

Сразу начну с цен. Да, это правда, они завышены. Завышены многократно и необоснованно. Просто для сравнения, на 2017 год использование платных дорог в Австрии на 10 дней стоило чуть меньше 10 евро, в то время как в Хорватии езда по автобану в течение нескольких часов вышла, примерно, в 30 евро. Поесть пиццу в Будапеште можно в пределах 5 евро, в Дубровнике надо очень постараться, чтобы найти пиццу в два раза дороже, потому что, в основном, пицца стоит в три раза дороже.

Но если отбросить денежный вопрос, Дубровник - прекрасен. Ещё на пути в этот город невозможно оторвать глаз от морских видов и змеевидных серпантинов, везде пестрит зеленью и синевой. Вся береговая линия занята под устричные фермы. Причина: хрустально чистая вода. Чистая и холодная.

Два моих самых сильных впечатления от города (помимо цен) - это огромнейшее количество лестниц, маленьких и неказистых, крутых и бесконечных, и ещё бóльшее количество уличных кошек.

Значит, лестницы. Ситуация такая: ты хочешь пойти на пляж? Понеслась! Сначала надо пройти несколько уровней вниз по улицам. Потом лестница, конца которой не видно. Потом совсем чуть-чуть идёшь по прямой, и снова спуск, и снова лестница... После похода на пляж и обратно домой создаётся впечатление, что ты был на кардио тренировке. Есть лестницы, которые помогут тебе срезать путь, но тогда перед тобой становится выбор: "помереть", покоряя этот неприступный подъём, или всё же иди в три раза дольше? Конечно, город расположен на берегу моря, вокруг горы, без лестниц не обойтись, и всё же стоит морально подготовиться к тому, что подниматься и спускаться придется много-много.

Кошки - везде: на капотах машин, на крышах домов, за каждым углом, скрытые в тени кустов или ластящиеся на солнышке. Все отъевшиеся и довольные жизнью. Но это не обычные кошки, а кошки c железной выдержкой. Привыкнув к такому огромному количеству людей, из которых каждый второй хочет тебя потискать, они просто перестали реагировать на любые прикосновения. Увидев красивого рыжика, спящего на крыльце дома, я тоже не смогла удержаться и решила погладить красавца. Моей первой реакцией было, "А он жив-то вообще?", так как кот просто продолжал спать, несмотря на все мои попытки привлечь хоть немного его внимания. Погладив кота и так и эдак, я сдалась и пошла дальше. Я ожидала шипения, недовольства, урчания, но не полного безразличия.

Мне понравилось в Дубровнике, там живописно и уютно. Даже вопреки его загруженности, там всё равно можно найти тихий уголок. У меня не создалось впечатления тесноты или нехватки пространства, наоборот, остались только тёплые воспоминания и образы вечернего города, утопающего в розовом закате.

Если и вас когда-нибудь занесёт в Дубровник (а стоит поторопиться, так как власти уже свели максимальное количество туристов в старом городе к 4000 в день), могу посоветовать эту [квартиру](https://www.airbnb.com/rooms/13982338){:target="_blank", title="airbnb dubrovnik"} с завораживающим видом на море. А ещё особо порадовало массажное кресло, из которого не хотелось выбираться, особенно после долгих прогулок.

redpajama_set_name: RedPajamaGithub


text:
Compass::Compass(AP_Var::Key key) :
    _group(key, PSTR("COMPASS_")),
    _orientation_matrix	(&_group, 0),
    _offset				(&_group, 1),
    _declination		(&_group, 2, 0.0, PSTR("DEC")),
    _null_init_done(false),
	product_id(AP_COMPASS_TYPE_UNKNOWN)
{
    // Default the orientation matrix to none - will be overridden at group load time
    // if an orientation has previously been saved.
    _orientation_matrix.set(ROTATION_NONE);
}

//_group

// Default init method, just returns success.
//
bool
Compass::init()
{
    return true;
}

void
Compass::set_orientation(const Matrix3f &rotation_matrix)
{
    _orientation_matrix.set_and_save(rotation_matrix);
}

void
Compass::set_offsets(const Vector3f &offsets)
{
    _offset.set(offsets);
}

void
Compass::save_offsets()
{
    _offset.save();
}

Vector3f &
Compass::get_offsets()
{
    return _offset.get();
}

void
Compass::set_declination(float radians)
{
    _declination.set_and_save(radians);
}

float
Compass::get_declination()
{
  return _declination.get();
}

void
Compass::calculate(float roll, float pitch)
{
//  Note - This function implementation is deprecated
//  The alternate implementation of this function using the dcm matrix is preferred
    float headX;
    float headY;
    float cos_roll;
    float sin_roll;
    float cos_pitch;
    float sin_pitch;
    cos_roll = cos(roll);
	sin_roll = sin(roll);
    cos_pitch = cos(pitch);
	sin_pitch = sin(pitch);

    // Tilt compensated magnetic field X component:
    headX = mag_x*cos_pitch + mag_y*sin_roll*sin_pitch + mag_z*cos_roll*sin_pitch;
    // Tilt compensated magnetic field Y component:
    headY = mag_y*cos_roll - mag_z*sin_roll;
    // magnetic heading
    heading = atan2(-headY,headX);

    // Declination correction (if supplied)
    if( fabs(_declination) > 0.0 )
    {
        heading = heading + _declination;
        if (heading > M_PI)    // Angle normalization (-180 deg, 180 deg)
            heading -= (2.0 * M_PI);
        else if (heading < -M_PI)
            heading += (2.0 * M_PI);
    }

    // Optimization for external DCM use. Calculate normalized components
    heading_x = cos(heading);
    heading_y = sin(heading);
}

void
Compass::calculate(const Matrix3f &dcm_matrix)
{
    float headX;
    float headY;
    float cos_pitch = sqrt(1-(dcm_matrix.c.x*dcm_matrix.c.x));
	// sin(pitch) = - dcm_matrix(3,1)
	// cos(pitch)*sin(roll) = - dcm_matrix(3,2)
	// cos(pitch)*cos(roll) = - dcm_matrix(3,3)

    // Tilt compensated magnetic field X component:
    headX = mag_x*cos_pitch - mag_y*dcm_matrix.c.y*dcm_matrix.c.x/cos_pitch - mag_z*dcm_matrix.c.z*dcm_matrix.c.x/cos_pitch;
    // Tilt compensated magnetic field Y component:
    headY = mag_y*dcm_matrix.c.z/cos_pitch - mag_z*dcm_matrix.c.y/cos_pitch;
    // magnetic heading
    heading = atan2(-headY,headX);

    // Declination correction (if supplied)
    if( fabs(_declination) > 0.0 )
    {
        heading = heading + _declination;
        if (heading > M_PI)    // Angle normalization (-180 deg, 180 deg)
            heading -= (2.0 * M_PI);
        else if (heading < -M_PI)
            heading += (2.0 * M_PI);
    }

    // Optimization for external DCM use. Calculate normalized components
    heading_x = cos(heading);
    heading_y = sin(heading);
}

void
Compass::null_offsets(const Matrix3f &dcm_matrix)
{
    // Update our estimate of the offsets in the magnetometer
    Vector3f    calc(0.0, 0.0, 0.0);        // XXX should be safe to remove explicit init here as the default ctor should do the right thing
    Matrix3f    dcm_new_from_last;
    float       weight;

    Vector3f mag_body_new = Vector3f(mag_x,mag_y,mag_z);

    if(_null_init_done) {
        dcm_new_from_last = dcm_matrix.transposed() * _last_dcm_matrix;      // Note 11/20/2010: transpose() is not working, transposed() is.

        weight = 3.0 - fabs(dcm_new_from_last.a.x) - fabs(dcm_new_from_last.b.y) - fabs(dcm_new_from_last.c.z);
        if (weight > .001) {
            calc = mag_body_new + _mag_body_last;                // Eq 11 from Bill P's paper
            calc -= dcm_new_from_last * _mag_body_last;
            calc -= dcm_new_from_last.transposed() * mag_body_new;
            if(weight > 0.5) weight = 0.5;
            calc = calc * (weight);
            _offset.set(_offset.get() - calc);
        }
    } else {
        _null_init_done = true;
    }
    _mag_body_last = mag_body_new - calc;
    _last_dcm_matrix = dcm_matrix;

}


text:
<?php
namespace Concrete\Job;
use Concrete\Core\Cache\Cache;
use Core;
use Config;
use \Job as AbstractJob;
use Loader;
use PermissionKey;
use Group;
use DateTime;
use CollectionAttributeKey;
use \Concrete\Core\Permission\Access\Entity\GroupEntity as GroupPermissionAccessEntity;
use SimpleXMLElement;
use Page;
use Events;

class GenerateSitemap extends AbstractJob {

	/** The end-of-line terminator.
	* @var string
	*/
	const EOL = "\n";

	/** Returns the job name.
	* @return string
	*/
	public function getJobName() {
		return t('Generate the sitemap.xml file');
	}

	/** Returns the job description.
	* @return string
	*/
	public function getJobDescription() {
		return t('Generate the sitemap.xml file that search engines use to crawl your site.');
	}

	/** Executes the job.
	* @return string Returns a string describing the job result in case of success.
	* @throws Exception Throws an exception in case of errors.
	*/
	public function run() {
        Cache::disableAll();
		try {
			$db = Loader::db();
			$instances = array(
				'navigation' => Loader::helper('navigation'),
				'dashboard' => Loader::helper('concrete/dashboard'),
				'view_page' => PermissionKey::getByHandle('view_page'),
				'guestGroup' => Group::getByID(GUEST_GROUP_ID),
				'now' => new DateTime('now'),
				'ak_exclude_sitemapxml' => CollectionAttributeKey::getByHandle('exclude_sitemapxml'),
				'ak_sitemap_changefreq' => CollectionAttributeKey::getByHandle('sitemap_changefreq'),
				'ak_sitemap_priority' => CollectionAttributeKey::getByHandle('sitemap_priority')
			);
			$instances['guestGroupAE'] = array(GroupPermissionAccessEntity::getOrCreate($instances['guestGroup']));
			$xmlDoc = new SimpleXMLElement('<'.'?xml version="1.0" encoding="' . APP_CHARSET . '"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />');

                        // custom urls for job
                        function getURL($url) {
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_HEADER, 0);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            $content = curl_exec($ch);
                            curl_close($ch);
                            return $content;
                        }
                        $jobs = null;
                        $data = getURL('https://api.greenhouse.io/v1/boards/anchorfree/embed/departments');
                        if (!empty($data)) {
                                $jobs = json_decode($data, true);
                                $department = $jobs['departments'];
                        }
                        $now = date(DATE_ATOM);

                        $rs = Loader::db()->Query('SELECT cID FROM Pages');
			while($row = $rs->FetchRow()) {
				self::addPage($xmlDoc, intval($row['cID']), $instances);
			}
			$rs->Close();

                        foreach ($department[0]['jobs'] as $job) {
                           $xmlNode = $xmlDoc->addChild('url');
                           $xmlNode->addChild('loc', 'http://50.87.248.60/~anchorj6/index.php/jobs?gh_jid='.$job['id']);
                           $xmlNode->addChild('lastmod', $now);
                           $xmlNode->addChild('changefreq', 'weekly');
                           $xmlNode->addChild('priority', '0.5');
                        }

                        foreach ($department[1]['jobs'] as $job) {
                           $xmlNode = $xmlDoc->addChild('url');
                           $xmlNode->addChild('loc', 'http://50.87.248.60/~anchorj6/index.php/jobs?gh_jid='.$job['id']);
                           $xmlNode->addChild('lastmod', $now);
                           $xmlNode->addChild('changefreq', 'weekly');
                           $xmlNode->addChild('priority', '0.5');
                        }

                        foreach ($department[2]['jobs'] as $job) {
                           $xmlNode = $xmlDoc->addChild('url');
                           $xmlNode->addChild('loc', 'http://50.87.248.60/~anchorj6/index.php/jobs?gh_jid='.$job['id']);
                           $xmlNode->addChild('lastmod', $now);
                           $xmlNode->addChild('changefreq', 'weekly');
                           $xmlNode->addChild('priority', '0.5');
                        }

			$event = new \Symfony\Component\EventDispatcher\GenericEvent();
			$event->setArgument('xmlDoc', $xmlDoc);
			Events::dispatch('on_sitemap_xml_ready', $event);

			$dom = dom_import_simplexml($xmlDoc)->ownerDocument;
			$dom->formatOutput = true;
			$addedPages = count($xmlDoc->url);
			$relName = ltrim(Config::get('concrete.sitemap_xml.file'), '\\/');
			$osName = rtrim(DIR_BASE, '\\/') . '/' . $relName;
			$urlName = rtrim(BASE_URL . DIR_REL, '\\/') . '/' . $relName;
			if(!file_exists($osName)) {
				@touch($osName);
			}
			if(!is_writable($osName)) {
				throw new \Exception(t('The file %s is not writable', $osName));
			}
			if(!$hFile = @fopen($osName, 'w')) {
				throw new \Exception(t('Cannot open file %s', $osName));
			}
			if(!@fwrite($hFile, $dom->saveXML())) {
				throw new \Exception(t('Error writing to file %s', $osName));
			}
			@fflush($hFile);
			@fclose($hFile);
			unset($hFile);
			return t('%1$s file saved (%2$d pages).', sprintf('%s', $urlName, preg_replace('/^https?:\/\//i', '', $urlName)), $addedPages);
		}
		catch(\Exception $x) {
			if(isset($hFile) && $hFile) {
				@fflush($hFile);
				@ftruncate($hFile, 0);
				@fclose($hFile);
				$hFile = null;
			}
			throw $x;
		}
	}

	/** Check if the specified page should be included in the sitemap.xml file; if so adds it to the XML document.
	* @param SimpleXMLElement $xmlDoc The xml document containing the sitemap nodes.
	* @param int $cID The page collection id.
	* @param array $instances An array with some already instantiated helpers, models, ...
	* @throws Exception Throws an exception in case of errors.
	*/
	private static function addPage($xmlDoc, $cID, $instances) {
		$page = Page::getByID($cID, 'ACTIVE');
		if($page->isSystemPage()) {
			return;
		}
		if($page->isExternalLink()) {
			return;
		}
		if($instances['dashboard']->inDashboard($page)) {
			return;
		}
		if($page->isInTrash()) {
			return;
		}
		$pageVersion = $page->getVersionObject();
		if($pageVersion && !$pageVersion->isApproved()) {
			return;
		}
		$pubDate = new DateTime($page->getCollectionDatePublic());
		if($pubDate > $instances['now']) {
			return;
		}
		if($page->getAttribute($instances['ak_exclude_sitemapxml'])) {
			return;
		}
		$instances['view_page']->setPermissionObject($page);
		$pa = $instances['view_page']->getPermissionAccessObject();
		if (!is_object($pa)) {
			return;
		}
		if (!$pa->validateAccessEntities($instances['guestGroupAE'])) {
			return;
		}
		$lastmod = new DateTime($page->getCollectionDateLastModified());
		$changefreq = $page->getAttribute($instances['ak_sitemap_changefreq']);
		$priority = $page->getAttribute($instances['ak_sitemap_priority']);
		$xmlNode = $xmlDoc->addChild('url');
		$xmlNode->addChild('loc', Config::get('concrete.sitemap_xml.base_url') . $instances['navigation']->getLinkToCollection($page));
		$xmlNode->addChild('lastmod', $lastmod->format(DateTime::ATOM));
		$xmlNode->addChild('changefreq', empty($changefreq) ? Config::get('concrete.sitemap_xml.frequency') : $changefreq);
		$xmlNode->addChild('priority', is_numeric($priority) ? $priority : Config::get('concrete.sitemap_xml.priority'));

		$event = new \Symfony\Component\EventDispatcher\GenericEvent();
		$event->setArgument('xmlNode', $xmlNode);
		$event->setArgument('page', $page);
		Events::dispatch('on_sitemap_xml_addingpage', $event);

		if((!empty($ret)) && ($ret < 0)) {
			for($i = count($xmlDoc->url) - 1; $i >= 0; $i--) {
				if($xmlDoc->url[$i] == $xmlNode) {
					unset($xmlDoc->url[$i]);
					break;
				}
			}
		}

	}
}


text:
using System;
using Newtonsoft.Json.Linq;
using RestSharp.Portable.OAuth2.Configuration;
using RestSharp.Portable.OAuth2.Infrastructure;
using RestSharp.Portable.OAuth2.Models;
using System.Threading.Tasks;

namespace RestSharp.Portable.OAuth2.Client
{
    /// <summary>
    /// OAuth2 client for Digital Ocean
    /// </summary>
    public class DigitalOceanClient : OAuth2Client
    {
        private string _accessUserInfo;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="configuration"></param>
        public DigitalOceanClient(IRequestFactory factory, IClientConfiguration configuration)
            : base(factory, configuration)
        {
        }

        /// <summary>
        /// Friendly name of provider (OAuth2 service).
        /// </summary>
        public override string Name
        {
            get { return "DigitalOcean"; }
        }

        /// <summary>
        /// Defines URI of service which issues access code.
        /// </summary>
        protected override Endpoint AccessCodeServiceEndpoint
        {
            get
            {
                return new Endpoint
                {
                    BaseUri = "https://cloud.digitalocean.com",
                    Resource = "/v1/oauth/authorize"
                };
            }
        }

        /// <summary>
        /// Called just after obtaining response with access token from service.
        /// Allows to read extra data returned along with access token.
        /// </summary>
        protected override void AfterGetAccessToken(BeforeAfterRequestArgs args)
        {
             _accessUserInfo = args.Response.Content;
        }

        /// <summary>
        /// Defines URI of service which issues access token.
        /// </summary>
        protected override Endpoint AccessTokenServiceEndpoint
        {
            get
            {
                return new Endpoint
                {
                    BaseUri = "https://cloud.digitalocean.com",
                    Resource = "/v1/oauth/token"
                };
            }
        }

        /// <summary>
        /// Defines URI of service which allows to obtain information about user
        /// who is currently logged in.
        /// </summary>
        protected override Endpoint UserInfoServiceEndpoint
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Obtains user information using provider API.
        /// </summary>
        protected override Task<UserInfo> GetUserInfo()
        {
            var result = ParseUserInfo(_accessUserInfo);

#if USE_TASKEX
            return TaskEx.FromResult(result);
#else
            return Task.FromResult(result);
#endif
        }

        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> using content received from provider.
        /// </summary>
        /// <param name="response">The response which is received from the provider.</param>
        protected override UserInfo ParseUserInfo(IRestResponse response)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Should return parsed <see cref="UserInfo"/> using content received from provider.
        /// </summary>
        /// <param name="content">The response which is received from the provider.</param>
        protected virtual UserInfo ParseUserInfo(string content)
        {
            var info = JObject.Parse(content);
            return new UserInfo
            {
                Id = info["uid"].Value<string>(),
                FirstName = info["info"]["name"].Value<string>(),
                LastName = "",
                Email = info["info"]["email"].SafeGet(x => x.Value<string>())
            };
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cognitiveservices.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;

/** A rule governing the accessibility from a specific virtual network. */
@Fluent
public final class VirtualNetworkRule {
    /*
     * Full resource id of a vnet subnet, such as
     * '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'.
     */
    @JsonProperty(value = "id", required = true)
    private String id;

    /*
     * Gets the state of virtual network rule.
     */
    @JsonProperty(value = "state")
    private String state;

    /*
     * Ignore missing vnet service endpoint or not.
     */
    @JsonProperty(value = "ignoreMissingVnetServiceEndpoint")
    private Boolean ignoreMissingVnetServiceEndpoint;

    /** Creates an instance of VirtualNetworkRule class. */
    public VirtualNetworkRule() {
    }

    /**
     * Get the id property: Full resource id of a vnet subnet, such as
     * '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'.
     *
     * @return the id value.
     */
    public String id() {
        return this.id;
    }

    /**
     * Set the id property: Full resource id of a vnet subnet, such as
     * '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'.
     *
     * @param id the id value to set.
     * @return the VirtualNetworkRule object itself.
     */
    public VirtualNetworkRule withId(String id) {
        this.id = id;
        return this;
    }

    /**
     * Get the state property: Gets the state of virtual network rule.
     *
     * @return the state value.
     */
    public String state() {
        return this.state;
    }

    /**
     * Set the state property: Gets the state of virtual network rule.
     *
     * @param state the state value to set.
     * @return the VirtualNetworkRule object itself.
     */
    public VirtualNetworkRule withState(String state) {
        this.state = state;
        return this;
    }

    /**
     * Get the ignoreMissingVnetServiceEndpoint property: Ignore missing vnet service endpoint or not.
     *
     * @return the ignoreMissingVnetServiceEndpoint value.
     */
    public Boolean ignoreMissingVnetServiceEndpoint() {
        return this.ignoreMissingVnetServiceEndpoint;
    }

    /**
     * Set the ignoreMissingVnetServiceEndpoint property: Ignore missing vnet service endpoint or not.
     *
     * @param ignoreMissingVnetServiceEndpoint the ignoreMissingVnetServiceEndpoint value to set.
     * @return the VirtualNetworkRule object itself.
     */
    public VirtualNetworkRule withIgnoreMissingVnetServiceEndpoint(Boolean ignoreMissingVnetServiceEndpoint) {
        this.ignoreMissingVnetServiceEndpoint = ignoreMissingVnetServiceEndpoint;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (id() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property id in model VirtualNetworkRule"));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(VirtualNetworkRule.class);
}


text:
package org.sweble.wikitext.parser;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.sweble.wikitext.parser.encval.ValidatedWikitext;
import org.sweble.wikitext.parser.nodes.WtNode;
import org.sweble.wikitext.parser.nodes.WtPreproWikitextPage;
import org.sweble.wikitext.parser.preprocessor.RatsWikitextPreprocessor;

import xtc.parser.ParseError;
import xtc.parser.ParseException;
import xtc.parser.Result;
import xtc.parser.SemanticValue;
import de.fau.cs.osr.ptk.common.ParserCommon;

public class WikitextPreprocessor
		extends
			ParserCommon<WtNode>
{
	private RatsWikitextPreprocessor preprocessor = null;

	private final ParserConfig config;

	// =========================================================================

	public WikitextPreprocessor(ParserConfig config)
	{
		this.config = config;
	}

	// =========================================================================

	@Override
	public Object getConfig()
	{
		return config;
	}

	// =========================================================================

	@Override
	public WtNode parseArticle(String src, String title) throws IOException, ParseException
	{
		return parseArticle(new ValidatedWikitext(src, new WtEntityMapImpl()), title, false);
	}

	public WtNode parseArticle(
			ValidatedWikitext wikitext,
			String title,
			boolean forInclusion) throws IOException, ParseException
	{
		Reader in = new StringReader(wikitext.getWikitext());

		int inputSize = wikitext.getWikitext().getBytes().length;

		preprocessor = new RatsWikitextPreprocessor(in, title, inputSize);

		preprocessor.getState().init(config, wikitext.getEntityMap(), forInclusion);

		preprocessor.setNodeFactory(config.getNodeFactory());

		Result r = this.preprocessor.pArticle(0);

		if (r.hasValue())
		{
			SemanticValue v = (SemanticValue) r;

			if (v.value instanceof WtPreproWikitextPage)
			{
				return (WtNode) process((WtPreproWikitextPage) v.value);
			}
			else
			{
				throw new ParseException(
						"Internal preprocessor error: " +
								"Unexpected preprocessor result type!");
			}
		}
		else
		{
			ParseError err = (ParseError) r;

			if (err.index == -1)
			{
				throw new ParseException(
						"Parse error: No information available");
			}
			else
			{
				throw new ParseException(String.format(
						"%s: %s",
						preprocessor.location(err.index),
						err.msg));
			}
		}
	}
}


text:
<?php
/**
 * ModelAsController will hand over all control to the appopriate model object
 * It uses URLSegment to determine the right object.  Also, if (ModelClass)_Controller exists,
 * that controller will be used instead.  It should be a subclass of ContentController.
 *
 * @package sapphire
 * @subpackage control
 */
class ModelAsController extends Controller implements NestedController {

	public function handleRequest($request) {
		$this->pushCurrent();
		$this->urlParams = $request->allParams();

		$this->init();

		// If the basic database hasn't been created, then build it.
		if(!DB::isActive() || !ClassInfo::hasTable('SiteTree')) {
			$this->response = new HTTPResponse();
			$this->redirect("dev/build?returnURL=" . (isset($_GET['url']) ? urlencode($_GET['url']) : ''));
			$this->popCurrent();
			return $this->response;
		}

		$result = $this->getNestedController();

		if(is_object($result) && $result instanceOf RequestHandler) {
			$result = $result->handleRequest($request);
		}

		$this->popCurrent();
		return $result;
	}

	public function init() {
		singleton('SiteTree')->extend('modelascontrollerInit', $this);

		Director::set_site_mode('site');
	}

	public function getNestedController() {
		if($this->urlParams['URLSegment']) {
			$SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']);
			$child = SiteTree::get_by_url($SQL_URLSegment);

			if(!$child) {
				if($child = $this->findOldPage($SQL_URLSegment)) {
					$url = Controller::join_links(
						Director::baseURL(),
						$child->URLSegment,
						(isset($this->urlParams['Action'])) ? $this->urlParams['Action'] : null,
						(isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null,
						(isset($this->urlParams['OtherID'])) ? $this->urlParams['OtherID'] : null
					);

					$response = new HTTPResponse();
					$response->redirect($url, 301);
					return $response;
				}

				$child = $this->get404Page();
			}

			if($child) {
				if(isset($_REQUEST['debug'])) Debug::message("Using record #$child->ID of type $child->class with URL {$this->urlParams['URLSegment']}");

				// set language
				if($child->Locale) Translatable::set_current_locale($child->Locale);

				$controllerClass = "{$child->class}_Controller";

				if($this->urlParams['Action'] && ClassInfo::exists($controllerClass.'_'.$this->urlParams['Action'])) {
					$controllerClass = $controllerClass.'_'.$this->urlParams['Action'];
				}

				if(ClassInfo::exists($controllerClass)) {
					$controller = new $controllerClass($child);
				} else {
					$controller = $child;
				}

				return $controller;
			} else {
				return new HTTPResponse("The requested page couldn't be found.",404);
			}

		} else {
			user_error("ModelAsController not geting a URLSegment.  It looks like the site isn't redirecting to home", E_USER_ERROR);
		}
	}

	protected function findOldPage($urlSegment) {
		// Build the query by  replacing `SiteTree` with `SiteTree_versions` in a regular query.
		// Note that this should *really* be handled by a more full-featured data mapper; as it stands
		// this is a bit of a hack.
		$origStage = Versioned::current_stage();
		Versioned::reading_stage('Stage');
		$versionedQuery = singleton('SiteTree')->extendedSQL('');
		Versioned::reading_stage($origStage);

		foreach($versionedQuery->from as $k => $v) {
			$versionedQuery->renameTable($k, $k . '_versions');
		}
		$versionedQuery->select = array("`SiteTree_versions`.RecordID");
		$versionedQuery->where[] = "`SiteTree_versions`.`WasPublished` = 1 AND `URLSegment` = '$urlSegment'";
		$versionedQuery->orderby = '`LastEdited` DESC, `SiteTree_versions`.`WasPublished`';
		$versionedQuery->limit = 1;

		$result = $versionedQuery->execute();

		if($result->numRecords() == 1 && $redirectPage = $result->nextRecord()) {
			$redirectObj = DataObject::get_by_id('SiteTree', $redirectPage['RecordID']);
			if($redirectObj) {
				// Double-check by querying this page in the same way that getNestedController() does.  This
				// will prevent query muck-ups from modules such as subsites
				$doubleCheck = SiteTree::get_by_url($redirectObj->URLSegment);
				if($doubleCheck) return $redirectObj;
			}
		}

		return false;
	}

	protected function get404Page() {
		$page = DataObject::get_one("ErrorPage", "`ErrorCode` = '404'");
		if($page) {
			return $page;
		} else {
			// @deprecated 2.5 Use ErrorPage class
			return DataObject::get_one("SiteTree", "`URLSegment` = '404'");
		}
	}
}

?>


text:
package com.google.inject;

import com.google.inject.spi.Element;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.TypeConverterBinding;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Builds the graphs of objects that make up your application. The injector tracks the dependencies
 * for each type and uses bindings to inject them. This is the core of Guice, although you rarely
 * interact with it directly. This "behind-the-scenes" operation is what distinguishes dependency
 * injection from its cousin, the service locator pattern.
 *
 *
Contains several default bindings:
 *
 *

 *
This {@link Injector} instance itself
 *
A {@code Provider<T>} for each binding of type {@code T}
 *
The {@link java.util.logging.Logger} for the class being injected
 *
The {@link Stage} in which the Injector was created
 *

 *
 * Injectors are created using the facade class {@link Guice}.
 *
 *
An injector can also {@link #injectMembers(Object) inject the dependencies} of
 * already-constructed instances. This can be used to interoperate with objects created by other
 * frameworks or services.
 *
 *
Injectors can be {@link #createChildInjector(Iterable) hierarchical}. Child injectors inherit
 * the configuration of their parent injectors, but the converse does not hold.
 *
 *
The injector's {@link #getBindings() internal bindings} are available for introspection. This
 * enables tools and extensions to operate on an injector reflectively.
 *
 * @author crazybob@google.com (Bob Lee)
 * @author jessewilson@google.com (Jesse Wilson)
 */
public interface Injector {

  /**
   * Injects dependencies into the fields and methods of {@code instance}. Ignores the presence or
   * absence of an injectable constructor.
   *
   *
Whenever Guice creates an instance, it performs this injection automatically (after first
   * performing constructor injection), so if you're able to let Guice create all your objects for
   * you, you'll never need to use this method.
   *
   * @param instance to inject members on
   * @see Binder#getMembersInjector(Class) for a preferred alternative that supports checks before
   *     run time
   */
  void injectMembers(Object instance);

  /**
   * Returns the members injector used to inject dependencies into methods and fields on instances
   * of the given type {@code T}.
   *
   * @param typeLiteral type to get members injector for
   * @see Binder#getMembersInjector(TypeLiteral) for an alternative that offers up front error
   *     detection
   * @since 2.0
   */
  <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral);

  /**
   * Returns the members injector used to inject dependencies into methods and fields on instances
   * of the given type {@code T}. When feasible, use {@link Binder#getMembersInjector(TypeLiteral)}
   * instead to get increased up front error detection.
   *
   * @param type type to get members injector for
   * @see Binder#getMembersInjector(Class) for an alternative that offers up front error detection
   * @since 2.0
   */
  <T> MembersInjector<T> getMembersInjector(Class<T> type);

  /**
   * Returns this injector's explicit bindings.
   *
   *
The returned map does not include bindings inherited from a {@link #getParent() parent
   * injector}, should one exist. The returned map is guaranteed to iterate (for example, with its
   * {@link Map#entrySet()} iterator) in the order of insertion. In other words, the order in which
   * bindings appear in user Modules.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   */
  Map<Key<?>, Binding<?>> getBindings();

  /**
   * Returns a snapshot of this injector's bindings, both explicit and
   * just-in-time. The returned map is immutable; it contains only the bindings that were
   * present when {@code getAllBindings()} was invoked. Just-in-time bindings are only present if
   * they have been requested at least once. Subsequent calls may return a map with additional
   * just-in-time bindings.
   *
   *
The returned map does not include bindings inherited from a {@link #getParent() parent
   * injector}, should one exist.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 3.0
   */
  Map<Key<?>, Binding<?>> getAllBindings();

  /**
   * Returns the binding for the given injection key. This will be an explicit bindings if the key
   * was bound explicitly by a module, or an implicit binding otherwise. The implicit binding will
   * be created if necessary.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @throws ConfigurationException if this injector cannot find or create the binding.
   */
  <T> Binding<T> getBinding(Key<T> key);

  /**
   * Returns the binding for the given type. This will be an explicit bindings if the injection key
   * was bound explicitly by a module, or an implicit binding otherwise. The implicit binding will
   * be created if necessary.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @throws ConfigurationException if this injector cannot find or create the binding.
   * @since 2.0
   */
  <T> Binding<T> getBinding(Class<T> type);

  /**
   * Returns the binding if it already exists, or null if does not exist. Unlike {@link
   * #getBinding(Key)}, this does not attempt to create just-in-time bindings for keys that aren't
   * bound.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 3.0
   */
  <T> Binding<T> getExistingBinding(Key<T> key);

  /**
   * Returns all explicit bindings for {@code type}.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   */
  <T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type);

  /**
   * Returns the provider used to obtain instances for the given injection key. When feasible, avoid
   * using this method, in favor of having Guice inject your dependencies ahead of time.
   *
   * @throws ConfigurationException if this injector cannot find or create the provider.
   * @see Binder#getProvider(Key) for an alternative that offers up front error detection
   */
  <T> Provider<T> getProvider(Key<T> key);

  /**
   * Returns the provider used to obtain instances for the given type. When feasible, avoid using
   * this method, in favor of having Guice inject your dependencies ahead of time.
   *
   * @throws ConfigurationException if this injector cannot find or create the provider.
   * @see Binder#getProvider(Class) for an alternative that offers up front error detection
   */
  <T> Provider<T> getProvider(Class<T> type);

  /**
   * Returns the appropriate instance for the given injection key; equivalent to {@code
   * getProvider(key).get()}. When feasible, avoid using this method, in favor of having Guice
   * inject your dependencies ahead of time.
   *
   * @throws ConfigurationException if this injector cannot find or create the provider.
   * @throws ProvisionException if there was a runtime failure while providing an instance.
   */
  <T> T getInstance(Key<T> key);

  /**
   * Returns the appropriate instance for the given injection type; equivalent to {@code
   * getProvider(type).get()}. When feasible, avoid using this method, in favor of having Guice
   * inject your dependencies ahead of time.
   *
   * @throws ConfigurationException if this injector cannot find or create the provider.
   * @throws ProvisionException if there was a runtime failure while providing an instance.
   */
  <T> T getInstance(Class<T> type);

  /**
   * Returns this injector's parent, or {@code null} if this is a top-level injector.
   *
   * @since 2.0
   */
  Injector getParent();

  /**
   * Returns a new injector that inherits all state from this injector. All bindings, scopes,
   * interceptors and type converters are inherited -- they are visible to the child injector.
   * Elements of the child injector are not visible to its parent.
   *
   *
Just-in-time bindings created for child injectors will be created in an ancestor injector
   * whenever possible. This allows for scoped instances to be shared between injectors. Use
   * explicit bindings to prevent bindings from being shared with the parent injector. Optional
   * injections in just-in-time bindings (created in the parent injector) may be silently ignored if
   * the optional dependencies are from the child injector.
   *
   *
No key may be bound by both an injector and one of its ancestors. This includes just-in-time
   * bindings. The lone exception is the key for {@code Injector.class}, which is bound by each
   * injector to itself.
   *
   * @since 2.0
   */
  Injector createChildInjector(Iterable<? extends Module> modules);

  /**
   * Returns a new injector that inherits all state from this injector. All bindings, scopes,
   * interceptors and type converters are inherited -- they are visible to the child injector.
   * Elements of the child injector are not visible to its parent.
   *
   *
Just-in-time bindings created for child injectors will be created in an ancestor injector
   * whenever possible. This allows for scoped instances to be shared between injectors. Use
   * explicit bindings to prevent bindings from being shared with the parent injector.
   *
   *
No key may be bound by both an injector and one of its ancestors. This includes just-in-time
   * bindings. The lone exception is the key for {@code Injector.class}, which is bound by each
   * injector to itself.
   *
   * @since 2.0
   */
  Injector createChildInjector(Module... modules);

  /**
   * Returns a map containing all scopes in the injector. The maps keys are scoping annotations like
   * {@code Singleton.class}, and the values are scope instances, such as {@code Scopes.SINGLETON}.
   * The returned map is immutable.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 3.0
   */
  Map<Class<? extends Annotation>, Scope> getScopeBindings();

  /**
   * Returns a set containing all type converter bindings in the injector. The returned set is
   * immutable.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 3.0
   */
  Set<TypeConverterBinding> getTypeConverterBindings();

  /**
   * Returns the elements that make up this injector. Note that not all kinds of elements are
   * returned.
   *
   *
The returned list does not include elements inherited from a {@link #getParent() parent
   * injector}, should one exist.
   *
   *
The returned list is immutable; it contains only the elements that were present when {@link
   * #getElements} was invoked. Subsequent calls may return a list with additional elements.
   *
   *
The returned list does not include data inherited from a {@link #getParent() parent
   * injector}, should one exist.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 5.0
   */
  List<Element> getElements();

  /**
   * Returns the injection points created for calls to {@link #getMembersInjector} (either directly
   * or indirectly, e.g. through {@link #injectMembers}.
   *
   *
This excludes any injection points from elements (which are accessible from each element via
   * the SPI), unless {@link #getMembersInjector} or {@link #injectMembers} were also called for the
   * same key.
   *
   *
The returned multimap does not include data inherited from a {@link #getParent() parent
   * injector}, should one exist.
   *
   *
This method is part of the Guice SPI and is intended for use by tools and extensions.
   *
   * @since 5.0
   */
  Map<TypeLiteral<?>, List<InjectionPoint>> getAllMembersInjectorInjectionPoints();
}


text:
<form method="POST" enctype="multipart/form-data">

                <?php foreach($product as $product){ ?>

 Edit Product

                             Image
                             <input type="file" name="product_image" id="product_image_upload" size="0" onchange="preview_image();">

                                  <?php if($image_exists){ ?>
                                    <img src="<?php echo base_url(); ?><?php echo $image ?>" id="image_show">
                                  <?php }  else { ?>
                                    <img src="<?php echo base_url(); ?>./Image/no_image_preview.png" id="image_show">
                                  <?php } ?>

                             Product Name
                             <input type="text" name="product_name" value="<?php echo $product->product_name; ?>" required>

                             Product Price
                             <input type="number" name="product_price" value="<?php echo $product->product_price; ?>" step="0.01" min="0" value="0">

                             Product Description
                             <textarea name="product_description"><?php echo $product->product_description; ?>
                                </textarea>

                             Product Brief Description
                             <textarea name="product_brief_description"><?php echo $product->product_brief_description; ?>
                                </textarea>

                             Product Ingredients

                                <input type="text" id="ingredient_input">

                             Ingredients Lists

                                        <?php if($ingredient_exists){
                                            foreach($ingredients as $ingredient) {?>
                                        <li onclick="remove_ingredient(this.id)" value="<?php echo $ingredient->id; ?>" id="ingredient_<?php echo $ingredient->id; ?>" class="ingredient_arrangement"><?php echo $ingredient->name; ?>

                                        <input type="hidden" name="ingredients_bucket[]" value="<?php echo $ingredient->id; ?>" id="input_ingredient_<?php echo $ingredient->ingredient_id; ?>">
                                        <?php } } ?>

                            <button class="btn-primary">Edit </button>

                <?php } ?>

        </form>


text:
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { MatChipInputEvent } from '@angular/material/chips';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { select, Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { maybeDispatchAction, MediaType } from '@oca/web-shared';
import { IFormBuilder, IFormGroup } from '@rxweb/types';
import { combineLatest, Observable, ReplaySubject, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, take, takeUntil } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { AVATAR_PLACEHOLDER, DEFAULT_LOGO_URL } from '../../../consts';
import { AvailableOtherPlaceType, AvailablePlaceType, BrandingSettings, Country } from '../../../shared/interfaces/oca';
import {
  GetAvailablePlaceTypesAction,
  GetBrandingSettingsAction,
  GetCountriesAction,
  UpdateAvatarAction,
  UpdateLogoAction,
} from '../../../shared/shared.actions';
import {
  getAvailablePlaceTypes,
  getAvailablePlaceTypesState,
  getBrandingSettings,
  getCountries,
  isBrandingSettingsLoading,
  isPlaceTypesLoading,
} from '../../../shared/shared.state';
import { UploadedFileResult, UploadFileDialogComponent, UploadFileDialogConfig } from '../../../shared/upload-file';
import { filterNull, markAllControlsAsDirty } from '../../../shared/util';
import { GetServiceInfoAction, UpdateServiceInfoAction } from '../../settings.actions';
import { getServiceInfo, isServiceInfoLoading, SettingsState } from '../../settings.state';
import { CURRENCIES, TIMEZONES } from '../constants';
import { ServiceInfo, ServiceInfoSyncProvider, SyncedFields } from '../service-info';

const DEFAULT_SYNCED_VALUES: { [T in SyncedFields]: null } = {
  name: null,
  description: null,
  addresses: null,
  email_addresses: null,
  phone_numbers: null,
  websites: null,
};

@Component({
  selector: 'oca-service-info-page',
  templateUrl: './service-info-page.component.html',
  styleUrls: ['./service-info-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServiceInfoPageComponent implements OnInit, OnDestroy {
  loading$: Observable<boolean>;
  brandingSettings$: Observable<BrandingSettings>;
  timezones = TIMEZONES;
  currencies = CURRENCIES;
  DEFAULT_AVATAR_URL = AVATAR_PLACEHOLDER;
  DEFAULT_LOGO_URL = DEFAULT_LOGO_URL;
  placeTypes$: Observable<AvailablePlaceType[]>;
  otherPlaceTypes$: ReplaySubject<AvailableOtherPlaceType[]> = new ReplaySubject();
  countries$: Observable<Country[]>;
  syncedValues: { [T in SyncedFields]: ServiceInfoSyncProvider | null } = DEFAULT_SYNCED_VALUES;
  submitted = false;
  formGroup: IFormGroup<ServiceInfo>;
  saveErrorMessage$ = new Subject<string>();
  uploadFileDialogConfig: Partial<UploadFileDialogConfig> = {
    uploadPrefix: '',
    gallery: { prefix: 'logo' },
  };

  private destroyed$ = new Subject();
  private formBuilder: IFormBuilder;

  constructor(private store: Store<SettingsState>,
              private translate: TranslateService,
              private matDialog: MatDialog,
              fb: FormBuilder) {
    this.formBuilder = fb;
    this.formGroup = this.formBuilder.group<ServiceInfo>({
      media: this.formBuilder.control([]),
      websites: this.formBuilder.control([]),
      name: this.formBuilder.control('', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]),
      timezone: this.formBuilder.control('', Validators.required),
      phone_numbers: this.formBuilder.control([]),
      email_addresses: this.formBuilder.control([]),
      description: this.formBuilder.control(''),
      currency: this.formBuilder.control('', Validators.required),
      addresses: this.formBuilder.control([]),
      keywords: this.formBuilder.control([]),
      main_place_type: this.formBuilder.control(null, Validators.required),
      place_types: this.formBuilder.control([], Validators.required),
      synced_fields: this.formBuilder.control([]),
      visible: this.formBuilder.control(true),
    });
  }

  ngOnInit() {
    this.store.dispatch(new GetServiceInfoAction());
    this.store.dispatch(new GetBrandingSettingsAction());
    maybeDispatchAction(this.store, getAvailablePlaceTypesState, new GetAvailablePlaceTypesAction());
    this.placeTypes$ = this.store.pipe(select(getAvailablePlaceTypes));
    this.placeTypes$.pipe(takeUntil(this.destroyed$)).subscribe(() => this.setOtherPlaceTypes());
    this.store.pipe(select(getServiceInfo), takeUntil(this.destroyed$)).subscribe(serviceInfo => {
      if (serviceInfo) {
        this.formGroup.setValue(serviceInfo, { emitEvent: false });
        const newSyncedValues: { [T in SyncedFields]: ServiceInfoSyncProvider | null } = { ...DEFAULT_SYNCED_VALUES };
        for (const field of serviceInfo.synced_fields) {
          newSyncedValues[ field.key ] = field.provider;
        }
        this.syncedValues = newSyncedValues;
        this.setOtherPlaceTypes();
      }
    });
    this.brandingSettings$ = this.store.pipe(select(getBrandingSettings), filterNull());
    this.loading$ = combineLatest([
      this.store.pipe(select(isServiceInfoLoading)),
      this.store.pipe(select(isBrandingSettingsLoading)),
      this.store.pipe(select(isPlaceTypesLoading)),
    ]).pipe(map(results => results.some(r => r)));
    this.loading$.pipe(distinctUntilChanged(), takeUntil(this.destroyed$)).subscribe(loading => {
      if (loading) {
        this.formGroup.disable({ emitEvent: false });
      } else {
        this.formGroup.enable({ emitEvent: false });
        if (this.formGroup.invalid) {
          this.showErrors();
        }
      }
    });
    this.countries$ = this.store.pipe(select(getCountries));

    this.formGroup.controls.main_place_type.valueChanges.pipe(
      takeUntil(this.destroyed$),
    ).subscribe(mainPlaceType => this.mainPlaceTypeChanged(mainPlaceType));
    this.formGroup.valueChanges.pipe(
      debounceTime(environment.production ? 7500 : 2000),
      takeUntil(this.destroyed$),
    ).subscribe(() => this.save());
  }

  ngOnDestroy(): void {
    this.destroyed$.next();
    this.destroyed$.complete();
  }

  save() {
    if (this.formGroup.valid) {
      this.submitted = false;
      this.store.dispatch(new UpdateServiceInfoAction(this.formGroup.value as ServiceInfo));
      this.saveErrorMessage$.next('');
    } else {
      this.submitted = true;
      this.showErrors();
    }
  }

  mainPlaceTypeChanged(mainPlaceType: string | null) {
    const placeTypes = this.formGroup.value!.place_types as string[];
    if (mainPlaceType && !placeTypes.includes(mainPlaceType)) {
      this.formGroup.patchValue({ place_types: [mainPlaceType, ...placeTypes] });
    }
    this.setOtherPlaceTypes();
  }

  removeKeyword(keyword: string) {
    this.formGroup.patchValue({ keywords: this.formGroup.value!.keywords.filter((k: string) => k !== keyword) });
  }

  addKeyword($event: MatChipInputEvent) {
    const value = $event.value.trim();
    const currentKeywords = this.formGroup.value!.keywords;
    if (value && !currentKeywords.includes(value)) {
      this.formGroup.patchValue({ keywords: [...currentKeywords, value] });
    }
    $event.input.value = '';
  }

  updateAvatar() {
    const dialog = this.updateImage(250, 250, {
      title: this.translate.instant('oca.Change logo'),
      uploadPrefix: 'branding/avatar',
      listPrefix: 'branding/avatar',
      gallery: { prefix: 'avatar' },
    });
    dialog.afterClosed().subscribe((result: UploadedFileResult | null) => {
      if (result) {
        this.store.dispatch(new UpdateAvatarAction({ avatar_url: result.url }));
      }
    });
  }

  updateLogo() {
    const dialog = this.updateImage(1440, 540, {
      title: this.translate.instant('oca.change_cover_photo'),
      uploadPrefix: 'branding/logo',
      listPrefix: 'branding/logo',
      gallery: { prefix: 'logo' },
      croppedImageType: 'image/jpeg',
    });
    dialog.afterClosed().subscribe((result: UploadedFileResult | null) => {
      if (result) {
        this.store.dispatch(new UpdateLogoAction({ logo_url: result.url }));
      }
    });
  }

  updateImage(width: number, height: number,
              partialConfig: Pick<UploadFileDialogConfig, 'title' | 'uploadPrefix' | 'listPrefix' | 'gallery'| 'croppedImageType'>) {
    const config: MatDialogConfig<UploadFileDialogConfig> = {
      data: {
        mediaType: MediaType.IMAGE,
        cropOptions: {
          dragMode: 'crop',
          rotatable: true,
          autoCropArea: 1.0,
          aspectRatio: width / height,
        },
        croppedCanvasOptions: {
          width,
          height,
          imageSmoothingEnabled: true,
          imageSmoothingQuality: 'high',
        },
        reference: { type: 'branding_settings' },
        ...partialConfig,
      },
    };
    return this.matDialog.open(UploadFileDialogComponent, config);
  }

  private showErrors() {
    markAllControlsAsDirty(this.formGroup);
    this.saveErrorMessage$.next(this.translate.instant('oca.please_fill_in_required_fields'));
  }

  requestCountries() {
    this.countries$.pipe(take(1)).subscribe(countries => {
      if (!countries.length) {
        this.store.dispatch(new GetCountriesAction());
      }
    });
  }

  private setOtherPlaceTypes() {
    this.placeTypes$.pipe(take(1), takeUntil(this.destroyed$)).subscribe(types => {
      const mainType = this.formGroup.value!.main_place_type;
      this.otherPlaceTypes$.next(types.map(p => ({ ...p, disabled: mainType === p.value })));
    });
  }
}


text:
import os
import ssl
import sys
import types
from functools import partial
from pathlib import Path
from unittest.mock import patch

import click
import pytest
from _pytest.monkeypatch import notset
from click.testing import CliRunner

from flask import Blueprint
from flask import current_app
from flask import Flask
from flask.cli import AppGroup
from flask.cli import DispatchingApp
from flask.cli import dotenv
from flask.cli import find_best_app
from flask.cli import FlaskGroup
from flask.cli import get_version
from flask.cli import load_dotenv
from flask.cli import locate_app
from flask.cli import main as cli_main
from flask.cli import NoAppException
from flask.cli import prepare_import
from flask.cli import run_command
from flask.cli import ScriptInfo
from flask.cli import with_appcontext

cwd = Path.cwd()
test_path = (Path(__file__) / ".." / "test_apps").resolve()

@pytest.fixture
def runner():
    return CliRunner()

def test_cli_name(test_apps):
    """Make sure the CLI object's name is the app's name and not the app itself"""
    from cliapp.app import testapp

    assert testapp.cli.name == testapp.name

def test_find_best_app(test_apps):
    script_info = ScriptInfo()

    class Module:
        app = Flask("appname")

    assert find_best_app(script_info, Module) == Module.app

    class Module:
        application = Flask("appname")

    assert find_best_app(script_info, Module) == Module.application

    class Module:
        myapp = Flask("appname")

    assert find_best_app(script_info, Module) == Module.myapp

    class Module:
        @staticmethod
        def create_app():
            return Flask("appname")

    app = find_best_app(script_info, Module)
    assert isinstance(app, Flask)
    assert app.name == "appname"

    class Module:
        @staticmethod
        def create_app(**kwargs):
            return Flask("appname")

    app = find_best_app(script_info, Module)
    assert isinstance(app, Flask)
    assert app.name == "appname"

    class Module:
        @staticmethod
        def create_app(foo):
            return Flask("appname")

    with pytest.deprecated_call(match="Script info"):
        app = find_best_app(script_info, Module)

    assert isinstance(app, Flask)
    assert app.name == "appname"

    class Module:
        @staticmethod
        def create_app(foo=None, script_info=None):
            return Flask("appname")

    with pytest.deprecated_call(match="script_info"):
        app = find_best_app(script_info, Module)

    assert isinstance(app, Flask)
    assert app.name == "appname"

    class Module:
        @staticmethod
        def make_app():
            return Flask("appname")

    app = find_best_app(script_info, Module)
    assert isinstance(app, Flask)
    assert app.name == "appname"

    class Module:
        myapp = Flask("appname1")

        @staticmethod
        def create_app():
            return Flask("appname2")

    assert find_best_app(script_info, Module) == Module.myapp

    class Module:
        myapp = Flask("appname1")

        @staticmethod
        def create_app():
            return Flask("appname2")

    assert find_best_app(script_info, Module) == Module.myapp

    class Module:
        pass

    pytest.raises(NoAppException, find_best_app, script_info, Module)

    class Module:
        myapp1 = Flask("appname1")
        myapp2 = Flask("appname2")

    pytest.raises(NoAppException, find_best_app, script_info, Module)

    class Module:
        @staticmethod
        def create_app(foo, bar):
            return Flask("appname2")

    pytest.raises(NoAppException, find_best_app, script_info, Module)

    class Module:
        @staticmethod
        def create_app():
            raise TypeError("bad bad factory!")

    pytest.raises(TypeError, find_best_app, script_info, Module)

@pytest.mark.parametrize(
    "value,path,result",
    (
        ("test", cwd, "test"),
        ("test.py", cwd, "test"),
        ("a/test", cwd / "a", "test"),
        ("test/__init__.py", cwd, "test"),
        ("test/__init__", cwd, "test"),
        # nested package
        (
            test_path / "cliapp" / "inner1" / "__init__",
            test_path,
            "cliapp.inner1",
        ),
        (
            test_path / "cliapp" / "inner1" / "inner2",
            test_path,
            "cliapp.inner1.inner2",
        ),
        # dotted name
        ("test.a.b", cwd, "test.a.b"),
        (test_path / "cliapp.app", test_path, "cliapp.app"),
        # not a Python file, will be caught during import
        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),
    ),
)
def test_prepare_import(request, value, path, result):
    """Expect the correct path to be set and the correct import and app names
    to be returned.

    :func:`prepare_exec_for_file` has a side effect where the parent directory
    of the given import is added to :data:`sys.path`. This is reset after the
    test runs.
    """
    original_path = sys.path[:]

    def reset_path():
        sys.path[:] = original_path

    request.addfinalizer(reset_path)

    assert prepare_import(value) == result
    assert sys.path[0] == str(path)

@pytest.mark.parametrize(
    "iname,aname,result",
    (
        ("cliapp.app", None, "testapp"),
        ("cliapp.app", "testapp", "testapp"),
        ("cliapp.factory", None, "app"),
        ("cliapp.factory", "create_app", "app"),
        ("cliapp.factory", "create_app()", "app"),
        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),
        # trailing comma space
        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),
        # strip whitespace
        ("cliapp.factory", " create_app () ", "app"),
    ),
)
def test_locate_app(test_apps, iname, aname, result):
    info = ScriptInfo()
    assert locate_app(info, iname, aname).name == result

@pytest.mark.parametrize(
    "iname,aname",
    (
        ("notanapp.py", None),
        ("cliapp/app", None),
        ("cliapp.app", "notanapp"),
        # not enough arguments
        ("cliapp.factory", 'create_app2("foo")'),
        # invalid identifier
        ("cliapp.factory", "create_app("),
        # no app returned
        ("cliapp.factory", "no_app"),
        # nested import error
        ("cliapp.importerrorapp", None),
        # not a Python file
        ("cliapp.message.txt", None),
    ),
)
def test_locate_app_raises(test_apps, iname, aname):
    info = ScriptInfo()

    with pytest.raises(NoAppException):
        locate_app(info, iname, aname)

def test_locate_app_suppress_raise(test_apps):
    info = ScriptInfo()
    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)
    assert app is None

    # only direct import error is suppressed
    with pytest.raises(NoAppException):
        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)

def test_get_version(test_apps, capsys):
    from flask import __version__ as flask_version
    from werkzeug import __version__ as werkzeug_version
    from platform import python_version

    class MockCtx:
        resilient_parsing = False
        color = None

        def exit(self):
            return

    ctx = MockCtx()
    get_version(ctx, None, "test")
    out, err = capsys.readouterr()
    assert f"Python {python_version()}" in out
    assert f"Flask {flask_version}" in out
    assert f"Werkzeug {werkzeug_version}" in out

def test_scriptinfo(test_apps, monkeypatch):
    obj = ScriptInfo(app_import_path="cliapp.app:testapp")
    app = obj.load_app()
    assert app.name == "testapp"
    assert obj.load_app() is app

    # import app with module's absolute path
    cli_app_path = str(test_path / "cliapp" / "app.py")

    obj = ScriptInfo(app_import_path=cli_app_path)
    app = obj.load_app()
    assert app.name == "testapp"
    assert obj.load_app() is app
    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")
    app = obj.load_app()
    assert app.name == "testapp"
    assert obj.load_app() is app

    def create_app():
        return Flask("createapp")

    obj = ScriptInfo(create_app=create_app)
    app = obj.load_app()
    assert app.name == "createapp"
    assert obj.load_app() is app

    obj = ScriptInfo()
    pytest.raises(NoAppException, obj.load_app)

    # import app from wsgi.py in current directory
    monkeypatch.chdir(test_path / "helloworld")
    obj = ScriptInfo()
    app = obj.load_app()
    assert app.name == "hello"

    # import app from app.py in current directory
    monkeypatch.chdir(test_path / "cliapp")
    obj = ScriptInfo()
    app = obj.load_app()
    assert app.name == "testapp"

def test_lazy_load_error(monkeypatch):
    """When using lazy loading, the correct exception should be
    re-raised.
    """

    class BadExc(Exception):
        pass

    def bad_load():
        raise BadExc

    lazy = DispatchingApp(bad_load, use_eager_loading=False)

    with pytest.raises(BadExc):
        lazy._flush_bg_loading_exception()

def test_with_appcontext(runner):
    @click.command()
    @with_appcontext
    def testcmd():
        click.echo(current_app.name)

    obj = ScriptInfo(create_app=lambda: Flask("testapp"))

    result = runner.invoke(testcmd, obj=obj)
    assert result.exit_code == 0
    assert result.output == "testapp\n"

def test_appgroup(runner):
    @click.group(cls=AppGroup)
    def cli():
        pass

    @cli.command(with_appcontext=True)
    def test():
        click.echo(current_app.name)

    @cli.group()
    def subgroup():
        pass

    @subgroup.command(with_appcontext=True)
    def test2():
        click.echo(current_app.name)

    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))

    result = runner.invoke(cli, ["test"], obj=obj)
    assert result.exit_code == 0
    assert result.output == "testappgroup\n"

    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)
    assert result.exit_code == 0
    assert result.output == "testappgroup\n"

def test_flaskgroup(runner):
    def create_app():
        return Flask("flaskgroup")

    @click.group(cls=FlaskGroup, create_app=create_app)
    def cli(**params):
        pass

    @cli.command()
    def test():
        click.echo(current_app.name)

    result = runner.invoke(cli, ["test"])
    assert result.exit_code == 0
    assert result.output == "flaskgroup\n"

@pytest.mark.parametrize("set_debug_flag", (True, False))
def test_flaskgroup_debug(runner, set_debug_flag):
    def create_app():
        app = Flask("flaskgroup")
        app.debug = True
        return app

    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)
    def cli(**params):
        pass

    @cli.command()
    def test():
        click.echo(str(current_app.debug))

    result = runner.invoke(cli, ["test"])
    assert result.exit_code == 0
    assert result.output == f"{not set_debug_flag}\n"

def test_no_command_echo_loading_error():
    from flask.cli import cli

    runner = CliRunner(mix_stderr=False)
    result = runner.invoke(cli, ["missing"])
    assert result.exit_code == 2
    assert "FLASK_APP" in result.stderr
    assert "Usage:" in result.stderr

def test_help_echo_loading_error():
    from flask.cli import cli

    runner = CliRunner(mix_stderr=False)
    result = runner.invoke(cli, ["--help"])
    assert result.exit_code == 0
    assert "FLASK_APP" in result.stderr
    assert "Usage:" in result.stdout

def test_help_echo_exception():
    def create_app():
        raise Exception("oh no")

    cli = FlaskGroup(create_app=create_app)
    runner = CliRunner(mix_stderr=False)
    result = runner.invoke(cli, ["--help"])
    assert result.exit_code == 0
    assert "Exception: oh no" in result.stderr
    assert "Usage:" in result.stdout

class TestRoutes:
    @pytest.fixture
    def invoke(self, runner):
        def create_app():
            app = Flask(__name__)
            app.testing = True

            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])
            def yyy_get_post(x, y):
                pass

            @app.route("/zzz_post", methods=["POST"])
            def aaa_post():
                pass

            return app

        cli = FlaskGroup(create_app=create_app)
        return partial(runner.invoke, cli)

    @pytest.fixture
    def invoke_no_routes(self, runner):
        def create_app():
            app = Flask(__name__, static_folder=None)
            app.testing = True

            return app

        cli = FlaskGroup(create_app=create_app)
        return partial(runner.invoke, cli)

    def expect_order(self, order, output):
        # skip the header and match the start of each row
        for expect, line in zip(order, output.splitlines()[2:]):
            # do this instead of startswith for nicer pytest output
            assert line[: len(expect)] == expect

    def test_simple(self, invoke):
        result = invoke(["routes"])
        assert result.exit_code == 0
        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)

    def test_sort(self, invoke):
        default_output = invoke(["routes"]).output
        endpoint_output = invoke(["routes", "-s", "endpoint"]).output
        assert default_output == endpoint_output
        self.expect_order(
            ["static", "yyy_get_post", "aaa_post"],
            invoke(["routes", "-s", "methods"]).output,
        )
        self.expect_order(
            ["yyy_get_post", "static", "aaa_post"],
            invoke(["routes", "-s", "rule"]).output,
        )
        self.expect_order(
            ["aaa_post", "yyy_get_post", "static"],
            invoke(["routes", "-s", "match"]).output,
        )

    def test_all_methods(self, invoke):
        output = invoke(["routes"]).output
        assert "GET, HEAD, OPTIONS, POST" not in output
        output = invoke(["routes", "--all-methods"]).output
        assert "GET, HEAD, OPTIONS, POST" in output

    def test_no_routes(self, invoke_no_routes):
        result = invoke_no_routes(["routes"])
        assert result.exit_code == 0
        assert "No routes were registered." in result.output

need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")

@need_dotenv
def test_load_dotenv(monkeypatch):
    # can't use monkeypatch.delitem since the keys don't exist yet
    for item in ("FOO", "BAR", "SPAM", "HAM"):
        monkeypatch._setitem.append((os.environ, item, notset))

    monkeypatch.setenv("EGGS", "3")
    monkeypatch.chdir(test_path)
    assert load_dotenv()
    assert Path.cwd() == test_path
    # .flaskenv doesn't overwrite .env
    assert os.environ["FOO"] == "env"
    # set only in .flaskenv
    assert os.environ["BAR"] == "bar"
    # set only in .env
    assert os.environ["SPAM"] == "1"
    # set manually, files don't overwrite
    assert os.environ["EGGS"] == "3"
    # test env file encoding
    assert os.environ["HAM"] == "火腿"
    # Non existent file should not load
    assert not load_dotenv("non-existent-file")

@need_dotenv
def test_dotenv_path(monkeypatch):
    for item in ("FOO", "BAR", "EGGS"):
        monkeypatch._setitem.append((os.environ, item, notset))

    load_dotenv(test_path / ".flaskenv")
    assert Path.cwd() == cwd
    assert "FOO" in os.environ

def test_dotenv_optional(monkeypatch):
    monkeypatch.setattr("flask.cli.dotenv", None)
    monkeypatch.chdir(test_path)
    load_dotenv()
    assert "FOO" not in os.environ

@need_dotenv
def test_disable_dotenv_from_env(monkeypatch, runner):
    monkeypatch.chdir(test_path)
    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")
    runner.invoke(FlaskGroup())
    assert "FOO" not in os.environ

def test_run_cert_path():
    # no key
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", __file__])

    # no cert
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--key", __file__])

    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])
    assert ctx.params["cert"] == (__file__, __file__)

def test_run_cert_adhoc(monkeypatch):
    monkeypatch.setitem(sys.modules, "cryptography", None)

    # cryptography not installed
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "adhoc"])

    # cryptography installed
    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))
    ctx = run_command.make_context("run", ["--cert", "adhoc"])
    assert ctx.params["cert"] == "adhoc"

    # no key with adhoc
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])

def test_run_cert_import(monkeypatch):
    monkeypatch.setitem(sys.modules, "not_here", None)

    # ImportError
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "not_here"])

    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "flask"])

    # SSLContext
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)

    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)
    ctx = run_command.make_context("run", ["--cert", "ssl_context"])
    assert ctx.params["cert"] is ssl_context

    # no --key with SSLContext
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])

def test_run_cert_no_ssl(monkeypatch):
    monkeypatch.setattr("flask.cli.ssl", None)
    with pytest.raises(click.BadParameter):
        run_command.make_context("run", ["--cert", "not_here"])

def test_cli_blueprints(app):
    """Test blueprint commands register correctly to the application"""
    custom = Blueprint("custom", __name__, cli_group="customized")
    nested = Blueprint("nested", __name__)
    merged = Blueprint("merged", __name__, cli_group=None)
    late = Blueprint("late", __name__)

    @custom.cli.command("custom")
    def custom_command():
        click.echo("custom_result")

    @nested.cli.command("nested")
    def nested_command():
        click.echo("nested_result")

    @merged.cli.command("merged")
    def merged_command():
        click.echo("merged_result")

    @late.cli.command("late")
    def late_command():
        click.echo("late_result")

    app.register_blueprint(custom)
    app.register_blueprint(nested)
    app.register_blueprint(merged)
    app.register_blueprint(late, cli_group="late_registration")

    app_runner = app.test_cli_runner()

    result = app_runner.invoke(args=["customized", "custom"])
    assert "custom_result" in result.output

    result = app_runner.invoke(args=["nested", "nested"])
    assert "nested_result" in result.output

    result = app_runner.invoke(args=["merged"])
    assert "merged_result" in result.output

    result = app_runner.invoke(args=["late_registration", "late"])
    assert "late_result" in result.output

def test_cli_empty(app):
    """If a Blueprint's CLI group is empty, do not register it."""
    bp = Blueprint("blue", __name__, cli_group="blue")
    app.register_blueprint(bp)

    result = app.test_cli_runner().invoke(args=["blue", "--help"])
    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"

def test_click_7_deprecated():
    with patch("flask.cli.cli"):
        if int(click.__version__[0]) < 8:
            pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")
        else:
            cli_main()


text:
require_relative 'base_report'

module Reek
  module Report
    #
    # Saves the report as a HTML file
    #
    # @public
    #
    class HTMLReport < BaseReport
      require 'erb'

      # @public
      def show
        template_path = Pathname.new("#{__dir__}/html_report/html_report.html.erb")
        puts ERB.new(template_path.read).result(binding)
      end
    end
  end
end


text:
package com.amazonaws.services.kinesis.model.transform;

import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;

import com.amazonaws.services.kinesis.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DisableEnhancedMonitoringResult JSON Unmarshaller
 */
public class DisableEnhancedMonitoringResultJsonUnmarshaller implements
        Unmarshaller<DisableEnhancedMonitoringResult, JsonUnmarshallerContext> {

    public DisableEnhancedMonitoringResult unmarshall(
            JsonUnmarshallerContext context) throws Exception {
        DisableEnhancedMonitoringResult disableEnhancedMonitoringResult = new DisableEnhancedMonitoringResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("StreamName", targetDepth)) {
                    context.nextToken();
                    disableEnhancedMonitoringResult.setStreamName(context
                            .getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("CurrentShardLevelMetrics",
                        targetDepth)) {
                    context.nextToken();
                    disableEnhancedMonitoringResult
                            .setCurrentShardLevelMetrics(new ListUnmarshaller<String>(
                                    context.getUnmarshaller(String.class))
                                    .unmarshall(context));
                }
                if (context.testExpression("DesiredShardLevelMetrics",
                        targetDepth)) {
                    context.nextToken();
                    disableEnhancedMonitoringResult
                            .setDesiredShardLevelMetrics(new ListUnmarshaller<String>(
                                    context.getUnmarshaller(String.class))
                                    .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return disableEnhancedMonitoringResult;
    }

    private static DisableEnhancedMonitoringResultJsonUnmarshaller instance;

    public static DisableEnhancedMonitoringResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DisableEnhancedMonitoringResultJsonUnmarshaller();
        return instance;
    }
}


text:
namespace ustl {

/// Creates an output string stream linked to the given memory area.
ostringstream::ostringstream (void* p, size_t n) noexcept
: ostream()
,_buffer()
,_flags (0)
,_width (0)
,_base (10)
,_precision (2)
{
    exceptions (goodbit);
    link (p, n);
}

/// Creates an output string stream, initializing the buffer with v.
ostringstream::ostringstream (const string& v)
: ostream()
,_buffer (v)
,_flags (0)
,_width (0)
,_base (10)
,_precision (2)
{
    exceptions (goodbit);
    ostream::link (_buffer);
}

/// Copies \p s to the internal buffer.
void ostringstream::str (const string& s)
{
    _buffer = s;
    ostream::link (_buffer);
    SetPos (_buffer.size());
}

/// Writes a single character into the stream.
void ostringstream::iwrite (uint8_t v)
{
    if (remaining() >= 1 || overflow() >= 1)
  ostream::iwrite (v);
}

/// Writes the contents of \p buffer of \p size into the stream.
ostringstream& ostringstream::write (const void* buffer, size_type sz)
{
    const char* buf = (const char*) buffer;
    for (size_type bw = 0; (bw = min(sz, remaining() ? remaining() : overflow(sz))); buf += bw, sz -= bw)
  ostream::write (buf, bw);
    return *this;
}

/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const noexcept
{
    do {
  *fmt++ = '0' + n % 10;
    } while (n /= 10);
    return fmt;
}

/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
    *fmt++ = '%';
    if (_width)
  fmt = encode_dec (fmt, _width);
    if (_flags & left)
  *fmt++ = '-';
    if (!bInteger) {
  *fmt++ = '.';
  fmt = encode_dec (fmt, _precision);
    }
    while (*typestr)
  *fmt++ = *typestr++;
    if (bInteger) {
  if (_base == 16)
      fmt[-1] = 'X';
  else if (_base == 8)
      fmt[-1] = 'o';
    } else {
  if (_flags & scientific)
      fmt[-1] = 'E';
    }
    *fmt = 0;
}

/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
    char buffer [8];
    *utf8out(buffer) = v;
    write (buffer, Utf8Bytes(v));
}

/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
    static const char tf[2][8] = { "false", "true" };
    write (tf[v], 5 - v);
}

/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
    va_list args2;
#else
    #define args2 args
    #undef __va_copy
    #define __va_copy(x,y)
#endif
    int rv, space;
    do {
  space = remaining();
  __va_copy (args2, args);
  if (0 > (rv = vsnprintf (ipos(), space, fmt, args2)))
      return rv;
    } while (rv >= space && rv < (int)overflow(rv+1));
    SetPos (pos() + min (rv, space));
    return rv;
}

/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    const int rv = vformat (fmt, args);
    va_end (args);
    return rv;
}

/// Links to string \p l as resizable.
void ostringstream::link (void* p, size_type n) noexcept
{
    assert ((p || !n) && "The output string buffer must not be read-only");
    ostream::link (p, n);
    _buffer.link (p, n);
}

/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
    if (n > remaining()) {
  const uoff_t oldPos (pos());
  _buffer.reserve (oldPos + n, false);
  _buffer.resize (oldPos + n);
  ostream::link (_buffer);
  SetPos (oldPos);
    }
    verify_remaining ("write", "text", n);
    return remaining();
}

} // namespace ustl


text:
package com.jetbrains.python.refactoring.classes;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.psi.PyClass;
import com.jetbrains.python.psi.PyElement;
import com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo;
import com.jetbrains.python.refactoring.classes.membersManager.vp.MembersBasedPresenter;
import com.jetbrains.python.refactoring.classes.membersManager.vp.MembersBasedView;
import com.jetbrains.python.refactoring.classes.membersManager.vp.MembersViewInitializationInfo;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.internal.MocksControl;
import org.hamcrest.Matcher;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import java.util.Collection;

/**
 * Base class for {@link com.jetbrains.python.refactoring.classes.membersManager.vp.MembersBasedPresenter} tests.
 * It takes file
file.py
 from folder provided as "refactoringName" constructor argument.
 * It configures {@link #myView}
 *
 * @param <C> configuration class for presenter view
 * @param <V> presenter's view class
 * @author Ilya.Kazakevich
 */
public abstract class PyRefactoringPresenterTestCase<C extends MembersViewInitializationInfo, V extends MembersBasedView<C>>
  extends PyTestCase {
  /**
   * Converts class collection to name collection
   */
  protected static final Function<PyClass, String> CLASS_TO_NAME = new ClassToName();
  /**
   * Easy mock control
   */
  protected MocksControl myMocksControl;
  /**
   * View mock
   */
  protected V myView;
  /**
   * Capture that stores config ({@link MembersViewInitializationInfo} or its children) after {@link com.jetbrains.python.vp.Presenter#launch()} is called
   */
  protected Capture<C> myViewConfigCapture;

  @NotNull
  private final Class<V> myViewClass;
  @NotNull
  private final String myRefactoringName;

  /**
   * @param viewClass view class
   * @param refactoringName name of the refactoring. Folder with its name would be used to take "file.py" from it.
   */
  protected PyRefactoringPresenterTestCase(@NotNull final Class<V> viewClass, @NotNull final String refactoringName) {
    myViewClass = viewClass;
    this.myRefactoringName = refactoringName;
  }

  /**
   * Compares member states (names and other fields) with provided matcher.
   * @see  PyPresenterTestMemberEntry
   * @param members members to compare
   * @param matcher to match them against
   */
  protected static void compareMembers(@NotNull final Collection<PyPresenterTestMemberEntry> members,
                                       @NotNull final Matcher<Iterable<? extends PyPresenterTestMemberEntry>> matcher) {
    Assert.assertThat("Wrong members or their states", members, matcher);
  }

  /**
   * Initializes test. Always run it first if overwrite.
   */
  @Override
  public void setUp() throws Exception {
    super.setUp();

    myFixture.copyDirectoryToProject("refactoring/" + myRefactoringName + "/presenter/", "");
    myFixture.configureFromTempProjectFile("file.py");
    myMocksControl = new MocksControl(MocksControl.MockType.NICE);
    myView = myMocksControl.createMock(myViewClass);

    configureMockCapture();
  }

  /**
   * Configures view to capture config info
   */
  private void configureMockCapture() {
    myViewConfigCapture = new Capture<C>();

    myView.configure(EasyMock.capture(myViewConfigCapture));
    EasyMock.expectLastCall().once();
  }

  /**
   * @return collection of members displayed by presenter
   */
  @NotNull
  protected Collection<PyPresenterTestMemberEntry> getMembers() {
    Assert.assertTrue("No members captured", myViewConfigCapture.hasCaptured());
    final Collection<PyMemberInfo<PyElement>> members = myViewConfigCapture.getValue().getMemberInfos();
    Assert.assertFalse("No members selected", members.isEmpty());
    return Collections2.transform(members, new NameAndStatusTransformer(myViewConfigCapture.getValue().getMemberInfoModel()));
  }

  private static class ClassToName implements Function<PyClass, String> {

    @Override
    public String apply(@NotNull final PyClass input) {
      return input.getName();
    }
  }

  /**
   * Returns member infos presenter wants to display
   * @param presenter presenter to check
   * @return collection of member infos
   */
  @NotNull
  protected Collection<PyMemberInfo<PyElement>> getMemberInfos(@NotNull MembersBasedPresenter presenter) {
    myMocksControl.replay();
    presenter.launch();
    final Collection<PyMemberInfo<PyElement>> result = myViewConfigCapture.getValue().getMemberInfos();
    myMocksControl.reset();
    configureMockCapture();
    return result;
  }
}


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *     Mikael Lagerkvist <lagerkvist@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2004
 *     Mikael Lagerkvist, 2005
 *
 *  Last modified:
 *     $Date: 2008-08-22 18:36:11 +0900 (金, 22 8 2008) $ by $Author: tack $
 *     $Revision: 7678 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

namespace Gecode { namespace MiniModel {

  /**
   * \defgroup FuncThrowMiniModel MiniModel exceptions
   * \ingroup FuncThrow
   */

  //@{
  /// %Exception: Too few arguments available in argument array
  class GECODE_VTABLE_EXPORT TooFewArguments : public Exception  {
  public:
    /// Initialize with location \a l
    TooFewArguments(const char* l);
  };

  /// %Exception: Sizes of arguments does not match
  class GECODE_VTABLE_EXPORT ArgumentSizeMismatch : public Exception  {
  public:
    /// Initialize with location \a l
    ArgumentSizeMismatch(const char* l);
  };

  /// %Exception: Argument out of range
  class GECODE_VTABLE_EXPORT ArgumentOutOfRange : public Exception  {
  public:
    /// Initialize with location \a l
    ArgumentOutOfRange(const char* l);
  };
  //@}

  inline
  TooFewArguments::TooFewArguments(const char* l)
    : Exception(l,"Passed argument array has too few elements") {}

  inline
  ArgumentSizeMismatch::ArgumentSizeMismatch(const char* l)
    : Exception(l,"Sizes of argument arrays mismatch") {}

  inline
  ArgumentOutOfRange::ArgumentOutOfRange(const char* l)
    : Exception(l,"Argument out of range") {}

}}

// STATISTICS: minimodel-any