text:
package com.vaklinov.zcashui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;

import com.vaklinov.zcashui.OSUtil.OS_TYPE;
import com.vaklinov.zcashui.ZCashClientCaller.NetworkAndBlockchainInfo;
import com.vaklinov.zcashui.ZCashClientCaller.WalletBalance;
import com.vaklinov.zcashui.ZCashClientCaller.WalletCallException;
import com.vaklinov.zcashui.ZCashInstallationObserver.DAEMON_STATUS;
import com.vaklinov.zcashui.ZCashInstallationObserver.DaemonInfo;

/**
 * Dashboard ...
 *
 * @author Ivan Vaklinov <ivan@vaklinov.com>
 */
public class DashboardPanel
	extends JPanel
	{

    private static final Logger LOG = Logger.getLogger(DashboardPanel.class.getName());

	private JFrame parentFrame;
	private ZCashInstallationObserver installationObserver;
	private ZCashClientCaller clientCaller;
	private StatusUpdateErrorReporter errorReporter;

	private JLabel networkAndBlockchainLabel = null;
	private DataGatheringThread<NetworkAndBlockchainInfo> netInfoGatheringThread = null;

	private Boolean walletIsEncrypted  = null;

	private String OSInfo              = null;
	private JLabel daemonStatusLabel   = null;
	private DataGatheringThread<DaemonInfo> daemonInfoGatheringThread = null;

	private JLabel walletBalanceLabel  = null;
	private DataGatheringThread<WalletBalance> walletBalanceGatheringThread = null;

	private JTable transactionsTable   = null;
	private JScrollPane transactionsTablePane  = null;
	private String[][] lastTransactionsData = null;
	private DataGatheringThread<String[][]> transactionGatheringThread = null;

	// Lists of threads and timers that may be stopped if necessary
	private List<Timer> timers                   = null;
	private List<DataGatheringThread<?>> threads = null;

	public DashboardPanel(JFrame parentFrame,
			              ZCashInstallationObserver installationObserver,
			              ZCashClientCaller clientCaller,
			              StatusUpdateErrorReporter errorReporter)
		throws IOException, InterruptedException, WalletCallException
	{
		this.parentFrame = parentFrame;
		this.installationObserver = installationObserver;
		this.clientCaller = clientCaller;
		this.errorReporter = errorReporter;

		this.timers = new ArrayList<Timer>();
		this.threads = new ArrayList<DataGatheringThread<?>>();

		// Build content
		JPanel dashboard = this;
		dashboard.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
		dashboard.setLayout(new BorderLayout(0, 0));

		// Upper panel with wallet balance
		JPanel balanceStatusPanel = new JPanel();
		// Use border layout to have balances to the left
		balanceStatusPanel.setLayout(new BorderLayout(3, 3));
		//balanceStatusPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

		JPanel tempPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 9));
		JLabel logoLabel = new JLabel(new ImageIcon(
			this.getClass().getClassLoader().getResource("images/"+ZCashUI.NAME+"-40x40.png")));
		tempPanel.add(logoLabel);
		//tempPanel.add(new JLabel(" "));
		JLabel zcLabel = new JLabel("Cash Wallet        ");
		zcLabel.setFont(new Font("Helvetica", Font.BOLD | Font.ITALIC, 32));
		tempPanel.add(zcLabel);
		tempPanel.setToolTipText("Powered by ZCash");
		balanceStatusPanel.add(tempPanel, BorderLayout.WEST);

		JLabel transactionHeadingLabel = new JLabel(
			"
Transactions:");
		transactionHeadingLabel.setFont(new Font("Helvetica", Font.BOLD, 19));
		balanceStatusPanel.add(transactionHeadingLabel, BorderLayout.CENTER);

		PresentationPanel walletBalancePanel = new PresentationPanel();
		walletBalancePanel.add(walletBalanceLabel = new JLabel());
		balanceStatusPanel.add(walletBalancePanel, BorderLayout.EAST);

		dashboard.add(balanceStatusPanel, BorderLayout.NORTH);

		// Table of transactions
		lastTransactionsData = getTransactionsDataFromWallet();
		dashboard.add(transactionsTablePane = new JScrollPane(
				         transactionsTable = this.createTransactionsTable(lastTransactionsData)),
				      BorderLayout.CENTER);

		// Lower panel with installation status
		JPanel installationStatusPanel = new JPanel();
		installationStatusPanel.setLayout(new BorderLayout(3, 3));
		//installationStatusPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		PresentationPanel daemonStatusPanel = new PresentationPanel();
		daemonStatusPanel.add(daemonStatusLabel = new JLabel());
		installationStatusPanel.add(daemonStatusPanel, BorderLayout.WEST);

		PresentationPanel networkAndBlockchainPanel = new PresentationPanel();
		networkAndBlockchainPanel.add(networkAndBlockchainLabel = new JLabel());
		installationStatusPanel.add(networkAndBlockchainPanel, BorderLayout.EAST);

		dashboard.add(installationStatusPanel, BorderLayout.SOUTH);

		// Thread and timer to update the daemon status
		this.daemonInfoGatheringThread = new DataGatheringThread<DaemonInfo>(
			new DataGatheringThread.DataGatherer<DaemonInfo>()
			{
				public DaemonInfo gatherData()
					throws Exception
				{
					long start = System.currentTimeMillis();
					DaemonInfo daemonInfo = DashboardPanel.this.installationObserver.getDaemonInfo();
					long end = System.currentTimeMillis();
					LOG.fine("Gathering of dashboard daemon status data done in " + (end - start) + "ms." );

					return daemonInfo;
				}
			},
			this.errorReporter, 2000, true);
		this.threads.add(this.daemonInfoGatheringThread);

		ActionListener alDeamonStatus = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					DashboardPanel.this.updateDaemonStatusLabel();
				} catch (Exception ex)
				{
					LOG.log(Level.WARNING, "", ex);
					DashboardPanel.this.errorReporter.reportError(ex);
				}
			}
		};
		Timer t = new Timer(1000, alDeamonStatus);
		t.start();
		this.timers.add(t);

		// Thread and timer to update the wallet balance
		this.walletBalanceGatheringThread = new DataGatheringThread<WalletBalance>(
			new DataGatheringThread.DataGatherer<WalletBalance>()
			{
				public WalletBalance gatherData()
					throws Exception
				{
					long start = System.currentTimeMillis();
					WalletBalance balance = DashboardPanel.this.clientCaller.getWalletInfo();
					long end = System.currentTimeMillis();

					// TODO: move this call to a dedicated one-off gathering thread - this is the wrong place
					// it works but a better design is needed.
					if (DashboardPanel.this.walletIsEncrypted == null)
					{
					    DashboardPanel.this.walletIsEncrypted = DashboardPanel.this.clientCaller.isWalletEncrypted();
					}

					LOG.fine("Gathering of dashboard wallet balance data done in " + (end - start) + "ms." );

					return balance;
				}
			},
			this.errorReporter, 8000, true);
		this.threads.add(this.walletBalanceGatheringThread);

		ActionListener alWalletBalance = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					DashboardPanel.this.updateWalletStatusLabel();
				} catch (Exception ex)
				{
					LOG.log(Level.WARNING, "", ex);
					DashboardPanel.this.errorReporter.reportError(ex);
				}
			}
		};
		Timer walletBalanceTimer =  new Timer(2000, alWalletBalance);
		walletBalanceTimer.setInitialDelay(1000);
		walletBalanceTimer.start();
		this.timers.add(walletBalanceTimer);

		// Thread and timer to update the transactions table
		this.transactionGatheringThread = new DataGatheringThread<String[][]>(
			new DataGatheringThread.DataGatherer<String[][]>()
			{
				public String[][] gatherData()
					throws Exception
				{
					long start = System.currentTimeMillis();
					String[][] data =  DashboardPanel.this.getTransactionsDataFromWallet();
					long end = System.currentTimeMillis();
					LOG.fine("Gathering of dashboard wallet transactions table data done in " + (end - start) + "ms." );

					return data;
				}
			},
			this.errorReporter, 25000);
		this.threads.add(this.transactionGatheringThread);

		ActionListener alTransactions = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					DashboardPanel.this.updateWalletTransactionsTable();
				} catch (Exception ex)
				{
					LOG.log(Level.WARNING, "", ex);
					DashboardPanel.this.errorReporter.reportError(ex);
				}
			}
		};
		t = new Timer(5000, alTransactions);
		t.start();
		this.timers.add(t);

		// Thread and timer to update the network and blockchain details
		this.netInfoGatheringThread = new DataGatheringThread<NetworkAndBlockchainInfo>(
			new DataGatheringThread.DataGatherer<NetworkAndBlockchainInfo>()
			{
				public NetworkAndBlockchainInfo gatherData()
					throws Exception
				{
					long start = System.currentTimeMillis();
					NetworkAndBlockchainInfo data =  DashboardPanel.this.clientCaller.getNetworkAndBlockchainInfo();
					long end = System.currentTimeMillis();
					LOG.fine("Gathering of network and blockchain info data done in " + (end - start) + "ms." );

					return data;
				}
			},
			this.errorReporter, 10000, true);
		this.threads.add(this.netInfoGatheringThread);

		ActionListener alNetAndBlockchain = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					DashboardPanel.this.updateNetworkAndBlockchainLabel();
				} catch (Exception ex)
				{
					LOG.log(Level.WARNING, "", ex);
					DashboardPanel.this.errorReporter.reportError(ex);
				}
			}
		};
		Timer netAndBlockchainTimer = new Timer(5000, alNetAndBlockchain);
		netAndBlockchainTimer.setInitialDelay(1000);
		netAndBlockchainTimer.start();
		this.timers.add(netAndBlockchainTimer);
	}

	public void stopThreadsAndTimers()
	{
		for (Timer t : this.timers)
		{
			t.stop();
		}

		for (DataGatheringThread<?> t : this.threads)
		{
			t.setSuspended(true);
		}
	}

	private void updateDaemonStatusLabel()
		throws IOException, InterruptedException, WalletCallException
	{
		DaemonInfo daemonInfo = this.daemonInfoGatheringThread.getLastData();

		// It is possible there has been no gathering initially
		if (daemonInfo == null)
		{
			return;
		}

		String daemonStatus = "RUNNING";
		if (daemonInfo.status != DAEMON_STATUS.RUNNING)
		{
			daemonStatus = "NOT RUNNING";
		}
		String runtimeInfo = "";
		if (daemonInfo.status == DAEMON_STATUS.RUNNING)
		{
			runtimeInfo = "" +
					      "Resident: " + daemonInfo.residentSizeMB + " MB, Virtual: " + daemonInfo.virtualSizeMB +
					      " MB, CPU: " + daemonInfo.cpuPercentage + "%" + "";
		}

		// TODO: what if ZCash directory is non-default...
		File walletDAT = new File(OSUtil.getBlockchainDirectory() + "/wallet.dat");

		if (this.OSInfo == null)
		{
			this.OSInfo = OSUtil.getSystemInfo();
		}

		String walletEncryption = "";
		// TODO: Use a one-off data gathering thread - better design
		if (this.walletIsEncrypted != null)
		{
			walletEncryption =
					"" +
			        " (" + (this.walletIsEncrypted ? "" : "not ") + "encrypted)" +
			        "";
		}

		String text =
			"zcashd status: " +
		    daemonStatus + ",  " + runtimeInfo + "
" +
			"Wallet: " + walletDAT.getCanonicalPath() + "" +
			walletEncryption + "
 " +
			"
" +
			"" +
			"Installation: " + OSUtil.getProgramDirectory() + ", " +
	        "Blockchain: " + OSUtil.getBlockchainDirectory() + "
 " +
		    "System: " + this.OSInfo + "  ";
		this.daemonStatusLabel.setText(text);
	}

	private void updateNetworkAndBlockchainLabel()
		throws IOException, InterruptedException
	{
		NetworkAndBlockchainInfo info = this.netInfoGatheringThread.getLastData();

		// It is possible there has been no gathering initially
		if (info == null)
		{
			return;
		}

		// TODO: Get the start date right after ZCash release - from first block!!!
		final Date startDate = new Date("28 Oct 2016 02:00:00 GMT");
		final Date nowDate = new Date(System.currentTimeMillis());

		long fullTime = nowDate.getTime() - startDate.getTime();
		long remainingTime = nowDate.getTime() - info.lastBlockDate.getTime();

		String percentage = "100";
		if (remainingTime > 20 * 60 * 1000) // After 20 min we report 100% anyway
		{
			double dPercentage = 100d - (((double)remainingTime / (double) fullTime) * 100d);
			if (dPercentage < 0)
			{
				dPercentage = 0;
			} else if (dPercentage > 100d)
			{
				dPercentage = 100d;
			}

			DecimalFormat df = new DecimalFormat("##0.##");
			percentage = df.format(dPercentage);
		}

		// Just in case early on the call returns some junk date
		if (info.lastBlockDate.before(startDate))
		{
			// TODO: write log that we fix minimum date! - this condition should not occur
			info.lastBlockDate = startDate;
		}

		String connections = " \u26D7";
		String tickSymbol = " \u2705";
		OS_TYPE os = OSUtil.getOSType();
		// Handling special symbols on Mac OS
		if (os == OS_TYPE.MAC_OS)
		{
			connections = " \u21D4";
			tickSymbol = " \u2606";
		}

		String tick = "";
		if (percentage.equals("100"))
		{
			tick = "" + tickSymbol + "";
		}

		String netColor = "red";
		if (info.numConnections > 0)
		{
			netColor = "#cc3300";
		}

		if (info.numConnections > 2)
		{
			netColor = "black";
		}

		if (info.numConnections > 6)
		{
			netColor = "green";
		}

		String text =
			" " +
		    "Blockchain synchronized: " +
			percentage + "%  " + tick + "
" +
			"Up to: " +
		    info.lastBlockDate.toLocaleString() + "
 " +
			"
" +
			"Network: " + info.numConnections + " connections" +
			"" + connections + "";
		this.networkAndBlockchainLabel.setText(text);
	}

	private void updateWalletStatusLabel()
		throws WalletCallException, IOException, InterruptedException
	{
		WalletBalance balance = this.walletBalanceGatheringThread.getLastData();

		// It is possible there has been no gathering initially
		if (balance == null)
		{
			return;
		}

		// Format double numbers - else sometimes we get exponential notation 1E-4 ZEC
		DecimalFormat df = new DecimalFormat("########0.00######");

		String transparentBalance = df.format(balance.transparentBalance);
		String privateBalance = df.format(balance.privateBalance);
		String totalBalance = df.format(balance.totalBalance);

		String transparentUCBalance = df.format(balance.transparentUnconfirmedBalance);
		String privateUCBalance = df.format(balance.privateUnconfirmedBalance);
		String totalUCBalance = df.format(balance.totalUnconfirmedBalance);

		String color1 = transparentBalance.equals(transparentUCBalance) ? "" : "color:#cc3300;";
		String color2 = privateBalance.equals(privateUCBalance)         ? "" : "color:#cc3300;";
		String color3 = totalBalance.equals(totalUCBalance)             ? "" : "color:#cc3300;";

		String text =
			"" +
		    "Transparent balance: " +
				transparentUCBalance + " ZEC
 " +
			"Private (Z) balance: " +
		    	privateUCBalance + " ZEC
 " +
			"Total (Z+T) balance: " +
		    	totalUCBalance + " ZEC " +
			"
  ";

		this.walletBalanceLabel.setText(text);

		String toolTip = null;
		if ((!transparentBalance.equals(transparentUCBalance)) ||
		    (!privateBalance.equals(privateUCBalance))         ||
		    (!totalBalance.equals(totalUCBalance)))
		{
			toolTip = "" +
					  "Unconfirmed (unspendable) balance is being shown due to an
" +
		              "ongoing transaction! Actual confirmed (spendable) balance is:
" +
		              "
" +
					  "Transparent: " + transparentBalance + " ZEC
" +
		              "Private ( Z ): " + privateBalance + " ZEC
" +
					  "Total ( Z+T ): " + totalBalance + " ZEC" +
					  "";
		}

		this.walletBalanceLabel.setToolTipText(toolTip);
	}

	private void updateWalletTransactionsTable()
		throws WalletCallException, IOException, InterruptedException
	{
		String[][] newTransactionsData = this.transactionGatheringThread.getLastData();

		// May be null - not even gathered once
		if (newTransactionsData == null)
		{
			return;
		}

		if (Util.arraysAreDifferent(lastTransactionsData, newTransactionsData))
		{
			LOG.fine("Updating table of transactions...");
			this.remove(transactionsTablePane);
			this.add(transactionsTablePane = new JScrollPane(
			             transactionsTable = this.createTransactionsTable(newTransactionsData)),
			         BorderLayout.CENTER);
		}

		lastTransactionsData = newTransactionsData;

		this.validate();
		this.repaint();
	}

	private JTable createTransactionsTable(String rowData[][])
		throws WalletCallException, IOException, InterruptedException
	{
		String columnNames[] = { "Type", "Direction", "Confirmed?", "Amount", "Date", "Destination Address"};
        JTable table = new TransactionTable(
        	rowData, columnNames, this.parentFrame, this.clientCaller);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        table.getColumnModel().getColumn(0).setPreferredWidth(190);
        table.getColumnModel().getColumn(1).setPreferredWidth(145);
        table.getColumnModel().getColumn(2).setPreferredWidth(170);
        table.getColumnModel().getColumn(3).setPreferredWidth(210);
        table.getColumnModel().getColumn(4).setPreferredWidth(405);
        table.getColumnModel().getColumn(5).setPreferredWidth(800);

        return table;
	}

	private String[][] getTransactionsDataFromWallet()
		throws WalletCallException, IOException, InterruptedException
	{
		// Get available public+private transactions and unify them.
		String[][] publicTransactions = this.clientCaller.getWalletPublicTransactions();
		String[][] zReceivedTransactions = this.clientCaller.getWalletZReceivedTransactions();

		String[][] allTransactions = new String[publicTransactions.length + zReceivedTransactions.length][];

		int i  = 0;

		for (String[] t : publicTransactions)
		{
			allTransactions[i++] = t;
		}

		for (String[] t : zReceivedTransactions)
		{
			allTransactions[i++] = t;
		}

		// Sort transactions by date
		Arrays.sort(allTransactions, new Comparator<String[]>() {
			public int compare(String[] o1, String[] o2)
			{
				Date d1 = new Date(0);
				if (!o1[4].equals("N/A"))
				{
					d1 = new Date(Long.valueOf(o1[4]).longValue() * 1000L);
				}

				Date d2 = new Date(0);
				if (!o2[4].equals("N/A"))
				{
					d2 = new Date(Long.valueOf(o2[4]).longValue() * 1000L);
				}

				if (d1.equals(d2))
				{
					return 0;
				} else
				{
					return d2.compareTo(d1);
				}
			}
		});

		DecimalFormat df = new DecimalFormat("########0.00######");

		// Change the direction and date etc. attributes for presentation purposes
		for (String[] trans : allTransactions)
		{
			// Direction
			if (trans[1].equals("receive"))
			{
				trans[1] = "\u21E8 IN";
			} else if (trans[1].equals("send"))
			{
				trans[1] = "\u21E6 OUT";
			} else if (trans[1].equals("generate"))
			{
				trans[1] = "\u2692\u2699 MINED";
			} else if (trans[1].equals("immature"))
			{
				trans[1] = "\u2696 Immature";
			};

			// Date
			if (!trans[4].equals("N/A"))
			{
				trans[4] = new Date(Long.valueOf(trans[4]).longValue() * 1000L).toLocaleString();
			}

			// Amount
			try
			{
				double amount = Double.valueOf(trans[3]);
				if (amount < 0d)
				{
					amount = -amount;
				}
				trans[3] = df.format(amount);
			} catch (NumberFormatException nfe)
			{
				LOG.log(Level.WARNING,"Error occurred while formatting amount: " + trans[3] +
						           " - " + nfe.getMessage() + "!",nfe);
			}

			// Confirmed?
			try
			{
				boolean isConfirmed = !trans[2].trim().equals("0");

				trans[2] = isConfirmed ? "Yes \u2690" : "No  \u2691";
			} catch (NumberFormatException nfe)
			{
				LOG.log(Level.WARNING,"Error occurred while formatting confirmations: " + trans[2] +
						           " - " + nfe.getMessage() + "!",nfe);
			}
		}

		return allTransactions;
	}

} // End class


text:
package se.test.dao.impl;

import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

import se.test.dao.Datastore;

public class DatastoreImpl implements Datastore {

	private final DatastoreService datastore;

    public DatastoreImpl()
    {
    	this.datastore = DatastoreServiceFactory.getDatastoreService();
    }

	public List<Entity> getEntityList(String kind, Integer limit) {
		Query query = new Query(kind);

		return datastore.prepare(query).asList(FetchOptions.Builder.withLimit(limit));
	}

	public void deleteEntity(String kind, long id)
	{
		Key key = KeyFactory.createKey(kind, id);
		datastore.delete(key);
	}

	public void updateEntity(String kind, Map<String, Object> properties, long id)
	{
		Key key = KeyFactory.createKey(kind, id);
		Entity entity = new Entity(key);
		for(Map.Entry<String, Object> property : properties.entrySet())
		{
			entity.setProperty(property.getKey(), property.getValue());
		}
		datastore.put(entity);
	}

	public void setEntity(String kind, Map<String, Object> properties) {

		Entity entity = new Entity(kind);
		for(Map.Entry<String, Object> property : properties.entrySet())
		{
			entity.setProperty(property.getKey(), property.getValue());
		}
		datastore.put(entity);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<person xmlns="http://ns.opensocial.org/2008/opensocial">
  <displayName></displayName>
  <gender>female</gender>
  <id></id>
  <name>
    <formatted>Jane Doe</formatted>
  </name>
</person>


text:
Pattern: Use of duplicate polyfills

Issue: -

## Description

You are using Polyfill.io and including duplicate polyfills already shipped with Next.js. This increases page weight unnecessarily which can affect loading performance.

#### Possible Ways to Fix It

Remove all duplicate polyfills that are included with Polyfill.io. If you need to add polyfills but are not sure if Next.js already includes it, take a look at the list of [supported browsers and features](https://nextjs.org/docs/basic-features/supported-browsers-features) first.

## Further Reading

* [next.js - Duplicate Polyfills from Polyfill.io](https://nextjs.org/docs/messages/no-unwanted-polyfillio)


text:
package pkg.xfl.unary;

import xfuzzy.lang.*;

public class sugeno extends Unary {
 public sugeno() {
   super("xfl","sugeno");
   Parameter single[] = new Parameter[1];
   single[0] = new Parameter("l");
   setSingleParameters(single);
  }

 public double compute(double a) {
   double l = singleparam[0].value;
 return (1-a)/(1+a*l);
  }

 public double derivative(double a) {
   double deriv;
   double l = singleparam[0].value;
 deriv = -(1+l)/((1+l*a)*(1+l*a));
   return deriv;
  }

 public boolean test () {
   double l = singleparam[0].value;
   return ( l>-1 );
  }

 public String getJavaCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (1-a)/(1+a*l); "+eol;
   return code;
  }

 public String getCCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (1-a)/(1+a*l); "+eol;
   return code;
  }

 public String getCppCode() {
   String eol = System.getProperty("line.separator", "\n");
   String code = "";
   code += "    return (1-a)/(1+a*l); "+eol;
   return code;
  }
}


text:
namespace _03.EnduranceRally
{
    using System;
    using System.Linq;

    public class EnduranceRally
    {
        public static void Main()
        {
            var players = Console.ReadLine().Split().Select(x => x.Trim()).ToArray();

            var positions = Console.ReadLine().Split().Select(double.Parse).ToArray();

            var chekPoints = Console.ReadLine().Split().Select(double.Parse).ToArray();

            foreach (var player in players)
            {
                double fuel = player[0];

                var hasFinished = true;

                for (int i = 0; i < positions.Length; i++)
                {
                    if (chekPoints.Contains(i))
                    {
                        fuel += positions[i];
                    }
                    else
                    {
                        fuel -= positions[i];
                    }
                    if (fuel <= 0)
                    {
                        Console.WriteLine($"{player} - reached {i}");

                        hasFinished = false;

                        break;
                    }
                }

                if (hasFinished)
                {
                    Console.WriteLine($"{player} - fuel left {fuel:F2}");
                }
            }
        }
    }
}


text:
package org.acdd.runtime;

import org.acdd.framework.Framework;
import org.osgi.framework.Bundle;

import java.util.List;

/***
 * DelegateClassLoader is ClassLoader custom implementation,used for  bundle class load<br>
 * override  findClass
 ***/
public class DelegateClassLoader extends ClassLoader {
    // add pathList field to make ACDD compatible with 'com.android.support:multidex'
    //private Object pathList;
    public DelegateClassLoader(ClassLoader classLoader) {
        super(classLoader);
//        try {
//            Class classBaseDexClassLoader = Class.forName("dalvik.system.BaseDexClassLoader");
//            if (classBaseDexClassLoader.isInstance(classLoader)) {
//                Field fieldPathList = classBaseDexClassLoader.getDeclaredField("pathList");
//                fieldPathList.setAccessible(true);
//                Object object = fieldPathList.get(classLoader);
//                this.pathList = object;
//            }
//
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//
//        } catch (NoSuchFieldException e) {
//            e.printStackTrace();
//
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public Class<?> loadClass(String className) throws ClassNotFoundException {
        return super.loadClass(className);
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        ClassLoadFromBundle.checkInstallBundleIfNeed(className);
        Class<?> loadFromInstalledBundles = ClassLoadFromBundle.loadFromInstalledBundles(className);
        if (loadFromInstalledBundles != null) {
            return loadFromInstalledBundles;
        }
        throw new ClassNotFoundException("Can't find class " + className + printExceptionInfo() + " " + ClassLoadFromBundle.getClassNotFoundReason(className));
    }

    private String printExceptionInfo() {
        StringBuilder stringBuilder = new StringBuilder("installed bundles: ");
        List<Bundle> bundles = Framework.getBundles();
        if (!(bundles == null || bundles.isEmpty())) {
            for (Bundle bundle : Framework.getBundles()) {

                stringBuilder.append(bundle.getLocation());

                stringBuilder.append(":");
            }
        }
        return stringBuilder.toString();
    }
}


text:
#ifndef WRAPPER_H
#define WRAPPER_H

#ifndef WIN32
	#define _GNU_SOURCE
#endif

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

#if !defined(NFS_CPP) && (defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64))
	#define STDCALL __attribute__((stdcall))
	#define REGPARM __attribute__((regparm(2))) //First two arguments are compatible with Watcom fastcall

	#define MAYBE_THIS_SINGLE void
	#define MAYBE_THIS
#else
	#define STDCALL
	#define REGPARM

	#define MAYBE_THIS_SINGLE void *this
	#define MAYBE_THIS void *this,

	#ifndef NFS_CPP
		#define NFS_CPP
	#endif
#endif

#if !defined(NFS_CPP) && defined(STACK_REALIGN)
	#define REALIGN __attribute__((force_align_arg_pointer))
#else
	#define REALIGN
#endif

#define MAX_PATH 260

#define BOOL int32_t
#define false 0
#define true 1

typedef uint32_t (STDCALL *WindowProc)(MAYBE_THIS void *hWnd, uint32_t uMsg, uint32_t wParam, uint32_t lParam);

char *convertFilePath(const char *srcPth, BOOL convToLower);

#endif // WRAPPER_H


text:
CREATE TABLE t1(a, b);
BEGIN;
INSERT INTO t1 VALUES(1, 2);


text:
$(document).ready(function() {
    resizeStub();
});

function resizeStub(buttonsOffset) {
    if (typeof(buttonsOffset) === 'undefined') {
        buttonsOffset = 36;
    }
    var stub = $('div.stub'),
        fullContainerSection = $('section.full_container_section'),
        containerOffset = fullContainerSection.offset();

    // Make view form non-editable
    stub.ready(function() {
        stub.show();

        // 10 px for top heading that comes out of the parent div
        // and minus px for bottom print buttons
        stub.height(fullContainerSection.height() + containerOffset.top - buttonsOffset);
        stub.width(fullContainerSection.width());

        stub.offset({'top' : 0, 'left' : 0});
    });
}


text:
def sort_by_likes(decks):
    return sorted(decks, key=lambda l: l[0], reverse=True)

def sort_by_faves(decks):
    return sorted(decks, key=lambda l: l[1], reverse=True)

def sort_by_comments(decks):
    return sorted(decks, key=lambda l: l[2], reverse=True)

def sort_by_name(decks):
    return sorted(decks, key=lambda l: l[3].lower())

def sort_by_user(decks):
    return sorted(decks, key=lambda l: l[5].lower())

def sort_by_rep(decks):
    return sorted(decks, key=lambda l: l[6], reverse=True)

def sort_by_date(decks):
    return sorted(decks, key=lambda l: l[7], reverse=True)

def sort_by_most_decks(decks):
    user_dict = most_prolific_users(decks)
    return sorted(user_dict.items(), key=lambda l: l[1], reverse=True)

def sort_by_most_rep(decks):
    user_dict = most_prolific_users(decks)
    return sorted(user_dict.items(), key=lambda l: l[1][1], reverse=True)

def most_prolific_users(decks):
    """Retrieves rep and number of decks in Hall of Fame for each user"""
    users = {}
    decks = sort_by_user(decks)
    for deck in decks:
        user = deck[5]
        if not user in users:
            users[user] = [1, deck[6]]
        else:
            users[user][0] += 1
    return users


text:
import { pixelsToNumber } from './utils';
/** @internal */
export function getJQueryLeftAndTop(element) {
    const style = getComputedStyle(element, null);
    const leftAndTop = {
        left: pixelsToNumber(style.left),
        top: pixelsToNumber(style.top),
    };
    return leftAndTop;
}
//# sourceMappingURL=jquery-legacy.js.map


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NuGetGallery
{
    public interface ICuratedFeedService
    {
        IQueryable<Package> GetPackages(string curatedFeedName);

        IQueryable<PackageRegistration> GetPackageRegistrations(string curatedFeedName);

        int? GetKey(string curatedFeedName);
    }
}


text:
<?php

namespace Symfony\Component\Security\Core\Authentication\Token;

use Symfony\Component\Security\Core\User\UserInterface;

/**
 * AnonymousToken represents an anonymous token.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @deprecated since 5.4, anonymous is now represented by the absence of a token
 */
class AnonymousToken extends AbstractToken
{
    private $secret;

    /**
     * @param string                           $secret A secret used to make sure the token is created by the app and not by a malicious client
     * @param string|\Stringable|UserInterface $user
     * @param string[]                         $roles
     */
    public function __construct(string $secret, $user, array $roles = [])
    {
        trigger_deprecation('symfony/security-core', '5.4', 'The "%s" class is deprecated.', __CLASS__);

        parent::__construct($roles);

        $this->secret = $secret;
        $this->setUser($user);
        // @deprecated since Symfony 5.4
        $this->setAuthenticated(true, false);
    }

    /**
     * {@inheritdoc}
     */
    public function getCredentials()
    {
        return '';
    }

    /**
     * Returns the secret.
     *
     * @return string
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * {@inheritdoc}
     */
    public function __serialize(): array
    {
        return [$this->secret, parent::__serialize()];
    }

    /**
     * {@inheritdoc}
     */
    public function __unserialize(array $data): void
    {
        [$this->secret, $parentData] = $data;
        $parentData = \is_array($parentData) ? $parentData : unserialize($parentData);
        parent::__unserialize($parentData);
    }
}


text:
class AddPolymorphicColumnToProfileData < ActiveRecord::Migration
  def up
    add_column :educations, :owner_id, :integer
    add_column :educations, :owner_type, :string
    add_column :careers, :owner_id, :integer
    add_column :careers, :owner_type, :string
    add_column :licenses, :owner_id, :integer
    add_column :licenses, :owner_type, :string
    add_column :awards, :owner_id, :integer
    add_column :awards, :owner_type, :string
    add_column :punishments, :owner_id, :integer
    add_column :punishments, :owner_type, :string
    add_column :reviews, :owner_id, :integer
    add_column :reviews, :owner_type, :string
    add_column :articles, :owner_id, :integer
    add_column :articles, :owner_type, :string

    add_index :educations, [:owner_id, :owner_type]
    add_index :careers, [:owner_id, :owner_type]
    add_index :licenses, [:owner_id, :owner_type]
    add_index :awards, [:owner_id, :owner_type]
    add_index :punishments, [:owner_id, :owner_type]
    add_index :reviews, [:owner_id, :owner_type]
    add_index :articles, [:owner_id, :owner_type]
  end

  def down
    remove_column :educations, :owner_id
    remove_column :educations, :owner_type
    remove_column :careers, :owner_id
    remove_column :careers, :owner_type
    remove_column :licenses, :owner_id
    remove_column :licenses, :owner_type
    remove_column :awards, :owner_id
    remove_column :awards, :owner_type
    remove_column :punishments, :owner_id
    remove_column :punishments, :owner_type
    remove_column :reviews, :owner_id
    remove_column :reviews, :owner_type
    remove_column :articles, :owner_id
    remove_column :articles, :owner_type
  end
end


text:
@implementation UIView (Rect)

- (void)setX:(CGFloat)x{
    CGRect frame = self.frame;
    frame.origin.x = isnan(x) ? 0 : x;
    self.frame = frame;
}

- (CGFloat)x{
    return self.frame.origin.x;
}

- (void)setY:(CGFloat)y{
    CGRect frame = self.frame;
    frame.origin.y = isnan(y) ? 0 : y;
    self.frame = frame;
}

- (CGFloat)y{
    return self.frame.origin.y;
}

- (void)setCenterX:(CGFloat)centerX{
    CGPoint center = self.center;
    center.x = isnan(centerX) ? 0 : centerX;
    self.center = center;
}

- (CGFloat)centerX{
    return self.center.x;
}

- (void)setCenterY:(CGFloat)centerY{
    CGPoint center = self.center;
    center.y = isnan(centerY) ? 0 : centerY;
    self.center = center;
}

- (CGFloat)centerY{
    return self.center.y;
}

- (void)setWidth:(CGFloat)width{
    CGRect frame = self.frame;
    frame.size.width = isnan(width) ? 0 : width;
    self.frame = frame;
}

- (CGFloat)width{
    return self.frame.size.width;
}

- (void)setHeight:(CGFloat)height{
    CGRect frame = self.frame;
    frame.size.height = isnan(height) ? 0 : height;
    self.frame = frame;
}

- (CGFloat)height{
    return self.frame.size.height;
}

- (void)setSize:(CGSize)size{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)size{
    return self.frame.size;
}

- (void)setMaxX:(CGFloat)maxX{
    CGRect frame = self.frame;
    double offset = maxX - CGRectGetMaxX(frame);
    frame.origin.x += offset;
    self.frame = frame;
}

- (CGFloat)maxX{
    return CGRectGetMaxX(self.frame);
}

- (void)setMaxY:(CGFloat)maxY{
    CGRect frame = self.frame;
    double offset = maxY - CGRectGetMaxY(frame);
    frame.origin.x += offset;
    self.frame = frame;
}

- (CGFloat)maxY{
    return CGRectGetMaxY(self.frame);
}

-(void)addBorderLineWithLineColor:(UIColor *)color width:(CGFloat)width cornerRadius:(CGFloat)radius
{
    self.layer.borderColor = [color CGColor];
    self.layer.borderWidth = width;
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = YES;
}

@end


text:
#include <cutils/ashmem.h>

/*
 * Implementation of the user-space ashmem API for devices, which have our
 * ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
 * used by the simulator.
 */
#define LOG_TAG "ashmem"

#include <errno.h>
#include <fcntl.h>
#include <linux/ashmem.h>
#include <linux/memfd.h>
#include <log/log.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>

#include <android-base/file.h>
#include <android-base/properties.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>

/* Will be added to UAPI once upstream change is merged */
#define F_SEAL_FUTURE_WRITE 0x0010

/*
 * The minimum vendor API level at and after which it is safe to use memfd.
 * This is to facilitate deprecation of ashmem.
 */
#define MIN_MEMFD_VENDOR_API_LEVEL 29
#define MIN_MEMFD_VENDOR_API_LEVEL_CHAR 'Q'

/* ashmem identity */
static dev_t __ashmem_rdev;
/*
 * If we trigger a signal handler in the middle of locked activity and the
 * signal handler calls ashmem, we could get into a deadlock state.
 */
static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;

/*
 * has_memfd_support() determines if the device can use memfd. memfd support
 * has been there for long time, but certain things in it may be missing.  We
 * check for needed support in it. Also we check if the VNDK version of
 * libcutils being used is new enough, if its not, then we cannot use memfd
 * since the older copies may be using ashmem so we just use ashmem. Once all
 * Android devices that are getting updates are new enough (ex, they were
 * originally shipped with Android release > P), then we can just use memfd and
 * delete all ashmem code from libcutils (while preserving the interface).
 *
 * NOTE:
 * The sys.use_memfd property is set by default to false in Android
 * to temporarily disable memfd, till vendor and apps are ready for it.
 * The main issue: either apps or vendor processes can directly make ashmem
 * IOCTLs on FDs they receive by assuming they are ashmem, without going
 * through libcutils. Such fds could have very well be originally created with
 * libcutils hence they could be memfd. Thus the IOCTLs will break.
 *
 * Set default value of sys.use_memfd property to true once the issue is
 * resolved, so that the code can then self-detect if kernel support is present
 * on the device. The property can also set to true from adb shell, for
 * debugging.
 */

static bool debug_log = false;            /* set to true for verbose logging and other debug  */
static bool pin_deprecation_warn = true; /* Log the pin deprecation warning only once */

/* Determine if vendor processes would be ok with memfd in the system:
 *
 * If VNDK is using older libcutils, don't use memfd. This is so that the
 * same shared memory mechanism is used across binder transactions between
 * vendor partition processes and system partition processes.
 */
static bool check_vendor_memfd_allowed() {
    std::string vndk_version = android::base::GetProperty("ro.vndk.version", "");

    if (vndk_version == "") {
        ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
              vndk_version.c_str());
        return false;
    }

    /* No issues if vendor is targetting current Dessert */
    if (vndk_version == "current") {
        return false;
    }

    /* Check if VNDK version is a number and act on it */
    char* p;
    long int vers = strtol(vndk_version.c_str(), &p, 10);
    if (*p == 0) {
        if (vers < MIN_MEMFD_VENDOR_API_LEVEL) {
            ALOGI("memfd: device VNDK version (%s) is < Q so using ashmem.\n",
                  vndk_version.c_str());
            return false;
        }

        return true;
    }

    // Non-numeric should be a single ASCII character. Characters after the
    // first are ignored.
    if (tolower(vndk_version[0]) < 'a' || tolower(vndk_version[0]) > 'z') {
        ALOGE("memfd: ro.vndk.version not defined or invalid (%s), this is mandated since P.\n",
              vndk_version.c_str());
        return false;
    }

    if (tolower(vndk_version[0]) < tolower(MIN_MEMFD_VENDOR_API_LEVEL_CHAR)) {
        ALOGI("memfd: device is using VNDK version (%s) which is less than Q. Use ashmem only.\n",
              vndk_version.c_str());
        return false;
    }

    return true;
}

/* Determine if memfd can be supported. This is just one-time hardwork
 * which will be cached by the caller.
 */
static bool __has_memfd_support() {
    if (check_vendor_memfd_allowed() == false) {
        return false;
    }

    /* Used to turn on/off the detection at runtime, in the future this
     * property will be removed once we switch everything over to ashmem.
     * Currently it is used only for debugging to switch the system over.
     */
    if (!android::base::GetBoolProperty("sys.use_memfd", false)) {
        if (debug_log) {
            ALOGD("sys.use_memfd=false so memfd disabled\n");
        }
        return false;
    }

    // Check if kernel support exists, otherwise fall back to ashmem.
    // This code needs to build on old API levels, so we can't use the libc
    // wrapper.
    android::base::unique_fd fd(
            syscall(__NR_memfd_create, "test_android_memfd", MFD_CLOEXEC | MFD_ALLOW_SEALING));
    if (fd == -1) {
        ALOGE("memfd_create failed: %s, no memfd support.\n", strerror(errno));
        return false;
    }

    if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
        ALOGE("fcntl(F_ADD_SEALS) failed: %s, no memfd support.\n", strerror(errno));
        return false;
    }

    if (debug_log) {
        ALOGD("memfd: device has memfd support, using it\n");
    }
    return true;
}

static bool has_memfd_support() {
    /* memfd_supported is the initial global per-process state of what is known
     * about memfd.
     */
    static bool memfd_supported = __has_memfd_support();

    return memfd_supported;
}

static std::string get_ashmem_device_path() {
    static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
    std::string boot_id;
    if (!android::base::ReadFileToString(boot_id_path, &boot_id)) {
        ALOGE("Failed to read %s: %s.\n", boot_id_path.c_str(), strerror(errno));
        return "";
    };
    boot_id = android::base::Trim(boot_id);

    return "/dev/ashmem" + boot_id;
}

/* logistics of getting file descriptor for ashmem */
static int __ashmem_open_locked()
{
    static const std::string ashmem_device_path = get_ashmem_device_path();

    if (ashmem_device_path.empty()) {
        return -1;
    }

    int fd = TEMP_FAILURE_RETRY(open(ashmem_device_path.c_str(), O_RDWR | O_CLOEXEC));

    // fallback for APEX w/ use_vendor on Q, which would have still used /dev/ashmem
    if (fd < 0) {
        int saved_errno = errno;
        fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDWR | O_CLOEXEC));
        if (fd < 0) {
            /* Q launching devices and newer must not reach here since they should have been
             * able to open ashmem_device_path */
            ALOGE("Unable to open ashmem device %s (error = %s) and /dev/ashmem(error = %s)",
                  ashmem_device_path.c_str(), strerror(saved_errno), strerror(errno));
            return fd;
        }
    }
    struct stat st;
    int ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
    if (ret < 0) {
        int save_errno = errno;
        close(fd);
        errno = save_errno;
        return ret;
    }
    if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
        close(fd);
        errno = ENOTTY;
        return -1;
    }

    __ashmem_rdev = st.st_rdev;
    return fd;
}

static int __ashmem_open()
{
    int fd;

    pthread_mutex_lock(&__ashmem_lock);
    fd = __ashmem_open_locked();
    pthread_mutex_unlock(&__ashmem_lock);

    return fd;
}

/* Make sure file descriptor references ashmem, negative number means false */
static int __ashmem_is_ashmem(int fd, int fatal)
{
    dev_t rdev;
    struct stat st;

    if (fstat(fd, &st) < 0) {
        return -1;
    }

    rdev = 0; /* Too much complexity to sniff __ashmem_rdev */
    if (S_ISCHR(st.st_mode) && st.st_rdev) {
        pthread_mutex_lock(&__ashmem_lock);
        rdev = __ashmem_rdev;
        if (rdev) {
            pthread_mutex_unlock(&__ashmem_lock);
        } else {
            int fd = __ashmem_open_locked();
            if (fd < 0) {
                pthread_mutex_unlock(&__ashmem_lock);
                return -1;
            }
            rdev = __ashmem_rdev;
            pthread_mutex_unlock(&__ashmem_lock);

            close(fd);
        }

        if (st.st_rdev == rdev) {
            return 0;
        }
    }

    if (fatal) {
        if (rdev) {
            LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
              fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
              S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
              major(rdev), minor(rdev));
        } else {
            LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
              fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
              S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
        }
        /* NOTREACHED */
    }

    errno = ENOTTY;
    return -1;
}

static int __ashmem_check_failure(int fd, int result)
{
    if (result == -1 && errno == ENOTTY) __ashmem_is_ashmem(fd, 1);
    return result;
}

static bool memfd_is_ashmem(int fd) {
    static bool fd_check_error_once = false;

    if (__ashmem_is_ashmem(fd, 0) == 0) {
        if (!fd_check_error_once) {
            ALOGE("memfd: memfd expected but ashmem fd used - please use libcutils.\n");
            fd_check_error_once = true;
        }

        return true;
    }

    return false;
}

int ashmem_valid(int fd)
{
    if (has_memfd_support() && !memfd_is_ashmem(fd)) {
        return 1;
    }

    return __ashmem_is_ashmem(fd, 0) >= 0;
}

static int memfd_create_region(const char* name, size_t size) {
    // This code needs to build on old API levels, so we can't use the libc
    // wrapper.
    android::base::unique_fd fd(syscall(__NR_memfd_create, name, MFD_CLOEXEC | MFD_ALLOW_SEALING));

    if (fd == -1) {
        ALOGE("memfd_create(%s, %zd) failed: %s\n", name, size, strerror(errno));
        return -1;
    }

    if (ftruncate(fd, size) == -1) {
        ALOGE("ftruncate(%s, %zd) failed for memfd creation: %s\n", name, size, strerror(errno));
        return -1;
    }

    if (debug_log) {
        ALOGE("memfd_create(%s, %zd) success. fd=%d\n", name, size, fd.get());
    }
    return fd.release();
}

/*
 * ashmem_create_region - creates a new ashmem region and returns the file
 * descriptor, or <0 on error
 *
 * `name' is an optional label to give the region (visible in /proc/pid/maps)
 * `size' is the size of the region, in page-aligned bytes
 */
int ashmem_create_region(const char *name, size_t size)
{
    int ret, save_errno;

    if (has_memfd_support()) {
        return memfd_create_region(name ? name : "none", size);
    }

    int fd = __ashmem_open();
    if (fd < 0) {
        return fd;
    }

    if (name) {
        char buf[ASHMEM_NAME_LEN] = {0};

        strlcpy(buf, name, sizeof(buf));
        ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
        if (ret < 0) {
            goto error;
        }
    }

    ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
    if (ret < 0) {
        goto error;
    }

    return fd;

error:
    save_errno = errno;
    close(fd);
    errno = save_errno;
    return ret;
}

static int memfd_set_prot_region(int fd, int prot) {
    /* Only proceed if an fd needs to be write-protected */
    if (prot & PROT_WRITE) {
        return 0;
    }

    if (fcntl(fd, F_ADD_SEALS, F_SEAL_FUTURE_WRITE) == -1) {
        ALOGE("memfd_set_prot_region(%d, %d): F_SEAL_FUTURE_WRITE seal failed: %s\n", fd, prot,
              strerror(errno));
        return -1;
    }

    return 0;
}

int ashmem_set_prot_region(int fd, int prot)
{
    if (has_memfd_support() && !memfd_is_ashmem(fd)) {
        return memfd_set_prot_region(fd, prot);
    }

    return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_PROT_MASK, prot)));
}

int ashmem_pin_region(int fd, size_t offset, size_t len)
{
    if (!pin_deprecation_warn || debug_log) {
        ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
        pin_deprecation_warn = true;
    }

    if (has_memfd_support() && !memfd_is_ashmem(fd)) {
        return 0;
    }

    // TODO: should LP64 reject too-large offset/len?
    ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
    return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin)));
}

int ashmem_unpin_region(int fd, size_t offset, size_t len)
{
    if (!pin_deprecation_warn || debug_log) {
        ALOGE("Pinning is deprecated since Android Q. Please use trim or other methods.\n");
        pin_deprecation_warn = true;
    }

    if (has_memfd_support() && !memfd_is_ashmem(fd)) {
        return 0;
    }

    // TODO: should LP64 reject too-large offset/len?
    ashmem_pin pin = { static_cast<uint32_t>(offset), static_cast<uint32_t>(len) };
    return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin)));
}

int ashmem_get_size_region(int fd)
{
    if (has_memfd_support() && !memfd_is_ashmem(fd)) {
        struct stat sb;

        if (fstat(fd, &sb) == -1) {
            ALOGE("ashmem_get_size_region(%d): fstat failed: %s\n", fd, strerror(errno));
            return -1;
        }

        if (debug_log) {
            ALOGD("ashmem_get_size_region(%d): %d\n", fd, static_cast<int>(sb.st_size));
        }

        return sb.st_size;
    }

    return __ashmem_check_failure(fd, TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)));
}


text:
+---------+-------------------+
| USPop   | R Documentation   |
+---------+-------------------+

Population of the United States
-------------------------------

Description
~~~~~~~~~~~

The ``USPop`` data frame has 22 rows and 1 columns. This is a decennial
time-series, from 1790 to 2000.

Usage
~~~~~

::

    USPop

Format
~~~~~~

This data frame contains the following columns:

year
    census year.

population
    Population in millions.

Source
~~~~~~

U.S.~Census Bureau:
`http://www.census-charts.com/Population/pop-us-1790-2000.html <http://www.census-charts.com/Population/pop-us-1790-2000.html>`__,
downloaded 1 May 2008.

References
~~~~~~~~~~

Fox, J. (2008) *Applied Regression Analysis and Generalized Linear
Models*, Second Edition. Sage.


text:
+++
date = "2015-03-03T08:51:32+12:00"
description = "Despite being on the back-burner it's still the number one quit smoking app on the Windows Phone app store."
title = "Monetising KickSmoking"
url = "/monetising-kicksmoking"
tags = ["article", "product", "kicksmoking"]
+++

[KickSmoking is a windows phone app](http://www.windowsphone.com/en-us/store/app/kicksmoking/53ab867a-417b-4aad-80e5-99022e0ce8d9) that I built 2-3 years ago which has been in maintenance mode for a while.

Despite being on the back-burner it's still the number one quit smoking app on the Windows Phone app store. It's had over 60k downloads and still achieves upwards of 50 new installs a day, and with 224 reviews at an average of 4.5 stars I'm not the only one who thinks it's awesome.

However, despite the stats I've only managed to earn about $300 to $400 over the lifetime of the application. I don't know many people who've managed to push over 60k downloads yet failed to make a grand.

This isn't due to the platform (the number of downloads are there) - I believe it's due to the poor monetisation strategy in use.

During this blog series we'll cover the existing app and monetisation model, the plan going forward, and finally the results of the experience.

### The current monetisation model

Currently there are two versions of the app, [a free version](http://www.windowsphone.com/en-us/store/app/kicksmoking/53ab867a-417b-4aad-80e5-99022e0ce8d9) and [a paid "pro" version](http://www.windowsphone.com/en-nz/store/app/kicksmoking/d4c56aa6-c4d3-494c-825a-d9a7e836cc1a).
The only difference between the two versions is that the free version is ad-supported.

The main failings with this model is that there is no way to upgrade from in the free app which has over 99% of the downloads - I'm convinced we're missing out on a lot of sales here.

Another area which can be improved is around premium features. We need to give more of an incentive to upgrade than just removing ads - however we still want the free app to be extremely useful so we will focus on adding features to the pro version rather than removing them from the free version.

### The plan

We're going to add an in-app upgrade option to allow free users to upgrade their app to the pro-version without downloading a whole new application. We want to make it as easy as possible for people to pay us!

We don't want to leave out our existing customers loyal customers, so we'll also keep our pro app up to date. As a bonus they will get all the new features at the lower price they originally purchased the app at as a thank-you for the support.

### The pricing

Cigarettes are expensive, so are developing apps. I've easily sunk more money into this little venture than received. At $1.99 it's just not sustainable - I've had people tell me they'll buy it if I lowered the price to $0.99, but with no disrespect if you're not going to buy it at $1.99, you're probably not going to buy it at $0.99.

The converse is also true to some extent so the price point will be moved to $4.99 - holding all else equal this should cover all the hosing costs for the back-end services.

This is about making the app sustainable - I want to be able to provide the best KickSmoking app available, and even port it to additional platforms. There needs to be a revenue stream to support this.

### New design

This isn't about squeezing money from an old app! We've not going to increase the price without upgrading the app, KickSmoking is showing it's age so we're going to introduce the new pricing along with a brand new app.

For the next instalment in the series we'll cover the new design and the features it uses to help encourage people to upgrade to the pro version.


text:
import IECore

import Gaffer
import GafferDispatch

class TaskContextProcessor( GafferDispatch.TaskNode ) :

	def __init__( self, name = "TaskContextProcessor" ) :

		GafferDispatch.TaskNode.__init__( self, name )

	def preTasks( self, context ) :

		contexts = self._processedContexts( context )

		result = []
		for plug in self["preTasks"] :

			source = plug.source()
			if source.isSame( plug ) :
				continue

			if not isinstance( source.node(), GafferDispatch.TaskNode ):
				continue

			result.extend( [ self.Task( source.node(), c ) for c in contexts ] )

		return result

	def hash( self, context ) :

		# Our hash is empty to signify that we don't do
		# anything in execute().
		return IECore.MurmurHash()

	def execute( self ) :

		# We don't need to do anything here because our
		# sole purpose is to manipulate the context
		# in which our preTasks are executed.
		pass

	## Must be implemented by derived classes to return
	# a list of contexts to be used by upstream tasks.
	def _processedContexts( self, context ) :

		raise NotImplementedError

IECore.registerRunTimeTyped( TaskContextProcessor, typeName = "GafferDispatch::TaskContextProcessor" )


text:
/*jslint node:true */
var fs = require('fs');
var path = require('path');

var file = "";
var jsonOutput = '',
    pageName = '';
var filePath = '';

/*fs.readFile(file, {encoding: 'utf-8'},function (err, data) {
    if(err) {
        console.log(err);
    } else {
        var array = data.toString().split("\n");
        for(i in array) {
            filePath = path.join("/Users/hjodiawalla/Desktop/MPPContentDevelopment/MPPContent/ContentRoot/US/en/", array[i], "/metadata.json")
            fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
                if (err) {
                    console.error(err);
                } else {
                    jsonOutput = JSON.parse(data);
                    pageName = jsonOutput.analyticsDescriptor.website + ":" + jsonOutput.analyticsDescriptor.feature + ":" + (jsonOutput.analyticsDescriptor.subFeature1 || "") + ":" + (jsonOutput.analyticsDescriptor.subFeature2 || "") + ":" + jsonOutput.analyticsDescriptor.contentTask;
                    console.log(pageName);
                }
            });
        }
    }
});*/

var contents = fs.readFileSync(file, {encoding: 'utf-8'}),
    array = contents.toString().split("\n"),
    json = '',
    i=0;

for (i in array) {
    filePath = "/Users/hjodiawalla/Desktop/MPPContentDevelopment/MPPContent/ContentRoot/JM/en/"+array[i]+"/metadata.json";
    json = fs.readFileSync(filePath, {encoding: 'utf-8'});
    jsonOutput = JSON.parse(json);
    pageName = jsonOutput.analyticsDescriptor.website + ":" + jsonOutput.analyticsDescriptor.feature + ":" + (jsonOutput.analyticsDescriptor.subFeature1 || "") + ":" + (jsonOutput.analyticsDescriptor.subFeature2 || "") + ":" + (jsonOutput.analyticsDescriptor.contentTask || "");
    console.log(pageName);
}


text:
'''
File    : thumbs.py
Author  : Nadav Samet
Contact : thesamet@gmail.com
Date    : 2010 Jun 17

Description : Thumbnailing functionality.
'''
import gtk
import os
import gc

THUMB_SIZE = 160

class ThumbLoader(object):
    """Thumbnail processing object."""
    def __init__(self, iconview, model, image_list):
        self.iconview, self.model, self.image_list = (
            iconview, model, list(image_list))
        # list of images with no thumbnail, to be generated.
        self.thumbnail_na = []
        self.thumbnail_generator = None

    def destroy(self):
        """Destroys the thumbnail generator."""
        self.model = None
        gc.collect()

    def __call__(self):
        if ((self.iconview.get_model() is not self.model) and
            (self.thumbnail_generator is None)):
            # if there's a different model for the icon view, then we are not
            # interesting anymore...
            self.destroy()
            return False

        if (not self.image_list and not self.thumbnail_na and
            self.thumbnail_generator is None):
            # we are done
            self.destroy()
            return False

        # Try to load as many as 20 images for which thumbnails are available
        count = 0
        while self.image_list and count < 20:
            image_dict = self.image_list.pop()
            item_data = image_dict['data']
            thumb = item_data['thumb']
            if (not os.path.exists(thumb) or
                os.path.getmtime(thumb) < os.path.getmtime(
                    item_data['filename'])):
                self.thumbnail_na.append(image_dict)
            else:
                pic = gtk.gdk.pixbuf_new_from_file(thumb)
                # IV_PIXBUF_COLUMN
                self.model.set_value(image_dict['position'], 1, pic)
                count += 1

        if self.thumbnail_na and self.thumbnail_generator is None:
            image_dict = self.thumbnail_na.pop()
            self.thumbnail_generator = thumbnail_generator(image_dict)

        if self.thumbnail_generator:
            try:
                pic = self.thumbnail_generator.next()
            except Exception:  # pylint: disable=W0703
                # many things can go wrong here.
                self.thumbnail_generator = None
            else:
                if pic is not None:
                    # IV_PIXBUF_COLUMN
                    self.model.set_value(pic[0]['position'], 1, pic[1])
                    self.thumbnail_generator = None

        return True

def thumbnail_generator(image_dict):
    """Generates a thumbnail. Loads the data slowly."""
    # Why is it a generator-function and not just a function?
    thumb_dir = os.path.dirname(image_dict['data']['thumb'])
    if not os.path.exists(thumb_dir):
        os.mkdir(thumb_dir)
    loader = gtk.gdk.PixbufLoader()
    try:
        fin = open(image_dict['data']['filename'], 'rb')
        while 1:
            data = fin.read(32768)
            if data:
                loader.write(data)
                yield None
            else:
                break
        pixbuf = loader.get_pixbuf()
        if pixbuf is None:
            raise ValueError(_("Invalid picture"))
        scaled = scale_image(pixbuf, image_dict['data']['thumb'])
        loader.close()
        loader = None
        fin.close()
        gc.collect()
        yield (image_dict, scaled)
    except (IOError, ValueError), exc:
        print image_dict['data']['filename'] + ': ' + str(exc)
        loader.close()
        loader = None
        raise

def scale_image(img, thumb):
    """Scales down a loaded image."""
    width, height = img.get_width(), img.get_height()
    scaled = img.scale_simple(THUMB_SIZE, THUMB_SIZE*height/width,
        gtk.gdk.INTERP_BILINEAR)
    scaled.save(thumb, 'jpeg', {"quality": "75"})
    return scaled


text:
using net::test::IsOk;

// TODO(eroman): Test that cookies aren't sent.

namespace net {

namespace {

const base::FilePath::CharType kDocRoot[] =
    FILE_PATH_LITERAL("net/data/cert_net_fetcher_impl_unittest");

const char kMockSecureDnsHostname[] = "mock.secure.dns.check";

// Wait for the request to complete, and verify that it completed successfully
// with the indicated bytes.
void VerifySuccess(const std::string& expected_body,
                   CertNetFetcher::Request* request) {
  Error actual_error;
  std::vector<uint8_t> actual_body;
  request->WaitForResult(&actual_error, &actual_body);

  EXPECT_THAT(actual_error, IsOk());
  EXPECT_EQ(expected_body, std::string(actual_body.begin(), actual_body.end()));
}

// Wait for the request to complete, and verify that it completed with the
// indicated failure.
void VerifyFailure(Error expected_error, CertNetFetcher::Request* request) {
  Error actual_error;
  std::vector<uint8_t> actual_body;
  request->WaitForResult(&actual_error, &actual_body);

  EXPECT_EQ(expected_error, actual_error);
  EXPECT_EQ(0u, actual_body.size());
}

struct NetworkThreadState {
  std::unique_ptr<URLRequestContext> context;
  // Owned by `context`.
  raw_ptr<TestNetworkDelegate> network_delegate;
};

class CertNetFetcherURLRequestTest : public PlatformTest {
 public:
  CertNetFetcherURLRequestTest() {
    test_server_.AddDefaultHandlers(base::FilePath(kDocRoot));
    StartNetworkThread();
  }

  ~CertNetFetcherURLRequestTest() override {
    if (!network_thread_)
      return;
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(&CertNetFetcherURLRequestTest::TeardownOnNetworkThread,
                       base::Unretained(this)));
    network_thread_->Stop();
  }

 protected:
  CertNetFetcher* fetcher() const { return fetcher_.get(); }

  void CreateFetcherOnNetworkThread(base::WaitableEvent* done) {
    fetcher_ = base::MakeRefCounted<CertNetFetcherURLRequest>();
    fetcher_->SetURLRequestContext(state_->context.get());
    done->Signal();
  }

  void CreateFetcher() {
    base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL,
                             base::WaitableEvent::InitialState::NOT_SIGNALED);
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(
            &CertNetFetcherURLRequestTest::CreateFetcherOnNetworkThread,
            base::Unretained(this), &done));
    done.Wait();
  }

  void ShutDownFetcherOnNetworkThread(base::WaitableEvent* done) {
    fetcher_->Shutdown();
    done->Signal();
  }

  void ShutDownFetcher() {
    base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL,
                             base::WaitableEvent::InitialState::NOT_SIGNALED);
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(
            &CertNetFetcherURLRequestTest::ShutDownFetcherOnNetworkThread,
            base::Unretained(this), &done));
    done.Wait();
  }

  int NumCreatedRequests() {
    int count = 0;
    base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL,
                             base::WaitableEvent::InitialState::NOT_SIGNALED);
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(&CertNetFetcherURLRequestTest::CountCreatedRequests,
                       base::Unretained(this), &count, &done));
    done.Wait();
    return count;
  }

  void StartNetworkThread() {
    // Start the network thread.
    network_thread_ = std::make_unique<base::Thread>("network thread");
    base::Thread::Options options(base::MessagePumpType::IO, 0);
    EXPECT_TRUE(network_thread_->StartWithOptions(std::move(options)));

    // Initialize the URLRequestContext (and wait till it has completed).
    base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL,
                             base::WaitableEvent::InitialState::NOT_SIGNALED);
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(&CertNetFetcherURLRequestTest::InitOnNetworkThread,
                       base::Unretained(this), &done));
    done.Wait();
  }

  void InitOnNetworkThread(base::WaitableEvent* done) {
    state_ = std::make_unique<NetworkThreadState>();
    auto builder = CreateTestURLRequestContextBuilder();
    state_->network_delegate =
        builder->set_network_delegate(std::make_unique<TestNetworkDelegate>());
    state_->context = builder->Build();
    done->Signal();
  }

  void ResetStateOnNetworkThread(base::WaitableEvent* done) {
    state_.reset();
    done->Signal();
  }

  void ResetState() {
    base::WaitableEvent done(base::WaitableEvent::ResetPolicy::MANUAL,
                             base::WaitableEvent::InitialState::NOT_SIGNALED);
    network_thread_->task_runner()->PostTask(
        FROM_HERE,
        base::BindOnce(&CertNetFetcherURLRequestTest::ResetStateOnNetworkThread,
                       base::Unretained(this), &done));
    done.Wait();
  }

  void TeardownOnNetworkThread() {
    fetcher_->Shutdown();
    state_.reset();
    fetcher_ = nullptr;
  }

  void CountCreatedRequests(int* count, base::WaitableEvent* done) {
    *count = state_->network_delegate->created_requests();
    done->Signal();
  }

  EmbeddedTestServer test_server_;
  std::unique_ptr<base::Thread> network_thread_;
  scoped_refptr<CertNetFetcherURLRequest> fetcher_;

  std::unique_ptr<NetworkThreadState> state_;
};

// Installs URLRequestHangingReadJob handlers and clears them on teardown.
class CertNetFetcherURLRequestTestWithHangingReadHandler
    : public CertNetFetcherURLRequestTest,
      public WithTaskEnvironment {
 protected:
  void SetUp() override { URLRequestHangingReadJob::AddUrlHandler(); }

  void TearDown() override { URLRequestFilter::GetInstance()->ClearHandlers(); }
};

// Interceptor to check that secure DNS has been disabled.
class SecureDnsInterceptor : public net::URLRequestInterceptor {
 public:
  explicit SecureDnsInterceptor(bool* invoked_interceptor)
      : invoked_interceptor_(invoked_interceptor) {}
  ~SecureDnsInterceptor() override = default;

 private:
  // URLRequestInterceptor implementation:
  std::unique_ptr<net::URLRequestJob> MaybeInterceptRequest(
      net::URLRequest* request) const override {
    EXPECT_EQ(SecureDnsPolicy::kDisable, request->secure_dns_policy());
    *invoked_interceptor_ = true;
    return nullptr;
  }

  raw_ptr<bool> invoked_interceptor_;
};

class CertNetFetcherURLRequestTestWithSecureDnsInterceptor
    : public CertNetFetcherURLRequestTest,
      public WithTaskEnvironment {
 public:
  CertNetFetcherURLRequestTestWithSecureDnsInterceptor() = default;

  void SetUp() override {
    URLRequestFilter::GetInstance()->AddHostnameInterceptor(
        "http", kMockSecureDnsHostname,
        std::make_unique<SecureDnsInterceptor>(&invoked_interceptor_));
  }

  void TearDown() override { URLRequestFilter::GetInstance()->ClearHandlers(); }

  bool invoked_interceptor() { return invoked_interceptor_; }

 private:
  bool invoked_interceptor_ = false;
};

// Helper to start an AIA fetch using default parameters.
[[nodiscard]] std::unique_ptr<CertNetFetcher::Request> StartRequest(
    CertNetFetcher* fetcher,
    const GURL& url) {
  return fetcher->FetchCaIssuers(url, CertNetFetcher::DEFAULT,
                                 CertNetFetcher::DEFAULT);
}

// Fetch a few unique URLs using GET in parallel. Each URL has a different body
// and Content-Type.
TEST_F(CertNetFetcherURLRequestTest, ParallelFetchNoDuplicates) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();

  // Request a URL with Content-Type "application/pkix-cert"
  GURL url1 = test_server_.GetURL("/cert.crt");
  std::unique_ptr<CertNetFetcher::Request> request1 =
      StartRequest(fetcher(), url1);

  // Request a URL with Content-Type "application/pkix-crl"
  GURL url2 = test_server_.GetURL("/root.crl");
  std::unique_ptr<CertNetFetcher::Request> request2 =
      StartRequest(fetcher(), url2);

  // Request a URL with Content-Type "application/pkcs7-mime"
  GURL url3 = test_server_.GetURL("/certs.p7c");
  std::unique_ptr<CertNetFetcher::Request> request3 =
      StartRequest(fetcher(), url3);

  // Wait for all of the requests to complete and verify the fetch results.
  VerifySuccess("-cert.crt-\n", request1.get());
  VerifySuccess("-root.crl-\n", request2.get());
  VerifySuccess("-certs.p7c-\n", request3.get());

  EXPECT_EQ(3, NumCreatedRequests());
}

// Fetch a caIssuers URL which has an unexpected extension and Content-Type.
// The extension is .txt and the Content-Type is text/plain. Despite being
// unusual this succeeds as the extension and Content-Type are not required to
// be meaningful.
TEST_F(CertNetFetcherURLRequestTest, ContentTypeDoesntMatter) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();

  GURL url = test_server_.GetURL("/foo.txt");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifySuccess("-foo.txt-\n", request.get());
}

// Fetch a URLs whose HTTP response code is not 200. These are considered
// failures.
TEST_F(CertNetFetcherURLRequestTest, HttpStatusCode) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();

  // Response was HTTP status 404.
  {
    GURL url = test_server_.GetURL("/404.html");
    std::unique_ptr<CertNetFetcher::Request> request =
        StartRequest(fetcher(), url);
    VerifyFailure(ERR_HTTP_RESPONSE_CODE_FAILURE, request.get());
  }

  // Response was HTTP status 500.
  {
    GURL url = test_server_.GetURL("/500.html");
    std::unique_ptr<CertNetFetcher::Request> request =
        StartRequest(fetcher(), url);
    VerifyFailure(ERR_HTTP_RESPONSE_CODE_FAILURE, request.get());
  }
}

// Fetching a URL with a Content-Disposition header should have no effect.
TEST_F(CertNetFetcherURLRequestTest, ContentDisposition) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();

  GURL url = test_server_.GetURL("/downloadable.js");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifySuccess("-downloadable.js-\n", request.get());
}

// Verifies that a cacheable request will be served from the HTTP cache the
// second time it is requested.
TEST_F(CertNetFetcherURLRequestTest, Cache) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  // Fetch a URL whose HTTP headers make it cacheable for 1 hour.
  GURL url(test_server_.GetURL("/cacheable_1hr.crt"));
  {
    std::unique_ptr<CertNetFetcher::Request> request =
        StartRequest(fetcher(), url);
    VerifySuccess("-cacheable_1hr.crt-\n", request.get());
  }

  EXPECT_EQ(1, NumCreatedRequests());

  // Kill the HTTP server.
  ASSERT_TRUE(test_server_.ShutdownAndWaitUntilComplete());

  // Fetch again -- will fail unless served from cache.
  {
    std::unique_ptr<CertNetFetcher::Request> request =
        StartRequest(fetcher(), url);
    VerifySuccess("-cacheable_1hr.crt-\n", request.get());
  }

  EXPECT_EQ(2, NumCreatedRequests());
}

// Verify that the maximum response body constraints are enforced by fetching a
// resource that is larger than the limit.
TEST_F(CertNetFetcherURLRequestTest, TooLarge) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  // This file has a response body 12 bytes long. So setting the maximum to 11
  // bytes will cause it to fail.
  GURL url(test_server_.GetURL("/certs.p7c"));
  std::unique_ptr<CertNetFetcher::Request> request =
      fetcher()->FetchCaIssuers(url, CertNetFetcher::DEFAULT, 11);

  VerifyFailure(ERR_FILE_TOO_BIG, request.get());
}

// Set the timeout to 10 milliseconds, and try fetching a URL that takes 5
// seconds to complete. It should fail due to a timeout.
TEST_F(CertNetFetcherURLRequestTest, Hang) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url(test_server_.GetURL("/slow/certs.p7c?5"));
  std::unique_ptr<CertNetFetcher::Request> request =
      fetcher()->FetchCaIssuers(url, 10, CertNetFetcher::DEFAULT);
  VerifyFailure(ERR_TIMED_OUT, request.get());
}

// Verify that if a response is gzip-encoded it gets inflated before being
// returned to the caller.
TEST_F(CertNetFetcherURLRequestTest, Gzip) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url(test_server_.GetURL("/gzipped_crl"));
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifySuccess("-gzipped_crl-\n", request.get());
}

// Try fetching an unsupported URL scheme (https).
TEST_F(CertNetFetcherURLRequestTest, HttpsNotAllowed) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url("https://foopy/foo.crt");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifyFailure(ERR_DISALLOWED_URL_SCHEME, request.get());

  // No request was created because the URL scheme was unsupported.
  EXPECT_EQ(0, NumCreatedRequests());
}

// Try fetching a URL which redirects to https.
TEST_F(CertNetFetcherURLRequestTest, RedirectToHttpsNotAllowed) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url(test_server_.GetURL("/redirect_https"));

  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifyFailure(ERR_DISALLOWED_URL_SCHEME, request.get());

  EXPECT_EQ(1, NumCreatedRequests());
}

// Try fetching an unsupported URL scheme (https) and then immediately
// cancelling. This is a bit special because this codepath needs to post a task.
TEST_F(CertNetFetcherURLRequestTest, CancelHttpsNotAllowed) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url("https://foopy/foo.crt");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);

  // Cancel the request (May or may not have started yet, as the request is
  // running on another thread).
  request.reset();
}

// Start a few requests, and cancel one of them before running the message loop
// again.
TEST_F(CertNetFetcherURLRequestTest, CancelBeforeRunningMessageLoop) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url1 = test_server_.GetURL("/cert.crt");
  std::unique_ptr<CertNetFetcher::Request> request1 =
      StartRequest(fetcher(), url1);

  GURL url2 = test_server_.GetURL("/root.crl");
  std::unique_ptr<CertNetFetcher::Request> request2 =
      StartRequest(fetcher(), url2);

  GURL url3 = test_server_.GetURL("/certs.p7c");

  std::unique_ptr<CertNetFetcher::Request> request3 =
      StartRequest(fetcher(), url3);

  // Cancel the second request.
  request2.reset();

  // Wait for the non-cancelled requests to complete, and verify the fetch
  // results.
  VerifySuccess("-cert.crt-\n", request1.get());
  VerifySuccess("-certs.p7c-\n", request3.get());
}

// Start several requests, and cancel one of them after the first has completed.
// NOTE: The python test server is single threaded and can only service one
// request at a time. After a socket is opened by the server it waits for it to
// be completed, and any subsequent request will hang until the first socket is
// closed.
// Cancelling the first request can therefore be problematic, since if
// cancellation is done after the socket is opened but before reading/writing,
// then the socket is re-cycled and things will be stalled until the cleanup
// timer (10 seconds) closes it.
// To work around this, the last request is cancelled, and hope that the
// requests are given opened sockets in a FIFO order.
// TODO(eroman): Make this more robust.
// TODO(eroman): Rename this test.
TEST_F(CertNetFetcherURLRequestTest, CancelAfterRunningMessageLoop) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url1 = test_server_.GetURL("/cert.crt");

  std::unique_ptr<CertNetFetcher::Request> request1 =
      StartRequest(fetcher(), url1);

  GURL url2 = test_server_.GetURL("/certs.p7c");
  std::unique_ptr<CertNetFetcher::Request> request2 =
      StartRequest(fetcher(), url2);

  GURL url3("ftp://www.not.supported.com/foo");
  std::unique_ptr<CertNetFetcher::Request> request3 =
      StartRequest(fetcher(), url3);

  // Wait for the ftp request to complete (it should complete right away since
  // it doesn't even try to connect to the server).
  VerifyFailure(ERR_DISALLOWED_URL_SCHEME, request3.get());

  // Cancel the second outstanding request.
  request2.reset();

  // Wait for the first request to complete and verify the fetch result.
  VerifySuccess("-cert.crt-\n", request1.get());
}

// Fetch the same URLs in parallel and verify that only 1 request is made per
// URL.
TEST_F(CertNetFetcherURLRequestTest, ParallelFetchDuplicates) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url1 = test_server_.GetURL("/cert.crt");
  GURL url2 = test_server_.GetURL("/root.crl");

  // Issue 3 requests for url1, and 3 requests for url2
  std::unique_ptr<CertNetFetcher::Request> request1 =
      StartRequest(fetcher(), url1);

  std::unique_ptr<CertNetFetcher::Request> request2 =
      StartRequest(fetcher(), url2);

  std::unique_ptr<CertNetFetcher::Request> request3 =
      StartRequest(fetcher(), url1);

  std::unique_ptr<CertNetFetcher::Request> request4 =
      StartRequest(fetcher(), url2);

  std::unique_ptr<CertNetFetcher::Request> request5 =
      StartRequest(fetcher(), url2);

  std::unique_ptr<CertNetFetcher::Request> request6 =
      StartRequest(fetcher(), url1);

  // Cancel all but one of the requests for url1.
  request1.reset();
  request3.reset();

  // Wait for the remaining requests to finish and verify the fetch results.
  VerifySuccess("-root.crl-\n", request2.get());
  VerifySuccess("-root.crl-\n", request4.get());
  VerifySuccess("-root.crl-\n", request5.get());
  VerifySuccess("-cert.crt-\n", request6.get());

  // Verify that only 2 URLRequests were started even though 6 requests were
  // issued.
  EXPECT_EQ(2, NumCreatedRequests());
}

// Cancel a request and then start another one for the same URL.
TEST_F(CertNetFetcherURLRequestTest, CancelThenStart) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();

  GURL url = test_server_.GetURL("/cert.crt");

  std::unique_ptr<CertNetFetcher::Request> request1 =
      StartRequest(fetcher(), url);
  request1.reset();

  std::unique_ptr<CertNetFetcher::Request> request2 =
      StartRequest(fetcher(), url);

  std::unique_ptr<CertNetFetcher::Request> request3 =
      StartRequest(fetcher(), url);
  request3.reset();

  // All but |request2| were canceled.
  VerifySuccess("-cert.crt-\n", request2.get());
}

// Start duplicate requests and then cancel all of them.
TEST_F(CertNetFetcherURLRequestTest, CancelAll) {
  ASSERT_TRUE(test_server_.Start());

  CreateFetcher();
  std::unique_ptr<CertNetFetcher::Request> requests[3];

  GURL url = test_server_.GetURL("/cert.crt");

  for (auto& request : requests) {
    request = StartRequest(fetcher(), url);
  }

  // Cancel all the requests.
  for (auto& request : requests) {
    request.reset();
  }

  EXPECT_EQ(1, NumCreatedRequests());
}

// Tests that Requests are signalled for completion even if they are
// created after the CertNetFetcher has been shutdown.
TEST_F(CertNetFetcherURLRequestTest, RequestsAfterShutdown) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();
  ShutDownFetcher();

  GURL url = test_server_.GetURL("/cert.crt");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifyFailure(ERR_ABORTED, request.get());
  EXPECT_EQ(0, NumCreatedRequests());
}

// Tests that Requests are signalled for completion if the fetcher is
// shutdown and the network thread stopped before the request is
// started.
TEST_F(CertNetFetcherURLRequestTest,
       RequestAfterShutdownAndNetworkThreadStopped) {
  ASSERT_TRUE(test_server_.Start());
  CreateFetcher();
  ShutDownFetcher();
  ResetState();
  network_thread_.reset();

  GURL url = test_server_.GetURL("/cert.crt");
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);
  VerifyFailure(ERR_ABORTED, request.get());
}

// Tests that outstanding Requests are cancelled when Shutdown is called.
TEST_F(CertNetFetcherURLRequestTestWithHangingReadHandler,
       ShutdownCancelsRequests) {
  CreateFetcher();

  GURL url = URLRequestHangingReadJob::GetMockHttpUrl();
  std::unique_ptr<CertNetFetcher::Request> request =
      StartRequest(fetcher(), url);

  ShutDownFetcher();
  VerifyFailure(ERR_ABORTED, request.get());
}

TEST_F(CertNetFetcherURLRequestTestWithSecureDnsInterceptor,
       SecureDnsDisabled) {
  CreateFetcher();
  std::unique_ptr<net::CertNetFetcher::Request> request = StartRequest(
      fetcher(),
      GURL("http://" + std::string(kMockSecureDnsHostname) + "/cert.crt"));
  Error actual_error;
  std::vector<uint8_t> actual_body;
  request->WaitForResult(&actual_error, &actual_body);
  EXPECT_TRUE(invoked_interceptor());
}

}  // namespace

}  // namespace net