text:
<?php

/*
 * By adding type hints and enabling strict type checking, code can become
 * easier to read, self-documenting and reduce the number of potential bugs.
 * By default, type declarations are non-strict, which means they will attempt
 * to change the original type to match the type specified by the
 * type-declaration.
 *
 * In other words, if you pass a string to a function requiring a float,
 * it will attempt to convert the string value to a float.
 *
 * To enable strict mode, a single declare directive must be placed at the top
 * of the file.
 * This means that the strictness of typing is configured on a per-file basis.
 * This directive not only affects the type declarations of parameters, but also
 * a function's return type.
 *
 * For more info review the Concept on strict type checking in the PHP track
 * <link>.
 *
 * To disable strict typing, comment out the directive below.
 */

declare(strict_types=1);

class BinarySearchTest extends PHPUnit\Framework\TestCase
{
    public static function setUpBeforeClass(): void
    {
        require_once 'BinarySearch.php';
    }

    public function testItWorksWithOneElement(): void
    {
        $this->assertEquals(0, find(6, [6]));
    }

    public function testItFindsValueInMiddle(): void
    {
        $this->assertEquals(3, find(6, [1, 3, 4, 6, 8, 9, 11]));
    }

    public function testItFindsValueInBeginning(): void
    {
        $this->assertEquals(0, find(1, [1, 3, 4, 6, 8, 9, 11]));
    }

    public function testItFindsValueAtEnd(): void
    {
        $this->assertEquals(6, find(11, [1, 3, 4, 6, 8, 9, 11]));
    }

    public function testItFindsValueInOddLengthArray(): void
    {
        $this->assertEquals(9, find(144, [1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634]));
    }

    public function testItFindsValueInEvenLengthArray(): void
    {
        $this->assertEquals(5, find(21, [1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]));
    }
    public function testLowerThanLowestValueNotIn(): void
    {
        $this->assertEquals(-1, find(0, [1, 3, 4, 6, 8, 9, 11]));
    }

    public function testLargerThanLargestValueNotIn(): void
    {
        $this->assertEquals(-1, find(13, [1, 3, 4, 6, 8, 9, 11]));
    }

    public function testNothingInEmptyArray(): void
    {
        $this->assertEquals(-1, find(1, []));
    }
}


text:
@implementation IFIOCObjectFactoryBase

- (id)initWithBaseConfiguration:(NSDictionary *)baseConfiguration {
    self = [super init];
    if (self) {
        IFConfiguration *configuration = [[IFConfiguration alloc] initWithData:baseConfiguration];
        _baseConfiguration = [configuration flatten];
    }
    return self;
}

- (id)buildObjectWithConfiguration:(IFConfiguration *)configuration
                       inContainer:(IFContainer *)container
                    withParameters:(NSDictionary *)params
                        identifier:(NSString *)identifier {
    // Flatten the object configuration.
    configuration = [configuration flatten];
    // Extend the object configuration from the base configuration.
    configuration = [_baseConfiguration mergeConfiguration:configuration];
    // If any parameters then extend the configuration using them.
    if (params) {
        configuration = [configuration extendWithParameters:params];
    }
    // Ask the container to build the object, then return the result.
    return [container buildObjectWithConfiguration:configuration identifier:identifier];
}

- (id)buildObjectWithConfiguration:(IFConfiguration *)configuration
                       inContainer:(IFContainer *)container
                        identifier:(NSString *)identifier {
    return [self buildObjectWithConfiguration:configuration inContainer:container withParameters:nil identifier:identifier];
}

@end

redpajama_set_name: RedPajamaGithub


text:
require 'airbrake'

module LoggerFacade::Plugins

  class Airbrake < Base

    attr_reader :environment

    def initialize(environment = nil)
      super("LoggerFacade::Plugins::Airbrake", { level: :error })
      @environment = environment.to_s
      set_default_airbrake_config
    end

    def configure(&block)
      ::Airbrake.configure do |config|
        yield config
      end
    end

    protected

    def log(log_level, message, logger, metadata)
      return unless is_level_active(log_level)
      return if is_dev_env?

      notify(logger, message, metadata)
    end

    private

    def is_dev_env?
      ::Airbrake.configuration.development_environments.include? environment
    end

    def notify(logger, message, metadata)
      return unless valid_config

      if message.is_a? Exception
        notify_exception(message, logger)
      else
        notify_error_log(message, logger)
      end
    end

    def set_default_airbrake_config
      ::Airbrake.configure do |config|
        config.host    = nil
        config.port    = 80
        config.secure  = config.port == 443
        config.async   = true
        config.development_environments = %w(development test)
      end
    end

    def valid_config
      config = ::Airbrake.configuration
      config.api_key && config.host
    end

    def notify_error_log(message, logger)
      ::Airbrake.notify_or_ignore(
        :error_class      => "#{logger}::LogError",
        :error_message    => "#{logger}::LogError: #{message}",
        :backtrace        => $@,
        :cgi_data         => ENV.to_hash,
        :environment_name => environment
      )
    end

    def notify_exception(e, logger)
      ::Airbrake.notify_or_ignore(
        e,
        :backtrace        => $@,
        :cgi_data         => ENV.to_hash,
        :environment_name => environment
      )
    end

  end

end


text: """Command line interface package."""


text: update vm_static set numatune_mode ='interleave';


text:
===========
rhel-common
===========
This element contains the common installation steps between RHEL os releases.

RHEL Registration
-----------------
This element provides functionality for registering RHEL images during the
image build process with the disk-image-create script from diskimage-builder.
The RHEL image will register itself with either the hosted Red Hat Customer
Portal or Satellite to enable software installation from official
repositories. After the end of the image creation process, the image will
unregister itself so an entitlement will not be decremented from the account.

SECURITY WARNING:
-----------------
While the image building workflow will allow you to register with a username
and password combination, that feature is deprecated in the boot process via
Heat as it will expose your username and password in clear text for anyone
that has rights to run heat stack-show.  A compromised username and password
can be used to login to the Red Hat Customer Portal or an instance of
Satellite.  An activation key can only be used for registration purposes using
the subscription-manager command line tool and is considered a lower security
risk.

IMPORTANT NOTES:
----------------
The 00-rhsm script is specific to RHEL6.  If you use the REG\_ variables to
use with RHEL7, you do not need to set any DIB_RHSM variables.  The scripts
named with "rhel-registration" have not been developed or tested for RHEL6.
For information on building RHEL6 images, please see the rhel element README.

The 01-module-configuration script is specific to RHEL8.  RHEL8 includes
various versions of software which can be selected during installation, some
may be older and/or incompatible with a given release of OpenStack.

Environment Variables For Regisration during Image Creation
-----------------------------------------------------------
The following environment variables are used for registering a RHEL instance
with either the Red Hat Customer Portal or Satellite 6.

#### REG\_ACTIVATION\_KEY
Attaches existing subscriptions as part of the registration process. The
subscriptions are pre-assigned by a vendor or by a systems administrator
using Subscription Asset Manager.

#### REG\_AUTO\_ATTACH
Automatically attaches the best-matched compatible subscription. This is
good for automated setup operations, since the system can be configured
in a single step.

#### REG\_BASE\_URL
Gives the hostname of the content delivery server to use to receive updates.
Both Customer Portal Subscription Management and Subscription Asset Manager
use Red Hat's hosted content delivery services, with the URL
https://cdn.redhat.com. Since Satellite 6 hosts its own content, the URL
must be used for systems registered with Satellite 6.

#### REG\_ENVIRONMENT
Registers the system to an environment within an organization.

#### REG\_FORCE
Registers the system even if it is already registered. Normally, any register
operations will fail if the machine is already registered.

#### REG\_HALT\_UNREGISTER
At the end of the image build process, the element runs a cleanup script that
will unregister it from the system it registered with.  There are some cases
when building an image where you may want to stop this from happening so you
can verify the registration or to build a one off-image where the boot-time
registration will not be enabled.  Set this value to '1' to stop the
unregistration process.

#### REG\_MACHINE\_NAME
Sets the name of the system to be registered. This defaults to be the same as
the hostname.

#### REG\_METHOD
Sets the method of registration.  Use "portal" to register a system with the
Red Hat Customer Portal.  Use "satellite" to register a system with Red
Hat Satellite 6.  Use "disable" to skip the registration process.

#### REG\_ORG
Gives the organization to which to join the system.

#### REG\_POOL\_ID
The pool ID is listed with the product subscription information, which is
available from running the list subcommand of subscription-manager.

#### REG\_PASSWORD
Gives the password for the user account.

#### REG\_RELEASE
Sets the operating system minor release to use for subscriptions for the
system. Products and updates are limited to that specific minor release
version. This is used only used with the REG_AUTO_ATTACH option.  Possible
values for this include 5Server, 5.7, 5.8, 5.9, 5.10, 6.1,...6.6, 7.0.
It will change over time as new releases come out.  There are also variants
6Server, 6Client, 6Workstation, 7Server, etc.

#### REG\_REPOS
A single string representing a list of repository names separated by a
comma (No spaces).  Each of the repositories in this string are enabled
through subscription manager.  Once you've attached a subscription, you can
find available repositories by running subscription-manager repos --list.

#### REG\_SERVER\_URL
Gives the hostname of the subscription service to use. The default is
for Customer Portal Subscription Management, subscription.rhn.redhat.com.
If this option is not used, the system is registered with Customer Portal
Subscription Management.

#### REG\_SERVICE\_LEVEL
Sets the service level to use for subscriptions on that machine. This
is only used with the REG_AUTO_ATTACH option.

#### REG\_USER
Gives the content server user account name.

#### REG\_TYPE
Sets what type of consumer is being registered. The default is system, which
is applicable to both physical systems and virtual guests. Other types include
hypervisor for virtual hosts, person, domain, rhui, and candlepin for some
subscription management applications.

Image Build Registration Examples
------------------------------------
To register with Satellite 6, a common example would be to set the following
variables:

REG_SAT_URL='http://my-sat06.server.org'
REG_ORG='tripleo'
REG_ENV='Library'
REG_USER='tripleo'
REG_PASSWORD='tripleo'
REG_METHOD=satellite

To register with the Red Hat Customer Portal, a common example would be to
set the following variables:

REG_REPOS='rhel-7-server-optional-rpms,rhel-7-server-extras-rpms'
REG_AUTO_ATTACH=true
REG_USER='tripleo'
REG_PASSWORD='tripleo'
REG_METHOD=portal

Configuration
-------------
Heat metadata can be used to configure the rhel-common element.

    rh_registration:
        activation_key:
            # Attaches existing subscriptions as part of the registration
            # process. The subscriptions are pre-assigned by a vendor or by
            # a systems administrator using Subscription Asset Manager.
        auto_attach: 'true'
            # Automatically attaches the best-matched compatible subscription.
            # This is good for automated setup operations, since the system can
            # be configured in a single step.
        base_url:
            # Gives the hostname of the content delivery server to use to
            # receive updates.  Both Customer Portal Subscription Management
            # and Subscription Asset Manager use Red Hat's hosted content
            # delivery services, with the URL https://cdn.redhat.com. Since
            # Satellite 6 hosts its own content, the URL must be used for
            # systems registered with Satellite 6.
        environment:
            # Registers the system to an environment within an organization.
        force:
            # Registers the system even if it is already registered. Normally,
            # any register operations will fail if the machine is already
            # registered.
        machine_name:
            # Sets the name of the system to be registered. This defaults to be
            # the same as the hostname.
        org:
            # Gives the organization to which to join the system.
        password:
            # DEPRECATED
            # Gives the password for the user account.
        release:
            # Sets the operating system minor release to use for subscriptions
            # for the system. Products and updates are limited to that specific
            # minor release version. This is only used with the auto_attach
            # option.
        repos:
            # A single string representing a list of repository names separated by a
            # comma (No spaces).  Each of the repositories in this string are enabled
            # through subscription manager.
        satellite_url:
            # The url of the Satellite instance to register with.  Required for
            # Satellite registration.
        server_url:
            # Gives the hostname of the subscription service to use. The default
            # is for Customer Portal Subscription Management,
            # subscription.rhn.redhat.com. If this option is not used, the system
            # is registered with Customer Portal Subscription Management.
        service_level:
            # Sets the service level to use for subscriptions on that machine.
            # This is only used with the auto_attach option.
        user:
            # DEPRECATED
            # Gives the content server user account name.
        type:
            # Sets what type of consumer is being registered. The default is
            # "system", which is applicable to both physical systems and virtual
            # guests. Other types include "hypervisor" for virtual hosts,
            # "person", "domain", "rhui", and "candlepin" for some subscription
            # management applications.
        method:
            # Sets the method of registration.  Use "portal" to register a
            # system with the Red Hat Customer Portal.  Use "satellite" to
            # register a system with Red Hat Satellite 6.  Use "disable" to
            # skip the registration process.
        satellite_cert:
            # Defines the ssl certificate to be installed when using "satellite"
            # as register mechanism. Default values of this is
            # "katello-ca-consumer-latest.noarch.rpm".

Configuration Registration Examples
------------------------------------
To register with Satellite 6, a common example would be to use the following
metadata::

    {
        "rh_registration":{
            "satellite_url": "http://my-sat06.server.org",
            "org": "tripleo",
            "environment": "Library",
            "activation_key": "my-key-SQQkh4",
            "method":"satellite",
            "repos": "rhel-ha-for-rhel-7-server-rpms"
        }
    }

To register with the Red Hat Customer Portal, a common example would be to
use the following metadata::

    {
        "rh_registration":{
            "repos":"rhel-7-server-optional-rpms,rhel-7-server-extras-rpms",
            "auto_attach":true,
            "activation_key": "my-key-SQQkh4",
            "org": "5643002",
            "method":"portal"
        }
    }

Environment Variables for Module Selection during Image Creation
----------------------------------------------------------------
The following environment variable is used to select module streams to be
enabled during an image build on RHEL8.  Any existing stream for the given
module is first disabled prior to enabling the specified stream.

#### DIB\_DNF\_MODULE\_STREAMS
This is a space-separated list of module streams to enable prior to any
RPMs being installed.

Image Build Module Selection Example
------------------------------------
When using Train on RHEL8.2, one must select the appropriate virt and
container-tools module streams:

DIB_DNF_MODULE_STREAMS='virt:8.2 container-tools:2.0'


text:
package com.asakusafw.lang.compiler.core;

import com.asakusafw.lang.compiler.api.CompilerOptions;
import com.asakusafw.lang.compiler.common.DiagnosticException;
import com.asakusafw.lang.compiler.model.graph.Batch;
import com.asakusafw.lang.compiler.packaging.FileContainer;
import com.asakusafw.lang.compiler.packaging.FileContainerRepository;

/**
 * Compiles Asakusa batches.
 */
@FunctionalInterface
public interface BatchCompiler {

    /**
     * Compiles the target jobflow.
     * @param context the current context
     * @param batch the target batch
     * @throws DiagnosticException if compilation was failed
     */
    void compile(Context context, Batch batch);

    /**
     * A context for {@link BatchCompiler}.
     */
    class Context extends CompilerContext.Basic {

        private final FileContainer output;

        /**
         * Creates a new instance.
         * Note that, this does NOT inherit the extension objects from the parent context.
         * @param parent the parent context
         * @param output the package element output
         */
        public Context(CompilerContext parent, FileContainer output) {
            this(parent.getOptions(), parent.getProject(), parent.getTools(), output, parent.getTemporaryOutputs());
        }

        /**
         * Creates a new instance.
         * @param options the compiler options
         * @param project the project information
         * @param tools the compiler tools
         * @param output the package elements output
         * @param temporary the temporary output provider
         */
        public Context(
                CompilerOptions options,
                ProjectRepository project,
                ToolRepository tools,
                FileContainer output,
                FileContainerRepository temporary) {
            super(options, project, tools, temporary);
            this.output = output;
        }

        /**
         * Returns the file container for batch package output.
         * @return the output file container
         */
        public FileContainer getOutput() {
            return output;
        }
    }
}


text:
package cryodex.modules.destiny.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JPanel;

import cryodex.CryodexController;
import cryodex.modules.Match;
import cryodex.modules.Match.GameResult;
import cryodex.modules.RoundPanel;
import cryodex.modules.destiny.DestinyTournament;

public class DestinyRoundPanel extends RoundPanel {

    private static final long serialVersionUID = 1L;

    public DestinyRoundPanel(DestinyTournament t, List<Match> matches) {
        super(t, matches);
    }

    @Override
    public void buildGamePanel(JPanel panel, GridBagConstraints gbc, cryodex.modules.RoundPanel.GamePanel gamePanel) {
        GamePanel gp = (GamePanel) gamePanel;

        gbc.gridy++;
        gbc.gridx = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(gp.getPlayerTitle(), gbc);

        gbc.gridx = 2;
        gbc.fill = GridBagConstraints.BOTH;
        panel.add(gp.getResultCombo(), gbc);
    }

    @Override
    public List<cryodex.modules.RoundPanel.GamePanel> getGamePanels(List<Match> matches) {
        List<RoundPanel.GamePanel> gamePanels = new ArrayList<RoundPanel.GamePanel>();

        int counter = 0;
        for (Match match : matches) {
            counter++;
            GamePanel gp = new GamePanel(counter, match);
            gamePanels.add(gp);
        }

        return gamePanels;
    }

    private class GamePanel extends RoundPanel.GamePanel {

        private JComboBox<String> resultsCombo;

        public GamePanel(int tableNumber, Match match) {
            super(tableNumber, match);
        }

        private String[] getComboValues() {

            if (getMatch().getPlayer2() == null) {
                String[] values = { "Select a result", "BYE" };
                return values;
            } else {
                String generic = "Select a result";
                String[] values = { generic, "WIN - " + getMatch().getPlayer1().getName(), "WIN - " + getMatch().getPlayer2().getName() };
                return values;
            }
        }

        private JComboBox<String> getResultCombo() {
            if (resultsCombo == null) {

                resultsCombo = new JComboBox<String>(getComboValues());

                resultsCombo.setRenderer(new DefaultListCellRenderer() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void paint(Graphics g) {
                        setForeground(Color.BLACK);
                        super.paint(g);
                    }
                });

                resultsCombo.addActionListener(GamePanel.this);
            }
            return resultsCombo;
        }

        public void setMatchResultFromGUI() {

            switch (getResultCombo().getSelectedIndex()) {
            case 0:
                getMatch().setGame1Result(null);
                break;
            case 1:
                if (getMatch().isBye() == false) {
                    getMatch().setGame1Result(GameResult.PLAYER_1_WINS);
                }
                break;
            case 2:
                getMatch().setGame1Result(GameResult.PLAYER_2_WINS);
                break;
            default:
                break;
            }
        }

        public void setGUIFromMatch() {

            if (getTournament().isMatchComplete(getMatch())) {
                if (getMatch().isBye()) {
                    getResultCombo().setSelectedIndex(1);
                } else {
                    if (getMatch().getWinner(1) == getMatch().getPlayer1()) {
                        getResultCombo().setSelectedIndex(1);
                    } else if (getMatch().getWinner(1) == getMatch().getPlayer2()) {
                        getResultCombo().setSelectedIndex(2);
                    }
                }
            }

            // Special exception for bye matches
            if (getMatch().isBye()) {
                getResultCombo().setSelectedIndex(1);
            }

            updateGUI();
        }

        public void updateGUI() {
            String titleText = null;

            boolean hideCompletedMatches = CryodexController.getOptions().isHideCompleted();

            boolean visible = hideCompletedMatches == false || getTournament().isMatchComplete(getMatch()) == false;

            getPlayerTitle().setVisible(visible);
            getResultCombo().setVisible(visible);

            if (getMatch().getPlayer2() == null) {
                titleText = getMatch().getPlayer1().getName() + " has a BYE";
            } else {
                titleText = getMatch().getPlayer1().getName() + " VS " + getMatch().getPlayer2().getName();
                if (getMatch().isDuplicate()) {
                    titleText = "(Duplicate)" + titleText;
                }

                if (CryodexController.getOptions().isShowTableNumbers()) {
                    titleText = getTableNumber() + ": " + titleText;
                }
            }

            getPlayerTitle().setText(titleText);

            getResultCombo().setEnabled(true);
        }

        @Override
        public void setResultsCombo() {
            // No Function
        }

        @Override
        public void setMatchPointsFromGUI() {
            // No Function
        }

        @Override
        public void addToFocusPolicy(Vector<Component> order) {
            // No Function
        }
    }
}


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugin;

use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * The base class for console commands.
 *
 * @api
 */
class ConsoleCommand extends SymfonyCommand
{
    public function writeSuccessMessage(OutputInterface $output, $messages)
    {
        $lengths = array_map('strlen', $messages);
        $maxLen = max($lengths) + 4;

        $separator = str_pad('', $maxLen, '*');

        $output->writeln('');
        $output->writeln('<info>' . $separator . '</info>');

        foreach ($messages as $message) {
            $output->writeln('  ' . $message . '  ');
        }

        $output->writeln('<info>' . $separator . '</info>');
        $output->writeln('');
    }

    protected function checkAllRequiredOptionsAreNotEmpty(InputInterface $input)
    {
        $options = $this->getDefinition()->getOptions();

        foreach ($options as $option) {
            $name  = $option->getName();
            $value = $input->getOption($name);

            if ($option->isValueRequired() && empty($value)) {
                throw new \InvalidArgumentException(sprintf('The required option %s is not set', $name));
            }
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enchir. fung. (Paris) 67 (1886)

#### Original name
Agaricus destruens Brond., 1829

### Remarks
null


text:
'use strict';

var setTimeout = require('timers').setTimeout;

var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('register and forward', {
    size: 5
}, function t(cluster, assert) {
    cluster.logger.whitelist('info', 'resetting connection');

    var steve = cluster.remotes.steve;
    var bob = cluster.remotes.bob;

    cluster.checkExitPeers(assert, {
        serviceName: steve.serviceName,
        hostPort: steve.hostPort
    });

    setTimeout(waitForConnect, 100);

    function waitForConnect() {
        // Force determinism
        bob.clientChannel.eachConnection(function close(conn) {
            if (conn.direction === 'out') {
                conn.resetAll();
            }
        });

        bob.clientChannel.request({
            serviceName: steve.serviceName
        }).send('echo', null, JSON.stringify('oh hi lol'), onPreFlight);
    }

    function onPreFlight(err) {
        assert.ifError(err);

        var exitNodes = cluster.getExitNodes(bob.serviceName);

        for (var i = 0; i < exitNodes.length; i++) {
            exitNodes[i].clients.egressNodes.changedEvent.emit();
        }

        makeRequest();
    }

    function makeRequest() {
        bob.clientChannel.request({
            serviceName: steve.serviceName
        }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
    }

    function onForwarded(err, res, arg2, arg3) {
        if (err) {
            assert.ifError(err);
            return assert.end();
        }

        assert.equal(String(arg3), '"oh hi lol"');

        assert.end();
    }
});


text:
package org.apache.reef.mock.request;

import org.apache.reef.annotations.Unstable;
import org.apache.reef.annotations.audience.Private;
import org.apache.reef.driver.task.CompletedTask;
import org.apache.reef.driver.task.FailedTask;
import org.apache.reef.mock.MockTaskReturnValueProvider;
import org.apache.reef.mock.ProcessRequest;
import org.apache.reef.mock.runtime.MockCompletedTask;
import org.apache.reef.mock.runtime.MockRunningTask;
import org.apache.reef.util.Optional;

/**
 * close task process request.
 */
@Unstable
@Private
public final class CloseTask implements ProcessRequestInternal<CompletedTask, FailedTask> {

  private final MockRunningTask task;

  private final MockTaskReturnValueProvider taskReturnValueProvider;

  public CloseTask(
      final MockRunningTask task,
      final MockTaskReturnValueProvider taskReturnValueProvider) {
    this.task = task;
    this.taskReturnValueProvider = taskReturnValueProvider;
  }

  public MockRunningTask getTask() {
    return task;
  }

  @Override
  public Type getType() {
    return Type.CLOSE_TASK;
  }

  @Override
  public MockCompletedTask getSuccessEvent() {
    return new MockCompletedTask(this.task, this.taskReturnValueProvider.getReturnValue(task));
  }

  @Override
  public FailedTask getFailureEvent() {
    return new FailedTask(
      task.getId(),
      "mock",
      Optional.<String>empty(),
      Optional.<Throwable>empty(),
      Optional.<byte[]>empty(),
      Optional.of(this.task.getActiveContext()));
  }

  @Override
  public boolean doAutoComplete() {
    return false;
  }

  @Override
  public void setAutoComplete(final boolean value) {
    throw new UnsupportedOperationException();
  }

  @Override
  public ProcessRequest getCompletionProcessRequest() {
    throw new UnsupportedOperationException();
  }
}


text:
There are currently a number of options you can supply to the compiler. This document simply gives a detailed explanation
and example usage of each. Note that this list will likely fluctuate and change over time, so keep an eye on this list and
update it accordingly.

## Glossary

If you invoke the RESOLVE compiler without command line arguments, you should get a help message that looks something like
this:

```
RESOLVE Compiler Version 0.0.1
 -o ___              specify output directory where all output is generated
 -long-messages      show exception details when available for errors and warnings
 -lib ___            specify location of resolve source files
 -genCode ___        generate code
 -package ___        specify a package/namespace for the generated code
 -vcs                generate verification conditions (VCs)
 -Xlog               dump lots of logging info to edu.clemson.resolve-timestamp.log
```

Here are some additional details on the options:

## `-o <outdir>`

RESOLVE generates output files in the current directory by default. This option specifies where the compiler will place any generated code such as VC `asrt` files, executable java, proof results, logs files, etc.

```
$ resolve -o /tmp T.resolve
$ ls /tmp/T*
/tmp/T.java
```

## `-lib <libdir>`

Sets a root search directory for the compiler. That is, when searching for a targetfile (or anything else) the compiler will start its search at `lib` and proceed recursively through all subdirectories.

Example. If your desired workspace directory is `playground` and is organized as follows:

```
$ cd ~/Documents/playground/
$ ls
$ concepts    facilities    precis
```
and you're targetfile is `Documents/playground/concepts/foo_template/T.resolve`, then you'll probably want to set `libdir` to `Documents/playground` as follows:
```
$ resolve concepts/foo_template/T.resolve -lib Documents/playground
```

## `-genCode <target>`

Specifies that the compiler should generate executable code for the current `target` file. Note that currently we only support a single target language: `Java`.

*Note: It's likely that we won't be adding any new targets (in near the future that is) so this command should likely be made argumentless soon.*

## `-package <pkg>`

Use this option to specify a package or namespace for any generated, executable `.java` files. If this is not present when generating java code, no namespace is present for the generated files.

## `-vcs`

Tells the compiler to generate VCs (**V**erification **C**ondition**s**) for the current target file. Results are written out to the current directory (unless `-o` is present) as a `.asrt` file with the same name as the target file specified.


text:
//clicking on the Add button

package mm.webclientservlets;

import mm.da.*;
import mm.model.*;
import mm.model.User.userType;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.GeneratePass;

/**
 * Servlet implementation class LoginWeb
 */

@WebServlet("/AddNewMentor")
public class AddNewMentor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void AddMentorButton() {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("AddMentor Servlet");

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Add New MentorServlet");
		String email = request.getParameter("email");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String phoneNumber = request.getParameter("phoneNumber");
		String address = request.getParameter("address");
		String notes = request.getParameter("notes");
		String experience = request.getParameter("experience");
		String volunteering = request.getParameter("volunteering");
		int gender = Integer.parseInt(request.getParameter("gender"));
		String nextPage = request.getParameter("jsp");
		String workHistory = request.getParameter("history");
		String role = request.getParameter("role");
		String pass = GeneratePass.getSaltString();
		String ProfilePicture = request.getParameter("profilePicture");
		String cityId=request.getParameter("cityId");
		String areaId=request.getParameter("areaId");
		String comp=request.getParameter("company");
		int uCity;
		int uArea;
		int company;
		System.out.println("company: "+comp+"city "+cityId +"area: "+ areaId);

		if(cityId.equals(null) ||cityId.equals(""))
			uCity=0;
		else
			uCity= Integer.parseInt(cityId);

		if(areaId.equals(null) ||areaId.equals(""))
		   uArea=0;
		else
		  uArea= Integer.parseInt(areaId);
		if(comp.equals(null) ||comp.equals(""))
			company=0;
		else
		    company = Integer.parseInt(comp);

		long millis=System.currentTimeMillis();
	    java.sql.Date date=new java.sql.Date(millis);

		User newMentor = new Mentor(0, firstName, lastName, email, phoneNumber, pass, gender, address, notes,
				ProfilePicture, true, userType.MENTOR,uArea,"",uCity,"",date, experience, role, company, volunteering, workHistory);
		DataAccess da = new DataAccess();
		int res = -1;
		RequestDispatcher req = null;

		try {
			res = da.addUser(newMentor);

		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (res>0) {
			response.getWriter().append("Mentor Added");
			req = request.getRequestDispatcher(nextPage);
			String to = email;
			String subject = "Thank you for registering to Mentorem project";
			String apk="https://goo.gl/dbYx8R";
		    String body = "Hi "+firstName+" "+lastName+",\nWe appreciate your registeration for Mentorem project,\n" +"Here is your login username and passwod: \n\nUsername: "+email+"\nPassword: " +pass+"\nDownload and Install the android client app  \n "+ apk+"\n\nHave a good day,\nTsofen team";

		    SendingMail.sendFromGMail(to,subject,body);

		}
		try {
			da.closeConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (res==-1)
		response.getWriter().append("Failed in added Mentor");

		newMentor.setId(res);
		request.setAttribute("NewMentor", newMentor);
		req=request.getRequestDispatcher("GetAllMentors");
		req.forward(request, response);
	}
}


text:
import core = require('../../interfaces');

export interface IBackgroundImage {
	attachment: string /* should be enum */;
	clip: string /* should be enum */;
	origin: string /* should be enum */;
	position: string /* should be enum */;
	repeat: string /* should be enum */;
	size: string /* should be enum */;
	url: string;
}

/* not all widget backends would support all background features; we are just starting with HTML/CSS for now */
export interface IBackgroundStyle {
	color: IColor;
	images: IBackgroundImage[];
}

export /* class */ interface IColor {
	r: number;
	g: number;
	b: number;
	h: number;
	s: number;
	l: number;
	a: number;
	toHex(): string;
	toString(): string;
}

export interface IClassList {
	add(className:string):void;
	has(className:string):boolean;
	remove(className:string):void;
	toggle(className:string, forceState?:boolean):void;
}

export interface IStyle extends core.IObservable {
	// Combined styles interface for multiple platform support
	background?: IBackgroundStyle;
	textColor?: IColor;
	/* etc. */

	observe(observer:core.IObserver<any>):IHandle;
	observe(key:string, observer:core.IObserver<any>):IHandle;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 Johan Nilsson <http://markupartist.com>

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources>
    <color name="actionbar_separator">#223253</color>
    <color name="actionbar_title">#FFFFFF</color>
    <color name="actionbar_background_start">#3E5C97</color>
    <color name="actionbar_background_end">#3E5C97</color>
    <color name="actionbar_background_item_pressed_start">#48C4FF</color>
    <color name="actionbar_background_item_pressed_end">#48C4FF</color>
</resources>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.springframework.mock.web Class Hierarchy (Spring Framework 4.3.3.RELEASE API)</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.springframework.mock.web

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

javax.servlet.jsp.el.ExpressionEvaluator

org.springframework.mock.web.MockExpressionEvaluator

java.io.InputStream (implements java.io.Closeable)

javax.servlet.ServletInputStream

org.springframework.mock.web.DelegatingServletInputStream

javax.servlet.jsp.JspContext

javax.servlet.jsp.PageContext

org.springframework.mock.web.MockPageContext

org.springframework.mock.web.MockAsyncContext (implements javax.servlet.AsyncContext)

org.springframework.mock.web.MockFilterChain (implements javax.servlet.FilterChain)

org.springframework.mock.web.MockFilterConfig (implements javax.servlet.FilterConfig)

org.springframework.mock.web.MockHttpServletRequest (implements javax.servlet.http.HttpServletRequest)

org.springframework.mock.web.MockMultipartHttpServletRequest (implements org.springframework.web.multipart.MultipartHttpServletRequest)

org.springframework.mock.web.MockHttpServletResponse (implements javax.servlet.http.HttpServletResponse)

org.springframework.mock.web.MockHttpSession (implements javax.servlet.http.HttpSession)

org.springframework.mock.web.MockMultipartFile (implements org.springframework.web.multipart.MultipartFile)

org.springframework.mock.web.MockRequestDispatcher (implements javax.servlet.RequestDispatcher)

org.springframework.mock.web.MockServletConfig (implements javax.servlet.ServletConfig)

org.springframework.mock.web.MockServletContext (implements javax.servlet.ServletContext)

org.springframework.mock.web.MockSessionCookieConfig (implements javax.servlet.SessionCookieConfig)

java.io.OutputStream (implements java.io.Closeable, java.io.Flushable)

javax.servlet.ServletOutputStream

org.springframework.mock.web.DelegatingServletOutputStream

org.springframework.mock.web.PassThroughFilterChain (implements javax.servlet.FilterChain)

java.io.Writer (implements java.lang.Appendable, java.io.Closeable, java.io.Flushable)

javax.servlet.jsp.JspWriter

javax.servlet.jsp.tagext.BodyContent

org.springframework.mock.web.MockBodyContent

org.springframework.mock.web.MockJspWriter

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
package se.kb.oai.pmh;

import java.util.LinkedList;

import org.dom4j.Document;
import org.dom4j.Node;

/**
 * This class represents the response from a ListMetadataFormats request to the OAI-PMH server.
 * Can be used to get a list of MetadataFormats, i.e. asList() will return a List<MetadataFormat>.
 *
 * @author Oskar Grenholm, National Library of Sweden
 */
public class MetadataFormatsList extends ListBase<MetadataFormat> {

    private static final String METADATAFORMAT_XPATH = "oai:ListMetadataFormats/oai:metadataFormat";

    /**
     * Creates a MetadataFormatsList from the returned response.
     *
     * @param document the response
     * @throws ErrorResponseException
     */
    public MetadataFormatsList(Document document) throws ErrorResponseException {
        super(document);

        super.list = new LinkedList<MetadataFormat>();
        for ( Node metadataFormat : this.xpath.selectNodes(METADATAFORMAT_XPATH) ) {
            this.list.add(new MetadataFormat(metadataFormat));
        }
    }

    /**
     * Overrides getResumptionToken in ListBase and because the response from a ListMetadataFormats request will never
     * have a resumption token this method will throw a NoSuchMethodError to prevent it from being used in that way.
     */
    @Override
    public ResumptionToken getResumptionToken() {
        throw new NoSuchMethodError("The response from the verb 'ListMetadataFormats' " + "can't have a ResumptionToken!");
    }
}


text:
{{ $project->name }}
        @if (! $project->owner)
            Contributor only
        @endif

                html_url }}" target="_blank">{{ substr($project->html_url, 8) }}

{{ $project->description }}

                @if ($project->downloads_count > 500)

                    html_url }}">{{ number_format_locale($project->downloads_count) }} Downloads

                @endif

                    html_url }}">{{ number_format_locale($project->stargazers_count) }} Stars


text:
<?php

namespace Cubalider\Component\Mobile\Manager;

use Cubalider\Component\Mobile\Model\Mobile;
use Doctrine\ORM\EntityManagerInterface;
use Yosmanyga\Component\Dql\Fit\Builder;
use Yosmanyga\Component\Dql\Fit\WhereCriteriaFit;

/**
 * @author Yosmany Garcia <yosmanyga@gmail.com>
 */
class MobileManager implements MobileManagerInterface
{
    /**
     * @var string
     */
    private $class = 'Cubalider\Component\Mobile\Model\Mobile';

    /**
     * @var \Doctrine\ORM\EntityManagerInterface
     */
    private $em;

    /**
     * @var Builder;
     */
    private $builder;

    /**
     * Constructor.
     *
     * @param EntityManagerInterface $em
     * @param Builder $builder
     */
    public function __construct(EntityManagerInterface $em, Builder $builder = null)
    {
        $this->em = $em;
        $this->builder = $builder ? : new Builder($em);
    }

    /**
     * @inheritdoc
     */
    public function add(Mobile $mobile)
    {
        $this->em->persist($mobile);
        $this->em->flush();
    }

    /**
     * @inheritdoc
     */
    public function pick($criteria)
    {
        if (is_string($criteria)) {
            $criteria = array('number' => $criteria);
        }
        $qb = $this->builder->build(
            $this->class,
            new WhereCriteriaFit($criteria)
        );

        return $qb
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @inheritdoc
     */
    public function remove($mobile)
    {
        $this->em->remove($mobile);
        $this->em->flush();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="一个 UI 设计语言"/>
    <title>
Radio 单选框 - Ant Design
</title>
    <link rel="icon" href="https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png" type="image/x-icon">
    <link rel="shortcut icon" href="https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png" type="image/x-icon">

    <link rel="stylesheet" href="../../dist/demo.css">
    <link rel="stylesheet" href="../../static/style.css">
    <link rel="stylesheet" href="../../static/tomorrow.css">

        Ant Design

            首页

            设计

            案例

            React

            Github

          Ant Design of React

          快速上手

          安装

          0.10 升级指南

          更新日志

Components

基本

              Button
              按钮

              Icon
              图标

              Layout
              布局

表单

              Checkbox
              多选框

              Datepicker
              日期选择框

              Form
              表单

              InputNumber
              数字输入框

              Radio
              单选框

              Select
              选择器

              Slider
              滑动输入条

              Switch
              开关

              Timepicker
              时间选择框

              Upload
              文件上传

              Validation
              表单校验

展示

              Alert
              警告提示

              Badge
              徽标数

              Calendar
              日历

              Carousel
              走马灯

              Collapse
              折叠面板

              Dropdown
              下拉菜单

              Message
              全局提示

              Modal
              对话框

              Notification
              通知提醒框

              Popconfirm
              气泡确认框

              Popover
              气泡卡片

              Progress
              进度条

              Table
              表格

              Tag
              标签

              Timeline
              时间轴

              Tooltip
              文字提示

              Tree
              树形控件

导航

              Breadcrumb
              面包屑

              Menu
              导航菜单

              Pagination
              分页

              Steps
              步骤条

              Tabs
              标签页

其他

              Affix
              固钉

              QueueAnim
              进出场动画

              Spin
              加载中

      Radio 单选框

单选框。

何时使用#

用于在多个备选项中选中单个状态。

和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。

API#

Radio#

参数
说明
类型
可选值
默认值

checked
指定当前是否选中
Boolean

false

defaultChecked
初始是否选中
Boolean

false

value
根据 value 进行比较,判断是否选中
String

无

RadioGroup#

单选框组合,用于包裹一组 Radio。

参数
说明
类型
可选值
默认值

onChange
选项变化时的回调函数
Function(e:Event)
无
无

value
用于设置当前选中的值
String
无
无

defaultValue
默认选中的值
String
无
无

  代码演示

import { Radio } from 'antd';

ReactDOM.render(<Radio>Radio</Radio>
, document.getElementById('components-radio-demo-basic'));

      基本

最简单的用法。

import { Radio } from 'antd';
const RadioGroup = Radio.Group;

const App = React.createClass({
  getInitialState: function () {
    return {
      value: 'a'
    };
  },
  onChange(e) {
    console.log('radio checked:' + e.target.value);
    this.setState({
      value: e.target.value
    });
  },
  render() {
    return <div>
      <RadioGroup onChange={this.onChange} value={this.state.value}>
        <Radio value="a">A</Radio>
        <Radio value="b">B</Radio>
        <Radio value="c">C</Radio>
        <Radio value="d">D</Radio>
      </RadioGroup>
      <div style={{marginTop: 20}}>你选中的: {this.state.value}</div>
    </div>;
  }
});
ReactDOM.render(<App />, document.getElementById('components-radio-demo-radiogroup'));

      RadioGroup 组合

一组互斥的 Radio 配合使用。

import { Radio, Button } from 'antd';

const App = React.createClass({
  getInitialState() {
    return {
      disabled: true
    };
  },
  toggleDisabled() {
    this.setState({
      disabled: !this.state.disabled
    });
  },
  render() {
    return <div>
      <Radio defaultChecked={false} disabled={this.state.disabled}>不可用</Radio>
      <br />
      <Radio defaultChecked disabled={this.state.disabled}>不可用</Radio>
      <div style={{marginTop: 20}}>
        <Button type="primary" onClick={this.toggleDisabled}>
          Toggle disabled
        </Button>
      </div>
    </div>;
  }
});

ReactDOM.render(<App />, document.getElementById('components-radio-demo-disable'));

      不可用

Radio 不可用。

import { Radio } from 'antd';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

function onChange(e) {
  console.log('radio checked:' + e.target.value);
}

ReactDOM.render(<div>
  <div>
    <RadioGroup onChange={onChange} defaultValue="a">
      <RadioButton value="a">杭州</RadioButton>
      <RadioButton value="b" disabled>上海</RadioButton>
      <RadioButton value="c">北京</RadioButton>
      <RadioButton value="d">成都</RadioButton>
    </RadioGroup>
  </div>
  <div style={{ marginTop: 16 }}>
    <RadioGroup disabled onChange={onChange} defaultValue="a">
      <RadioButton value="a">杭州</RadioButton>
      <RadioButton value="b">上海</RadioButton>
      <RadioButton value="c">北京</RadioButton>
      <RadioButton value="d">成都</RadioButton>
    </RadioGroup>
  </div>
</div>, document.getElementById('components-radio-demo-radiobutton'));

      按钮样式

按钮样式的单选组合。

GitHub

      仓库
      样式
      开发工具

关于我们

      博客 - Ant UED

联系我们

      反馈和建议
      讨论
      报告 Bug

©2015 蚂蚁金服体验技术部出品

文档版本:


text:
require "flo/version"

module Flo
  # Your code goes here...
end


text:
namespace g2o {

  class G2O_TYPES_SLAM2D_API EdgeSE2LotsOfXY : public BaseMultiEdge<-1,VectorXD>
  {
    protected:
      unsigned int _observedPoints;

    public:
      EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
      EdgeSE2LotsOfXY();

      void setDimension(int dimension_)
      {
        _dimension = dimension_;
        _information.resize(dimension_, dimension_);
        _error.resize(dimension_, 1);
        _measurement.resize(dimension_, 1);
      }

      void setSize(int vertices)
      {
        resize(vertices);
        _observedPoints = vertices-1;
        setDimension(_observedPoints*2);
      }

      virtual void computeError();

      virtual bool read(std::istream& is);
      virtual bool write(std::ostream& os) const;

      virtual bool setMeasurementFromState();

      virtual void initialEstimate(const OptimizableGraph::VertexSet&, OptimizableGraph::Vertex*);
      virtual double initialEstimatePossible(const OptimizableGraph::VertexSet&, OptimizableGraph::Vertex*);

      virtual void linearizeOplus();
  };

} // end namespace g2o

#endif	// G2O_EDGE_SE2_LOTSOF_XY


text:
#include "xmlParser.h"
#include <strings.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>

/* Global */
static const char *debugSplit = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
std::ostream &operator<<(std::ostream &out, const STRCONV_ERROR &error);

enum STRCONV_ERROR str2int(int *i, char const *s, int base) {
    char *end;
    long  l;
    errno = 0;
    l = strtol(s, &end, base);

    if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {
        return CONV_OVERFLOW;
    }

    if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {
        return CONV_UNDERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = l;
    return CONV_SUCCESS;
}

enum STRCONV_ERROR str2uint(uint32_t *i, char const *s, int base) {
    char *end;
    unsigned long  l;
    errno = 0;
    l = strtoul(s, &end, base);

    if ((errno == ERANGE && l == ULONG_MAX) || l > UINT_MAX) {
        return CONV_OVERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = l;
    return CONV_SUCCESS;
}

enum STRCONV_ERROR str2float(float *i, char const *s) {
    float f;
    char *end = NULL;

    errno = 0;
    f = strtof(s, &end);

    if ((errno == ERANGE && f == HUGE_VAL)) {
        return CONV_OVERFLOW;
    }

    if ((errno == ERANGE && f == 0)) {
        return CONV_UNDERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = f;
    return CONV_SUCCESS;
}

enum STRCONV_ERROR str2double(double *i, char const *s) {
    char *end;
    double d;
    errno = 0;
    d = strtod(s, &end);

    if ((errno == ERANGE && d == HUGE_VAL)) {
        return CONV_OVERFLOW;
    }

    if ((errno == ERANGE && d == 0)) {
        return CONV_UNDERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = d;
    return CONV_SUCCESS;
}

enum STRCONV_ERROR str2int64(int64_t *i, char const *s, int base) {
    char *end;
    long long l;

    errno = 0;
    l = strtoll(s, &end, base);

    if ((errno == ERANGE && l == LLONG_MAX) || l > LLONG_MAX) {
        return CONV_OVERFLOW;
    }

    if ((errno == ERANGE && l == LLONG_MIN) || l < LLONG_MIN) {
        return CONV_UNDERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = l;
    return CONV_SUCCESS;
}

enum STRCONV_ERROR str2uint64(uint64_t *i, char const *s, int base) {
    char *end;
    unsigned long long l;

    errno = 0;
    l = strtoull(s, &end, base);

    if ((errno == ERANGE && l == ULLONG_MAX) || l > ULLONG_MAX) {
        return CONV_OVERFLOW;
    }

    if (*s == '\0' || *end != '\0') {
        return CONV_INCONVERTIBLE;
    }

    *i = l;
    return CONV_SUCCESS;
}

std::ostream &operator<<(std::ostream &out, const STRCONV_ERROR &error) {
    switch (error) {
        case CONV_SUCCESS:
            out << "success" << endl;
            break;

        case CONV_OVERFLOW:
            out << "overflow" << endl;
            break;

        case CONV_UNDERFLOW:
            out << "underflow" << endl;
            break;

        case CONV_INCONVERTIBLE:
            out << "inconvertible" << endl;
            break;

        default	:
            out << "unknow status" << endl;
            break;
    }

    return out;
}

/* struct parse_rule operator== mothed */
bool operator== (const xmlParseRule &lhs, const xmlParseRule &hhs) {
    return ((lhs.m_key == hhs.m_key) && \
            (lhs.m_valueType == hhs.m_valueType) && \
            (lhs.m_defValue.d64 == hhs.m_defValue.d64) && \
            (lhs.m_valuePtr.d64 == hhs.m_valuePtr.d64) && \
            (lhs.m_charValue == hhs.m_charValue) && \
            (lhs.m_charDefault == hhs.m_charDefault) && \
            (lhs.m_charValueSize == hhs.m_charValueSize));
}

/* Overloaded operator<< */
std::ostream &operator<<(std::ostream &out, const xmlParseRule &rule) {
    out << "key:\t" << rule.m_key << "\tvalue\t";

    switch (rule.m_valueType) {
        case xmlParseRule::Str:
            out << rule.m_charValue << endl;
            break;

        case xmlParseRule::F32:
            out.precision(6);
            out << *rule.m_valuePtr.f32 << endl;
            break;

        case xmlParseRule::D64:
            out.precision(12);
            out << *rule.m_valuePtr.d64 << endl;
            break;

        case xmlParseRule::I32:
            out << *rule.m_valuePtr.i32 << endl;
            break;

        case xmlParseRule::I64:
            out << *rule.m_valuePtr.i64 << endl;
            break;

        case xmlParseRule::U32:
            out << *rule.m_valuePtr.u32 << endl;
            break;

        case xmlParseRule::U64:
            out << *rule.m_valuePtr.u64 << endl;
            break;

        default:
            out << "None" << endl;
    }

    return out;
}

bool xmlParseRule::check(void) {
    /* Check key */
    if (!m_key.size()) {
        cerr << "Rule error: key is empty!" << endl;
        return false;
    }

    /* Check value type */
    if (m_valueType == None) {
        cerr << "Rule error: value type is None" << endl;
        return false;
    }

    /*	Check value target */
    if (!m_charValue && !m_valuePtr.d64) {
        cerr << "Rule error: value is invalid!" << endl;
        return false;
    }

    return true;
}

bool xmlParseRule::parse(const char *value) {
    enum STRCONV_ERROR result;

    switch (m_valueType) {
        case Str:
            snprintf(m_charValue, m_charValueSize, "%s", value);
            break;

        case I32:
            if ((result = str2int(m_valuePtr.i32, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        case U32:
            if ((result = str2uint(m_valuePtr.u32, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        case I64:
            if ((result = str2int64(m_valuePtr.i64, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        case U64:
            if ((result = str2uint64(m_valuePtr.u64, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        case F32:
            if ((result = str2float(m_valuePtr.f32, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        case D64:
            if ((result = str2double(m_valuePtr.d64, value)) != CONV_SUCCESS) {
                cerr << "Parse[" << m_key << "]\t value is error: " << result << endl;
                return false;
            }

            break;

        default:
            return false;
    }

    return true;
}

void xmlParseRule::loadDefaultValue(void) {
    switch (m_valueType) {
        case Str:
            snprintf(m_charValue, m_charValueSize, "%s", m_charDefault.c_str());
            break;

        case F32:
            *m_valuePtr.f32 = m_defValue.f32;
            break;

        case D64:
            *m_valuePtr.d64 = m_defValue.d64;
            break;

        case I32:
            *m_valuePtr.i32 = m_defValue.i32;
            break;

        case I64:
            *m_valuePtr.i64 = m_defValue.i64;
            break;

        case U32:
            *m_valuePtr.u32 = m_defValue.u32;
            break;

        case U64:
            *m_valuePtr.u64 = m_defValue.u64;
            break;

        default:
            return;
    }
}

xmlParser::xmlParser(const string &desc) {
    /* 	Set parser name */
    parserDesc = desc;

    /* 	Clear parser rules */
    attrParserRules.clear();
    valueParserRules.clear();
}

void xmlParser::addRule(const xmlParseRule &rule) {
    valueParserRules.push_back(rule);
}

void xmlParser::addAttrRule(const xmlParseRule &rule) {
    attrParserRules.push_back(rule);
}

bool xmlParser::checkRules(const XMLElement *root, const ParserRules &rules) {
    /*	Check parser rules */
    if (rules.empty()) {
        cerr << "Parser[" << parserDesc << "] parse rules linklist is empty!" << endl;
        return false;
    }

    /*	Check parser root node */
    if (!root) {
        cerr << "Parser[" << parserDesc << "] parse root node unset!" << endl;
        return false;
    }

    return true;
}

std::ostream &operator<<(std::ostream &out, const xmlParser &parser) {
    ParserRules::const_iterator rule_it;

    out << "=============================================================" << endl;
    out << "Name:\t" << parser.parserDesc << endl;

    if (parser.valueParserRules.size() != 0) {
        out << "Value parser rules num: " << parser.valueParserRules.size() << endl;

        for (rule_it = parser.valueParserRules.begin(); rule_it != parser.valueParserRules.end(); rule_it++) {
            out << *rule_it << endl;
        }
    }

    if (parser.attrParserRules.size()) {
        out << "Attribute parser rules num: " << parser.attrParserRules.size() << endl;

        for (rule_it = parser.attrParserRules.begin(); rule_it != parser.attrParserRules.end(); rule_it++) {
            out << *rule_it << endl;
        }
    }

    return out;
}

/*
**  @brief	:	Parsing xml value according rules
**  #root	:	Parsing start root element
**  #debug	:	Enable or disbale debug mode
**  #output :   Debug output stream
**  $return	:	Success return true, else false
*/
bool xmlParser::parseValue(XMLElement *root, bool debug, ostream &output) {
    XMLElement *key = NULL;
    const char *value = NULL;
    ParserRules::iterator rule;

    /* Check if parser is ready */
    if (!checkRules(root, valueParserRules)) {
        return false;
    }

    /* Parser each rule form valueParserRules */
    for (rule = valueParserRules.begin(); rule != valueParserRules.end(); rule++) {
        /*	Check rule */
        if (!rule->check())
            return false;

        /* 	Find key */
        if (!(key = root->FirstChildElement(rule->key()))) {
            rule->loadDefaultValue();
            continue;
        }

        /* 	Find key value ? */
        if (!(value = key->ToElement()->GetText())) {
            rule->loadDefaultValue();
            continue;
        }

        /* Parse rule */
        if (!rule->parse(value)) {
            return false;
        }
    }

    /* 	Debug output */
    if (debug) {
        output << debugSplit << endl << root->Value() << endl << debugSplit << endl;

        for (rule = valueParserRules.begin(); rule != valueParserRules.end(); rule++) {
            output << *rule << endl;
        }
    }

    return true;
}

/*
**  @brief	:	Parsing xml attribute according rules
**  #root	:	Parsing start root element
**  #debug	:	Enable or disbale debug mode
**  #output :   Debug output stream
**  $return	:	Success return true, else false
*/
bool xmlParser::parseAttr(XMLElement *root, bool debug, ostream &output) {
    const char *attr = NULL;
    ParserRules::iterator rule;

    /* Check parser is ready */
    if (!checkRules(root, attrParserRules)) {
        return false;
    }

    /* Parser each rule from attrParserRules */
    for (rule = attrParserRules.begin(); rule != attrParserRules.end(); rule++) {
        /* Check rule */
        if (!rule->check()) {
            return false;
        }

        /* Find attribute */
        if ((attr = root->Attribute(rule->key())) == NULL) {
            rule->loadDefaultValue();
            continue;
        }

        /* Parse attrValue */
        if (!rule->parse(attr)) {
            return false;
        }
    }

    /* Debug output */
    if (debug) {
        output << debugSplit << endl << root->Value() << endl << debugSplit << endl;

        for (rule = attrParserRules.begin(); rule != attrParserRules.end(); rule++) {
            output << *rule << endl;
        }
    }

    return true;
}


text:
package com.gentics.mesh.core.schema.field;

/**
 * Interface for tests for field migrations
 */
public interface FieldMigrationTestcases {
	/**
	 * Test removing the field
	 *
	 * @throws Exception
	 */
	void testRemove() throws Exception;

	/**
	 * Test changing the field to a binary field
	 *
	 * @throws Exception
	 */
	void testChangeToBinary() throws Exception;

	/**
	 * Test changing an empty source field to a binary field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToBinary() throws Exception;

	/**
	 * Test changing the field to a boolean field.
	 *
	 * @throws Exception
	 */
	void testChangeToBoolean() throws Exception;

	/**
	 * Test changing an empty source field to a boolean field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToBoolean() throws Exception;

	/**
	 * Test changing to a boolean list field.
	 *
	 * @throws Exception
	 */
	void testChangeToBooleanList() throws Exception;

	/**
	 * Test changing an empty field to a boolean list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToBooleanList() throws Exception;

	/**
	 * Test changing to date field.
	 *
	 * @throws Exception
	 */
	void testChangeToDate() throws Exception;

	/**
	 * Test changing an empty field to a date field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToDate() throws Exception;

	/**
	 * Test changing to date list field.
	 *
	 * @throws Exception
	 */
	void testChangeToDateList() throws Exception;

	/**
	 * Test changing an empty field to date list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToDateList() throws Exception;

	/**
	 * Test changing to a html field.
	 *
	 * @throws Exception
	 */
	void testChangeToHtml() throws Exception;

	/**
	 * Test changing an empty field to a html field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToHtml() throws Exception;

	/**
	 * Test changing to a html list field.
	 *
	 * @throws Exception
	 */
	void testChangeToHtmlList() throws Exception;

	/**
	 * Test changing an empty field to a html list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToHtmlList() throws Exception;

	/**
	 * Test changing to a micronode field.
	 *
	 * @throws Exception
	 */
	void testChangeToMicronode() throws Exception;

	/**
	 * Test changing an empty field to a micronode field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToMicronode() throws Exception;

	/**
	 * Test changing to a micronode list field.
	 *
	 * @throws Exception
	 */
	void testChangeToMicronodeList() throws Exception;

	/**
	 * Test changing an empty field to a micronode list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToMicronodeList() throws Exception;

	/**
	 * Test changing to a node field.
	 *
	 * @throws Exception
	 */
	void testChangeToNode() throws Exception;

	/**
	 * Test changing an empty field to a node field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToNode() throws Exception;

	/**
	 * Test changing to node list field.
	 *
	 * @throws Exception
	 */
	void testChangeToNodeList() throws Exception;

	/**
	 * Test changing an empty field to a node list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToNodeList() throws Exception;

	/**
	 * Test changing to a number field.
	 *
	 * @throws Exception
	 */
	void testChangeToNumber() throws Exception;

	/**
	 * Test changing an empty field to a number field.
	 *
	 * @throws Exception
	 */

	void testEmptyChangeToNumber() throws Exception;

	/**
	 * Test changing to a number list field.
	 *
	 * @throws Exception
	 */
	void testChangeToNumberList() throws Exception;

	/**
	 * Test changing an empty field to a number list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToNumberList() throws Exception;

	/**
	 * Test changing to string field.
	 *
	 * @throws Exception
	 */
	void testChangeToString() throws Exception;

	/**
	 * Test changing an empty field to string field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToString() throws Exception;

	/**
	 * Test changing to string list field.
	 *
	 * @throws Exception
	 */
	void testChangeToStringList() throws Exception;

	/**
	 * Test changing an empty field to string list field.
	 *
	 * @throws Exception
	 */
	void testEmptyChangeToStringList() throws Exception;

}


text:
tests=$(for file in $(find . -iname "*_test.go" | grep -v "./vendor" | sed "s/\.//"); do test=$(dirname $file | sed "s/\.//"); echo "github.com/kubernetes-incubator/cluster-capacity$test"; done)
go test $tests


text:
require 'math_captcha/captcha'
require 'math_captcha/has_captcha'


text:
/**
 * Stores are responsible for storing a specific domain of application state.
 * They subscribe to updates from Actions through the Dispatcher, emitting
 * "change" events whenever their state changes.
 *
 * Two kinds of change events are fired:
 * - `change`: Indicates any value has changed on this Store. The Store is the
 *    only argument provided.
 * - `change:key` Indicates `key` has changed on this Store. The new value of
 *    `key` is the only argument provided.
 */
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

/**
 * Creates a new Store. If provided, `properties` is expected to be an Object
 * of property names to their initial values. Additionally, `dispatcher` may
 * be provided to associate this Store with a specific Dispatcher, granting use
 * of the `handle` method.
 */
function Store(properties, dispatcher) {
  if (!(this instanceof Store)) {
    return new Store(properties, dispatcher);
  }

  EventEmitter.call(this);

  this.dispatcher = dispatcher;

  this._db = {};
  this._init(properties);
}
util.inherits(Store, EventEmitter);
Store.createStore = Store;

/**
 * Defines a new property named `name` on the Store. If provided, `value` sets
 * the initial value of the property. No `"change"` event is fired for this
 * initial value.
 */
Store.prototype.define = function define(name, value) {
  if (!this.has(name)) {
    this._defineProperty(name, value);
  } else {
    this[name] = value;
  }

  return this;
};

/**
 * Returns true if the property has been defined on this Store, false otherwise.
 */
Store.prototype.has = function has(name) {
  return this.hasOwnProperty(name);
};

/**
 * If `dispatcher` has been set (presumably by the constructor argument), this
 * registers `fn` as a `name` event handler on the Dispatcher. This makes
 * creating Stores extremely expressive, as multiple `define` and `handle`
 * calls can be chained to completely define the Store in one large statement.
 *
 * When `fn` is finally called, `this` will be the Store handling the event.
 *
 * If `dispatcher` has not been set, this method will throw a ReferenceError.
 */
Store.prototype.handle = function handle(name, fn) {
  if (!this.dispatcher) {
    throw new ReferenceError('Store has no dispatcher defined.');
  }

  assert(name, 'Missing name');
  assert(typeof fn === 'function', 'Invalid function');

  this.dispatcher.register(name, fn.bind(this));

  return this;
};

/**
 * Returns a Plain Old JavaScript Object with the same keys and values as this
 * Store. This is a shallow copy, but changes to this Object should be
 * discouraged.
 */
Store.prototype.toObject = function toObject() {
  var obj = {};
  util._extend(obj, this._db);
  return obj;
};

/**
 * Returns a JSON representation of the Store.
 */
Store.prototype.toJSON = function toJSON() {
  return this.toObject();
};

/**
 * Re-populates the Store from a previously-cached version.
 */
Store.prototype.fromObject = function fromObject(obj) {
  var self = this;

  if (!obj || typeof obj === 'undefined') {
    return self;
  }

  assert(typeof obj === 'object', 'Invalid object');

  Object.keys(obj).forEach(function (key) {
    self.define(key, obj[key]);
  });

  return self;
};

/**
 * Internal helper to add all `properties` by key and initial value.
 */
Store.prototype._init = function _init(properties) {
  var self = this;

  if (properties && typeof properties === 'object') {
    Object.keys(properties).forEach(function (key) {
      self.define(key, properties[key]);
    });
  }

  return self;
};

/**
 * Internal helper to define the underlying property.
 */
Store.prototype._defineProperty = function _defineProperty(name, initialValue) {
  var self = this;

  Object.defineProperty(self, name, {
    get: function () {
      return self._db[name];
    },
    set: function (value) {
      self._db[name] = value;

      process.nextTick(function () {
        self.emit('change', self);
        self.emit('change:' + name, value);
      });

      return value;
    }
  });

  // Synchronously fire initial change events.
  self._db[name] = initialValue;
  self.emit('change', self);
  self.emit('change:' + name, initialValue);

  return self;
};

/*!
 * Export `Store`.
 */
module.exports = Store;


text:
class Nagira < Sinatra::Base

  ##
  # @method get_status_servicegroup
  #
  # Endpoint:
  # -  GET /_status/_servicegroup/:servicegroup
  #
  # Supported extensions: _state, _list
  #

  get "/_status/_servicegroup/:servicegroup" do |group_name|
    ServicegroupController.new(group_name).send(@output)
  end

end


text:
package main.java.helloworld.http;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import main.java.helloworld.http.impl.MainHandler;
import main.java.helloworld.lang.Lang;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;

class HttpProvider {

    private static Logger Log = LogManager.getLogger(HttpProvider.class);

    private int _port;
    private int _maxConn;

    private HttpServer httpServer;

    HttpProvider(int port, int maxConn) {
        _port = port;
        _maxConn = maxConn;
    }

    void startService() {
        Log.debug(Lang.get("HTTP_SRV_INFO", _port, _maxConn));

        try {
            HttpServerProvider provider = HttpServerProvider.provider();
            this.httpServer = provider.createHttpServer(new InetSocketAddress(_port), _maxConn);
            this.httpServer.createContext("/", new MainHandler());
            this.httpServer.setExecutor(null);
            this.httpServer.start();
        } catch (Exception ex) {
            Log.error(Lang.get("GENERIC_ERROR_MSG", "Perhaps you are using that port?"));
            System.exit(-1);
        }
    }

    void stopHttpServer() {
        if (this.httpServer != null) {
            this.httpServer.stop(0);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    tools:ignore="ResourceName">
    <translate
        android:toYDelta="100%p"
        android:duration="400"
        />
</set>


text:
extern "C"{
#endif

// Public key blob binary format.
typedef struct {
    unsigned int SigAlgID;       // (ALG_ID) signature algorithm used to create the signature
    unsigned int HashAlgID;      // (ALG_ID) hash algorithm used to create the signature
    ULONG        cbPublicKey;    // length of the key in bytes
    BYTE         PublicKey[1];   // variable length byte array containing the key value in format output by CryptoAPI
} PublicKeyBlob;

// Location in the registry (under HKLM) that strong name configuration info is
// stored.
#define SN_CONFIG_KEY               "Software\\Microsoft\\StrongName"
#define SN_CONFIG_CSP               "CSP"                   // REG_SZ
#define SN_CONFIG_MACHINE_KEYSET    "MachineKeyset"         // REG_DWORD
#define SN_CONFIG_KEYSPEC           "KeySpec"               // REG_DWORD
#define SN_CONFIG_HASH_ALG          "HashAlgorithm"         // REG_DWORD
#define SN_CONFIG_SIGN_ALG          "SignAlgorithm"         // REG_DWORD
#define SN_CONFIG_VERIFICATION      "Verification"          // Registry subkey
#define SN_CONFIG_USERLIST          "UserList"              // REG_MULTI_SZ
#define SN_CONFIG_CACHE_VERIFY      "CacheVerify"           // REG_DWORD

#define SN_CONFIG_KEY_W             L"Software\\Microsoft\\StrongName"
#define SN_CONFIG_CSP_W             L"CSP"                  // REG_SZ
#define SN_CONFIG_PROV_TYPE_W       L"ProvType"             // REG_DWORD
#define SN_CONFIG_MACHINE_KEYSET_W  L"MachineKeyset"        // REG_DWORD
#define SN_CONFIG_KEYSPEC_W         L"KeySpec"              // REG_DWORD
#define SN_CONFIG_HASH_ALG_W        L"HashAlgorithm"        // REG_DWORD
#define SN_CONFIG_SIGN_ALG_W        L"SignAlgorithm"        // REG_DWORD
#define SN_CONFIG_VERIFICATION_W    L"Verification"         // Registry subkey
#define SN_CONFIG_USERLIST_W        L"UserList"             // REG_MULTI_SZ
#define SN_CONFIG_TESTPUBLICKEY_W   L"TestPublicKey"        // REG_SZ
#define SN_CONFIG_CACHE_VERIFY_W    L"CacheVerify"          // REG_DWORD

// VM related registry locations (Note, these values are under HKLM\Software\Microsoft\.NETFramework, rather
// than SN_CONFIG_KEY
#define SN_CONFIG_BYPASS_POLICY     "AllowStrongNameBypass" // REG_DWORD
#define SN_CONFIG_BYPASS_POLICY_W   L"AllowStrongNameBypass" // REG_DWORD

#if defined(_MSC_VER) && !defined(USE_DEPRECATED_CLR_API_WITHOUT_WARNING)
#define DEPRECATED_CLR_API_MESG "This API has been deprecated. Refer to http://go.microsoft.com/fwlink/?LinkId=143720 for more details."
#define DECLARE_DEPRECATED __declspec(deprecated(DEPRECATED_CLR_API_MESG))
#else // _MSC_VER && !USE_DEPRECATED_CLR_API_WITHOUT_WARNING
#define DECLARE_DEPRECATED
#endif // _MSC_VER && !USE_DEPRECATED_CLR_API_WITHOUT_WARNING

#define SNAPI DECLARE_DEPRECATED BOOLEAN __stdcall
#define SNAPI_(_type) DECLARE_DEPRECATED _type __stdcall

// Return last error.
SNAPI_(DWORD) StrongNameErrorInfo(VOID);

// Free buffer allocated by routines below.
SNAPI_(VOID) StrongNameFreeBuffer(BYTE *pbMemory);  // [in] address of memory to free

// Generate a new key pair for strong name use.
SNAPI StrongNameKeyGen(LPCWSTR  wszKeyContainer,    // [in] desired key container name
                       DWORD    dwFlags,            // [in] flags (see below)
                       BYTE   **ppbKeyBlob,         // [out] public/private key blob
                       ULONG   *pcbKeyBlob);

// Generate a new key pair with the specified key size for strong name use.
SNAPI StrongNameKeyGenEx(LPCWSTR  wszKeyContainer,    // [in] desired key container name, must be a non-empty string
                         DWORD    dwFlags,            // [in] flags (see below)
                         DWORD    dwKeySize,          // [in] desired key size.
                         BYTE   **ppbKeyBlob,         // [out] public/private key blob
                         ULONG   *pcbKeyBlob);

// Flags for StrongNameKeyGen.
#define SN_LEAVE_KEY    0x00000001                  // Leave key pair registered with CSP

// Import key pair into a key container.
SNAPI StrongNameKeyInstall(LPCWSTR  wszKeyContainer,// [in] desired key container name, must be a non-empty string
                           BYTE    *pbKeyBlob,      // [in] public/private key pair blob
                           ULONG    cbKeyBlob);

// Delete a key pair.
SNAPI StrongNameKeyDelete(LPCWSTR wszKeyContainer); // [in] desired key container name

// Retrieve the public portion of a key pair.
SNAPI StrongNameGetPublicKey (LPCWSTR   wszKeyContainer,    // [in] desired key container name
                              BYTE     *pbKeyBlob,          // [in] public/private key blob (optional)
                              ULONG     cbKeyBlob,
                              BYTE    **ppbPublicKeyBlob,   // [out] public key blob
                              ULONG    *pcbPublicKeyBlob);

// Retrieve the public portion of a key pair.
SNAPI StrongNameGetPublicKeyEx (LPCWSTR   wszKeyContainer,    // [in] desired key container name
                                BYTE     *pbKeyBlob,          // [in] public/private key blob (optional)
                                ULONG     cbKeyBlob,
                                BYTE    **ppbPublicKeyBlob,   // [out] public key blob
                                ULONG    *pcbPublicKeyBlob,
                                ULONG     uHashAlgId,
                                ULONG     uReserved);          // reserved for future use

// Hash and sign a manifest.
SNAPI StrongNameSignatureGeneration(LPCWSTR     wszFilePath,        // [in] valid path to the PE file for the assembly
                                    LPCWSTR     wszKeyContainer,    // [in] desired key container name
                                    BYTE       *pbKeyBlob,          // [in] public/private key blob (optional)
                                    ULONG       cbKeyBlob,
                                    BYTE      **ppbSignatureBlob,   // [out] signature blob
                                    ULONG      *pcbSignatureBlob);

SNAPI StrongNameSignatureGenerationEx(LPCWSTR     wszFilePath,        // [in] valid path to the PE file for the assembly
                                      LPCWSTR     wszKeyContainer,    // [in] desired key container name
                                      BYTE       *pbKeyBlob,          // [in] public/private key blob (optional)
                                      ULONG       cbKeyBlob,
                                      BYTE      **ppbSignatureBlob,   // [out] signature blob
                                      ULONG      *pcbSignatureBlob,
                                      DWORD       dwFlags);           // [in] modifer flags; see below

#define SN_SIGN_ALL_FILES   0x00000001      // Rehash all linked modules as well as resigning the manifest
#define SN_TEST_SIGN        0x00000002      // Test sign the assembly
#define SN_ECMA_SIGN        0x00000004      // Sign the assembly treating the input key as the real ECMA key

// Digest signing support

// Generate the digest of an input assembly, which can be signed with StrongNameDigestSign
SNAPI StrongNameDigestGenerate(_In_z_ LPCWSTR                                       wszFilePath,        // [in] valid path to the PE file for the assembly
                               _Outptr_result_bytebuffer_(*pcbDigestBlob) BYTE**    ppbDigestBlob,      // [out] digest of the assembly, free with StrongNameFreeBuffer
                               _Out_  ULONG*                                        pcbDigestBlob,      // [out] number of bytes in the assembly digest
                               DWORD                                                dwFlags);           // [in] modifier flags (see StrongNameSignatureGenerationEx)

// Sign an the digest of an assembly calculated by StrongNameDigestGenerate
SNAPI StrongNameDigestSign(_In_opt_z_ LPCWSTR                                   wszKeyContainer,        // [in] desired key container name (optional)
                           _In_reads_bytes_opt_(cbKeyBlob) BYTE*                pbKeyBlob,              // [in] public/private key blob (optional)
                           ULONG                                                cbKeyBlob,
                           _In_reads_bytes_(cbDigestBlob) BYTE*                 pbDigestBlob,           // [in] digest blob, from StrongNameDigestGenerate
                           ULONG                                                cbDigestBlob,
                           DWORD                                                hashAlgId,              // [in] algorithm id of the hash algorithm used with pbDigestBlob
                           _Outptr_result_bytebuffer_(*pcbSignatureBlob) BYTE** ppbSignatureBlob,       // [out] signature blob, freed with StrongNameFreeBuffer
                           _Out_ ULONG*                                         pcbSignatureBlob,
                           DWORD                                                dwFlags);               // [in] modifier flags (see StrongNameSignatureGenerationEx)

// Embed a digest signature generated with StrongNameDigestSign into an assembly
SNAPI StrongNameDigestEmbed(_In_z_ LPCWSTR                          wszFilePath,                        // [in] valid path to the PE file for the assembly to update
                            _In_reads_bytes_(cbSignatureBlob) BYTE* pbSignatureBlob,                    // [in] signature blob for the assembly
                            ULONG                                   cbSignatureBlob);

// Create a strong name token from an assembly file.
SNAPI StrongNameTokenFromAssembly(LPCWSTR   wszFilePath,            // [in] valid path to the PE file for the assembly
                                  BYTE    **ppbStrongNameToken,     // [out] strong name token
                                  ULONG    *pcbStrongNameToken);

// Create a strong name token from an assembly file and additionally return the full public key.
SNAPI StrongNameTokenFromAssemblyEx(LPCWSTR   wszFilePath,            // [in] valid path to the PE file for the assembly
                                    BYTE    **ppbStrongNameToken,     // [out] strong name token
                                    ULONG    *pcbStrongNameToken,
                                    BYTE    **ppbPublicKeyBlob,       // [out] public key blob
                                    ULONG    *pcbPublicKeyBlob);

// Create a strong name token from a public key blob.
SNAPI StrongNameTokenFromPublicKey(BYTE    *pbPublicKeyBlob,        // [in] public key blob
                                   ULONG    cbPublicKeyBlob,
                                   BYTE   **ppbStrongNameToken,     // [out] strong name token
                                   ULONG   *pcbStrongNameToken);

// Verify a strong name/manifest against a public key blob.
SNAPI StrongNameSignatureVerification(LPCWSTR wszFilePath,      // [in] valid path to the PE file for the assembly
                                      DWORD   dwInFlags,        // [in] flags modifying behaviour (see below)
                                      DWORD  *pdwOutFlags);     // [out] additional output info (see below)

// Verify a strong name/manifest against a public key blob.
SNAPI StrongNameSignatureVerificationEx(LPCWSTR     wszFilePath,        // [in] valid path to the PE file for the assembly
                                        BOOLEAN     fForceVerification, // [in] verify even if settings in the registry disable it
                                        BOOLEAN    *pfWasVerified);     // [out] set to false if verify succeeded due to registry settings

// Verify a strong name/manifest against a public key blob.
SNAPI StrongNameSignatureVerificationEx2(LPCWSTR    wszFilePath,         // [in] valid path to the PE file for the assembly
                                         BOOLEAN    fForceVerification,  // [in] verify even if settings in the registry disable it
                                         BYTE      *pbEcmaPublicKey,     // [in] mapping from the ECMA public key to the real key used for verification
                                         DWORD      cbEcmaPublicKey,     // [in] length of the real ECMA public key
                                         BOOLEAN   *pfWasVerified);      // [out] set to false if verify succeeded due to registry settings

// Verify a strong name/manifest against a public key blob when the assembly is
// already memory mapped.
SNAPI StrongNameSignatureVerificationFromImage(BYTE     *pbBase,             // [in] base address of mapped manifest file
                                               DWORD     dwLength,           // [in] length of mapped image in bytes
                                               DWORD     dwInFlags,          // [in] flags modifying behaviour (see below)
                                               DWORD    *pdwOutFlags);       // [out] additional output info (see below)

// Flags for use with the verify routines.
#define SN_INFLAG_FORCE_VER      0x00000001     // verify even if settings in the registry disable it
#define SN_INFLAG_INSTALL        0x00000002     // verification is the first (on entry to the cache)
#define SN_INFLAG_ADMIN_ACCESS   0x00000004     // cache protects assembly from all but admin access
#define SN_INFLAG_USER_ACCESS    0x00000008     // cache protects user's assembly from other users
#define SN_INFLAG_ALL_ACCESS     0x00000010     // cache provides no access restriction guarantees

#define SN_INFLAG_RUNTIME        0x80000000     // internal debugging use only

#define SN_OUTFLAG_WAS_VERIFIED  0x00000001     // set to false if verify succeeded due to registry settings
#define SN_OUTFLAG_MICROSOFT_SIGNATURE 0x00000002 // set if the public key corresponds to SN_THE_KEY

// Verify that two assemblies differ only by signature blob.
SNAPI StrongNameCompareAssemblies(LPCWSTR   wszAssembly1,           // [in] file name of first assembly
                                  LPCWSTR   wszAssembly2,           // [in] file name of second assembly
                                  DWORD    *pdwResult);             // [out] result of comparison (see codes below)

#define SN_CMP_DIFFERENT    0   // Assemblies contain different data
#define SN_CMP_IDENTICAL    1   // Assemblies are exactly the same, even signatures
#define SN_CMP_SIGONLY      2   // Assemblies differ only by signature (and checksum etc.)

// Compute the size of buffer needed to hold a hash for a given hash algorithm.
SNAPI StrongNameHashSize(ULONG  ulHashAlg,  // [in] hash algorithm
                         DWORD *pcbSize);   // [out] size of the hash in bytes

// Compute the size that needs to be allocated for a signature in an assembly.
SNAPI StrongNameSignatureSize(BYTE    *pbPublicKeyBlob,    // [in] public key blob
                              ULONG    cbPublicKeyBlob,
                              DWORD   *pcbSize);           // [out] size of the signature in bytes

SNAPI_(DWORD) GetHashFromAssemblyFile(LPCSTR szFilePath, // [IN] location of file to be hashed
                                      unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                                      BYTE   *pbHash,    // [OUT] hash buffer
                                      DWORD  cchHash,    // [IN]  max size of buffer
                                      DWORD  *pchHash);  // [OUT] length of hash byte array

SNAPI_(DWORD) GetHashFromAssemblyFileW(LPCWSTR wszFilePath, // [IN] location of file to be hashed
                                       unsigned int *piHashAlg, // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                                       BYTE   *pbHash,    // [OUT] hash buffer
                                       DWORD  cchHash,    // [IN]  max size of buffer
                                       DWORD  *pchHash);  // [OUT] length of hash byte array

SNAPI_(DWORD) GetHashFromFile(LPCSTR szFilePath, // [IN] location of file to be hashed
                              unsigned int *piHashAlg,   // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                              BYTE   *pbHash,    // [OUT] hash buffer
                              DWORD  cchHash,    // [IN]  max size of buffer
                              DWORD  *pchHash);  // [OUT] length of hash byte array

SNAPI_(DWORD) GetHashFromFileW(LPCWSTR wszFilePath, // [IN] location of file to be hashed
                               unsigned int *piHashAlg,   // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                               BYTE   *pbHash,    // [OUT] hash buffer
                               DWORD  cchHash,    // [IN]  max size of buffer
                               DWORD  *pchHash);  // [OUT] length of hash byte array

SNAPI_(DWORD) GetHashFromHandle(HANDLE hFile,      // [IN] handle of file to be hashed
                                unsigned int *piHashAlg,   // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                                BYTE   *pbHash,    // [OUT] hash buffer
                                DWORD  cchHash,    // [IN]  max size of buffer
                                DWORD  *pchHash);  // [OUT] length of hash byte array

SNAPI_(DWORD) GetHashFromBlob(BYTE   *pbBlob,       // [IN] pointer to memory block to hash
                              DWORD  cchBlob,       // [IN] length of blob
                              unsigned int *piHashAlg,  // [IN/OUT] constant specifying the hash algorithm (set to 0 if you want the default)
                              BYTE   *pbHash,       // [OUT] hash buffer
                              DWORD  cchHash,       // [IN]  max size of buffer
                              DWORD  *pchHash);     // [OUT] length of hash byte array

SNAPI StrongNameGetBlob(LPCWSTR            wszFilePath,         // [in] valid path to the PE file for the assembly
                        BYTE               *pbBlob,             // [in] buffer to fill with blob
                        DWORD              *pcbBlob);           // [in/out] size of buffer/number of bytes put into buffer

SNAPI StrongNameGetBlobFromImage(BYTE      *pbBase,             // [in] base address of mapped manifest file
                                 DWORD     dwLength,            // [in] length of mapped image in bytes
                                 BYTE      *pbBlob,             // [in] buffer to fill with blob
                                 DWORD     *pcbBlob);           // [in/out] size of buffer/number of bytes put into buffer

#undef DECLARE_DEPRECATED
#undef DEPRECATED_CLR_API_MESG
#undef SNAPI
#undef SNAPI_
#define SNAPI BOOLEAN __stdcall
#define SNAPI_(_type) _type __stdcall

#ifdef __cplusplus
}
#endif

#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)

#endif