text:
<template is="dom-if" if="[[androidAppsInfo.settingsAppAvailable]]" restamp>
  <cr-link-row id="manageApps" label="$i18n{androidAppsManageApps}"
      on-click="onManageAndroidAppsTap_" external
      deep-link-focus-id$="[[Setting.kManageAndroidPreferences]]">
  </cr-link-row>
</template>

<template is="dom-if" if="[[showArcvmManageUsb]]">
  <cr-link-row
      class="hr"
      label="$i18n{guestOsSharedUsbDevicesLabel}"
      id="manageArcvmShareUsbDevices"
      on-click="onSharedUsbDevicesClick_"
      role-description="$i18n{subpageArrowRoleDescription}">
  </cr-link-row>
</template>

<template is="dom-if" if="[[allowRemove_(prefs.arc.enabled.*)]]" restamp>

      $i18n{androidAppsRemove}

    <cr-button on-click="onRemoveTap_"
        aria-labelledby="androidRemoveLabel"
        deep-link-focus-id$="[[Setting.kRemovePlayStore]]">
      $i18n{androidAppsRemoveButton}
    </cr-button>

</template>

<cr-dialog id="confirmDisableDialog" close-text="$i18n{close}"
    on-cancel="onConfirmDisableDialogCancel_"
    on-close="onConfirmDisableDialogClose_">

$i18n{androidAppsDisableDialogTitle}

    <cr-button class="cancel-button"
        on-click="onConfirmDisableDialogCancel_">
      $i18n{cancel}
    </cr-button>
    <cr-button class="action-button"
        on-click="onConfirmDisableDialogConfirm_">
      $i18n{androidAppsDisableDialogRemove}
    </cr-button>

</cr-dialog>


text:
<?php

declare(strict_types = 1);

namespace WebHemi\Middleware\Action\Admin\ControlPanel\Applications;

use Exception;
use WebHemi\Form\ServiceAdapter\Base\ServiceAdapter as HtmlForm;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Http\ResponseInterface;

/**
 * Class AddAction.
 */
class AddAction extends ListAction
{
    /**
     * Gets template map name or template file path.
     *
     * @return string
     */
    public function getTemplateName() : string
    {
        return 'admin-control-panel-applications-add';
    }

    /**
     * Gets template data.
     *
     * @throws Exception
     * @return array
     */
    public function getTemplateData() : array
    {
        // TODO complete form
        /** @var array $postData */
        $postData = $this->request->getParsedBody();
        /** @var HtmlForm $form */
        $form = $this->applicationFormPreset->getPreset();
        $form->loadData($postData);

        if ($form->validate()) {
            // TODO validate name
            // * in case of domain: no other application with the same domain (== name)
            // * in case of directory: no other application with the same path (== name)
            //   + no filesystem path within the same path
        } else {
            throw new Exception('Form validation failed', ResponseInterface::STATUS_BAD_REQUEST);
        }

        $applicationUri = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_APPLICATION_URI);

        $this->response = $this->response
            ->withStatus(ResponseInterface::STATUS_REDIRECT, 'Found')
            ->withHeader('Location', $applicationUri.'applications');

        return [];
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.php.internal.core.util;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.IBuildpathEntry;
import org.eclipse.dltk.core.environment.EnvironmentPathUtils;
import org.eclipse.dltk.core.internal.environment.LocalEnvironment;
import org.eclipse.php.internal.core.CoreMessages;
import org.eclipse.php.internal.core.PHPCoreConstants;
import org.eclipse.php.internal.core.PHPCorePlugin;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * This class contains utility methods for converting PDT 1.0.x projects into
 * PDT 1.1.x projects Old model include path entries are converted here into the
 * new build path entries of the new model. Further conversion utilities should
 * be added here.
 */
public class ProjectBackwardCompatibilityUtil {
	public static final String TAG_INCLUDEPATHENTRY = "includepathentry"; //$NON-NLS-1$
	public static final String TAG_ENTRY_KIND = "kind"; //$NON-NLS-1$
	public static final String TAG_PATH = "path"; //$NON-NLS-1$
	public static final String TAG_RESOURCE = "resource"; //$NON-NLS-1$
	public static final String TAG_EXPORTED = "exported"; //$NON-NLS-1$
	private static final String PREF_QUALIFIER = PHPCorePlugin.ID
			+ ".projectOptions"; //$NON-NLS-1$

	private IBuildpathEntry[] buildpathEntries = {};
	private List<String> notImportedIncludePathVariableNames = new ArrayList<String>();

	public List<String> getNotImportedIncludePathVariableNames() {
		return notImportedIncludePathVariableNames;
	}

	/*
	 * Reads the project include paths and returns the corresponding build paths
	 */
	public IBuildpathEntry[] convertIncludePathForProject(IProject project) {
		try {
			ProjectScope projectScope = new ProjectScope(project);
			// reads the project options created by the old model
			IEclipsePreferences preferences = projectScope
					.getNode(PREF_QUALIFIER);
			String includePathXml = preferences.get(
					PHPCoreConstants.PHPOPTION_INCLUDE_PATH, null);

			if (includePathXml == null) {
				return buildpathEntries;
			}

			// parse the includes xml
			Element cpElement = null;
			final Reader reader = new StringReader(includePathXml);

			try {
				final DocumentBuilder parser = DocumentBuilderFactory
						.newInstance().newDocumentBuilder();
				cpElement = parser.parse(new InputSource(reader))
						.getDocumentElement();
			} catch (final Exception e) {
				throw new IOException(CoreMessages
						.getString("PHPProjectOptions_1")); //$NON-NLS-1$
			} finally {
				reader.close();
			}

			if (cpElement == null) {
				return buildpathEntries;
			}

			// convert each node in the xml into a build path entry
			final List<IBuildpathEntry> paths = new ArrayList<IBuildpathEntry>();
			NodeList list = cpElement
					.getElementsByTagName(TAG_INCLUDEPATHENTRY);
			for (int i = 0; i < list.getLength(); ++i) {
				final Node node = list.item(i);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					final IBuildpathEntry entry = elementDecode((Element) node);
					if (entry != null) {
						paths.add(entry);
					}
				}
			}
			final int pathSize = paths.size();
			buildpathEntries = new IBuildpathEntry[pathSize];
			return paths.toArray(buildpathEntries);
		} catch (IOException e) {
			PHPCorePlugin.log(e);
		} finally {

		}
		return buildpathEntries;
	}

	/*
	 * constructs a build entry from an element
	 */
	private IBuildpathEntry elementDecode(Element element) {

		String entryKindAttr = element.getAttribute(TAG_ENTRY_KIND);
		String pathAttr = element.getAttribute(TAG_PATH);
		String resourceAttr = element.getAttribute(TAG_RESOURCE);

		// exported flag (optional)
		boolean isExported = element.getAttribute(TAG_EXPORTED).equals("true"); //$NON-NLS-1$
		IBuildpathEntry entry = null;
		IPath path = null;
		String variableName = null;

		int entryKind = entryKindFromString(entryKindAttr);
		switch (entryKind) {
		case IBuildpathEntry.BPE_PROJECT:
			path = ResourcesPlugin.getWorkspace().getRoot().getProject(
					resourceAttr).getFullPath();
			if (path != null) {
				entry = DLTKCore.newProjectEntry(path, isExported);
			}
			break;
		case IBuildpathEntry.BPE_LIBRARY:
			if ("var".equalsIgnoreCase(entryKindAttr)) { //$NON-NLS-1$
				variableName = pathAttr;
				if (variableName != null && variableName.length() > 0) {
					String resolvedPath = ""; //$NON-NLS-1$
					Preferences pluginPreferences = PHPCorePlugin.getDefault()
							.getPluginPreferences();
					String pathString = pluginPreferences
							.getString(variableName);
					// try to read from default values
					if (pathString != null) {
						path = IncludePathVariableManager.instance()
								.getIncludePathVariable(pathString);
						// second chance, try to read from old workspace
						// configuration
						if (path == null) {
							path = IncludePathVariableManager.instance()
									.resolveVariablePath(variableName);
						}
					}

					if (path != null) {
						entry = DLTKCore
								.newExtLibraryEntry(EnvironmentPathUtils
										.getFullPath(LocalEnvironment
												.getInstance(), path));
					} else {
						notImportedIncludePathVariableNames.add(variableName);
					}
				}
			} else {
				entry = DLTKCore.newLibraryEntry(new Path(pathAttr)
						.makeAbsolute());
			}
		case IBuildpathEntry.BPE_CONTAINER:
			break;
		case IBuildpathEntry.BPE_SOURCE:
			entry = DLTKCore.newSourceEntry(path);
			break;
		}

		return entry;
	}

	/**
	 * Returns the entry kind of a PackageFragmentRoot from its
	 * String form.
	 */
	static int entryKindFromString(String kindStr) {
		if (kindStr.equalsIgnoreCase("prj")) //$NON-NLS-1$
			return IBuildpathEntry.BPE_PROJECT;
		// TODO: add better variable support
		if (kindStr.equalsIgnoreCase("var")) //$NON-NLS-1$
			return IBuildpathEntry.BPE_LIBRARY;
		if (kindStr.equalsIgnoreCase("con")) //$NON-NLS-1$
			return IBuildpathEntry.BPE_CONTAINER;
		if (kindStr.equalsIgnoreCase("src")) //$NON-NLS-1$
			return IBuildpathEntry.BPE_SOURCE;
		if (kindStr.equalsIgnoreCase("lib")) //$NON-NLS-1$
			return IBuildpathEntry.BPE_LIBRARY;
		return -1;
	}

	/*
	 * Class from the 1.0.x branch - used for trying to resolve include path
	 * variables from the old model
	 */
	static class IncludePathVariableManager {

		private static IncludePathVariableManager instance;

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

		Preferences preferenceStore = PHPCorePlugin.getDefault()
				.getPluginPreferences();

		HashMap<String, Path> variables = new HashMap<String, Path>();

		private IncludePathVariableManager() {
			startUp();
		}

		public IPath getIncludePathVariable(String variableName) {
			IPath varPath = null;
			IPath path = new Path(variableName);
			if (path.segmentCount() == 1) {
				varPath = variables.get(variableName);
			} else {
				varPath = variables.get(path.segment(0));
				if (varPath != null) {
					varPath = varPath.append(path.removeFirstSegments(1));
				}
			}
			return varPath;
		}

		public String[] getIncludePathVariableNames() {
			ArrayList<String> list = new ArrayList<String>();
			list.addAll(variables.keySet());
			return list.toArray(new String[list.size()]);

		}

		public void startUp() {
			String namesString = preferenceStore
					.getString(PHPCoreConstants.INCLUDE_PATH_VARIABLE_NAMES);
			String pathsString = preferenceStore
					.getString(PHPCoreConstants.INCLUDE_PATH_VARIABLE_PATHS);
			String[] names = {};
			if (namesString.length() > 0)
				names = namesString.split(","); //$NON-NLS-1$
			String[] paths = {};
			if (pathsString.length() > 0)
				paths = pathsString.split(","); //$NON-NLS-1$
			// Not good since empty paths are allowed!!!
			// assert (names.length == paths.length);
			for (int i = 0; i < names.length; i++) {
				String path;
				if (i < paths.length) {
					path = paths[i];
				} else {
					path = ""; //$NON-NLS-1$
				}
				variables.put(names[i], new Path(path));
			}

		}

		/**
		 * Returns resolved IPath from the given path string that starts from
		 * include path variable
		 *
		 * @param path
		 *            Path string
		 * @return resolved IPath or null if it couldn't be
		 *         resolved
		 */
		public IPath resolveVariablePath(String path) {
			int index = path.indexOf('/');
			if (index != -1) {
				String var = path.substring(0, index);
				IPath varPath = getIncludePathVariable(var);
				if (varPath != null && index + 1 < path.length()) {
					varPath = varPath.append(path.substring(index + 1));
				}
				return varPath;
			}
			return getIncludePathVariable(path);
		}
	}

}


text:
/**
 * Format number as currency.
 * @param {number} value number of cents.
 * @return {string} formatted string for currency.
 */
export default function(value: number): string {
  if (value === null || value === undefined) {
    return 'n/a';
  }
  return (value / 100.0).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
}


text:
module Softlayer
  module Product
    class Catalog
      module Item
        autoload :Price, 'softlayer/product/catalog/item/price'
      end
    end
  end
end


text:
var path = require('path');

// Third Party Dependencies
var parser = require('nomnom').script('t2');

// Internal
var controller = require('../lib/controller');
var init = require('../lib/init');
var logs = require('../lib/logs');
var drivers = require('./tessel-install-drivers');

function makeCommand(commandName) {
  return parser.command(commandName)
    .option('timeout', {
      abbr: 't',
      metavar: 'TIMEOUT',
      help: 'Set timeout in seconds for scanning for networked tessels',
      default: 5
    })
    .option('key', {
      required: false,
      metavar: 'PRIVATEKEY',
      abbr: 'i',
      help: 'SSH key for authorization with your Tessel'
    })
    .option('name', {
      metavar: 'NAME',
      help: 'The name of the tessel on which the command will be executed'
    })
    .option('lan', {
      flag: true,
      help: 'Use only a LAN connection'
    })
    .option('usb', {
      flag: true,
      help: 'Use only a USB connection'
    })
    .option('lanPrefer', {
      flag: true,
      default: false,
      help: 'Prefer a LAN connection when available, otherwise use USB.'
    })
    .option('output', {
      default: true,
      choices: [true, false],
      abbr: 'o',
      help: 'Enable or disable writing command output to stdout/stderr. Useful for CLI API consumers.'
    });
}

function callControllerWith(methodName, opts) {
  return controller[methodName](opts)
    .then(module.exports.closeSuccessfulCommand, module.exports.closeFailedCommand);
}

function callControllerCallback(methodName) {
  return function(opts) {
    return callControllerWith(methodName, opts);
  };
}

parser.command('install-drivers')
  .callback(function() {
    require('./tessel-install-drivers');
    drivers.install()
      .then(module.exports.closeSuccessfulCommand, module.exports.closeFailedCommand);
  })
  .help('Install drivers');

parser.command('provision')
  .callback(callControllerCallback('provisionTessel'))
  .option('force', {
    abbr: 'f',
    flag: true,
    help: 'Delete existing .tessel authorization and reprovision.'
  })
  .help('Authorize your computer to control the USB-connected Tessel');

makeCommand('restart')
  .callback(function(opts) {
    var packageJson;

    if (opts.type !== 'ram' && opts.type !== 'flash') {
      return module.exports.closeFailedCommand('--type Invalid ');
    }

    if (opts.entryPoint === undefined) {
      packageJson = require(path.resolve(process.cwd(), 'package.json'));

      if (packageJson && packageJson.main) {
        opts.entryPoint = packageJson.main;
      }
    }

    callControllerWith('restartScript', opts);
  })
  .option('entryPoint', {
    position: 1,
    help: 'The entry point file to deploy to Tessel'
  })
  .option('type', {
    default: 'ram',
    help: 'Specify where in memory the script is located: `--type=flash` (push) or `--type=ram` (run)'
  })
  .help('Restart a previously deployed script in RAM or Flash memory (does not rebundle)');

makeCommand('run')
  .callback(function(opts) {
    opts.lanPrefer = true;
    opts.push = false;
    // Overridden in tarBundle if opts.full is `true`
    opts.slim = true;
    callControllerWith('deployScript', opts);
  })
  .option('entryPoint', {
    position: 1,
    required: true,
    help: 'The program entry point file to deploy to Tessel'
  })
  .option('single', {
    flag: true,
    abbr: 's',
    help: 'Run only the specified entry point file'
  })
  .option('verbose', {
    flag: true,
    abbr: 'v',
    help: 'Choose to view more debugging information'
  })
  .option('slim', {
    flag: true,
    default: true,
    help: 'Deploy a single "bundle" file that contains that contains only the required files, excluding any files matched by non-negated rules in .tesselignore and including any files matched by rules in .tesselinclude. Program is run from "slimPath" file (if not provided, a default name is given).',
  })
  .option('full', {
    flag: true,
    default: false,
    help: 'Deploy all files in project including those not used by the program, excluding any files matched by non-negated rules in .tesselignore and including any files matched by rules in .tesselinclude. Program is run from specified "entryPoint" file.'
  })
  .help('Deploy a script to Tessel and run it with Node');

makeCommand('push')
  .callback(function(opts) {
    opts.lanPrefer = true;
    opts.push = true;
    // Overridden in tarBundle if opts.full is `true`
    opts.slim = true;
    callControllerWith('deployScript', opts);
  })
  .option('entryPoint', {
    position: 1,
    required: true,
    help: 'The program entry point file to deploy to Tessel'
  })
  .option('single', {
    flag: true,
    abbr: 's',
    help: 'Push only the specified entry point file'
  })
  .option('verbose', {
    flag: true,
    abbr: 'v',
    help: 'Choose to view more debugging information'
  })
  .option('slim', {
    flag: true,
    default: true,
    help: 'Push a single "bundle" file that contains that contains only the required files, excluding any files matched by non-negated rules in .tesselignore and including any files matched by rules in .tesselinclude. Program is run from "slimPath" file (if not provided, a default name is given).'
  })
  .option('full', {
    flag: true,
    default: false,
    help: 'Push all files in project including those not used by the program, excluding any files matched by non-negated rules in .tesselignore and including any files matched by rules in .tesselinclude. Program is run from specified "entryPoint" file.'
  })
  .help('Pushes the file/dir to Flash memory to be run anytime the Tessel is powered, runs the file immediately once the file is copied over');

makeCommand('erase')
  .callback(callControllerCallback('eraseScript'))
  .option('verbose', {
    flag: true,
    abbr: 'v',
    help: 'Choose to view more debugging information'
  })
  .help('Erases files pushed to Flash using the tessel push command');

makeCommand('list')
  .callback(callControllerCallback('listTessels'))
  .help('Lists all connected Tessels and their authorization status.');

parser.command('init')
  .callback(init)
  .option('interactive', {
    flag: true,
    abbr: 'i',
    help: 'Run in interactive mode'
  })
  .help('Initialize repository for your Tessel project');

makeCommand('wifi')
  .callback(function(opts) {
    // TODO: Refactor switch case into controller.wifi
    if (opts.list) {
      callControllerWith('printAvailableNetworks', opts);
    } else if (opts.off || opts.on) {
      if (opts.off) {
        opts.on = false;
      }
      callControllerWith('setWiFiState', opts);
    } else if (opts.ssid) {
      callControllerWith('connectToNetwork', opts);
    } else {
      callControllerWith('getWifiInfo', opts);
    }
  })
  .option('list', {
    abbr: 'l',
    flag: true,
    help: 'List available Wifi networks'
  })
  .option('ssid', {
    abbr: 'n',
    metavar: 'SSID',
    help: 'Set the SSID of the network to connect to'
  })
  .option('password', {
    abbr: 'p',
    metavar: 'PASSWORD',
    help: 'Set the password of the network to connect to'
  })
  .option('security', {
    abbr: 's',
    help: 'Set the encryption of the network to connect to (i.e. wep, psk, psk2, wpa, wpa2).'
  })
  .option('off', {
    flag: true,
    help: 'Disable the wireless network'
  })
  .option('on', {
    flag: true,
    help: 'Enable the wireless network'
  })
  .help('Configure the wireless connection');

parser.command('key')
  .callback(function(opts) {
    controller.setupLocal(opts)
      .then(function() {
        logs.info('Key successfully generated.');
      })
      .then(module.exports.closeSuccessfulCommand, module.exports.closeFailedCommand);
  })
  .option('generate', {
    position: 1,
    required: true,
    help: 'Generate a local SSH keypair for authenticating to a Tessel'
  })
  .help('Manage ssh keys for connecting to a Tessel');

makeCommand('rename')
  .option('newName', {
    help: 'The new name for the selected Tessel',
    position: 1,
  })
  .option('reset', {
    abbr: 'r',
    flag: true
  })
  .callback(callControllerCallback('renameTessel'))
  .help('Change the name of a Tessel to something new');

makeCommand('update')
  .option('version', {
    abbr: 'v',
    required: false,
    help: 'Specify a build version.'
  })
  .option('list', {
    abbr: 'l',
    required: false,
    flag: true,
    help: 'List the available builds.'
  })
  .option('force', {
    abbr: 'f',
    required: false,
    flag: true,
    help: 'Update to the latest version regardless of current version.'
  })
  .callback(function(opts) {
    if (opts.list) {
      callControllerWith('printAvailableUpdates');
    } else {
      callControllerWith('update', opts);
    }
  })
  .help('Update the Tessel firmware and openWRT image');

makeCommand('version')
  .callback(callControllerCallback('tesselFirmwareVerion'))
  .help('Display Tessel\'s current firmware version');

makeCommand('ap')
  .option('ssid', {
    abbr: 'n',
    help: 'Name of the network.'
  })
  .option('pass', {
    abbr: 'p',
    help: 'Password to access network.'
  })
  .option('security', {
    abbr: 's',
    help: 'Encryption to use on network (i.e. wep, psk, psk2, wpa, wpa2).'
  })
  .option('off', {
    flag: true,
    help: 'Disable the access point'
  })
  .option('on', {
    flag: true,
    help: 'Enable the access point'
  })
  .help('Configure the Tessel as an access point')
  .callback(function(opts) {
    if (opts.on || opts.off) {
      if (opts.on) {
        callControllerWith('enableAccessPoint', opts);
      } else {
        callControllerWith('disableAccessPoint', opts);
      }
    } else if (opts.ssid) {
      callControllerWith('createAccessPoint', opts);
    } else {
      callControllerWith('getAccessPointInfo', opts);
    }
  });

makeCommand('root')
  .callback(function(opts) {
    callControllerWith('root', opts);
  })
  .help('Gain SSH root access to one of your authorized tessels');

module.exports = function(args) {
  parser.parse(args);
};

module.exports.closeSuccessfulCommand = function() {
  process.exit(0);
};

// Allow options to be partially applied
module.exports.closeFailedCommand = function(status, options) {
  var code = 1;

  options = options || {};

  if (status instanceof Error) {
    logs.err(status.toString());
  } else {
    if (status !== undefined) {
      // Print a stern warning by default
      options.type = options.type || 'warn';
      logs[options.type](status);
    }
  }

  process.exit(options.code || status.code || code);
};

if (require.main === module) {
  module.exports(process.argv.slice(2));
}

if (global.IS_TEST_ENV) {
  module.exports.makeCommand = makeCommand;
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper.rb')

describe Attributor::HashDSLCompiler do
  let(:target) { double('model', attributes: {}) }

  let(:dsl_compiler_options) { {} }
  subject(:dsl_compiler) { Attributor::HashDSLCompiler.new(target, dsl_compiler_options) }

  it 'returns the requirements DSL attached to the right target' do
    req_dsl = dsl_compiler._requirements_dsl
    expect(req_dsl).to be_kind_of(Attributor::HashDSLCompiler::RequiresDSL)
    expect(req_dsl.target).to be(target)
  end

  context 'requires' do
    context 'without any arguments' do
      it 'without params returns the underlying compiler to chain internal methods' do
        expect(subject.requires).to be_kind_of(Attributor::HashDSLCompiler::RequiresDSL)
      end
    end

    context 'with params only (and some options)' do
      it 'takes then array to mean all attributes are required' do
        expect(target).to receive(:add_requirement)
        requirement = subject.requires :one, :two, description: 'These are very required'
        expect(requirement).to be_kind_of(Attributor::HashDSLCompiler::Requirement)
        expect(requirement.type).to be(:all)
      end
    end
    context 'with a block only (and some options)' do
      it 'evals it in the context of the Compiler' do
        proc = proc {}
        dsl = dsl_compiler._requirements_dsl
        expect(dsl).to receive(:instance_eval) # .with(&proc) << Does rspec 2.99 support block args?
        subject.requires description: 'These are very required', &proc
      end
    end
  end

  context 'RequiresDSL' do
    subject(:dsl) { Attributor::HashDSLCompiler::RequiresDSL.new(target) }
    it 'stores the received target' do
      expect(subject.target).to be(target)
    end

    context 'has DSL methods' do
      let(:req) { double('requirement') }
      let(:attr_names) { [:one, :two, :tree] }
      let(:number) { 2 }
      let(:req_class) { Attributor::HashDSLCompiler::Requirement }
      before do
        expect(target).to receive(:add_requirement).with(req)
      end
      it 'responds to .all' do
        expect(req_class).to receive(:new).with(all: attr_names).and_return(req)
        subject.all(*attr_names)
      end
      it 'responds to .at_most(n)' do
        expect(req_class).to receive(:new).with(at_most: number).and_return(req)
        subject.at_most(number)
      end
      it 'responds to .at_least(n)' do
        expect(req_class).to receive(:new).with(at_least: number).and_return(req)
        subject.at_least(number)
      end
      it 'responds to .exactly(n)' do
        expect(req_class).to receive(:new).with(exactly: number).and_return(req)
        subject.exactly(number)
      end
      it 'responds to .exclusive' do
        expect(req_class).to receive(:new).with(exclusive: attr_names).and_return(req)
        subject.exclusive(*attr_names)
      end
    end
  end

  context 'Requirement' do
    let(:attr_names) { [:one, :two, :tree] }
    let(:req_class) { Attributor::HashDSLCompiler::Requirement }

    context 'initialization' do
      it 'calls .of for exclusive' do
        expect_any_instance_of(req_class).to receive(:of).with(*attr_names)
        req_class.new(exclusive: attr_names)
      end
      it 'calls .of for all' do
        expect_any_instance_of(req_class).to receive(:of).with(*attr_names)
        req_class.new(all: attr_names)
      end
      it 'saves the number for the rest' do
        expect(req_class.new(exactly:  1).number).to be(1)
        expect(req_class.new(exactly:  1).type).to be(:exactly)
        expect(req_class.new(at_most:  2).number).to be(2)
        expect(req_class.new(at_most:  2).type).to be(:at_most)
        expect(req_class.new(at_least: 3).number).to be(3)
        expect(req_class.new(at_least: 3).type).to be(:at_least)
      end
      it 'understands and saves a :description' do
        req = req_class.new(exactly:  1, description: 'Hello')
        expect(req.number).to be(1)
        expect(req.description).to eq('Hello')
      end
    end

    context 'Requirement#validate' do
      let(:requirement) { req_class.new(arguments) }
      let(:subject) { requirement.validate(value, ['$'], nil) }

      context 'for :all' do
        let(:arguments) { { all: [:one, :two, :three] } }
        let(:value) { [:one] }
        let(:validation_error) { ['Key two is required for $.', 'Key three is required for $.'] }
        it { expect(subject).to include(*validation_error) }
      end
      context 'for :exactly' do
        let(:requirement) { req_class.new(exactly: 1).of(:one, :two) }
        let(:value) { [:one, :two] }
        let(:validation_error) { 'Exactly 1 of the following keys [:one, :two] are required for $. Found 2 instead: [:one, :two]' }
        it { expect(subject).to include(validation_error) }
      end
      context 'for :at_least' do
        let(:requirement) { req_class.new(at_least: 2).of(:one, :two, :three) }
        let(:value) { [:one] }
        let(:validation_error) { 'At least 2 keys out of [:one, :two, :three] are required to be passed in for $. Found [:one]' }
        it { expect(subject).to include(validation_error) }
      end
      context 'for :at_most' do
        let(:requirement) { req_class.new(at_most: 1).of(:one, :two, :three) }
        let(:value) { [:one, :two] }
        let(:validation_error) { 'At most 1 keys out of [:one, :two, :three] can be passed in for $. Found [:one, :two]' }
        it { expect(subject).to include(validation_error) }
      end
      context 'for :exclusive' do
        let(:arguments) { { exclusive: [:one, :two] } }
        let(:value) { [:one, :two] }
        let(:validation_error) { 'keys [:one, :two] are mutually exclusive for $.' }
        it { expect(subject).to include(validation_error) }
      end
    end

    context 'Requirement#describe' do
      it 'should work for :all' do
        req = req_class.new(all: attr_names).describe
        expect(req).to eq(type: :all, attributes: [:one, :two, :tree])
      end
      it 'should work for :exclusive n' do
        req = req_class.new(exclusive: attr_names).describe
        expect(req).to eq(type: :exclusive, attributes: [:one, :two, :tree])
      end
      it 'should work for :exactly' do
        req = req_class.new(exactly: 1).of(*attr_names).describe
        expect(req).to include(type: :exactly, count: 1, attributes: [:one, :two, :tree])
      end
      it 'should work for :at_most n' do
        req = req_class.new(at_most: 1).of(*attr_names).describe
        expect(req).to include(type: :at_most, count: 1, attributes: [:one, :two, :tree])
      end
      it 'should work for :at_least n' do
        req = req_class.new(at_least: 1).of(*attr_names).describe
        expect(req).to include(type: :at_least, count: 1, attributes: [:one, :two, :tree])
      end
      it 'should report a description' do
        req = req_class.new(at_least: 1, description: 'no more than 1').of(*attr_names).describe
        expect(req).to include(type: :at_least, count: 1, attributes: [:one, :two, :tree], description: 'no more than 1')
      end
    end
  end
end


text:
Fork of Scoutcamp maintained for [Shields][]

[shields]: https://shields.io

## Contribute

Discussions in the [main repo][issues], please.

[issues]: https://github.com/badges/shields/issues

## License

MIT. See LICENSE.md for more.

The "Red spiders" comic is CC BY-NC 2.5 from Randall Munroe, XKCD.
Link in `web/index.html`.


text:
<!DOCTYPE html>

<meta charset="UTF-8"/>
	<title>Recetas veganas</title>
	<link rel="stylesheet" type="text/css" href="css/styles.css">

Inicio

Recetas

Sube tu receta

Salchichas de soja

fotografía del plato

Tiempo de preparación estimado: 30-45 minutos.

Ingredientes:

150 gr

500 cc de caldo

2 cdas grandes de pan rallado

1/2 cucharadita de aroma de humo

4 cdas grandes de gluten de trigo (Se puede reemplazar por harina de trigo o harina aglutinada)

1/4  cdita de pimienta

1 cucharada grande de pimentón

2 cditas de guindilla o ají molido

75 cc de salsa de soja

1 diente de ajo picado chiquito

1  ramito de perejil picado bien pequeño

Método:

Primero poner a hidratar la soja texturizada en el caldo tibio por unos minutos. Una vez hidratada, se procesa con procesador o licuadora y se pasa por una tela para eliminar el excedente de liquido.

En un recipiente agregamos a la pasta de soja todos los demás ingredientes y amasamos bien nuestra carne de soja.

Formar las salchichas y envolverlas en papel film. Hervirlas durante 20 minutos. Dejar enfriar sumergiendo en agua fría.

Sacar del film. Se pueden consumir asadas en parrilla, a la plancha, en salsa, etc.

Consejos:

Se pueden congelar.

Descongelarlos, dejarlos en remojo en agua tibia hasta que estén blandos.

Antes de asarlas, pincelar las salchichas con aceite y condimentos para que no se sequen.

Inicio

Recetas

Sube tu receta

  copyright© 2005 - 2014 Recetas - Veganas. Todos los derechos reservados.Términos & Condiciones | Política de privacidad


text:
#pragma once
#include "Common/Runtime/Handle.h"

#include <glm/vec3.hpp>

struct NetFx;
class QString;
class Entity;
namespace FXSystem
{
struct Data;
}

using NetFxHandle = HandleT<20,12,NetFx>;
using FxHandle = HandleT<20,12,FXSystem::Data>;

NetFxHandle createNetFx(FxHandle from_fx);
void release(NetFxHandle handle);
NetFx &lookup(NetFxHandle handle);
void attachToEntity(NetFxHandle h, Entity *tgt);
void updateNetFx();
bool updateNetFxFromParent(NetFxHandle h);


text:
ExampleApplication::ExampleApplication()
{
}

ExampleApplication::~ExampleApplication()
{
}

//-------------------------------------------------------------------------------------
void ExampleApplication::createScene()
{
  // Create SceneManager.
  mSceneMgr = mRoot->createSceneManager("DefaultSceneManager");

  // Create a camera.
  mCamera = mSceneMgr->createCamera("PlayerCam");
  mCamera->setPosition(Ogre::Vector3(0, 0, 80));
  mCamera->lookAt(Ogre::Vector3(0, 0, -3));
  mCamera->setNearClipDistance(5);
  mCamNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("CamNode");
  mCamNode->attachObject(mCamera);

  // Set control parameters.
  mRotationSpeed = 0.13;
  mMaxSpeed = 1000;
  mSlowMaxSpeed = mMaxSpeed / 15;
  mAccelerationRate = 100;

  // Create one viewport, entire window.
  Ogre::Viewport* vp = mWindow->addViewport(mCamera);
  // vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

  // Set camera aspect ratio to match viewport.
  mCamera->setAspectRatio(
    Ogre::Real(vp->getActualWidth() / Ogre::Real(vp->getActualHeight())));

  // Add lighting.
  mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

  Ogre::Light* l = mSceneMgr->createLight("MainLight");
  l->setPosition(20, 80, 50);

  // Add meshes.
  Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh");
  Ogre::SceneNode* headNode =
    mSceneMgr->getRootSceneNode()->createChildSceneNode();
  headNode->attachObject(ogreHead);
}

//==============================================================================
// Cross-platform boilerplate main()
//==============================================================================
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
  INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
    int main(int argc, char *argv[])
#endif
  {
    ExampleApplication app;

    try {
      app.go();
    } catch (Ogre::Exception& e) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
      MessageBox( NULL, e.getFullDescription().c_str(),
                  "An exception has occured!",
                  MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
      std::cerr << "An exception has occured: " <<
        e.getFullDescription().c_str() << std::endl;
#endif
    }

    return 0;
  }

#ifdef __cplusplus
}
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".section.home.EditDisplayNameActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/edit_display_name_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            app:title="@string/edit_display_name_title" />

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/edit_display_name_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_margin="@dimen/activity_horizontal_margin"
        app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

        <EditText
            android:id="@+id/edit_deisplay_name_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="@string/input_username_hint"
            android:inputType="textPersonName"
            android:singleLine="true" />
    </android.support.design.widget.TextInputLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:text="@string/header_username"
        android:textAlignment="center"
        android:textSize="18sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="bottom"
        android:layout_margin="@dimen/activity_horizontal_margin">

        <Button
            android:id="@+id/edit_display_name_cancel"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@android:string/cancel" />

        <Button
            android:id="@+id/edit_display_name_save"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/full_screen_add_save_item" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>


text:
package com.mongodb.internal.connection;

import com.mongodb.MongoClientException;
import com.mongodb.MongoNamespace;
import com.mongodb.ReadPreference;
import com.mongodb.ServerApi;
import com.mongodb.connection.ClusterConnectionMode;
import com.mongodb.internal.session.SessionContext;
import com.mongodb.lang.Nullable;
import org.bson.BsonArray;
import org.bson.BsonBinaryWriter;
import org.bson.BsonBoolean;
import org.bson.BsonDocument;
import org.bson.BsonElement;
import org.bson.BsonInt64;
import org.bson.BsonString;
import org.bson.FieldNameValidator;
import org.bson.io.BsonOutput;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.mongodb.ReadPreference.primary;
import static com.mongodb.ReadPreference.primaryPreferred;
import static com.mongodb.assertions.Assertions.assertFalse;
import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.connection.ClusterConnectionMode.LOAD_BALANCED;
import static com.mongodb.connection.ClusterConnectionMode.SINGLE;
import static com.mongodb.connection.ServerType.SHARD_ROUTER;
import static com.mongodb.connection.ServerType.STANDALONE;
import static com.mongodb.internal.connection.BsonWriterHelper.writePayload;
import static com.mongodb.internal.connection.ReadConcernHelper.getReadConcernDocument;
import static com.mongodb.internal.operation.ServerVersionHelper.FOUR_DOT_TWO_WIRE_VERSION;
import static com.mongodb.internal.operation.ServerVersionHelper.FOUR_DOT_ZERO_WIRE_VERSION;
import static com.mongodb.internal.operation.ServerVersionHelper.THREE_DOT_SIX_WIRE_VERSION;

/**
 * A command message that uses OP_MSG or OP_QUERY to send the command.
 *
 *
This class is not part of the public API and may be removed or changed at any time

 */
public final class CommandMessage extends RequestMessage {
    private final MongoNamespace namespace;
    private final BsonDocument command;
    private final FieldNameValidator commandFieldNameValidator;
    private final ReadPreference readPreference;
    private final boolean exhaustAllowed;
    private final SplittablePayload payload;
    private final FieldNameValidator payloadFieldNameValidator;
    private final boolean responseExpected;
    private final ClusterConnectionMode clusterConnectionMode;
    private final ServerApi serverApi;

    CommandMessage(final MongoNamespace namespace, final BsonDocument command, final FieldNameValidator commandFieldNameValidator,
            final ReadPreference readPreference, final MessageSettings settings, final ClusterConnectionMode clusterConnectionMode,
            final @Nullable ServerApi serverApi) {
        this(namespace, command, commandFieldNameValidator, readPreference, settings, true, null, null,
                clusterConnectionMode, serverApi);
    }

    CommandMessage(final MongoNamespace namespace, final BsonDocument command, final FieldNameValidator commandFieldNameValidator,
            final ReadPreference readPreference, final MessageSettings settings, final boolean exhaustAllowed,
            final ClusterConnectionMode clusterConnectionMode, final @Nullable ServerApi serverApi) {
        this(namespace, command, commandFieldNameValidator, readPreference, settings, true, exhaustAllowed, null, null,
                clusterConnectionMode, serverApi);
    }

    CommandMessage(final MongoNamespace namespace, final BsonDocument command, final FieldNameValidator commandFieldNameValidator,
                   final ReadPreference readPreference, final MessageSettings settings, final boolean responseExpected,
                   final SplittablePayload payload, final FieldNameValidator payloadFieldNameValidator,
                   final ClusterConnectionMode clusterConnectionMode, final @Nullable ServerApi serverApi) {
        this(namespace, command, commandFieldNameValidator, readPreference, settings, responseExpected, false, payload,
                payloadFieldNameValidator, clusterConnectionMode, serverApi);
    }

    CommandMessage(final MongoNamespace namespace, final BsonDocument command, final FieldNameValidator commandFieldNameValidator,
                   final ReadPreference readPreference, final MessageSettings settings,
                   final boolean responseExpected, final boolean exhaustAllowed,
                   final SplittablePayload payload, final FieldNameValidator payloadFieldNameValidator,
                   final ClusterConnectionMode clusterConnectionMode, final @Nullable ServerApi serverApi) {
        super(namespace.getFullName(), getOpCode(settings, clusterConnectionMode, serverApi), settings);
        this.namespace = namespace;
        this.command = command;
        this.commandFieldNameValidator = commandFieldNameValidator;
        this.readPreference = readPreference;
        this.responseExpected = responseExpected;
        this.exhaustAllowed = exhaustAllowed;
        this.payload = payload;
        this.payloadFieldNameValidator = payloadFieldNameValidator;
        this.clusterConnectionMode = notNull("clusterConnectionMode", clusterConnectionMode);
        this.serverApi = serverApi;
    }

    BsonDocument getCommandDocument(final ByteBufferBsonOutput bsonOutput) {
        ByteBufBsonDocument byteBufBsonDocument = ByteBufBsonDocument.createOne(bsonOutput,
                getEncodingMetadata().getFirstDocumentPosition());
        BsonDocument commandBsonDocument;

        if (containsPayload()) {
            commandBsonDocument = byteBufBsonDocument.toBaseBsonDocument();

            int payloadStartPosition = getEncodingMetadata().getFirstDocumentPosition()
                    + byteBufBsonDocument.getSizeInBytes()
                    + 1 // payload type
                    + 4 // payload size
                    + payload.getPayloadName().getBytes(StandardCharsets.UTF_8).length + 1;  // null-terminated UTF-8 payload name
            commandBsonDocument.append(payload.getPayloadName(),
                    new BsonArray(ByteBufBsonDocument.createList(bsonOutput, payloadStartPosition)));
        } else {
            commandBsonDocument = byteBufBsonDocument;
        }

       return commandBsonDocument;
    }

    boolean containsPayload() {
        return payload != null;
    }

    boolean isResponseExpected() {
        isTrue("The message must be encoded before determining if a response is expected", getEncodingMetadata() != null);
        return !useOpMsg() || requireOpMsgResponse();
    }

    MongoNamespace getNamespace() {
        return namespace;
    }

    @Override
    protected EncodingMetadata encodeMessageBodyWithMetadata(final BsonOutput bsonOutput, final SessionContext sessionContext) {
        int messageStartPosition = bsonOutput.getPosition() - MESSAGE_PROLOGUE_LENGTH;
        int commandStartPosition;
        if (useOpMsg()) {
            int flagPosition = bsonOutput.getPosition();
            bsonOutput.writeInt32(0);   // flag bits
            bsonOutput.writeByte(0);    // payload type
            commandStartPosition = bsonOutput.getPosition();

            addDocument(command, bsonOutput, commandFieldNameValidator, getExtraElements(sessionContext));

            if (payload != null) {
                bsonOutput.writeByte(1);          // payload type
                int payloadBsonOutputStartPosition = bsonOutput.getPosition();
                bsonOutput.writeInt32(0);         // size
                bsonOutput.writeCString(payload.getPayloadName());
                writePayload(new BsonBinaryWriter(bsonOutput, payloadFieldNameValidator), bsonOutput, getSettings(),
                        messageStartPosition, payload, getSettings().getMaxDocumentSize());

                int payloadBsonOutputLength = bsonOutput.getPosition() - payloadBsonOutputStartPosition;
                bsonOutput.writeInt32(payloadBsonOutputStartPosition, payloadBsonOutputLength);
            }

            // Write the flag bits
            bsonOutput.writeInt32(flagPosition, getOpMsgFlagBits());
        } else {
            bsonOutput.writeInt32(0);
            bsonOutput.writeCString(namespace.getFullName());
            bsonOutput.writeInt32(0);
            bsonOutput.writeInt32(-1);

            commandStartPosition = bsonOutput.getPosition();

            List<BsonElement> elements = null;
            if (serverApi != null) {
                elements = new ArrayList<>(3);
                addServerApiElements(elements);
            }
            addDocument(command, bsonOutput, commandFieldNameValidator, elements);
        }
        return new EncodingMetadata(commandStartPosition);
    }

    private int getOpMsgFlagBits() {
        int flagBits = 0;
        if (!requireOpMsgResponse()) {
            flagBits = 1 << 1;
        }
        if (exhaustAllowed) {
            flagBits |= 1 << 16;
        }
        return flagBits;
    }

    private boolean requireOpMsgResponse() {
        if (responseExpected) {
            return true;
        } else {
            return payload != null && payload.hasAnotherSplit();
        }
    }

    private boolean isDirectConnectionToReplicaSetMember() {
        return clusterConnectionMode == SINGLE
                && getSettings().getServerType() != SHARD_ROUTER
                && getSettings().getServerType() != STANDALONE;
    }

    private boolean useOpMsg() {
        return getOpCode().equals(OpCode.OP_MSG);
    }

    private List<BsonElement> getExtraElements(final SessionContext sessionContext) {
        List<BsonElement> extraElements = new ArrayList<>();
        extraElements.add(new BsonElement("$db", new BsonString(new MongoNamespace(getCollectionName()).getDatabaseName())));
        if (sessionContext.getClusterTime() != null) {
            extraElements.add(new BsonElement("$clusterTime", sessionContext.getClusterTime()));
        }
        if (sessionContext.hasSession() && responseExpected) {
            extraElements.add(new BsonElement("lsid", sessionContext.getSessionId()));
        }
        boolean firstMessageInTransaction = sessionContext.notifyMessageSent();

        assertFalse(sessionContext.hasActiveTransaction() && sessionContext.isSnapshot());
        if (sessionContext.hasActiveTransaction()) {
            checkServerVersionForTransactionSupport();
            extraElements.add(new BsonElement("txnNumber", new BsonInt64(sessionContext.getTransactionNumber())));
            if (firstMessageInTransaction) {
                extraElements.add(new BsonElement("startTransaction", BsonBoolean.TRUE));
                addReadConcernDocument(extraElements, sessionContext);
            }
            extraElements.add(new BsonElement("autocommit", BsonBoolean.FALSE));
        } else if (sessionContext.isSnapshot()) {
            addReadConcernDocument(extraElements, sessionContext);
        }

        if (serverApi != null) {
            addServerApiElements(extraElements);
        }

        if (readPreference != null) {
            if (!readPreference.equals(primary())) {
                extraElements.add(new BsonElement("$readPreference", readPreference.toDocument()));
            } else if (isDirectConnectionToReplicaSetMember()) {
                extraElements.add(new BsonElement("$readPreference", primaryPreferred().toDocument()));
            }
        }
        return extraElements;
    }

    private void addServerApiElements(final List<BsonElement> extraElements) {
        extraElements.add(new BsonElement("apiVersion", new BsonString(serverApi.getVersion().getValue())));
        if (serverApi.getStrict().isPresent()) {
            extraElements.add(new BsonElement("apiStrict", BsonBoolean.valueOf(serverApi.getStrict().get())));
        }
        if (serverApi.getDeprecationErrors().isPresent()) {
            extraElements.add(new BsonElement("apiDeprecationErrors", BsonBoolean.valueOf(serverApi.getDeprecationErrors().get())));
        }
    }

    private void checkServerVersionForTransactionSupport() {
        int wireVersion = getSettings().getMaxWireVersion();
        if (wireVersion < FOUR_DOT_ZERO_WIRE_VERSION
                || (wireVersion < FOUR_DOT_TWO_WIRE_VERSION && getSettings().getServerType() == SHARD_ROUTER)) {
            throw new MongoClientException("Transactions are not supported by the MongoDB cluster to which this client is connected.");
        }
    }

    private void addReadConcernDocument(final List<BsonElement> extraElements, final SessionContext sessionContext) {
        BsonDocument readConcernDocument = getReadConcernDocument(sessionContext, getSettings().getMaxWireVersion());
        if (!readConcernDocument.isEmpty()) {
            extraElements.add(new BsonElement("readConcern", readConcernDocument));
        }
    }

    private static OpCode getOpCode(final MessageSettings settings, final ClusterConnectionMode clusterConnectionMode,
            @Nullable final ServerApi serverApi) {
        return isServerVersionAtLeastThreeDotSix(settings) || clusterConnectionMode == LOAD_BALANCED || serverApi != null
                ? OpCode.OP_MSG
                : OpCode.OP_QUERY;
    }

    private static boolean isServerVersionAtLeastThreeDotSix(final MessageSettings settings) {
        return settings.getMaxWireVersion() >= THREE_DOT_SIX_WIRE_VERSION;
    }
}


text:
package org.cagrid.dorian.common;

import junit.framework.TestCase;

import org.cagrid.dorian.common.Metadata;
import org.cagrid.dorian.service.MetadataManager;
import org.cagrid.gaards.dorian.test.Utils;
import org.cagrid.tools.database.Database;

/**
 * @author Stephen Langella
 * @author Scott Oster
 * @author Shannon Hastings
 * @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
 *          Exp $
 */
public class TestMetadataManager extends TestCase {

    private static final String TABLE = "test_metadata";

    private Database db;

    public void testDelete() {

        MetadataManager mm = new MetadataManager(db, TABLE);
        try {
            mm.clearDatabase();
            // mm.destroy();
            int count = 20;

            // Test Insert;
            for (int i = 0; i < count; i++) {
                Metadata data = new Metadata();
                data.setName("name" + i);
                data.setValue("value" + i);
                data.setDescription("description" + i);
                mm.insert(data);
                Metadata out = mm.get(data.getName());
                assertNotNull(out);
                assertEquals(data, out);
            }

            // Test delete
            for (int i = 0; i < count; i++) {
                String n = "name" + count;
                assertNull(mm.get(n));

            }

        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        } finally {
            try {
                mm.clearDatabase();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void testUpdate() {
        MetadataManager mm = new MetadataManager(db, TABLE);
        try {
            mm.clearDatabase();
            int count = 20;

            // Test Insert;
            for (int i = 0; i < count; i++) {
                Metadata data = new Metadata();
                data.setName("name" + i);
                data.setValue("value" + i);
                data.setDescription("description" + i);
                mm.insert(data);
                Metadata out = mm.get(data.getName());
                assertNotNull(out);
                assertEquals(data, out);
            }
            // Test update
            for (int i = 0; i < count; i++) {
                Metadata data = new Metadata();
                data.setName("name" + i);
                data.setValue("changedvalue" + i);
                data.setDescription("description" + i);
                mm.update(data);
                Metadata out = mm.get(data.getName());
                assertNotNull(out);
                assertEquals(data, out);
            }

        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        } finally {
            try {
                mm.clearDatabase();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void testInsert() {
        MetadataManager mm = new MetadataManager(db, TABLE);
        try {
            mm.clearDatabase();
            int count = 20;

            // Test Insert;
            for (int i = 0; i < count; i++) {
                Metadata data = new Metadata();
                data.setName("name" + i);
                data.setValue("value" + i);
                data.setDescription("description" + i);
                mm.insert(data);
                Metadata out = mm.get(data.getName());
                assertNotNull(out);
                assertEquals(data, out);
            }

        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        } finally {
            try {
                mm.clearDatabase();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void setUp() throws Exception {
        super.setUp();
        try {
            db = Utils.getDB();
            assertEquals(0, db.getUsedConnectionCount());
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }

    protected void tearDown() throws Exception {
        super.setUp();
        try {
            assertEquals(0, db.getUsedConnectionCount());
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }

}


text:
package app.akexorcist.bluetotohspp.library;

import java.util.ArrayList;
import java.util.Set;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("NewApi")
public class BluetoothSPP {
    // Listener for Bluetooth Status & Connection
    private BluetoothStateListener mBluetoothStateListener = null;
    private OnDataReceivedListener mDataReceivedListener = null;
    private BluetoothConnectionListener mBluetoothConnectionListener = null;
    private AutoConnectionListener mAutoConnectionListener = null;

    // Context from activity which call this class
    private Context mContext;

    private byte mDelimiter;

    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;

    // Member object for the chat services
    private BluetoothService mChatService = null;

    // Name and Address of the connected device
    private String mDeviceName = null;
    private String mDeviceAddress = null;

    private boolean isAutoConnecting = false;
    private boolean isAutoConnectionEnabled = false;
    private boolean isConnected = false;
    private boolean isConnecting = false;
    private boolean isServiceRunning = false;

    private String keyword = "";
    private boolean isAndroid = BluetoothState.DEVICE_ANDROID;

    private BluetoothConnectionListener bcl;
    private int c = 0;

    public BluetoothSPP(Context context) {
        mContext = context;
        mDelimiter = '\n';
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public BluetoothSPP(Context context, byte delimiter) {
        mContext = context;
        mDelimiter = delimiter;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public interface BluetoothStateListener {
        public void onServiceStateChanged(int state);
    }

    public interface OnDataReceivedListener {
        public void onDataReceived(byte[] data, String message);
    }

    public interface BluetoothConnectionListener {
        public void onDeviceConnected(String name, String address);
        public void onDeviceDisconnected();
        public void onDeviceConnectionFailed();
    }

    public interface AutoConnectionListener {
        public void onAutoConnectionStarted();
        public void onNewConnection(String name, String address);
    }

    public boolean isBluetoothAvailable() {
        try {
            if (mBluetoothAdapter == null || mBluetoothAdapter.getAddress().equals(null))
                return false;
        } catch (NullPointerException e) {
             return false;
        }
        return true;
    }

    public boolean isBluetoothEnabled() {
        return mBluetoothAdapter.isEnabled();
    }

    public boolean isServiceAvailable() {
        return mChatService != null;
    }

    public boolean isAutoConnecting() {
        return isAutoConnecting;
    }

    public boolean startDiscovery() {
        return mBluetoothAdapter.startDiscovery();
    }

    public boolean isDiscovery() {
        return mBluetoothAdapter.isDiscovering();
    }

    public boolean cancelDiscovery() {
        return mBluetoothAdapter.cancelDiscovery();
    }

    public void setupService() {
        mChatService = new BluetoothService(mContext, mHandler, mDelimiter);
    }

    public BluetoothAdapter getBluetoothAdapter() {
        return mBluetoothAdapter;
    }

    public int getServiceState() {
        if(mChatService != null)
            return mChatService.getState();
        else
            return -1;
    }

    public void startService(boolean isAndroid) {
        if (mChatService != null) {
            if (mChatService.getState() == BluetoothState.STATE_NONE) {
                isServiceRunning = true;
                mChatService.start(isAndroid);
                BluetoothSPP.this.isAndroid = isAndroid;
            }
        }
    }

    public void stopService() {
        if (mChatService != null) {
            isServiceRunning = false;
            mChatService.stop();
        }
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mChatService != null) {
                    isServiceRunning = false;
                    mChatService.stop();
                }
            }
        }, 500);
    }

    public void setDeviceTarget(boolean isAndroid) {
        stopService();
        startService(isAndroid);
        BluetoothSPP.this.isAndroid = isAndroid;
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case BluetoothState.MESSAGE_WRITE:
                break;
            case BluetoothState.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf);
                if(readBuf != null && readBuf.length > 0) {
                    if(mDataReceivedListener != null)
                        mDataReceivedListener.onDataReceived(readBuf, readMessage);
                }
                break;
            case BluetoothState.MESSAGE_DEVICE_NAME:
                mDeviceName = msg.getData().getString(BluetoothState.DEVICE_NAME);
                mDeviceAddress = msg.getData().getString(BluetoothState.DEVICE_ADDRESS);
                if(mBluetoothConnectionListener != null)
                    mBluetoothConnectionListener.onDeviceConnected(mDeviceName, mDeviceAddress);
                isConnected = true;
                break;
            case BluetoothState.MESSAGE_TOAST:
                Toast.makeText(mContext, msg.getData().getString(BluetoothState.TOAST)
                        , Toast.LENGTH_SHORT).show();
                break;
            case BluetoothState.MESSAGE_STATE_CHANGE:
                if(mBluetoothStateListener != null)
                    mBluetoothStateListener.onServiceStateChanged(msg.arg1);
                if(isConnected && msg.arg1 != BluetoothState.STATE_CONNECTED) {
                    if(mBluetoothConnectionListener != null)
                        mBluetoothConnectionListener.onDeviceDisconnected();
                    if(isAutoConnectionEnabled) {
                        isAutoConnectionEnabled = false;
                        autoConnect(keyword);
                    }
                    isConnected = false;
                    mDeviceName = null;
                    mDeviceAddress = null;
                }

                if(!isConnecting && msg.arg1 == BluetoothState.STATE_CONNECTING) {
                    isConnecting = true;
                } else if(isConnecting) {
                    if(msg.arg1 != BluetoothState.STATE_CONNECTED) {
                        if(mBluetoothConnectionListener != null)
                            mBluetoothConnectionListener.onDeviceConnectionFailed();
                    }
                    isConnecting = false;
                }
                break;
            }
        }
    };

    public void stopAutoConnect() {
        isAutoConnectionEnabled = false;
    }

    public void connect(Intent data) {
        String address = data.getExtras().getString(BluetoothState.EXTRA_DEVICE_ADDRESS);
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        mChatService.connect(device);
    }

    public void connect(String address) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        mChatService.connect(device);
    }

    public void disconnect() {
        if(mChatService != null) {
            isServiceRunning = false;
            mChatService.stop();
            if(mChatService.getState() == BluetoothState.STATE_NONE) {
                isServiceRunning = true;
                mChatService.start(BluetoothSPP.this.isAndroid);
            }
        }
    }

    public void setBluetoothStateListener (BluetoothStateListener listener) {
        mBluetoothStateListener = listener;
    }

    public void setOnDataReceivedListener (OnDataReceivedListener listener) {
        mDataReceivedListener = listener;
    }

    public void setBluetoothConnectionListener (BluetoothConnectionListener listener) {
        mBluetoothConnectionListener = listener;
    }

    public void setAutoConnectionListener(AutoConnectionListener listener) {
        mAutoConnectionListener = listener;
    }

    public void enable() {
        mBluetoothAdapter.enable();
    }

    public void send(byte[] data) {
        if(mChatService.getState() == BluetoothState.STATE_CONNECTED) {
            mChatService.write(data);
        }
    }

    public void send(String data) {
        if(mChatService.getState() == BluetoothState.STATE_CONNECTED) {
            mChatService.write(data.getBytes());
        }
    }

    public String getConnectedDeviceName() {
        return mDeviceName;
    }

    public String getConnectedDeviceAddress() {
        return mDeviceAddress;
    }

    public String[] getPairedDeviceName() {
        int c = 0;
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        String[] name_list = new String[devices.size()];
        for(BluetoothDevice device : devices) {
            name_list[c] = device.getName();
            c++;
        }
        return name_list;
    }

    public String[] getPairedDeviceAddress() {
        int c = 0;
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        String[] address_list = new String[devices.size()];
        for(BluetoothDevice device : devices) {
            address_list[c] = device.getAddress();
            c++;
        }
        return address_list;
    }

    public void autoConnect(String keywordName) {
        if(!isAutoConnectionEnabled) {
            keyword = keywordName;
            isAutoConnectionEnabled = true;
            isAutoConnecting = true;
            if(mAutoConnectionListener != null)
                mAutoConnectionListener.onAutoConnectionStarted();
            final ArrayList<String> arr_filter_address = new ArrayList<String>();
            final ArrayList<String> arr_filter_name = new ArrayList<String>();
            String[] arr_name = getPairedDeviceName();
            String[] arr_address = getPairedDeviceAddress();
            for(int i = 0 ; i < arr_name.length ; i++) {
                if(arr_name[i].contains(keywordName)) {
                    arr_filter_address.add(arr_address[i]);
                    arr_filter_name.add(arr_name[i]);
                }
            }

            bcl = new BluetoothConnectionListener() {
                public void onDeviceConnected(String name, String address) {
                    bcl = null;
                    isAutoConnecting = false;
                }

                public void onDeviceDisconnected() { }
                public void onDeviceConnectionFailed() {
                	Log.e("CHeck", "Failed");
                    if(isServiceRunning) {
                        if(isAutoConnectionEnabled) {
                            c++;
                            if(c >= arr_filter_address.size())
                                c = 0;
                            connect(arr_filter_address.get(c));
                        	Log.e("CHeck", "Connect");
                            if(mAutoConnectionListener != null)
                                mAutoConnectionListener.onNewConnection(arr_filter_name.get(c)
                                    , arr_filter_address.get(c));
                        } else {
                            bcl = null;
                            isAutoConnecting = false;
                        }
                    }
                }
            };

            setBluetoothConnectionListener(bcl);
            c = 0;
            if(mAutoConnectionListener != null)
                mAutoConnectionListener.onNewConnection(arr_name[c], arr_address[c]);
            if(arr_filter_address.size() > 0)
                connect(arr_filter_address.get(c));
            else
                Toast.makeText(mContext, "Device name mismatch", Toast.LENGTH_SHORT).show();
        }
    }
}


text:
import { MenuIDs } from '../models/menu-ids'
import { merge } from './merge'
import { IAppState, SelectionType } from '../lib/app-state'
import {
  Repository,
  isRepositoryWithGitHubRepository,
} from '../models/repository'
import { CloningRepository } from '../models/cloning-repository'
import { TipState } from '../models/tip'
import { updateMenuState as ipcUpdateMenuState } from '../ui/main-process-proxy'
import { AppMenu, MenuItem } from '../models/app-menu'
import { hasConflictedFiles } from './status'
import { enableSquashMerging } from './feature-flag'

export interface IMenuItemState {
  readonly enabled?: boolean
}

/**
 * Utility class for coalescing updates to menu items
 */
class MenuStateBuilder {
  private readonly _state: Map<MenuIDs, IMenuItemState>

  public constructor(state: Map<MenuIDs, IMenuItemState> = new Map()) {
    this._state = state
  }

  /**
   * Returns an Map where each key is a MenuID and the values
   * are IMenuItemState instances containing information about
   * whether a particular menu item should be enabled/disabled or
   * visible/hidden.
   */
  public get state() {
    return new Map<MenuIDs, IMenuItemState>(this._state)
  }

  private updateMenuItem<K extends keyof IMenuItemState>(
    id: MenuIDs,
    state: Pick<IMenuItemState, K>
  ) {
    const currentState = this._state.get(id) || {}
    this._state.set(id, merge(currentState, state))
  }

  /** Set the state of the given menu item id to enabled */
  public enable(id: MenuIDs): this {
    this.updateMenuItem(id, { enabled: true })
    return this
  }

  /** Set the state of the given menu item id to disabled */
  public disable(id: MenuIDs): this {
    this.updateMenuItem(id, { enabled: false })
    return this
  }

  /** Set the enabledness of the given menu item id */
  public setEnabled(id: MenuIDs, enabled: boolean): this {
    this.updateMenuItem(id, { enabled })
    return this
  }

  /**
   * Create a new state builder by merging the current state with the state from
   * the other state builder. This will replace values in `this` with values
   * from `other`.
   */
  public merge(other: MenuStateBuilder): MenuStateBuilder {
    const merged = new Map<MenuIDs, IMenuItemState>(this._state)
    for (const [key, value] of other._state) {
      merged.set(key, value)
    }
    return new MenuStateBuilder(merged)
  }
}

function isRepositoryHostedOnGitHub(
  repository: Repository | CloningRepository
) {
  if (
    !repository ||
    repository instanceof CloningRepository ||
    !repository.gitHubRepository
  ) {
    return false
  }

  return repository.gitHubRepository.htmlURL !== null
}

function menuItemStateEqual(state: IMenuItemState, menuItem: MenuItem) {
  if (
    state.enabled !== undefined &&
    menuItem.type !== 'separator' &&
    menuItem.enabled !== state.enabled
  ) {
    return false
  }

  return true
}

const squashAndMergeMenuIds: ReadonlyArray<MenuIDs> = enableSquashMerging()
  ? ['squash-and-merge-branch']
  : []

const allMenuIds: ReadonlyArray<MenuIDs> = [
  'rename-branch',
  'delete-branch',
  'discard-all-changes',
  'stash-all-changes',
  'preferences',
  'update-branch',
  'compare-to-branch',
  'merge-branch',
  'rebase-branch',
  'view-repository-on-github',
  'compare-on-github',
  'open-in-shell',
  'push',
  'pull',
  'branch',
  'repository',
  'go-to-commit-message',
  'create-branch',
  'show-changes',
  'show-history',
  'show-repository-list',
  'show-branches-list',
  'open-working-directory',
  'show-repository-settings',
  'open-external-editor',
  'remove-repository',
  'new-repository',
  'add-local-repository',
  'clone-repository',
  'about',
  'create-pull-request',
  ...squashAndMergeMenuIds,
]

function getAllMenusDisabledBuilder(): MenuStateBuilder {
  const menuStateBuilder = new MenuStateBuilder()

  for (const menuId of allMenuIds) {
    menuStateBuilder.disable(menuId)
  }

  return menuStateBuilder
}

function getRepositoryMenuBuilder(state: IAppState): MenuStateBuilder {
  const selectedState = state.selectedState
  const isHostedOnGitHub = selectedState
    ? isRepositoryHostedOnGitHub(selectedState.repository)
    : false

  let repositorySelected = false
  let onNonDefaultBranch = false
  let onBranch = false
  let onDetachedHead = false
  let hasChangedFiles = false
  let hasConflicts = false
  let hasDefaultBranch = false
  let hasPublishedBranch = false
  let networkActionInProgress = false
  let tipStateIsUnknown = false
  let branchIsUnborn = false
  let rebaseInProgress = false
  let branchHasStashEntry = false

  // check that its a github repo and if so, that is has issues enabled
  const repoIssuesEnabled =
    selectedState !== null &&
    selectedState.repository instanceof Repository &&
    getRepoIssuesEnabled(selectedState.repository)

  if (selectedState && selectedState.type === SelectionType.Repository) {
    repositorySelected = true

    const { branchesState, changesState } = selectedState.state
    const tip = branchesState.tip
    const defaultBranch = branchesState.defaultBranch

    hasDefaultBranch = Boolean(defaultBranch)

    onBranch = tip.kind === TipState.Valid
    onDetachedHead = tip.kind === TipState.Detached
    tipStateIsUnknown = tip.kind === TipState.Unknown
    branchIsUnborn = tip.kind === TipState.Unborn

    // If we are:
    //  1. on the default branch, or
    //  2. on an unborn branch, or
    //  3. on a detached HEAD
    // there's not much we can do.
    if (tip.kind === TipState.Valid) {
      if (defaultBranch !== null) {
        onNonDefaultBranch = tip.branch.name !== defaultBranch.name
      } else {
        onNonDefaultBranch = true
      }

      hasPublishedBranch = !!tip.branch.upstream
      branchHasStashEntry = changesState.stashEntry !== null
    } else {
      onNonDefaultBranch = true
    }

    networkActionInProgress = selectedState.state.isPushPullFetchInProgress

    const { conflictState, workingDirectory } = selectedState.state.changesState

    rebaseInProgress = conflictState !== null && conflictState.kind === 'rebase'
    hasConflicts =
      changesState.conflictState !== null ||
      hasConflictedFiles(workingDirectory)
    hasChangedFiles = workingDirectory.files.length > 0
  }

  // These are IDs for menu items that are entirely _and only_
  // repository-scoped. They're always enabled if we're in a repository and
  // always disabled if we're not.
  const repositoryScopedIDs: ReadonlyArray<MenuIDs> = [
    'branch',
    'repository',
    'remove-repository',
    'open-in-shell',
    'open-working-directory',
    'show-repository-settings',
    'go-to-commit-message',
    'show-changes',
    'show-history',
    'show-branches-list',
    'open-external-editor',
    'compare-to-branch',
  ]

  const menuStateBuilder = new MenuStateBuilder()

  const windowOpen = state.windowState !== 'hidden'
  const inWelcomeFlow = state.showWelcomeFlow
  const repositoryActive = windowOpen && repositorySelected && !inWelcomeFlow

  if (repositoryActive) {
    for (const id of repositoryScopedIDs) {
      menuStateBuilder.enable(id)
    }

    menuStateBuilder.setEnabled(
      'rename-branch',
      (onNonDefaultBranch || !hasPublishedBranch) &&
        !branchIsUnborn &&
        !onDetachedHead
    )
    menuStateBuilder.setEnabled(
      'delete-branch',
      onNonDefaultBranch && !branchIsUnborn && !onDetachedHead
    )
    menuStateBuilder.setEnabled(
      'update-branch',
      onNonDefaultBranch && hasDefaultBranch && !onDetachedHead
    )
    menuStateBuilder.setEnabled('merge-branch', onBranch)
    if (enableSquashMerging()) {
      menuStateBuilder.setEnabled('squash-and-merge-branch', onBranch)
    }
    menuStateBuilder.setEnabled('rebase-branch', onBranch)
    menuStateBuilder.setEnabled(
      'compare-on-github',
      isHostedOnGitHub && hasPublishedBranch
    )

    menuStateBuilder.setEnabled('view-repository-on-github', isHostedOnGitHub)
    menuStateBuilder.setEnabled(
      'create-issue-in-repository-on-github',
      repoIssuesEnabled
    )
    menuStateBuilder.setEnabled(
      'create-pull-request',
      isHostedOnGitHub && !branchIsUnborn && !onDetachedHead
    )
    menuStateBuilder.setEnabled(
      'push',
      !branchIsUnborn && !onDetachedHead && !networkActionInProgress
    )
    menuStateBuilder.setEnabled(
      'pull',
      hasPublishedBranch && !networkActionInProgress
    )
    menuStateBuilder.setEnabled(
      'create-branch',
      !tipStateIsUnknown && !branchIsUnborn && !rebaseInProgress
    )

    menuStateBuilder.setEnabled(
      'discard-all-changes',
      repositoryActive && hasChangedFiles && !rebaseInProgress
    )

    menuStateBuilder.setEnabled(
      'stash-all-changes',
      hasChangedFiles && onBranch && !rebaseInProgress && !hasConflicts
    )

    menuStateBuilder.setEnabled('compare-to-branch', !onDetachedHead)
    menuStateBuilder.setEnabled('toggle-stashed-changes', branchHasStashEntry)

    if (
      selectedState &&
      selectedState.type === SelectionType.MissingRepository
    ) {
      menuStateBuilder.disable('open-external-editor')
    }
  } else {
    for (const id of repositoryScopedIDs) {
      menuStateBuilder.disable(id)
    }

    menuStateBuilder.disable('view-repository-on-github')
    menuStateBuilder.disable('create-pull-request')

    if (
      selectedState &&
      selectedState.type === SelectionType.MissingRepository
    ) {
      if (selectedState.repository.gitHubRepository) {
        menuStateBuilder.enable('view-repository-on-github')
      }
      menuStateBuilder.enable('remove-repository')
    }

    menuStateBuilder.disable('create-branch')
    menuStateBuilder.disable('rename-branch')
    menuStateBuilder.disable('delete-branch')
    menuStateBuilder.disable('discard-all-changes')
    menuStateBuilder.disable('stash-all-changes')
    menuStateBuilder.disable('update-branch')
    menuStateBuilder.disable('merge-branch')
    if (enableSquashMerging()) {
      menuStateBuilder.disable('squash-and-merge-branch')
    }
    menuStateBuilder.disable('rebase-branch')

    menuStateBuilder.disable('push')
    menuStateBuilder.disable('pull')
    menuStateBuilder.disable('compare-to-branch')
    menuStateBuilder.disable('compare-on-github')
    menuStateBuilder.disable('toggle-stashed-changes')
  }

  return menuStateBuilder
}

function getMenuState(state: IAppState): Map<MenuIDs, IMenuItemState> {
  if (state.currentPopup) {
    return getAllMenusDisabledBuilder().state
  }

  return getAllMenusEnabledBuilder()
    .merge(getRepositoryMenuBuilder(state))
    .merge(getInWelcomeFlowBuilder(state.showWelcomeFlow))
    .merge(getNoRepositoriesBuilder(state)).state
}

function getAllMenusEnabledBuilder(): MenuStateBuilder {
  const menuStateBuilder = new MenuStateBuilder()
  for (const menuId of allMenuIds) {
    menuStateBuilder.enable(menuId)
  }
  return menuStateBuilder
}

function getInWelcomeFlowBuilder(inWelcomeFlow: boolean): MenuStateBuilder {
  const welcomeScopedIds: ReadonlyArray<MenuIDs> = [
    'new-repository',
    'add-local-repository',
    'clone-repository',
    'preferences',
    'about',
  ]

  const menuStateBuilder = new MenuStateBuilder()
  if (inWelcomeFlow) {
    for (const id of welcomeScopedIds) {
      menuStateBuilder.disable(id)
    }
  } else {
    for (const id of welcomeScopedIds) {
      menuStateBuilder.enable(id)
    }
  }

  return menuStateBuilder
}

function getNoRepositoriesBuilder(state: IAppState): MenuStateBuilder {
  const noRepositoriesDisabledIds: ReadonlyArray<MenuIDs> = [
    'show-repository-list',
  ]

  const menuStateBuilder = new MenuStateBuilder()
  if (state.repositories.length === 0) {
    for (const id of noRepositoriesDisabledIds) {
      menuStateBuilder.disable(id)
    }
  }

  return menuStateBuilder
}

function getRepoIssuesEnabled(repository: Repository): boolean {
  if (isRepositoryWithGitHubRepository(repository)) {
    const ghRepo = repository.gitHubRepository

    if (ghRepo.parent) {
      // issues enabled on parent repo
      return (
        ghRepo.parent.issuesEnabled !== false &&
        ghRepo.parent.isArchived !== true
      )
    }

    // issues enabled on repo
    return ghRepo.issuesEnabled !== false && ghRepo.isArchived !== true
  }

  return false
}

/**
 * Update the menu state in the main process.
 *
 * This function will set the enabledness and visibility of menu items
 * in the main process based on the AppState. All changes will be
 * batched together into one ipc message.
 */
export function updateMenuState(
  state: IAppState,
  currentAppMenu: AppMenu | null
) {
  const menuState = getMenuState(state)

  // Try to avoid updating sending the IPC message at all
  // if we have a current app menu that we can compare against.
  if (currentAppMenu) {
    for (const [id, menuItemState] of menuState.entries()) {
      const appMenuItem = currentAppMenu.getItemById(id)

      if (appMenuItem && menuItemStateEqual(menuItemState, appMenuItem)) {
        menuState.delete(id)
      }
    }
  }

  if (menuState.size === 0) {
    return
  }

  // because we can't send Map over the wire, we need to convert
  // the remaining entries into an array that can be serialized
  const array = new Array<{ id: MenuIDs; state: IMenuItemState }>()
  menuState.forEach((value, key) => array.push({ id: key, state: value }))
  ipcUpdateMenuState(array)
}