text:
import * as path from 'path';
import * as ts from 'typescript';
import {AotPlugin} from './plugin';
import {TypeScriptFileRefactor} from './refactor';
import {LoaderContext, ModuleReason} from './webpack';

interface Platform {
  name: string;
  importLocation: string;
}

const loaderUtils = require('loader-utils');
const NormalModule = require('webpack/lib/NormalModule');

// This is a map of changes which need to be made
const changeMap: {[key: string]: Platform} = {
  platformBrowserDynamic: {
    name: 'platformBrowser',
    importLocation: '@angular/platform-browser'
  },
  platformDynamicServer: {
    name: 'platformServer',
    importLocation: '@angular/platform-server'
  }
};

function _getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string {
  if (!node) {
    return null;
  } else if (node.kind == ts.SyntaxKind.Identifier) {
    return (node as ts.Identifier).text;
  } else if (node.kind == ts.SyntaxKind.StringLiteral) {
    return (node as ts.StringLiteral).text;
  } else {
    return null;
  }
}

function _angularImportsFromNode(node: ts.ImportDeclaration, _sourceFile: ts.SourceFile): string[] {
  const ms = node.moduleSpecifier;
  let modulePath: string | null = null;
  switch (ms.kind) {
    case ts.SyntaxKind.StringLiteral:
      modulePath = (ms as ts.StringLiteral).text;
      break;
    default:
      return [];
  }

  if (!modulePath.startsWith('@angular/')) {
    return [];
  }

  if (node.importClause) {
    if (node.importClause.name) {
      // This is of the form `import Name from 'path'`. Ignore.
      return [];
    } else if (node.importClause.namedBindings) {
      const nb = node.importClause.namedBindings;
      if (nb.kind == ts.SyntaxKind.NamespaceImport) {
        // This is of the form `import * as name from 'path'`. Return `name.`.
        return [(nb as ts.NamespaceImport).name.text + '.'];
      } else {
        // This is of the form `import {a,b,c} from 'path'`
        const namedImports = nb as ts.NamedImports;

        return namedImports.elements
          .map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text);
      }
    }
  } else {
    // This is of the form `import 'path';`. Nothing to do.
    return [];
  }
}

function _ctorParameterFromTypeReference(paramNode: ts.ParameterDeclaration,
                                         angularImports: string[],
                                         refactor: TypeScriptFileRefactor) {
  let typeName = 'undefined';

  if (paramNode.type) {
    switch (paramNode.type.kind) {
      case ts.SyntaxKind.TypeReference:
        const type = paramNode.type as ts.TypeReferenceNode;
        if (type.typeName) {
          typeName = type.typeName.getText(refactor.sourceFile);
        } else {
          typeName = type.getText(refactor.sourceFile);
        }
        break;
      case ts.SyntaxKind.AnyKeyword:
        typeName = 'undefined';
        break;
      default:
        typeName = 'null';
    }
  }

  const decorators = refactor.findAstNodes(paramNode, ts.SyntaxKind.Decorator) as ts.Decorator[];
  const decoratorStr = decorators
    .map(decorator => {
      const call =
        refactor.findFirstAstNode(decorator, ts.SyntaxKind.CallExpression) as ts.CallExpression;

      if (!call) {
        return null;
      }

      const fnName = call.expression.getText(refactor.sourceFile);
      const args = call.arguments.map(x => x.getText(refactor.sourceFile)).join(', ');
      if (angularImports.indexOf(fnName) === -1) {
        return null;
      } else {
        return [fnName, args];
      }
    })
    .filter(x => !!x)
    .map(([name, args]: string[]) => {
      if (args) {
        return `{ type: ${name}, args: [${args}] }`;
      }
      return `{ type: ${name} }`;
    })
    .join(', ');

  if (decorators.length > 0) {
    return `{ type: ${typeName}, decorators: [${decoratorStr}] }`;
  }
  return `{ type: ${typeName} }`;
}

function _addCtorParameters(classNode: ts.ClassDeclaration,
                            angularImports: string[],
                            refactor: TypeScriptFileRefactor) {
  // For every classes with constructors, output the ctorParameters function which contains a list
  // of injectable types.
  const ctor = (
    refactor.findFirstAstNode(classNode, ts.SyntaxKind.Constructor) as ts.ConstructorDeclaration);
  if (!ctor) {
    // A class can be missing a constructor, and that's _okay_.
    return;
  }

  const params = Array.from(ctor.parameters).map(paramNode => {
    return _ctorParameterFromTypeReference(paramNode, angularImports, refactor);
  });

  const ctorParametersDecl = `static ctorParameters() { return [ ${params.join(', ')} ]; }`;
  refactor.prependBefore(classNode.getLastToken(refactor.sourceFile), ctorParametersDecl);
}

function _removeDecorators(refactor: TypeScriptFileRefactor) {
  const angularImports: string[]
    = refactor.findAstNodes(refactor.sourceFile, ts.SyntaxKind.ImportDeclaration)
      .map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, refactor.sourceFile))
      .reduce((acc: string[], current: string[]) => acc.concat(current), []);

  // Find all decorators.
  refactor.findAstNodes(refactor.sourceFile, ts.SyntaxKind.Decorator)
    .forEach(node => {
      // First, add decorators to classes to the classes array.
      if (node.parent) {
        const declarations = refactor.findAstNodes(node.parent,
          ts.SyntaxKind.ClassDeclaration, false, 1);
        if (declarations.length > 0) {
          _addCtorParameters(declarations[0] as ts.ClassDeclaration, angularImports, refactor);
        }
      }

      refactor.findAstNodes(node, ts.SyntaxKind.CallExpression)
        .filter((node: ts.CallExpression) => {
          const fnName = node.expression.getText(refactor.sourceFile);
          if (fnName.indexOf('.') != -1) {
            // Since this is `a.b`, see if it's the same namespace as a namespace import.
            return angularImports.indexOf(fnName.replace(/\..*$/, '') + '.') != -1;
          } else {
            return angularImports.indexOf(fnName) != -1;
          }
        })
        .forEach(() => refactor.removeNode(node));
    });
}

function _getNgFactoryPath(plugin: AotPlugin, refactor: TypeScriptFileRefactor) {
  // Calculate the base path.
  const basePath = path.normalize(plugin.basePath);
  const genDir = path.normalize(plugin.genDir);
  const dirName = path.normalize(path.dirname(refactor.fileName));
  const entryModule = plugin.entryModule;
  const entryModuleFileName = path.normalize(entryModule.path + '.ngfactory');
  const relativeEntryModulePath = path.relative(basePath, entryModuleFileName);
  const fullEntryModulePath = path.resolve(genDir, relativeEntryModulePath);
  const relativeNgFactoryPath = path.relative(dirName, fullEntryModulePath);
  return './' + relativeNgFactoryPath.replace(/\\/g, '/');
}

function _replacePlatform(
  refactor: TypeScriptFileRefactor, bootstrapCall: ts.PropertyAccessExpression) {
  const platforms = (refactor.findAstNodes(bootstrapCall,
    ts.SyntaxKind.CallExpression, true) as ts.CallExpression[])
    .filter(call => {
      return call.expression.kind == ts.SyntaxKind.Identifier;
    })
    .filter(call => !!changeMap[(call.expression as ts.Identifier).text]);

  platforms.forEach(call => {
    const platform = changeMap[(call.expression as ts.Identifier).text];

    // Replace with mapped replacement
    refactor.replaceNode(call.expression, platform.name);

    // Add the appropriate import
    refactor.insertImport(platform.name, platform.importLocation);
  });
}

function _replaceBootstrapOrRender(refactor: TypeScriptFileRefactor, call: ts.CallExpression) {
  // If neither bootstrapModule or renderModule can't be found, bail out early.
  let replacementTarget: string;
  let identifier: ts.Identifier;
  if (call.getText().includes('bootstrapModule')) {
    if (call.expression.kind != ts.SyntaxKind.PropertyAccessExpression) {
      return;
    }

    replacementTarget = 'bootstrapModule';
    const access = call.expression as ts.PropertyAccessExpression;
    identifier = access.name;
    _replacePlatform(refactor, access);

  } else if (call.getText().includes('renderModule')) {
    if (call.expression.kind != ts.SyntaxKind.Identifier) {
      return;
    }

    replacementTarget = 'renderModule';
    identifier = call.expression as ts.Identifier;
    refactor.insertImport('renderModuleFactory', '@angular/platform-server');
  }

  if (identifier && identifier.text === replacementTarget) {
    refactor.replaceNode(identifier, replacementTarget + 'Factory');
  }
}

function _getCaller(node: ts.Node): ts.CallExpression {
  while (node = node.parent) {
    if (node.kind === ts.SyntaxKind.CallExpression) {
      return node as ts.CallExpression;
    }
  }
  return null;
}

function _replaceEntryModule(plugin: AotPlugin, refactor: TypeScriptFileRefactor) {
  const modules = refactor.findAstNodes(refactor.sourceFile, ts.SyntaxKind.Identifier, true)
    .filter(identifier => identifier.getText() === plugin.entryModule.className)
    .filter(identifier =>
      identifier.parent.kind === ts.SyntaxKind.CallExpression ||
      identifier.parent.kind === ts.SyntaxKind.PropertyAssignment)
    .filter(node => !!_getCaller(node));

  if (modules.length == 0) {
    return;
  }

  const factoryClassName = plugin.entryModule.className + 'NgFactory';

  refactor.insertImport(factoryClassName, _getNgFactoryPath(plugin, refactor));

  modules
    .forEach(reference => {
      refactor.replaceNode(reference, factoryClassName);
      const caller = _getCaller(reference);
      _replaceBootstrapOrRender(refactor, caller);
    });
}

function _refactorBootstrap(plugin: AotPlugin, refactor: TypeScriptFileRefactor) {
  const genDir = path.normalize(plugin.genDir);
  const dirName = path.normalize(path.dirname(refactor.fileName));

  // Bail if in the generated directory
  if (dirName.startsWith(genDir)) {
    return;
  }

  _replaceEntryModule(plugin, refactor);
}

export function removeModuleIdOnlyForTesting(refactor: TypeScriptFileRefactor) {
  _removeModuleId(refactor);
}

function _removeModuleId(refactor: TypeScriptFileRefactor) {
  const sourceFile = refactor.sourceFile;

  refactor.findAstNodes(sourceFile, ts.SyntaxKind.Decorator, true)
    .reduce((acc, node) => {
      return acc.concat(refactor.findAstNodes(node, ts.SyntaxKind.ObjectLiteralExpression, true));
    }, [])
    // Get all their property assignments.
    .filter((node: ts.ObjectLiteralExpression) => {
      return node.properties.some(prop => {
        return prop.kind == ts.SyntaxKind.PropertyAssignment
            && _getContentOfKeyLiteral(sourceFile, prop.name) == 'moduleId';
      });
    })
    .forEach((node: ts.ObjectLiteralExpression) => {
      const moduleIdProp = node.properties.filter((prop: ts.ObjectLiteralElement, _idx: number) => {
        return prop.kind == ts.SyntaxKind.PropertyAssignment
            && _getContentOfKeyLiteral(sourceFile, prop.name) == 'moduleId';
      })[0];
      // Get the trailing comma.
      const moduleIdCommaProp = moduleIdProp.parent
        ? moduleIdProp.parent.getChildAt(1).getChildren()[1] : null;
      refactor.removeNodes(moduleIdProp, moduleIdCommaProp);
    });
}

function _getResourceRequest(element: ts.Expression, sourceFile: ts.SourceFile) {
  if (element.kind == ts.SyntaxKind.StringLiteral) {
    const url = (element as ts.StringLiteral).text;
    // If the URL does not start with ./ or ../, prepends ./ to it.
    return `'${/^\.?\.\//.test(url) ? '' : './'}${url}'`;
  } else {
    // if not string, just use expression directly
    return element.getFullText(sourceFile);
  }
}

function _replaceResources(refactor: TypeScriptFileRefactor): void {
  const sourceFile = refactor.sourceFile;

  _getResourceNodes(refactor)
    // Get the full text of the initializer.
    .forEach((node: ts.PropertyAssignment) => {
      const key = _getContentOfKeyLiteral(sourceFile, node.name);

      if (key == 'templateUrl') {
        refactor.replaceNode(node,
          `template: require(${_getResourceRequest(node.initializer, sourceFile)})`);
      } else if (key == 'styleUrls') {
        const arr = <ts.ArrayLiteralExpression[]>(
          refactor.findAstNodes(node, ts.SyntaxKind.ArrayLiteralExpression, false));
        if (!arr || arr.length == 0 || arr[0].elements.length == 0) {
          return;
        }

        const initializer = arr[0].elements.map((element: ts.Expression) => {
          return _getResourceRequest(element, sourceFile);
        });
        refactor.replaceNode(node, `styles: [require(${initializer.join('), require(')})]`);
      }
    });
}

function _getResourceNodes(refactor: TypeScriptFileRefactor) {
  const { sourceFile } = refactor;

  // Find all object literals.
  return refactor.findAstNodes(sourceFile, ts.SyntaxKind.ObjectLiteralExpression, true)
  // Get all their property assignments.
    .map(node => refactor.findAstNodes(node, ts.SyntaxKind.PropertyAssignment))
    // Flatten into a single array (from an array of array<property assignments>).
    .reduce((prev, curr) => curr ? prev.concat(curr) : prev, [])
    // Remove every property assignment that aren't 'loadChildren'.
    .filter((node: ts.PropertyAssignment) => {
      const key = _getContentOfKeyLiteral(sourceFile, node.name);
      if (!key) {
        // key is an expression, can't do anything.
        return false;
      }
      return key == 'templateUrl' || key == 'styleUrls';
    });
}

function _getResourcesUrls(refactor: TypeScriptFileRefactor): string[] {
  return _getResourceNodes(refactor)
    .reduce((acc: string[], node: ts.PropertyAssignment) => {
      const key = _getContentOfKeyLiteral(refactor.sourceFile, node.name);

      if (key == 'templateUrl') {
        const url = (node.initializer as ts.StringLiteral).text;
        if (url) {
          acc.push(url);
        }
      } else if (key == 'styleUrls') {
        const arr = <ts.ArrayLiteralExpression[]>(
          refactor.findAstNodes(node, ts.SyntaxKind.ArrayLiteralExpression, false));
        if (!arr || arr.length == 0 || arr[0].elements.length == 0) {
          return acc;
        }

        arr[0].elements.forEach((element: ts.Expression) => {
          if (element.kind == ts.SyntaxKind.StringLiteral) {
            const url = (element as ts.StringLiteral).text;
            if (url) {
              acc.push(url);
            }
          }
        });
      }
      return acc;
    }, []);
}

/**
 * Recursively calls diagnose on the plugins for all the reverse dependencies.
 * @private
 */
function _diagnoseDeps(reasons: ModuleReason[], plugin: AotPlugin, checked: Set<string>) {
  reasons
    .filter(reason => reason && reason.module && reason.module instanceof NormalModule)
    .filter(reason => !checked.has(reason.module.resource))
    .forEach(reason => {
      checked.add(reason.module.resource);
      plugin.diagnose(reason.module.resource);
      _diagnoseDeps(reason.module.reasons, plugin, checked);
    });
}

export function _getModuleExports(plugin: AotPlugin,
                                  refactor: TypeScriptFileRefactor): ts.Identifier[] {
  const exports = refactor
    .findAstNodes(refactor.sourceFile, ts.SyntaxKind.ExportDeclaration, true);

  return exports
    .filter(node => {

      const identifiers = refactor.findAstNodes(node, ts.SyntaxKind.Identifier, false)
        .filter(node => node.getText() === plugin.entryModule.className);

      return identifiers.length > 0;
    }) as ts.Identifier[];
}

export function _replaceExport(plugin: AotPlugin, refactor: TypeScriptFileRefactor) {
  if (!plugin.replaceExport) {
    return;
  }
  _getModuleExports(plugin, refactor)
    .forEach(node => {
      const factoryPath = _getNgFactoryPath(plugin, refactor);
      const factoryClassName = plugin.entryModule.className + 'NgFactory';
      const exportStatement = `export \{ ${factoryClassName} \} from '${factoryPath}'`;
      refactor.appendAfter(node, exportStatement);
    });
}

export function _exportModuleMap(plugin: AotPlugin, refactor: TypeScriptFileRefactor) {
  if (!plugin.replaceExport) {
    return;
  }

  const dirName = path.normalize(path.dirname(refactor.fileName));
  const classNameAppend = plugin.skipCodeGeneration ? '' : 'NgFactory';
  const modulePathAppend = plugin.skipCodeGeneration ? '' : '.ngfactory';

  _getModuleExports(plugin, refactor)
    .forEach(node => {
      const modules = Object.keys(plugin.discoveredLazyRoutes)
        .map((loadChildrenString) => {
          let [lazyRouteKey, moduleName] = loadChildrenString.split('#');

          if (!lazyRouteKey || !moduleName) {
            throw new Error(`${loadChildrenString} was not a proper loadChildren string`);
          }

          moduleName += classNameAppend;
          lazyRouteKey += modulePathAppend;
          const modulePath = plugin.lazyRoutes[lazyRouteKey];

          return {
            modulePath,
            moduleName,
            loadChildrenString
          };
        });

      modules.forEach((module, index) => {
        const relativePath = path.relative(dirName, module.modulePath).replace(/\\/g, '/');
        refactor.prependBefore(node, `import * as __lazy_${index}__ from './${relativePath}'`);
      });

      const jsonContent: string = modules
        .map((module, index) =>
          `"${module.loadChildrenString}": __lazy_${index}__.${module.moduleName}`)
        .join();

      refactor.appendAfter(node, `export const LAZY_MODULE_MAP = {${jsonContent}};`);
    });
}

// Super simple TS transpiler loader for testing / isolated usage. does not type check!
export function ngcLoader(this: LoaderContext & { _compilation: any }, source: string | null) {
  const cb = this.async();
  const sourceFileName: string = this.resourcePath;

  const plugin = this._compilation._ngToolsWebpackPluginInstance as AotPlugin;
  if (plugin) {
    // We must verify that AotPlugin is an instance of the right class.
    // Throw an error if it isn't, that often means multiple @ngtools/webpack installs.
    if (!(plugin instanceof AotPlugin)) {
      throw new Error('AotPlugin was detected but it was an instance of the wrong class.\n'
        + 'This likely means you have several @ngtools/webpack packages installed. '
        + 'You can check this with `npm ls @ngtools/webpack`, and then remove the extra copies.'
      );
    }

    if (plugin.compilerHost.readFile(sourceFileName) == source) {
      // In the case where the source is the same as the one in compilerHost, we don't have
      // extra TS loaders and there's no need to do any trickery.
      source = null;
    }
    const refactor = new TypeScriptFileRefactor(
      sourceFileName, plugin.compilerHost, plugin.program, source);

    Promise.resolve()
      .then(() => {
        if (!plugin.skipCodeGeneration) {
          return Promise.resolve()
            .then(() => _removeDecorators(refactor))
            .then(() => _refactorBootstrap(plugin, refactor))
            .then(() => _replaceExport(plugin, refactor))
            .then(() => _exportModuleMap(plugin, refactor));
        } else {
          return Promise.resolve()
            .then(() => _replaceResources(refactor))
            .then(() => _removeModuleId(refactor))
            .then(() => _exportModuleMap(plugin, refactor));
        }
      })
      .then(() => {
        if (plugin.typeCheck) {
          // Check all diagnostics from this and reverse dependencies also.
          if (!plugin.firstRun) {
            _diagnoseDeps(this._module.reasons, plugin, new Set<string>());
          }
          // We do this here because it will throw on error, resulting in rebuilding this file
          // the next time around if it changes.
          plugin.diagnose(sourceFileName);
        }
      })
      .then(() => {
        // Add resources as dependencies.
        _getResourcesUrls(refactor).forEach((url: string) => {
          this.addDependency(path.resolve(path.dirname(sourceFileName), url));
        });
      })
      .then(() => {
        if (source) {
          // We need to validate diagnostics. We ignore type checking though, to save time.
          const diagnostics = refactor.getDiagnostics(false);
          if (diagnostics.length) {
            let message = '';

            diagnostics.forEach(diagnostic => {
              const messageText = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');

              if (diagnostic.file) {
                const position = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
                const fileName = diagnostic.file.fileName;
                const {line, character} = position;
                message += `${fileName} (${line + 1},${character + 1}): ${messageText}\n`;
              } else {
                message += `${messageText}\n`;
              }
            });
            throw new Error(message);
          }
        }

        // Force a few compiler options to make sure we get the result we want.
        const compilerOptions: ts.CompilerOptions = Object.assign({}, plugin.compilerOptions, {
          inlineSources: true,
          inlineSourceMap: false,
          sourceRoot: plugin.basePath
        });

        const result = refactor.transpile(compilerOptions);
        cb(null, result.outputText, result.sourceMap);
      })
      .catch(err => cb(err));
  } else {
    const options = loaderUtils.getOptions(this) || {};
    const tsConfigPath = options.tsConfigPath;

    if (tsConfigPath === undefined) {
      throw new Error('@ngtools/webpack is being used as a loader but no `tsConfigPath` option nor '
        + 'AotPlugin was detected. You must provide at least one of these.'
      );
    }

    const tsConfig = ts.readConfigFile(tsConfigPath, ts.sys.readFile);

    if (tsConfig.error) {
      throw tsConfig.error;
    }

    const compilerOptions: ts.CompilerOptions = tsConfig.config.compilerOptions;
    for (const key of Object.keys(options)) {
      if (key == 'tsConfigPath') {
        continue;
      }
      compilerOptions[key] = options[key];
    }
    const compilerHost = ts.createCompilerHost(compilerOptions);
    const refactor = new TypeScriptFileRefactor(sourceFileName, compilerHost);
    _replaceResources(refactor);

    const result = refactor.transpile(compilerOptions);
    // Webpack is going to take care of this.
    result.outputText = result.outputText.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '');
    cb(null, result.outputText, result.sourceMap);
  }
}


text:
'use strict'; /* @flow */

import React from 'react';
import ReactCSS from 'reactcss';
import merge from 'merge';
import _ from 'lodash';
import color from '../helpers/color';

import Photoshop from './photoshop/Photoshop';
import Sketch from './sketch-2/Sketch';
import Chrome from './chrome/Chrome';
import Swatches from './swatches/Swatches';
import Slider from './slider/Slider';
import Material from './material/Material';
import Compact from './compact/Compact';

class ColorPicker extends ReactCSS.Component {

  constructor(props: any) {
    super();

    this.state = merge(color.toState(props.color, 0), {
      visible: props.display,
    });

    this.debounce = _.debounce(function(fn: any, data: any) {
      fn(data);
    }, 100);

    this.handleChange = this.handleChange.bind(this);
    this.handleHide = this.handleHide.bind(this);
    this.handleAccept = this.handleAccept.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
  }

  classes(): any {
    return {
      'show': {
        wrap: {
          zIndex: '999',
          position: 'absolute',
          display: 'block',
        },
        picker: {
          zIndex: '2',
          position: 'relative',
        },
        cover: {
          position: 'fixed',
          top: '0',
          bottom: '0',
          left: '0',
          right: '0',
        },
      },
      'hide': {
        wrap: {
          zIndex: '999',
          position: 'absolute',
          display: 'none',
        },
      },
      'right': {
        wrap: {
          left: '100%',
          marginLeft: '20px',
          top: '0',
        },
      },
      'left': {
        wrap: {
          right: '100%',
          marginRight: '20px',
          top: '0',
        },
      },
      'below': {
        wrap: {
          left: '0',
          marginLeft: '0',
          top: '100%',
          marginTop: '20px',
        },
      },
      'override': {
        wrap: this.props.positionCSS,
      },
    };
  }

  styles(): any {
    return this.css({
      'below': this.props.position === 'below' && this.props.display !== null,
      'right': this.props.position === 'right' && this.props.display !== null,
      'left': this.props.position === 'left' && this.props.display !== null,
      'show': this.state.visible === true,
      'hide': this.state.visible === false,
      'override': _.isPlainObject(this.props.positionCSS),
    });
  }

  handleHide() {
    if (this.state.visible === true) {
      this.setState({
        visible: false,
      });
      this.props.onClose && this.props.onClose({
        hex: this.state.hex,
        hsl: this.state.hsl,
        rgb: this.state.rgb,
      });
    }
  }

  handleAccept() {
    this.handleHide();
  }

  handleCancel() {
    if (this.state.visible === true) {
      this.setState({
        visible: false,
      });
    }
  }

  handleChange(data: any) {
    data = color.simpleCheckForValidColor(data);
    if (data) {
      var colors = color.toState(data, data.h || this.state.oldHue);
      this.setState(colors);
      this.props.onChangeComplete && this.debounce(this.props.onChangeComplete, colors);
      this.props.onChange && this.props.onChange(colors);
    }
  }

  componentWillReceiveProps(nextProps: any) {
    this.setState(merge(color.toState(nextProps.color, this.state.oldHue), {
      visible: nextProps.display,
    }));
  }

  render(): any {
    var Picker: any;
    if (this.props.custom) {
      Picker = this.props.custom;
    } else if (this.props.type === 'sketch') {
      Picker = Sketch;
    } else if (this.props.type === 'photoshop') {
      Picker = Photoshop;
    } else if (this.props.type === 'chrome') {
      Picker = Chrome;
    } else if (this.props.type === 'swatches') {
      Picker = Swatches;
    } else if (this.props.type === 'slider') {
      Picker = Slider;
    } else if (this.props.type === 'material') {
      Picker = Material;
    } else if (this.props.type === 'compact') {
      Picker = Compact;
    }

    return (

          <Picker {...this.props} {...this.state} onChange={ this.handleChange } onAccept={ this.handleAccept } onCancel={ this.handleCancel } />

    );
  }
}

ColorPicker.defaultProps = {
  color: {
    h: 250,
    s: .50,
    l: .20,
    a: 1,
  },
  display: null,
  type: 'sketch',
  position: 'right',
  positionCSS: {},
};

export default ColorPicker;

redpajama_set_name: RedPajamaGithub


text:
package com.ubiqlog.vis.ui.extras.DateTimeSelector;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.ubiqlog.vis.ui.extras.DateTimeSelector.DateTimePickerDialog.Type;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * A framelayout displaying a button with the a date on it. When the button is
 * pressed a DateTimePicker dialog will be displayed and the user can change the
 * date and/or time
 *
 * @author Victor Gugonatu
 * @date 10.2010
 * @version 1.0
 */
public class DateTimeSelector extends FrameLayout implements
		View.OnClickListener {

	/**
	 * The callback used to indicate the user is done filling in the data.
	 * Refers to {@link DateTimeSelector DateTimeSelector}
	 */
	public interface OnDataChangedListener {

		public abstract void onDataChanged(Date date, Type type);
	}

	private Date mInitialDate;
	private boolean mIs24HourView;
	private Type mType;

	private final OnDataChangedListener mCallBack;
	private final Button mButton;
	private final TextView mTextView;
	private final TableRow mCustomLayout;
	private final String mTitle;

	/**
	 * @param context
	 *            The context the framelayout belongs to
	 * @param callBack
	 *            How the parent is notified that the date and time is set.
	 *
	 * @param date
	 *            The initial date to be displayed.
	 * @param type
	 *            The type of the selector. See
	 *            {@link DateTimePickerDialog.Type DateTimePickerDialog.Type}
	 * @param is24HourView
	 *            Whether this is a 24 hour view, or AM/PM.
	 * @param title
	 *            The text that should be shown on the button.
	 */
	public DateTimeSelector(Context context, OnDataChangedListener callback,
			Date date, Type type, boolean is24Hour, String title) {
		super(context);

		mTitle = title;
		mCallBack = callback;
		mIs24HourView = is24Hour;

		mCustomLayout = new TableRow(context);
		mCustomLayout.setLayoutParams(new TableRow.LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

		mInitialDate = date;
		mType = type;

		mButton = new Button(context);
		mButton.setOnClickListener(this);

		mTextView = new TextView(context);
		updateText();

		TextView tv = new TextView(context);
		tv.setText(title);

		LinearLayout lay = new LinearLayout(context);
		lay.setLayoutParams(new LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT));
		lay.setOrientation(LinearLayout.VERTICAL);

		mButton.setLayoutParams(new TableRow.LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.FILL_PARENT));
		mTextView.setLayoutParams(new TableRow.LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		mCustomLayout.setLayoutParams(new TableLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.FILL_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

		lay.setPadding(1, 1, 1, 1);
		tv.setBackgroundColor(Color.LTGRAY);
		mCustomLayout.setGravity(Gravity.CENTER);

		tv.setGravity(Gravity.CENTER);

		lay.addView(mCustomLayout);
		lay.setGravity(Gravity.CENTER);
		addView(mButton);

	}

	public Date getDate() {
		return mInitialDate;
	}

	/**
	 * opens the corresponding dialog (Date, Time or DateTime dialog)
	 */
	public void onClick(View v) {
		Dialog d = null;
		switch (mType) {
		case DATE:
			d = new DatePickerDialog(this.getContext(), dateSetListener,
					mInitialDate.getYear() + 1900, mInitialDate.getMonth(),
					mInitialDate.getDate());

			break;
		case DATETIME:
			d = new DateTimePickerDialog(this.getContext(), saveListener,
					mInitialDate.getYear() + 1900, mInitialDate.getMonth(),
					mInitialDate.getDate(), mInitialDate.getHours(),
					mInitialDate.getMinutes(), mIs24HourView);

			break;
		case TIME:
			d = new TimePickerDialog(this.getContext(), timeSetListener,
					mInitialDate.getHours(), mInitialDate.getMinutes(),
					mIs24HourView);

			break;
		default:
			break;
		}

		// should never be null
		if (d != null) {
			d.show();
		}
	}

	private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			mInitialDate.setHours(hourOfDay);
			mInitialDate.setMinutes(minute);

			updateText();
			mButton.clearFocus();
			mTextView.clearFocus();
			mCustomLayout.clearFocus();
			if (mCallBack != null) {

				mCallBack.onDataChanged(mInitialDate, mType);
			}

		}
	};
	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			mInitialDate.setYear(year - 1900);
			mInitialDate.setMonth(monthOfYear);
			mInitialDate.setDate(dayOfMonth);

			updateText();
			mButton.clearFocus();
			mTextView.clearFocus();
			mCustomLayout.clearFocus();
			if (mCallBack != null) {

				mCallBack.onDataChanged(mInitialDate, mType);
			}

		}
	};

	private DateTimePickerDialog.DateTimePickerDialogOnDataChangedListener saveListener = new DateTimePickerDialog.DateTimePickerDialogOnDataChangedListener() {

		public void onDataChanged(DatePicker datePicker, TimePicker timePicker,
				int year, int month, int dayOfMonth, int hourOfDay, int minute) {

			mInitialDate.setYear(year - 1900);
			mInitialDate.setMonth(month);
			mInitialDate.setDate(dayOfMonth);
			mInitialDate.setHours(hourOfDay);
			mInitialDate.setMinutes(minute);

			updateText();
			mButton.clearFocus();
			mTextView.clearFocus();
			mCustomLayout.clearFocus();
			if (mCallBack != null) {

				mCallBack.onDataChanged(mInitialDate, mType);
			}
		}
	};

	private void updateText() {

		String datenow = "";

		SimpleDateFormat dateformatDATE = new SimpleDateFormat("dd.MM.yyyy");
		new SimpleDateFormat("dd.MM.yyyy HH:mm");
		SimpleDateFormat dateformatTIME = new SimpleDateFormat("HH:mm");

		switch (mType) {
		case DATE:

			datenow = java.text.DateFormat.getDateInstance(
					java.text.DateFormat.SHORT).format(mInitialDate);
			datenow = dateformatDATE.format(mInitialDate);

			break;

		case TIME:

			datenow = dateformatTIME.format(mInitialDate);

			break;

		case DATETIME:

			datenow = java.text.DateFormat.getDateInstance(
					java.text.DateFormat.LONG).format(mInitialDate);

			datenow = dateformatDATE.format(mInitialDate) + " "
					+ dateformatTIME.format(mInitialDate);

			break;

		default:
			break;
		}

		mButton.setText(mTitle + "\n" + datenow);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DC.Nitrus
{
    [JsonObject]
    public class BottleArgValue
    {
        #region Constrcutor
        public BottleArgValue(string fullname, string value)
        {
            Fullname = fullname;
            Value = value;
        }
        #endregion

        #region Members
        [JsonProperty("fullname")]
        public string Fullname { get; set; }

        [JsonProperty("value")]
        public string Value{ get; set; }
        #endregion
    }
}


text: Gallery:


text:
package org.codehaus.mojo.keytool.requests;

import org.apache.maven.shared.utils.cli.javatool.JavaToolResult;
import org.junit.Assert;

import java.io.File;

/**
 * Test the {@link KeyToolGenerateCertificateRequest}.
 *
 * @author tchemit
 * @since 1.1
 */
public class KeyToolGenerateCertificateRequestIT
    extends AbstractKeyToolGenerateCertificateRequestIT
{

    @Override
    protected void requestResult( JavaToolResult keyToolResult, File keyStore, File inFile, File outputFile )
    {
        assertKeyToolResult( keyToolResult,
                             new String[]{ "-gencert", "-v", "-keystore", keyStore.getAbsolutePath(), "-storepass",
                                 "changeit", "-storetype", "jks", "-alias", "foo_alias", "-rfc", "-infile",
                                 inFile.getAbsolutePath(), "-outfile", outputFile.getAbsolutePath(), "-sigalg",
                                 "SHA1withDSA", "-dname",
                                 "CN=Me, OU=Unknown, O=Codehaus, L=Unknown, ST=Unknown, C=France", "-startdate",
                                 "2011/11/11", "-validity", "100", "-keypass", "key-passwd" }, 0 );
        Assert.assertTrue( outputFile.exists() );
    }

}


text:
/* @test
 * @bug 4214888
 * @clean CheckModifiers TestClass1 TestClass2
 * @build CheckModifiers
 * @run main CheckModifiers
 * @summary Make sure that serialpersistentFields data member is used to
 *          represent tyhe serializable fields only if it has the modfiers
 *          static, final, private and the type is ObjectStreamField.
 *          No need to check for static, as ObjectStreamField class is not
 *          serializable.
 *
 */

import java.io.*;
class TestClass1 implements Serializable {
    // Missing the "final" modifier
    private static ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("field1", Integer.class),
        new ObjectStreamField("field2", Double.TYPE),
    };

    Integer field1;
    double field2;
    int field3;
    String field4;

    public TestClass1(Integer f1, double f2, int f3, String f4) {
        field1 = f1;
        field2 = f2;
        field3 = f3;
        field4 = f4;
    }

    private void readObject(ObjectInputStream ois)
        throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField pfields = ois.readFields();

        field1 = (Integer) pfields.get("field1", new Integer(100));
        field2 = pfields.get("field2", 99.99);

        /* These fields must be present in the stream */
        try {
            field3 = pfields.get("field3", 99);
            System.out.println("Passes test 1a");
        } catch(IllegalArgumentException e) {
            throw new Error("data field: field3 not in the persistent stream");
        }
        try {
            field4 = (String) pfields.get("field4", "Default string");
            System.out.println("Passes test 1b");
        } catch(IllegalArgumentException e) {
            throw new Error("data field: field4 not in the persistent stream");
        }
    }
};

class TestClass2 implements Serializable {
    // public instead of private
    public static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("field1", Integer.class),
        new ObjectStreamField("field2", Double.TYPE),
    };

    Integer field1;
    double field2;
    int field3;
    String field4;

    public TestClass2(Integer f1, double f2, int f3, String f4) {
        field1 = f1;
        field2 = f2;
        field3 = f3;
        field4 = f4;
    }

    private void readObject(ObjectInputStream ois)
        throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField pfields = ois.readFields();

        field1 = (Integer) pfields.get("field1", new Integer(100));
        field2 = pfields.get("field2", 99.99);

        /* These fields must be present in the stream */
        try {
            field3 = pfields.get("field3", 99);
            System.out.println("Passes test 2a");
        } catch(IllegalArgumentException e) {
            throw new Error("data field: field3 not in the persistent stream");
        }
        try {
            field4 = (String) pfields.get("field4", "Default string");
            System.out.println("Passes test 2b");
        } catch(IllegalArgumentException e) {
            throw new Error("data field: field4 not in the persistent stream");
        }
    }
};

class TestClass3 implements Serializable{
    // Not of type ObjectStreamField
    private final String[] serialPersistentFields =  {"Foo","Foobar"};;
    Integer field1;
    double field2;
    int field3;
    String field4;

    public TestClass3(Integer f1, double f2, int f3, String f4) {
        field1 = f1;
        field2 = f2;
        field3 = f3;
        field4 = f4;
    }

    private void readObject(ObjectInputStream ois)
        throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField pfields = ois.readFields();

        field1 = (Integer) pfields.get("field1", new Integer(100));
        field2 = pfields.get("field2", 99.99);
        field3 = pfields.get("field3", 99);
        field4 = (String) pfields.get("field4", "Default string");

        try {
            String[] tserialPersistentFields =
                (String[])pfields.get("serialPersistentFields", null);
            System.out.println("Passes test 3");
        } catch(IllegalArgumentException e) {
            throw new Error("non-static field:  " +
                "serialPersistentFields must be in the persistent stream");
        }
    }
};

class TestClass4 implements Serializable {
    // Correct format
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("field1", Integer.class),
        new ObjectStreamField("field2", Double.TYPE),
    };

    Integer field1;
    double field2;
    int field3;
    String field4;

    public TestClass4(Integer f1, double f2, int f3, String f4) {
        field1 = f1;
        field2 = f2;
        field3 = f3;
        field4 = f4;
    }

    private void readObject(ObjectInputStream ois)
        throws IOException, ClassNotFoundException {
        ObjectInputStream.GetField pfields = ois.readFields();

        field1 = (Integer) pfields.get("field1", new Integer(100));
        field2 = pfields.get("field2", 99.99);

        try {
            field3 = pfields.get("field3", 99);
            throw new Error("data field: field3 in the persistent stream");
        } catch(IllegalArgumentException e) {
            System.out.println("Passes test 4a");
        }
        try {
            field4 = (String) pfields.get("field4", "Default string");
            throw new Error("data field: field4 in the persistent stream");
        } catch(IllegalArgumentException e) {
            System.out.println("Passes test 4b");
        }
    }
};

public class CheckModifiers {
    public static void main(String[] args)
        throws ClassNotFoundException, IOException{
        TestClass1 tc1 = new TestClass1(new Integer(100), 25.56, 2000,
            new String("Test modifiers of serialPersistentFields"));

        TestClass2 tc2 = new TestClass2(new Integer(100), 25.56, 2000,
            new String("Test modifiers of serialPersistentFields"));

        TestClass3 tc3 = new TestClass3(new Integer(100), 25.56, 2000,
            new String("Test Type of serialPersistentFields"));

        TestClass4 tc4 = new TestClass4(new Integer(100), 25.56, 2000,
            new String("Test modifiers of serialPersistentFields"));

        FileOutputStream fos = new FileOutputStream("fields.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        System.out.println("Writing obj 1");
        oos.writeObject(tc1);
        System.out.println("Writing obj 2");
        oos.writeObject(tc2);
        System.out.println("Writing obj 3");
        oos.writeObject(tc3);
        System.out.println("Writing obj 4");
        oos.writeObject(tc4);

        FileInputStream fis = new FileInputStream("fields.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);

        System.out.println("Test modifiers for serialPeristentFields ");
        System.out.println("---------------------------------------- ");
        System.out.println("Declaration missing final modifier");
        ois.readObject();
        System.out.println();
        System.out.println("Declaration with public instead of private access");
        ois.readObject();
        System.out.println();
        System.out.println("Declaration with different type");
        ois.readObject();
        System.out.println();
        System.out.println("Declaration as in specification");
        ois.readObject();
    }
};


text:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {actionCreators} from '../../public/store';
import Album from '../../components/Album';
import AlbumEdit from '../../components/AlbumEdit';

import './AlbumCon.scss'

class AlbumCon extends Component {
    constructor () {
        super();
        this.state = {
            hide: false
        }
    }
    render() {
        let props = this.props,
            state = this.state;
        return (
            <div className="albumCon">
                <Album
                    hide={state.hide}
                    src={props.src}
                    name={props.name}
                    sum={props.sum}
                    onDelete={props.onDelete.bind(this, props.id, props.index)}
                    onEdit={this.handleEdit.bind(this)}
                    onAlbumClick={props.onAlbumClick}
                />
                <AlbumEdit
                    hide={!state.hide}
                    name={props.name}
                    desc={props.desc}
                    onCheck={this.handleCheck.bind(this)}
                    onCancel={()=>this.setState({hide:false})}
                />
            </div>
        )
    }

    handleEdit () {
        this.setState({hide: true});
    }

    handleCheck (name, desc) {
        let {id, index} = this.props;

        if(name!==this.props.name || desc!==this.props.desc){
            this.props.onEdit(id, index, name, desc);
        }
        this.setState({hide:false})
    }
}

export default connect(null,
    (dispatch) => {
        return {
            onDelete (id, index) {
                dispatch(actionCreators.delAlbum(id, index))
            },
            onEdit (id, index, name, desc) {
                dispatch(actionCreators.editAlbum(id, index, name, desc))
            }
        }
    }
)(AlbumCon);


text:
/**
 * View Compilation Helpers
 */

'use strict';

var _ = require('lodash'),
    loremIpsum = require('lorem-ipsum'),
    marked = require('marked');

module.exports = function (options) {

    return {
        lorem: function (min, max, config) {
            var count = max ? _.random(min, max) : min,
                defaults = {
                    units: 'words',
                    count: count
                },
                conf = _.defaults(config || {}, defaults);

            return loremIpsum(conf);
        },

        md: function (src) {
            return marked(src);
        }
    };

};


text:
package collection;

import java.util.*;
/**
 * @author Bharat Verma
 */
public class ArrayListDemo
{
	public static void printArrayList (ArrayList p_arraylist)
	{
		System.out.println("------------------------------------------");
		System.out.println("Content of ArrayList : "+p_arraylist);
		System.out.println("Size of ArrayList = "+p_arraylist.size());
		System.out.println("------------------------------------------");
	}
	public static void main(String[] args)
	{
		ArrayList<Object> sampleArrayList =new ArrayList<Object>(); // you can specify the object type

		Integer intr = new Integer(729);
		String str ="Bharat";
		double dtr = 169.721;

		printArrayList(sampleArrayList);

		sampleArrayList.add(intr);
		sampleArrayList.add(str);
		sampleArrayList.add(dtr);
		printArrayList(sampleArrayList);

		Integer i5=new Integer(50);
		sampleArrayList.add(3, i5); // using add(int index, object obj)
		printArrayList(sampleArrayList);

		sampleArrayList.remove(3); // using remove()
		printArrayList(sampleArrayList);

		Object a=sampleArrayList.clone(); // using clone

		System.out.println("The clone is: " + a);

		printArrayList(sampleArrayList);

		System.out.println(sampleArrayList.contains("Bharat")); // True as it contains

		// iteration using iterator
		Iterator iter = sampleArrayList.iterator();
		System.out.println("Using Iterator");
		while (iter.hasNext())
		{
			System.out.println(iter.next());
		}

		// using for loop and indexes
		System.out.println("Using for loop and index");
		for (int i=0; i<sampleArrayList.size(); i++)
		{
			System.out.println(sampleArrayList.get(i));
		}
	}
}


text:
package org.jivesoftware.openfire.admin;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.jivesoftware.util.*;
import org.jivesoftware.openfire.user.*;
import java.util.HashMap;
import java.util.Map;
import java.net.URLEncoder;
import org.xmpp.packet.JID;

public final class user_002dsearch_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static java.util.List _jspx_dependants;

  private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_fmt_message_key_nobody;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _jspx_tagPool_fmt_message_key_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
  }

  public void _jspDestroy() {
    _jspx_tagPool_fmt_message_key_nobody.release();
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n\n");
      out.write('\n');
      org.jivesoftware.util.WebManager webManager = null;
      synchronized (_jspx_page_context) {
        webManager = (org.jivesoftware.util.WebManager) _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
        if (webManager == null){
          webManager = new org.jivesoftware.util.WebManager();
          _jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
   webManager.init(request, response, session, application, out );
      out.write('\n');

    // Get parameters
    boolean search = ParamUtils.getBooleanParameter(request,"search");
    String username = ParamUtils.getParameter(request,"username");
    username = JID.escapeNode(username);

    // Handle a cancel
    if (request.getParameter("cancel") != null) {
        response.sendRedirect("user-summary.jsp");
        return;
    }

    // Handle a search execute:
    Map<String,String> errors = new HashMap<String,String>();
    if (search) {
        User user = null;
        try {
            user = webManager.getUserManager().getUser(username);
        }
        catch (Exception e2) {
            errors.put("username","username");
        }
        if (user != null) {
            // found the user, so redirect to the user properties page:
            response.sendRedirect("user-properties.jsp?username=" +
                    URLEncoder.encode(user.getUsername(), "UTF-8"));
            return;
        }
    }

      out.write("\n\n\n    \n        <title>");
      if (_jspx_meth_fmt_message_0(_jspx_page_context))
        return;
      out.write("</title>\n        <meta name=\"pageID\" content=\"user-search\"/>\n        <meta name=\"helpPage\" content=\"search_for_a_user.html\"/>\n    \n    \n\n");
    if (errors.size() > 0) {
      out.write("\n
");
      if (_jspx_meth_fmt_message_1(_jspx_page_context))
        return;
      out.write("
\n");
    }
      out.write("\n<form name=\"f\" action=\"user-search.jsp\">\n  <input type=\"hidden\" name=\"search\" value=\"true\"/>\n  <fieldset>\n    <legend>");
      if (_jspx_meth_fmt_message_2(_jspx_page_context))
        return;
      out.write("</legend>\n
\n
\n        ");
      if (_jspx_meth_fmt_message_3(_jspx_page_context))
        return;
      out.write(":	\n        \n          <input type=\"text\" name=\"username\" value=\"");
      out.print( ((username!=null) ? StringUtils.escapeForXML(username) : "") );
      out.write("\" size=\"30\" maxlength=\"75\"/>\n        	\n
\n
<input type=\"submit\" name=\"search\" value=\"");
      if (_jspx_meth_fmt_message_4(_jspx_page_context))
        return;
      out.write("\"/><input type=\"submit\" name=\"cancel\" value=\"");
      if (_jspx_meth_fmt_message_5(_jspx_page_context))
        return;
      out.write("\"/>	\n
\n
\n  </fieldset>\n</form>\n\n\n    \n\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }

  private boolean _jspx_meth_fmt_message_0(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_0.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_0.setParent(null);
    _jspx_th_fmt_message_0.setKey("user.search.title");
    int _jspx_eval_fmt_message_0 = _jspx_th_fmt_message_0.doStartTag();
    if (_jspx_th_fmt_message_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_0);
    return false;
  }

  private boolean _jspx_meth_fmt_message_1(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_1.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_1.setParent(null);
    _jspx_th_fmt_message_1.setKey("user.search.not_found");
    int _jspx_eval_fmt_message_1 = _jspx_th_fmt_message_1.doStartTag();
    if (_jspx_th_fmt_message_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_1);
    return false;
  }

  private boolean _jspx_meth_fmt_message_2(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_2 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_2.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_2.setParent(null);
    _jspx_th_fmt_message_2.setKey("user.search.search_user");
    int _jspx_eval_fmt_message_2 = _jspx_th_fmt_message_2.doStartTag();
    if (_jspx_th_fmt_message_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_2);
    return false;
  }

  private boolean _jspx_meth_fmt_message_3(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_3 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_3.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_3.setParent(null);
    _jspx_th_fmt_message_3.setKey("user.create.username");
    int _jspx_eval_fmt_message_3 = _jspx_th_fmt_message_3.doStartTag();
    if (_jspx_th_fmt_message_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_3);
    return false;
  }

  private boolean _jspx_meth_fmt_message_4(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_4 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_4.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_4.setParent(null);
    _jspx_th_fmt_message_4.setKey("user.search.search");
    int _jspx_eval_fmt_message_4 = _jspx_th_fmt_message_4.doStartTag();
    if (_jspx_th_fmt_message_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_4);
    return false;
  }

  private boolean _jspx_meth_fmt_message_5(PageContext _jspx_page_context)
          throws Throwable {
    PageContext pageContext = _jspx_page_context;
    JspWriter out = _jspx_page_context.getOut();
    //  fmt:message
    org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_message_5 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _jspx_tagPool_fmt_message_key_nobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class);
    _jspx_th_fmt_message_5.setPageContext(_jspx_page_context);
    _jspx_th_fmt_message_5.setParent(null);
    _jspx_th_fmt_message_5.setKey("global.cancel");
    int _jspx_eval_fmt_message_5 = _jspx_th_fmt_message_5.doStartTag();
    if (_jspx_th_fmt_message_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5);
      return true;
    }
    _jspx_tagPool_fmt_message_key_nobody.reuse(_jspx_th_fmt_message_5);
    return false;
  }
}


text:
.chartist-tooltip {
  position: absolute;
  display: inline-block;
  opacity: 0;
  min-width: 5em;
  padding: .5em;
  background: #F4C63D;
  color: #453D3F;
  font-family: Oxygen,Helvetica,Arial,sans-serif;
  font-weight: 700;
  text-align: center;
  pointer-events: none;
  z-index: 1;
  -webkit-transition: opacity .2s linear;
  -moz-transition: opacity .2s linear;
  -o-transition: opacity .2s linear;
  transition: opacity .2s linear; }
.chartist-tooltip:before {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    width: 0;
    height: 0;
    margin-left: -15px;
    border: 15px solid transparent;
    border-top-color: #F4C63D; }
.chartist-tooltip.tooltip-show {
    opacity: 1; }

.ct-area, .ct-line {
  pointer-events: none; }

/*# sourceMappingURL=chartist-plugin-tooltip.css.map */


text:
package me.panavtec.wizard;

import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;

public abstract class WizardPage<T extends Fragment> {

  public abstract T createFragment();

  public void setupActionBar(ActionBar supportActionBar) {
  }

  public boolean hasOptionMenu() {
    return false;
  }

  public boolean allowsBackNavigation() {
    return true;
  }
}


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

<meta http-equiv="Content-Language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery 3-Column Splitter</title>

3-Column Splitter Layout

Here is a 3-column layout using nested splitters. The left and right columns are a semi-fixed width; the center column grows or shrinks. Page scroll bars have been removed since all the content is inside the splitter, and the splitter is anchored to the bottom of the window using an onresize event handler.

See the splitter documentation

This is the left pane of the 3-column splitter. It has been limited to a range of 100 to 250 pixels wide by inline styles. It starts at 150 pixels wide.

This is the center part of the 3-column splitter. It does most of the resizing because the left and right panes were given initial sizes and limits. Try resizing the browser window or moving a splitbar to see what I mean.

The splitbars are keyboard-accessible. Use Alt-Shift-L to select the left vertical splitbar, or Alt-Shift-R for the right one. (Or, press tab until the splitbar you want to move is in focus.) Then use the arrow keys to move the bar.

Splitters nested one or two levels deep are a great solution for user interfaces that just need a small number of user-resizable panes. If the data is more tabular in nature, it would be better to build a plugin that accepted a table as input and created resizable columns.

This is the right pane of the 3-column splitter. It has been limited to a range of 100 to 250 pixels wide by inline styles. It starts at 150 pixels wide.


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { PlanetAddComponent } from './planet-add.component';

describe('PlanetAddComponent', () => {
  let component: PlanetAddComponent;
  let fixture: ComponentFixture<PlanetAddComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ PlanetAddComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PlanetAddComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
<!DOCTYPE html>

  <title>getRTI</title>

  <link rel="stylesheet" href="css/foundation.css">

Home

Find your MP

About

Page4

Mail us at getrti@gmail.com

"Together for an Open Government"

						Locate your constituency & Ask your MP to vote against RTI Amendment

What is getRTI?

					The RTI Act was passed in 2005 and since then, applications have been filed
					and replies received in huge numbers. So a lot of information and data is
					out in the public domain but unfortunately not in one place that is
					searchable by those who want to use it. It is either with
					individuals/organisations but also with government departments/public
					bodies that have dispensed with the information. Information will be
					public in the true sense if it is accessible and reusable.

					So the objectives of the portal are:

					1. Make RTI info publicly available in the true sense of public

					2. Organise it into a neatly searchable format: Central/state, Departments,
					Public bodies, Commissions etc.

					3. Reusable format

					4. Make filing easier using the online platform

					Soochna ka Haq. Your Right to Know. A simple but powerful slogan that got us the Right to Information Act in 2005. RTI has empowered people to ask questions of their government and breach the culture of secrecy pervading the government. This process of transparency has been powered entirely by the citizen. By You.

					Now is the time to take this process of transparency a step further. Massive amount of information has been liberated using the RTI, exposing scams, corruption and blatant abuse of power .  Yet, a lot of this lies scattered in the hands of people and organisations that have filed for such information. We felt it was necessary to build a public database of all RTI requests and replies in a easy, searchable and reusable format to make information open in the real sense. Thus GetRTI.org was born.

					GetRTI  is both a crowd-sourced public repository of all RTI information as well as a filing platform. You can use this platform to search from hundreds and eventually thousands of requests as well as reuse data. If you have ever filed an RTI request, you can scan and upload the document onto the website in easy and simple steps.

					At the end of it all, we aim to create an active space for citizen engagement using the RTI to make government more transparent and accountable. As always, this process will also be driven by the citizen. By you.

					This site has been conceived, built and operated entirely in public interest by volunteers who are non-partisan and are passionate and committed to the idea of Open Government. Together, we can and we shall achieve a government that is answerable to its citizens.

Roadmap

version 0.1

Creative Commons


text:
{% extends 'umanage/base_umanage.html' %}
{% load i18n umanage %}
{% block page_title %}{% trans 'Password Successfully Updated' %} - {% endblock %}

{% block breadcrumb %}

{% trans 'Password Successfully Updated' %}

{% endblock %}

{% block umanage_content %}

{% trans 'Password Successfully Updated' %}

{% trans "Your password has been successfully updated!" %}

{% trans 'Back to account' %}

{% endblock %}


text:
// Tests for RxJS-BackPressure TypeScript definitions
// Tests by Igor Oleinikov <https://github.com/Igorbek>

///<reference path="index.d.ts" />
///<reference path="rx.backpressure.d.ts" />

function testPausable() {
	var o: Rx.Observable<string>;

	var pauser = new Rx.Subject<boolean>();

	var p = o.pausable(pauser);
	p = o.pausableBuffered(pauser);
}

function testControlled() {
	var o: Rx.Observable<string>;
	var c = o.controlled();

	var d: Rx.IDisposable = c.request();
	d = c.request(5);
}


text:
package org.red5.server.messaging;

import org.red5.compatibility.flex.messaging.messages.CommandMessage;
import org.red5.compatibility.flex.messaging.messages.Message;

/**
 * The ServiceAdapter class is the base definition of a service adapter.
 *
 * @author Paul Gregoire
 */
public abstract class ServiceAdapter {

    /**
     * Starts the adapter if its associated Destination is started and if the adapter is not already running. If subclasses override, they must call super.start().
     */
    public void start() {

    }

    /**
     * Stops the ServiceAdapter. If subclasses override, they must call super.start().
     */
    public void stop() {

    }

    /**
     * Handle a data message intended for this adapter. This method is responsible for handling the message and returning a result (if any). The return value of this message is used as the body of the acknowledge message returned to the client. It may be null if there is no data being returned for this message. Typically the data content for the message is stored in the body property of the message. The headers of
     * the message are used to store fields which relate to the transport of the message. The type of operation is stored as the operation property of the message.
     *
     * @param message
     *            the message as sent by the client intended for this adapter
     * @return the body of the acknowledge message (or null if there is no body)
     */
    public abstract Object invoke(Message message);

    /**
     * Accept a command from the adapter's service and perform some internal action based upon it. CommandMessages are used for messages which control the state of the connection between the client and the server. For example, this handles subscribe, unsubscribe, and ping operations. The messageRefType property of the CommandMessage is used to associate a command message with a particular service. Services are
     * configured to handle messages of a particular concrete type. For example, the MessageService is typically invoked to handle messages of type flex.messaging.messages.AsyncMessage. To ensure a given CommandMessage is routed to the right service, its MessageRefType is set to the string name of the message type for messages handled by that service.
     *
     * @param commandMessage
     *            message
     * @return Exception if not implemented
     */
    public Object manage(CommandMessage commandMessage) {
        throw new UnsupportedOperationException("This adapter does not support the manage call");
    }

    /**
     * Returns true if the adapter performs custom subscription management. The default return value is false, and subclasses should override this method as necessary.
     *
     * @return true if subscriptions are handled
     */
    public boolean handlesSubscriptions() {
        return true;
    }

}


text:
:- module( lexicon_home_english, [output_form/2, input_form/2,
				  input_form2/3, digit_word/2,
				  yn_answer/1]).
:- use_module( library(lists), [ member/2, select/3, append/3 ] ).
:- use_module( library(charsio), [ format_to_chars/3 ] ).

/*----------------------------------------------------------------------
     output_form( +Move, -String )
     -- Canned output
----------------------------------------------------------------------*/

output_form( ask(X^(task(X))), "What can I do for you?" ).

output_form( ask(task(T)), Str ):-
	output_form(task(T), StrT ),
	append( "Do you want to ", StrT, Str0 ),
	append( Str0, " ?", Str).

output_form( ask(TaskList), Str ) :-
	TaskList = [task(_)|_],
	altlist2altstr_or( TaskList, AltStr ),
	append( "Do you want to ", AltStr, Str0 ),
	append( Str0, " ?", Str).

output_form( ask(X^(device(X))), "What object are you referring to?" ).
output_form( ask(X^(device_type(X))), "What object are you referring to?" ).
output_form( ask(X^(action(X))), "What do you want to do?" ).
output_form( ask(X^(device_state(X))), "What do you want to know?" ).
output_form( ask(X^(location(X))), "Where?" ).
output_form( ask(main_menu), "Do you want to choose another domain?" ).

output_form( ask(light(X)), Str ) :-
	atom_chars(X,XS),
	append( "Do you want to turn on the light in the ", XS, Str0 ),
	append( Str0, "?", Str ).

output_form( ask(leave_on_light),
	     "Do you want to leave the light on in any of the rooms?" ).

output_form( task(perform_specific_action), "change the light in any of the rooms" ).
output_form( task(make_query), "make a query").
output_form( task(main_menu), "choose another domain" ).
output_form( task(wake_up), "set to morning mode" ).
output_form( task(leaving), "set to leaving mode" ).

output_form( inform(device_already_switched_on(_,L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "The lamp in the ~s is already switched on.", [LS], Cs ).
output_form( inform(device_already_switched_off(_,L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "The lamp in the ~s is already switched off.", [LS], Cs ).
output_form( inform(light_already_dimmed(_,L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "The light in the ~s is already dimmed.", [LS], Cs ).

output_form( inform(no_lamp_in(_)),
	     "There is no lamp there." ).
output_form( inform(no_dimmer_in(_)),
	     "There is no dimmer there." ).

output_form( inform(is_switched_onoff(OnOff,S,L)), Cs ) :-
	concept_string( L, LS ),
	( ( ( OnOff = on,  S = switched_on ) ;
	    ( OnOff = off, S = switched_off ) ) ->
	    CR = "Yes" ; CR = "No" ),
	format_to_chars( "~s, the lamp in the ~s is switched ~a.", [CR,LS,OnOff], Cs ).

output_form( inform(is_dimmed(_,L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "The light in the ~s is dimmed.", [LS], Cs ).
output_form( inform(is_not_dimmed(_,L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "The light in the ~s is not dimmed.", [LS], Cs ).

output_form( inform(bad_action(lamp)),
	     "You can't do that with a lamp." ).
output_form( inform(bad_action(dimmer)),
	     "You can't do that with a dimmer." ).

output_form( inform(switched_on_lamp(L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "OK. The lamp in the ~s is now switched on.", [LS], Cs ).
output_form( inform(switched_off_lamp(L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "OK. The lamp in the ~s is now switched off.", [LS], Cs ).
output_form( inform(dimmed_light(L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "OK. The light in the ~s is now dimmed.", [LS], Cs ).

output_form( inform(woken_up_lit_kitchen),
	     "Switched to morning mode. All lights are now switched on." ).
output_form( inform(woken_up_no_lit_kitchen),
	     "Switched to morning mode. All lights except for the one in the kitchen are now switched on." ).

output_form( inform(closed_down_except(L)), Cs ) :-
	concept_string( L, LS ),
	format_to_chars( "OK. All lights except the one in the ~s have been shut down.", [LS], Cs ).
output_form( inform(closed_down_all),
	     "OK. All lights have been shut down." ).

output_form( greet, "Welcome to the home device manager!" ).
output_form( quit, "Good bye!" ).
output_form( reqRep(understanding), "I didnt understand what you said. Please rephrase." ).
output_form( reqRep(relevance), "What do you mean by that?" ).
output_form( thank, "Thank you very much." ).
output_form( confirm, "OK" ).

% repeating a move

output_form( repeat(Move), Str ):-
	output_form( Move, Str ).

altlist2altstr_and( [D], Str ):-
	alt2altstr( D, Str1 ),
	append( " and ", Str1, Str ).
altlist2altstr_and( [D|Ds], Str ):-
	alt2altstr( D, Str1 ),
	altlist2altstr_and( Ds, Str2 ),
	append( Str1, ", ", Str3 ),
	append(Str3, Str2, Str ).

altlist2altstr_or( [D], Str ):-
	alt2altstr( D, Str1 ),
	append( " or ", Str1, Str ).
altlist2altstr_or( [D|Ds], Str ):-
	alt2altstr( D, Str1 ),
	altlist2altstr_or( Ds, Str2 ),
	append( Str1, ", ", Str3 ),
	append(Str3, Str2, Str ).

alt2altstr( D, Str ):-
	output_form( D, Str ).

alt2altstr( D, Str ):-
	name( D, Str ).

/*----------------------------------------------------------------------
     input_form( +Phrase, -Move )
     -- Almost canned input
----------------------------------------------------------------------*/

input_form( [turn,on],      answer(action(switch_on)) ).
input_form( [turn,off],     answer(action(switch_off)) ).
input_form( [turn,it,on],   answer(action(switch_on)) ).
input_form( [turn,it,off],  answer(action(switch_off)) ).
input_form( [switch,on],    answer(action(switch_on)) ).
input_form( [switch,off],   answer(action(switch_off)) ).
input_form( [switch,it,on], answer(action(switch_on)) ).
input_form( [switch,it,off],answer(action(switch_off)) ).
input_form( [dim,the,light],answer(action(dim_light)) ).
input_form( [dim,it],       answer(action(dim_light)) ).

input_form( [turned,on],    answer(device_state(switched_on)) ).
input_form( [turned,off],   answer(device_state(switched_off)) ).
input_form( [switched,on],  answer(device_state(switched_on)) ).
input_form( [switched,off], answer(device_state(switched_off)) ).
input_form( [dimmed],       answer(device_state(dimmed)) ).

input_form( [change,domain],answer(task(main_menu)) ).
input_form( [change],       answer(task(perform_specific_action)) ).
input_form( [wake,up],      answer(task(wake_up)) ).
input_form( [good,morning], answer(task(wake_up)) ).
input_form( [morning,mode], answer(task(wake_up)) ).
input_form( [going,out],    answer(task(leaving)) ).
input_form( [leaving],      answer(task(leaving)) ).
input_form( [query],        answer(task(make_query)) ).
input_form( [is,the],       answer(task(make_query)) ).
input_form( [leave,on,the,light], answer(leave_on_light) ).
input_form( [leave,the,light,on], answer(leave_on_light) ).
input_form( [domain],       answer(task(main_menu))).

input_form( S, M ) :-
	lexsem( S, C ),
	input_move( C, M ).

% simple stuff

input_form( [hi], greet ).
input_form( [hello], greet ).
input_form( [bye], quit ).
input_form( [goodbye], quit ).
input_form( [quit], quit ).
input_form( [what,did,you,say], reqRep ).
input_form( ['what?'], reqRep ).
input_form( [sorry], reqRep ).
input_form( [pardon], reqRep ).
input_form( [yes], answer(yes) ).
input_form( [no], answer(no) ).
input_form( [okay], ack ).
input_form( [ok], ack ).
input_form( [aha], ack ).

% concepts

input_move( L, answer(location(L)) ) :-
	location( L ).

input_move( T, answer(device_type(T)) ) :-
	device_type( T ).

% don't use complex interpretation

input_form2( _, _, _ ) :- fail.

% do not use numbers

digit_word(_,_) :- fail.

/*----------------------------------------------------------------------
     lexsem( ?Word, ?Concept )
     -- Lexical semantics
----------------------------------------------------------------------*/

lexsem( Word, Concept ):-
	synset( Words, Concept ),
	member( Word, Words ).

%synset( [[lamp], [light]], lamp ).
synset( [[lamp]], lamp ).
synset( [[dimmer]], dimmer ).
synset( [[kitchen], [diner]], kitchen ).
synset( [[tv,room], [tele,room], [television,room]], tv_room ).
synset( [[living,room], ['living-room']], living_room ).
synset( [[hall]], hall ).
synset( [[hobby]], hobby_room ).
synset( [[study]], study ).

% yes or no answer

yn_answer(A):-
	A = 'yes';
	A = 'no'.

% from concept to string (pick the first synonym)

concept_string( Concept, String ) :-
	synset( [Words|_], Concept ),
	concat_words( Words, String ).

concat_words( [Word], String ) :-
	atom_chars( Word, String ).

concat_words( [Word|Words], String ) :-
	atom_chars( Word, S1 ),
	concat_words( Words, S2 ),
	append( S1, [ 0' | S2 ], String ).

/*----------------------------------------------------------------------
     - Domain concepts
----------------------------------------------------------------------*/

action( X ) :- domain_home:action( X ).
task( T ) :- domain_home:task( T ).
location( L ) :- domain_home:location( L ).
device_type( T ) :- domain_home:device_type( T ).

sublist( SubList, List ) :-
	append( _, Suffix, List ),
	append( SubList, _, Suffix ).


text:
import java.util.*;

public class Main {
  public void testBitwiseAndHighestBit() {
    int[] arr = {0x80000000, 0xffffffff};
      int acc = Arrays.stream(arr).reduce(-1, (a, b) -> a & b);
  }
}


text:
"use strict";

const webpack = require('webpack');
const path = require('path');
const pkg = require('./package.json');
const fs = require('fs');
const execSync = require('child_process').execSync;
const TerserPlugin = require('terser-webpack-plugin');

module.exports = (env = {}) => {
  const isDevServer = Boolean(process.env.WEBPACK_DEV_SERVER);
  const minimize = env.MINIMIZE || isDevServer || false;
  const alpha = env.ALPHA || false;
  const maxSize = 450 * 1024;
  const commitHash = execSync('git rev-parse --short HEAD').toString().trim();
  const version = !alpha ? pkg.version : `${pkg.version}-alpha+${commitHash}`;
  const license = fs.readFileSync('LICENSE', 'utf8');
  const name = pkg.name;
  const alphaInfo = 'Experimental pre-release build.\n  ';

  const banner =
`${pkg.name} ${version} by @liabru
${alpha ? alphaInfo : ''}${pkg.homepage}
License ${pkg.license}${!minimize ? '\n\n' + license : ''}`;

  return {
    entry: { [name]: './src/index' },
    output: {
      library: 'MatterTools',
      publicPath: '/demo/lib/',
      libraryTarget: 'umd',
      umdNamedDefine: true,
      globalObject: 'this',
      path: path.resolve(__dirname, './build'),
      filename: `${name}${alpha ? '.alpha' : ''}${minimize ? '.min' : ''}.js`
    },
    module: {
      rules: [
        {
          test: /\.css$/i,
          use: [
            {
              loader: 'raw-loader',
              options: {
              esModule: false,
              },
            },
          ],
        }
      ]
    },
    node: false,
    optimization: {
      minimize,
      minimizer: [
        new TerserPlugin({
          extractComments: false,
          terserOptions: {
            output: {
              comments: /license|copyright|\(c\)/ig,
            },
          }
        })
      ]
    },
    performance: {
      maxEntrypointSize: maxSize,
      maxAssetSize: maxSize
    },
    plugins: [
      new webpack.BannerPlugin(banner),
      new webpack.DefinePlugin({
        '%NAME%': name,
        '%VERSION%': version
      })
    ],
    resolve: {
      alias: {
        'jquery': 'jquery/dist/jquery.min',
        'jstree': 'jstree/dist/jstree.min',
        'dat.gui': 'dat.gui/build/dat.gui.min',
        'Demo': path.resolve(__dirname, 'src/tools/Demo'),
        'Gui': path.resolve(__dirname, 'src/tools/Gui'),
        'Inspector': path.resolve(__dirname, 'src/tools/Inspector'),
        'Serializer': path.resolve(__dirname, 'src/tools/Serializer')
      }
    },
    externals: {
      'matter-js': {
        commonjs: 'matter-js',
        commonjs2: 'matter-js',
        amd: 'matter-js',
        root: 'Matter'
      }
    },
    devServer: {
      watchContentBase: true,
      hot: false,
      compress: true,
      overlay: true,
      port: 8080,
      contentBase: [
        path.resolve(__dirname, './docs'),
        path.resolve(__dirname, './node_modules/matter-js/build')
      ],
      proxy: {
        '/demo/lib/matter.min.js': {
          target: 'http://localhost:8080/',
          pathRewrite: { '^/demo/lib/' : '/' }
        }
      }
    }
  };
};


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

namespace Microsoft.CodeAnalysis.Simplification
{
    // When applied to a SyntaxNode, prevents AbstractImportsAdder from adding imports for this
    // node. Applied alongside SymbolAnnotation when a type should be simplified without adding a
    // using for the type.
    //
    // For example, override completion adds void goo() => throw new
    // System.NotImplementedException() with a SymbolAnnotation and a DoNotAddImportsAnnotation.
    //
    // This allows the simplifier to remove the `System.` if `using System` is already in the file
    // but prevents the addition of `using System` just for the NotImplementedException.
    //
    // This could have been implemented as an additional bit serialized into the `Data` string of
    // SymbolAnnotation. However that would require additional substring operations to retrieve
    // SymbolAnnotation symbols even in the common case where we don't need to suppress add imports.
    // This is therefore implemented as a separate annotation.
    internal class DoNotAddImportsAnnotation
    {
        public static readonly SyntaxAnnotation Annotation = new(Kind);
        public const string Kind = "DoNotAddImports";
    }
}


text:
using namespace std;

//Funckija za posodobitev youtube-dl
void posodobitev()
{
    stringstream posodobitev_string;
    posodobitev_string << "youtube-dl.exe -U"; //String za posodobitev
    system(posodobitev_string.str().c_str());
}

//Funkcija za pretvorbo prenesenega videa
void pretvorba_prenesenega() //Trenutno v testni fazi
{
    system("cls");
    system("cd output & dir /b *.mp4"); //Prikaže vse .mp4 datoteke v mapi output.
    cout << "\n" << endl;
    cout << "Vnesite naslov videa:" << endl;
    cout << "OPOMBA: Naslov vnesi v narekovajih drugace ne bo delovalo!" << endl;
    cout << "Naslov: ";
    string naslov_videa ="";
    cin.ignore();
    getline(cin, naslov_videa); //Uporaba getline namesto navadnega cin da zazna celoten vnos z narekovaji.
    izbris_prompt:
    int izbris;
    cout << "\nZelite obdrzati .mp4 datoteko? (1[da]/0[ne]): ";
    cin >> izbris;
    stringstream premakni_mp4, konvertiraj, premakni_mp3, zbris_mp4, obdrzi_mp4;
    cout << naslov_videa;
    premakni_mp4 << "cd output & move " << naslov_videa << " .."; //Premakne .mp4 datoteko iz output mape v mapo kjer se nahaja program
    konvertiraj << "ffmpeg -i " << naslov_videa << " -c:v lib264 " << naslov_videa << ".mp3"; //Pretvori premaknjeno .mp4 datoteko
    premakni_mp3  << "move " << naslov_videa << ".mp3 output"; //Premakne novo .mp3 datoteko katera je bila pretvorjena v mapo output
    zbris_mp4 << "del /q /f " << naslov_videa; //Zbrise .mp4 datoteko po pretvorbi
    obdrzi_mp4 << "move " << naslov_videa << " output"; //Premakne .mp4 datoteko v primeru da je ne zelimo izbrisati

    if(izbris == 1)
    {
        system(premakni_mp4.str().c_str());
        system(konvertiraj.str().c_str());
        system(premakni_mp3.str().c_str());
        system(obdrzi_mp4.str().c_str());
    }
    else if (izbris == 0)
    {
        system(premakni_mp4.str().c_str());
        system(konvertiraj.str().c_str());
        system(premakni_mp3.str().c_str());
        system(zbris_mp4.str().c_str());
    }
    else
        goto izbris_prompt;

}

//Funkcija poslje informacije za formate
void format_info()
{
    cout << "\"Hitri\" formati:" << endl;
    cout << "1. mp3" << endl;
    cout << "2. aac" << endl;
    cout << "3. wav" << endl;
    cout << "4. vorbis" << endl;
    cout << "5. opus" << endl;
    cout << "6. m4a" << endl;
    cout << "Vpisi stevilko za hitri format ali vpisi ime formata v katerega zelis pretvoriti" << endl;
}

//Funkcija za pretvorbo stevilk hitrih formatov(int) v string
string formati(string vhodni_format)
{
    //Program preveri ce je uporabnik uporabil številko za hitri format, ce ne uporabi vpisan format
    if(vhodni_format == "1")
    {
        vhodni_format = "mp3";
    }
    else if(vhodni_format == "2")
    {
        vhodni_format = "aac";
    }
    else if(vhodni_format == "3")
    {
        vhodni_format = "wav";
    }
    else if(vhodni_format == "4")
    {
        vhodni_format = "vorbis";
    }
    else if(vhodni_format == "5")
    {
        vhodni_format = "opus";
    }
    else if(vhodni_format == "6")
    {
        vhodni_format = "m4a";
    }
    return vhodni_format;
}

//Funkcija samo za prenos videa
void prenos_videa()
{
    string url;
    system("cls");
    cout << "URL Naslov videa: ";
    cin >> url;
    stringstream vnos_podatkov;
    vnos_podatkov << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --keep-video --ignore-errors -f best " << url; //String za prenos videa v mp4 formatu
    system(vnos_podatkov.str().c_str());
}

//Funkcija za prenos in pretvorbo videa
void prenos_in_pretvorba()
{
    pip_vnos:  //Zaèetek za vnosa; V primeru da uporanbik ne vpiše èesar pravilno ga vrne na zaèetek vpisa za prenos in pretvorbo
    string url, format;
    int obdrzi;
    stringstream obdrzi_datoteko_string, zbrisi_datoteko_string;
    system("cls");
    cout << "Vnesi URL videa: ";
    cin >> url;
    format_info();
    cout << "Vnesi format: ";
    cin >> format;
    format=formati(format); //Poklice funkcijo s formati in vrne string v primeru da smo vnesli stevilko.
    cout << "Zelite obdrzati izvorno datoteko? (DA [1]/NE [0]) " << endl;
    cout << "Vasa izbira: ";
    cin >> obdrzi;

    switch(obdrzi)
    {
        //Pretvori izvorno datoteko in jo obdrzi
        case 1:
        obdrzi_datoteko_string << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --keep-video --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
        system(obdrzi_datoteko_string.str().c_str());
        break;

        //Izbris izvorne datoteke po pretvorbi
        case 0:
        zbrisi_datoteko_string << "youtube-dl.exe --output /output/%(title)s.%(ext)s --console-title --ignore-errors --extract-audio --audio-quality 0 --audio-format " << format << " " << url;
        system(zbrisi_datoteko_string.str().c_str());
        break;

        //Povrne uporabnika nazaj na vpis v primeru, da ni vpisal 1(da) ali 0 (ne).
        default:
            goto pip_vnos;
    }

}

int main()
{
    int zacetna_izbira;
    //Program nastavi pisavo na zeleno  barvo in prikaze zagonsko sporocilo
    system("color A");
    cout << "Dobrodosli v uporabniskem vmesniku za Youtube-dl \n" << endl;
    cout << "Program Youtube-dl in ffmpeg sta tuja programa in pripadata svojim lastnikom" << endl;
    cout << "Ta program je samo uporabniski vmesnik kateri je namenjen lazji uporabi teh programov" << endl;

    //Program pocaka uporabnika, da pritisne tipko za nadaljevanje, pobirse sporocilo in nastavi pisavo nazaj na belo
    system("pause");
    system("cls");
    system("color F");

    //Zacetna izbira
    zacetek:
    cout << "1. Posodobitev" << endl;
    cout << "2. Prenos videa" << endl;
    cout << "3. Prenos in pretvorba videa" << endl;
    cout << "4. Pretvorba prenesenega videa v mp3" << endl;
    cout << "0. Izhod iz programa" << endl;
    cout << "Vasa izbira: ";
    cin >> zacetna_izbira;

    //Switch za zacetno izbiro glede na uporabnikov vnos
    switch(zacetna_izbira)
    {

    //Izhod iz programa
    case 0:
        return 0;
        break;

    //Program gre na funkcijo za posodobitev
    case 1:
        posodobitev();
        break;

    //Funkcija za samo prenos videa
    case 2:
        prenos_videa();
        break;

    //Funkcija za prenos in pretvorbo videa
    case 3:
        prenos_in_pretvorba();
        break;

    //Funkcija za pretvorbo prenesenih videev
    case 4:
        pretvorba_prenesenega();
        break;

    //Vrne uporabnika na zacetek ce je vnesel napacno stevilko
    default:
        goto zacetek;
        cout << "Napacna izbira! Poskusi znova." << endl;
        system("pause");
        system("cls");
        break;
    }

    //Se izvede po pretvorbi, prenosu ali kater koli drugi funkciji
    nadaljevanje:
    int nadaljuj;
    system("cls");
    cout << "Zelite nadaljevati? (DA [1]/NE [0]): " ;
    cin >> nadaljuj;

    switch(nadaljuj)
    {
        //Vrne se na zacetek za izbiro funkcij
        case 1:
            goto zacetek;
            break;

        //Konca program
        case 0:
            return 0;
            break;

        //Pozove uporabnika za ponoven vnos v primeru napacnega vnosa.
        default:
            cout << "Napacen vnos! Poskusi znova.";
            break;
    }

}


text:
package com.bright.mvc.mapping;

import com.bright.boot.IBootService;
import com.bright.mvc.data.jdbc.pool.DBBoot;
import com.bright.mvc.view.page.Jspx;
import com.bright.util.jsonx.Jsonx;

public class BaseMapping implements IBootService {

    public static Jsonx mapping;

    @Override
    public void serviceStart(Jsonx option) {
        mapping = option;
        String controllerPath = option.get("controller").toString();
        ControllerContainer.getContainer().start(controllerPath);
        FilterContainer.getContainer().start(option.get("filter").toString());
        Jspx.init(option.get("view"));
        ServiceContainer.getContainer().start(option.get("service").toString());
        ModelContainer.getContainer().start(option.get("model").toString());
        DaoContainer.getCotnainer().start(option.get("dao").toString());
        new DBBoot(option.get("jdbc"));
    }

    @Override
    public void serviceStop() {
    }
}


text:
require 'active_support/dependencies'

module Gingham
  # Utility
  autoload :VERSION, 'gingham/version'
  autoload :PathFinder, 'gingham/path_finder'
  autoload :MoveSimulator, 'gingham/move_simulator'
  autoload :ActionSimulator, 'gingham/action_simulator'
  autoload :MoveStatus, 'gingham/move_status'

  # World
  autoload :Naterua, 'gingham/naterua' # GameMaster
  autoload :Space, 'gingham/space'
  autoload :Cell, 'gingham/cell'
  autoload :Position, 'gingham/position'
  autoload :Direction, 'gingham/direction'
  autoload :Waypoint, 'gingham/waypoint'

  # Objects
  autoload :Actor, 'gingham/actor'

  # Timeline
  autoload :TimeLine, 'gingham/time_line'
  autoload :MoveFrame, 'gingham/move_frame'
  autoload :ActionFrame, 'gingham/action_frame'
end


text:
package org.opencb.opencga.storage.core.metadata.adaptors;

import com.google.common.collect.Iterators;
import org.apache.commons.lang3.time.StopWatch;
import org.opencb.biodata.models.variant.VariantFileMetadata;
import org.opencb.commons.datastore.core.DataResult;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryParam;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.core.metadata.models.FileMetadata;
import org.opencb.opencga.storage.core.metadata.models.Lock;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Cristina Yenyxe Gonzalez Garcia <cyenyxe@ebi.ac.uk>
 */
public interface FileMetadataDBAdaptor extends AutoCloseable {

    enum VariantFileMetadataQueryParam implements QueryParam {
        STUDY_ID("studyId", Type.INTEGER_ARRAY),
        FILE_ID("fileId", Type.INTEGER_ARRAY);

        private final String key;
        private final Type type;

        VariantFileMetadataQueryParam(String key, Type type) {
            this.key = key;
            this.type = type;
        }

        @Override
        public String key() {
            return key;
        }

        @Override
        public Type type() {
            return type;
        }

        @Override
        public String description() {
            return "";
        }
    }

    FileMetadata getFileMetadata(int studyId, int fileId, Long timeStamp);

    Iterator<FileMetadata> fileIterator(int studyId);

    void updateFileMetadata(int studyId, FileMetadata file, Long timeStamp);

    Integer getFileId(int studyId, String fileName);

    LinkedHashSet<Integer> getIndexedFiles(int studyId);

    default void addIndexedFiles(int studyId, List<Integer> fileIds) {}

    default void removeIndexedFiles(int studyId, Collection<Integer> fileIds) {};

    default DataResult count() {
        return count(new Query());
    }

    DataResult count(Query query);

    default void updateVariantFileMetadata(Number studyId, VariantFileMetadata metadata) throws StorageEngineException {
        updateVariantFileMetadata(studyId.toString(), metadata);
    }

    void updateVariantFileMetadata(String studyId, VariantFileMetadata metadata) throws StorageEngineException;

    default DataResult<VariantFileMetadata> getVariantFileMetadata(int studyId, int fileId, QueryOptions options)
            throws StorageEngineException {
        StopWatch stopWatch = StopWatch.createStarted();
        Iterator<VariantFileMetadata> iterator;
        try {
            Query query = new Query(VariantFileMetadataQueryParam.FILE_ID.key(), fileId)
                    .append(VariantFileMetadataQueryParam.STUDY_ID.key(), studyId);
            iterator = iterator(query, options);
        } catch (IOException e) {
            throw new StorageEngineException("Error reading from FileMetadataDBAdaptor", e);
        }
        VariantFileMetadata metadata = Iterators.getOnlyElement(iterator, null);
        if (metadata != null) {
            return new DataResult<>(((int) stopWatch.getTime(TimeUnit.MILLISECONDS)), Collections.emptyList(), 1,
                    Collections.singletonList(metadata), 1);
        } else {
            return new DataResult<>(((int) stopWatch.getTime(TimeUnit.MILLISECONDS)), Collections.emptyList(), 0, Collections.emptyList(),
                    0);
        }
    }

    Iterator<VariantFileMetadata> iterator(Query query, QueryOptions options) throws IOException;

//    DataResult<String> getSamplesBySource(String fileId, QueryOptions options);

//    DataResult<String> getSamplesBySources(List<String> fileIds, QueryOptions options);

//    DataResult updateStats(VariantSourceStats variantSourceStats, StudyConfiguration studyConfiguration, QueryOptions queryOptions);

    void removeVariantFileMetadata(int study, int file) throws IOException;

    void close() throws IOException;

    Lock lock(int studyId, int id, long lockDuration, long timeout) throws StorageEngineException;
}


text:
<?php
	define('DIR_BASE', dirname( dirname( __FILE__ ) ) . '/hci/');

	date_default_timezone_set('America/Chicago');

	define('ROOT', 'http://localhost:81/hci');