text:
package org.ikernits.lib.vaadin.builders;

import com.vaadin.ui.PasswordField;

@SuppressWarnings({"deprecation", "unused", "unchecked"})
public class PasswordFieldBuilder<T extends PasswordField, B extends PasswordFieldBuilder<T, B>> extends AbstractTextFieldBuilder<T, B> {

    public PasswordFieldBuilder(T delegate) {
        super(delegate);
    }

}


text:
package org.crazyit.intentProject5_2_2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ActionAttr extends Activity
{
	public final static String CRAZYIT_ACTION =
		"org.crazyit.intent.action.CRAZYIT_ACTION";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button bn = (Button) findViewById(R.id.bn);
		// Ϊbn°´Å¥°ó¶¨Ê¼þ¼àÌýÆ÷
		bn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				// ´´½¨Intent¶ÔÏó
				Intent intent = new Intent();
				// ΪIntentÉèÖÃActionÊôÐÔ£¨ÊôÐÔÖµ¾ÍÊÇÒ»¸öÆÕͨ×Ö·û´®£©
				intent.setAction(ActionAttr.CRAZYIT_ACTION);
				startActivity(intent);
			}
		});
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.tappe.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

public class Txqpg3 {
	public static void main(String[] args) throws IOException {
		String name = "";
		try {

			String urlName = "http://localhost:8080/xqpg/services/ExportDataCollectorService?wsdl";
			// String urlName =
			// "http://130.2.32.14:9080/xqpg/services/ExportDataCollectorService?wsdl";
			// urlName =
			// "http://130.2.32.14:9080/xqpg/services/ExportDataCollectorService";
			Service s = new Service();
			Call call = (Call) s.createCall();
			 call.setTimeout(new Integer(10000));

			File fileread = new File("xml.txt");

			// FileInputStream fis=new FileInputStream(fileread);
			FileReader read = new FileReader(fileread);

			BufferedReader br = new BufferedReader(read);
			int len = 0;
			String xml = "";
			br.read();
			urlName=br.readLine();
			urlName = urlName.trim();
			call.setTargetEndpointAddress(new URL(urlName));
			br.read();

			call.setOperationName(new QName(
					br.readLine().trim(), "xqpgOlderApply"));
			while ((len = br.read()) != -1) {
				String s1 = br.readLine();
				s1 = s1.trim();
				System.out.println(s1);
				xml += s1;
			}
			br.close();
			read.close();
			System.out.println(xml);

			// String xml = "<xqpg>" + "<name>钱云娥</name>"
			// + "<idcard>310223193609230845</idcard>"
			// + "<applytime>2016-06-24</applytime>" + "<gender>F</gender>"
			// + "<birth>1936-09-23</birth>" + "<marry>2</marry>"
			// + "<nation></nation>" + "<regarea>310113000000</regarea>"
			// + "<regneighbor>310113003000</regneighbor>"
			// + "<regvillage></regvillage>"
			// + "<regtext>宝钢九村13号405室</regtext>" + "<regzip></regzip>"
			// + "<regphone></regphone>" + "<mobile>13916321268</mobile>"
			// + "<livearea>310113000000</livearea>"
			// + "<liveneighbor>310113003000</liveneighbor>"
			// + "<livevillage></livevillage>"
			// + "<livetext>宝钢九村13号405室</livetext>" + "<monincome></monincome>"
			// + "<monolder></monolder>" + "<datasource>2</datasource>"
			// + "<healthlevel>5</healthlevel>" + "<econresult>4</econresult>"
			// + "<mateoldername></mateoldername>"
			// + "<mateidcard></mateidcard>" + "<matecon></matecon>"
			// + "</xqpg>";

			// String xml = "<xqpg>" + "<name>钱云鹅</name>"
			// + "<idcard>310223193609230845</idcard>"
			// + "<applytime>2016-06-24</applytime>" + "<gender>F</gender>"
			// + "<birth>1985-06-02</birth>" + "<marry>2</marry>"
			// + "<nation></nation>" + "<regarea>310113000000</regarea>"
			// + "<regneighbor>310113000000</regneighbor>"
			// + "<regvillage>310112108010</regvillage>"
			// + "<regtext></regtext>" + "<regzip></regzip>"
			// + "<regphone></regphone>" + "<mobile>11111111111</mobile>"
			// + "<livearea>310112000000</livearea>"
			// + "<liveneighbor>310112108000</liveneighbor>"
			// + "<livevillage>310112108010</livevillage>"
			// + "<livetext>eeeee</livetext>" + "<monincome>1234</monincome>"
			// + "<monolder>123</monolder>" + "<datasource>2</datasource>"
			// + "<healthlevel>3</healthlevel>" + "<econresult>3</econresult>"
			// + "<mateoldername></mateoldername>"
			// + "<mateidcard></mateidcard>" + "<matecon></matecon>"
			// + "</xqpg>";
			name = (String) call.invoke(new Object[] { xml });
			System.out.println(name);
		} catch (Exception e) {
			name=e.getMessage();
		}
		File file = new File("tt.txt");
		if (!file.exists())
			file.createNewFile();

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				file, true));
		osw.write(name+"\n");
		osw.flush();
		osw.close();

	}
}


text:
> Capture some or all of an X server screen, and save the image to a file.
> Part of the ImageMagick library.

- Capture the entire X server screen in the PostScript image format:

`import -window root {{output.postscript}}`

- Capture contents of a remote X server screen in the PNG image format:

`import -window root -display {{remote_host}}:{screen}.{display} {{output.png}}`

- Capture a specific window, given its ID as displayed by `xwininfo`, into the JPEG format:

`import -window {{window_id}} {{output.jpg}}`


text:
static struct {
    hashmap_t* registry;
    spin_lock_t lock;
} blockdev_subsystem;

#define REGISTRY blockdev_subsystem.registry
#define LOCK() spin_lock(&blockdev_subsystem.lock)
#define UNLOCK() spin_unlock(&blockdev_subsystem.lock)

void block_device_subsystem_init(void) {
    REGISTRY = hashmap_create(5);

    SET_SPIN_LOCK_LABEL(&blockdev_subsystem.lock, "Block Devices");

    block_device_mbr_subsystem_init();
    block_device_t* nulldev = null_block_dev_create("null");
    block_device_register(device_root(), nulldev);
}

block_device_t* block_device_create(char* name) {
    size_t name_size = strlen(name);

    if (name_size > 63) {
        printf(
            WARN "Failed to create block device "
                  "called '%s', name is bigger "
                  "than 63 characters.\n", name);
        return NULL;
    }

    block_device_t* device = zalloc(sizeof(block_device_t));
    memcpy(device->name, name, name_size);
    return device;
}

block_device_t* block_device_get(char* name) {
    LOCK();
    block_device_t* device = hashmap_get(REGISTRY, name);
    UNLOCK();
    return device;
}

list_t* block_device_get_all(void) {
    LOCK();
    list_t* block_devices = hashmap_values(REGISTRY);
    UNLOCK();
    return block_devices;
}

block_device_error_t block_device_register(
    device_entry_t* parent,
    block_device_t* device
) {
    LOCK();

    if (hashmap_has(REGISTRY, device->name)) {
        printf(
            WARN "Failed to register block device '%s': "
                 "device already exists!\n"
        );

        UNLOCK();
        return BLOCK_DEVICE_ERROR_EXISTS;
    }

    hashmap_set(REGISTRY, device->name, device);
    UNLOCK();

    event_dispatch_async(
        EVENT_BLOCK_DEVICE_INITIALIZED,
        device
    );

    device_register(
        parent,
        device->name,
        DEVICE_CLASS_BLOCK,
        device
    );

    return BLOCK_DEVICE_ERROR_OK;
}

block_device_error_t block_device_destroy(block_device_t* device) {
    event_dispatch(
        EVENT_BLOCK_DEVICE_DESTROYING,
        device
    );

    if (device->entry != NULL) {
        device_unregister(device->entry);
    }

    LOCK();

    char* name = device->name;
    block_device_error_t error = BLOCK_DEVICE_ERROR_OK;

    if (device->ops.destroy != NULL) {
        error = device->ops.destroy(device);
    }

    hashmap_remove(REGISTRY, device);
    event_dispatch_async(
        EVENT_BLOCK_DEVICE_DESTROYED,
        name
    );

    UNLOCK();

    return error;
}

block_device_error_t block_device_read(
    block_device_t* device,
    size_t offset,
    uint8_t* buffer,
    size_t size
) {
    if (device->ops.read != NULL) {
        return device->ops.read(
            device,
            offset,
            buffer,
            size
        );
    }
    return BLOCK_DEVICE_ERROR_UNHANDLED;
}

block_device_error_t block_device_write(
    block_device_t* device,
    size_t offset,
    uint8_t* buffer,
    size_t size
) {
    if (device->ops.write != NULL) {
        return device->ops.write(
            device,
            offset,
            buffer,
            size
        );
    }
    return BLOCK_DEVICE_ERROR_UNHANDLED;
}

block_device_error_t block_device_ioctl(
    block_device_t* device,
    ulong request,
    void* ptr
) {
    if (device->ops.ioctl != NULL) {
        return device->ops.ioctl(
            device,
            request,
            ptr
        );
    }
    return BLOCK_DEVICE_ERROR_UNHANDLED;
}

block_device_error_t block_device_stat(
    block_device_t* device,
    block_device_stat_t* stat
) {
    if (device->ops.stat != NULL) {
        return device->ops.stat(
            device,
            stat
        );
    }
    return BLOCK_DEVICE_ERROR_UNHANDLED;
}


text:
package definitions

type AttachmentInfo struct {
	ContentType string `json:"contentType,omitempty"`
	URI         string `json:"uri,omitempty"`
}


text:
CMD=/home/jenkins/bin/son-validate
BASE_DIR=`dirname $0`
SCHEMA=${BASE_DIR}/../pd-schema.yml
FILE=${BASE_DIR}/../examples/simplest-example.yml

#
# We can provide an argument that overrides
# the given CMD variable.
#
if [ $# -eq 1 ]
then
  CMD=$1
fi

#
# Execute the test.
#
${CMD} -s ${SCHEMA} ${FILE}


text:
var chaii = require('chai');
chaii.use(require('chai-fuzzy'));
var assert = chaii.assert;
var _ = require('underscore');

process.env['mocha-unfunk-color'] = true;


text:
package it.unibas.trikc.repository.reduction;

import it.unibas.trikc.modelEntity.TestSuite;
import it.unibas.trikc.repository.XMLException;

public interface IDAOTestSuite {

	public void save (TestSuite testSuite, String nameFile) throws XMLException;
	public TestSuite load(String nameFile)throws XMLException;
	public TestSuite loadForTest(String nameFile) throws XMLException;

}


text:
"""Tests for GPU PCIe bandwidth benchmark."""
import os
import unittest

import mock

from perfkitbenchmarker.linux_benchmarks import gpu_pcie_bandwidth_benchmark

class GpuBandwidthTestCase(unittest.TestCase):

  def setUp(self):
    p = mock.patch(gpu_pcie_bandwidth_benchmark.__name__ + '.FLAGS')
    p.start()
    self.addCleanup(p.stop)

    path = os.path.join(os.path.dirname(__file__), '../data',
                        'cuda_bandwidth_test_results.txt')
    with open(path) as fp:
      self.test_output = fp.read()

  def testParseDeviceMetadata(self):
    actual = gpu_pcie_bandwidth_benchmark.\
        _ParseDeviceInfo(self.test_output)
    expected = {'0': 'Tesla K80', '1': 'Tesla K80'}
    self.assertEqual(expected, actual)

  def testParseCudaBandwidthTestResults(self):
    results = gpu_pcie_bandwidth_benchmark.\
        _ParseOutputFromSingleIteration(self.test_output)
    self.assertEqual(3, len(results))
    self.assertAlmostEqual(9254.7, results['Host to device bandwidth'])
    self.assertAlmostEqual(9686.1, results['Device to host bandwidth'])
    self.assertAlmostEqual(155985.8, results['Device to device bandwidth'])

  def testCalculateMetrics(self):
    raw_results = [{
        'Host to device bandwidth': 9250,
        'Device to host bandwidth': 9000,
        'Device to device bandwidth': 155000
    }, {
        'Host to device bandwidth': 8000,
        'Device to host bandwidth': 8500,
        'Device to device bandwidth': 152000
    }]
    samples = gpu_pcie_bandwidth_benchmark.\
        _CalculateMetricsOverAllIterations(raw_results)
    metrics = {i[0]: i[1] for i in samples}

    sample = next(x for x in samples if x.metadata == {'iteration': 0}
                  and x.metric == 'Host to device bandwidth')
    self.assertAlmostEqual(9250, sample.value)

    sample = next(x for x in samples if x.metadata == {'iteration': 0}
                  and x.metric == 'Device to host bandwidth')
    self.assertAlmostEqual(9000, sample.value)

    sample = next(x for x in samples if x.metadata == {'iteration': 0}
                  and x.metric == 'Device to device bandwidth')
    self.assertAlmostEqual(155000, sample.value)

    sample = next(x for x in samples if x.metadata == {'iteration': 1}
                  and x.metric == 'Host to device bandwidth')
    self.assertAlmostEqual(8000, sample.value)

    sample = next(x for x in samples if x.metadata == {'iteration': 1}
                  and x.metric == 'Device to host bandwidth')
    self.assertAlmostEqual(8500, sample.value)

    sample = next(x for x in samples if x.metadata == {'iteration': 1}
                  and x.metric == 'Device to device bandwidth')
    self.assertAlmostEqual(152000, sample.value)

    self.assertAlmostEqual(8000, metrics['Host to device bandwidth, min'])
    self.assertAlmostEqual(9250, metrics['Host to device bandwidth, max'])
    self.assertAlmostEqual(8625.0, metrics['Host to device bandwidth, mean'])
    self.assertAlmostEqual(625.0, metrics['Host to device bandwidth, stddev'])

    self.assertAlmostEqual(8500, metrics['Device to host bandwidth, min'])
    self.assertAlmostEqual(9000, metrics['Device to host bandwidth, max'])
    self.assertAlmostEqual(8750.0, metrics['Device to host bandwidth, mean'])
    self.assertAlmostEqual(250.0, metrics['Device to host bandwidth, stddev'])

    self.assertAlmostEqual(152000, metrics['Device to device bandwidth, min'])
    self.assertAlmostEqual(155000, metrics['Device to device bandwidth, max'])
    self.assertAlmostEqual(153500, metrics['Device to device bandwidth, mean'])
    self.assertAlmostEqual(1500, metrics['Device to device bandwidth, stddev'])

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


text:
package com.media;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;

import com.sun.media.protocol.avi.DataSource;

public class AudioPlayer extends JFrame {

	//String fileName = "C:\\Users\\Karthik\\workspace_j2ee\\Orbital_Forces\\src\\clips\\soundtrack.wav";
	InputStream in;
	Clip push;
	AudioInputStream ais1,ais2;
	public AudioPlayer (int playSound) throws LineUnavailableException, IOException {
		if (playSound == 1)
			playMissilesound();
		if (playSound == 2)
			playGameoversound();

	}

	public AudioPlayer () throws IOException, InterruptedException, LineUnavailableException {

        URL url = new URL(
                "file:///C://Users//Karthik//workspace_j2ee//Orbital_Forces//src//sounds//soundtrack.wav");
            Clip clip = AudioSystem.getClip();
            // getAudioInputStream() also accepts a File or InputStream

			try {
				ais1 = AudioSystem.
				    getAudioInputStream( url );
			} catch (UnsupportedAudioFileException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            clip.open(ais1);
            clip.loop(Clip.LOOP_CONTINUOUSLY);

            //------------------------
            /*
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    // A GUI element to prevent the Clip's daemon Thread
                    // from terminating at the end of the main()
                    JOptionPane.showMessageDialog(null, "Close to exit!");
                }
            });
            */
            //------------------------
	}

	private void playMissilesound () throws LineUnavailableException, IOException {
    	//push.start();
		URL url = new URL(
                "file:///C://Users//Karthik//workspace_j2ee//Orbital_Forces//src//sounds//missle.wav");
            Clip clip = AudioSystem.getClip();
            // getAudioInputStream() also accepts a File or InputStream

			try {
				ais2 = AudioSystem.
				    getAudioInputStream( url );
			} catch (UnsupportedAudioFileException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            clip.open(ais2);
            clip.start();

    }

	private void playGameoversound() throws LineUnavailableException, IOException {

		URL url = new URL(
                "file:///C://Users//Karthik//workspace_j2ee//Orbital_Forces//src//sounds//gameover.wav");
            Clip clip = AudioSystem.getClip();
            // getAudioInputStream() also accepts a File or InputStream

			try {
				ais2 = AudioSystem.
				    getAudioInputStream( url );
			} catch (UnsupportedAudioFileException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            clip.open(ais2);
            clip.start();
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}

module PSBT.Bower (
    Bower(..)
    , BowerError(..)
    , Dependency(..)
    , bowerErrorHandler
    , bowerErrorMessage
    , createBowerFile
    , minimalBower
    , readBowerFile
) where

import           Control.Applicative        (empty, optional, (<|>))
import           Control.Exception          (Exception)
import           Control.Monad              (unless)
import           Control.Monad.Catch        (Handler (..), MonadThrow, throwM)
import           Control.Monad.IO.Class     (MonadIO, liftIO)
import           Control.Monad.Trans.Class  (lift)
import           Control.Monad.Trans.Reader (ReaderT (..), runReaderT)
import           Data.Aeson                 (ToJSON, object, toJSON, (.=))
import           Data.Aeson.BetterErrors    (Parse, ParseError, asBool,
                                             asObject, asString, displayError,
                                             eachInArray, eachInObject, key,
                                             keyMay, keyOrDefault,
                                             throwCustomError)
import qualified Data.Aeson.BetterErrors    as A (parse)
import           Data.Aeson.Encode.Pretty   (Config (..), defConfig,
                                             encodePretty', keyOrder)
import qualified Data.ByteString.Lazy       as B (hPutStr, readFile)
import           Data.Char                  (toLower)
import           Data.HashMap.Lazy          (HashMap, toList)
import           Data.Text                  (Text)
import qualified Data.Text                  as T (pack, unlines, unpack)
import           System.Directory           (doesFileExist)
import           System.IO                  (IOMode (WriteMode), withFile,
                                             writeFile)
import           Text.Megaparsec            (errorMessages, messageString)
import qualified Text.Megaparsec            as M (parse)

import           PSBT.SemVer                (Range, displayRange, range)

data Dependency = Dependency {
    packageName :: Text
    , version   :: Maybe Range
    } deriving Show

instance ToJSON Dependency where
  toJSON d = object [packageName d .= maybe "latest" displayRange (version d)]

data Bower = Bower {
    name              :: String
    , description     :: Maybe String
    , mainModule      :: Maybe [String]
    , dependencies    :: Maybe [Dependency]
    , devDependencies :: Maybe [Dependency]
    , resolutions     :: Maybe [Dependency]
    } deriving Show

minimalBower :: String -> Bower
minimalBower name = Bower name Nothing Nothing Nothing Nothing Nothing

instance ToJSON Bower where
  toJSON b = object [
    "name" .= name b
    , "description" .= description b
    , "main" .= mainModule b
    , "dependencies" .= dependencies b
    , "devDependencies" .= devDependencies b
    , "resolutions" .= resolutions b
    ]

data BowerError = JSONError Text
                | FileNotFound FilePath
                deriving Show

instance Exception BowerError where

asDependencies :: Parse Text [Dependency]
asDependencies = do
    depList <- eachInObject asString
    traverse getDependency depList
  where
    getDependency (name,versionStr)
      | versionStr == "latest" = return $ Dependency name Nothing
      | otherwise = case M.parse range "Bower" versionStr of
            Right r  -> return $ Dependency name (Just r)
            Left e -> throwCustomError . T.pack . unlines . map messageString . errorMessages $ e

asBower :: Parse Text Bower
asBower = Bower <$>
    key "name" asString <*>
    keyMay "description" asString <*>
    keyMay "main" (eachInArray asString) <*>
    keyMay "dependencies" asDependencies <*>
    keyMay "devDependencies" asDependencies <*>
    keyMay "resolutions" asDependencies

readBowerFile :: (MonadIO m, MonadThrow m) => FilePath -> m Bower
readBowerFile fp = do
        exists <- liftIO $ doesFileExist fp
        unless exists (throwM $ FileNotFound fp)
        bower <- liftIO $ B.readFile fp
        case A.parse asBower bower of
            Left e  -> throwM (JSONError . T.unlines $ displayError id e)
            Right b -> return b

createBowerFile :: (MonadIO m, MonadThrow m) => Bower -> m ()
createBowerFile bower = liftIO $ do
  b <- doesFileExist "bower.json"
  if b then prompt else createTheFile
  where
    prompt = do
      putStrLn "bower.json already exists. Do you want to overwrite it? (y/n)"
      r <- toLower <$> getChar
      case r of
        'y' -> createTheFile
        'n' -> return ()
        _   -> prompt
    orderList = ["name","description","main","dependencies","devDependencies","resolutions"]
    jsonString = encodePretty' defConfig { confCompare = keyOrder orderList } bower
    createTheFile = withFile "bower.json" WriteMode (`B.hPutStr` jsonString)

bowerErrorMessage :: BowerError -> String
bowerErrorMessage (JSONError msg) = "Error parsing bower.json: " ++ T.unpack msg
bowerErrorMessage (FileNotFound fp) = "bower.json not found: " ++ fp ++ " does not exist"

bowerErrorHandler :: MonadIO m => Handler m ()
bowerErrorHandler = Handler $ liftIO . putStrLn . bowerErrorMessage


text:
u'''
Created on Oct 3, 2010

Use this module to start Arelle in web server mode

@author: Mark V Systems Limited
(c) Copyright 2010 Mark V Systems Limited, All rights reserved.
'''
from arelle.webserver.bottle import Bottle, request, response, static_file
import os, sys, time, threading, uuid
from arelle import Version
from arelle.FileSource import FileNamedStringIO
from io import open
_os_pid = os.getpid()

def startWebserver(_cntlr, options):
    u"""Called once from main program in CmtlrCmdLine to initiate web server on specified local port.
    To test WebServer run from source in IIS, use an entry like this: c:\python33\python.exe c:\\users\\myname\\mySourceFolder\\arelleCmdLine.py %s

    :param options: OptionParser options from parse_args of main argv arguments (the argument *webserver* provides hostname and port), port being used to startup the webserver on localhost.
    :type options: optparse.Values
    """
    global imagesDir, cntlr, optionsPrototype
    cntlr = _cntlr
    imagesDir = cntlr.imagesDir
    optionValuesTypes = _STR_NUM_TYPES + (type(None),)
    optionsPrototype = dict((option,value if isinstance(value,_STR_NUM_TYPES) else None)
                            for option in dir(options)
                            for value in (getattr(options, option),)
                            if isinstance(value,optionValuesTypes) and not option.startswith(u'_'))
    host, sep, portServer = options.webserver.partition(u":")
    port, sep, server = portServer.partition(u":")
    # start a Bottle application
    app = Bottle()

    GETorPOST = (u'GET', u'POST')
    GET = u'GET'
    POST = u'POST'

    # install REST API interfaces
    # if necessary to support CGI hosted servers below root, add <prefix:path> as first part of routes
    # and corresponding arguments to the handler methods
    app.route(u'/rest/login', GET, login_form)
    app.route(u'/rest/login', POST, login_submit)
    app.route(u'/rest/logout', GET, logout)
    app.route(u'/favicon.ico', GET, arelleIcon)
    app.route(u'/rest/xbrl/<file:path>/open', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/close', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/validation/xbrl', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/DTS', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/concepts', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/pre', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/cal', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/dim', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/facts', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/factTable', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/roleTypes', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/arcroleTypes', GETorPOST, validation)
    app.route(u'/rest/xbrl/<file:path>/formulae', GETorPOST, validation)
    app.route(u'/rest/xbrl/validation', GETorPOST, validation)
    app.route(u'/rest/xbrl/view', GETorPOST, validation)
    app.route(u'/rest/xbrl/open', GETorPOST, validation)
    app.route(u'/rest/xbrl/close', GETorPOST, validation)
    app.route(u'/images/<imgFile>', GET, image)
    app.route(u'/rest/xbrl/diff', GET, diff)
    app.route(u'/rest/configure', GET, configure)
    app.route(u'/rest/stopWebServer', GET, stopWebServer)
    app.route(u'/quickbooks/server.asmx', POST, quickbooksServer)
    app.route(u'/rest/quickbooks/<qbReport>/xbrl-gl/<file:path>', GET, quickbooksGLrequest)
    app.route(u'/rest/quickbooks/<qbReport>/xbrl-gl/<file:path>/view', GET, quickbooksGLrequest)
    app.route(u'/rest/quickbooks/<qbReport>/xbrl-gl/view', GET, quickbooksGLrequest)
    app.route(u'/rest/quickbooks/response', GET, quickbooksGLresponse)
    app.route(u'/quickbooks/server.html', GET, quickbooksWebPage)
    app.route(u'/quickbooks/localhost.crt', GET, localhostCertificate)
    app.route(u'/localhost.crt', GET, localhostCertificate)
    app.route(u'/help', GET, helpREST)
    app.route(u'/about', GET, about)
    app.route(u'/', GET, indexPageREST)
    if server == u"cgi":
        # catch a non-REST interface by cgi Interface (may be a cgi app exe module, etc)
        app.route(u'<cgiAppPath:path>', GETorPOST, cgiInterface)
    if server == u"wsgi":
        return app
    elif server == u"cgi":
        if sys.stdin is None:
            sys.stdin = open(os.devnull, u'r')
        app.run(server=server)
        sys.exit(0)
    elif server:
        app.run(host=host, port=port or 80, server=server)
    else:
        app.run(host=host, port=port or 80)

def cgiInterface(cgiAppPath):
    # route request according to content
    #with open(r"c:\temp\tracecgi.log", "at", encoding="utf-8") as fh:
    #    fh.write("trace 2 arg={}\n".format(cgiAppPath))
    if not request.query:  # no parameters, index page
        return indexPageCGI()
    elif u'about' in request.query:
        return about(cgiAppPath + u"?image=arelle32.gif")
    elif u'help' in request.query:
        return helpREST()
    elif u'image' in request.query:
        return image(request.query.image)
    else:
        return indexPageCGI()

def login_form():
    u"""Request for a login form (get to */rest/login*).  Corresponds to login from other providers of XBRL validation services, but
    this version of Arelle does not perform accounting or charges for validation requests, so the login is ignored.

    :returns: str -- HTML login form to enter and submit via method=POST these fields: name, password
    """
    return _(u'''<form method="POST">

Name:	<input name="name" type="text" />

Password:	<input name="password" type="password" />

 	<input type="submit" value="Submit" />

</form>''')

def login_submit():
    u"""Login of fields from login form (post to */rest/login*).  Saves user ID for future use.

    :param name: User ID
    :param password: Password
    """
    name     = request.forms.get(u'name')
    password = request.forms.get(u'password')
    if checkLogin(name, password):
        return _(u"
You are logged in as user: {0}
").format(name)
    else:
        return _(u"
Login failed
")

def checkLogin(_user, _password):
    u"""Save user ID for future use.  Password not currently processed.

    :returns: bool -- True (for now, future user may interact with authentication and accounting services.)
    """
    global user
    user = _user
    return True

def logout():
    u"""Request to log out (get */rest/logout*).  Removes any proior user ID from session.

    :returns: html -- Message that user has logged out
    """
    global user
    user = None
    return _(u"
You are logged out.
")

def arelleIcon():
    u"""Request for icon for URL display (get */favicon.ico*).

    :returns: ico -- Icon file for browsers
    """
    return static_file(u"arelle.ico", root=imagesDir, mimetype=u'image/vnd.microsoft.icon')

def image(imgFile):
    u"""Request for an image file for URL display (get */images/<imgFile>*).

    :returns: image file -- Requested image file from images directory of application for browsers
    """
    return static_file(imgFile, root=imagesDir)

validationOptions = {
    # these options have no value (after + in query)
    u"efm": (u"validateEFM", True),
    u"efm-pragmatic": (u"disclosureSystemName", u"efm-pragmatic"),
    u"efm-strict": (u"disclosureSystemName", u"efm-strict"),
    u"disclosure-system": (u"disclosureSystemName", None),
    u"ifrs": (u"gfmName", u"ifrs"),
    u"hmrc": (u"gfmName", u"hmrc"),
    u"sbr-nl": (u"gfmName", u"sbr-nl"),
    u"utr": (u"utrValidate", True),
    u"infoset": (u"infosetValidate", True),
    # these parameters pass through the value after + in query
    u"import": (u"importFiles", None),
                     }

class Options():
    u"""Class to emulate options needed by CntlrCmdLine.run"""
    def __init__(self):
        for option, defaultValue in optionsPrototype.items():
            setattr(self, option, defaultValue)

supportedViews = set([u'DTS', u'concepts', u'pre', u'cal', u'dim', u'facts', u'factTable', u'formulae', u'roleTypes', u'arcroleTypes'])

def validation(file=None):
    u"""REST request to validate, by *get* or *post*, to URL patterns including */rest/xbrl/<file:path>/{open|close|validation|DTS...}*,
    and */rest/xbrl/{view|open|close}*.
    Sets up CntrlCmdLine options for request, performed by runOptionsAndGetResult using CntlrCmdLine.run with get or post arguments.

    :returns: html, xhtml, xml, json, text -- Return per media type argument and request arguments
    """
    errors = []
    flavor = request.query.flavor or u'standard'
    media = request.query.media or u'html'
    requestPathParts = request.urlparts[2].split(u'/')
    isValidation = u'validation' == requestPathParts[-1] or u'validation' == requestPathParts[-2]
    view = request.query.view
    viewArcrole = request.query.viewArcrole
    if request.method == u'POST':
        sourceZipStream = request.body
        mimeType = request.get_header(u"Content-Type")
        if mimeType not in (u'application/zip', u'application/x-zip', u'application/x-zip-compressed', u'multipart/x-zip'):
            errors.append(_(u"POST must provide a zip file, Content-Type '{0}' not recognized as a zip file.").format(mimeType))
    else:
        sourceZipStream = None
    if not view and not viewArcrole:
        if requestPathParts[-1] in supportedViews:
            view = requestPathParts[-1]
    if isValidation:
        if view or viewArcrole:
            errors.append(_(u"Only validation or one view can be specified in one requested."))
        if media not in (u'xml', u'xhtml', u'html', u'json', u'text'):
            errors.append(_(u"Media '{0}' is not supported for validation (please select xhtml, html, xml, json or text)").format(media))
    elif view or viewArcrole:
        if media not in (u'xml', u'xhtml', u'html', u'csv', u'json'):
            errors.append(_(u"Media '{0}' is not supported for view (please select xhtml, html, xml, csv, or json)").format(media))
    elif requestPathParts[-1] not in (u"open", u"close"):
        errors.append(_(u"Neither validation nor view requested, nothing to do."))
    if (flavor not in (u'standard', u'standard-except-formula', u'formula-compile-only', u'formula-compile-and-run')
        and not flavor.startswith(u'edgar') and not flavor.startswith(u'sec')):
        errors.append(_(u"Flavor '{0}' is not supported").format(flavor))
    if view and view not in supportedViews:
        errors.append(_(u"View '{0}' is not supported").format(view))
    if errors:
        errors.insert(0, _(u"URL: ") + (file or request.query.file or u'(no file)'))
        return errorReport(errors, media)
    options = Options() # need named parameters to simulate options
    isFormulaOnly = False
    for key, value in request.query.items():
        if key == u"file":
            setattr(options, u"entrypointFile", value)
        elif key == u"flavor":
            if value.startswith(u"sec") or value.startswith(u"edgar"):
                setattr(options, u"validateEFM", True)
            elif value == u"formula-compile-only":
                isFormulaOnly = True
                setattr(options, u"formulaAction", u"validate")
            elif value == u"formula-compile-and-run":
                isFormulaOnly = True
                setattr(options, u"formulaAction", u"run")
            elif value == u"standard-except-formula":
                setattr(options, u"formulaAction", u"none")
        elif key in(u"media", u"view", u"viewArcrole"):
            pass
        elif key in validationOptions:
            optionKey, optionValue = validationOptions[key]
            setattr(options, optionKey, optionValue if optionValue is not None else value)
        elif not value: # convert plain str parameter present to True parameter
            setattr(options, key, True)
        else:
            setattr(options, key, value)
    if file:
        setattr(options, u"entrypointFile", file.replace(u';',u'/'))
    requestPathParts = set(request.urlparts[2].split(u'/'))
    viewFile = None
    if isValidation:
        if not isFormulaOnly:
            setattr(options, u"validate", True)
    elif view:
        viewFile = FileNamedStringIO(media)
        setattr(options, view + u"File", viewFile)
    elif viewArcrole:
        viewFile = FileNamedStringIO(media)
        setattr(options, u"viewArcrole", viewArcrole)
        setattr(options, u"viewFile", viewFile)
    return runOptionsAndGetResult(options, media, viewFile, sourceZipStream)

def runOptionsAndGetResult(options, media, viewFile, sourceZipStream=None):
    u"""Execute request according to options, for result in media, with *post*ed file in sourceZipStream, if any.

    :returns: html, xml, csv, text -- Return per media type argument and request arguments
    """
    successful = cntlr.run(options, sourceZipStream)
    if media == u"xml":
        response.content_type = u'text/xml; charset=UTF-8'
    elif media == u"csv":
        response.content_type = u'text/csv; charset=UTF-8'
    elif media == u"json":
        response.content_type = u'application/json; charset=UTF-8'
    elif media == u"text":
        response.content_type = u'text/plain; charset=UTF-8'
    else:
        response.content_type = u'text/html; charset=UTF-8'
    if successful and viewFile:
        # defeat re-encoding
        result = viewFile.getvalue().replace(u" ",u"\u00A0").replace(u"",u"\u00AD").replace(u"&",u"&")
        viewFile.close()
    elif media == u"xml":
        result = cntlr.logHandler.getXml()
    elif media == u"json":
        result = cntlr.logHandler.getJson()
    elif media == u"text":
        result = cntlr.logHandler.getText()
    else:
        result = htmlBody(tableRows(cntlr.logHandler.getLines(), header=_(u"Messages")))
    return result

def diff():
    u"""Execute versioning diff request for *get* request to */rest/xbrl/diff*.

    :returns: xml -- Versioning report.
    """
    if not request.query.fromDTS or not request.query.toDTS or not request.query.report:
        return _(u"From DTS, to DTS, and report must be specified")
    options = Options()
    setattr(options, u"entrypointFile", request.query.fromDTS)
    setattr(options, u"diffFile", request.query.toDTS)
    fh = FileNamedStringIO(request.query.report)
    setattr(options, u"versReportFile", fh)
    cntlr.run(options)
    reportContents = fh.getvalue()
    fh.close()
    response.content_type = u'text/xml; charset=UTF-8'
    return reportContents

def configure():
    u"""Set up features for *get* requests to */rest/configure*, e.g., proxy or plug-ins.

    :returns: html -- Status of configuration request (e.g., proxy or plug-ins).
    """
    if not request.query.proxy and not request.query.plugins and not request.query.packages and u'environment' not in request.query:
        return _(u"proxy, plugins, packages or environment must be specified")
    options = Options()
    if request.query.proxy:
        setattr(options, u"proxy", request.query.proxy)
    if request.query.plugins:
        setattr(options, u"plugins", request.query.plugins)
    if request.query.packages:
        setattr(options, u"packages", request.query.packages)
    if u'environment' in request.query:
        setattr(options, u"showEnvironment", True)
    cntlr.run(options)
    response.content_type = u'text/html; charset=UTF-8'
    return htmlBody(tableRows(cntlr.logHandler.getLines(), header=_(u"Configuration Request")))

def stopWebServer():
    u"""Stop the web server by *get* requests to */rest/stopWebServer*.

    """
    def stopSoon(delaySeconds):
        time.sleep(delaySeconds)
        import signal
        os.kill(_os_pid, signal.SIGTERM)
    thread = threading.Thread(target=lambda: stopSoon(2.5))
    thread.daemon = True
    thread.start()
    response.content_type = u'text/html; charset=UTF-8'
    return htmlBody(tableRows((time.strftime(u"Received at %Y-%m-%d %H:%M:%S"),
                               u"Good bye...",),
                              header=_(u"Stop Request")))

def quickbooksServer():
    u"""Interface to QuickBooks server responding to  *post* requests to */quickbooks/server.asmx*.

    (Part of QuickBooks protocol, see module CntlrQuickBooks.)
    """
    from arelle import CntlrQuickBooks
    response.content_type = u'text/xml; charset=UTF-8'
    return CntlrQuickBooks.server(cntlr, request.body, request.urlparts)

def quickbooksGLrequest(qbReport=None, file=None):
    u"""Initiate request to QuickBooks server for *get* requests to */rest/quickbooks/<qbReport>/xbrl-gl/...*.

    :returns: html, xml, csv, text -- Return per media type argument and request arguments
    """
    from arelle.CntlrQuickBooks import supportedQbReports, qbRequest
    from arelle.ModelValue import dateTime
    errors = []
    requestPathParts = request.urlparts[2].split(u'/')
    viewRequested = u"view" == requestPathParts[-1]
    media = request.query.media or u'html'
    fromDate = request.query.fromDate
    toDate = request.query.toDate
    if qbReport not in supportedQbReports:
        errors.append(_(u"QuickBooks report '{0}' is not supported (please select from: {1})").format(
                          qbReport, u', '.join(supportedQbReports)))
    if media not in (u'xml', u'xhtml', u'html'):
        errors.append(_(u"Media '{0}' is not supported for xbrl-gl (please select xhtml, html or xml)").format(media))
    if not fromDate or dateTime(fromDate) is None:
        errors.append(_(u"FromDate '{0}' missing or not valid").format(fromDate))
    if not toDate or dateTime(toDate) is None:
        errors.append(_(u"ToDate '{0}' missing or not valid").format(toDate))
    if errors:
        return errorReport(errors, media)
    ticket = qbRequest(qbReport, fromDate, toDate, file)
    result = htmlBody(tableRows([_(u"Request queued for QuickBooks...")], header=_(u"Quickbooks Request")), script=u'''

'''.format(ticket, media, viewRequested))
    return result

def quickbooksGLresponse():
    u"""Poll for QuickBooks protocol responses for *get* requests to */rest/quickbooks/response*.

    :returns: html, xml, csv, text -- Return per media type argument and request arguments, if response is ready, otherwise javascript to requery this *get* request periodicially.
    """
    from arelle import CntlrQuickBooks
    ticket = request.query.ticket
    media = request.query.media
    viewRequested = request.query.view
    status = CntlrQuickBooks.qbRequestStatus.get(ticket)
    if not status:
        return htmlBody(tableRows([_(u"QuickBooks ticket not found, request canceled.")], header=_(u"Quickbooks Request")))
    if status.startswith(u"ConnectionErrorMessage: "):
        CntlrQuickBooks.qbRequestStatus.pop(ticket, None)
        return errorReport([status[24:]], media)
    if status != u"Done" or ticket not in CntlrQuickBooks.xbrlInstances:
        return htmlBody(tableRows([_(u"{0}, Waiting 20 seconds...").format(status)],
                                  header=_(u"Quickbooks Request")),
                                  script=u'''

''')
    CntlrQuickBooks.qbRequestStatus.pop(ticket)

    instanceUuid = CntlrQuickBooks.xbrlInstances[ticket]
    CntlrQuickBooks.xbrlInstances.pop(ticket)
    options = Options()
    setattr(options, u"entrypointFile", instanceUuid)
    viewFile = FileNamedStringIO(media)
    setattr(options, u"factsFile", viewFile)
    return runOptionsAndGetResult(options, media, viewFile)

def quickbooksWebPage():
    return htmlBody(_(u'''

Arelle QuickBooks Global Ledger Interface

checkbox	Trial Balance.

close button	Done

'''))

def localhostCertificate():
    u"""Interface to QuickBooks server responding to  *get* requests for a host certificate */quickbooks/localhost.crt* or */localhost.crt*.

    (Supports QuickBooks protocol.)

    :returns: self-signed certificate
    """
    return u'''
-----BEGIN CERTIFICATE-----
MIIDljCCAn4CAQAwDQYJKoZIhvcNAQEEBQAwgZAxCzAJBgNVBAYTAlVTMRMwEQYD
VQQIEwpDYWxpZm9ybmlhMQ8wDQYDVQQHEwZFbmNpbm8xEzARBgNVBAoTCmFyZWxs
ZS5vcmcxDzANBgNVBAsTBmFyZWxsZTESMBAGA1UEAxMJbG9jYWxob3N0MSEwHwYJ
KoZIhvcNAQkBFhJzdXBwb3J0QGFyZWxsZS5vcmcwHhcNMTIwMTIwMDg0NjM1WhcN
MTQxMDE1MDg0NjM1WjCBkDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3Ju
aWExDzANBgNVBAcTBkVuY2lubzETMBEGA1UEChMKYXJlbGxlLm9yZzEPMA0GA1UE
CxMGYXJlbGxlMRIwEAYDVQQDEwlsb2NhbGhvc3QxITAfBgkqhkiG9w0BCQEWEnN1
cHBvcnRAYXJlbGxlLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AMJEq9zT4cdA2BII4TG4OJSlUP22xXqNAJdZZeB5rTIX4ePwIZ8KfFh/XWQ1/q5I
c/rkZ5TyC+SbEmQa/unvv1CypMAWWMfuguU6adOsxt+zFFMJndlE1lr3A2SBjHbD
vBGzGJJTivBzDPBIQ0SGcf32usOeotmE2PA11c5en8/IsRXm9+TA/W1xL60mfphW
9PIaJ+WF9rRROjKXVdQZTRFsNRs/Ag8o3jWEyWYCwR97+XkorYsAJs2TE/4zV+8f
8wKuhOrsy9KYFZz2piVWaEC0hbtDwX1CqN+1oDHq2bYqLygUSD/LbgK1lxM3ciVy
ewracPVHBErPlcJFxiOxAw0CAwEAATANBgkqhkiG9w0BAQQFAAOCAQEAM2np3UVY
6g14oeV0Z32Gn04+r6FV2D2bobxCVLIQDsWGEv1OkjVBJTu0bLsZQuNVZHEn5a+2
I0+MGME3HK1rx1c8MrAsr5u7ZLMNj7cjjtFWAUp9GugJyOmGK136o4/j1umtBojB
iVPvHsAvwZuommfME+AaBE/aJjPy5I3bSu8x65o1fuJPycrSeLAnLd/shCiZ31xF
QnJ9IaIU1HOusplC13A0tKhmRMGNz9v+Vqdj7J/kpdTH7FNMulrJTv/0ezTPjaOB
QhpLdqly7hWJ23blbQQv4ILT2CiPDotJslcKDT7GzvPoDu6rIs2MpsB/4RDYejYU
+3cu//C8LvhjkQ==
-----END CERTIFICATE-----
'''

def helpREST():
    u"""Help web page for *get* requests to */help*.

    :returns: html - Table of CntlrWebMain web API
    """
    return htmlBody(_(u'''

Arelle web API

/help	This web page.

/about	About web page, copyrights, etc.

Validation

/rest/xbrl/{file}/validation/xbrl	Validate document at {file}.

''') +
(_(u'''

\u00A0	For an http POST of a zip file (mime type application/zip), {file} is the relative file path inside the zip file.

\u00A0	For an http GET request, {file} may be a web url, and may have "/" characters replaced by ";" characters
(but that is not necessary).

Example:	/rest/xbrl/c.xbrl/validation/xbrl?media=xml: Validate entry instance
document in the POSTed zip archived file c.xbrl and return structured xml results.

/rest/xbrl/validation	(Alternative syntax) Validate document, file is provided as a parameter (see below).

Example:	/rest/xbrl/validation?file=c.xbrl&media=xml: Validate entry instance
document c.xbrl (in POSTed zip) and return structured xml results.

''')
if cntlr.isGAE else
_(u'''

\u00A0	For a browser request or http GET request, {file} may be local or web url, and may have "/" characters replaced by ";" characters
(but that is not necessary).

Example:	/rest/xbrl/c:/a/b/c.xbrl/validation/xbrl?media=xml: Validate entry instance
document at c:/a/b/c.xbrl (on local drive) and return structured xml results.

\u00A0	For an http POST of a zip file (mime type application/zip), {file} is the relative file path inside the zip file.

/rest/xbrl/validation	(Alternative syntax) Validate document, file is provided as a parameter (see below).

Example:	/rest/xbrl/validation?file=c:/a/b/c.xbrl&media=xml: Validate entry instance
document at c:/a/b/c.xbrl (on local drive) and return structured xml results.

''')) +
_(u'''

	Parameters are optional after "?" character, and are separated by "&" characters,
as follows:

flavor	standard: XBRL 2.1 and XDT validation.  (If formulas are present they will also be compiled and run.)  (default)

{sec*|edgar*}: SEC Edgar Filer Manual validation.   (If formulas are present they will also be compiled and run.)

standard-except-formula: XBRL 2.1 and XDT validation.  (If formulas are present they will be ignored.)

formula-compile-only: Formulas will be compiled but not run.  (No XBRL 2.1, XDT, or disclosure system validation.)

formula-compile-and-run: Formulas will be compiled and run.  (No XBRL 2.1, XDT, or disclosure system validation.)

media	html or xhtml: Html text results. (default)

xml: XML structured results.

json: JSON results.

text: Plain text results (no markup).

file	Alternate way to specify file name or url by a parameter.

import	A list of files to import to the DTS, such as additional formula
or label linkbases.  Multiple file names are separated by a '|' character.

labelLang	Label language to override system settings, e.g., &labelLang=ja.

labelRole	Label role instead of standard label, e.g., &labelRole=http://www.xbrl.org/2003/role/verboseLabel.  To use the concept QName instead of a label, specify &labelRole=XBRL-concept-name.

uiLang	User interface language to override system settings, e.g., &uiLang=fr.  Changes setting for current session (but not saved setting).

calcDecimals	Specify calculation linkbase validation inferring decimals.

calcPrecision	Specify calculation linkbase validation inferring precision.

efm-*	Select Edgar Filer Manual (U.S. SEC) disclosure system validation. (Alternative to flavor parameter.):

efm-pragmatic: SEC-required rules, currently-allowed years

efm-strict: SEC-semantic additional rules, currently-allowed years

efm-pragmatic-all-years: SEC-required rules, all years

efm-strict-all-years: SEC-semantic additional rules, all years

ifrs	Specify IFRS Global Filer Manual validation.

hmrc	Specify HMRC validation.

sbr-nl	Specify SBR-NL taxonomy validation.

utr	Select validation with respect to Unit Type Registry.

infoset	Select validation with respect to testcase infoset.

parameters	Specify parameters for validation or formula (comma separated name=value[,name2=value2]).

formulaAsserResultCounts	Report formula assertion counts.

formulaVarSetExprResult	Trace variable set formula value, assertion test results.

formulaVarSetTiming	Trace variable set execution times.

formulaVarFilterWinnowing	Trace variable set filter winnowing.

{other}	Other detailed formula trace parameters:

formulaParamExprResult, formulaParamInputValue, formulaCallExprSource, formulaCallExprCode, formulaCallExprEval,
formulaCallExprResult, formulaVarSetExprEval, formulaFormulaRules, formulaVarsOrder,
formulaVarExpressionSource, formulaVarExpressionCode, formulaVarExpressionEvaluation, formulaVarExpressionResult, formulaVarFiltersResult, and formulaRunIDs.

abortOnMajorError	Abort process on major error, such as when load is unable to find an entry or discovered file.

collectProfileStats	Collect profile statistics, such as timing of validation activities and formulae.

plugins	Activate plug-ins, specify  '|' separated .py modules (relative to plug-in directory).

packages	Activate taxonomy packages, specify  '|' separated .zip packages (absolute URLs or file paths).

Versioning Report (diff of two DTSes)

/rest/xbrl/diff	Diff two DTSes, producing an XBRL versioning report relative to report directory.

	Parameters are requred "?" character, and are separated by "&" characters,
as follows:

fromDTS	File name or url of from DTS.

toDTS	File name or url of to DTS.

report	File name or url of to report (to for relative path construction).  The report is not written out, but its contents are returned by the web request to be saved by the requestor.

Example:	/rest/diff?fromDTS=c:/a/prev/old.xsd&toDTS=c:/a/next/new.xsd&report=c:/a/report/report.xml: Diff two DTSes and produce versioning report.

Views

/rest/xbrl/{file}/{view}	View document at {file}.

\u00A0	{file} may be local or web url, and may have "/" characters replaced by ";" characters (but that is not necessary).

\u00A0	{view} may be DTS, concepts, pre, cal, dim, facts, factTable, formulae, roleTypes, or arcroleTypes.

Example:	/rest/xbrl/c:/a/b/c.xbrl/dim?media=html: View dimensions of
document at c:/a/b/c.xbrl (on local drive) and return html result.

/rest/xbrl/view	(Alternative syntax) View document, file and view are provided as parameters (see below).

Example:	/rest/xbrl/view?file=c:/a/b/c.xbrl&view=dim&media=xml: Validate entry instance
document at c:/a/b/c.xbrl (on local drive) and return structured xml results.

	Parameters are optional after "?" character, and are separated by "&" characters,
as follows:

media	html or xhtml: Html text results. (default)

xml: XML structured results.

csv: CSV text results (no markup).

json: JSON text results.

file	Alternate way to specify file name or url by a parameter.

view	Alternate way to specify view by a parameter.

viewArcrole	Alternate way to specify view by indicating arcrole desired.

import	A list of files to import to the DTS, such as additional formula
or label linkbases.  Multiple file names are separated by a '|' character.

factListCols	A list of column names for facts list.  Multiple names are separated by a space or comma characters.
Example:  factListCols=Label,unitRef,Dec,Value,EntityScheme,EntityIdentifier,Period,Dimensions

Excel interface

GUI operation:	Select data tab.
Click Get External Data From Web.

New Web Query dialog, enter rest URI to Address (example, for instance with indicated fact columns:
http://localhost:8080/rest/xbrl/C:/Users/John Doe/Documents/eu/instance.xbrl/facts?media=xhtml&factListCols=Label,unitRef,Dec,Value,EntityScheme,EntityIdentifier,Period,Dimensions

Before clicking Go, click Options, on Options dialog select Full HTML Formatting, then Ok to Options dialog.

Click Go.

Click arrow to select table.

Click Import button.

Review insertion cell, click ok on Import Data dialog.

VBA macro:
With ActiveSheet.QueryTables.Add(Connection:= _

   "URL;http://localhost:8080/rest/xbrl/C:/Users/John Doe/Documents/eu/instance.xbrl/facts?media=xhtml&factListCols=Label,unitRef,Dec,Value,EntityScheme,EntityIdentifier,Period,Dimensions" _

   , Destination:=Range("$A$1"))

   .Name = "facts"

   .FieldNames = True

   .RowNumbers = False

   .FillAdjacentFormulas = False

   .PreserveFormatting = False

   .RefreshOnFileOpen = False

   .BackgroundQuery = True

   .RefreshStyle = xlInsertDeleteCells

   .SavePassword = False

   .SaveData = True

   .AdjustColumnWidth = True

   .RefreshPeriod = 0

   .WebSelectionType = xlAllTables

   .WebFormatting = xlWebFormattingAll

   .WebPreFormattedTextToColumns = True

   .WebConsecutiveDelimitersAsOne = True

   .WebSingleBlockTextImport = False

   .WebDisableDateRecognition = False

   .WebDisableRedirections = False

   .Refresh BackgroundQuery:=False

End With

QuickBooks interface

Setup:	Install QuickBooks Web Connector by clicking here.

Click on QuickBooks.qwc in the Program Files Arelle directory, to install web connector for Arelle.  (It specifies localhost:8080 in it.)

Open your QuickBooks and desired company

From start menu, programs, QuickBooks, start Web Connector (QBWC).  Web connector may want a password, use any string, such as "abcd", as it's not checked at this time.

Start Arelle web server (if it wasn't already running)

To request xbrl-gl, select report type (generalLedger, journal, or trialBalance) and specify file name for xbrl-gl output instance.

QBWC polls once a minute, if impatient, in the QBWC window, click its Arelle checkbox and press the update button.

(If you get the error [8004041A] from Quickbooks, enable the company file for Arelle access in
Quickbooks: Edit->Preferences...->Integrated Applications->Company Preferences->click allow web access for ArelleWebService)

Example:	http://localhost:8080/rest/quickbooks/generalLedger/xbrl-gl/C:/mystuff/xbrlGeneralLedger.xbrl/view?fromDate=2011-01-01&toDate=2011-12-31
(You may omit /view.)

	Parameters follow "?" character, and are separated by "&" characters,
as follows:

media	html or xhtml: Html text results. (default)

xml: XML structured results.

json: JSON results.

text: Plain text results (no markup).

fromDate, toDate	From &amp to dates for GL transactions

Management

/rest/configure	Configure settings:

	Parameters are required following "?" character, and are separated by "&" characters,
as follows:

proxy	Show or modify and re-save proxy settings:

Enter 'show' to view current setting, 'system' to configure to use system proxy setting, 'none' to configure for no proxy, or 'http://[user[:password]@]host[:port]' (e.g., http://192.168.1.253, http://example.com:8080, http://joe:secret@example.com:8080)." ))

plugins	Show or modify and re-save plug-ins configuration:

Enter 'show' to view plug-ins configuration, , or '|' separated modules:
+url to add plug-in by its url or filename (relative to plug-in directory else absolute), ~name to reload a plug-in by its name, -name to remove a plug-in by its name,
 (e.g., '+http://arelle.org/files/hello_web.py', '+C:\Program Files\Arelle\examples\plugin\hello_dolly.py' to load,
~Hello Dolly to reload, -Hello Dolly to remove).  (Note that plug-ins are transient on Google App Engine, specify with &plugins to other rest commands.)

packages	Show or modify and re-save taxonomy packages configuration:

Enter 'show' to view packages configuration, , or '|' separated package URLs:
+url to add package by its full url or filename, ~name to reload a package by its name, -name to remove a package by its name.
(Note that packages are transient on Google App Engine, specify with &packages to other rest commands.)

environment	Show host environment (config and cache directories).

''') +
(_(u'''

/rest/stopWebServer	Shut down (terminate process after 2.5 seconds delay).

''') if cntlr.isGAE else u'') +
u'
')

def about(arelleImgFile=None):
    from lxml import etree
    u"""About web page for *get* requests to */about*.

    :returns: html - About web page
    """
    return htmlBody(_(u'''

About arelle

	arelle® version: %s %sbit %s. An open source XBRL platform

© 2010-2014 Mark V Systems Limited.  All rights reserved.

Web site: http://www.arelle.org.
E-mail support: support@arelle.org.

Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file
except in compliance with the License.  You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.

Includes:

Python® %s.%s.%s © 2001-2010 Python Software Foundation

PyParsing © 2003-2010 Paul T. McGuire

lxml %s.%s.%s © 2004 Infrae, ElementTree © 1999-2004 by Fredrik Lundh

xlrd © 2005-2013 Stephen J. Machin, Lingfo Pty Ltd, © 2001 D. Giffin, © 2000 A. Khan

xlwt © 2007 Stephen J. Machin, Lingfo Pty Ltd, © 2005 R. V. Kiseliov

Bottle © 2011 Marcel Hellkamp

''') % (arelleImgFile or u'/images/arelle32.gif',
                cntlr.__version__,
                cntlr.systemWordSize,
                Version.version,
                sys.version_info[0],sys.version_info[1],sys.version_info[2],
                etree.LXML_VERSION[0],etree.LXML_VERSION[1],etree.LXML_VERSION[2]) )

def indexPageREST():
    u"""Index (default) web page for *get* requests to */*.

    :returns: html - Web page of choices to navigate to */help* or */about*.
    """
    return htmlBody(_(u'''

Arelle Web Services

/help	Help web page, web services API.

/about	About web page, copyrights, license, included software.

'''))

def indexPageCGI():
    u"""Default web page response for *get* CGI request with no parameters.

    :returns: html - Web page of choices to navigate to *?help* or *?about*.
    """
    return htmlBody(_(u'''

Arelle CGI Services

?help	Help web page, CGI services.

?about	About web page, copyrights, license, included software.

REST API	The Arelle REST API is supported through CGI if the entire CGI path is wildcard-mapped to the arelleCmdLine executable.

'''))

def htmlBody(body, script=u""):
    u"""Wraps body html string in a css-styled html web page

    :param body: Contents for the ** element
    :type body: html str
    :param script: Script to insert in generated html web page (such as a timed reload script)
    :type script: javascript str
    :returns: html - Web page of choices to navigate to */help* or */about*.
    """
    return u'''
<?xml version="1.0" encoding="utf-8"?>

%s

    %s

''' % (script, body)

def tableRows(lines, header=None):
    u"""Wraps lines of text into a one-column table (for display of text results of operations, such as processing messages and status, to web browser).
    Replaces any *&* with *&* and *<* with *<*.

    :param lines: Sequence (list or tuple) of line strings.
    :type lines: [str]
    :param header: Optional header text for top row of table.
    :type header: str
    :returns: html -
 html string.
    """
    return u'
%s\n
' % (
            (u"
%s
" % header if header else u"") +
            u"\n".join(u"
%s
" % line.replace(u"&",u"&").replace(u"<",u"<") for line in lines))

def errorReport(errors, media=u"html"):
    u"""Wraps lines of error text into specified media type for return of result to a request.

    :param errors: Sequence (list or tuple) of error strings.
    :type errors: [str]
    :param media: Type of result requestd.
    :type media: str
    :returns: html -
 html string.
    """
    if media == u"text":
        response.content_type = u'text/plain; charset=UTF-8'
        return u'\n'.join(errors)
    else:
        response.content_type = u'text/html; charset=UTF-8'
        return htmlBody(tableRows(errors, header=_(u"Messages")))

def multipartResponse(parts):
    # call with ( (filename, contentType, content), ...)
    boundary=u'----multipart-boundary-%s----' % (uuid.uuid1(),)
    response.content_type = u'multipart/mixed; boundary=%s' % (boundary,)
    buf = []

    for filename, contentType, content in parts:
        buf.append(u"\r\n" + boundary + u"\r\n")
        buf.append(u'Content-Disposition: attachment; filename="{0}";\r\n'.format(filename))
        buf.append(u'Content-Type: {0};\r\n'.format(contentType))
        buf.append(u'Content-Length: {0}\r\n'.format(len(content)))
        buf.append(u'\r\n')
        buf.append(content)
    buf.append(u"\r\n" + boundary + u"\r\n")
    s = u''.join(buf)
    response.content_length = len(s)
    return s


text:
from shirka.responders import Responder
from random import randint
import requests
from shirka.consumers import BaseTestCase

class NineGagResponder(Responder):
    def name(self):
        return '9gag'

    def generate(self, request):
        """
        usage: 9gag
        retrieves a random 9gag image
        """
        section = requests.get("http://infinigag.eu01.aws.af.cm/?section=hot").json()

        return section['data'][randint(0, len(section['data']))]['images']['small']

class TestNineGagResponder(BaseTestCase):
    def setUp(self):
        self.responder = NineGagResponder()

    def test_support(self):
        self.assertTrue(self.responder.support(self.create_request("9gag")))
        self.assertFalse(self.responder.support(self.create_request("fuu")))

    def test_valid(self):
        self.assertIsNotNone(self.generate("9gag"))

    def test_on_start(self):
        self.assertFalse(self.responder.on_start(False))


text:
package org.schema;

/**
 *
 * A condition or factor that indicates use of a medical therapy, including
 * signs, symptoms, risk factors, anatomical states, etc.
 *
 * @fullPath Thing > MedicalEntity > MedicalIndication
 *
 * @author Texelz (by Onhate)
 *
 */
public class MedicalIndication extends MedicalEntity {

}


text:
import { Disposable, Tooltip } from '../index';

export type TooltipPlacement =
    | 'top'
    | 'bottom'
    | 'left'
    | 'right'
    | 'auto'
    | 'auto top'
    | 'auto bottom'
    | 'auto left'
    | 'auto right';

/** Associates tooltips with HTML elements or selectors. */
export interface TooltipManager {
    /** Add a tooltip to the given element. */
    add(
        target: HTMLElement | JQueryCompatible,
        options:
            | {
                  item?: object;
              }
            | ({
                  title?: string | (() => string);
                  html?: boolean;
                  keyBindingCommand?: string;
                  keyBindingTarget?: HTMLElement;
              } & {
                  class?: string;
                  placement?: TooltipPlacement | (() => TooltipPlacement);
                  trigger?: 'click' | 'hover' | 'focus' | 'manual';
                  delay?: { show: number; hide: number };
              }),
    ): Disposable;

    /** Find the tooltips that have been applied to the given element. */
    findTooltips(target: HTMLElement): Tooltip[];
}

export interface JQueryCompatible<Element extends Node = HTMLElement> extends Iterable<Element> {
    jquery: string;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Consp. fung. (Leipzig) 217 (1805)

#### Original name
Agaricus squamulosus var. rufocinnamomeus Alb. & Schwein.

### Remarks
null


text:
package org.statmantis.stat.common;

import org.statmantis.model.Play;
import org.statmantis.model.PlayType;
import org.statmantis.stat.StatisticInfo;
import org.statmantis.stat.StatisticType;

@StatisticInfo(
        name = "Grounded Into Double Plays",
        abbreviations = { "GDP", "GIDP" },
        types = { StatisticType.BATTING, StatisticType.PITCHING })
public class GroundedIntoDoublePlays extends PitcherAndBatterBasedPlayStatistic<Integer> {

    private int groundedIntoDoublePlays = 0;

    @Override
    public void applyPlay(Play play) {
        if (isPlayApplicable(play) && play.getEvent().
                getPlayType() == PlayType.GROUND_OUT_DOUBLE_PLAY) {
            groundedIntoDoublePlays++;
        }
    }

    @Override
    public Integer getCurrentValue() {
        return groundedIntoDoublePlays;
    }

}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

  Guiding Principles

- Changelogs are for humans, not machines.
- There should be an entry for every single version.
- The same types of changes should be grouped.
- Versions and sections should be linkable.
- The latest version comes first.
- The release date of each versions is displayed.
- Mention whether you follow Semantic Versioning.

  Types of changes

Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_):

- `Added` for new features.
- `Changed` for changes in existing functionality.
- `Deprecated` for soon-to-be removed features.
- `Removed` for now removed features.
- `Fixed` for any bug fixes.
- `Security` in case of vulnerabilities.

## [4.0.0] - 2019-03-20

### Added

- Adds support for `options.onMatch`. See the readme for details
- Adds support for `options.onIgnore`. See the readme for details
- Adds support for `options.onResult`. See the readme for details

### Breaking changes

- Removed support for passing an array of brace patterns to `micromatch.braces()`.
- To strictly enforce closing brackets (for `{`, `[`, and `(`), you must now use `strictBrackets=true` instead of `strictErrors`.
- `cache` - caching and all related options and methods have been removed
- `options.unixify` was renamed to `options.windows`
- `options.nodupes` Was removed. Duplicates are always removed by default. You can override this with custom behavior by using the `onMatch`, `onResult` and `onIgnore` functions.
- `options.snapdragon` was removed, as snapdragon is no longer used.
- `options.sourcemap` was removed, as snapdragon is no longer used, which provided sourcemap support.

## [3.0.0] - 2017-04-11

Complete overhaul, with 36,000+ new unit tests validated against actual output generated by Bash and minimatch. More specifically, 35,000+ of the tests:

 - micromatch results are directly compared to bash results
 - in rare cases, when micromatch and bash disagree, micromatch's results are compared to minimatch's results
 - micromatch is much more accurate than minimatch, so there were cases where I had to make assumptions. I'll try to document these.

This refactor introduces a parser and compiler that are supersets of more granular parsers and compilers from other sub-modules. Each of these sub-modules has a singular responsibility and focuses on a certain type of matching that aligns with a specific part of the Bash "expansion" API.

These sub-modules work like plugins to seamlessly create the micromatch parser/compiler, so that strings are parsed in one pass, an [AST is created](https://gist.github.com/jonschlinkert/099c8914f56529f75bc757cc9e5e8e2a), then a new string is generated by the compiler.

Here are those sub-modules with links to related prs on those modules if you want to see how they contribute to this code:

[nanomatch](https://github.com/jonschlinkert/nanomatch) (new library) - glob expansion (`*`, `**`, `?` and `[...]`))
[braces](https://github.com/jonschlinkert/braces/pull/10) - brace expansion (`{1..10}`, `{a,b,c}`, etc)
[extglob](https://github.com/jonschlinkert/extglob/pull/5) - extended globs (`!(a|b)`, `@(!(foo|bar))`, etc)
[expand-brackets](https://github.com/jonschlinkert/expand-brackets/pull/5) - POSIX character classes `[[:alpha:][:digit:]]`

**Added**

 - source map support (optionally created when using parse or compile - I have no idea what the use case is yet, but they come for free) (note that source maps are not generated for brace expansion at present, since the braces compiler uses a different strategy. I'll update if/when this changes).
 - parser is exposed, so that implementors can customize or override specific micromatch parsers if necessary
 - compiler is exposed, so that implementors can customize or override specific micromatch compilers if necessary

**Fixed**

 - more accurate matching (passes 100% of Bash 4.3 of the brace expansion and extglob unit tests, as well as all Bash glob tests that are relevant to node.js usage, all minimatch tests, all brace-expansion tests, and also passes a couple of tests that bash fails)
 - even safer - micromatch has always generated optimized patterns so it's not subject to DoS exploits like minimatch (completely different than the regex DoS issue, minimatch and multimatch are still openly exposed to being used for DoS attacks), but more safeguards were built into this refactor

**Changed**

 - the public API of this library did not change in this version and should be safe to upgrade without changing implentor code. However, we have released this as a major version for the following reasons:
   - out of an abundance of caution due to the large amount of code changed in this release
   - we have improved parser accuracy to such a degree that some implementors using invalid globs have noted change in behavior. If this is the case for you, please check that you are using a valid glob expression before logging a bug with this library

## [1.0.1] - 2016-12-12

**Added**

- Support for windows path edge cases where backslashes are used in brackets or other unusual combinations.

## [1.0.0] - 2016-12-12

Stable release.

## [0.1.0] - 2016-10-08

First release.

[Unreleased]: https://github.com/jonschlinkert/micromatch/compare/0.1.0...HEAD
[0.2.0]: https://github.com/jonschlinkert/micromatch/compare/0.1.0...0.2.0

[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog


text:
package com.anysoftkeyboard.saywhat;

import android.view.View;
import androidx.annotation.NonNull;

public class CandidateViewShowingHelper {

    public boolean shouldShow(@NonNull PublicNotices ime) {
        final View candidate = ime.getInputViewContainer().getCandidateView();
        return candidate != null && candidate.getVisibility() == View.VISIBLE;
    }
}


text:
/*jshint globalstrict:false, strict:false, maxlen: 500 */
/*global assertEqual */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for index usage
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

const jsunity = require("jsunity");
const db = require("@arangodb").db;

function optimizerQueryStatsTestSuite () {
  let c;

  return {
    setUp : function () {
      db._drop("UnitTestsCollection");
      // intentionally single-shard only to test statistics here (much easier with one shard)
      c = db._create("UnitTestsCollection");
    },

    tearDown : function () {
      db._drop("UnitTestsCollection");
    },

    testFullScanEmpty : function () {
      let stats = db._query("FOR doc IN " + c.name() + " RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(0, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanNonEmpty : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i });
      }
      let stats = db._query("FOR doc IN " + c.name() + " RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(1000, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanSkipped : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i });
      }
      let stats = db._query("FOR doc IN " + c.name() + " LIMIT 500, 1000 RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(1000, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanLimited : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i });
      }
      let stats = db._query("FOR doc IN " + c.name() + " LIMIT 0, 100 RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(100, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanFiltered : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i % 10 });
      }
      let stats = db._query("FOR doc IN " + c.name() + " FILTER doc.value == 3 RETURN doc").getExtra().stats;

      assertEqual(900, stats.filtered);
      assertEqual(1000, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanFilteredSkipped : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i % 10 });
      }
      let stats = db._query("FOR doc IN " + c.name() + " FILTER doc.value == 3 LIMIT 500, 1000 RETURN doc").getExtra().stats;

      assertEqual(900, stats.filtered);
      assertEqual(1000, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testFullScanFilteredLimited : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i % 10 });
      }
      let stats = db._query("FOR doc IN " + c.name() + " FILTER doc.value == 3 LIMIT 0, 10 RETURN doc",{},{fullCount: true}).getExtra().stats;

      assertEqual(900, stats.filtered);
      assertEqual(1000, stats.scannedFull);
      assertEqual(0, stats.scannedIndex);
    },

    testIndexScan : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i % 10 });
      }
      c.ensureIndex({ type: "hash", fields: ["value"] });
      let stats = db._query("FOR doc IN " + c.name() + " FILTER doc.value == 3 RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(0, stats.scannedFull);
      assertEqual(100, stats.scannedIndex);
    },

    testIndexScanFiltered : function () {
      for (let i = 0; i < 1000; ++i) {
        c.insert({ value: i % 10 });
      }
      c.ensureIndex({ type: "hash", fields: ["value"] });
      let stats = db._query("FOR doc IN " + c.name() + " FILTER doc.value == 3 && doc._key != 'peng' RETURN doc").getExtra().stats;

      assertEqual(0, stats.filtered);
      assertEqual(0, stats.scannedFull);
      assertEqual(100, stats.scannedIndex);
    },
  };
}

jsunity.run(optimizerQueryStatsTestSuite);

return jsunity.done();


text:
set +v
. ./gridConfig.sh

echo "Downloading selenium version $SELENIUM_VERSION"

wget https://selenium-release.storage.googleapis.com/$SELENIUM_VERSION_SHORT/selenium-server-standalone-$SELENIUM_VERSION.jar

mv selenium-server-standalone-$SELENIUM_VERSION.jar selenium.jar
mv selenium.jar ../../localGrid

exit


text:
#include "jhelpers.h"

using namespace CryptoPP;

string bin2hex(const string bin, const bool uppercase)
{
  string retval;
  StringSource(bin, true, new HexEncoder(new StringSink(retval), uppercase));
  return retval;
}

string hex2bin(const string hex)
{
  string retval;
  StringSource(hex, true, new HexDecoder(new StringSink(retval)));
  return retval;
}

char* bin2hex(const char* bin, size_t length, const bool uppercase)
{
  char* retval = new char[length * 2 + 1];
  StringSource(bin, true, new HexEncoder(new ArraySink((byte*) retval, length * 2), uppercase));
  return retval;
}

char* hex2bin(const char* hex, size_t length)
{
  char* retval = new char[length / 2 + 1];
  StringSource(hex, true, new HexDecoder(new ArraySink((byte*) retval, length / 2)));
  return retval;
}

string generateIV(const unsigned int size, const enum RNGEnum rng)
{
  string retval;
  RandomNumberGenerator* randPool = NULL;

  #ifdef NONBLOCKING_RNG_AVAILABLE
  if (rng == NON_BLOCKING_RNG) {
    randPool = new NonblockingRng;
  }
  #endif

  #if defined(NONBLOCKING_RNG_AVAILABLE) && defined(BLOCKING_RNG_AVAILABLE)
  else
  #endif

  #ifdef BLOCKING_RNG_AVAILABLE
  if (rng == BLOCKING_RNG) {
    randPool = new BlockingRng;
  }
  #endif

  if (rng == RAND_RNG) {
    for (unsigned int i = 0; i < size; i++) {
      retval += (char)(255.0 * rand() / RAND_MAX);
    }
  }
  else if (randPool != NULL) {
    for (unsigned int i = 0; i < size; i++) {
      retval += (char) randPool->GenerateByte();
    }
    delete randPool;
  }

  return retval;
}

unsigned int checkBounds(unsigned int length, unsigned int min, unsigned int max, unsigned short int multiple)
{
  if (min == max) {
    return min;
  }
  else if (length < min) {
    return min;
  }
  else if (length > max) {
    return max;
  }
  else {
    return (length + multiple - 1) - ((length + multiple - 1) % multiple);
  }
}


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

namespace ServiceStackTest
{
    public class MyServices1 : Service
    {
        public object Get(string request) => throw null; // this might not be a remote source
        public object Get(Request1 request) => throw null;
        public object Get(Request2 request) => throw null;
        public object Get(Request3 request) => throw null; // might be a remote source if routes are looked up with Routes.AddFromAssembly
        public object Get(Request4 request)
        {
            Console.WriteLine(request.Nested.Prop1);
            Console.WriteLine(request.Nested.Prop2[0].Prop1);
            throw null;
        }

        public object Post(Request1 request) => throw null;
        public Task<object> PostAsync(Request1 request) => throw null;
        public object Method1(Request1 request) // Not a request method
        {
            Console.WriteLine(request.Field1);
            throw null;
        }

        public object GetJson(Request1 request) => throw null;
    }

    public class MyServices2 : IService
    {
        public object Get(Request1 request) => throw null;
    }

    public class Request1 : IReturn<Response1>
    {
        public string Field1;
    }

    public class Response1
    {
        public string Result { get; set; }
    }

    [Route("/req2/{Prop1}")]
    public class Request2
    {
        public string Prop1 { get; set; }
    }

    public class Request3
    {
        public string Prop1 { get; set; }
    }

    [Route("/req4")]
    public class Request4 : IReturnVoid
    {
        public string Prop1 { get; set; }
        public Nested Nested { get; set; }
    }

    public class Nested
    {
        public string Prop1 { get; set; }
        public List<Element> Prop2 { get; set; }
    }

    public class Element
    {
        public string Prop1 { get; set; }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer-when-downgrade">

<title>retalls - La vista cansada</title>
<meta name="description" content="">

<link rel="alternate" type="application/rss+xml" href="https://carlesbellver.github.io/tags/retalls/index.xml" title="La vista cansada" />
<link rel="icon" type="image/x-icon" href="https://carlesbellver.github.io/favicon.ico">
<link rel="apple-touch-icon-precomposed" href="https://carlesbellver.github.io/favicon.png">

<link rel="stylesheet" href="https://carlesbellver.github.io/css/light.css?rnd=1602439751" />

<link rel="stylesheet" href="https://carlesbellver.github.io/css/style.css?rnd=1602439751" />

<meta property="og:title" content="retalls" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://carlesbellver.github.io/tags/retalls/" />
<meta property="og:updated_time" content="2020-10-01T16:20:42+00:00" />

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="retalls"/>
<meta name="twitter:description" content=""/>

    Anar al contingut principal

    La vista cansada

        Informació

        Etiquetes

Etiqueta: retalls

        Totes les etiquetes

📎 Google Maps Hacks. Simon Weckert. Performance & Installation, 2020.

Un carretó carregat amb noranta-nou telèfons mòbils de segona ma genera un fals embús en Google Maps i desvia el trànsit real. El mapa no és el territori.

2020-02-05

#retalls

📎 Open is Cancelled

Lessig, Joi, Stallman… Faltes individuals o biaix ideològic? El moviment open ha posat la llibertat molt per davant de la justícia.

2020-01-27

#retalls

📎 Resistencia Digital. Manual de seguridad operacional e instrumental para smartphones. PDF, EPUB, MOBI.

«La invencibilidad es una cuestión de defensa», dice Sun Tzu.

2020-01-08

#retalls

…quant més automatizem, i més sofisticada fem l'automatització, més dependrem d'operaris humans altament qualificats.

📎 Ironies of automation

2020-01-08

#retalls

#citacions

L'estil… és allò que fas malament

          Sé que Jerry Garcia ho va dir una vegada, però sé que molta gent ho havia dit abans que ell, que "

          Continua

2019-12-10

#retalls

#citacions

Un mètode pseudocientífic d’identificació de culpables, basat en l’anàlisi de l’escriptura, fa furor en els cossos policials dels EUA i d’altres països.

📎 ‘Why Are Cops Around the World Using This Outlandish Mind-Reading Tool?'

2019-12-09

#retalls

📎 Who Can Use. Simulació: com funcionaria cada combinació de colors amb les dificultats visuals més comunes?

2019-12-05

#retalls

Els satèl·lits meteorològics capten el senyal —feble— del vapor d’aigua a 23.8 GHz, dins de l’espectre del 5G. L’extensió d’aquesta tecnologia podria dificultar els mesuraments —no se sabria si es detecten núvols o connexions de dades— i faria menys fiables les prediccions.

📎 Why Your 5G Phone Connection Could Mean Lousy Weather Forecasts

2019-12-05

#retalls

📎 Ben Werdmüller: The next big thing? The hybrid cloud.

Dividir les aplicacions: conservar la gestió de dades a casa —per seguretat— i pujar l’API al núvol —per agilitar-ne la gestió i les actualitzacions.

2019-11-28

#retalls

Elon Musk promet que volarem en coets o per túnels subterranis. Però els futuròlegs de Singularity creuen que el 5G, la hiperrealitat virtual i els robots instauraran la telepresència i aboliran les distàncies.

📎 Within 10 Years, We’ll Travel by Hyperloop, Rockets, and Avatars

2019-11-20

#retalls

                articles posteriors

                articles anteriors

Carles Bellver Torlà

    <button class="theme-switcher">
        Tema fosc
    </button>


text:
<?php

Loader::load('model', array(
	'crawler/Domain',
	'crawler/Link',
	'crawler/Page',
	'crawler/PageContentH1Map',
	'crawler/PageContentImageSourceMap',
	'crawler/PageLinkMap',
	'crawler/PageMetaKeywordMap',
	'crawler/content/ContentH1',
	'crawler/content/ContentImageAlternateText',
	'crawler/content/ContentImageSource',
	'crawler/content/ContentImageSourceContentImageAlternateTextMap',
	'crawler/content/ContentPage',
	'crawler/meta/MetaDescription',
	'crawler/meta/MetaKeyword',
	'crawler/meta/MetaTitle'));

class CrawlerPage
{

	private static $MATCH_HTTP_CODE				= '@HTTP([^\s]+)\s(\d+)\s(.*)@';
	private static $MATCH_TITLE					= '@<title>(.*)</title>@';
	private static $MATCH_META_REDIRECT			= '@<meta http-equiv="refresh" content="(\d+)" />@';
	private static $MATCH_META_DESCRIPTION		= '@<meta name="description" content="(.*)" />@';
	private static $MATCH_META_KEYWORD			= '@<meta name="keywords" content="(.*)" />@';
	private static $MATCH_CONTENT_H1			= '@<h1(.*)>(.*)</h1>@';
	private static $MATCH_CONTENT_IMAGE			= '@<img(.*)>@';
	private static $MATCH_IMAGE_SOURCE			= '@src="([^"]+)"@';
	private static $MATCH_IMAGE_ALTERNATE_TEXT	= '@alt="([^"]+)"@';
	private static $MATCH_LINK					= '@href="([^"]+)"@';

	private static $GOOGLEBOT_HEADERS = array(
		'http' => array(
			'method' => 'GET',
			'user_agent' => 'Googlebot/2.1 (+http://www.googlebot.com/bot.html)'));

	private $crawlerURL;
	private $data;
	private $headers;
	private $date_accessed;
	private $page;

	private function __construct(CrawlerURL $crawlerURL)
	{
		$this->crawlerURL = $crawlerURL;
	}

	public static function instance(CrawlerURL $crawlerURL)
	{
		return new CrawlerPage($crawlerURL);
	}

	public function execute()
	{
		$this->data = $this->file_get_contents();
		$this->headers = $this->file_get_headers();
		$this->date_accessed = time();
		return $this;
	}

	public function save()
	{
		$domain = Finder::instance('Domain')
			->setNameFilter($this->crawlerURL->getDomain())
			->getDomain();

		if(!isset($domain))
		{
			$domain = Mutator::instance('Domain', 'Create')
				->setData($this->crawlerURL->getDomain())
				->execute();
		}

		$link = Finder::instance('Link')
			->setNameFilter($this->crawlerURL->getAbsoluteURL())
			->getLink();

		if(!isset($link))
		{
			$link = Mutator::instance('Link', 'Create')
				->setData($this->crawlerURL->getAbsoluteURL())
				->execute();
		}

		$metaTitle = Finder::instance('MetaTitle')
			->setNameFilter($this->getMetaTitle())
			->getMetaTitle();

		if(!isset($metaTitle))
		{
			$metaTitle = Mutator::instance('MetaTitle', 'Create')
				->setData($this->getMetaTitle())
				->execute();
		}

		$metaDescription = Finder::instance('MetaDescription')
			->setNameFilter($this->getMetaDescription())
			->getMetaDescription();

		if(!isset($metaDescription))
		{
			$metaDescription = Mutator::instance('MetaDescription', 'Create')
				->setData($this->getMetaDescription())
				->execute();
		}

		$contentPage = Finder::instance('ContentPage')
			->setNameFilter($this->getContentPage())
			->getContentPage();

		if(!isset($contentPage))
		{
			$contentPage = Mutator::instance('ContentPage', 'Create')
				->setData($this->getContentPage())
				->execute();
		}

		$page = Finder::instance('Page')
			->setDomainFilter($domain->getID())
			->setLinkFilter($link->getID())
			->setMetaTitleFilter($metaTitle->getID())
			->setMetaDescriptionFilter($metaDescription->getID())
			->setMetaRedirectFilter($this->hasMetaRedirect())
			->setContentPageFilter($contentPage->getID())
			->setHTTPCodeFilter($this->getHTTPCode())
			->getPage();

		if(!isset($page))
		{
			$page = Mutator::instance('Page', 'Create')
				->setData($domain, $link, $metaTitle, $metaDescription, $this->hasMetaRedirect(), $contentPage, $this->getHTTPCode(), $this->getDateAccessed())
				->execute();
		}

		$this->page = $page;

		foreach($this->getContentH1s() as $contentH1)
		{
			$contentH1Object = Finder::instance('ContentH1')
				->setNameFilter($contentH1)
				->getContentH1();

			if(!isset($contentH1Object))
			{
				$contentH1Object = Mutator::instance('ContentH1', 'Create')
					->setData($contentH1)
					->execute();
			}

			$pageContentH1Map = Mutator::instance('PageContentH1Map', 'Create')
				->setData($page, $contentH1Object)
				->execute();
		}

		foreach($this->getContentImages() as $image)
		{
			$contentImageSource = Finder::instance('ContentImageSource')
				->setNameFilter($image->source)
				->getContentImageSource();

			if(!isset($contentImageSource))
			{
				$contentImageSource = Mutator::instance('ContentImageSource', 'Create')
					->setData($image->source)
					->execute();
			}

			$pageContentImageSourceMap = Finder::instance('PageContentImageSourceMap')
				->setPageFilter($page->getID())
				->setContentImageSourceFilter($contentImageSource->getID())
				->getPageContentImageSourceMap();

			if(!$pageContentImageSourceMap)
			{
				$pageContentImageSourceMap = Mutator::instance('PageContentImageSourceMap', 'Create')
					->setData($page, $contentImageSource)
					->execute();
			}

			if(strlen($image->alternate_text) > 0)
			{

				$contentImageAlternateText = Finder::instance('ContentImageAlternateText')
					->setNameFilter($image->alternate_text)
					->getContentImageAlternateText();

				if(!isset($contentImageAlternateText))
				{
					$contentImageAlternateText = Mutator::instance('ContentImageAlternateText', 'Create')
						->setData($image->alternate_text)
						->execute();
				}

				$contentImageSourceContentImageAlternateTextMap = Finder::instance('ContentImageSourceContentImageAlternateTextMap')
					->setContentImageSourceFilter($contentImageSource->getID())
					->setContentImageAlternateTextFilter($contentImageAlternateText->getID())
					->getContentImageSourceContentImageAlternateTextMap();

				if(!isset($contentImageSourceContentImageAlternateTextMap))
				{
					$contentImageSourceContentImageAlternateTextMap = Mutator::instance('ContentImageSourceContentImageAlternateTextMap', 'Create')
						->setData($contentImageSource, $contentImageAlternateText)
						->execute();
				}
			}
		}

		foreach($this->get_links() as $crawlerLink)
		{
			if(!$crawlerLink->isContentLink())
				continue;

			$link = Finder::instance('Link')
				->setNameFilter($crawlerLink->getAbsoluteURL())
				->getLink();

			if(!isset($link))
			{
				$link = Mutator::instance('Link', 'Create')
					->setData($crawlerLink->getAbsoluteURL())
					->execute();
			}

			$host = $domain->getName();
			$host = str_replace('http://', '', $host);

			$pageLinkMap = Finder::instance('PageLinkMap')
				->setPageFilter($page->getID())
				->setLinkFilter($link->getID())
				->setInternalLinkFilter($crawlerLink->isInternalLink($host))
				->getPageLinkMap();

			if(!$pageLinkMap)
			{
				$pageLinkMap = Mutator::instance('PageLinkMap', 'Create')
					->setData($page, $link, $crawlerLink->isInternalLink($host))
					->execute();
			}
		}

		foreach($this->getMetaKeywords() as $metaKeyword)
		{
			$keyword = Finder::instance('MetaKeyword')
				->setNameFilter($metaKeyword)
				->getMetaKeyword();

			if(!isset($keyword))
			{
				$keyword = Mutator::instance('MetaKeyword', 'Create')
					->setData($metaKeyword)
					->execute();
			}

			$pageKeywordMap = Finder::instance('PageMetaKeywordMap')
				->setPageFilter($page->getID())
				->setMetaKeywordFilter($keyword->getID())
				->getPageMetaKeywordMap();

			if(!$pageKeywordMap)
			{
				$pageKeywordMap = Mutator::instance('PageMetaKeywordMap', 'Create')
					->setData($page, $keyword)
					->execute();
			}
		}
	}

	private function file_get_contents()
	{
		$context = stream_context_create(self::$GOOGLEBOT_HEADERS);
		return file_get_contents($this->crawlerURL->getURL(), false, $context);
	}

	private function file_get_headers()
	{
		$headers = get_headers($this->crawlerURL->getURL(), 1);
		return $headers;
	}

	private $http_code;
	public function getHTTPCode()
	{
		if(!isset($this->http_code))
		{
			$code = $this->headers[0];
			preg_match(self::$MATCH_HTTP_CODE, $code, $matches);
			$this->http_code = $matches[2];
		}
		return $this->http_code;
	}

	private $external_links;
	public function getExternalLinks()
	{
		if(!isset($this->external_links))
		{
			$links = $this->get_links();
			$host = $this->crawlerURL->getHost();

			$this->external_links = array();
			foreach($links as $link)
			{
				if(!$link->isInternalLink($host) && $link->isContentLink())
					$this->external_links[] = $link->getAbsoluteURL();
			}
		}
		return $this->external_links;
	}

	private $internal_links;
	public function getInternalLinks()
	{
		if(!isset($this->internal_links))
		{
			$links = $this->get_links();
			$host = $this->crawlerURL->getHost();

			$this->internal_links = array();
			foreach($links as $link)
			{
				if($link->isInternalLink($host) && $link->isContentLink())
					$this->internal_links[] = $link->getAbsoluteURL();
			}
		}
		return $this->internal_links;
	}

	private $links;
	private function get_links()
	{
		if(!isset($this->links))
		{
			preg_match_all(self::$MATCH_LINK, $this->data, $match);
			if(isset($match[1]) && is_array($match[1]))
			{
				$links = array();
				foreach($match[1] as $link)
				{
					if(stristr($link, 'http://') != $link)
						$link = $this->crawlerURL->getDomain() . $link;

					$links[] = CrawlerURL::instance($link);
				}
				$this->links = $links;
			}
			else
				$this->links = array();
		}
		return $this->links;
	}

	private $title;
	public function getMetaTitle()
	{
		if(!isset($this->title))
		{
			preg_match(self::$MATCH_TITLE, $this->data, $match);
			if(isset($match[1]) && is_string($match[1]))
				$this->title = $match[1];
			else
				$this->title = '';
		}
		return $this->title;
	}

	private $has_meta_redirect;
	public function hasMetaRedirect()
	{
		if(!isset($this->has_meta_redirect))
		{
			if(preg_match(self::$MATCH_META_REDIRECT, $this->data) > 0)
				$this->has_meta_redirect = true;
			else
				$this->has_meta_redirect = false;
		}
		return $this->has_meta_redirect;
	}

	private $meta_description;
	public function getMetaDescription()
	{
		if(!isset($this->meta_description))
		{
			preg_match(self::$MATCH_META_DESCRIPTION, $this->data, $match);
			if(isset($match[1]) && is_string($match[1]))
				$this->meta_description = $match[1];
			else
				$this->meta_description = '';
		}
		return $this->meta_description;
	}

	private $meta_keywords;
	public function getMetaKeywords()
	{
		if(!isset($this->meta_keywords))
		{
			preg_match(self::$MATCH_META_KEYWORD, $this->data, $match);
			if(isset($match[1]) && is_string($match[1]))
			{
				$meta_keywords = $match[1];
				$meta_keywords = explode(',', $meta_keywords);
				$this->meta_keywords = $meta_keywords;
			}
			else
				$this->meta_keywords = array();
		}
		return $this->meta_keywords;
	}

	private $content_h1s;
	public function getContentH1s()
	{
		if(!isset($this->content_h1s))
		{
			preg_match_all(self::$MATCH_CONTENT_H1, $this->data, $match);
			if(isset($match[2]) && is_array($match[2]))
				$this->content_h1s = $match[2];
			else
				$this->content_h1s = array();
		}
		return $this->content_h1s;
	}

	private $content_images;
	public function getContentImages()
	{
		if(!isset($this->content_images))
		{
			preg_match_all(self::$MATCH_CONTENT_IMAGE, $this->data, $match);
			if(isset($match[0]) && is_array($match[0]) && count($match[0]) > 0)
			{
				foreach($match[0] as $image)
				{
					preg_match(self::$MATCH_IMAGE_SOURCE, $image, $match);
					if(isset($match[1]) && is_string($match[1]))
						$source = $match[1];
					else
						$source = '';

					preg_match(self::$MATCH_IMAGE_ALTERNATE_TEXT, $image, $match);
					if(isset($match[1]) && is_string($match[1]))
						$alternate_text = $match[1];
					else
						$alternate_text = '';

					$this->content_images[] = (object) array(
						'source' => $source,
						'alternate_text' => $alternate_text);
				}
			}
			else
				$this->content_images = array();
		}
		return $this->content_images;
	}

	public function getContentPage()
	{
		return $this->data;
	}

	public function getDateAccessed()
	{
		return date('Y-m-d g:i:s', $this->date_accessed);
	}

	public function getPage()
	{
		return $this->page;
	}

}

?>


text:
package org.springframework.boot.autoconfigure.webservices;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Tests for {@link WebServicesProperties}.
 *
 * @author Madhura Bhave
 */
public class WebServicesPropertiesTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	private WebServicesProperties properties;

	@Test
	public void pathMustNotBeEmpty() {
		this.properties = new WebServicesProperties();
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Path must have length greater than 1");
		this.properties.setPath("");
	}

	@Test
	public void pathMustHaveLengthGreaterThanOne() {
		this.properties = new WebServicesProperties();
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Path must have length greater than 1");
		this.properties.setPath("/");
	}

	@Test
	public void customPathMustBeginWithASlash() {
		this.properties = new WebServicesProperties();
		this.thrown.expect(IllegalArgumentException.class);
		this.thrown.expectMessage("Path must start with '/'");
		this.properties.setPath("custom");
	}

}


text:
set -echo
echo "Installing mssql-tools"
curl -sSL https://packages.microsoft.com/keys/microsoft.asc | (OUT=$(apt-key add - 2>&1) || echo $OUT)
DISTRO=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
CODENAME=$(lsb_release -cs)
echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-${DISTRO}-${CODENAME}-prod ${CODENAME} main" > /etc/apt/sources.list.d/microsoft.list
apt-get update
ACCEPT_EULA=Y apt-get -y install unixodbc-dev msodbcsql17 libunwind8 mssql-tools

echo "Installing sqlpackage"
curl -sSL -o sqlpackage.zip "https://aka.ms/sqlpackage-linux"
mkdir /opt/sqlpackage
unzip sqlpackage.zip -d /opt/sqlpackage
rm sqlpackage.zip
chmod a+x /opt/sqlpackage/sqlpackage