text:
package org.globus.ftp.test;

import org.globus.ftp.Session;
import org.globus.ftp.FTPClient;
import org.globus.ftp.DataSource;
import org.globus.ftp.DataSink;
import org.globus.ftp.DataSinkStream;
import org.globus.ftp.DataSourceStream;
import org.globus.ftp.exception.ServerException;

import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;

/**
   Test FTPClient.get() and put()
 **/
public class FTPClient2PartyTest extends TestCase {

    private static Log logger =
	LogFactory.getLog(FTPClient2PartyTest.class.getName());

    protected FTPClient src = null;
    // note that this can be always null, because
    // user is not obliged to provide FTP destination server
    protected FTPClient dest = null;

    public FTPClient2PartyTest(String name) {
	super(name);
    }

    public static void main (String[] args) throws Exception{
	junit.textui.TestRunner.run(suite());
    }

    public static Test suite ( ) {
	return new TestSuite(FTPClient2PartyTest.class);
    }

    private boolean skipTest(String property, String msg) {
	if (property == null) {
	    if (TestEnv.failUnset) {
		fail(msg);
	    }
	    logger.info("Test skipped: " + msg);
	    return true;
	} else {
	    return false;
	}
    }

    public void testGet() throws Exception {
	logger.info("get");

	testGet(TestEnv.serverFHost,
		TestEnv.serverFPort,
		TestEnv.serverFUser,
		TestEnv.serverFPassword,
		TestEnv.serverFDir,
		TestEnv.serverFFile,
		TestEnv.localDestDir);
    }

    public void testPut() throws Exception {
	logger.info("put");

	if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) {
	    return;
	}

	testPut(TestEnv.serverGHost,
		TestEnv.serverGPort,
		TestEnv.serverGUser,
		TestEnv.serverGPassword,
		TestEnv.serverGDir,
		TestEnv.localSrcDir,
		TestEnv.localSrcFile);
    }

    /**
	Try transferring file to and from bad port on existing server.
	IOException should be thrown.
    **/
    public void testGetNoSuchPort() throws Exception{

	if (TestEnv.serverANoSuchPort == TestEnv.UNDEFINED) {
	    logger.info("Omitting the test: test3Party_noSuchPort");
	    logger.info("because some necessary properties are not defined.");
	    return;
	}
	logger.info("get from non existent port");
	boolean caughtOK = false;
	try {

	    testGet(TestEnv.serverFHost,
		    TestEnv.serverFNoSuchPort,
		    TestEnv.serverFUser,
		    TestEnv.serverFPassword,
		    TestEnv.serverFDir,
		    TestEnv.serverFFile,
		    TestEnv.localDestDir);

	} catch (Exception e) {
	    if (e instanceof IOException) {
		logger.debug(e.toString());
		caughtOK = true;
		logger.debug("Test passed: IOException properly thrown.");
	    } else {
		logger.error("", e);
		fail(e.toString());
	    }
	} finally {
	    if (!caughtOK) {
		fail("Attempted to contact non existent server, but the expected exception has not been thrown.");
	    }
	}

	logger.info("put to non existent port");
	caughtOK = false;
	try {

	    testPut(TestEnv.serverAHost,
		    TestEnv.serverANoSuchPort,
		    TestEnv.serverGUser,
		    TestEnv.serverGPassword,
		    TestEnv.serverGDir,
		    TestEnv.localSrcDir,
		    TestEnv.localSrcFile);

	} catch (Exception e) {
	    if (e instanceof IOException) {
		logger.debug(e.toString());
		caughtOK = true;
		logger.debug("Test passed: IOException properly thrown.");
	    } else {
		logger.error("", e);
		fail(e.toString());
	    }
	} finally {
	    if (!caughtOK) {
		fail("Attempted to contact non existent server, but the expected exception has not been thrown.");
	    }
	}
    }

    /**
	Try transferring file to and from non existent server.
	IOException should be thrown.
    **/
    public void testGetNoSuchServer() throws Exception{
	logger.info("get from non existent server");
	boolean caughtOK = false;
	try {

	    testGet(TestEnv.noSuchServer,
		    TestEnv.serverFPort,
		    TestEnv.serverFUser,
		    TestEnv.serverFPassword,
		    TestEnv.serverFDir,
		    TestEnv.serverFFile,
		    TestEnv.localDestDir);

	} catch (Exception e) {
	    if (e instanceof IOException) {
		logger.debug(e.toString());
		caughtOK = true;
		logger.debug("Test passed: IOException properly thrown.");
	    } else {
		logger.error("", e);
		fail(e.toString());
	    }
	} finally {
	    if (!caughtOK) {
		fail("Attempted to contact non existent server, but the expected exception has not been thrown.");
	    }
	}

	logger.info("put to non existent server");
	caughtOK = false;
	try {

	    testPut(TestEnv.noSuchServer,
		    TestEnv.serverFPort,
		    TestEnv.serverFUser,
		    TestEnv.serverFPassword,
		    TestEnv.serverFDir,
		    TestEnv.serverFFile,
		    TestEnv.localDestDir);

	} catch (Exception e) {
	    if (e instanceof IOException) {
		logger.debug(e.toString());
		caughtOK = true;
		logger.debug("Test passed: IOException properly thrown.");
	    } else {
		logger.error("", e);
		fail(e.toString());
	    }
	} finally {
	    if (!caughtOK) {
		fail("Attempted to contact non existent server, but the expected exception has not been thrown.");
	    }
	}
    }

    /**
	try transferring non existent file;
	ServerException should be thrown
    **/

    public void testGetNoSuchSrcFile() throws Exception{
	logger.info("get with bad src file");

	try {
	    testGet(TestEnv.serverFHost,
		    TestEnv.serverFPort,
		    TestEnv.serverFUser,
		    TestEnv.serverFPassword,
		    TestEnv.serverFDir,
		    TestEnv.serverFNoSuchFile,
		    TestEnv.localDestDir);
	} catch (ServerException e) {
	    logger.debug("Test passed: ServerException properly thrown.",
			 e);
	}
    }

    /** try transferring file to non existent directory;
	ServerException should be thrown.
    **/

    public void testPutNoSuchDestDir() throws Exception{
	logger.info("put with bad dest dir");

	if (skipTest(TestEnv.serverGHost, "serverGHost undefined")) {
	    return;
	}

	try {
	    testPut(TestEnv.serverGHost,
		    TestEnv.serverGPort,
		    TestEnv.serverGUser,
		    TestEnv.serverGPassword,
		    TestEnv.serverGNoSuchDir,
		    TestEnv.localSrcDir,
		    TestEnv.localSrcFile);
	} catch (ServerException e) {
	    logger.debug("Test passed: ServerException properly thrown.", e);
	}
    }

    private void testGet(String host,
			 int port,
			 String user,
			 String password,
			 String remoteDir,
			 String remoteFile,
			 String localDir)
	throws Exception{

	logger.info("active, image, stream");
	testGet(host, port, user, password, remoteDir  + "/" + remoteFile,
		localDir,
		Session.SERVER_ACTIVE,
		Session.TYPE_IMAGE,
		Session.MODE_STREAM);
	logger.info("active, ascii, stream");
	testGet(host, port, user, password, remoteDir + "/" + remoteFile,
		localDir,
		Session.SERVER_ACTIVE,
		Session.TYPE_ASCII,
		Session.MODE_STREAM);
	logger.info("pasive, image, stream");
	testGet(host, port, user, password, remoteDir  + "/" + remoteFile,
		localDir,
		Session.SERVER_PASSIVE,
		Session.TYPE_IMAGE,
		Session.MODE_STREAM);
	logger.info("pasive, ascii, stream");
	testGet(host, port, user, password, remoteDir + "/" + remoteFile,
		localDir,
		Session.SERVER_PASSIVE,
		Session.TYPE_ASCII,
		Session.MODE_STREAM);
    }

    private void testGet(String host,
			 int port,
			 String user,
			 String password,
			 String fullRemoteFile,
			 String localDestDir,

			 int localServerMode,
			 int transferType,
			 int transferMode)
	throws Exception {
	String smode = (localServerMode == Session.SERVER_PASSIVE)?
	    "pasv" : "actv";
	String tmode = (transferMode == Session.MODE_STREAM) ?
	    "stream" : "eblok";
	String ttype = (transferType == Session.TYPE_ASCII) ?
	    "ascii" : "image";
 	String fullLocalFile =
	    localDestDir + "/test.get."
	    + smode + "." + tmode +"." + ttype +"."
	    + System.currentTimeMillis();
	logger.debug("will write to: " + fullLocalFile);
	FTPClient client = new FTPClient(host, port);
	testGet_setParams(client,
			  user,
			  password,
			  localServerMode,
			  transferType,
			  transferMode);
	DataSink sink = new DataSinkStream(new FileOutputStream(fullLocalFile));
	client.get(fullRemoteFile,
		   sink,
		   null);
	client.close();
    }

    protected void testGet_setParams(FTPClient client,
				      String user,
				      String password,
				   int localServerMode,
				   int transferType,
				   int transferMode)
	throws Exception{
    	//System.out.println("USER = "+ user + "PAssword="+ password);
    	client.authorize(user, password);
	// secure server: client.setProtectionBufferSize(16384);
	client.setType(transferType);
	client.setMode(transferMode);
	if (localServerMode == Session.SERVER_ACTIVE) {
	    client.setPassive();
	    client.setLocalActive();
	} else {
	    client.setLocalPassive();
	    client.setActive();
	}
    }

    private void testPut(String host,
			 int port,
			 String user,
			 String password,
			 String remoteDir,
			 String localDir,
			 String localFile)
	throws Exception{

	logger.info("active, image, stream");
	testPut(host, port, user, password, remoteDir, localFile,
		localDir,
		Session.SERVER_ACTIVE,
		Session.TYPE_IMAGE,
		Session.MODE_STREAM);
	logger.info("active, ascii, stream");
	testPut(host, port, user, password, remoteDir, localFile,
		localDir,
		Session.SERVER_ACTIVE,
		Session.TYPE_ASCII,
		Session.MODE_STREAM);
	logger.info("pasive, image, stream");
	testPut(host, port, user, password, remoteDir, localFile,
		localDir,
		Session.SERVER_PASSIVE,
		Session.TYPE_IMAGE,
		Session.MODE_STREAM);
	logger.info("pasive, ascii, stream");
	testPut(host, port, user, password, remoteDir, localFile,
		localDir,
		Session.SERVER_PASSIVE,
		Session.TYPE_ASCII,
		Session.MODE_STREAM);
    }

    private void testPut(String host,
			 int port,
			 String user,
			 String password,
			 String remoteDestDir,
			 String localFile,
			 String localDir,

			 int localServerMode,
			 int transferType,
			 int transferMode)
	throws Exception {
	FTPClient client = new FTPClient(host, port);
	testPut_setParams(client,
			  user,
			  password,
			  localServerMode,
			  transferType,
			  transferMode);
	String fullLocalFile = localDir + "/" + localFile;
	String fullRemoteFile = remoteDestDir + "/" + localFile;
	DataSource source = new DataSourceStream(new FileInputStream(fullLocalFile));
	client.put(fullRemoteFile,
		   source,
		   null);
	client.close();
    }

    protected void testPut_setParams(FTPClient client,
				   String user,
				   String password,
				   int localServerMode,
				   int transferType,
				   int transferMode)
	throws Exception{
	client.authorize(user, password);
	// secure server: client.setProtectionBufferSize(16384);
	client.setType(transferType);
	client.setMode(transferMode);
	if (localServerMode == Session.SERVER_ACTIVE) {
	    client.setPassive();
	    client.setLocalActive();
	} else {
	    client.setLocalPassive();
	    client.setActive();
	}
    }

}


text:
# openapi-validation-tools [oav]

[![Build Status](https://dev.azure.com/azure-public/adx/_apis/build/status/public.Azure.oav)](https://dev.azure.com/azure-public/adx/_build/latest?definitionId=3)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Tools for validating OpenAPI (Swagger) files.

## Requirements

- **node.js version > 10.x**

You can install the latest stable release of node.js from [here](https://nodejs.org/en/download/). For a machine with a linux flavored OS, please follow the node.js installation instructions over [here](https://nodejs.org/en/download/package-manager/)

### How to install the tool

```bash
npm install -g oav
```

#### Command usage:

```bash
bash-3.2$ oav -h
Commands:
  extract-xmsexamples <spec-path>           Extracts the x-ms-examples for a
  <recordings>                              given swagger from the .NET session
                                            recordings and saves them in a file.
  generate-uml <spec-path>                  Generates a class diagram of the
                                            model definitions in the given
                                            swagger spec.
  generate-wireformat <spec-path>           Transforms the x-ms-examples for a
                                            given operation into raw
                                            request/response format and saves
                                            them in a markdown file.
  resolve-spec <spec-path>                  Resolves the swagger spec based on
                                            the selected options like allOfs,
                                            relativePaths, examples etc.
  validate-example <spec-path>              Performs validation of x-ms-examples
                                            and examples present in the spec.
  validate-spec <spec-path>                 Performs semantic validation of the
                                            spec.

Options:
  --version          Show version number                               [boolean]
  -l, --logLevel     Set the logging level for console.
  [choices: "off", "json", "error", "warn", "info", "verbose", "debug", "silly"]
                                                               [default: "warn"]
  -f, --logFilepath  Set the log file path. It must be an absolute filepath. By
                     default the logs will stored in a timestamp based log file
                     at "C:\Users\amzavery\oav_output".
  -h, --help         Show help                                         [boolean]

bash-3.2$
```

### What does the tool do? What issues does the tool catch?

Model validation checks whether definitions for request parameters and responses, match an expected input/output payload of the service.

Examples of issues:

- required properties not sent in requests or responses;
- defined types not matching the value provided in the payload;
- constraints on properties not met; enumeration values that don't match the value used by the service.

References: https://github.com/Azure/azure-rest-api-specs/issues/778 , https://github.com/Azure/azure-rest-api-specs/issues/755 , https://github.com/Azure/azure-rest-api-specs/issues/773

Model validation _requires_ example payloads (request/response) of the service, so the data can be matched with the defined models. See [x-ms-examples extension](https://github.com/Azure/azure-rest-api-specs/issues/648) on how to specify the examples/payloads. Swagger "examples" is also supported and data included there is validated as well. To get the most benefit from this tool, make sure to have the simplest and most complex examples possible as part of x-ms-examples.

- Please take a look at the redis-cache swagger spec as an example for providing "x-ms-examples" over [here](https://github.com/Azure/azure-rest-api-specs/blob/master/arm-redis/2016-04-01/swagger/redis.json#L45).
- The examples need to be provided in a separate file in the examples directory under the api-version directory `azure-rest-api-specs/arm-<yourService>/<api-version>/examples/<exampleName>.json`. You can take a look over [here](https://github.com/Azure/azure-rest-api-specs/tree/master/arm-redis/2016-04-01/examples) for the structure of examples.
- We require you to provide us a minimum (just required properties/parameters of the request/response) and a maximum (full blown) example. Feel free to provide more examples as deemed necessary.
- We have provided schemas for examples to be provided in the examples directory. It can be found over [here](https://github.com/Azure/autorest/blob/master/schema/example-schema.json). This will help you with intellisene and validation.
  - If you are using **vscode** to edit your swaggers in the azure-rest-api-specs repo then everything should work out of the box as the schemas have been added in the `.vscode/settings.json` file over [here](https://github.com/Azure/azure-rest-api-specs/blob/master/.vscode/settings.json).
  - If you are using **Visual Studio** then you can use the urls provided in the settings.json file and put them in the drop down list at the top of a json file when the file is opened in VS.

### How does this tool fit with others

Swagger specs validation could be split in the following:

1. Schema validation
2. Semantic validation
3. Model definition validation
4. Swagger operations execution (against mocked data or live tests)
5. Human-eye review to complement the above

In the context of "azure-rest-api-specs" repo:

- #1 is being performed on every PR as part of CI.
- #2 and #3 are performed by the tool currently in openapi-validation-tools repo and by AutoRest linter. We're working towards integrating them into CI for "azure-rest-api-specs" repo.
- #4 is not available yet, though we're starting to work on it.
- #5 will be done by the approvers of PRs in "azure-rest-api-specs", as this won't be automated.

### Autorest plugin configuration

- Please don't edit this section unless you're re-configuring how oav plugs in to AutoRest
  AutoRest needs the below config to pick this up as a plug-in - see [Autorest extensions](https://github.com/Azure/autorest/blob/master/docs/developer/architecture/AutoRest-extension.md).

```yaml $(model-validator)
pipeline:
  swagger-document/model-validator:
    input: swagger-document/identity
```

### Live Validation Mode

- A **Live Validation** mode has been added to OAV with the purpose of enabling validation of live traffic.
- Usage (here is a sample of a [request-response pair](./test/sampleRequestResponsePair.json)):

```javascript
const liveValidatorOptions = {
  git: {
    url: "https://github.com/Azure/azure-rest-api-specs.git",
    shouldClone: true
  },
  directory: path.resolve(os.homedir(), "cloneRepo"),
  swaggerPathsPattern: "/specification/**/resource-manager/**/*.json",
  isPathCaseSensitive: false,
  shouldModelImplicitDefaultResponse: true
}

const apiValidator = new oav.LiveValidator(liveValidatorOptions)
await apiValidator.initialize() // Note that for a large number of specs this can take some time.

// After `initialize()` finishes we are ready to validate
const validationResult = apiValidator.validateLiveRequestResponse(requestResponsePair)
```

---

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

redpajama_set_name: RedPajamaGithub


text: This is being committed to the readme-edits branch. IT still says hello world.


text:
package com.ibatis.common.util;

import org.apache.ibatis.parsing.*;

import java.lang.reflect.Method;

public class NodeEventWrapper {

  private Object nodeletTarget;
  private Method method;

  public NodeEventWrapper(Object nodeletTarget, Method method) {
    this.nodeletTarget = nodeletTarget;
    this.method = method;
  }

  public void process(XNode context) {
    try {
      method.invoke(nodeletTarget, new Object[]{context});
    } catch (Exception e) {
      throw new ParsingException("Error processing node " + context.getNode().getNodeName() + ". Cause: " + e, e);
    }
  }

}


text:
@import FirebaseAuth;

@interface RegisterTwoVC () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *emailField;
@property (weak, nonatomic) IBOutlet UITextField *passField;
@property (weak, nonatomic) IBOutlet UITextField *confirmPassField;

@property (weak, nonatomic) IBOutlet UIButton *doneButton;

@property (weak, nonatomic) IBOutlet UIView *emailSeperator;
@property (weak, nonatomic) IBOutlet UIView *passSeperator;
@property (weak, nonatomic) IBOutlet UIView *confirmPassSeperator;

@property (weak, nonatomic) IBOutlet UILabel *errorLabel;
@property (weak, nonatomic) IBOutlet UIView *viewForCloseScreen;

@property (weak, nonatomic) UITextField *currentTextField;

@property (strong, nonatomic) User *userModel;

@end

@implementation RegisterTwoVC

#pragma mark - life time
- (void)viewDidLoad {
    [super viewDidLoad];

    _doneButton.layer.cornerRadius = 5.0f;
    _doneButton.clipsToBounds = YES;
}

#pragma mark - Actions

- (IBAction)doneAction:(id)sender {

    [self toggleScreenByView:TRUE];
    [_currentTextField resignFirstResponder];

    NSString *email = _emailField.text;
    NSString *pass = _passField.text;
    NSString *confirmPass = _confirmPassField.text;

    BOOL isEmailValid = [StringValidator emailValidation:email];
    BOOL isPassValid = [StringValidator passwordValidation:pass];
    BOOL isConfirmPassValid = [pass isEqualToString:confirmPass];

    if (!isEmailValid)
        _emailSeperator.backgroundColor = WARNING_COLOR;

    if (!isPassValid)
        _passSeperator.backgroundColor = WARNING_COLOR;

    if (!isConfirmPassValid)
        _confirmPassSeperator.backgroundColor = WARNING_COLOR;

    if (isEmailValid && isPassValid && isConfirmPassValid) {

        _userModel.email = email;
        _userModel.pass = pass;

        [[FIRServerManager sharedManager] registrationUser:_userModel successBlock:^(BOOL status, NSError *error) {
            if (!error && status) {
                [self performSegueAfterRegistration];
            } else {
                [self errorWithMessage:error.localizedDescription];
            }
        }];
    } else {
        [self errorWithMessage:@"Email or password are not valid, try again."];
    }
}

-(void)errorWithMessage:(NSString*)message {
    [self toggleScreenByView:FALSE];
    [self showErrorMessage:message];
}

#pragma ToggleScreen

- (void)toggleScreenByView:(BOOL)toggle {

    _viewForCloseScreen.hidden = !toggle;
}

- (void)showErrorMessage:(NSString*)error {
    _errorLabel.hidden = FALSE;
    _errorLabel.text = error;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _errorLabel.hidden = TRUE;
    });
}

#pragma mark - Segues

- (void)performSegueAfterRegistration {
    [self.currentTextField resignFirstResponder];
    [self performSegueWithIdentifier:@"afterRegisteration" sender:nil];
}

#pragma mark - NavigationToNextPart

- (void)receiveUserModel:(User*)userModel {
    _userModel = userModel;
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    _currentTextField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    if ([textField isEqual:_emailField]) {
        if ([StringValidator emailValidation:_emailField.text]) {
            _emailSeperator.backgroundColor = GREY_THEME_COLOR;

        } else {
            _emailSeperator.backgroundColor = WARNING_COLOR;
        }

    } else if ([textField isEqual:_passField]) {
        if ([StringValidator passwordValidation:_passField.text]) {
            _passSeperator.backgroundColor = GREY_THEME_COLOR;

        } else {
            _passSeperator.backgroundColor = WARNING_COLOR;
        }
    } else if ([textField isEqual:_confirmPassField]) {
        if (_passField.text == _confirmPassField.text) {
            _confirmPassSeperator.backgroundColor = GREY_THEME_COLOR;

        } else {
            _confirmPassSeperator.backgroundColor = WARNING_COLOR;
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if ([textField isEqual:_emailField]){
        [_passField becomeFirstResponder];
    } else if ([textField isEqual:_passField]) {
        [_confirmPassField becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
    }

    return YES;
}

@end


text:
/** @flow */
import { applyMiddleware, combineReducers, compose, createStore } from 'redux'
import { reducer as searchReducer, reduxSearch } from '../source/index'
import { reducer as resourceReducer } from './resources'
import thunk from 'redux-thunk'

export default function createAppStore (): Object {
  const finalCreateStore = compose(
    applyMiddleware(thunk),
    reduxSearch({
      resourceIndexes: {
        map: ['name', 'title'],
        immutableMap: ['name', 'title']
      },
      resourceSelector: (resourceName, state) => {
        return state.resources.get(resourceName)
      }
    })
  )(createStore)

  const rootReducer = combineReducers({
    resources: resourceReducer,
    search: searchReducer
  })

  return finalCreateStore(rootReducer)
}


text:
<?php

namespace Magento\Setup\Test\Unit\Model;

use \Magento\Setup\Model\StoreConfigurationDataMapper;

use Magento\Backend\Model\Url;
use Magento\Directory\Helper\Data;
use Magento\Directory\Model\Currency;
use Magento\Setup\Module\Setup;
use Magento\Store\Model\Store;

class StoreConfigurationDataMapperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @param array $data
     * @param array $expected
     * @dataProvider getConfigDataDataProvider
     */
    public function testGetConfigData(array $data, array $expected)
    {
        $userConfigurationDataMapper = new StoreConfigurationDataMapper();
        $this->assertEquals($expected, $userConfigurationDataMapper->getConfigData($data));
    }

    /**
     * @return array
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function getConfigDataDataProvider()
    {
        return [
            'valid' =>
            [
                [
                    StoreConfigurationDataMapper::KEY_ADMIN_USE_SECURITY_KEY => '1',
                    StoreConfigurationDataMapper::KEY_BASE_URL => 'http://127.0.0.1/',
                    StoreConfigurationDataMapper::KEY_BASE_URL_SECURE => 'https://127.0.0.1/',
                    StoreConfigurationDataMapper::KEY_CURRENCY => 'USD',
                    StoreConfigurationDataMapper::KEY_IS_SECURE => '1',
                    StoreConfigurationDataMapper::KEY_IS_SECURE_ADMIN => '1',
                    StoreConfigurationDataMapper::KEY_LANGUAGE => 'en_US',
                    StoreConfigurationDataMapper::KEY_TIMEZONE => 'America/Chicago',
                    StoreConfigurationDataMapper::KEY_USE_SEF_URL => '1',
                ],
                [
                    Store::XML_PATH_USE_REWRITES => '1',
                    Store::XML_PATH_UNSECURE_BASE_URL => 'http://127.0.0.1/',
                    Store::XML_PATH_SECURE_IN_FRONTEND => '1',
                    Store::XML_PATH_SECURE_BASE_URL => 'https://127.0.0.1/',
                    Store::XML_PATH_SECURE_IN_ADMINHTML => '1',
                    Data::XML_PATH_DEFAULT_LOCALE => 'en_US',
                    Data::XML_PATH_DEFAULT_TIMEZONE => 'America/Chicago',
                    Currency::XML_PATH_CURRENCY_BASE => 'USD',
                    Currency::XML_PATH_CURRENCY_DEFAULT => 'USD',
                    Currency::XML_PATH_CURRENCY_ALLOW => 'USD',
                    Url::XML_PATH_USE_SECURE_KEY => '1',
                ],
            ],
            'valid alphabet url' => [
                [
                    StoreConfigurationDataMapper::KEY_ADMIN_USE_SECURITY_KEY => '1',
                    StoreConfigurationDataMapper::KEY_BASE_URL => 'http://example.com/',
                    StoreConfigurationDataMapper::KEY_BASE_URL_SECURE => 'https://example.com/',
                    StoreConfigurationDataMapper::KEY_CURRENCY => 'USD',
                    StoreConfigurationDataMapper::KEY_IS_SECURE => '1',
                    StoreConfigurationDataMapper::KEY_IS_SECURE_ADMIN => '1',
                    StoreConfigurationDataMapper::KEY_LANGUAGE => 'en_US',
                    StoreConfigurationDataMapper::KEY_TIMEZONE => 'America/Chicago',
                    StoreConfigurationDataMapper::KEY_USE_SEF_URL => '1',
                ],
                [
                    Store::XML_PATH_USE_REWRITES => '1',
                    Store::XML_PATH_UNSECURE_BASE_URL => 'http://example.com/',
                    Store::XML_PATH_SECURE_IN_FRONTEND => '1',
                    Store::XML_PATH_SECURE_BASE_URL => 'https://example.com/',
                    Store::XML_PATH_SECURE_IN_ADMINHTML => '1',
                    Data::XML_PATH_DEFAULT_LOCALE => 'en_US',
                    Data::XML_PATH_DEFAULT_TIMEZONE => 'America/Chicago',
                    Currency::XML_PATH_CURRENCY_BASE => 'USD',
                    Currency::XML_PATH_CURRENCY_DEFAULT => 'USD',
                    Currency::XML_PATH_CURRENCY_ALLOW => 'USD',
                    Url::XML_PATH_USE_SECURE_KEY => '1',
                ],
            ],
            'no trailing slash' =>
            [
                [
                    StoreConfigurationDataMapper::KEY_ADMIN_USE_SECURITY_KEY => '1',
                    StoreConfigurationDataMapper::KEY_BASE_URL => 'http://127.0.0.1',
                    StoreConfigurationDataMapper::KEY_BASE_URL_SECURE => 'https://127.0.0.1',
                    StoreConfigurationDataMapper::KEY_CURRENCY => 'USD',
                    StoreConfigurationDataMapper::KEY_IS_SECURE => '1',
                    StoreConfigurationDataMapper::KEY_IS_SECURE_ADMIN => '1',
                    StoreConfigurationDataMapper::KEY_LANGUAGE => 'en_US',
                    StoreConfigurationDataMapper::KEY_TIMEZONE => 'America/Chicago',
                    StoreConfigurationDataMapper::KEY_USE_SEF_URL => '1',
                ],
                [
                    Store::XML_PATH_USE_REWRITES => '1',
                    Store::XML_PATH_UNSECURE_BASE_URL => 'http://127.0.0.1/',
                    Store::XML_PATH_SECURE_IN_FRONTEND => '1',
                    Store::XML_PATH_SECURE_BASE_URL => 'https://127.0.0.1/',
                    Store::XML_PATH_SECURE_IN_ADMINHTML => '1',
                    Data::XML_PATH_DEFAULT_LOCALE => 'en_US',
                    Data::XML_PATH_DEFAULT_TIMEZONE => 'America/Chicago',
                    Currency::XML_PATH_CURRENCY_BASE => 'USD',
                    Currency::XML_PATH_CURRENCY_DEFAULT => 'USD',
                    Currency::XML_PATH_CURRENCY_ALLOW => 'USD',
                    Url::XML_PATH_USE_SECURE_KEY => '1',
                ],
            ],
            'no trailing slash, alphabet url' =>
                [
                    [
                        StoreConfigurationDataMapper::KEY_ADMIN_USE_SECURITY_KEY => '1',
                        StoreConfigurationDataMapper::KEY_BASE_URL => 'http://example.com',
                        StoreConfigurationDataMapper::KEY_BASE_URL_SECURE => 'https://example.com',
                        StoreConfigurationDataMapper::KEY_CURRENCY => 'USD',
                        StoreConfigurationDataMapper::KEY_IS_SECURE => '1',
                        StoreConfigurationDataMapper::KEY_IS_SECURE_ADMIN => '1',
                        StoreConfigurationDataMapper::KEY_LANGUAGE => 'en_US',
                        StoreConfigurationDataMapper::KEY_TIMEZONE => 'America/Chicago',
                        StoreConfigurationDataMapper::KEY_USE_SEF_URL => '1',
                    ],
                    [
                        Store::XML_PATH_USE_REWRITES => '1',
                        Store::XML_PATH_UNSECURE_BASE_URL => 'http://example.com/',
                        Store::XML_PATH_SECURE_IN_FRONTEND => '1',
                        Store::XML_PATH_SECURE_BASE_URL => 'https://example.com/',
                        Store::XML_PATH_SECURE_IN_ADMINHTML => '1',
                        Data::XML_PATH_DEFAULT_LOCALE => 'en_US',
                        Data::XML_PATH_DEFAULT_TIMEZONE => 'America/Chicago',
                        Currency::XML_PATH_CURRENCY_BASE => 'USD',
                        Currency::XML_PATH_CURRENCY_DEFAULT => 'USD',
                        Currency::XML_PATH_CURRENCY_ALLOW => 'USD',
                        Url::XML_PATH_USE_SECURE_KEY => '1',
                    ],
                ],
        ];
    }
}


text:
<!DOCTYPE html>

<title>How do I delegate site access to a user?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.delegatedaccess" name="description">
<meta content="" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I delegate site access to a user?

Go to Delegated Access tool.

Select Delegated Access from the Tool Menu of the Administration Workspace or in your own My Workspace site.

Find and select user

              Zoom

Click the Search by User button*

Enter the user name or user ID and click Submit (or hit "enter" key).

Click the Edit link for the user.

Tip: You can also search for a user by clicking the Search by Access button. See How do I search users in Delegated Access?

Expand hierarchy nodes.

              Zoom

If you want to provide the user with admin capability for all hierarchy nodes, you can skip this step. Otherwise, click the Expand All Nodes link (or click the root node). Continue expanding nodes to access the appropriate node.

Note: Settings you select for a node will apply to all its "child" (lower-level) nodes, but not to any other nodes at the same level in the hierarchy. You can always override settings that a lower-level node inherits from a higher node.

Set access and role

              Zoom

For a particular node:

Check Site Access.

Select a role from the User Becomes menu. The user will have the permissions for the selected role when accessing sites.

Set tool restrictions. (Optional)

              Zoom

If you would like to restrict access to specific tools within a node or site, click Restricted Tools.

Select the tool/s you want to restrict, then click Done.

Add Become User tool. (Optional)

              Zoom

If you would like to enable access to the Become User tool, click Advanced.

Enable Become User tool, then click Done.

In the window that displays, enable the Allow user to use Become User tool for users in the these sites setting. Then, click Done. The Become User tool will be added to the user's system landing page.

Note: The Become User tool will only function for the sites to which the user has been granted access.

Save settings

Click Save. A "Successfully saved" message displays.

If the user has no previous delegated access permissions enabled, the Delegated Access tool gets added to the user's My Workspace, along with Become User if you also enabled access to that tool.


text:
package com.hubspot.singularity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import io.swagger.v3.oas.annotations.media.Schema;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(
  use = Id.MINIMAL_CLASS,
  include = As.PROPERTY,
  property = "@class",
  defaultImpl = SingularityTaskShellCommandRequest.class
)
@JsonSubTypes(
  {
    @Type(value = SingularityTaskShellCommandRequest.class, name = "SHELL_COMMAND"),
    @Type(value = SingularityTaskDestroyFrameworkMessage.class, name = "TASK_KILL")
  }
)
@Schema(
  subTypes = {
    SingularityTaskShellCommandRequest.class, SingularityTaskDestroyFrameworkMessage.class
  }
)
public abstract class SingularityFrameworkMessage {

  public abstract SingularityTaskId getTaskId();
}


text:
<?php

/**
 * This file is a part of the FTP Wrapper package
 *
 * For the full informations, please read the README file
 * distributed with this source code
 *
 * @package FTP Wrapper
 * @version 1.1.1
 * @author  Touki <g.vincendon@vithemis.com>
 */

namespace Touki\FTP\Exception;

/**
 * Base exception class for any exception thrown by FTP
 *
 * @author Touki <g.vincendon@vithemis.com>
 */
class FTPException extends \Exception
{
    /**
     * Overrides the default to String
     * @return string
     */
    public function __toString()
    {
        return sprintf('[FTP Error] %s', $this->getMessage());
    }
}


text:
extern alias PortableTestUtils;

using System;
using System.Reflection;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using AssertEx = PortableTestUtils::Roslyn.Test.Utilities.AssertEx;
using TestBase = PortableTestUtils::Roslyn.Test.Utilities.TestBase;

namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests
{
    public class CsiTests : TestBase
    {
        private static readonly string CompilerVersion = typeof(Csi).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
        private string CsiPath => typeof(Csi).GetTypeInfo().Assembly.Location;

        /// <summary>
        /// csi should use the current working directory of its environment to resolve relative paths specified on command line.
        /// </summary>
        [Fact]
        public void CurrentWorkingDirectory1()
        {
            var dir = Temp.CreateDirectory();
            dir.CreateFile("a.csx").WriteAllText(@"Console.Write(Environment.CurrentDirectory + ';' + typeof(C).Name);");
            dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1);

            var result = ProcessUtilities.Run(CsiPath, "/r:C.dll a.csx", workingDirectory: dir.Path);
            AssertEx.AssertEqualToleratingWhitespaceDifferences(dir.Path + ";C", result.Output);
            Assert.False(result.ContainsErrors);
        }

        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7826")]
        public void CurrentWorkingDirectory_Change()
        {
            var dir = Temp.CreateDirectory();
            dir.CreateFile("a.csx").WriteAllText(@"int X = 1;");
            dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1);

            var result = ProcessUtilities.Run(CsiPath, "", stdInput:
$@"#load ""a.csx""
#r ""C.dll""
Directory.SetCurrentDirectory(@""{dir.Path}"")
#load ""a.csx""
#r ""C.dll""
X
new C()
Environment.Exit(0)
");

            AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
Microsoft (R) Visual C# Interactive Compiler version {CompilerVersion}
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> (1,7): error CS1504: Source file 'a.csx' could not be opened -- Could not find file.
> (1,1): error CS0006: Metadata file 'C.dll' could not be found
> > > > 1
> C {{ }}
>
", result.Output);

            Assert.False(result.ContainsErrors);
        }

        /// <summary>
        /// csi does NOT use LIB environment variable to populate reference search paths.
        /// </summary>
        [Fact]
        public void ReferenceSearchPaths_LIB()
        {
            var cwd = Temp.CreateDirectory();
            cwd.CreateFile("a.csx").WriteAllText(@"Console.Write(typeof(C).Name);");

            var dir = Temp.CreateDirectory();
            dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1);

            var result = ProcessUtilities.Run(CsiPath, "/r:C.dll a.csx", workingDirectory: cwd.Path, additionalEnvironmentVars: new[] { KeyValuePair.Create("LIB", dir.Path) });

            // error CS0006: Metadata file 'C.dll' could not be found
            Assert.True(result.Output.StartsWith("error CS0006", StringComparison.Ordinal));
            Assert.True(result.ContainsErrors);
        }

        /// <summary>
        /// csi does use SDK path (FX dir)
        /// </summary>
        [Fact]
        public void ReferenceSearchPaths_Sdk()
        {
            var cwd = Temp.CreateDirectory();
            cwd.CreateFile("a.csx").WriteAllText(@"Console.Write(typeof(DataSet).Name);");

            var result = ProcessUtilities.Run(CsiPath, "/r:System.Data.dll /u:System.Data;System a.csx", workingDirectory: cwd.Path);

            AssertEx.AssertEqualToleratingWhitespaceDifferences("DataSet", result.Output);
            Assert.False(result.ContainsErrors);
        }

        [Fact]
        public void DefaultUsings()
        {
            var source = @"
dynamic d = new ExpandoObject();
Process p = new Process();
Expression<Func<int>> e = () => 1;
var squares = from x in new[] { 1, 2, 3 } select x * x;
var sb = new StringBuilder();
var list = new List<int>();
var stream = new MemoryStream();
await Task.Delay(10);

Console.Write(""OK"");
";

            var cwd = Temp.CreateDirectory();
            cwd.CreateFile("a.csx").WriteAllText(source);

            var result = ProcessUtilities.Run(CsiPath, "a.csx", workingDirectory: cwd.Path);

            AssertEx.AssertEqualToleratingWhitespaceDifferences("OK", result.Output);
            Assert.False(result.ContainsErrors);
        }
    }
}


text:
"""Manage class and methods for sessions."""
import logging
import pandas
import utils

# Load logging configuration
log = logging.getLogger(__name__)

class Session:
    """Session class."""

    def update_session_status(self, authorization: str, session_id: int, session_status: str):
        """Update a session status."""

        query = 'mutation updateSessionStatus($id: Int!, $sessionPatch: SessionPatch!){updateSessionById(input:{id: $id, sessionPatch: $sessionPatch}){session{status}}}'
        variables = {'id': session_id, 'sessionPatch': {'status': session_status}}
        payload = {'query': query, 'variables': variables}
        response = utils.execute_graphql_request(authorization, payload)

        return response

    def compute_session_result(self, authorization: str, session_id: int, alert_operator: str, alert_threshold: str, result_data: pandas.DataFrame):
        """Compute aggregated results for the indicator session."""

        log.info('Compute session results.')
        nb_records = len(result_data)
        nb_records_alert = len(result_data.loc[result_data['Alert'] == True]) # pylint: disable=C0121
        nb_records_no_alert = len(result_data.loc[result_data['Alert'] == False]) # pylint: disable=C0121

        # Post results to database
        query = 'mutation updateSessionResults($id: Int!, $sessionPatch: SessionPatch!){updateSessionById(input:{id: $id, sessionPatch: $sessionPatch}){session{id}}}'
        variables = {}
        variables['id'] = session_id
        variables['sessionPatch'] = {}
        variables['sessionPatch']['alertOperator'] = alert_operator
        variables['sessionPatch']['alertThreshold'] = float(alert_threshold)  # Alert threshold is stored as string in parameters and needs to be converted to float
        variables['sessionPatch']['nbRecordsNoAlert'] = nb_records_no_alert
        variables['sessionPatch']['nbRecordsAlert'] = nb_records_alert
        variables['sessionPatch']['nbRecords'] = nb_records
        payload = {'query': query, 'variables': variables}
        utils.execute_graphql_request(authorization, payload)

        return nb_records_alert


text:
class GovernorCreateTags < ActiveRecord::Migration
  def self.up
    create_table :tags do |t|
      t.string :name
      t.timestamps
    end

    create_table :<%= ['tags', mapping.plural.to_s].sort.join '_' %>, :id => false do |t|
      t.references :<%= mapping.singular %>, :tag
    end
  end

  def self.down
    drop_table :tags
    drop_table :<%= ['tags', mapping.plural.to_s].sort.join '_' %>
  end
end


text:
package com.commonsware.android.recyclerview.actionmodelist2;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;

abstract public class
    ChoiceCapableAdapter<T extends RecyclerView.ViewHolder>
    extends RecyclerView.Adapter<T> {
  private final ChoiceMode choiceMode;

  public ChoiceCapableAdapter(ChoiceMode choiceMode) {
    super();
    this.choiceMode=choiceMode;
  }

  void onChecked(int position, boolean isChecked) {
    choiceMode.setChecked(position, isChecked);
  }

  boolean isChecked(int position) {
    return(choiceMode.isChecked(position));
  }

  void onSaveInstanceState(Bundle state) {
    choiceMode.onSaveInstanceState(state);
  }

  void onRestoreInstanceState(Bundle state) {
    choiceMode.onRestoreInstanceState(state);
  }

  int getCheckedCount() {
    return(choiceMode.getCheckedCount());
  }

  void clearChecks() {
    choiceMode.clearChecks();
  }

  void visitChecks(ChoiceMode.Visitor v) {
    choiceMode.visitChecks(v);
  }
}


text:
Files from: http://www.wa4e.com/code/json-03-crud.zip

viewapi.php

Howdy - Lets get a JSON list

<?php // getjson.php

require_once "pdo.php";
session_start();
header('Content-Type: application/json; charset=utf-8');
$stmt = $pdo->query("SELECT title, plays, rating, id FROM tracks");
$rows = array();
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
  $rows[] = $row;
}

echo json_encode($rows);

?>

<?php // index.php

require_once "pdo.php";
session_start();
?>

<?php
if ( isset($_SESSION['error']) ) {
    echo '
'.$_SESSION['error']."
\n";
    unset($_SESSION['error']);
}
if ( isset($_SESSION['success']) ) {
    echo '
'.$_SESSION['success']."
\n";
    unset($_SESSION['success']);
}
?>

Add New
viewapi.php


text:
- Are concerned with how things look.
- May contain both presentational and container components** inside, and usually have some DOM markup and styles of their own.
- Often allow containment via `this.props.children`.
- Have no dependencies on the rest of the app, such as Flux actions or stores.
- Don't specify how the data is loaded or mutated.
- Receive data and callbacks exclusively via props.
- Rarely have their own state (when they do, it's UI state rather than data).
- Are written as functional components unless they need state, lifecycle hooks, or performance optimizations.
- Examples: Page, Sidebar, Story, UserInfo, List.

### Source

- [Presentational and Container Components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) by Dan Abramov


text:
#if LESSTHAN_NET35
extern alias nunitlinq;
#endif

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
//    Miguel de Icaza (miguel@novell.com)
//    Jb Evain (jbevain@novell.com)
//

using System;
using System.Linq.Expressions;
using NUnit.Framework;

#if LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD20

using System.Reflection;

#endif

namespace MonoTests.System.Linq.Expressions
{
    [TestFixture]
    public class ExpressionTestEqual
    {
        public enum Foo
        {
            Bar,
            Baz
        }

        [Test]
        public void Arg1Null()
        {
            Assert.Throws<ArgumentNullException>(() => Expression.Equal(null, Expression.Constant(1)));
        }

        [Test]
        public void Arg2Null()
        {
            Assert.Throws<ArgumentNullException>(() => Expression.Equal(Expression.Constant(1), null));
        }

        [Test]
        public void ArgTypesDifferent()
        {
            Assert.Throws<InvalidOperationException>(() => Expression.Equal(Expression.Constant(1), Expression.Constant(2.0)));
        }

        [Test]
        public void EnumEqual()
        {
            var l = Expression.Parameter(typeof(Foo), "l");
            var r = Expression.Parameter(typeof(Foo), "r");

            var node = Expression.Equal(l, r);
            Assert.IsFalse(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNull(node.Method);

            var compiled = Expression.Lambda<Func<Foo, Foo, bool>>(node, l, r).Compile();

            Assert.AreEqual(true, compiled(Foo.Bar, Foo.Bar));
            Assert.AreEqual(false, compiled(Foo.Bar, Foo.Baz));
        }

        [Test]
        public void LiftedEnumEqual()
        {
            var l = Expression.Parameter(typeof(Foo?), "l");
            var r = Expression.Parameter(typeof(Foo?), "r");

            var node = Expression.Equal(l, r);
            Assert.IsTrue(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNull(node.Method);

            var compiled = Expression.Lambda<Func<Foo?, Foo?, bool>>(node, l, r).Compile();

            Assert.AreEqual(true, compiled(Foo.Bar, Foo.Bar));
            Assert.AreEqual(false, compiled(Foo.Bar, Foo.Baz));
            Assert.AreEqual(false, compiled(Foo.Bar, null));
            Assert.AreEqual(true, compiled(null, null));
        }

        [Test]
        public void NoOperatorClass()
        {
            Assert.Throws<InvalidOperationException>(() => Expression.Equal(Expression.Constant(new D()), Expression.Constant(new D())));
        }

        [Test]
        public void Nullable_LiftToNull_SetToFalse()
        {
            int? a = 1;
            int? b = 2;

            var expr = Expression.Equal
            (
                Expression.Constant(a, typeof(int?)),
                Expression.Constant(b, typeof(int?)),
                false, null
            );
            Assert.AreEqual(ExpressionType.Equal, expr.NodeType);
            Assert.AreEqual(typeof(bool), expr.Type);
            Assert.AreEqual(true, expr.IsLifted);
            Assert.AreEqual(false, expr.IsLiftedToNull);
            Assert.IsNull(expr.Method);
        }

        [Test]
        public void Nullable_LiftToNull_SetToTrue()
        {
            int? a = 1;
            int? b = 2;

            var expr = Expression.Equal
            (
                Expression.Constant(a, typeof(int?)),
                Expression.Constant(b, typeof(int?)),
                true, null
            );
            Assert.AreEqual(ExpressionType.Equal, expr.NodeType);
            Assert.AreEqual(typeof(bool?), expr.Type);
            Assert.AreEqual(true, expr.IsLifted);
            Assert.AreEqual(true, expr.IsLiftedToNull);
            Assert.IsNull(expr.Method);
        }

        [Test]
        public void Nullable_Mixed()
        {
            Assert.Throws<InvalidOperationException>
            (
                () =>
                {
                    int? a = 1;
                    const int b = 2;

                    Expression.Equal
                    (
                        Expression.Constant(a, typeof(int?)),
                        Expression.Constant(b, typeof(int))
                    );
                }
            );
        }

        [Test]
        public void NullableBoolEqualToBool()
        {
            var l = Expression.Parameter(typeof(bool?), "l");
            var r = Expression.Parameter(typeof(bool?), "r");

            var node = Expression.Equal(l, r);
            Assert.IsTrue(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNull(node.Method);

            var compiled = Expression.Lambda<Func<bool?, bool?, bool>>(node, l, r).Compile();

            Assert.AreEqual(false, compiled(true, null));
            Assert.AreEqual(true, compiled(null, null));
            Assert.AreEqual(true, compiled(false, false));
        }

        [Test]
        public void NullableInt32Equal()
        {
            var l = Expression.Parameter(typeof(int?), "l");
            var r = Expression.Parameter(typeof(int?), "r");

            var compiled = Expression.Lambda<Func<int?, int?, bool>>
            (
                Expression.Equal(l, r), l, r
            ).Compile();

            Assert.IsTrue(compiled(null, null));
            Assert.IsFalse(compiled(null, 1));
            Assert.IsFalse(compiled(1, null));
            Assert.IsFalse(compiled(1, 2));
            Assert.IsTrue(compiled(1, 1));
            Assert.IsFalse(compiled(null, 0));
            Assert.IsFalse(compiled(0, null));
        }

        [Test]
        public void NullableInt32EqualLiftedToNull()
        {
            var l = Expression.Parameter(typeof(int?), "l");
            var r = Expression.Parameter(typeof(int?), "r");

            var compiled = Expression.Lambda<Func<int?, int?, bool?>>
            (
                Expression.Equal(l, r, true, null), l, r
            ).Compile();

            Assert.AreEqual(null, compiled(null, null));
            Assert.AreEqual(null, compiled(null, 1));
            Assert.AreEqual(null, compiled(1, null));
            Assert.AreEqual((bool?)false, compiled(1, 2));
            Assert.AreEqual((bool?)true, compiled(1, 1));
            Assert.AreEqual(null, compiled(null, 0));
            Assert.AreEqual(null, compiled(0, null));
        }

        [Test]
        public void NullableNullEqual()
        {
            var param = Expression.Parameter(typeof(DateTime?), "x");

            var node = Expression.Equal(param, Expression.Constant(null));

            Assert.IsTrue(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNull(node.Method);

            var compiled = Expression.Lambda<Func<DateTime?, bool>>(node, param).Compile();

            Assert.AreEqual(true, compiled(null));
            Assert.AreEqual(false, compiled(DateTime.Now));
        }

        [Test]
        public void Numeric()
        {
            var expr = Expression.Equal(Expression.Constant(1), Expression.Constant(2));
            Assert.AreEqual(ExpressionType.Equal, expr.NodeType);
            Assert.AreEqual(typeof(bool), expr.Type);
            Assert.IsNull(expr.Method);
        }

        [Test]
        public void PrimitiveNonNumeric()
        {
            var expr = Expression.Equal(Expression.Constant('a'), Expression.Constant('b'));
            Assert.AreEqual(ExpressionType.Equal, expr.NodeType);
            Assert.AreEqual(typeof(bool), expr.Type);
            Assert.IsNull(expr.Method);

            var compiled = Expression.Lambda<Func<bool>>(expr).Compile();
            Assert.IsFalse(compiled());
        }

        [Test]
        public void ReferenceCompare()
        {
            Expression.Equal(Expression.Constant(new NoOpClass()), Expression.Constant(new NoOpClass()));
        }

        [Test]
        public void UserDefinedClass()
        {
            // We can use the simplest version of GetMethod because we already know only one
            // exists in the very simple class we're using for the tests.
            var method = typeof(OpClass).GetMethod("op_Equality");

            var expr = Expression.Equal(Expression.Constant(new OpClass()), Expression.Constant(new OpClass()));
            Assert.AreEqual(ExpressionType.Equal, expr.NodeType);
            Assert.AreEqual(typeof(bool), expr.Type);
            Assert.AreEqual(method, expr.Method);
        }

        [Test]
        public void UserDefinedEqual()
        {
            var l = Expression.Parameter(typeof(Slot), "l");
            var r = Expression.Parameter(typeof(Slot), "r");

            var node = Expression.Equal(l, r);

            Assert.IsFalse(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNotNull(node.Method);

            var compiled = Expression.Lambda<Func<Slot, Slot, bool>>(node, l, r).Compile();

            Assert.AreEqual(true, compiled(new Slot(21), new Slot(21)));
            Assert.AreEqual(false, compiled(new Slot(1), new Slot(-1)));
        }

        [Test]
        public void UserDefinedEqualLifted()
        {
            var l = Expression.Parameter(typeof(Slot?), "l");
            var r = Expression.Parameter(typeof(Slot?), "r");

            var node = Expression.Equal(l, r);

            Assert.IsTrue(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool), node.Type);
            Assert.IsNotNull(node.Method);

            var compiled = Expression.Lambda<Func<Slot?, Slot?, bool>>(node, l, r).Compile();

            Assert.AreEqual(true, compiled(null, null));
            Assert.AreEqual(false, compiled(new Slot(2), null));
            Assert.AreEqual(false, compiled(null, new Slot(2)));
            Assert.AreEqual(true, compiled(new Slot(21), new Slot(21)));
        }

        [Test]
        public void UserDefinedEqualLiftedToNull()
        {
            var l = Expression.Parameter(typeof(Slot?), "l");
            var r = Expression.Parameter(typeof(Slot?), "r");

            var node = Expression.Equal(l, r, true, null);

            Assert.IsTrue(node.IsLifted);
            Assert.IsTrue(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool?), node.Type);
            Assert.IsNotNull(node.Method);

            var compiled = Expression.Lambda<Func<Slot?, Slot?, bool?>>(node, l, r).Compile();

            Assert.AreEqual(null, compiled(null, null));
            Assert.AreEqual(null, compiled(new Slot(2), null));
            Assert.AreEqual(null, compiled(null, new Slot(2)));
            Assert.AreEqual((bool?)true, compiled(new Slot(21), new Slot(21)));
            Assert.AreEqual((bool?)false, compiled(new Slot(21), new Slot(-21)));
        }

        [Test]
        public void UserDefinedToNullableEqual()
        {
            var l = Expression.Parameter(typeof(SlotToNullable), "l");
            var r = Expression.Parameter(typeof(SlotToNullable), "r");

            var node = Expression.Equal(l, r, false, null);

            Assert.IsFalse(node.IsLifted);
            Assert.IsFalse(node.IsLiftedToNull);
            Assert.AreEqual(typeof(bool?), node.Type);
            Assert.IsNotNull(node.Method);

            var compiled = Expression.Lambda<Func<SlotToNullable, SlotToNullable, bool?>>(node, l, r).Compile();

            Assert.AreEqual((bool?)true, compiled(new SlotToNullable(2), new SlotToNullable(2)));
            Assert.AreEqual((bool?)false, compiled(new SlotToNullable(2), new SlotToNullable(-2)));
        }

        [Test]
        public void UserDefinedToNullableEqualFromNullable()
        {
            Assert.Throws<InvalidOperationException>
            (
                () => Expression.Equal
                (
                    Expression.Parameter(typeof(SlotToNullable?), "l"),
                    Expression.Parameter(typeof(SlotToNullable?), "r")
                )
            );
        }

        public struct D
        {
            // Empty
        }

        private struct Slot
        {
            private readonly int _value;

            public Slot(int value)
            {
                _value = value;
            }

            public static bool operator !=(Slot a, Slot b)
            {
                return a._value != b._value;
            }

            public static bool operator ==(Slot a, Slot b)
            {
                return a._value == b._value;
            }

            public override bool Equals(object obj)
            {
                var other = obj as Slot?;
                return other?._value == _value;
            }

            public override int GetHashCode()
            {
                return _value;
            }
        }

        private struct SlotToNullable
        {
            private readonly int _value;

            public SlotToNullable(int value)
            {
                _value = value;
            }

            public static bool? operator !=(SlotToNullable a, SlotToNullable b)
            {
                return a._value != b._value;
            }

            public static bool? operator ==(SlotToNullable a, SlotToNullable b)
            {
                return a._value == b._value;
            }

            public override bool Equals(object obj)
            {
                var other = obj as SlotToNullable?;
                return other?._value == _value;
            }

            public override int GetHashCode()
            {
                return _value;
            }
        }
    }
}


text:
ServioMicro
===

Minimal middleware to store/fetch data to/from Servioticy API.

#Setup

Install deps with `npm install`

Run with

`node index.js`

or additionally specifying host and port

`node index.js 192.168.10.2 80`

#Usage

Enables an http service to interact with easier payload with servioticy, potentially avoiding json

To get the last value of a stream and, optionally, of a channel

```
GET /
Authorization: [api key]
Soid: [service object soid]
Stream: [service object stream]
Channel: [Optional, channel name to return]

```

To set the value of a stream

```
POST /
Authorization: [api key]
Soid: [service object soid]
Stream: [service object stream]
Content-Type: application/x-www-form-urlencoded

channel1=channel1Value&channel2=channel2Value
```

or with json

```
POST /
Authorization: [api key]
Soid: [service object soid]
Stream: [service object stream]
Content-Type: application/json

{ "channel1": "channel1Value", "channel2": 123 }
```

Extras:

- `GET /now` will return the current timestamp on the machine

#License

MIT


text:
extern "C" {
    void init_param_PciDevice();
}

EmbeddedSwig embed_swig_param_PciDevice(init_param_PciDevice);


text:
namespace base {
class FilePath;
}

namespace fileapi {
class FileSystemContext;
}

class MTPFileStreamReader
    : public NON_EXPORTED_BASE(webkit_blob::FileStreamReader) {
 public:
  MTPFileStreamReader(fileapi::FileSystemContext* file_system_context,
                      const fileapi::FileSystemURL& url,
                      int64 initial_offset,
                      const base::Time& expected_modification_time);

  virtual ~MTPFileStreamReader();

  // FileStreamReader overrides.
  virtual int Read(net::IOBuffer* buf, int buf_len,
                   const net::CompletionCallback& callback) OVERRIDE;
  virtual int64 GetLength(
      const net::Int64CompletionCallback& callback) OVERRIDE;

 private:
  void OnFileInfoForRead(net::IOBuffer* buf, int buf_len,
                         const net::CompletionCallback& callback,
                         const base::File::Info& file_info);

  void FinishRead(const net::CompletionCallback& callback,
                  int bytes_read);

  void FinishGetLength(const net::Int64CompletionCallback& callback,
                       const base::File::Info& file_info);

  scoped_refptr<fileapi::FileSystemContext> file_system_context_;
  fileapi::FileSystemURL url_;
  int64 current_offset_;
  const base::Time expected_modification_time_;
  base::WeakPtrFactory<MTPFileStreamReader> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(MTPFileStreamReader);
};

#endif  // CHROME_BROWSER_MEDIA_GALLERIES_FILEAPI_MTP_FILE_STREAM_READER_H_


text:
package com.google.template.soy.data;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.html.types.SafeHtml;
import com.google.common.html.types.SafeHtmlProto;
import com.google.common.html.types.SafeHtmls;
import com.google.common.html.types.SafeScript;
import com.google.common.html.types.SafeScriptProto;
import com.google.common.html.types.SafeScripts;
import com.google.common.html.types.SafeStyle;
import com.google.common.html.types.SafeStyleProto;
import com.google.common.html.types.SafeStyleSheet;
import com.google.common.html.types.SafeStyleSheetProto;
import com.google.common.html.types.SafeStyleSheets;
import com.google.common.html.types.SafeStyles;
import com.google.common.html.types.SafeUrl;
import com.google.common.html.types.SafeUrlProto;
import com.google.common.html.types.SafeUrls;
import com.google.common.html.types.TrustedResourceUrl;
import com.google.common.html.types.TrustedResourceUrlProto;
import com.google.common.html.types.TrustedResourceUrls;
import com.google.common.io.Resources;
import com.google.errorprone.annotations.CompileTimeConstant;
import com.google.template.soy.data.SanitizedContent.ContentKind;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

/**
 * Creation utilities for SanitizedContent objects for common use cases.
 *
 *
This should contain utilities that have extremely broad application. More specific utilities
 * should reside with the specific project.
 *
 *
All utilities here should be extremely difficult to abuse in a way that could create
 * attacker-controlled SanitizedContent objects. Java's type system is a great tool to achieve this.
 *
 */
@ParametersAreNonnullByDefault
public final class SanitizedContents {
  /** Extensions for static resources that we allow to be treated as safe HTML. */
  private static final ImmutableSet<String> SAFE_HTML_FILE_EXTENSIONS =
      ImmutableSet.of("html", "svg");

  /** No constructor. */
  private SanitizedContents() {}

  /** Creates an empty string constant. */
  public static SanitizedContent emptyString(ContentKind kind) {
    return SanitizedContent.create("", kind, Dir.NEUTRAL); // Empty string is neutral.
  }

  /**
   * Creates a SanitizedContent object of kind TEXT of a given direction (null if unknown).
   *
   *
This is useful when stubbing out a function that needs to create a SanitizedContent object.
   */
  public static SanitizedContent unsanitizedText(String text, @Nullable Dir dir) {
    return SanitizedContent.create(text, ContentKind.TEXT, dir);
  }

  /**
   * Creates a SanitizedContent object of kind TEXT and unknown direction.
   *
   *
This is useful when stubbing out a function that needs to create a SanitizedContent object.
   */
  public static SanitizedContent unsanitizedText(String text) {
    return unsanitizedText(text, null);
  }

  /**
   * Concatenate the contents of multiple {@link SanitizedContent} objects of kind HTML.
   *
   * @param contents The HTML content to combine.
   */
  public static SanitizedContent concatHtml(SanitizedContent... contents) {
    for (SanitizedContent content : contents) {
      checkArgument(content.getContentKind() == ContentKind.HTML, "Can only concat HTML");
    }

    StringBuilder combined = new StringBuilder();
    Dir dir = Dir.NEUTRAL; // Empty string is neutral.
    for (SanitizedContent content : contents) {
      combined.append(content.getContent());
      if (dir == Dir.NEUTRAL) {
        // neutral + x -> x
        dir = content.getContentDirection();
      } else if (content.getContentDirection() == dir
          || content.getContentDirection() == Dir.NEUTRAL) {
        // x + x|neutral -> x, so leave dir unchanged.
      } else {
        // LTR|unknown + RTL|unknown -> unknown
        // RTL|unknown + LTR|unknown -> unknown
        dir = null;
      }
    }
    return SanitizedContent.create(combined.toString(), ContentKind.HTML, dir);
  }

  /**
   * Loads assumed-safe content from a Java resource.
   *
   *
This performs ZERO VALIDATION of the data, and takes you on your word that the input is
   * valid. We assume that resources should be safe because they are part of the binary, and
   * therefore not attacker controlled, unless the source code is compromised (in which there's
   * nothing we can do).
   *
   * @param contextClass Class relative to which to load the resource.
   * @param resourceName The name of the resource, relative to the context class.
   * @param charset The character set to use, usually Charsets.UTF_8.
   * @param kind The content kind of the resource.
   */
  public static SanitizedContent fromResource(
      Class<?> contextClass, String resourceName, Charset charset, ContentKind kind)
      throws IOException {
    pretendValidateResource(resourceName, kind);
    return SanitizedContent.create(
        Resources.toString(Resources.getResource(contextClass, resourceName), charset),
        kind,
        // Text resources are usually localized, so one might think that the locale direction should
        // be assumed for them. We do not do that because:
        // - We do not know the locale direction here.
        // - Some messages do not get translated.
        // - This method currently can't be used for text resources (see pretendValidateResource()).
        getDefaultDir(kind));
  }

  /**
   * Loads assumed-safe content from a Java resource.
   *
   *
This performs ZERO VALIDATION of the data, and takes you on your word that the input is
   * valid. We assume that resources should be safe because they are part of the binary, and
   * therefore not attacker controlled, unless the source code is compromised (in which there's
   * nothing we can do).
   *
   * @param resourceName The name of the resource to be found using {@linkplain
   *     Thread#getContextClassLoader() context class loader}.
   * @param charset The character set to use, usually Charsets.UTF_8.
   * @param kind The content kind of the resource.
   */
  public static SanitizedContent fromResource(
      String resourceName, Charset charset, ContentKind kind) throws IOException {
    pretendValidateResource(resourceName, kind);
    return SanitizedContent.create(
        Resources.toString(Resources.getResource(resourceName), charset),
        kind,
        // Text resources are usually localized, so one might think that the locale direction should
        // be assumed for them. We do not do that because:
        // - We do not know the locale direction here.
        // - Some messages do not get translated.
        // - This method currently can't be used for text resources (see pretendValidateResource()).
        getDefaultDir(kind));
  }

  /**
   * Wraps an assumed-safe URI constant.
   *
   *
This only accepts compile-time constants, based on the assumption that URLs that are
   * controlled by the application (and not user input) are considered safe.
   */
  public static SanitizedContent constantUri(@CompileTimeConstant final String constant) {
    return fromConstant(constant, ContentKind.URI, Dir.LTR);
  }

  /**
   * Wraps an assumed-safe constant string that specifies a safe, balanced, document fragment.
   *
   *
This only accepts compile-time constants, based on the assumption that HTML snippets that
   * are controlled by the application (and not user input) are considered safe.
   */
  public static SanitizedContent constantHtml(@CompileTimeConstant final String constant) {
    return fromConstant(constant, ContentKind.HTML, null);
  }

  /** Wraps an assumed-safe constant string. */
  private static SanitizedContent fromConstant(
      String constant, ContentKind kind, @Nullable Dir dir) {
    // Extra runtime check in case the compile-time check doesn't work.
    Preconditions.checkArgument(
        constant.intern().equals(constant),
        "The provided argument does not look like a compile-time constant.");
    return SanitizedContent.create(constant, kind, dir);
  }

  /** Converts a {@link SafeHtml} into a Soy {@link SanitizedContent} of kind HTML. */
  public static SanitizedContent fromSafeHtml(SafeHtml html) {
    return SanitizedContent.create(html.getSafeHtmlString(), ContentKind.HTML, null);
  }

  /** Converts a {@link SafeHtmlProto} into a Soy {@link SanitizedContent} of kind HTML. */
  public static SanitizedContent fromSafeHtmlProto(SafeHtmlProto html) {
    return SanitizedContent.create(
        SafeHtmls.fromProto(html).getSafeHtmlString(), ContentKind.HTML, null);
  }

  /** Converts a {@link SafeScript} into a Soy {@link SanitizedContent} of kind JS. */
  public static SanitizedContent fromSafeScript(SafeScript script) {
    return SanitizedContent.create(script.getSafeScriptString(), ContentKind.JS, null);
  }

  /** Converts a {@link SafeScriptProto} into a Soy {@link SanitizedContent} of kind JS. */
  public static SanitizedContent fromSafeScriptProto(SafeScriptProto script) {
    return SanitizedContent.create(
        SafeScripts.fromProto(script).getSafeScriptString(), ContentKind.JS, null);
  }

  /** Converts a {@link SafeStyle} into a Soy {@link SanitizedContent} of kind CSS. */
  public static SanitizedContent fromSafeStyle(SafeStyle style) {
    return SanitizedContent.create(style.getSafeStyleString(), ContentKind.CSS, null);
  }

  /** Converts a {@link SafeStyleProto} into a Soy {@link SanitizedContent} of kind CSS. */
  public static SanitizedContent fromSafeStyleProto(SafeStyleProto style) {
    return SanitizedContent.create(
        SafeStyles.fromProto(style).getSafeStyleString(), ContentKind.CSS, null);
  }

  /** Converts a {@link SafeStyleSheet} into a Soy {@link SanitizedContent} of kind CSS. */
  public static SanitizedContent fromSafeStyleSheet(SafeStyleSheet styleSheet) {
    return SanitizedContent.create(styleSheet.getSafeStyleSheetString(), ContentKind.CSS, null);
  }

  /** Converts a {@link SafeStyleSheetProto} into a Soy {@link SanitizedContent} of kind CSS. */
  public static SanitizedContent fromSafeStyleSheetProto(SafeStyleSheetProto styleSheet) {
    return SanitizedContent.create(
        SafeStyleSheets.fromProto(styleSheet).getSafeStyleSheetString(), ContentKind.CSS, null);
  }

  /** Converts a {@link SafeUrl} into a Soy {@link SanitizedContent} of kind URI. */
  public static SanitizedContent fromSafeUrl(SafeUrl url) {
    return SanitizedContent.create(url.getSafeUrlString(), ContentKind.URI, Dir.LTR);
  }

  /** Converts a {@link SafeUrlProto} into a Soy {@link SanitizedContent} of kind URI. */
  public static SanitizedContent fromSafeUrlProto(SafeUrlProto url) {
    return SanitizedContent.create(
        SafeUrls.fromProto(url).getSafeUrlString(), ContentKind.URI, Dir.LTR);
  }

  /**
   * Converts a {@link TrustedResourceUrl} into a Soy {@link SanitizedContent} of kind
   * TRUSTED_RESOURCE_URI.
   */
  public static SanitizedContent fromTrustedResourceUrl(TrustedResourceUrl url) {
    return SanitizedContent.create(
        url.getTrustedResourceUrlString(), ContentKind.TRUSTED_RESOURCE_URI, Dir.LTR);
  }

  /**
   * Converts a {@link TrustedResourceUrlProto} into a Soy {@link SanitizedContent} of kind
   * TRUSTED_RESOURCE_URI.
   */
  public static SanitizedContent fromTrustedResourceUrlProto(TrustedResourceUrlProto url) {
    return SanitizedContent.create(
        TrustedResourceUrls.fromProto(url).getTrustedResourceUrlString(),
        ContentKind.TRUSTED_RESOURCE_URI,
        Dir.LTR);
  }

  /**
   * Very basic but strict validation that the resource's extension matches the content kind.
   *
   *
In practice, this may be unnecessary, but it's always good to start out strict. This list
   * can either be expanded as needed, or removed if too onerous.
   */
  @VisibleForTesting
  static void pretendValidateResource(String resourceName, ContentKind kind) {
    int index = resourceName.lastIndexOf('.');
    Preconditions.checkArgument(
        index >= 0, "Currently, we only validate resources with explicit extensions.");
    String fileExtension = resourceName.substring(index + 1).toLowerCase();

    switch (kind) {
      case JS:
        Preconditions.checkArgument(fileExtension.equals("js"));
        break;
      case HTML:
        Preconditions.checkArgument(SAFE_HTML_FILE_EXTENSIONS.contains(fileExtension));
        break;
      case CSS:
        Preconditions.checkArgument(fileExtension.equals("css"));
        break;
      default:
        throw new IllegalArgumentException("Don't know how to validate resources of kind " + kind);
    }
  }

  /*
   * Returns the default direction per content kind: LTR for JS, URI, ATTRIBUTES, and CSS content,
   * and otherwise unknown.
   */
  static Dir getDefaultDir(ContentKind kind) {
    switch (kind) {
      case JS:
      case URI:
      case ATTRIBUTES:
      case CSS:
      case TRUSTED_RESOURCE_URI:
        return Dir.LTR;
      default:
        return null;
    }
  }
}


text:
/*
 * test SQLBindParameter with text and Sybase
 * test from Keith Woodard (bug #885122)
 */
#include "common.h"

static char software_version[] = "$Id: convert_error.c,v 1.12 2011-07-12 10:16:59 freddy77 Exp $";
static void *no_unused_var_warn[] = { software_version, no_unused_var_warn };

static int test_num = 0;

static void
Test(const char *bind1, SQLSMALLINT type1, const char *bind2, SQLSMALLINT type2)
{
	char sql[512];
	char *val = "test";
	SQLLEN ind = 4;
	int id = 1;
	ODBC_BUF *odbc_buf = NULL;

	SQLFreeStmt(odbc_stmt, SQL_RESET_PARAMS);

	++test_num;
	sprintf(sql, "insert into #test_output values (%s, %s)", bind1, bind2);

	CHKPrepare(T(sql), strlen(sql), "S");
	if (bind1[0] == '?')
		CHKBindParameter(id++, SQL_PARAM_INPUT, SQL_C_LONG, type1, 3, 0, &test_num, 0, &ind, "S");
	if (bind2[0] == '?')
		CHKBindParameter(id++, SQL_PARAM_INPUT, SQL_C_CHAR, type2, strlen(val) + 1, 0, (SQLCHAR *) val,
					 0, &ind, "S");
	CHKExecute("S");
	ODBC_FREE();
}

int
main(int argc, char **argv)
{
	odbc_use_version3 = 1;
	odbc_connect();

	odbc_command("create table #test_output (id int, msg text)");

	Test("?", SQL_INTEGER, "?", SQL_LONGVARCHAR);
	Test("123", SQL_INTEGER, "?", SQL_LONGVARCHAR);
	Test("?", SQL_INTEGER, "'foo'", SQL_LONGVARCHAR);
	Test("?", SQL_INTEGER, "?", SQL_VARCHAR);

	/*
	 * Sybase cannot pass this test without complicated query parsing.
	 * Query with blob columns cannot be prepared so prepared query must
	 * be emulated loosing column informations from server and Sybase do
	 * not convert implicitly VARCHAR to INT
	 */
	if (odbc_db_is_microsoft())
		Test("?", SQL_VARCHAR, "?", SQL_LONGVARCHAR);
	else
		++test_num;

	odbc_disconnect();

	return 0;
}