text:
// ==========================================================================
// Project:   Ember - JavaScript Application Framework
// Copyright: Copyright 2013 Stefan Penner and Ember App Kit Contributors
// License:   Licensed under MIT license
//            See https://raw.github.com/ember-cli/ember-resolver/master/LICENSE
// ==========================================================================

 // Version: 0.1.20

(function() {
/*globals define registry requirejs */

define("ember/resolver",
  [],
  function() {
    "use strict";

    if (typeof requirejs.entries === 'undefined') {
      requirejs.entries = requirejs._eak_seen;
    }

  /*
   * This module defines a subclass of Ember.DefaultResolver that adds two
   * important features:
   *
   *  1) The resolver makes the container aware of es6 modules via the AMD
   *     output. The loader's _moduleEntries is consulted so that classes can be
   *     resolved directly via the module loader, without needing a manual
   *     `import`.
   *  2) is able to provide injections to classes that implement `extend`
   *     (as is typical with Ember).
   */

  function classFactory(klass) {
    return {
      create: function (injections) {
        if (typeof klass.extend === 'function') {
          return klass.extend(injections);
        } else {
          return klass;
        }
      }
    };
  }

  var create = (Object.create || Ember.create);
  if (!(create && !create(null).hasOwnProperty)) {
    throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg");
  }

  function makeDictionary() {
    var cache = create(null);
    cache['_dict'] = null;
    delete cache['_dict'];
    return cache;
  }

  var underscore = Ember.String.underscore;
  var classify = Ember.String.classify;
  var get = Ember.get;

  function parseName(fullName) {
    /*jshint validthis:true */

    if (fullName.parsedName === true) { return fullName; }

    var prefix, type, name;
    var fullNameParts = fullName.split('@');

    // Htmlbars uses helper:@content-helper which collides
    // with ember-cli namespace detection.
    // This will be removed in a future release of Htmlbars.
    if (fullName !== 'helper:@content-helper' &&
        fullNameParts.length === 2) {
      var prefixParts = fullNameParts[0].split(':');

      if (prefixParts.length === 2) {
        prefix = prefixParts[1];
        type = prefixParts[0];
        name = fullNameParts[1];
      } else {
        var nameParts = fullNameParts[1].split(':');

        prefix = fullNameParts[0];
        type = nameParts[0];
        name = nameParts[1];
      }
    } else {
      fullNameParts = fullName.split(':');
      type = fullNameParts[0];
      name = fullNameParts[1];
    }

    var fullNameWithoutType = name;
    var namespace = get(this, 'namespace');
    var root = namespace;

    return {
      parsedName: true,
      fullName: fullName,
      prefix: prefix || this.prefix({type: type}),
      type: type,
      fullNameWithoutType: fullNameWithoutType,
      name: name,
      root: root,
      resolveMethodName: "resolve" + classify(type)
    };
  }

  function resolveOther(parsedName) {
    /*jshint validthis:true */

    // Temporarily disabling podModulePrefix deprecation
    /*
    if (!this._deprecatedPodModulePrefix) {
      var podModulePrefix = this.namespace.podModulePrefix || '';
      var podPath = podModulePrefix.substr(podModulePrefix.lastIndexOf('/') + 1);

      Ember.deprecate('`podModulePrefix` is deprecated and will be removed '+
        'from future versions of ember-cli. Please move existing pods from '+
        '\'app/' + podPath + '/\' to \'app/\'.', !this.namespace.podModulePrefix);

      this._deprecatedPodModulePrefix = true;
    }
    */
    Ember.assert('`modulePrefix` must be defined', this.namespace.modulePrefix);

    var normalizedModuleName = this.findModuleName(parsedName);

    if (normalizedModuleName) {
      var defaultExport = this._extractDefaultExport(normalizedModuleName, parsedName);

      if (defaultExport === undefined) {
        throw new Error(" Expected to find: '" + parsedName.fullName + "' within '" + normalizedModuleName + "' but got 'undefined'. Did you forget to `export default` within '" + normalizedModuleName + "'?");
      }

      if (this.shouldWrapInClassFactory(defaultExport, parsedName)) {
        defaultExport = classFactory(defaultExport);
      }

      return defaultExport;
    } else {
      return this._super(parsedName);
    }
  }

  // Ember.DefaultResolver docs:
  //   https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
  var Resolver = Ember.DefaultResolver.extend({
    resolveOther: resolveOther,
    resolveTemplate: resolveOther,
    pluralizedTypes: null,

    makeToString: function(factory, fullName) {
      return '' + this.namespace.modulePrefix + '@' + fullName + ':';
    },
    parseName: parseName,
    shouldWrapInClassFactory: function(module, parsedName){
      return false;
    },
    init: function() {
      this._super();
      this.moduleBasedResolver = true;
      this._normalizeCache = makeDictionary();

      this.pluralizedTypes = this.pluralizedTypes || makeDictionary();

      if (!this.pluralizedTypes.config) {
        this.pluralizedTypes.config = 'config';
      }

      this._deprecatedPodModulePrefix = false;
    },
    normalize: function(fullName) {
      return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this._normalize(fullName));
    },
    _normalize: function(fullName) {
      // replace `.` with `/` in order to make nested controllers work in the following cases
      // 1. `needs: ['posts/post']`
      // 2. `{{render "posts/post"}}`
      // 3. `this.render('posts/post')` from Route
      var split = fullName.split(':');
      if (split.length > 1) {
        return split[0] + ':' + Ember.String.dasherize(split[1].replace(/\./g, '/'));
      } else {
        return fullName;
      }
    },

    pluralize: function(type) {
      return this.pluralizedTypes[type] || (this.pluralizedTypes[type] = type + 's');
    },

    podBasedLookupWithPrefix: function(podPrefix, parsedName) {
      var fullNameWithoutType = parsedName.fullNameWithoutType;

      if (parsedName.type === 'template') {
        fullNameWithoutType = fullNameWithoutType.replace(/^components\//, '');
      }

        return podPrefix + '/' + fullNameWithoutType + '/' + parsedName.type;
    },

    podBasedModuleName: function(parsedName) {
      var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;

      return this.podBasedLookupWithPrefix(podPrefix, parsedName);
    },

    podBasedComponentsInSubdir: function(parsedName) {
      var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix;
      podPrefix = podPrefix + '/components';

      if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) {
        return this.podBasedLookupWithPrefix(podPrefix, parsedName);
      }
    },

    mainModuleName: function(parsedName) {
      // if router:main or adapter:main look for a module with just the type first
      var tmpModuleName = parsedName.prefix + '/' + parsedName.type;

      if (parsedName.fullNameWithoutType === 'main') {
        return tmpModuleName;
      }
    },

    defaultModuleName: function(parsedName) {
      return parsedName.prefix + '/' +  this.pluralize(parsedName.type) + '/' + parsedName.fullNameWithoutType;
    },

    prefix: function(parsedName) {
      var tmpPrefix = this.namespace.modulePrefix;

      if (this.namespace[parsedName.type + 'Prefix']) {
        tmpPrefix = this.namespace[parsedName.type + 'Prefix'];
      }

      return tmpPrefix;
    },

    /**

      A listing of functions to test for moduleName's based on the provided
      `parsedName`. This allows easy customization of additional module based
      lookup patterns.

      @property moduleNameLookupPatterns
      @returns {Ember.Array}
    */
    moduleNameLookupPatterns: Ember.computed(function(){
      return Ember.A([
        this.podBasedModuleName,
        this.podBasedComponentsInSubdir,
        this.mainModuleName,
        this.defaultModuleName
      ]);
    }),

    findModuleName: function(parsedName, loggingDisabled){
      var self = this;
      var moduleName;

      this.get('moduleNameLookupPatterns').find(function(item) {
        var moduleEntries = requirejs.entries;
        var tmpModuleName = item.call(self, parsedName);

        // allow treat all dashed and all underscored as the same thing
        // supports components with dashes and other stuff with underscores.
        if (tmpModuleName) {
          tmpModuleName = self.chooseModuleName(moduleEntries, tmpModuleName);
        }

        if (tmpModuleName && moduleEntries[tmpModuleName]) {
          if (!loggingDisabled) {
            self._logLookup(true, parsedName, tmpModuleName);
          }

          moduleName = tmpModuleName;
        }

        if (!loggingDisabled) {
          self._logLookup(moduleName, parsedName, tmpModuleName);
        }

        return moduleName;
      });

      return moduleName;
    },

    chooseModuleName: function(moduleEntries, moduleName) {
      var underscoredModuleName = Ember.String.underscore(moduleName);

      if (moduleName !== underscoredModuleName && moduleEntries[moduleName] && moduleEntries[underscoredModuleName]) {
        throw new TypeError("Ambiguous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
      }

      if (moduleEntries[moduleName]) {
        return moduleName;
      } else if (moduleEntries[underscoredModuleName]) {
        return underscoredModuleName;
      } else {
        // workaround for dasherized partials:
        // something/something/-something => something/something/_something
        var partializedModuleName = moduleName.replace(/\/-([^\/]*)$/, '/_$1');

        if (moduleEntries[partializedModuleName]) {
          Ember.deprecate('Modules should not contain underscores. ' +
                          'Attempted to lookup "'+moduleName+'" which ' +
                          'was not found. Please rename "'+partializedModuleName+'" '+
                          'to "'+moduleName+'" instead.', false);

          return partializedModuleName;
        } else {
          return moduleName;
        }
      }
    },

    // used by Ember.DefaultResolver.prototype._logLookup
    lookupDescription: function(fullName) {
      var parsedName = this.parseName(fullName);

      var moduleName = this.findModuleName(parsedName, true);

      return moduleName;
    },

    // only needed until 1.6.0-beta.2 can be required
    _logLookup: function(found, parsedName, description) {
      if (!Ember.ENV.LOG_MODULE_RESOLVER && !parsedName.root.LOG_RESOLVER) {
        return;
      }

      var symbol, padding;

      if (found) { symbol = '[✓]'; }
      else       { symbol = '[ ]'; }

      if (parsedName.fullName.length > 60) {
        padding = '.';
      } else {
        padding = new Array(60 - parsedName.fullName.length).join('.');
      }

      if (!description) {
        description = this.lookupDescription(parsedName);
      }

      Ember.Logger.info(symbol, parsedName.fullName, padding, description);
    },

    knownForType: function(type) {
      var moduleEntries = requirejs.entries;
      var moduleKeys = (Object.keys || Ember.keys)(moduleEntries);

      var items = makeDictionary();
      for (var index = 0, length = moduleKeys.length; index < length; index++) {
        var moduleName = moduleKeys[index];
        var fullname = this.translateToContainerFullname(type, moduleName);

        if (fullname) {
          items[fullname] = true;
        }
      }

      return items;
    },

    translateToContainerFullname: function(type, moduleName) {
      var prefix = this.prefix({ type: type });
      var pluralizedType = this.pluralize(type);
      var nonPodRegExp = new RegExp('^' + prefix + '/' + pluralizedType + '/(.+)$');
      var podRegExp = new RegExp('^' + prefix + '/(.+)/' + type + '$');
      var matches;

      if ((matches = moduleName.match(podRegExp))) {
        return type + ':' + matches[1];
      }

      if ((matches = moduleName.match(nonPodRegExp))) {
        return type + ':' + matches[1];
      }
    },

    _extractDefaultExport: function(normalizedModuleName) {
      var module = require(normalizedModuleName, null, null, true /* force sync */);

      if (module && module['default']) {
        module = module['default'];
      }

      return module;
    }
  });

  Resolver.moduleBasedResolver = true;
  Resolver['default'] = Resolver;
  return Resolver;
});

define("resolver",
  ["ember/resolver"],
  function (Resolver) {
    Ember.deprecate('Importing/requiring Ember Resolver as "resolver" is deprecated, please use "ember/resolver" instead');
    return Resolver;
  });

})();

(function() {
/*globals define registry requirejs */

define("ember/container-debug-adapter",
  [],
  function() {
    "use strict";

  // Support Ember < 1.5-beta.4
  // TODO: Remove this after 1.5.0 is released
  if (typeof Ember.ContainerDebugAdapter === 'undefined') {
    return null;
  }
  /*
   * This module defines a subclass of Ember.ContainerDebugAdapter that adds two
   * important features:
   *
   *  1) is able provide injections to classes that implement `extend`
   *     (as is typical with Ember).
   */

  var ContainerDebugAdapter = Ember.ContainerDebugAdapter.extend({
    /**
      The container of the application being debugged.
      This property will be injected
      on creation.

      @property container
      @default null
    */
    // container: null, LIVES IN PARENT

    /**
      The resolver instance of the application
      being debugged. This property will be injected
      on creation.

      @property resolver
      @default null
    */
    // resolver: null,  LIVES IN PARENT
    /**
      Returns true if it is possible to catalog a list of available
      classes in the resolver for a given type.

      @method canCatalogEntriesByType
      @param {string} type The type. e.g. "model", "controller", "route"
      @return {boolean} whether a list is available for this type.
    */
    canCatalogEntriesByType: function(type) {
      return true;
    },

    /**
     * Get all defined modules.
     *
     * @method _getEntries
     * @return {Array} the list of registered modules.
     * @private
     */
    _getEntries: function() {
      return requirejs.entries;
    },

    /**
      Returns the available classes a given type.

      @method catalogEntriesByType
      @param {string} type The type. e.g. "model", "controller", "route"
      @return {Array} An array of classes.
    */
    catalogEntriesByType: function(type) {
      var entries = this._getEntries(),
          module,
          types = Ember.A();

      var makeToString = function(){
        return this.shortname;
      };

      var prefix = this.namespace.modulePrefix;

      for(var key in entries) {
        if(entries.hasOwnProperty(key) && key.indexOf(type) !== -1) {
          // Check if it's a pod module
          var name = getPod(type, key, this.namespace.podModulePrefix || prefix);
          if (!name) {
            // Not pod
            name = key.split(type + 's/').pop();

            // Support for different prefix (such as ember-cli addons).
            // Uncomment the code below when
            // https://github.com/ember-cli/ember-resolver/pull/80 is merged.

            //var match = key.match('^/?(.+)/' + type);
            //if (match && match[1] !== prefix) {
              // Different prefix such as an addon
              //name = match[1] + '@' + name;
            //}
          }
          types.addObject(name);
        }
      }
      return types;
    }
  });

  function getPod(type, key, prefix) {
    var match = key.match(new RegExp('^/?' + prefix + '/(.+)/' + type + '$'));
    if (match) {
      return match[1];
    }
  }

  ContainerDebugAdapter['default'] = ContainerDebugAdapter;
  return ContainerDebugAdapter;
});

})();

(function() {
(function() {
  "use strict";

  Ember.Application.initializer({
    name: 'container-debug-adapter',

    initialize: function() {
      var app = arguments[1] || arguments[0];
      var ContainerDebugAdapter = require('ember/container-debug-adapter');
      var Resolver = require('ember/resolver');

      app.register('container-debug-adapter:main', ContainerDebugAdapter);
      app.inject('container-debug-adapter:main', 'namespace', 'application:main');
    }
  });
}());

})();

(function() {

})();

if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) {
  Ember.Logger.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+
               "If you want full error messages please use the non-minified build provided on the Ember website.");
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.aerospike</groupId>
  <artifactId>spark_session_rollup</artifactId>
  <version>1.0.0</version>
  <dependencies>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.10</artifactId>
      <version>1.1.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>2.5.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.aerospike</groupId>
      <artifactId>aerospike-client</artifactId>
      <version>3.0.31</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.aerospike</groupId>
      <artifactId>aerospike-mapreduce</artifactId>
      <version>1.0.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
  <build>
    <directory>build/libs</directory>
    <finalName>${project.artifactId}-notfull</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <filters>
            <filter>
              <artifact>*:*</artifact>
              <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
              </excludes>
            </filter>
          </filters>
        </configuration>
        <executions>
          <execution>
            <id>job-driver-jar</id>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>true</shadedArtifactAttached>
              <shadedClassifierName>driver</shadedClassifierName>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                <!--
                    Some care is required:
                    http://doc.akka.io/docs/akka/snapshot/general/configuration.html
                -->
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>reference.conf</resource>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.aerospike.spark.examples.SparkSessionRollup</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
          <execution>
            <id>worker-library-jar</id>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>true</shadedArtifactAttached>
              <shadedClassifierName>worker</shadedClassifierName>
              <artifactSet>
                <includes>
                  <include>commons-codec:commons-codec</include>
                  <include>com.aerospike:aerospike-client</include>
                  <include>com.aerospike:aerospike-mapreduce</include>
                  <include>org.gnu:gnu-crypto</include>
                  <include>org.luaj:luaj-jse</include>
                  <include>org.mindrot:jbcrypt</include>
                </includes>
              </artifactSet>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
import {
    CompletionItem,
    Position
} from "vscode-languageserver";
import { Diagnostic } from "vscode-languageserver";

import { CompilerOptions, FileReference, HasInvalidatedResolution, Program } from "../compiler/types";

//
// Public services of a language service instance associated
// with a language service host instance
//
export interface LanguageService {
    getCompletionsAtPosition(fileName: string, position: Position): CompletionItem[];
    getCompilerDiagnostics(fileName: string): Diagnostic[];
    getSoliumDiagnostics(fileName: string, soliumRules?: any): Diagnostic[];
    getSolhintDiagnostics(fileName: string, solhintRules: any): Diagnostic[];

    getProgram(): Program;
}

export interface HostCancellationToken {
    isCancellationRequested(): boolean;
}

//
// Public interface of the host of a language service instance.
//
export interface LanguageServiceHost {
    getCompilationSettings(): CompilerOptions;
    getNewLine?(): string;
    getProjectVersion?(): string;
    getScriptFileNames(): string[];
    getScriptVersion(fileName: string): string;
    getCancellationToken?(): HostCancellationToken;
    getCurrentDirectory(): string;
    log?(s: string): void;
    trace?(s: string): void;
    error?(s: string): void;
    useCaseSensitiveFileNames?(): boolean;

    readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[];
    readFile?(path: string, encoding?: string): string;
    fileExists?(path: string): boolean;
    directoryExists?(directoryName: string): boolean;

    /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution;

    /*
     * getDirectories is also required for full import and type reference completions. Without it defined, certain
     * completions will not be provided
     */
    getDirectories?(directoryName: string): string[];
}

export interface PreProcessedFileInfo {
    importedFiles: FileReference[];
}


text:
var express = require('express');
var router = express.Router();
module.exports = router;

var mongoose = require('mongoose');
var Disease = mongoose.model('Disease');

// Information for each patient
router.get('/listByIdType/:idType', function(req, res, next) {
  var id_type = req.params.idType;
  Disease.find({ disease_id_type: id_type }, function(err, data)
  {
    if(err) { return next(err); }
    res.json(data);
  }
  );

});

router.get('/list', function(req, res, next) {
  Disease.find({}, function(err, data)
  {
    if(err) { return next(err); }
    res.json(data);
  }
  );

});


text:
test_name "Puppetserver 'foreground' subcommand tests."

if (master['platform'] =~ /el-5/)
  skip_test("RHEL5 is not supported by this test case. See SERVER-653")
end

cli = "puppetserver"
service = options['puppetservice']

# puppetserver seems to take about 45s to start up
timout_length = "60s"
foreground_cmd = "#{cli} foreground --debug"
timeout_cmd = "timeout -s INT #{timout_length} #{foreground_cmd}"

expected_messages = {
  / DEBUG .*Debug logging enabled/ => "Debug logging isn't enabled",
  /Initializing the JRuby service/ => "JRuby didn't initialize",
  /Starting web server/ => "Expected web server to start",
  /Puppet Server has successfully started and is now ready to handle requests/ => "puppetserver never finished starting",
  /Finished shutdown sequence/ => "Test ended without puppetserver shutting down gracefully"
}

# Start of test
step "Stop puppetserver"
on(master, puppet("resource service #{service} ensure=stopped"))

step "Run #{cli} with foreground subcommand, wait for #{timout_length}"
on(master, timeout_cmd, :acceptable_exit_codes => [124]) do |result|
  assert_no_match(/error:/i, result.stderr, "Unexpected error running puppetserver!")

  step "Check that #{cli} ran successfully and shutdown gracefully"
  expected_messages.each do |message, explanation|
    assert_match(message, result.stdout, explanation)
  end
end

teardown do
  step "Teardown: Start puppetserver again"
  on(master, puppet("resource service #{service} ensure=running"))
end


text:
package org.apereo.cas.adaptors.x509.web.flow;

import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.X509CertificateCredentialsNonInteractiveAction;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;

import java.security.cert.X509Certificate;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author Marvin S. Addison
 * @since 3.0.0
 */
public class X509CertificateCredentialsNonInteractiveActionTests extends BaseCertificateCredentialActionTests {

    @Test
    public void verifyNoCredentialsResultsInError() throws Exception {
        val context = new MockRequestContext();
        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse()));
        assertEquals(CasWebflowConstants.TRANSITION_ID_ERROR, this.action.getObject().execute(context).getId());
    }

    @Test
    public void verifyCredentialsResultsInSuccess() throws Exception {
        val context = new MockRequestContext();
        val request = new MockHttpServletRequest();
        request.setAttribute(X509CertificateCredentialsNonInteractiveAction.REQUEST_ATTRIBUTE_X509_CERTIFICATE, new X509Certificate[]{VALID_CERTIFICATE});
        context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
        assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, this.action.getObject().execute(context).getId());
    }
}


text:
package com.v7lin.android.env.webkit;

import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.WebSettings;

/**
 *
 *
 * @author v7lin Email:v7lin@qq.com
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class WebSettingsCompatHoneyComb {

	public static void setAllowContentAccess(WebSettings settings, boolean allow) {
		settings.setAllowContentAccess(allow);
	}

	public static void setDisplayZoomControls(WebSettings settings, boolean enabled) {
		settings.setDisplayZoomControls(enabled);
	}
}


text:
export default function (node) {
  const comments = node.trailingComments || [];

  return !!comments.find(({ value }) => value.trim() === 'remove-proptypes');
}


text:
package pierre.brito.app.motorspectrum.screens;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import pierre.brito.app.motorspectrum.R;

public class InsertFileName extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.container_file_name);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        final EditText editTextFileName = (EditText) findViewById(R.id.editTextFileName);
        Button buttonCancel = (Button) findViewById(R.id.buttonCancel);
        final Button buttonOk = (Button) findViewById(R.id.buttonOk);

        editTextFileName.setFilters(new InputFilter[] {new InputFilter.LengthFilter(8)});
        editTextFileName.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                if (charSequence.toString().trim().length() > 0)
                {
                    buttonOk.setEnabled(true);
                    buttonOk.setBackgroundResource(R.drawable.button_enable);
                }
                else
                {
                    buttonOk.setEnabled(false);
                    buttonOk.setBackgroundResource(R.drawable.button_disable);
                }
            }

            @Override
            public void afterTextChanged(Editable editable)
            {
            }
        });

        buttonCancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                finish();
            }
        });

        buttonOk.setOnClickListener(new View.OnClickListener()
        {
            @SuppressLint ("DefaultLocale")
            @Override
            public void onClick(View view)
            {
                Intent RESULT = new Intent();
                RESULT.putExtra("fileName", editTextFileName.getText().toString());
                setResult(Activity.RESULT_OK, RESULT);
                finish();
            }
        });
    }
}


text:
import React from 'react';
import { mount } from 'enzyme';
import { buildCSV } from '../../../components/Dashboard/DownloadButton';
import test_data from './test_data';
import expected_csv from './expected_download';

describe('DownloadButton', () => {
  it('should build the correct CSV', () => {
    const results = test_data;
    expect(buildCSV(results)).toEqual(expected_csv);
  });
});


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
		<title>Charity</title>
		<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">

		<link href='http://fonts.googleapis.com/css?family=Lato:400,300italic,300,700%7CPlayfair+Display:400,700italic%7CRoboto:300%7CMontserrat:400,700%7COpen+Sans:400,300%7CLibre+Baskerville:400,400italic' rel='stylesheet' type='text/css'>

		<link rel="stylesheet" type="text/css" href="assets/fancybox/css/fancybox.css" media="screen" />

		<link href="assets/css/bootstrap.min.css" rel="stylesheet">
		<link href="assets/css/bootstrap-theme.css" rel="stylesheet">
		<link href="assets/css/font-awesome.min.css" rel="stylesheet">
		<link href="assets/revolution-slider/css/settings.css" rel="stylesheet">
		<link href="assets/css/global.css" rel="stylesheet">
		<link href="assets/css/style.css" rel="stylesheet">
		<link href="assets/css/responsive.css" rel="stylesheet">
		<link href="assets/css/skin.less" rel="stylesheet/less">

							Become volunteer

							<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
								Toggle navigation

							</button>

									Home

												Index-1

												Index-2

												Index-3

									Causes

												Causes Home

												Causes Details full width

												Causes Details with sidebar

									features

												Our Story

												Our Mission

												Become a Volunteer

												Gallery 2 Columns

												Gallery 3 Columns

												Faq

												404 Error

									Store

												Shop Listing

												Shop Detail

												Shoping Cart

												Checkout

									Gallery

												Portfolio

												Portfolio Detail

									Blog

												Blog Full Width

												Blog Detail Full Width

									contact us

							<form class="navbar-form navbar-right search-form" role="search">

									<input type="text" class="form-control" placeholder="Search Here">

								<button type="submit">

								</button>
							</form>

Our Shop

										Home

										 Product Details

Shop our products & Help us.

Heading title product

													$300.00 $250.00

Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris  malesuada fames.

												Category :  women
												Tags : fashion, women, suit, sunglasses

													<input type="text" />

												add to cart

Description

Reviews (1)

Product Description

Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris et malesuada fames.Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris et malesuada fames.

Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris et malesuada fames.

Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris et malesuada fames.Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Inmensae subtilitatis, obscuris et malesuada fames.

Product Reviews

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec risus neque, eget sagittis est. Nulla eget libero ligula, ac scelerisque sapien. Donec sit amet sapien purus, sit amet tristique nisi.

Related Products

Heading title product

												 		$300.00 $250.00
												 		add to cart

Heading title product

												 		$300.00 $250.00
												 		add to cart

Heading title product

												 		$300.00 $250.00
												 		add to cart

Product Categories

Handbag

Men's

Shoes

Sunglasses

Watches

Women's

Top Rated Products

																Fusce mauris enim faci lisis sceler

															£290.00  £260.00

																Mauris enim faci lisis sceler isque non

															£290.00  £260.00

																Enim faci lisis sceler isque nonmauris

															£290.00  £260.00

																Enim faci lisis sceler isque nonmauris

															£290.00  £260.00

Buy our product and help us to improve our causes

Dictumst cras sit amet est eget dui viverra scelerisque duis semper pulvinar in risus ac bibendum aenean hendrerit pharetra

								add to cart

								There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour,

							<address>
								  A-2, Sector-63, Noida, 201301, India
								  +1 707 921 7269
								  contact@charity.com
							</address>

Twitter Feed

								 @charity Various versions have evolved over the years, sometimes by accident, sometimes on purpos. 2 hours ago

								 @charity Various versions have evolved over the years, sometimes by accident, sometimes on purpos. 2 hours ago

Newsletter Signup

								Variations of passages of Lorem Ipsum available, but the majokgrity

							<form role="form" class="sign-up">

									<input class="form-control" type="email" placeholder="Email">

										<input type="submit" class="btn btn-theme" value="Submit">

							</form>

Follow us

								 © Copyright 2014, All Rights Reserved by Charity Theme.


text:
var BaseArrayClass = require('./BaseArrayClass');
var utils = require('cordova/utils');

var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();
var nextTick = resolvedPromise ? function (fn) {
  resolvedPromise.then(fn);
} : function (fn) {
  setTimeout(fn);
};

//---------------------------
// Convert HTML color to RGB
//---------------------------
function isHTMLColorString(inputValue) {
  if (!inputValue || typeof inputValue !== 'string') {
    return false;
  }
  if (inputValue.match(/^#[0-9A-F]{3}$/i) ||
    inputValue.match(/^#[0-9A-F]{4}$/i) ||
    inputValue.match(/^#[0-9A-F]{6}$/i) ||
    inputValue.match(/^#[0-9A-F]{8}$/i) ||
    inputValue.match(/^rgba?\([\d,.\s]+\)$/) ||
    inputValue.match(/^hsla?\([\d%,.\s]+\)$/)) {
    return true;
  }

  inputValue = inputValue.toLowerCase();
  return inputValue in HTML_COLORS;
}

function HTMLColor2RGBA(colorValue, defaultOpacity) {
  defaultOpacity = !defaultOpacity ? 1.0 : defaultOpacity;
  if (colorValue instanceof Array) {
    return colorValue;
  }
  if (colorValue === 'transparent' || !colorValue) {
    return [0, 0, 0, 0];
  }
  var alpha = Math.floor(255 * defaultOpacity),
    matches;
  var colorStr = colorValue.toLowerCase();
  if (colorStr in HTML_COLORS) {
    colorStr = HTML_COLORS[colorStr];
  }
  if (colorStr.match(/^#([0-9A-F]){3}$/i)) {
    matches = colorStr.match(/([0-9A-F])/ig);

    return [
      parseInt(matches[0], 16),
      parseInt(matches[1], 16),
      parseInt(matches[2], 16),
      alpha
    ];
  }

  if (colorStr.match(/^#[0-9A-F]{4}$/i)) {
    alpha = colorStr.substr(4, 1);
    alpha = parseInt(alpha + alpha, 16);

    matches = colorStr.match(/([0-9A-F])/ig);
    return [
      parseInt(matches[0], 16),
      parseInt(matches[1], 16),
      parseInt(matches[2], 16),
      alpha
    ];
  }

  if (colorStr.match(/^#[0-9A-F]{6}$/i)) {
    matches = colorStr.match(/([0-9A-F]{2})/ig);
    return [
      parseInt(matches[0], 16),
      parseInt(matches[1], 16),
      parseInt(matches[2], 16),
      alpha
    ];
  }
  if (colorStr.match(/^#[0-9A-F]{8}$/i)) {
    matches = colorStr.match(/([0-9A-F]{2})/ig);

    return [
      parseInt(matches[0], 16),
      parseInt(matches[1], 16),
      parseInt(matches[2], 16),
      parseInt(matches[3], 16)
    ];
  }
  // convert rgb(), rgba()
  if (colorStr.match(/^rgba?\([\d,.\s]+\)$/)) {
    matches = colorStr.match(/([\d.]+)/g);
    alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 255) : alpha;
    return [
      parseInt(matches[0], 10),
      parseInt(matches[1], 10),
      parseInt(matches[2], 10),
      alpha
    ];
  }

  // convert hsl(), hsla()
  if (colorStr.match(/^hsla?\([\d%,.\s]+\)$/)) {
    matches = colorStr.match(/([\d%.]+)/g);
    alpha = matches.length == 4 ? Math.floor(parseFloat(matches[3]) * 255) : alpha;
    var rgb = HLStoRGB(matches[0], matches[1], matches[2]);
    rgb.push(alpha);
    return rgb;
  }

  console.warn('Warning: "' + colorValue + '" is not available. The overlay is drew by black.');
  return [0, 0, 0, alpha];
}

/**
 * http://d.hatena.ne.jp/ja9/20100907/1283840213
 */
function HLStoRGB(h, l, s) {
  var r, g, b; // 0..255

  while (h < 0) {
    h += 360;
  }
  h = h % 360;

  // In case of saturation = 0
  if (s === 0) {
    // RGB are the same as V
    l = Math.round(l * 255);
    return [l, l, l];
  }

  var m2 = (l < 0.5) ? l * (1 + s) : l + s - l * s,
    m1 = l * 2 - m2,
    tmp;

  tmp = h + 120;
  if (tmp > 360) {
    tmp = tmp - 360;
  }

  if (tmp < 60) {
    r = (m1 + (m2 - m1) * tmp / 60);
  } else if (tmp < 180) {
    r = m2;
  } else if (tmp < 240) {
    r = m1 + (m2 - m1) * (240 - tmp) / 60;
  } else {
    r = m1;
  }

  tmp = h;
  if (tmp < 60) {
    g = m1 + (m2 - m1) * tmp / 60;
  } else if (tmp < 180) {
    g = m2;
  } else if (tmp < 240) {
    g = m1 + (m2 - m1) * (240 - tmp) / 60;
  } else {
    g = m1;
  }

  tmp = h - 120;
  if (tmp < 0) {
    tmp = tmp + 360;
  }
  if (tmp < 60) {
    b = m1 + (m2 - m1) * tmp / 60;
  } else if (tmp < 180) {
    b = m2;
  } else if (tmp < 240) {
    b = m1 + (m2 - m1) * (240 - tmp) / 60;
  } else {
    b = m1;
  }
  return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

function parseBoolean(boolValue) {
  return typeof (boolValue) === 'string' && boolValue.toLowerCase() === 'true' ||
    boolValue === true ||
    boolValue === 1;
}

function isDom(element) {
  return element &&
    element.nodeType === Node.ELEMENT_NODE &&
    element instanceof SVGElement === false &&
    typeof element.getBoundingClientRect === 'function';
}

function getDivRect(div) {
  if (!div) {
    return;
  }
  var rect;
  if (div === document.body) {
    rect = div.getBoundingClientRect();
    rect.left = Math.max(rect.left, window.pageOffsetX);
    rect.top = Math.max(rect.top, window.pageOffsetY);
    rect.width = Math.max(rect.width, window.innerWidth);
    rect.height = Math.max(rect.height, window.innerHeight);
    rect.right = rect.left + rect.width;
    rect.bottom = rect.top + rect.height;
  } else {
    rect = div.getBoundingClientRect();
    if ('right' in rect === false) {
      rect.right = rect.left + rect.width;
    }
    if ('bottom' in rect === false) {
      rect.bottom = rect.top + rect.height;
    }
  }
  return {
    left: rect.left,
    top: rect.top,
    width: rect.width,
    height: rect.height,
    right: rect.right,
    bottom: rect.bottom
  };
}

var ignoreTags = [
  'pre', 'textarea', 'p', 'input', 'caption', 'canvas', 'svg'
];

function shouldWatchByNative(node) {
  if (!node || node.nodeType !== Node.ELEMENT_NODE || !node.parentNode || node instanceof SVGElement) {
    if (node === document.body) {
      return true;
    }
    return false;
  }

  var tagName = node.tagName.toLowerCase();
  if (ignoreTags.indexOf(tagName) > -1) {
    return false;
  }

  var classNames = (node.className || '').split(' ');
  if (classNames.indexOf('_gmaps_cdv_') > -1) {
    return true;
  }

  var visibilityCSS = getStyle(node, 'visibility');
  var displayCSS = getStyle(node, 'display');

  // Do not check this at here.
  //var pointerEventsCSS = getStyle(node, 'pointer-events');

  //-----------------------------------------
  // no longer check the opacity property,
  // because the app might start changing the opacity later.
  //-----------------------------------------
  //var opacityCSS = getStyle(node, 'opacity');
  //opacityCSS = /^[\d.]+$/.test(opacityCSS + '') ? opacityCSS : 1;

  //-----------------------------------------
  // no longer check the clickable size,
  // because HTML still can display larger element inside one small element.
  //-----------------------------------------
  // var clickableSize = (
  //   node.offsetHeight > 0 && node.offsetWidth > 0 ||
  //   node.clientHeight > 0 && node.clientWidth > 0);
  return displayCSS !== 'none' &&
    visibilityCSS !== 'hidden';
}

// Get z-index order
// http://stackoverflow.com/a/24136505
var internalCache = {};

function _clearInternalCache() {
  internalCache = undefined;
  internalCache = {};
}

function _removeCacheById(elemId) {
  delete internalCache[elemId];
}

function getZIndex(dom) {
  if (dom === document.body) {
    internalCache = undefined;
    internalCache = {};
  }
  if (!dom) {
    return 0;
  }

  var z = 0;
  if (window.getComputedStyle) {
    z = document.defaultView.getComputedStyle(dom, null).getPropertyValue('z-index');
  }
  if (dom.currentStyle) {
    z = dom.currentStyle['z-index'];
  }
  var elemId = dom.getAttribute('__pluginDomId');
  var parentNode = dom.parentNode;
  var parentZIndex = 0;
  if (parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
    var parentElemId = parentNode.getAttribute('__pluginDomId');
    if (parentElemId in internalCache) {
      parentZIndex = internalCache[parentElemId];
    } else {
      parentZIndex = getZIndex(dom.parentNode);
      internalCache[parentElemId] = parentZIndex;
    }
  }

  var isInherit = false;
  if (z === 'unset' || z === 'initial') {
    z = 0;
  } else if (z === 'auto' || z === 'inherit') {
    z = 0;
    isInherit = true;
  } else {
    z = parseInt(z);
  }
  //dom.setAttribute('__ZIndex', z);
  internalCache[elemId] = z + parentZIndex;
  return {
    isInherit: isInherit,
    z: z
  };
}

// Get CSS value of an element
// http://stackoverflow.com/a/1388022
function getStyle(element, styleProperty) {
  if (window.getComputedStyle) {
    return document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProperty);
  } else if (element.currentStyle) {
    return element.currentStyle[styleProperty];
  }
  return;
}

var HTML_COLORS = {
  'aliceblue': '#f0f8ff',
  'antiquewhite': '#faebd7',
  'aqua': '#00ffff',
  'aquamarine': '#7fffd4',
  'azure': '#f0ffff',
  'beige': '#f5f5dc',
  'bisque': '#ffe4c4',
  'black': '#000000',
  'blanchedalmond': '#ffebcd',
  'blue': '#0000ff',
  'blueviolet': '#8a2be2',
  'brown': '#a52a2a',
  'burlywood': '#deb887',
  'cadetblue': '#5f9ea0',
  'chartreuse': '#7fff00',
  'chocolate': '#d2691e',
  'coral': '#ff7f50',
  'cornflowerblue': '#6495ed',
  'cornsilk': '#fff8dc',
  'crimson': '#dc143c',
  'cyan': '#00ffff',
  'darkblue': '#00008b',
  'darkcyan': '#008b8b',
  'darkgoldenrod': '#b8860b',
  'darkgray': '#a9a9a9',
  'darkgrey': '#a9a9a9',
  'darkgreen': '#006400',
  'darkkhaki': '#bdb76b',
  'darkmagenta': '#8b008b',
  'darkolivegreen': '#556b2f',
  'darkorange': '#ff8c00',
  'darkorchid': '#9932cc',
  'darkred': '#8b0000',
  'darksalmon': '#e9967a',
  'darkseagreen': '#8fbc8f',
  'darkslateblue': '#483d8b',
  'darkslategray': '#2f4f4f',
  'darkslategrey': '#2f4f4f',
  'darkturquoise': '#00ced1',
  'darkviolet': '#9400d3',
  'deeppink': '#ff1493',
  'deepskyblue': '#00bfff',
  'dimgray': '#696969',
  'dimgrey': '#696969',
  'dodgerblue': '#1e90ff',
  'firebrick': '#b22222',
  'floralwhite': '#fffaf0',
  'forestgreen': '#228b22',
  'fuchsia': '#ff00ff',
  'gainsboro': '#dcdcdc',
  'ghostwhite': '#f8f8ff',
  'gold': '#ffd700',
  'goldenrod': '#daa520',
  'gray': '#808080',
  'grey': '#808080',
  'green': '#008000',
  'greenyellow': '#adff2f',
  'honeydew': '#f0fff0',
  'hotpink': '#ff69b4',
  'indianred ': '#cd5c5c',
  'indigo  ': '#4b0082',
  'ivory': '#fffff0',
  'khaki': '#f0e68c',
  'lavender': '#e6e6fa',
  'lavenderblush': '#fff0f5',
  'lawngreen': '#7cfc00',
  'lemonchiffon': '#fffacd',
  'lightblue': '#add8e6',
  'lightcoral': '#f08080',
  'lightcyan': '#e0ffff',
  'lightgoldenrodyellow': '#fafad2',
  'lightgray': '#d3d3d3',
  'lightgrey': '#d3d3d3',
  'lightgreen': '#90ee90',
  'lightpink': '#ffb6c1',
  'lightsalmon': '#ffa07a',
  'lightseagreen': '#20b2aa',
  'lightskyblue': '#87cefa',
  'lightslategray': '#778899',
  'lightslategrey': '#778899',
  'lightsteelblue': '#b0c4de',
  'lightyellow': '#ffffe0',
  'lime': '#00ff00',
  'limegreen': '#32cd32',
  'linen': '#faf0e6',
  'magenta': '#ff00ff',
  'maroon': '#800000',
  'mediumaquamarine': '#66cdaa',
  'mediumblue': '#0000cd',
  'mediumorchid': '#ba55d3',
  'mediumpurple': '#9370db',
  'mediumseagreen': '#3cb371',
  'mediumslateblue': '#7b68ee',
  'mediumspringgreen': '#00fa9a',
  'mediumturquoise': '#48d1cc',
  'mediumvioletred': '#c71585',
  'midnightblue': '#191970',
  'mintcream': '#f5fffa',
  'mistyrose': '#ffe4e1',
  'moccasin': '#ffe4b5',
  'navajowhite': '#ffdead',
  'navy': '#000080',
  'oldlace': '#fdf5e6',
  'olive': '#808000',
  'olivedrab': '#6b8e23',
  'orange': '#ffa500',
  'orangered': '#ff4500',
  'orchid': '#da70d6',
  'palegoldenrod': '#eee8aa',
  'palegreen': '#98fb98',
  'paleturquoise': '#afeeee',
  'palevioletred': '#db7093',
  'papayawhip': '#ffefd5',
  'peachpuff': '#ffdab9',
  'peru': '#cd853f',
  'pink': '#ffc0cb',
  'plum': '#dda0dd',
  'powderblue': '#b0e0e6',
  'purple': '#800080',
  'rebeccapurple': '#663399',
  'red': '#ff0000',
  'rosybrown': '#bc8f8f',
  'royalblue': '#4169e1',
  'saddlebrown': '#8b4513',
  'salmon': '#fa8072',
  'sandybrown': '#f4a460',
  'seagreen': '#2e8b57',
  'seashell': '#fff5ee',
  'sienna': '#a0522d',
  'silver': '#c0c0c0',
  'skyblue': '#87ceeb',
  'slateblue': '#6a5acd',
  'slategray': '#708090',
  'slategrey': '#708090',
  'snow': '#fffafa',
  'springgreen': '#00ff7f',
  'steelblue': '#4682b4',
  'tan': '#d2b48c',
  'teal': '#008080',
  'thistle': '#d8bfd8',
  'tomato': '#ff6347',
  'turquoise': '#40e0d0',
  'violet': '#ee82ee',
  'wheat': '#f5deb3',
  'white': '#ffffff',
  'whitesmoke': '#f5f5f5',
  'yellow': '#ffff00',
  'yellowgreen': '#9acd32'
};

function defaultTrueOption(value) {
  return value === undefined ? true : value === true;
}

function createMvcArray(array) {
  if (!array) {
    return new BaseArrayClass();
  }
  if (array.type === 'BaseArrayClass') {
    return array;
  }

  var mvcArray;
  if (array.type === 'LatLngBounds') {
    array = [
      array.southwest,
      {
        lat: array.northeast.lat,
        lng: array.southwest.lng
      },
      array.northeast,
      {
        lat: array.southwest.lat,
        lng: array.northeast.lng
      },
      array.southwest
    ];
    array = array.map(getLatLng);
  }

  if (array && typeof array.getArray === 'function') {
    mvcArray = new BaseArrayClass(array.getArray());
    array.on('set_at', function (index) {
      var value = array.getAt(index);
      value = 'position' in value ? value.getPosition() : value;
      mvcArray.setAt(index, value);
    });
    array.on('insert_at', function (index) {
      var value = array.getAt(index);
      value = 'position' in value ? value.getPosition() : value;
      mvcArray.insertAt(index, value);
    });
    array.on('remove_at', function (index) {
      mvcArray.removeAt(index);
    });

  } else {
    mvcArray = new BaseArrayClass(array ? array.slice(0) : undefined);
  }
  return mvcArray;
}

function getLatLng(target) {
  return 'getPosition' in target ? target.getPosition() : {
    'lat': parseFloat(target.lat, 10),
    'lng': parseFloat(target.lng, 10)
  };
}

function convertToPositionArray(array) {
  array = array || [];

  if (!utils.isArray(array)) {
    if (array.type === 'LatLngBounds') {
      array = [
        array.southwest,
        {
          lat: array.northeast.lat,
          lng: array.southwest.lng
        },
        array.northeast,
        {
          lat: array.southwest.lat,
          lng: array.northeast.lng
        },
        array.southwest
      ];
    } else if (array && typeof array.getArray === 'function') {
      array = array.getArray();
    } else {
      array = [array];
    }
  }

  array = array.map(getLatLng);

  return array;
}

function markerOptionsFilter(markerOptions) {
  markerOptions = markerOptions || {};

  markerOptions.animation = markerOptions.animation || undefined;
  markerOptions.position = markerOptions.position || {};
  markerOptions.position.lat = markerOptions.position.lat || 0.0;
  markerOptions.position.lng = markerOptions.position.lng || 0.0;
  markerOptions.draggable = markerOptions.draggable === true;
  markerOptions.icon = markerOptions.icon || undefined;
  markerOptions.zIndex = markerOptions.zIndex || 0;
  markerOptions.snippet = typeof (markerOptions.snippet) === 'string' ? markerOptions.snippet : undefined;
  markerOptions.title = typeof (markerOptions.title) === 'string' ? markerOptions.title : undefined;
  markerOptions.visible = defaultTrueOption(markerOptions.visible);
  markerOptions.flat = markerOptions.flat === true;
  markerOptions.rotation = markerOptions.rotation || 0;
  markerOptions.opacity = markerOptions.opacity === 0 ? 0 : (parseFloat('' + markerOptions.opacity, 10) || 1);
  markerOptions.disableAutoPan = markerOptions.disableAutoPan === true;
  markerOptions.noCache = markerOptions.noCache === true; //experimental
  if (typeof markerOptions.icon === 'object') {
    if ('anchor' in markerOptions.icon &&
      !Array.isArray(markerOptions.icon.anchor) &&
      'x' in markerOptions.icon.anchor &&
      'y' in markerOptions.icon.anchor) {
      markerOptions.icon.anchor = [markerOptions.icon.anchor.x, markerOptions.icon.anchor.y];
    }
  }

  if ('infoWindowAnchor' in markerOptions &&
    !Array.isArray(markerOptions.infoWindowAnchor) &&
    'x' in markerOptions.infoWindowAnchor &&
    'y' in markerOptions.infoWindowAnchor) {
    markerOptions.infoWindowAnchor = [markerOptions.infoWindowAnchor.x, markerOptions.infoWindowAnchor.anchor.y];
  }

  if ('style' in markerOptions && !('styles' in markerOptions)) {
    markerOptions.styles = markerOptions.style;
    delete markerOptions.style;
  }
  if ('styles' in markerOptions) {
    markerOptions.styles = typeof markerOptions.styles === 'object' ? markerOptions.styles : {};

    if ('color' in markerOptions.styles) {
      markerOptions.styles.color = HTMLColor2RGBA(markerOptions.styles.color || '#000000');
    }
  }
  if (markerOptions.icon && isHTMLColorString(markerOptions.icon)) {
    markerOptions.icon = HTMLColor2RGBA(markerOptions.icon);
  }
  if (markerOptions.icon && markerOptions.icon.label &&
    isHTMLColorString(markerOptions.icon.label.color)) {
    markerOptions.icon.label.color = HTMLColor2RGBA(markerOptions.icon.label.color);
  }
  return markerOptions;
}

function quickfilter(domPositions, mapElemIDs) {
  //console.log('before', JSON.parse(JSON.stringify(domPositions)));
  var keys = Object.keys(domPositions);

  var tree = {};
  mapElemIDs.forEach(function (mapElemId) {
    var size = domPositions[mapElemId].size;
    var mapRect = {
      left: size.left,
      top: size.top,
      right: size.left + size.width,
      bottom: size.top + size.height
    };

    tree[mapElemId] = domPositions[mapElemId];

    keys.forEach(function (elemId) {
      if (domPositions[elemId].ignore) {
        return;
      }
      var domSize = {
        left: domPositions[elemId].size.left,
        top: domPositions[elemId].size.top,
        right: domPositions[elemId].size.left + domPositions[elemId].size.width,
        bottom: domPositions[elemId].size.bottom + domPositions[elemId].size.height
      };
      if (
        (domSize.left >= mapRect.left && domSize.left <= mapRect.right) ||
        (domSize.right >= mapRect.left && domSize.right <= mapRect.right) ||
        (domSize.top >= mapRect.top && domSize.top <= mapRect.bottom) ||
        (domSize.bottom >= mapRect.top && domSize.bottom <= mapRect.bottom)
      ) {
        tree[elemId] = domPositions[elemId];
      }
    });
  });

  //console.log('after', JSON.parse(JSON.stringify(tree)));
  return tree;
}

function getPluginDomId(element) {
  // Generates a __pluginDomId
  if (!element || !shouldWatchByNative(element)) {
    return;
  }
  var elemId = element.getAttribute('__pluginDomId');
  if (!elemId) {
    if (element === document.body) {
      elemId = 'root';
    } else {
      elemId = 'pgm' + Math.floor(Math.random() * Date.now());
    }
    element.setAttribute('__pluginDomId', elemId);
  }
  return elemId;
}

// Add hashCode() method
// https://stackoverflow.com/a/7616484/697856
function hashCode(text) {
  var hash = 0,
    i, chr;
  if (text.length === 0) return hash;
  for (i = 0; i < text.length; i++) {
    chr = text.charCodeAt(i);
    hash = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
}

function createEvent(eventName, properties) {
  var evt;
  if (typeof CustomEvent === 'function') {
    evt = new CustomEvent(eventName, {
      bubbles: true,
      detail: properties || null
    });
  } else {
    evt = document.createEvent('Event');
    evt.initEvent(eventName, true, false);
    if (properties) {
      Object.keys(properties).forEach(function (key) {
        if (!(key in properties)) {
          evt[key] = properties[key];
        }
      });
    }
  }
  return evt;
}

function attachTransparentClass(div) {

  if (div.classList && !div.classList.contains('_gmaps_cdv_')) {
    div.classList.add('_gmaps_cdv_');
  } else if (div.className && div.className.indexOf('_gmaps_cdv_') === -1) {
    div.className = div.className + ' _gmaps_cdv_';
  }

  if (div.shadowRoot) {
    var styleAttr = div.getAttribute('style') || '';
    if (styleAttr && styleAttr.indexOf('--ion-background-color') === -1) {
      styleAttr = styleAttr + ' --ion-background-color: transparent;';
    }
    div.setAttribute('style', styleAttr);
  }
}
// function dettachTransparentClass(root) {
//
//   if (div.classList && div.classList.contains('_gmaps_cdv_')) {
//     div.classList.remove('_gmaps_cdv_');
//   } else if (div.className && div.className.indexOf('_gmaps_cdv_') === -1) {
//     div.className = div.className.replace('_gmaps_cdv_', '');
//   }
//
//   var visibilityCSS = getStyle(node, 'visibility');
//   if (getStyle(div, 'background-color') === 'transparent !important') {
//     div.style.backgroundColor = undefined;
//   }
//   if (getStyle(div, 'background') === 'transparent !important') {
//     div.style.backgroundColor = undefined;
//   }
//   if (getStyle(div, 'background-image') === 'transparent !important') {
//     div.style.backgroundImage = undefined;
//   }
//   if (div.shadowRoot) {
//     var hiddenChildren = div.querySelectorAll('*');
//     hiddenChildren = Array.prototype.splice(hiddenChildren, 0);
//     hiddenChildren.forEach(dettachTransparentClass);
//   }
// }

module.exports = {
  _clearInternalCache: _clearInternalCache,
  _removeCacheById: _removeCacheById,
  getZIndex: getZIndex,
  getDivRect: getDivRect,
  isDom: isDom,
  parseBoolean: parseBoolean,
  HLStoRGB: HLStoRGB,
  HTMLColor2RGBA: HTMLColor2RGBA,
  isHTMLColorString: isHTMLColorString,
  defaultTrueOption: defaultTrueOption,
  createMvcArray: createMvcArray,
  getStyle: getStyle,
  convertToPositionArray: convertToPositionArray,
  getLatLng: getLatLng,
  shouldWatchByNative: shouldWatchByNative,
  markerOptionsFilter: markerOptionsFilter,
  quickfilter: quickfilter,
  nextTick: nextTick,
  getPluginDomId: getPluginDomId,
  hashCode: hashCode,
  createEvent: createEvent,
  //dettachTransparentClass: dettachTransparentClass,
  attachTransparentClass: attachTransparentClass
};

if (cordova && cordova.platformId === 'browser') {
  require('cordova/exec/proxy').add('common', module.exports);
}


text:
<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
    "http://getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
    <allow>
        <create creator="spring" javascript="UserManager">
            <param name="class" value="com.vnpt.spdv.service.UserManager"/>
            <param name="beanName" value="userManager"/>
            <include method="getUsers"/>
        </create>
        <convert converter="bean" match="com.vnpt.spdv.model.User"/>
    </allow>
</dwr>


text:
import {Component, Input} from '@angular/core';
import {ElementRef} from "@angular/core";
import {AuthStrategy} from "./auth-strategy.component";

export class AuthApiKey implements AuthStrategy {
  public name: string;
  in: string;

  public tempKey: string;
  key: string;

  url: string = "";

  loggedIn = false;

  constructor(private id: string, definition: any){
    if(!definition || !definition['name'] || !definition['in']){
      throw new Error("Invalid arguments in AuthApiKey");
    }
    this.name = definition['name'];
    this.in = definition['in'];
  }

  getTemplate():string{
    return "
" +
      "{{scope.name}}" +
      "<input [disabled]='scope.isLoggedIn()' id='__auth_api_key_input__' type='text' [(ngModel)]='scope.tempKey' placeholder='Key' />" +
      "
" +
      "<button *ngIf='!scope.isLoggedIn()' (click)='scope.login()'>Log In</button>" +
      "<button *ngIf='scope.isLoggedIn()' (click)='scope.logout()'>Log Out</button>" +
      "
" +
      "
";
  }

  isLoggedIn(): boolean{
    return this.loggedIn;
  }

  getId(): string {
    return this.id;
  }

  login(): void{
    if(this.tempKey){
      this.key = this.tempKey;
      this.loggedIn = true;
    }
  }

  logout():void{
    this.key = "";
    this.tempKey = "";
    this.loggedIn = false;
  }

  // this function doesn't override values if they are already present in the query/header
  apply(obj: any): void {
    if(this.in === "query"){
      if(typeof obj.parameters[this.name] === 'undefined') {
        obj.parameters[this.name] = this.key;
      }
    }else{ // header
      if(typeof obj.headers[this.name] === 'undefined') {
        obj.headers[this.name] = this.key;
      }
    }
  }
}


text:
package net.runelite.client.plugins.inventorygrid;

import com.google.inject.Inject;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.api.widgets.WidgetItem;
import net.runelite.client.game.ItemManager;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;

class InventoryGridOverlay extends Overlay
{
	private static final int INVENTORY_SIZE = 28;
	private static final int DISTANCE_TO_ACTIVATE_HOVER = 5;

	private static final Color HIGHLIGHT = new Color(0, 255, 0, 45);
	private static final Color GRID = new Color(255, 255, 255, 45);

	private final InventoryGridConfig config;
	private final Client client;
	private final ItemManager itemManager;

	private Point initialMousePoint;
	private boolean hoverActive = false;

	@Inject
	private InventoryGridOverlay(InventoryGridConfig config, Client client, ItemManager itemManager)
	{
		this.itemManager = itemManager;
		this.client = client;
		this.config = config;

		setPosition(OverlayPosition.DYNAMIC);
		setLayer(OverlayLayer.ABOVE_WIDGETS);
	}

	@Override
	public Dimension render(Graphics2D graphics)
	{
		final Widget draggingWidget = getDraggedWidget();
		if (draggingWidget == null)
		{
			initialMousePoint = null;
			hoverActive = false;
			// not dragging
			return null;
		}

		// grid is only supported on bank inventory and inventory
		Widget inventoryWidget = draggingWidget.isIf3() ?
			client.getWidget(WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER) :
			client.getWidget(WidgetInfo.INVENTORY);

		// with if3 the dragged widget is a child of the inventory, with if1 it is an item of the inventory (and the same widget)
		if (inventoryWidget == null || (draggingWidget.isIf3() ? draggingWidget.getParent() != inventoryWidget : draggingWidget != inventoryWidget))
		{
			return null;
		}

		final net.runelite.api.Point mouse = client.getMouseCanvasPosition();
		final Point mousePoint = new Point(mouse.getX(), mouse.getY());
		final int draggedItemIndex = draggingWidget.isIf3() ? draggingWidget.getIndex() : client.getIf1DraggedItemIndex();
		final WidgetItem draggedItem = getWidgetItem(inventoryWidget, draggedItemIndex);
		final Rectangle initialBounds = draggedItem.getCanvasBounds(false);

		if (initialMousePoint == null)
		{
			initialMousePoint = mousePoint;
		}

		if (draggedItem.getId() == -1
			|| client.getItemPressedDuration() < config.dragDelay() / Constants.CLIENT_TICK_LENGTH
			|| !hoverActive && initialMousePoint.distance(mousePoint) < DISTANCE_TO_ACTIVATE_HOVER)
		{
			return null;
		}

		hoverActive = true;

		for (int i = 0; i < INVENTORY_SIZE; ++i)
		{
			final WidgetItem targetWidgetItem = getWidgetItem(inventoryWidget, i);
			final Rectangle bounds = targetWidgetItem.getCanvasBounds(false);
			boolean inBounds = bounds.contains(mousePoint);

			if (config.showItem() && inBounds)
			{
				drawItem(graphics, bounds, draggedItem);
				drawItem(graphics, initialBounds, targetWidgetItem);
			}

			if (config.showHighlight() && inBounds)
			{
				graphics.setColor(HIGHLIGHT);
				graphics.fill(bounds);
			}
			else if (config.showGrid())
			{
				graphics.setColor(GRID);
				graphics.fill(bounds);
			}
		}

		return null;
	}

	private Widget getDraggedWidget()
	{
		Widget widget = client.getIf1DraggedWidget(); // if1 drag
		if (widget != null)
		{
			return widget;
		}
		return client.getDraggedWidget(); // if3 drag
	}

	private static WidgetItem getWidgetItem(Widget parentWidget, int idx)
	{
		if (parentWidget.isIf3())
		{
			Widget wi = parentWidget.getChild(idx);
			return new WidgetItem(wi.getItemId(), wi.getItemQuantity(), -1, wi.getBounds(), parentWidget, wi.getBounds());
		}
		else
		{
			return parentWidget.getWidgetItem(idx);
		}
	}

	private void drawItem(Graphics2D graphics, Rectangle bounds, WidgetItem item)
	{
		if (item.getId() == -1)
		{
			return;
		}

		final BufferedImage draggedItemImage = itemManager.getImage(item.getId(), item.getQuantity(), false);
		final int x = (int) bounds.getX();
		final int y = (int) bounds.getY();

		graphics.setComposite(AlphaComposite.SrcOver.derive(0.3f));
		graphics.drawImage(draggedItemImage, x, y, null);
		graphics.setComposite(AlphaComposite.SrcOver);
	}
}


text:
Weibo OAuth 2.0 support for the PHP League's OAuth 2.0 Client
##Install
You can open a terminal and type in
```shell
composer require spoonwep/oauth2-weibo
```
or require in a composer.json
```json
"require": {
	"spoonwep/oauth2-weibo": "^1.2"
}
```
then run:
```shell
composer update
```
##Useage
```php
session_start();
$provider = new \spoonwep\OAuth2\Client\Provider\Weibo([
	'clientId' => '{weibo App Key}',
	'clientSecret' => '{weibo App Secret}',
	'redirectUri' => '{http://example.com/callback-url}',
]);
if (!isset($_GET['code'])) {
	$authUrl = $provider->getAuthorizationUrl();
	$_SESSION['oauth2state'] = $provider->getState();
	header('Location: '.$authUrl);
	exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
	unset($_SESSION['oauth2state']);
	exit('Invalid state');
} else {
	$token = $provider->getAccessToken('authorization_code', [
		'code' => $_GET['code']
	]);

	//fetch userinfo returned by serverside
	$user = $provider->getResourceOwner($token);
	print_r($user->toArray());
}
```
###License
The MIT License (MIT). Please see [License](https://github.com/spoonwep/oauth2-weibo/blob/master/LICENSE.txt) File for more information.


text:
using namespace node;
using namespace avro;
using namespace v8;

namespace node {

struct datumBaton {
  ValidSchema schema;
  GenericDatum *datum;
  const char* errorMessage;
  Persistent<Value> onSuccess;
  Persistent<Value> onError;
};

class Avro : public ObjectWrap
{
public:
  Avro() : ObjectWrap(), dictionary_(){};
  ~Avro() {};
  std::queue<datumBaton> processQueue_;
  std::vector<datumBaton> datums_;
  DecoderPtr decoder_;
  helper::SymbolMap dictionary_;
  uv_sem_t sem_;
  uv_loop_t *avro_loop_;
  uv_async_t async_;
  uv_mutex_t datumLock_;
  uv_mutex_t queueLock_;
  avronode::BufferedInputStream *buffer_;
  bool read_;
  static void Initialize(Handle<Object> target);
private:
  static Handle<Value> New(const Arguments& args);
  static Handle<Value> ClearDictionary(const Arguments& args);
  static Handle<Value> QueueSchema(const Arguments &args);
  static Handle<Value> AddSchema(const Arguments &args);
  static Handle<Value> PendingSchemas(const Arguments &args);
  static Handle<Value> Push(const Arguments &args);
  static Handle<Value> BufferLength(const Arguments &args);
  static Handle<Value> DecodeFile(const Arguments &args);
  static Handle<Value> EncodeDatum(const Arguments &args);
  static Handle<Value> EncodeDatumFile(const Arguments &args);
  static Handle<Value> DecodeDatum(const Arguments &args);
  static Handle<Value> Close(const Arguments &args);

};
}


text:
package cn.sharesdk.demo;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

public class UriUtil {

    public static String convertUriToPath(Context context, Uri uri) {
        if (uri == null)
            return null;
        String schema = uri.getScheme();
        if (TextUtils.isEmpty(schema) || ContentResolver.SCHEME_FILE.equals(schema)) {
            return uri.getPath();
        }
        if ("http".equals(schema))
            return uri.toString();
        if (ContentResolver.SCHEME_CONTENT.equals(schema)) {
            String[] projection = new String[]{MediaStore.MediaColumns.DATA};
            Cursor cursor = null;
            String filePath = "";
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        filePath = cursor.getString(0);
                    }

                    cursor.close();
                }
            } catch (Exception e) {
                // do nothing
            } finally {
                try {
                    if (null != cursor) {
                        cursor.close();
                    }
                } catch (Exception e2) {
                    // do nothing
                }
            }
            if (TextUtils.isEmpty(filePath)) {
                try {
                    ContentResolver contentResolver = context.getContentResolver();
                    String selection = MediaStore.Images.Media._ID + "= ?";
                    String id = uri.getLastPathSegment();
                    if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(id) && id.contains(":")) {
                        id = id.split(":")[1];
                    }
                    String[] selectionArgs = new String[]{id};
                    cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, null);
                    if (cursor.moveToFirst()) {
                        filePath = cursor.getString(0);
                    }
                    if (null != cursor) {
                        cursor.close();
                    }

                } catch (Exception e) {
                    // do nothing
                } finally {
                    try {
                        if (cursor != null) {
                            cursor.close();
                        }
                    } catch (Exception e) {
                        // do nothing
                    }
                }
            }
            return filePath;
        }
        return null;
    }

    public static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }

            cursor.close();
        }
        return path;
    }

}


text:
!function($) {

  'use strict';

  /**
   * Soooooooo dirty ;_;
   * add the "detach from post" link
   */
  $(document).on('click', '.attachments-browser .attachment', function() {
    if ($('.attachment-filters').val() === 'uploaded') {
      var html = 'Detach from the post'
      $('.attachment-details').find('.delete-attachment').parent().append(html)
    }
  })

  /**
   * Remove the media from the post
   */
  $(document).on('click', '.remove-post-attachment', function(e) {
    e.preventDefault()
    // get the attachment id
    var datas = $(this).closest('.media-sidebar').find('.edit-attachment').attr('href')
      , regex = /post=([0-9]*)&/g
      , match = regex.exec(datas)

    if (match !== null) {
      var id = match[1]

      $.ajax({
          url: ajaxurl
        , type: 'post'
        , dataType: 'json'
        , data: {
              action: 'removePostAttachmentAjax'
            , id: id
          }
      })
      .done(function() {
        // quick and dirty: deselect the attachment and remove it from the list
        var attachment = $('.attachments').find('.attachment.selected')
        attachment.find('.check').click()
        attachment.remove()
      })
    }
  })

}(window.jQuery);


text:
package com.mycompany.diplom.store;

import com.mycompany.diplom.components.CurrencyPanel;
import com.mycompany.diplom.profile.authorizationpanel.AuthorizationProfileDate;
import com.mycompany.diplom.shop.Article;
import com.mycompany.diplom.shop.Purchases;
import com.mycompany.diplom.shop.PurchasesDao;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 *
 * @since May 4, 2014
 * @author dmorari
 */
public class StorePanel extends JPanel {
        private AbstractTable availableArticles;
        private AbstractTable bookedArticles;

        public StorePanel(){
            this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

          this.availableArticles = new AvailableArticlesTable();
          this.bookedArticles = new BookedArticlesTable();

          availableArticles.setOppositeTable(bookedArticles);
          bookedArticles.setOppositeTable(availableArticles);

          JButton confirmButton = new JButton("Купить!");
          confirmButton.setMaximumSize(new Dimension(100, 50));
          confirmButton.setAlignmentX(Component.CENTER_ALIGNMENT);

          JScrollPane tableScrollPane1 = new JScrollPane(availableArticles);
          tableScrollPane1.setPreferredSize(new Dimension(700, 250));
          tableScrollPane1.setAlignmentX(Component.CENTER_ALIGNMENT);

          JScrollPane tableScrollPane2 = new JScrollPane(bookedArticles);
          tableScrollPane2.setPreferredSize(new Dimension(700, 150));
          tableScrollPane2.setAlignmentX(Component.CENTER_ALIGNMENT);

          this.add(tableScrollPane1, BorderLayout.PAGE_START);
          this.add(Box.createVerticalStrut(15));
          this.add(tableScrollPane2, BorderLayout.CENTER);
          this.add(confirmButton, BorderLayout.PAGE_END);

          availableArticles.getTable().addMouseListener(createMouseLister(availableArticles));
          bookedArticles.getTable().addMouseListener(createMouseLister(bookedArticles));

          confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                for (Article article : bookedArticles.getArticles()) {
                      System.out.println(article.getId() + ") " + article.getName());
                }

                AuthorizationProfileDate profDate = new AuthorizationProfileDate();
                if (profDate.getName() != null && profDate.getBalance() != null) {
                    for (Article article : bookedArticles.getArticles()) {
                        profDate.setBalance(profDate.getBalance() - article.getCost());
                        CurrencyPanel.getInstance().setBalanceInCurrencyLabel(profDate.getBalance());

                        List<Purchases> list = PurchasesDao.getInstance().allPurchases();
                        PurchasesDao.getInstance().insertPurchases((list.size() + 1), article.getId(), profDate.getId());
                    }
                    JOptionPane.showMessageDialog(null, "Спасибо за покупки!");
                }
            }
          });
        }

        private MouseListener createMouseLister(final AbstractTable table) {
          return new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e)
            {
              if (e.getClickCount() == 2) {
                int row = table.getTable().getSelectedRow();
                table.move(row);
              }
            }

          };
        }
}


text:
/* $Id$ JSONUtil.java */
package com.leafsoft.util;

import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class JSONUtil {

	private static final String RESTAPICONFIG_JSON = "restapiconfig.json";//NO I18N
	private static final String DEBUG_JSON = "debug.json";//NO I18N

	private JSONObject debug;
	private JSONObject restapiConfigJSON;

	private static final JSONUtil JSON_UTIL = new JSONUtil();

	public static JSONUtil getInstance() {
		return JSON_UTIL;
	}

	private JSONObject getJSONObject(String resource,String path)
			throws Exception {
		String json = getJSONString(resource,path);
		if (json != null) {
			return new JSONObject(json);
		}
		return new JSONObject();
	}

	private JSONArray getJSONArray(String resource,String path)
			throws Exception {
		return new JSONArray(getJSONString(resource,path));
	}

	private String getJSONString(String resource,String path)
			throws Exception {
		if(path == null) {
			path = Constants.JSON_PATH;
		}
		ClassLoader classLoader = getClass().getClassLoader();
		File resourceFile = null;
		if (resourceFile == null || !resourceFile.exists()) {
			resourceFile = new File(path);
			if (!resourceFile.exists()) {
				resourceFile = new File(classLoader.getResource(path + "/" + resource).getFile());
			}
		}
		return IOUtils.toString(new FileInputStream(resourceFile));
	}

	public JSONObject getDebugJson() throws Exception {
		if (debug == null) {
			debug = getJSONObject(DEBUG_JSON,null);
		}
		return debug;
	}

	public JSONObject getRestAPIConfigJSON() throws Exception {
		if (restapiConfigJSON == null) {
			restapiConfigJSON = getJSONObject(RESTAPICONFIG_JSON,null);
		}
		return restapiConfigJSON;
	}
}


text:
import unittest
from tests import testutils
from common import environment
from tests import testconstants
from services.locations.atms.services import countryatmlocationservice

class CountryAtmLocationServiceTest(unittest.TestCase):
    def setUp(self):
        test_utils = testutils.TestUtils(environment.Environment.SANDBOX)
        self._service = countryatmlocationservice.CountryAtmLocationService(testconstants.TestConstants.SANDBOX_CONSUMER_KEY,
                                                                            test_utils.get_private_key(),
                                                                            environment.Environment.SANDBOX)

    def test_country_atm_location_service(self):
        countries = self._service.get_countries()
        assert countries is not None
        assert len(countries.country) > 0


text:
author: slowe
categories: News
comments: true
date: 2008-06-26T10:55:37Z
slug: hyper-v-released
tags:
- HyperV
- Microsoft
- Virtualization
title: Hyper-V Released
url: /2008/06/26/hyper-v-released/
wordpress_id: 749
---

Today Microsoft released Hyper-V 1.0, their bare-metal hypervisor. I haven't been able to find much information on the Internet about it yet other than [Alessandro's announcement](http://www.virtualization.info/2008/06/release-microsoft-hyper-v-10.html) and [this article at Network World](http://www.networkworld.com/news/2008/062608-microsoft-ships-hyperv.html?nlhtmn=ts_062608&nladname=062608microsoftal); there was nothing on the Microsoft web site about it at the time of this writing.

I've covered Hyper-V extensively in the last few weeks due to my Tech-Ed coverage, so I'll refer readers back to some of the Hyper-V related sessions for more information on Hyper-V architecture, networking, security, or storage:

[VIR367: Hyper-V Security and Best Practices][1]

[VIR250: Advanced Storage Connectivity for VMs][2]

[VIR358: Hyper-V Architecture, Scenarios, and Networking][3]

[Significant Networking Problem with Hyper-V][4]

[Hyper-V Clustering Scenarios][5]

[More on Hyper-V and NIC Teaming][6]

The release of Hyper-V now opens the door for Microsoft's System Center team to finalize Virtual Machine Manager 2008, which I currently see as a notable competitive advantage over VMware due to VMM's ability to manage both Hyper-V as well as VI3. There are a number of VMM 2008 posts available with more information also:

[VIR253: Microsoft System Center VMM 2008, Part 1 of 2][7]

[VIR360: Microsoft System Center VMM 2008, Part 2 of 2][8]

[VIR350: System Center VMM Advanced Integration][9]

The next few weeks will be interesting to watch; in particular, I'm interested to see what actions VMware will take to counter this new competitive threat.

**UPDATE:** Microsoft finally provided some URLs to their announcements:

[Microsofts Hypervisor Technology Gives Customers Combined Benefits of Windows Server 2008 and Virtualization](http://www.microsoft.com/presspass/features/2008/jun08/06-26hyperv.mspx)

[Its here! Windows Server 2008 Hyper-V is available for download](http://blogs.technet.com/stbnewsbytes/archive/2008/06/26/it-s-here-windows-server-2008-hyper-v-is-available-for-download.aspx)

[1]: {{< relref "2008-06-10-vir367-hyper-v-security-and-best-practices.md" >}}
[2]: {{< relref "2008-06-11-vir250-advanced-storage-connectivity-for-vms.md" >}}
[3]: {{< relref "2008-06-12-vir358-hyper-v-architecture-scenarios-and-networking.md" >}}
[4]: {{< relref "2008-06-12-significant-networking-problem-with-hyper-v.md" >}}
[5]: {{< relref "2008-06-22-hyper-v-clustering-scenarios.md" >}}
[6]: {{< relref "2008-06-23-more-on-hyper-v-and-nic-teaming.md" >}}
[7]: {{< relref "2008-06-11-vir253-microsoft-system-center-vmm-2008-part-1-of-2.md" >}}
[8]: {{< relref "2008-06-11-vir360-microsoft-system-center-vmm-2008-part-2-of-2.md" >}}
[9]: {{< relref "2008-06-12-vir350-system-center-vmm-advanced-integration.md" >}}


text:
package main

import (
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"time"
)

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 512
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

// connection is an middleman between the websocket connection and the hub.
type connection struct {
	// The websocket connection.
	ws *websocket.Conn

	// Buffered channel of outbound messages.
	send chan []byte
}

// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump() {
	defer func() {
		h.unregister <- c
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			break
		}
		h.broadcast <- message
	}
}

// write writes a message with the given message type and payload.
func (c *connection) write(mt int, payload []byte) error {
	c.ws.SetWriteDeadline(time.Now().Add(writeWait))
	return c.ws.WriteMessage(mt, payload)
}

// writePump pumps messages from the hub to the websocket connection.
func (c *connection) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.ws.Close()
	}()
	for {
		select {
		case message, ok := <-c.send:
			if !ok {
				c.write(websocket.CloseMessage, []byte{})
				return
			}
			if err := c.write(websocket.TextMessage, message); err != nil {
				return
			}
		case <-ticker.C:
			if err := c.write(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

// serverWs handles webocket requests from the peer.
func serveWs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	h.register <- c
	go c.writePump()
	c.readPump()
}


text:
// Copyright 2017 Google Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
// limitations under the License.

/**
 * hitbox
 *
 * A box collision component which acts as a single mesh
 * for hit-testing against scene elements with multiple
 * children. This simplifies collision detection, as an
 * element will only need to listen for collision events
 * from its hitbox, rather than from each of its child
 * elements.
 *
 * The size of the box is calculated from the bounding box
 * of the element it is attached to, with an added expansion
 * parameter.
 *
 * The box can also change the controller-dot color and size
 * on intersection. TODO: maybe a separate component should
 * do this.
 */

const HITBOX_GEOMETRY = new THREE.PlaneBufferGeometry( 1, 1 );
// const HITBOX_MATERIAL = new THREE.MeshBasicMaterial( { color: 0xFF00FF, side: THREE.DoubleSide, transparent: true, opacity: 0.25 } );
const HITBOX_MATERIAL = new THREE.MeshBasicMaterial( { side: THREE.DoubleSide, visible: false } );

import { TextColorHex, TextColor, WhiteColor } from '../core/colors';
import { Scene } from '../core/scene';
import { PlatformUtils } from '../utils/platform-utils';

if ( typeof AFRAME !== 'undefined' && AFRAME ) {
	AFRAME.registerComponent( 'hitbox', {

		dependencies: [ 'event-priority' ],

		schema: {
			expansion: { default: 20 },
			cursorScale: { default: 1 },
			desktopCursorPointer: { default: true }
		},

		init: function() {

			this.el.classList.add( 'clickable' );
			this.el.setAttribute( 'consume-click', '' );

			// Route intersection events to their functions
			this.el.addEventListener( 'raycaster-intersected', this.onIntersect.bind( this ) );
			this.el.addEventListener( 'raycaster-intersected-cleared', this.onIntersectionCleared.bind( this ) );

			// Update the bounding box if any children are added to the parent element
			this.el.addEventListener( 'child-attached', this.updateBoundingBox.bind( this ) );
			this.el.addEventListener( 'child-detached', this.updateBoundingBox.bind( this ) );

			this.cursor = document.getElementById( 'controller-dot' );
		},

		/**
		 * Calculate the new box scale from the parent element's bounding box
		 */
		updateBoundingBox: function() {
			// Calculate the new box scale from the parent element's bounding box
			this.resizeToThis( this.el.parentNode );
		},

		resizeToThis: function( el ) {
			const obj = el.getObject3D( 'mesh' );
			if ( !obj ) return;
			this.bounds = new THREE.Box3().setFromObject( obj );
			this.bounds.expandByScalar( this.data.expansion );
			this.updateHitboxMesh();
		},

		updateHitboxMesh: function() {
			this.mesh = new THREE.Mesh( HITBOX_GEOMETRY, HITBOX_MATERIAL );
			this.mesh.position.copy( this.bounds.getCenter() );
			this.mesh.position.setZ( this.mesh.position.z + 0.02 );
			this.mesh.scale.copy( this.bounds.getSize() );
			this.mesh.scale.setZ( 1 );

			this.el.setObject3D( 'mesh', this.mesh );

			// raycaster usually updates when hittests are added
			// doesn't work on certain objects like info-card
			Scene.emit( 'force-added', null, false );
		},

		update: function() {
			this.updateBoundingBox();
		},

		onIntersect: function() {
			if ( this.data.desktopCursorPointer ) {
				document.body.classList.add( 'pointer' );
			}

			if ( !this.cursor ) return;
			this.cursor.setAttribute( 'controller-dot', {
				color: TextColor,
				scale: this.data.cursorScale
			});
		},

		onIntersectionCleared: function() {
			document.body.classList.remove( 'pointer' );
			this.cursor.setAttribute( 'controller-dot', {
				color: WhiteColor,
				scale: 1
			});
		},

		remove: function() {
			this.el.removeObject3D( 'mesh' );
			document.body.classList.remove( 'pointer' );
			this.cursor.removeAttribute( 'controller-dot', 'color' );
			this.cursor.removeAttribute( 'controller-dot', 'scale' );
		}
	});
}


text:
@class SNTCertificate;

/// SNTCodesignChecker validates a binary (either on-disk or in memory) has been signed
/// and if so allows for pulling out the certificates that were used to sign it.
@interface SNTCodesignChecker : NSObject

/// The SecStaticCodeRef that this SNTCodesignChecker is working around
@property(readonly) SecStaticCodeRef codeRef;

/// Returns a dictionary of raw signing information
@property(readonly) NSDictionary *signingInformation;

/// Returns an array of @c SNTCertificate objects representing the chain that signed this binary.
@property(readonly) NSArray *certificates;

/// Returns the leaf certificate that this binary was signed with
@property(readonly) SNTCertificate *leafCertificate;

/// Returns the on-disk path of this binary.
@property(readonly) NSString *binaryPath;

/// Initialize an @c SNTCodesignChecker with a SecStaticCodeRef
/// Designated initializer.
/// Takes ownership of @c codeRef.
- (instancetype)initWithSecStaticCodeRef:(SecStaticCodeRef)codeRef;

/// Initialize an @c SNTCodesignChecker with a binary on disk.
/// Returns nil if @c binaryPath does not exist, is not a binary or is not codesigned.
- (instancetype)initWithBinaryPath:(NSString *)binaryPath;

/// Initialize an @c SNTCodesignChecker with the PID of a running process.
- (instancetype)initWithPID:(pid_t)PID;

/// Initialize an @c SNTCodesignChecker for the currently-running process.
- (instancetype)initWithSelf;

/// Returns true if the binary represented by @c otherChecker has signing information that matches
/// this binary.
- (BOOL)signingInformationMatches:(SNTCodesignChecker *)otherChecker;

@end


text:
#if NETFRAMEWORK
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#pragma warning disable CS3015 // Not CLS compliant
#pragma warning disable CS0436 // Type conflict
namespace System.Runtime.Versioning
{
    /// <summary>
    /// Base type for all platform-specific API attributes.
    /// </summary>
    public abstract class OSPlatformAttribute : Attribute
    {
        private protected OSPlatformAttribute(string platformName)
        {
            PlatformName = platformName;
        }
        public string PlatformName { get; }
    }

#if NETFRAMEWORK
    /// <summary>
    /// Records the platform that the project targeted.
    /// </summary>
    [AttributeUsage(AttributeTargets.Assembly,
                    AllowMultiple = false, Inherited = false)]
    public sealed class TargetPlatformAttribute : OSPlatformAttribute
    {
        public TargetPlatformAttribute(string platformName) : base(platformName)
        {
        }
    }

    /// <summary>
    /// Records the operating system (and minimum version) that supports an API. Multiple attributes can be
    /// applied to indicate support on multiple operating systems.
    /// </summary>
    /// <remarks>
    /// Callers can apply a <see cref="System.Runtime.Versioning.SupportedOSPlatformAttribute " />
    /// or use guards to prevent calls to APIs on unsupported operating systems.
    ///
    /// A given platform should only be specified once.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Assembly |
                    AttributeTargets.Class |
                    AttributeTargets.Constructor |
                    AttributeTargets.Enum |
                    AttributeTargets.Event |
                    AttributeTargets.Field |
                    AttributeTargets.Interface |
                    AttributeTargets.Method |
                    AttributeTargets.Module |
                    AttributeTargets.Property |
                    AttributeTargets.Struct,
                    AllowMultiple = true, Inherited = false)]
    public sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
    {
        public SupportedOSPlatformAttribute(string platformName) : base(platformName)
        {
        }
    }

    /// <summary>
    /// Marks APIs that were removed in a given operating system version.
    /// </summary>
    /// <remarks>
    /// Primarily used by OS bindings to indicate APIs that are only available in
    /// earlier versions.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Assembly |
                    AttributeTargets.Class |
                    AttributeTargets.Constructor |
                    AttributeTargets.Enum |
                    AttributeTargets.Event |
                    AttributeTargets.Field |
                    AttributeTargets.Interface |
                    AttributeTargets.Method |
                    AttributeTargets.Module |
                    AttributeTargets.Property |
                    AttributeTargets.Struct,
                    AllowMultiple = true, Inherited = false)]
    public sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
    {
        public UnsupportedOSPlatformAttribute(string platformName) : base(platformName)
        {
        }
    }
#endif

    /// <summary>
    /// Annotates a custom guard field, property or method with a supported platform name and optional version.
    /// Multiple attributes can be applied to indicate guard for multiple supported platforms.
    /// </summary>
    /// <remarks>
    /// Callers can apply a <see cref="System.Runtime.Versioning.SupportedOSPlatformGuardAttribute " /> to a field, property or method
    /// and use that field, property or method in a conditional or assert statements in order to safely call platform specific APIs.
    ///
    /// The type of the field or property should be boolean, the method return type should be boolean in order to be used as platform guard.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Field |
                    AttributeTargets.Method |
                    AttributeTargets.Property,
                    AllowMultiple = true, Inherited = false)]
    public sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
    {
        public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName)
        {
        }
    }

    /// <summary>
    /// Annotates the custom guard field, property or method with an unsupported platform name and optional version.
    /// Multiple attributes can be applied to indicate guard for multiple unsupported platforms.
    /// </summary>
    /// <remarks>
    /// Callers can apply a <see cref="System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute " /> to a field, property or method
    /// and use that  field, property or method in a conditional or assert statements as a guard to safely call APIs unsupported on those platforms.
    ///
    /// The type of the field or property should be boolean, the method return type should be boolean in order to be used as platform guard.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Field |
                    AttributeTargets.Method |
                    AttributeTargets.Property,
                    AllowMultiple = true, Inherited = false)]
    public sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
    {
        public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName)
        {
        }
    }
}
#else
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Versioning.TargetPlatformAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Versioning.SupportedOSPlatformAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Versioning.UnsupportedOSPlatformAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Versioning.SupportedOSPlatformGuardAttribute))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute))]
#endif


text:
/* jshint -W079, -W030, -W117 */
var angularTestPatterns = (function () {
  'use strict';
  return {
    service: {
      resourceHitsEndpoint: resourceHitsEndpoint,
      resourceSuccess: serviceResourceSuccess,
      resourceServerError: serviceResourceServerError
    }
  };

  /**
   * Mocha/Chai test of a service $resource method hitting the endpoint
   * @param {Object} service
   * @param {String} methodName
   * @param {String} resourcePath
   * @param {String=} httpMethod
   */
  function resourceHitsEndpoint (service, methodName, resourcePath, httpMethod) {
    httpMethod = httpMethod || 'GET';
    $httpBackend.when(httpMethod, resourcePath).respond(200); //mock the $resource request
    var promise;
    var resourceMethod = service[methodName]();
    $rootScope.$apply(); // kick angular-mocks to resolve promises
    resourceMethod.$promise.then(function (response) {
      promise = response;
    });
    $httpBackend.flush();
    expect(promise).to.exist;
  }

  /**
   * Mocha/Chai test of a service $resource method, happy path
   * @param {Object} service The $resource service Object
   * @param {String} methodName
   * @param {String} resourcePath
   * @param {Object} mockData
   */
  function serviceResourceSuccess (service, methodName, resourcePath, mockData) {
    $httpBackend.when('GET', resourcePath).respond(200, mockData); // mock the $resource[method]()
    var queryResponse;
    var resourceMethod = service[methodName]();
    $rootScope.$apply();
    resourceMethod.$promise.then(function(response) {
      queryResponse = response;
    });
    $httpBackend.flush();
    expect(queryResponse).to.exist;
    expect(queryResponse.$resolved).to.be.true;
    expect(queryResponse.length).to.equal(mockData.length);
  }

  /**
   * Mocha/Chai test of service $resource method, server error
   * @param {Object} service
   * @param {String} methodName
   * @param {String} resourceUrl
   * @param {Number} httpErrorCode the error code we want to return
   */
  function serviceResourceServerError (service, methodName, resourceUrl, httpErrorCode) {
    var queryResponse
      , resourceMethod
      , errorMessage = 'An Internal Error Occurred';
    $httpBackend.when('GET', resourceUrl).respond(httpErrorCode, {message: errorMessage}); // return error
    resourceMethod = service[methodName]();
    $rootScope.$apply(); // kick angular-mocks to resolve promises
    resourceMethod.$promise.catch(function(response) {
      queryResponse = response;
    });
    $httpBackend.flush();
    //console.log(queryResponse);
    expect(queryResponse).to.exist;
    expect(queryResponse.status).to.exist;
    expect(queryResponse.status).to.equal(httpErrorCode);
    expect(queryResponse.data).to.exist;
    expect(queryResponse.data.message).to.exist;
    expect(queryResponse.data.message).to.equal(errorMessage);
  }

})();