text:
package uk.co.optimisticpanda.gtest.dto.propertyaccess;

/**
 * These are used for introspection purposes.
 * <p>One {@link IPropertyAccess} is
 * created for each instance that extends {@link PropertyAccessSupport}.
 * </p>
 * @see IPropertyAccessFactory
 * @author Andy Lee
 */
public interface IPropertyAccess {

	/**
	 * Get the value of the property that this {@link IPropertyAccess}
	 * represents from a specific instance.
	 *
	 * @param instance
	 *            to get the value from.
	 * @return value of the property this property value represents
	 * @throws PropertyAccessException
	 */
	public Object getValue(Object instance) throws PropertyAccessException;

	/**
	 * Set the property belonging to an instance to the specified value.
	 *
	 * @param instance
	 *            to set the value on.
	 * @param value
	 *            the value to set
	 * @throws PropertyAccessException
	 */
	public void setValue(Object instance, Object value) throws PropertyAccessException;
}


text:
/*
 *	NET3	PLIP tuning facilities for the new Niibe PLIP.
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License
 *	as published by the Free Software Foundation; either version
 *	2 of the License, or (at your option) any later version.
 *
 */

#ifndef _LINUX_IF_PLIP_H
#define _LINUX_IF_PLIP_H

#include <linux/sockios.h>

#define	SIOCDEVPLIP	SIOCDEVPRIVATE

struct plipconf {
	unsigned short pcmd;
	unsigned long  nibble;
	unsigned long  trigger;
};

#define PLIP_GET_TIMEOUT	0x1
#define PLIP_SET_TIMEOUT	0x2

#endif

redpajama_set_name: RedPajamaGithub


text:
/**
 * This file tests the codesplitting phase
 * - It checks the creation of split modules
 * - It checks on circular dependencies within splits
 * - It flags commonly used modules within splits
 * - It checks differently import methods
 */
import * as path from 'path';
import { IProductionContext } from '../ProductionContext';
import { ISplitEntry } from '../module/SplitEntries';
import { CodeSplittingPhase } from '../phases/CodeSplittingPhase';
import { WarmupPhase } from '../phases/WarmupPhase';
import { createTestEnvironment, ITestEnvironment } from './testUtils';

describe('Code Splitting test', () => {
  let environment: ITestEnvironment;
  let cachedModule: ISplitEntry;

  const getProductionContext = async (files: Record<string, string>): Promise<IProductionContext> => {
    environment = await createTestEnvironment({ entry: 'index.ts' }, files);
    const context = await environment.run([WarmupPhase, CodeSplittingPhase]);
    return context;
  };

  /**
   * Helper function to get the SplitEntry based on the original filename
   * This is convenient cause orders of modules might change in the future.
   * @param fileName
   * @param entries
   */
  const getSplitEntry = (fileName: string, entries: Array<ISplitEntry>): ISplitEntry => {
    if (!!cachedModule && cachedModule.entry.absPath === path.join(environment.sourceDir + fileName)) {
      return cachedModule;
    }
    cachedModule = undefined;
    for (const entry of entries) {
      const moduleFileName = entry.entry.absPath.replace(environment.sourceDir + path.sep, '');
      if (fileName === moduleFileName) {
        cachedModule = entry;
        break;
      }
    }
    return cachedModule;
  };

  // cleanup after each test
  afterEach(() => {
    if (environment) {
      environment.cleanup();
      environment = undefined;
    }
    cachedModule = undefined;
  });

  /**
   * This test is to ensure we have a splitted module
   * 'bar' is dynamically required, so we would have 1 splitEntry
   */
  it('should have splitEntry', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        export default function() {}
      `,
      'foo.ts': `
        export default function() {}
      `,
      'index.ts': `
        import './foo';
        async function load() {
          const dynamicFunc = await import('./bar');
        }
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(3);
    expect(entries).toHaveLength(1);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(1);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
    expect(barModule.references).toHaveLength(1);
    expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
  });

  /**
   * This test ensures we have a split entry
   * and modules required by that entry should end up in the
   * subModules of the splitted module
   */
  it('should have splitEntry with submodules', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        import './foo';
        export default function() {}
      `,
      'foo.ts': `
        export default function() {}
      `,
      'index.ts': `
        async function load() {
          const dynamicFunc = await import('./bar');
        }
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(3);
    expect(entries).toHaveLength(1);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(2);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
    expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
    expect(barModule.references).toHaveLength(1);
    expect(barModule.references[0].module.publicPath).toContain('src/index.ts');
  });

  /**
   * In this test case, we have one dynamic import 'bar.ts'
   *
   * 1.
   * index.ts AND bar.ts import the module './test'
   * - 'test' should not be in bar.subModules
   * 2.
   * bar requires 'ignored.ts' but doesn't use it
   * - 'ignored' should not be in bar.subModules
   */
  it('should drop imported module thats required directly somewhere else', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        import { test } from './test';
        import { ignored } from './ignored';
        export default function() {};

        console.log(test);
      `,
      'foo.ts': `
        export function foo() {}
      `,
      'ignored.ts': `
        export const ignored = 'this module is being ignored';
      `,
      'index.ts': `
        import './foo';
        import { test } from './test';

        async function load() {
          const dynamicFunc = await import('./bar');
        }

        console.log(test);
      `,
      'test.ts': `
        export const test = 'test';
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(4);
    expect(entries).toHaveLength(1);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(1);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
  });

  /**
   * In this test case we make sure we can have multiple
   * splitEntries and each entry has it's own isolated submodules
   */
  it('should have multiple splitEntries with submodules', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        import './foo';
        export default function() {}
      `,
      'foo.ts': `
        export default function() {}
      `,
      'index.ts': `
        async function load() {
          const bar = await import('./bar');
          const oi = await import('./oi');
        }
      `,
      'oi.ts': `
        import './utils';
        export default function() {}
      `,
      'utils.ts': `
        export default function() {}
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(5);
    expect(entries).toHaveLength(2);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(2);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
    expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
    expect(barModule.references).toHaveLength(1);
    expect(barModule.references[0].module.publicPath).toContain('src/index.ts');

    const oiModule = getSplitEntry('oi.ts', entries);
    expect(oiModule.modules).toHaveLength(2);
    expect(oiModule.modules[0].publicPath).toContain('src/oi.ts');
    expect(oiModule.modules[1].publicPath).toContain('src/utils.ts');
    expect(oiModule.references).toHaveLength(1);
    expect(oiModule.references[0].module.publicPath).toContain('src/index.ts');
  });

  /**
   * This test case will test that a module required by a splitted module
   * but also required by a module outside of the split is being dropped
   * from the subModules of the splitEntry
   */
  it('should drop imported module thats required directly somewhere else', async () => {
    const context = await getProductionContext({
      'ai.ts': `
        export const ai = 'ai';
      `,
      'bar.ts': `
        import { oi } from './oi';
        console.log(oi);
        export default function() {};
      `,
      'foo.ts': `
        export default function() {};
      `,
      'index.ts': `
        import './foo';
        import { oi } from './oi';
        import { ai } from './ai';

        async function load() {
          const dynamicFunc = await import('./bar');
        }
        console.log(oi);
        console.log(ai);
      `,
      'oi.ts': `
        export const oi = 'oi!';
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(5);
    expect(entries).toHaveLength(1);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(1);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
  });

  /**
   * Another test to test multiple split entries.
   */
  it('should have multiple splitEntries with submodules', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        import './foo';
        export default function() {}
      `,
      'foo.ts': `
        async function load() {
          const oi = await import('./oi');
        }
        export default function() {}
      `,
      'index.ts': `
        async function load() {
          const bar = await import('./bar');
        }
      `,
      'oi.ts': `
        import './utils';
        export default function() {}
      `,
      'utils.ts': `
        export default function() {}
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(5);
    expect(entries).toHaveLength(2);

    const barModule = getSplitEntry('bar.ts', entries);
    expect(barModule.modules).toHaveLength(2);
    expect(barModule.modules[0].publicPath).toContain('src/bar.ts');
    expect(barModule.modules[1].publicPath).toContain('src/foo.ts');
    expect(barModule.references).toHaveLength(1);
    expect(barModule.references[0].module.publicPath).toContain('src/index.ts');

    const oiModule = getSplitEntry('oi.ts', entries);
    expect(oiModule.modules).toHaveLength(2);
    expect(oiModule.modules[0].publicPath).toContain('src/oi.ts');
    expect(oiModule.modules[1].publicPath).toContain('src/utils.ts');
    expect(oiModule.references).toHaveLength(1);
    expect(oiModule.references[0].module.publicPath).toContain('src/foo.ts');
  });

  /**
   * This is a test where we test that a dynamic imported module can ALSO
   * dynamically import modules and those will have their own splitEntry
   */
  it('should work with dynamic in dynamic in dynamic', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        console.log('empty');
      `,
      'entry1.ts': `
        import('./one');
      `,
      'foo.ts': `
        import './bar';
      `,
      'index.ts': `
        import './entry1';
      `,
      'one.ts': `
        import './foo';
        import('./two');
      `,
      'three.ts': `
        import './utils';
      `,
      'two.ts': `
        import('./three');
        import './bar';
      `,
      'utils.ts': `
        console.log('empty');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(8);
    expect(entries).toHaveLength(3);

    // we're not splitting commons atm
    const oneModule = getSplitEntry('one.ts', entries);
    expect(oneModule.entry.publicPath).toContain('src/one.ts');
    // expect(oneModule.modules).toHaveLength(3);
    expect(oneModule.modules).toHaveLength(2);

    const twoModule = getSplitEntry('two.ts', entries);
    expect(twoModule.entry.publicPath).toContain('src/two.ts');
    // expect(twoModule.modules).toHaveLength(2);
    expect(twoModule.modules).toHaveLength(1);

    const threeModule = getSplitEntry('three.ts', entries);
    expect(threeModule.entry.publicPath).toContain('src/three.ts');
    expect(threeModule.modules).toHaveLength(2);

    expect(modules[7].isCommonsEligible).toBe(false);
    // expect(modules[7].isCommonsEligible).toBe(true);
  });

  /**
   * If a module is required from within different splitEntries and not outside
   * of splittedModules it should be flagged as commons, so we can create
   * another isolated splitted module
   *
   * This feature is disabled until further notice
   */
  it('should NOT flag commons', async () => {
    const context = await getProductionContext({
      'bar.ts': `
        import './utils';
        import './foo';
        export default function() {}
      `,
      'foo.ts': `
        export default function() {}
      `,
      'index.ts': `
        import './foo';
        async function load() {
          await import('./bar');
          await import('./one');
        }
      `,
      'one.ts': `
        import './utils';
      `,
      'utils.ts': `
        console.log('empty');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(5);
    expect(entries).toHaveLength(2);
    // utils.ts
    expect(modules[2].isCommonsEligible).toBe(false);
    // expect(modules[2].isCommonsEligible).toBe(true);
    // foo.ts
    expect(modules[4].isCommonsEligible).toBe(false);
  });

  /**
   * If there's an circular dependency, we prevent entering
   * a loop of death and prevent duplicate subModules
   */
  it('should detect circular dependency', async () => {
    const context = await getProductionContext({
      'a.ts': `
        import './b';
        export default function() {};
      `,
      'b.ts': `
        import './c';
      `,
      'c.ts': `
        import './b';
      `,
      'index.ts': `
        async function load() {
          const dynamicFunc = await import('./a');
        }
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(4);
    // we only have 1 split
    expect(entries).toHaveLength(1);
    // the split we have has 3 modules: a, b, c
    expect(getSplitEntry('a.ts', entries).modules).toHaveLength(3);
  });

  /**
   * This test is to ensure that a 'deep' circular dependency
   * is resolved too.
   */
  it('should detect deep circular dependency', async () => {
    const context = await getProductionContext({
      'a.ts': `
        import './b';
        export default function() {};
      `,
      'b.ts': `
        import './c';
      `,
      'c.ts': `
        import './d';
      `,
      'd.ts': `
        import './e';
      `,
      'e.ts': `
        import './f';
      `,
      'f.ts': `
        import './g';
      `,
      'g.ts': `
        import './b';
      `,
      'index.ts': `
        async function load() {
          const dynamicFunc = await import('./a');
        }
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(8);
    // we only have 1 split
    expect(entries).toHaveLength(1);
    // the split we have has 7 modules: a, b, c, d, e, f, g
    expect(getSplitEntry('a.ts', entries).modules).toHaveLength(7);
  });

  /**
   * Another dynamic in dynamic test
   */
  it('should detect dynamic in dynamic', async () => {
    const context = await getProductionContext({
      'entry1.ts': `
        import('./one');
      `,
      'index.ts': `
        import './entry1';
      `,
      'one.ts': `
        import('./two');
      `,
      'three.ts': `
        import './utils';
      `,
      'two.ts': `
        import('./three');
      `,
      'utils.ts': `
        console.log('emtpy');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(6);
    expect(entries).toHaveLength(3);

    expect(getSplitEntry('one.ts', entries).modules).toHaveLength(1);
    expect(getSplitEntry('two.ts', entries).modules).toHaveLength(1);
    expect(getSplitEntry('three.ts', entries).modules).toHaveLength(2);
  });

  /**
   * A weird badly written code base shouldn't fail
   */
  it('should handle funky setups', async () => {
    const context = await getProductionContext({
      'entry1.ts': `
        import('./one');
        import('./two');
      `,
      'foo.ts': `
        import './utils';
      `,
      'index.ts': `
        import './entry1';
      `,
      'one.ts': `
        import './two';
        import './utils';
      `,
      'three.ts': `
        import './utils';
      `,
      'two.ts': `
        import './foo';
      `,
      'utils.ts': `
        console.log('emtpy');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    // three.ts isn't required, so being dropped
    expect(modules).toHaveLength(6);
    // two is required normally, so shouldn't be a dynamic!
    expect(entries).toHaveLength(1);

    expect(getSplitEntry('one.ts', entries).modules).toHaveLength(1);
    expect(getSplitEntry('two.ts', entries)).toBe(undefined);
  });

  /**
   * We support all types of imports for modules in the splitEntry
   * With this test we ensure that that works ;)
   */
  it('should handle all type import types; require, import and export from', async () => {
    const context = await getProductionContext({
      'a.ts': `
        console.log('emtpy');
      `,
      'b.ts': `
        import './utils';
        export const b = 'b';
      `,
      'c.ts': `
        console.log('emtpy');
      `,
      'd.ts': `
        import './two';
        import './utils';
      `,
      'entry1.ts': `
        import { c } from './c';
        import('./d');
        const a = require('./a');
        export { b } from './b';

        console.log(c);
        console.log(a);

        export default function() {};
      `,
      'index.ts': `
        import a, { b } from './entry1';
        console.log(a, b);
      `,
      'two.ts': `
        console.log('emtpy');
      `,
      'utils.ts': `
        console.log('emtpy');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    // three.ts isn't required, so being dropped
    expect(modules).toHaveLength(8);
    expect(entries).toHaveLength(1);

    expect(getSplitEntry('d.ts', entries).modules).toHaveLength(2);
  });

  /**
   * We support circular dependencies without erroring
   * We should also be able to support multiple circular dependencies
   */
  it('should handle multiple circular dependencies', async () => {
    const context = await getProductionContext({
      'a.ts': `
        import './b';
      `,
      'b.ts': `
        import './c';
      `,
      'c.ts': `
        import './b';
        import './d';
      `,
      'd.ts': `
        import './b';
      `,
      'index.ts': `
        import('./a');
      `,
    });
    const {
      modules,
      splitEntries: { entries },
    } = context;
    expect(modules).toHaveLength(5);
    expect(entries).toHaveLength(1);
    expect(getSplitEntry('a.ts', entries).modules).toHaveLength(4);
  });
});


text:
[![Build Status](https://travis-ci.org/arnaudforaison/proxilabs-bot.svg?branch=develop)](https://travis-ci.org/arnaudforaison/proxilabs-bot)

# ProxiLabs bot
A Slack bot for Proxilabs management

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

### Prerequisites

You must need __NodeJs & npm__ was installed with version :
 - > 6.9.x for NodeJs
 - >v5.x.x for npm

### Installing

Install dependencies & setup env variables locally

```
npm run setup
```

Then, fill new **.env** created file with correct tokens

## Running the tests

To run all tests, only do this :
```
npm test
```

### Start application

To run locally the application is necessary to start a tunnel to expose localhost ip to the world.

```
npm i -g localtunnel
lt --port 9090 --subdomain proxilabs
```

This is necessary to allow Slack to find your localhost for slash command or dialog popin for examples

Then,
```
npm run start
```

## Deployment

Add additional notes about how to deploy this on a live system

## Built With

* [Botkit](https://github.com/howdyai/botkit/blob/master/docs/readme.md#botkit---building-blocks-for-building-bots) - Bot framework
* [Firebase](https://firebase.google.com/docs/) - Database manager

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details


text:
const request = require('request');
const helpers = require('../../lib/helpers');

const config = require('../../../shared/config');
const API_KEY = config.google.keys.unrestricted;

const querystring = require('querystring');

const GEOCODING_URL = 'https://maps.googleapis.com/maps/api/geocode/json';

module.exports = (metadata, context) => {
  const enabled = context.geocoding && context.geocoding.enabled;
  const forced = context.geocoding && context.geocoding.forced;

  const hasApproximateLocation = !!metadata.google_maps_coordinates_approximate;
  const needsGeocoding = !hasApproximateLocation || forced;

  if(enabled && API_KEY && metadata.street_name && needsGeocoding) {
    const address = helpers.geoTagging.getAddress(metadata);
    const query = querystring.stringify({
      address: address,
      key: API_KEY
    });

    const url = GEOCODING_URL + '?' + query;

    return new Promise((resolve, reject) => {
      request({
        url: url,
        json: true
      }, (error, response, body) => {
        if(error) {
          reject(error);
        } else {
          resolve(body);
        }
      });
    }).then(response => {
      if(response.results && response.results.length > 0) {
        const result = response.results[0];
        return result.geometry.location;
      } else {
        return null;
      }
    }).then(location => {
      if(location) {
        metadata.google_maps_coordinates_approximate = [
          location.lat,
          location.lng
        ].join(', ');
      }
      return metadata;
    }).then(metadata => {
      // Save these new approximate coordinates to the CIP.
      const coordinates = metadata.google_maps_coordinates_approximate;
      if(coordinates) {
        // Persist the coordinates in Cumulus
        context.persist('google_maps_coordinates_approximate', coordinates);
      }
      return metadata;
    });
  } else if(enabled && !API_KEY) {
    console.log('A Google Maps API key is required to geocode.');
    return metadata;
  } else if(enabled && hasApproximateLocation) {
    // Skipping geocoding, as the approximate location was sat
    return metadata;
  } else {
    return metadata;
  }
}


text:
/*	$NetBSD: LDAPRequest.h,v 1.1.1.3 2014/05/28 09:58:26 tron Exp $	*/

// $OpenLDAP$
/*
 * Copyright 2000-2014 The OpenLDAP Foundation, All Rights Reserved.
 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
 */

#ifndef LDAP_REQUEST_H
#define LDAP_REQUEST_H

#include <LDAPConstraints.h>
#include <LDAPAsynConnection.h>
#include <LDAPMessageQueue.h>

class LDAPUrl;

/**
 * For internal use only
 *
 * Each request that is sent to a LDAP-server by this library is
 * represented by a special object that contains the parameters and some
 * other info of the request. This virtual class is the common base classe
 * for these specialized request classes.
 */
class LDAPRequest{

    public :
        static const int BIND=0;
        static const int UNBIND=2;
        static const int SEARCH=3;
        static const int MODIFY=7;
        static const int ADD=8;
		static const int DELETE=10;
        static const int COMPARE=14;

        LDAPRequest(const LDAPRequest& req);
        LDAPRequest(LDAPAsynConnection* conn,
                const LDAPConstraints* cons, bool isReferral=false,
                const LDAPRequest* parent=0);
        virtual ~LDAPRequest();

        const LDAPConstraints* getConstraints() const;
        const LDAPAsynConnection* getConnection() const;
        virtual LDAPMsg *getNextMessage() const;
        int getType()const;
        int getMsgID() const;
        int getHopCount() const;

        /**
         * @return The LDAPRequest that has created this object. Or 0 if
         * this object was not created by another request.
         */
        const LDAPRequest* getParent() const;

        /**
         * @return true if this object was created during the automatic
         * chasing of referrals. Otherwise false
         */
        bool isReferral() const;

        void unbind() const;

        /**
         * This method encodes the request an calls the apprpriate
         * functions of the C-API to send the Request to a LDAP-Server
         */
        virtual LDAPMessageQueue* sendRequest()=0;
        virtual LDAPRequest* followReferral(LDAPMsg* ref);

        /**
         * Compare this request with another on. And returns true if they
         * have the same parameters.
         */
        virtual bool equals(const LDAPRequest* req) const;

        bool isCycle() const;

    protected :
        bool m_isReferral;
        int m_requestType;
        LDAPConstraints *m_cons;
        LDAPAsynConnection *m_connection;
        const LDAPRequest* m_parent;
        int m_hopCount;
        int m_msgID;  //the associated C-API Message ID
        LDAPRequest();
};
#endif //LDAP_REQUEST_H


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mne.event.define_target_events — MNE 0.17.1 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/reset-syntax.css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.17.1

Install

Documentation

API

Glossary

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.17.1

  </button>

Development

v0.17 (stable)

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.event.define_target_events

Examples using mne.event.define_target_events

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.event.define_target_events¶

mne.event.define_target_events(events, reference_id, target_id, sfreq, tmin, tmax, new_id=None, fill_na=None)[source]¶

Define new events by co-occurrence of existing events.

This function can be used to evaluate events depending on the
temporal lag to another event. For example, this can be used to
analyze evoked responses which were followed by a button press within
a defined time window.

<col class="field-name" />
<col class="field-body" />

Parameters:

events : ndarray

Array as returned by mne.find_events.

reference_id : int

The reference event. The event defining the epoch of interest.

target_id : int

The target event. The event co-occurring in within a certain time
window around the reference event.

sfreq : float

The sampling frequency of the data.

tmin : float

The lower limit in seconds from the target event.

tmax : float

The upper limit border in seconds from the target event.

new_id : int

new_id for the new event

fill_na : int | None

Fill event to be inserted if target is not available within the time
window specified. If None, the 'null' events will be dropped.

Returns:

new_events : ndarray

The new defined events

lag : ndarray

time lag between reference and target in milliseconds.

Examples using mne.event.define_target_events¶

Define target events based on time lag, plot evoked response

Plot single trial activity, grouped by ROI and sorted by RT

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2019, MNE Developers. Last updated on 2019-02-22.


text:
package org.jboss.weld.tests.contexts.passivating.validation;

import java.io.Serializable;

import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;

@SuppressWarnings("serial")
@Decorator
public class VesselDecorator implements Vessel, Serializable {

    @Inject
    @Delegate
    private Ferry ferry;

    @Inject
    private Engine engine;

    public void sail() {
        engine.start();
        ferry.sail();
    }
}


text:
module Resque
  def self.enqueued?(klass, *args)
    enqueued_in?(queue_from_class(klass), klass, *args)
  end

  def self.enqueued_in?(queue, klass, *args)
    item = { class: klass.to_s, args: args }
    return nil unless Resque::Plugins::Loner::Helpers.item_is_a_unique_job?(item)
    Resque::Plugins::Loner::Helpers.loner_queued?(queue, item)
  end

  def self.remove_queue_with_loner_cleanup(queue)
    remove_queue_without_loner_cleanup(queue)
    Resque::Plugins::Loner::Helpers.cleanup_loners(queue)
  end

  class << self
    alias_method :remove_queue_without_loner_cleanup, :remove_queue
    alias_method :remove_queue, :remove_queue_with_loner_cleanup
  end
end


text:
                  <button type="button" class="close" data-dismiss="modal">×</button>

Create new namespace

                  <form action="/logdata?form=namespace" method="post" enctype="multipart/form-data">

                      Namespace
                      <input type="name" class="form-control" id="namespace" name="namespace" placeholder="Enter namespace">

                      Description
                      <textarea class="form-control" rows="3" placeholder="Enter description" name="desc" id="desc"></textarea>

                      Source
                      <input type="fileSource" class="form-control" id="fileSource" name="fileSource" placeholder="Enter source">

                        <input type="radio" name="namespace1" id="radioFile" ng-model="namespace1" value="radioFile">File Upload

                        <input type="radio" name="namespace1" id="radioStream" ng-model="namespace1" value="radioStream">Streaming Data

                        File input
                        <input type="file" id="exampleInputFile" required accept=".json" name="file">

Upload your log file here.

 Streaming Data

                    <button type="submit" class="btn btn-success">Submit</button>

                  </form>

                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                  {{header}}

                  {{row[dat]}}

                Select Entity

                {{dat}}
                {{selectedRow[dat]}}

                  <button type="submit" name="dim" ng-show="hoverEdit" class="btn btn-warning btn-circle" ng-click="selectedDim(dat)">D</button>
                  <button type="submit" name="meas" ng-show="hoverEdit" class="btn btn-danger btn-circle" ng-click="selectedMeas(dat,selectedRow[dat])">M</button>

                Dimensions  |   Measures

Dimensions

Measures

Dimensions

              <form action="/dimensions/addDimension?form=dimension" method="post">

                  Display Name
                  <input type="displayname" class="form-control" id="displayname" name="displayname" placeholder="Enter Display Name" ng-model="displayname">

                  Field name
                  <input type="fieldname" class="form-control" id="fieldname" name="fieldname" placeholder="Enter Field Name" ng-model="dimVal">

              </form>
              <button class="btn btn-success" ng-click="submitDimension()">Save</button>

Measures

              <form action="/measures/addMeasure?form=measure" method="post">

                  Display Name
                  <input type="displaymeasurename" class="form-control" id="displaymeasurename" name="displaymeasurename" placeholder="Enter Display Name" ng-model="displaymeasurename">

                    <input type="radio" name="measure" id="radioField" ng-model="measure" value="radioField">Fieldname

                    <input type="radio" name="measure" id="radioEvent" ng-model="measure" value="radioEvent">Event

                  Fieldname
                  <select class="form-control" id="fieldmeasurename" name="measureFieldSelector" ng-model= "measureFieldSelector">
                    <option ng-repeat="dat in getKeys(selectedRow)" ng-if="!$last">{{dat}}</option>
                  </select>

Selected Event

                  Selected Event Field
                  <input type="eventField" class="form-control" id="eventField" placeholder="Selected Event Field.." readonly name="measureEventSelector" ng-model="measField">
                  Selected Event value
                  <input type="eventField" class="form-control" id="eventValue" placeholder="Selected Event Value.." readonly name="measureEventValueSelector" ng-model="measValue">

              </form>
              <button class="btn btn-success" ng-click="submitMeasure()">GO..</button>

                Dimensions

{{dim}}

                Measures

{{m}}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//

package ru.gov.zakupki.fz44.ws.priz;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="sender">
 *           <simpleType>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               <maxLength value="200"/>
 *               <minLength value="1"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *         <element name="senderType" type="{http://zakupki.gov.ru/fz44/ws/priz}partnerType"/>
 *         <element name="code" type="{http://zakupki.gov.ru/fz44/ws/priz}spzNumType"/>
 *         <element name="consRegistryNum" type="{http://zakupki.gov.ru/fz44/ws/priz}consRegistryNumType" minOccurs="0"/>
 *         <element name="documentKind" type="{http://zakupki.gov.ru/fz44/ws/priz}PRIZDocumentKindType" minOccurs="0"/>
 *         <element name="regNumber" type="{http://zakupki.gov.ru/fz44/ws/priz}shortNameType" minOccurs="0"/>
 *         <element name="tenderPlanPositionNumber" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <choice>
 *                   <element name="positionNumber" type="{http://zakupki.gov.ru/fz44/ws/priz}zfcs_tenderPlanPositionNumberType"/>
 *                   <element name="extNumber">
 *                     <simpleType>
 *                       <restriction base="{http://www.w3.org/2001/XMLSchema}int">
 *                       </restriction>
 *                     </simpleType>
 *                   </element>
 *                 </choice>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <element name="fromDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *         <element name="toDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "sender",
    "senderType",
    "code",
    "consRegistryNum",
    "documentKind",
    "regNumber",
    "tenderPlanPositionNumber",
    "fromDate",
    "toDate"
})
@XmlRootElement(name = "getPRIZObjectListRequest")
public class GetPRIZObjectListRequest {

    @XmlElement(required = true)
    protected String sender;
    @XmlElement(required = true)
    @XmlSchemaType(name = "string")
    protected PartnerType senderType;
    @XmlElement(required = true)
    protected String code;
    protected String consRegistryNum;
    @XmlSchemaType(name = "string")
    protected PRIZDocumentKindType documentKind;
    protected String regNumber;
    protected GetPRIZObjectListRequest.TenderPlanPositionNumber tenderPlanPositionNumber;
    @XmlElement(required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar fromDate;
    @XmlElement(required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar toDate;

    /**
     * Gets the value of the sender property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSender() {
        return sender;
    }

    /**
     * Sets the value of the sender property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSender(String value) {
        this.sender = value;
    }

    /**
     * Gets the value of the senderType property.
     *
     * @return
     *     possible object is
     *     {@link PartnerType }
     *
     */
    public PartnerType getSenderType() {
        return senderType;
    }

    /**
     * Sets the value of the senderType property.
     *
     * @param value
     *     allowed object is
     *     {@link PartnerType }
     *
     */
    public void setSenderType(PartnerType value) {
        this.senderType = value;
    }

    /**
     * Gets the value of the code property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCode() {
        return code;
    }

    /**
     * Sets the value of the code property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCode(String value) {
        this.code = value;
    }

    /**
     * Gets the value of the consRegistryNum property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getConsRegistryNum() {
        return consRegistryNum;
    }

    /**
     * Sets the value of the consRegistryNum property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setConsRegistryNum(String value) {
        this.consRegistryNum = value;
    }

    /**
     * Gets the value of the documentKind property.
     *
     * @return
     *     possible object is
     *     {@link PRIZDocumentKindType }
     *
     */
    public PRIZDocumentKindType getDocumentKind() {
        return documentKind;
    }

    /**
     * Sets the value of the documentKind property.
     *
     * @param value
     *     allowed object is
     *     {@link PRIZDocumentKindType }
     *
     */
    public void setDocumentKind(PRIZDocumentKindType value) {
        this.documentKind = value;
    }

    /**
     * Gets the value of the regNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRegNumber() {
        return regNumber;
    }

    /**
     * Sets the value of the regNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRegNumber(String value) {
        this.regNumber = value;
    }

    /**
     * Gets the value of the tenderPlanPositionNumber property.
     *
     * @return
     *     possible object is
     *     {@link GetPRIZObjectListRequest.TenderPlanPositionNumber }
     *
     */
    public GetPRIZObjectListRequest.TenderPlanPositionNumber getTenderPlanPositionNumber() {
        return tenderPlanPositionNumber;
    }

    /**
     * Sets the value of the tenderPlanPositionNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link GetPRIZObjectListRequest.TenderPlanPositionNumber }
     *
     */
    public void setTenderPlanPositionNumber(GetPRIZObjectListRequest.TenderPlanPositionNumber value) {
        this.tenderPlanPositionNumber = value;
    }

    /**
     * Gets the value of the fromDate property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getFromDate() {
        return fromDate;
    }

    /**
     * Sets the value of the fromDate property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setFromDate(XMLGregorianCalendar value) {
        this.fromDate = value;
    }

    /**
     * Gets the value of the toDate property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getToDate() {
        return toDate;
    }

    /**
     * Sets the value of the toDate property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setToDate(XMLGregorianCalendar value) {
        this.toDate = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <choice>
     *         <element name="positionNumber" type="{http://zakupki.gov.ru/fz44/ws/priz}zfcs_tenderPlanPositionNumberType"/>
     *         <element name="extNumber">
     *           <simpleType>
     *             <restriction base="{http://www.w3.org/2001/XMLSchema}int">
     *             </restriction>
     *           </simpleType>
     *         </element>
     *       </choice>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "positionNumber",
        "extNumber"
    })
    public static class TenderPlanPositionNumber {

        protected String positionNumber;
        protected Integer extNumber;

        /**
         * Gets the value of the positionNumber property.
         *
         * @return
         *     possible object is
         *     {@link String }
         *
         */
        public String getPositionNumber() {
            return positionNumber;
        }

        /**
         * Sets the value of the positionNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link String }
         *
         */
        public void setPositionNumber(String value) {
            this.positionNumber = value;
        }

        /**
         * Gets the value of the extNumber property.
         *
         * @return
         *     possible object is
         *     {@link Integer }
         *
         */
        public Integer getExtNumber() {
            return extNumber;
        }

        /**
         * Sets the value of the extNumber property.
         *
         * @param value
         *     allowed object is
         *     {@link Integer }
         *
         */
        public void setExtNumber(Integer value) {
            this.extNumber = value;
        }

    }

}


text:
/// <summary> </summary>
using System;
namespace org.javarosa.core.services.transport.payload
{

    /// <author>  Clayton Sims
    /// </author>
    /// <date>  Dec 18, 2008 </date>
    /// <summary>
    /// </summary>

    public

    interface IDataPayloadVisitor<T>
    {

         T visit(ByteArrayPayload payload);

         T visit(MultiMessagePayload payload);

         T visit(DataPointerPayload payload);

    }
}


text:
import { NovoFormControl } from './NovoFormControl';
import { NovoFormGroup } from './NovoFormGroup';

describe('Elements: NovoFormGroup', () => {
  const component = new NovoFormGroup({});

  describe('Method: enableAllControls()', () => {
    it('should enable all controls', () => {
      component.controls = {
        firstName: new NovoFormControl('John', {}),
        lastName: new NovoFormControl('Doe', {}),
      };
      for (const key in component.controls) {
        jest.spyOn(component.controls[key], 'enable');
        (component.controls[key] as NovoFormControl).readOnly = true;
      }
      component.enableAllControls();
      for (const key in component.controls) {
        expect((component.controls[key] as NovoFormControl).readOnly).toEqual(false);
        expect((component.controls[key] as NovoFormControl).enable).toHaveBeenCalled();
      }
    });
  });

  describe('Method: disableAllControls()', () => {
    it('should disable all controls', () => {
      component.controls = {
        firstName: new NovoFormControl('John', {}),
        lastName: new NovoFormControl('Doe', {}),
      };
      for (const key in component.controls) {
        jest.spyOn(component.controls[key], 'disable');
        (component.controls[key] as NovoFormControl).readOnly = false;
      }
      component.disableAllControls();
      for (const key in component.controls) {
        expect((component.controls[key] as NovoFormControl).readOnly).toEqual(true);
        expect((component.controls[key] as NovoFormControl).disable).toHaveBeenCalled();
      }
    });
  });
});


text:
package server

type CommunicationHandler func(conn *ChildConn) error

type Dispatch struct {
	H map[string]CommunicationHandler // Do not change at runtime!
}

func (d *Dispatch) Handle(cmd string, conn *ChildConn) error {
	f, ok := d.H[cmd]
	if !ok {
		return ErrHandlerNotFound
	}

	return f(conn)
}


text:
a{
	color: #000;
	text-decoration: none;
}
header{
	font-family: Arial;
	display: block;
	margin: 0 auto;
	width: 100%;
	text-align: center;
}
header h1{
	font-size: 60px;
	font-weight: bold;
}
header #newgamebutton{
	display: block;
	margin: 20px auto;
	width: 100px;
	padding: 10px 10px;
	background-color: #8f7a66;
	color: white;
	border-radius: 10px;
}
header #newgamebutton:hover{
	background-color: #9f8b77;
}
header p{
	font-size: 25px;
	margin: 20px auto;
}
#grid-container{
	width: 460px;
	height: 460px;
	padding: 20px;
	margin: 50px auto;
	background-color: #bbada0;
	border-radius: 10px;
	position: relative;
}
.grid-cell{
	width: 100px;
	height: 100px;
	border-radius: 6px;
	background-color: #ccc0b3;
	position: absolute;
}
.number-cell{
	border-radius: 6px;
	font-family: Arial;
	font-weight: bold;
	font-size: 60px;
	text-align: center;
	line-height: 100px;
	position: absolute;
}


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:
//      Federico Di Gregorio <fog@initd.org>

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 ExpressionTestMultiply
    {
        [Test]
        public void Arg1Null()
        {
            Assert.Throws<ArgumentNullException>(() => Expression.Multiply(null, Expression.Constant(1)));
        }

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

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

        [Test]
        public void Boolean()
        {
            Assert.Throws<InvalidOperationException>(() => Expression.Multiply(Expression.Constant(true), Expression.Constant(false)));
        }

        [Test]
        public void Compile()
        {
            var left = Expression.Parameter(typeof(int), "l");
            var right = Expression.Parameter(typeof(int), "r");
            var lambda = Expression.Lambda<Func<int, int, int>>
            (
                Expression.Multiply(left, right), left, right
            );

            var be = lambda.Body as BinaryExpression;
            Assert.IsNotNull(be);
            Assert.AreEqual(typeof(int), be.Type);
            Assert.IsFalse(be.IsLifted);
            Assert.IsFalse(be.IsLiftedToNull);

            var compiled = lambda.Compile();

            Assert.AreEqual(36, compiled(6, 6));
            Assert.AreEqual(-1, compiled(-1, 1));
            Assert.AreEqual(-3, compiled(1, -3));
        }

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

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

            var expr = Expression.Multiply(Expression.Constant(a), Expression.Constant(b));
            Assert.AreEqual(ExpressionType.Multiply, expr.NodeType, "Multiply#05");
            Assert.AreEqual(typeof(int), expr.Type, "Multiply#06");
            Assert.IsNull(expr.Method, "Multiply#07");
            Assert.AreEqual("(1 * 2)", expr.ToString(), "Multiply#08");
        }

        [Test]
        public void Numeric()
        {
            var expr = Expression.Multiply(Expression.Constant(1), Expression.Constant(2));
            Assert.AreEqual(ExpressionType.Multiply, expr.NodeType, "Multiply#01");
            Assert.AreEqual(typeof(int), expr.Type, "Multiply#02");
            Assert.IsNull(expr.Method, "Multiply#03");
            Assert.AreEqual("(1 * 2)", expr.ToString(), "Multiply#04");
        }

        [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_Multiply");

            var expr = Expression.Multiply(Expression.Constant(new OpClass()), Expression.Constant(new OpClass()));
            Assert.AreEqual(ExpressionType.Multiply, expr.NodeType, "Multiply#09");
            Assert.AreEqual(typeof(OpClass), expr.Type, "Multiply#10");
            Assert.AreEqual(method, expr.Method, "Multiply#11");
            Assert.AreEqual("op_Multiply", expr.Method.Name, "Multiply#12");
            Assert.AreEqual
            (
                "(value(MonoTests.System.Linq.Expressions.OpClass) * value(MonoTests.System.Linq.Expressions.OpClass))",
                expr.ToString(), "Multiply#13"
            );
        }
    }
}


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("react"), require("tether"), require("moment"), require("lodash"), require("react-onclickoutside"));
	else if(typeof define === 'function' && define.amd)
		define(["react", "tether", "moment", "lodash", "react-onclickoutside"], factory);
	else if(typeof exports === 'object')
		exports["DatePicker"] = factory(require("react"), require("tether"), require("moment"), require("lodash"), require("react-onclickoutside"));
	else
		root["DatePicker"] = factory(root["React"], root["Tether"], root["moment"], root["_"], root["OnClickOutside"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_7__, __WEBPACK_EXTERNAL_MODULE_8__, __WEBPACK_EXTERNAL_MODULE_9__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	var React = __webpack_require__(1);
	var Popover = __webpack_require__(2);
	var DateUtil = __webpack_require__(4);
	var Calendar = __webpack_require__(5);
	var DateInput = __webpack_require__(10);
	var moment = __webpack_require__(7);
	var _ = __webpack_require__(8);

	var DatePicker = React.createClass({
	  displayName: "DatePicker",

	  propTypes: {
	    weekdays: React.PropTypes.arrayOf(React.PropTypes.string),
	    locale: React.PropTypes.string,
	    dateFormatCalendar: React.PropTypes.string,
	    popoverAttachment: React.PropTypes.string,
	    popoverTargetAttachment: React.PropTypes.string,
	    popoverTargetOffset: React.PropTypes.string,
	    onChange: React.PropTypes.func.isRequired,
	    onBlur: React.PropTypes.func
	  },

	  getDefaultProps: function getDefaultProps() {
	    return {
	      weekdays: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
	      locale: "en",
	      dateFormatCalendar: "MMMM YYYY",
	      moment: moment,
	      onChange: function onChange() {},
	      disabled: false
	    };
	  },

	  getInitialState: function getInitialState() {
	    return {
	      focus: false,
	      virtualFocus: false,
	      selected: this.props.selected
	    };
	  },

	  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
	    this.setState({
	      selected: nextProps.selected
	    });
	  },

	  shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
	    return !(_.isEqual(nextProps, this.props) && _.isEqual(nextState, this.state));
	  },

	  getValue: function getValue() {
	    return this.state.selected;
	  },

	  handleFocus: function handleFocus() {
	    this.setState({
	      focus: true
	    });
	  },

	  handleBlur: function handleBlur() {
	    this.setState({ virtualFocus: false }, (function () {
	      setTimeout((function () {
	        if (!this.state.virtualFocus && typeof this.props.onBlur === "function") {
	          this.props.onBlur(this.state.selected);
	          this.hideCalendar();
	        }
	      }).bind(this), 200);
	    }).bind(this));
	  },

	  hideCalendar: function hideCalendar() {
	    setTimeout((function () {
	      this.setState({
	        focus: false
	      });
	    }).bind(this), 0);
	  },

	  handleSelect: function handleSelect(date) {
	    this.setSelected(date);

	    setTimeout((function () {
	      this.hideCalendar();
	    }).bind(this), 200);
	  },

	  setSelected: function setSelected(date) {
	    this.setState({
	      selected: date.moment(),
	      virtualFocus: true
	    }, (function () {
	      this.props.onChange(this.state.selected);
	    }).bind(this));
	  },

	  clearSelected: function clearSelected() {
	    if (this.state.selected === null) return; //Due to issues with IE onchange events sometimes this gets noisy, so skip if we've already cleared

	    this.setState({
	      selected: null
	    }, (function () {
	      this.props.onChange(null);
	    }).bind(this));
	  },

	  onInputClick: function onInputClick() {
	    this.setState({
	      focus: true,
	      virtualFocus: true
	    });
	  },

	  calendar: function calendar() {
	    if (this.state.focus) {
	      return React.createElement(
	        Popover,
	        {
	          attachment: this.props.popoverAttachment,
	          targetAttachment: this.props.popoverTargetAttachment,
	          targetOffset: this.props.popoverTargetOffset },
	        React.createElement(Calendar, {
	          weekdays: this.props.weekdays,
	          locale: this.props.locale,
	          moment: this.props.moment,
	          dateFormat: this.props.dateFormatCalendar,
	          selected: this.state.selected,
	          onSelect: this.handleSelect,
	          hideCalendar: this.hideCalendar,
	          minDate: this.props.minDate,
	          maxDate: this.props.maxDate,
	          excludeDates: this.props.excludeDates,
	          weekStart: this.props.weekStart })
	      );
	    }
	  },

	  render: function render() {
	    return React.createElement(
	      "div",
	      null,
	      React.createElement(DateInput, {
	        name: this.props.name,
	        date: this.state.selected,
	        dateFormat: this.props.dateFormat,
	        focus: this.state.focus,
	        onFocus: this.handleFocus,
	        onBlur: this.handleBlur,
	        handleClick: this.onInputClick,
	        handleEnter: this.hideCalendar,
	        setSelected: this.setSelected,
	        clearSelected: this.clearSelected,
	        hideCalendar: this.hideCalendar,
	        placeholderText: this.props.placeholderText,
	        disabled: this.props.disabled,
	        className: this.props.className,
	        title: this.props.title }),
	      this.props.disabled ? null : this.calendar()
	    );
	  }
	});

	module.exports = DatePicker;

/***/ },
/* 1 */
/***/ function(module, exports) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_1__;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	var React = __webpack_require__(1);

	var Popover = React.createClass({
	  displayName: "Popover",

	  propTypes: {
	    attachment: React.PropTypes.string,
	    targetAttachment: React.PropTypes.string,
	    targetOffset: React.PropTypes.string
	  },

	  getDefaultProps: function getDefaultProps() {
	    return {
	      attachment: "top left",
	      targetAttachment: "bottom left",
	      targetOffset: "10px 0"
	    };
	  },

	  componentWillMount: function componentWillMount() {
	    var popoverContainer = document.createElement("span");
	    popoverContainer.className = "datepicker__container";

	    this._popoverElement = popoverContainer;

	    document.querySelector("body").appendChild(this._popoverElement);
	  },

	  componentDidMount: function componentDidMount() {
	    this._renderPopover();
	  },

	  componentDidUpdate: function componentDidUpdate() {
	    this._renderPopover();
	  },

	  _popoverComponent: function _popoverComponent() {
	    var className = this.props.className;
	    return React.createElement(
	      "div",
	      { className: className },
	      this.props.children
	    );
	  },

	  _tetherOptions: function _tetherOptions() {
	    return {
	      element: this._popoverElement,
	      target: this.getDOMNode().parentElement.querySelector("input"),
	      attachment: this.props.attachment,
	      targetAttachment: this.props.targetAttachment,
	      targetOffset: this.props.targetOffset,
	      optimizations: {
	        moveElement: false // always moves to <body> anyway!
	      },
	      constraints: [{
	        to: "window",
	        attachment: "together"
	      }]
	    };
	  },

	  _renderPopover: function _renderPopover() {
	    React.render(this._popoverComponent(), this._popoverElement);

	    if (this._tether != null) {
	      this._tether.setOptions(this._tetherOptions());
	    } else if (window && document) {
	      var Tether = __webpack_require__(3);
	      this._tether = new Tether(this._tetherOptions());
	    }
	  },

	  componentWillUnmount: function componentWillUnmount() {
	    this._tether.destroy();
	    React.unmountComponentAtNode(this._popoverElement);
	    if (this._popoverElement.parentNode) {
	      this._popoverElement.parentNode.removeChild(this._popoverElement);
	    }
	  },

	  render: function render() {
	    return React.createElement("span", null);
	  }
	});

	module.exports = Popover;

/***/ },
/* 3 */
/***/ function(module, exports) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_3__;

/***/ },
/* 4 */
/***/ function(module, exports) {

	"use strict";

	function DateUtil(date) {
	  this._date = date;
	}

	DateUtil.prototype.isBefore = function (other) {
	  return this._date.isBefore(other._date, "day");
	};

	DateUtil.prototype.isAfter = function (other) {
	  return this._date.isAfter(other._date, "day");
	};

	DateUtil.prototype.sameDay = function (other) {
	  return this._date.isSame(other._date, "day");
	};

	DateUtil.prototype.sameMonth = function (other) {
	  return this._date.isSame(other._date, "month");
	};

	DateUtil.prototype.day = function () {
	  return this._date.date();
	};

	DateUtil.prototype.mapDaysInWeek = function (callback) {
	  var week = [];
	  var firstDay = this._date.clone();

	  for (var i = 0; i < 7; i++) {
	    var day = new DateUtil(firstDay.clone().add(i, "days"));

	    week[i] = callback(day, i);
	  }

	  return week;
	};

	DateUtil.prototype.mapWeeksInMonth = function (callback) {
	  var month = [];
	  var firstDay = this._date.clone().startOf("month").startOf("week");

	  for (var i = 0; i < 6; i++) {
	    var weekStart = new DateUtil(firstDay.clone().add(i, "weeks"));

	    month[i] = callback(weekStart, i);
	  }

	  return month;
	};

	DateUtil.prototype.weekInMonth = function (other) {
	  var firstDayInWeek = this._date.clone();
	  var lastDayInWeek = this._date.clone().weekday(7);

	  return firstDayInWeek.isSame(other._date, "month") || lastDayInWeek.isSame(other._date, "month");
	};

	DateUtil.prototype.format = function () {
	  return this._date.format.apply(this._date, arguments);
	};

	DateUtil.prototype.localeFormat = function () {
	  var args = Array.prototype.slice.call(arguments);
	  var locale = args.shift();
	  return this._date.locale(locale).format.apply(this._date, args);
	};

	DateUtil.prototype.addMonth = function () {
	  return new DateUtil(this._date.clone().add(1, "month"));
	};

	DateUtil.prototype.subtractMonth = function () {
	  return new DateUtil(this._date.clone().subtract(1, "month"));
	};

	DateUtil.prototype.clone = function () {
	  return new DateUtil(this._date.clone());
	};

	DateUtil.prototype.safeClone = function (alternative) {
	  if (!!this._date) return this.clone();

	  if (alternative === undefined) alternative = null;
	  return new DateUtil(alternative);
	};

	DateUtil.prototype.moment = function () {
	  return this._date;
	};

	module.exports = DateUtil;

/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	var React = __webpack_require__(1);
	var Day = __webpack_require__(6);
	var DateUtil = __webpack_require__(4);
	var _ = __webpack_require__(8);

	var Calendar = React.createClass({
	  displayName: "Calendar",

	  mixins: [__webpack_require__(9)],

	  handleClickOutside: function handleClickOutside() {
	    this.props.hideCalendar();
	  },

	  getInitialState: function getInitialState() {
	    return {
	      date: new DateUtil(this.props.selected).safeClone(this.props.moment())
	    };
	  },

	  getDefaultProps: function getDefaultProps() {
	    return {
	      weekStart: 1
	    };
	  },

	  componentWillMount: function componentWillMount() {
	    this.initializeMomentLocale();
	  },

	  componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
	    if (nextProps.selected === null) {
	      return;
	    }

	    // When the selected date changed
	    if (nextProps.selected !== this.props.selected) {
	      this.setState({
	        date: new DateUtil(nextProps.selected).clone()
	      });
	    }
	  },

	  initializeMomentLocale: function initializeMomentLocale() {
	    var weekdays = this.props.weekdays.slice(0);
	    weekdays = weekdays.concat(weekdays.splice(0, this.props.weekStart));

	    this.props.moment.locale(this.props.locale, {
	      week: {
	        dow: this.props.weekStart
	      },
	      weekdaysMin: weekdays
	    });
	  },

	  increaseMonth: function increaseMonth() {
	    this.setState({
	      date: this.state.date.addMonth()
	    });
	  },

	  decreaseMonth: function decreaseMonth() {
	    this.setState({
	      date: this.state.date.subtractMonth()
	    });
	  },

	  weeks: function weeks() {
	    return this.state.date.mapWeeksInMonth(this.renderWeek);
	  },

	  handleDayClick: function handleDayClick(day) {
	    this.props.onSelect(day);
	  },

	  renderWeek: function renderWeek(weekStart, key) {
	    if (!weekStart.weekInMonth(this.state.date)) {
	      return;
	    }

	    return React.createElement(
	      "div",
	      { key: key },
	      this.days(weekStart)
	    );
	  },

	  renderDay: function renderDay(day, key) {
	    var minDate = new DateUtil(this.props.minDate).safeClone(),
	        maxDate = new DateUtil(this.props.maxDate).safeClone(),
	        excludeDates,
	        disabled;

	    if (this.props.excludeDates && Array.isArray(this.props.excludeDates)) {
	      excludeDates = _(this.props.excludeDates).map(function (date) {
	        return new DateUtil(date).safeClone();
	      });
	    }

	    disabled = day.isBefore(minDate) || day.isAfter(maxDate) || _(excludeDates).some(function (xDay) {
	      return day.sameDay(xDay);
	    });

	    return React.createElement(Day, {
	      key: key,
	      day: day,
	      date: this.state.date,
	      onClick: this.handleDayClick.bind(this, day),
	      selected: new DateUtil(this.props.selected),
	      disabled: disabled });
	  },

	  days: function days(weekStart) {
	    return weekStart.mapDaysInWeek(this.renderDay);
	  },

	  header: function header() {
	    return this.props.moment.weekdaysMin().map(function (day, key) {
	      return React.createElement(
	        "div",
	        { className: "datepicker__day", key: key },
	        day
	      );
	    });
	  },

	  render: function render() {
	    return React.createElement(
	      "div",
	      { className: "datepicker" },
	      React.createElement("div", { className: "datepicker__triangle" }),
	      React.createElement(
	        "div",
	        { className: "datepicker__header" },
	        React.createElement("a", { className: "datepicker__navigation datepicker__navigation--previous",
	          onClick: this.decreaseMonth }),
	        React.createElement(
	          "span",
	          { className: "datepicker__current-month" },
	          this.state.date.localeFormat(this.props.locale, this.props.dateFormat)
	        ),
	        React.createElement("a", { className: "datepicker__navigation datepicker__navigation--next",
	          onClick: this.increaseMonth }),
	        React.createElement(
	          "div",
	          null,
	          this.header()
	        )
	      ),
	      React.createElement(
	        "div",
	        { className: "datepicker__month" },
	        this.weeks()
	      )
	    );
	  }
	});

	module.exports = Calendar;

/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	var React = __webpack_require__(1);
	var moment = __webpack_require__(7);

	var Day = React.createClass({
	  displayName: "Day",

	  handleClick: function handleClick(event) {
	    if (this.props.disabled) return;

	    this.props.onClick(event);
	  },

	  isWeekend: function isWeekend() {
	    var weekday = this.props.day.moment().weekday();
	    return weekday === 5 || weekday === 6;
	  },

	  render: function render() {
	    var classes = ["datepicker__day"];

	    if (this.props.disabled) classes.push("datepicker__day--disabled");

	    if (this.props.day.sameDay(this.props.selected)) classes.push("datepicker__day--selected");

	    if (this.props.day.sameDay(moment())) classes.push("datepicker__day--today");

	    if (this.isWeekend()) {
	      classes.push("datepicker__day--weekend");
	    }

	    return React.createElement(
	      "div",
	      { className: classes.join(" "), onClick: this.handleClick },
	      this.props.day.day()
	    );
	  }
	});

	module.exports = Day;

/***/ },
/* 7 */
/***/ function(module, exports) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_7__;

/***/ },
/* 8 */
/***/ function(module, exports) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_8__;

/***/ },
/* 9 */
/***/ function(module, exports) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_9__;

/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	var React = __webpack_require__(1);
	var DateUtil = __webpack_require__(4);
	var moment = __webpack_require__(7);

	var DateInput = React.createClass({
	  displayName: "DateInput",

	  getDefaultProps: function getDefaultProps() {
	    return {
	      dateFormat: "YYYY-MM-DD",
	      className: "datepicker__input",
	      onBlur: function onBlur() {}
	    };
	  },

	  componentDidMount: function componentDidMount() {
	    this.toggleFocus(this.props.focus);
	  },

	  componentWillReceiveProps: function componentWillReceiveProps(newProps) {
	    this.toggleFocus(newProps.focus);
	  },

	  toggleFocus: function toggleFocus(focus) {
	    if (focus) {
	      React.findDOMNode(this.refs.input).focus();
	    } else {
	      React.findDOMNode(this.refs.input).blur();
	    }
	  },

	  handleChange: function handleChange(event) {
	    var value = event.target.value;
	    var date = moment(value, this.props.dateFormat, true);

	    if (date.isValid()) {
	      this.props.setSelected(new DateUtil(date));
	    } else if (value === "") {
	      this.props.clearSelected();
	    }
	  },

	  safeDateFormat: function safeDateFormat(date) {
	    return !!date ? date.format(this.props.dateFormat) : null;
	  },

	  handleKeyDown: function handleKeyDown(event) {
	    switch (event.key) {
	      case "Enter":
	        event.preventDefault();
	        this.props.handleEnter();
	        break;
	      case "Escape":
	        event.preventDefault();
	        this.props.hideCalendar();
	        break;
	    }
	  },

	  handleClick: function handleClick(event) {
	    if (!this.props.disabled) {
	      this.props.handleClick(event);
	    }
	  },

	  render: function render() {
	    return React.createElement("input", {
	      ref: "input",
	      type: "text",
	      name: this.props.name,
	      value: this.safeDateFormat(this.props.date),
	      onClick: this.handleClick,
	      onKeyDown: this.handleKeyDown,
	      onFocus: this.props.onFocus,
	      onBlur: this.props.onBlur,
	      onChange: this.handleChange,
	      className: this.props.className,
	      disabled: this.props.disabled,
	      placeholder: this.props.placeholderText });
	  }
	});

	module.exports = DateInput;

/***/ }
/******/ ])
});
;


text:
"""
A module for effectively caching the public keys of various token issuer endpoints.
"""

import os
import sqlite3
import time
import pkg_resources  # part of setuptools
import re
import logging
try:
    PKG_VERSION = pkg_resources.require("scitokens")[0].version
except pkg_resources.DistributionNotFound as error:
    # During testing, scitokens won't be installed, so requiring it will fail
    # Instead, fake it
    PKG_VERSION = '1.0.0'

try:
    import urllib.request as request
except ImportError:
    import urllib2 as request

try:
    import urlparse
except ImportError:
    import urllib.parse as urlparse

import json

from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_public_key
import cryptography.hazmat.backends as backends
import cryptography.hazmat.primitives.asymmetric.ec as ec
import cryptography.hazmat.primitives.asymmetric.rsa as rsa
from scitokens.utils.errors import SciTokensException, MissingKeyException, NonHTTPSIssuer, UnableToCreateCache, UnsupportedKeyException
from scitokens.utils import long_from_bytes
import scitokens.utils.config as config

CACHE_FILENAME = "scitokens_keycache.sqllite"
KEYCACHE_INSTANCE = None

class UnableToWriteKeyCache(SciTokensException):
    """
    For whatever reason, unable to write to the Key Cache
    """
    pass

class KeyCache(object):
    """
    Object that persistently caches signing keys associated with a token issuer endpoint.
    """

    def __init__(self):
        # Check for the cache
        self.cache_location = self._get_cache_file()

    @staticmethod
    def getinstance():
        """
        Return the singleton instance of the KeyCache.
        """
        global KEYCACHE_INSTANCE
        if KEYCACHE_INSTANCE is None:
            KEYCACHE_INSTANCE = KeyCache()
        return KEYCACHE_INSTANCE

    def addkeyinfo(self, issuer, key_id, public_key, cache_timer=0, next_update=0):
        """
        Add a single, known public key to the cache.

        :param str issuer: URI of the issuer
        :param str key_id: Key Identifier
        :param public_key: Cryptography public_key object
        :param int cache_timer: Cache lifetime of the public_key
        :param int next_update: Seconds until next update time
        """

        # If the next_update is 0, then set it to 1 hour
        if next_update == 0:
            next_update = 3600

        conn = sqlite3.connect(self.cache_location)
        conn.row_factory = sqlite3.Row
        curs = conn.cursor()
        curs.execute("DELETE FROM keycache WHERE issuer = '{}' AND key_id = '{}'".format(issuer, key_id))
        KeyCache._addkeyinfo(curs, issuer, key_id, public_key, cache_timer=cache_timer, next_update=next_update)
        conn.commit()
        conn.close()

    @staticmethod
    def _addkeyinfo(curs, issuer, key_id, public_key, cache_timer=0, next_update=0):
        """
        Given an open database cursor to a key cache, insert a key.
        """
        # Add the key to the cache
        insert_key_statement = "INSERT INTO keycache VALUES('{issuer}', '{expiration}', '{key_id}', \
                               '{keydata}', '{next_update}')"
        keydata = {
            'pub_key': public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode('ascii'),
        }

        curs.execute(insert_key_statement.format(issuer=issuer, expiration=time.time()+cache_timer, key_id=key_id,
                                                 keydata=json.dumps(keydata), next_update=time.time()+next_update))
        if curs.rowcount != 1:
            raise UnableToWriteKeyCache("Unable to insert into key cache")

    def _parse_key_data(self, issuer, kid, keydata):
        """
        Keydata is stored as a JSON object inside the DB.  Therefore, we must extract it.

        :param str issuer: Token Issuer in keydata
        :param str kid: Key ID
        :param str keydata: Raw JSON key data (at least, it should be)
        :param curs: SQLite cursor, in case it has to delete the row

        :returns str: encoded public key, otherwise None
        """

        # First, get the key data
        try:
            return json.loads(keydata)['pub_key']
        except ValueError:
            logging.exception("Unable to parse JSON stored in keycache.  "
                              "This likely means the database format needs"
                              "to be updated, which we will now do automatically")

            self._delete_cache_entry(issuer, kid)
            return None

    def _delete_cache_entry(self, issuer, key_id):
        """
        Delete a cache entry
        """
        # Open the connection to the database
        conn = sqlite3.connect(self.cache_location)
        curs = conn.cursor()
        curs.execute("DELETE FROM keycache WHERE issuer = '{}' AND key_id = '{}'".format(issuer,
                     key_id))
        conn.commit()
        conn.close()

    def getkeyinfo(self, issuer, key_id=None, insecure=False):
        """
        Get the key information

        :param str issuer: The issuer URI
        :param str key_id: Text key id to identify the key
        :param bool insecure: Whether insecure methods are acceptable (defaults to False).
        :returns: None if no key is found.  Else, returns the public key
        """
        # Check the sql database
        key_query = ("SELECT * FROM keycache WHERE "
                     "issuer = '{issuer}'")
        if key_id != None:
            key_query += " AND key_id = '{key_id}'"
        conn = sqlite3.connect(self.cache_location)
        conn.row_factory = sqlite3.Row
        curs = conn.cursor()
        curs.execute(key_query.format(issuer=issuer, key_id=key_id))

        row = curs.fetchone()
        conn.commit()
        conn.close()
        if row != None:
            # If it's time to update the key, but the key is still valid
            if int(row['next_update']) < time.time() and self._check_validity(row):
                # Try to update the key, but if it doesn't work, just return the saved one
                try:
                    # Get the public key, probably from a webserver
                    public_key, cache_timer = self._get_issuer_publickey(issuer, key_id, insecure)

                    # Get the sqllite connection again
                    self.addkeyinfo(issuer, key_id, public_key, cache_timer)
                    return public_key
                except Exception as ex:
                    logger = logging.getLogger("scitokens")
                    logger.warning("Unable to get key triggered by next update: {0}".format(str(ex)))
                    keydata = self._parse_key_data(row['issuer'], row['key_id'], row['keydata'])
                    # Upgrade proof
                    if keydata:
                        return load_pem_public_key(keydata.encode(), backend=backends.default_backend())

            # If it's not time to update the key, but the key is still valid
            elif self._check_validity(row):
                keydata = self._parse_key_data(row['issuer'], row['key_id'], row['keydata'])
                if keydata:
                    return load_pem_public_key(keydata.encode(), backend=backends.default_backend())

                # update the keycache
                public_key, cache_timer = self._get_issuer_publickey(issuer, key_id, insecure)
                self.addkeyinfo(issuer, key_id, public_key, cache_timer)
                return public_key

            # If it's not time to update the key, and the key is not valid
            else:

                # Delete the row
                # If it gets to this point, then there is a row for the key, but it's:
                # - Not valid anymore
                self._delete_cache_entry(row['issuer'], row['key_id'])

        # If it reaches here, then no key was found in the SQL
        # Try checking the issuer (negative cache?)
        public_key, cache_timer = self._get_issuer_publickey(issuer, key_id, insecure)
        self.addkeyinfo(issuer, key_id, public_key, cache_timer)

        return public_key

    @classmethod
    def _check_validity(cls, key_info):
        """
        Check the key to see if it has expired
        """
        # Make sure the key hasn't expired
        if key_info['expiration'] <= time.time():
            return False
        else:
            return True

    @staticmethod
    def _get_issuer_publickey(issuer, key_id=None, insecure=False):
        """
        :return: Tuple containing (public_key, cache_lifetime).  Cache_lifetime how
            the public key is valid
        """

        # Set the user agent so Cloudflare isn't mad at us
        headers={'User-Agent' : 'SciTokens/{}'.format(PKG_VERSION)}

        # Go to the issuer's website, and download the OAuth well known bits
        # https://tools.ietf.org/html/draft-ietf-oauth-discovery-07
        well_known_uri = ".well-known/openid-configuration"
        if not issuer.endswith("/"):
            issuer = issuer + "/"
        parsed_url = urlparse.urlparse(issuer)
        updated_url = urlparse.urljoin(parsed_url.path, well_known_uri)
        parsed_url_list = list(parsed_url)
        parsed_url_list[2] = updated_url
        meta_uri = urlparse.urlunparse(parsed_url_list)

        # Make sure the protocol is https
        if not insecure:
            parsed_url = urlparse.urlparse(meta_uri)
            if parsed_url.scheme != "https":
                raise NonHTTPSIssuer("Issuer is not over HTTPS.  RFC requires it to be over HTTPS")
        response = request.urlopen(request.Request(meta_uri, headers=headers))
        data = json.loads(response.read().decode('utf-8'))

        # Get the keys URL from the openid-configuration
        jwks_uri = data['jwks_uri']

        # Now, get the keys
        if not insecure:
            parsed_url = urlparse.urlparse(jwks_uri)
            if parsed_url.scheme != "https":
                raise NonHTTPSIssuer("jwks_uri is not over HTTPS, insecure!")
        response = request.urlopen(request.Request(jwks_uri, headers=headers))

        # Get the cache data from the headers
        cache_timer = 0
        headers = response.info()
        if "Cache-Control" in headers:
            # Parse out the max-age, if it's there.
            if "max-age" in headers['Cache-Control']:
                match = re.search(r".*max-age=(\d+)", headers['Cache-Control'])
                if match:
                    cache_timer = int(match.group(1))
        # Minimum cache time of 10 minutes, no matter what the remote says
        cache_timer = max(cache_timer, config.get_int("cache_lifetime"))

        keys_data = json.loads(response.read().decode('utf-8'))
        # Loop through each key, looking for the right key id
        public_key = ""
        raw_key = None

        # If there is no kid in the header, then just take the first key?
        if key_id == None:
            if len(keys_data['keys']) != 1:
                raise NotImplementedError("No kid in header, but multiple keys in "
                                          "response from certs server.  Don't know which key to use!")
            else:
                raw_key = keys_data['keys'][0]
        else:
            # Find the right key
            for key in keys_data['keys']:
                if key['kid'] == key_id:
                    raw_key = key
                    break

        if raw_key == None:
            raise MissingKeyException("Unable to find key at issuer {}".format(jwks_uri))

        if raw_key['kty'] == "RSA":
            public_key_numbers = rsa.RSAPublicNumbers(
                long_from_bytes(raw_key['e']),
                long_from_bytes(raw_key['n'])
            )
            public_key = public_key_numbers.public_key(backends.default_backend())
        elif raw_key['kty'] == 'EC':
            public_key_numbers = ec.EllipticCurvePublicNumbers(
                   long_from_bytes(raw_key['x']),
                   long_from_bytes(raw_key['y']),
                   ec.SECP256R1()
               )
            public_key = public_key_numbers.public_key(backends.default_backend())
        else:
            raise UnsupportedKeyException("SciToken signed with an unsupported key type")

        return public_key, cache_timer

    def _get_cache_file(self):
        """
        Get the Cache file location

        1. Configuration cache location
        2. $XDG_CACHE_HOME
        3. .cache subdirectory of home directory as returned by the password database
        """

        config_cache_location = config.get('cache_location')
        xdg_cache_home = os.environ.get("XDG_CACHE_HOME", None)
        home_dir = os.path.expanduser("~")

        if config_cache_location != "":
            cache_dir = config_cache_location
        elif xdg_cache_home != None:
            cache_dir = xdg_cache_home
        elif home_dir != None:
            cache_dir = os.path.join(home_dir, ".cache")

        if not os.path.exists(cache_dir):
            try:
                os.makedirs(cache_dir)
            except OSError as ose:
                raise UnableToCreateCache("Unable to create cache: {}".format(str(ose)))

        keycache_dir = os.path.join(cache_dir, "scitokens")
        if not os.path.exists(keycache_dir):
            os.makedirs(keycache_dir)

        keycache_file = os.path.join(keycache_dir, CACHE_FILENAME)
        if not os.path.exists(keycache_file):
            self._initialize_cachedb(keycache_file)

        return keycache_file

    @staticmethod
    def _initialize_cachedb(sql_file):
        """
        Create a simple flat sqllite cache
        """
        conn = sqlite3.connect(sql_file)
        curs = conn.cursor()

        # Create cache table
        curs.execute ("CREATE TABLE keycache ("
                      "issuer text NOT NULL,"
                      "expiration integer NOT NULL,"
                      "key_id text,"
                      "keydata text NOT NULL,"
                      "next_update integer NOT NULL,"
                      "PRIMARY KEY (issuer, key_id))")
        # Save (commit) the changes
        conn.commit()

        # We can also close the connection if we are done with it.
        # Just be sure any changes have been committed or they will be lost.
        conn.close()


text:
import { MeasurementApi } from 'meteor/lesiontracker/client/api/measurement';

Template.lesionTable.onCreated(() => {
    const instance = Template.instance();

    instance.data.lesionTableLayout = new ReactiveVar('comparison');
    instance.data.timepoints = new ReactiveVar([]);

    // Run this computation every time table layout changes
    instance.autorun(() => {
        // Get the current table layout
        const tableLayout = instance.data.lesionTableLayout.get();

        let timepoints;
        if (tableLayout === 'key') {
            timepoints = instance.data.timepointApi.key();
        } else {
            timepoints = instance.data.timepointApi.currentAndPrior();
        }

        // Return key timepoints
        instance.data.timepoints.set(timepoints);
    });
});

Template.lesionTable.onRendered(() => {
    const instance = Template.instance();

    instance.autorun(() => {
        // Run this computation every time the lesion table layout is changed
        instance.data.lesionTableLayout.dep.depend();

        if (instance.data.state.get('rightSidebar') !== 'lesions') {
            // Remove the amount attribute from sidebar element tag
            instance.$('#lesionTableContainer').closest('.sidebarMenu').removeAttr('data-timepoints');
            return;
        }

        // Get the amount of timepoints being shown
        const timepointAmount = instance.data.timepoints.get().length;

        // Set the amount in an attribute on sidebar element tag
        instance.$('#lesionTableContainer').closest('.sidebarMenu').attr('data-timepoints', timepointAmount);
    });
});

// Temporary until we have a real window manager with events for series/study changed
Session.setDefault('NewSeriesLoaded', false);

Template.lesionTable.onRendered(() => {
    // Find the first measurement by Lesion Number
    const firstLesion = MeasurementApi.firstLesion();

    // Create an object to store the ContentId inside
    const templateData = {
        contentId: Session.get('activeContentId')
    };

    // Activate the first lesion
    if (firstLesion) {
        activateLesion(firstLesion._id, templateData);
    }
});

Template.lesionTable.events({
    /**
     * Retrieve the lesion id from the DOM data for this row
     */
    /*'click table#tblLesion tbody tr': function(e, template) {
          var measurementId = $(e.currentTarget).data('measurementid');
          activateLesion(measurementId, template.data);
    },*/
});

Template.lesionTable.helpers({
    buttonGroupData() {
        const instance = Template.instance();
        return {
            value: instance.data.lesionTableLayout,
            options: [{
                value: 'comparison',
                text: 'Comparison'
            }, {
                value: 'key',
                text: 'Key Timepoints'
            }]
        };
    }
});


text:
class AccessToken < ApplicationRecord
  TOKEN_LIST_KEY = 'access-token-list'
  TOKEN_LIMIT = 100

  paginates_per 50

  belongs_to :user
end


text:
package router

import (
	"net/http"
	"sync"

	"knative.dev/eventing-github/pkg/client/listers/sources/v1alpha1"
)

// keyedHandler associates a http.Handler to a source object identified by
// namespace/name.
type keyedHandler struct {
	handler   http.Handler
	namespace string
	name      string
}

// Router is a GitHub webhook router which delegates webhook events received
// over HTTP to sub-routers.
type Router struct {
	routersMu sync.RWMutex
	routers   map[string]keyedHandler

	lister v1alpha1.GitHubSourceLister
}

// Check that Router implements http.Handler.
var _ http.Handler = (*Router)(nil)

// New returns a new Router.
func New(lister v1alpha1.GitHubSourceLister) *Router {
	return &Router{
		routers: make(map[string]keyedHandler),
		lister:  lister,
	}
}

// ServeHTTP implements http.Handler.
func (h *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Path-based dispatch
	h.routersMu.RLock()
	keyedHandler, ok := h.routers[r.URL.Path]
	h.routersMu.RUnlock()

	if ok {
		// Check if source still exists.
		_, err := h.lister.GitHubSources(keyedHandler.namespace).Get(keyedHandler.name)
		if err == nil {
			keyedHandler.handler.ServeHTTP(w, r)
			return
		}

		h.Unregister(r.URL.Path)
	}
	http.NotFoundHandler().ServeHTTP(w, r)
}

// Register adds a new GitHub event handler for the given GitHubSource.
func (h *Router) Register(name, namespace, path string, handler http.Handler) {
	h.routersMu.Lock()
	defer h.routersMu.Unlock()
	h.routers[path] = keyedHandler{
		handler:   handler,
		namespace: namespace,
		name:      name,
	}
}

// Unregister removes the GitHubSource served at the given path.
func (h *Router) Unregister(path string) {
	h.routersMu.Lock()
	defer h.routersMu.Unlock()
	delete(h.routers, path)
}


text:
package assert

import "testing"

func TestLe(t *testing.T) {
	{
		err := AssertThat(2, Le(3))
		if err != nil {
			t.Fatal("expect nil")
		}
	}
	{
		err := AssertThat(3, Le(3))
		if err != nil {
			t.Fatal("expect nil")
		}
	}
	{
		err := AssertThat(3, Le(2))
		if err == nil {
			t.Fatal("expect nil")
		}
	}
	{
		err := AssertThat(3, Le(2))
		expectedValue := "expected <3> is less or equal than <2>"
		if err.Error() != expectedValue {
			t.Fatalf("error message missmatch, expected '%v' but was '%v'", expectedValue, err.Error())
		}
	}
	{
		err := AssertThat(3, Le(2).Message("msg"))
		expectedValue := "msg, expected <3> is less or equal than <2>"
		if err.Error() != expectedValue {
			t.Fatalf("error message missmatch, expected '%v' but was '%v'", expectedValue, err.Error())
		}
	}
	{
		err := AssertThat(2.1, Le(3))
		expectedValue := "expected type int but got float64"
		if err.Error() != expectedValue {
			t.Fatalf("error message missmatch, expected '%v' but was '%v'", expectedValue, err.Error())
		}
	}
	{
		err := AssertThat(2.1, Le(3).Message("msg"))
		expectedValue := "msg, expected type int but got float64"
		if err.Error() != expectedValue {
			t.Fatalf("error message missmatch, expected '%v' but was '%v'", expectedValue, err.Error())
		}
	}
}


text:
require 'spec_helper'

module Uploadcare
  module Entity
    RSpec.describe Uploader do
      subject { Uploadcare::Entity::Uploader }
      let!(:file) { ::File.open('spec/fixtures/kitten.jpeg') }
      let!(:another_file) { ::File.open('spec/fixtures/another_kitten.jpeg') }
      let!(:big_file) { ::File.open('spec/fixtures/big.jpeg') }

      describe 'upload_many' do
        it 'returns a hash of filenames and uids', :aggregate_failures do
          VCR.use_cassette('upload_upload_many') do
            uploads_list = subject.upload([file, another_file])
            expect(uploads_list.length).to eq 2
            first_upload = uploads_list.first
            expect(first_upload.original_filename).not_to be_empty
            expect(first_upload.uuid).not_to be_empty
          end
        end

        describe 'upload_one' do
          it 'returns a file', :aggregate_failures do
            VCR.use_cassette('upload_upload_one') do
              upload = subject.upload(file)
              expect(upload).to be_kind_of(Uploadcare::Entity::File)
              expect(upload.size).to eq(file.size)
            end
          end
        end

        describe 'upload_from_url' do
          it 'polls server and returns array of files' do
            VCR.use_cassette('upload_upload_from_url') do
              url = 'https://placekitten.com/2250/2250'
              upload = subject.upload(url)
              expect(upload[0]).to be_kind_of(Uploadcare::Entity::File)
            end
          end
        end

        describe 'multipart_upload' do
          let!(:some_var) { nil }

          it 'uploads a file', :aggregate_failures do
            VCR.use_cassette('upload_multipart_upload') do
              # Minimal size for file to be valid for multipart upload is 10 mb
              Uploadcare.config.multipart_size_threshold = 10 * 1024 * 1024
              expect(some_var).to receive(:to_s).at_least(:once)
              file = subject.multipart_upload(big_file) { some_var.to_s }
              expect(file).to be_kind_of(Uploadcare::Entity::File)
              expect(file.uuid).not_to be_empty
            end
          end
        end

        describe 'get_upload_from_url_status' do
          it 'gets a status of upload-from-URL' do
            VCR.use_cassette('upload_get_upload_from_url_status') do
              token = 'c6e31082-6bdc-4cb1-bef5-14dd10574d73'
              status_info = subject.get_upload_from_url_status(token).success
              expect(status_info[:status]).to eq 'success'
            end
          end
        end
      end
    end
  end
end


text:
/* eslint-disable no-undef */
import React from 'react';
import Select from '../../src/Select';
import Option from '../../src/Option';
import { shallow, render } from 'enzyme';

export default function maxTagTextLengthTest(mode) {
  describe('render', () => {
    it('truncates values by maxTagTextLength', () => {
      const wrapper = render(
        <Select
          {...{ [mode]: true } }
          value={['one', 'two']}
          maxTagTextLength={2}
        >
          <Option value="one">One</Option>
          <Option value="two">Two</Option>
        </Select>
      );

      expect(wrapper).toMatchSnapshot();
    });

    it('truncates tags by maxTagCount', () => {
      const wrapper = render(
        <Select
          {...{ [mode]: true } }
          value={['one', 'two', 'three']}
          maxTagCount={2}
        >
          <Option value="one">One</Option>
          <Option value="two">Two</Option>
          <Option value="three">Three</Option>
        </Select>
      );

      expect(wrapper).toMatchSnapshot();
    });

    it('render animation', () => {
      const wrapper = shallow(
        <Select
          {...{ [mode]: true } }
          choiceTransitionName="slide-up"
        >
          <Option value="1">1</Option>
          <Option value="2">2</Option>
        </Select>
      );

      expect(wrapper).toMatchSnapshot();
    });
  });
}