text:
import React from 'react';
import { shallow } from 'enzyme';
import { AxisLeft, AxisRight } from '@vx/axis';
import { scaleLinear } from '@vx/scale';
import YAxis from '../src/components/YAxis';

describe('<YAxis />', () => {
  const props = {
    scale: scaleLinear({ range: [0, 10], domain: [-5, 400] }),
    width: 100,
  };

  it('should be defined', () => {
    expect(YAxis).toBeDefined();
  });

  it('should render the appropriate axis based on props.orientation', () => {
    const leftAxis = shallow(<YAxis {...props} orientation="left" />);
    const rightAxis = shallow(<YAxis {...props} orientation="right" />);

    expect(leftAxis.find(AxisLeft)).toHaveLength(1);
    expect(leftAxis.find(AxisRight)).toHaveLength(0);

    expect(rightAxis.find(AxisLeft)).toHaveLength(0);
    expect(rightAxis.find(AxisRight)).toHaveLength(1);
  });

  it('should render a label if passed', () => {
    const wrapper = shallow(<YAxis {...props} label="banana" />);
    expect(
      wrapper
        .render()
        .find('.vx-axis-label')
        .first()
        .text(),
    ).toBe('banana');
  });

  it('should use the output of tickFormat() for ticks', () => {
    const tickFormat = () => 'iNvaRiAnT LabEl';
    const wrapper = shallow(<YAxis {...props} tickFormat={tickFormat} />);
    const tick = wrapper
      .render()
      .find('.vx-axis-tick')
      .first();
    expect(tick.find('text').text()).toBe(tickFormat());
  });
});


text:
module RestfulObjects::LinkGenerator
  HTTP_OK = 200

  def link_to(rel, href, type, options = {})
    link = {
      'rel' => generate_rel(rel, options),
      'href' => RestfulObjects::DomainModel.current.base_url + href,
      'type' => generate_repr_type(type, options[:domain_type], options[:element_type]),
      'method' => options[:method] || 'GET' }

    link['arguments'] = options[:arguments] if options[:arguments]

    link
  end

  def generate_rel(rel, options = {})
    if [:self, :up, :next, :previous, :icon, :help].include?(rel)
      rel.to_s
    elsif rel == :described_by
      'describedby'
    else
      if [:action, :action_param, :collection, :delete, :domain_type, :domain_types, :element, :element_type, :persist,
          :property, :return_type, :services, :update, :user, :version].include?(rel)
        'urn:org.restfulobjects:rels/' + underscore_to_hyphen_string(rel)
      else
        'urn:org.restfulobjects:rels/' +
          case rel
            when :add_to
              'add-to;collection="' + options[:collection] + '"'
            when :attachment
              'attachment;property="' + options[:property] + '"'
            when :choice
              if options[:property]
                'choice;property="' + options[:property] + '"'
              elsif options[:action]
                'choice;action="' + options[:action] + '"'
              elsif options[:param]
                'choice;param="' + options[:param] + '"'
              else
                raise 'option not found for choice rel'
              end
            when :clear
              'clear;property="' + options[:property] + '"'
            when :details
              if options[:property]
                'details;property="' + options[:property] + '"'
              elsif options[:collection]
                'details;collection="' + options[:collection] + '"'
              elsif options[:action]
                'details;action="' + options[:action] + '"'
              else
                raise 'option not found for details rel'
              end
            when :invoke
              if options[:action]
                'invoke;action="' + options[:action] + '"'
              elsif options[:type_action]
                'invoke;typeaction="' + options[:type_action] + '"'
              else
                raise 'option not found for invoke rel'
              end
            when :modify
              'modify;property="' + options[:property] + '"'
            when :remove_from
              'remove-from;collection="' + options[:collection] + '"'
            when :service
              'service;serviceId="' + options[:service_id] + '"'
            when :value
              if options[:property]
                'value;property="' + options[:property] + '"'
              elsif options[:collection]
                'value;collection="' + options[:collection] + '"'
              else
                raise 'option not found for value rel'
              end
            else
              raise "rel invalid: #{rel}"
          end
      end
    end
  end

  def generate_repr_type(type, domain_type = nil, element_type = nil)
    valid_repr = [:homepage, :user, :version, :list, :object, :object_property, :object_collection, :object_action,
     :object_result, :action_result, :type_list, :domain_type, :property_description, :collection_description,
     :action_description, :action_param_description, :type_action_result, :error, :services]

    raise "repr-type invalid: #{type.to_s}" if not valid_repr.include?(type)

    repr = 'application/json;profile="urn:org.restfulobjects:repr-types/' + underscore_to_hyphen_string(type) + '"'

    if domain_type && [:object, :action].include?(type)
      repr += ';x-ro-domain-type="' + domain_type + '"'
    elsif element_type && [:object_collection, :action].include?(type)
      repr +=';x-ro-element-type="' + element_type + '"'
    end

    repr
  end

  def underscore_to_hyphen_string(symbol)
    symbol.to_s.sub('_', '-')
  end

  def ro_content_type_for_object(domain_type)
    "application/json;profile=\"urn:org.restfulobjects:repr-types/object\";x-ro-domain-type=\"#{domain_type}\""
  end

  def ro_content_type_for_property
    "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
  end

  def ro_content_type_for_object_collection(element_type)
    "application/json;profile=\"urn:org.restfulobjects:repr-types/object-collection\";x-ro-element-type=\"#{element_type}\""
  end
end

redpajama_set_name: RedPajamaGithub


text:
const webpack = require('webpack');
const merge = require('lodash/merge');
const defaultConfig = require('./webpack.bix');
const productionConfig = merge({}, defaultConfig, {
  cache: false,

  debug: false,

  output: merge({}, defaultConfig.output, {
    filename: 'bix.min.js'
  }),

  plugins: defaultConfig.plugins.concat([
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        booleans: true,
        conditionals: true,
        drop_console: true,
        drop_debugger: true,
        join_vars: true,
        screw_ie8: true,
        sequences: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      sourceMap: false
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ])
});

delete productionConfig.devtool;

module.exports = productionConfig;


text:
"""
sentry.interfaces.exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""

from __future__ import absolute_import

__all__ = ('Exception',)

from django.conf import settings

from sentry.interfaces.base import Interface
from sentry.interfaces.stacktrace import Stacktrace, is_newest_frame_first
from sentry.utils.safe import trim
from sentry.web.helpers import render_to_string

class SingleException(Interface):
    """
    A standard exception with a ``type`` and value argument, and an optional
    ``module`` argument describing the exception class type and
    module namespace. Either ``type`` or ``value`` must be present.

    You can also optionally bind a stacktrace interface to an exception. The
    spec is identical to ``sentry.interfaces.Stacktrace``.

    >>>  {
    >>>     "type": "ValueError",
    >>>     "value": "My exception value",
    >>>     "module": "__builtins__"
    >>>     "stacktrace": {
    >>>         # see sentry.interfaces.Stacktrace
    >>>     }
    >>> }
    """
    score = 900
    display_score = 1200

    @classmethod
    def to_python(cls, data):
        assert data.get('type') or data.get('value')

        if data.get('stacktrace') and data['stacktrace'].get('frames'):
            stacktrace = Stacktrace.to_python(data['stacktrace'])
        else:
            stacktrace = None

        kwargs = {
            'type': trim(data.get('type'), 128),
            'value': trim(data.get('value'), 4096),
            'module': trim(data.get('module'), 128),
            'stacktrace': stacktrace,
        }

        return cls(**kwargs)

    def to_json(self):
        if self.stacktrace:
            stacktrace = self.stacktrace.to_json()
        else:
            stacktrace = None

        return {
            'type': self.type,
            'value': self.value,
            'module': self.module,
            'stacktrace': stacktrace,
        }

    def get_api_context(self):
        if self.stacktrace:
            stacktrace = self.stacktrace.get_api_context()
        else:
            stacktrace = None

        return {
            'type': self.type,
            'value': self.value,
            'module': self.module,
            'stacktrace': stacktrace,
        }

    def get_alias(self):
        return 'exception'

    def get_path(self):
        return 'sentry.interfaces.Exception'

    def get_hash(self):
        output = None
        if self.stacktrace:
            output = self.stacktrace.get_hash()
            if output and self.type:
                output.append(self.type)
        if not output:
            output = filter(bool, [self.type, self.value])
        return output

    def get_context(self, event, is_public=False, **kwargs):
        last_frame = None
        interface = event.interfaces.get('sentry.interfaces.Stacktrace')
        if interface is not None and interface.frames:
            last_frame = interface.frames[-1]

        e_module = self.module
        e_type = self.type
        e_value = self.value

        if self.module:
            fullname = '%s.%s' % (e_module, e_type)
        else:
            fullname = e_type

        if e_value and not e_type:
            e_type = e_value
            e_value = None

        return {
            'is_public': is_public,
            'event': event,
            'exception_type': e_type,
            'exception_value': e_value,
            'exception_module': e_module,
            'fullname': fullname,
            'last_frame': last_frame,
        }

class Exception(Interface):
    """
    An exception consists of a list of values. In most cases, this list
    contains a single exception, with an optional stacktrace interface.

    Each exception has a mandatory ``value`` argument and optional ``type`` and
    ``module`` arguments describing the exception class type and module
    namespace.

    You can also optionally bind a stacktrace interface to an exception. The
    spec is identical to ``sentry.interfaces.Stacktrace``.

    >>> {
    >>>     "values": [{
    >>>         "type": "ValueError",
    >>>         "value": "My exception value",
    >>>         "module": "__builtins__"
    >>>         "stacktrace": {
    >>>             # see sentry.interfaces.Stacktrace
    >>>         }
    >>>     }]
    >>> }

    Values should be sent oldest to newest, this includes both the stacktrace
    and the exception itself.

    .. note:: This interface can be passed as the 'exception' key in addition
              to the full interface path.
    """

    score = 2000

    @classmethod
    def to_python(cls, data):
        if 'values' not in data:
            data = {'values': [data]}

        assert data['values']

        trim_exceptions(data)

        kwargs = {
            'values': [
                SingleException.to_python(v)
                for v in data['values']
            ],
        }

        if data.get('exc_omitted'):
            assert len(data['exc_omitted']) == 2
            kwargs['exc_omitted'] = data['exc_omitted']
        else:
            kwargs['exc_omitted'] = None

        return cls(**kwargs)

    def to_json(self):
        return {
            'values': [v.to_json() for v in self.values],
            'exc_omitted': self.exc_omitted,
        }

    def get_api_context(self):
        return {
            'values': [v.get_api_context() for v in self.values],
            'excOmitted': self.exc_omitted,
        }

    def __getitem__(self, key):
        return self.values[key]

    def __iter__(self):
        return iter(self.values)

    def __len__(self):
        return len(self.values)

    def get_alias(self):
        return 'exception'

    def get_path(self):
        return 'sentry.interfaces.Exception'

    def compute_hashes(self, platform):
        system_hash = self.get_hash(system_frames=True)
        if not system_hash:
            return []

        app_hash = self.get_hash(system_frames=False)
        if system_hash == app_hash or not app_hash:
            return [system_hash]

        return [system_hash, app_hash]

    def get_hash(self, system_frames=True):
        # optimize around the fact that some exceptions might have stacktraces
        # while others may not and we ALWAYS want stacktraces over values
        output = []
        for value in self.values:
            if not value.stacktrace:
                continue
            stack_hash = value.stacktrace.get_hash(
                system_frames=system_frames,
            )
            if stack_hash:
                output.extend(stack_hash)
                output.append(value.type)

        if not output:
            for value in self.values:
                output.extend(value.get_hash())

        return output

    def get_context(self, event, is_public=False, **kwargs):
        newest_first = is_newest_frame_first(event)

        system_frames = 0
        app_frames = 0
        unknown_frames = 0
        for exc in self.values:
            if not exc.stacktrace:
                continue

            for frame in exc.stacktrace.frames:
                if frame.in_app is False:
                    system_frames += 1
                elif frame.in_app is True:
                    app_frames += 1
                else:
                    unknown_frames += 1

        # TODO(dcramer): this should happen in normalize
        # We need to ensure that implicit values for in_app are handled
        # appropriately
        if unknown_frames and (app_frames or system_frames):
            for exc in self.values:
                if not exc.stacktrace:
                    continue

                for frame in exc.stacktrace.frames:
                    if frame.in_app is None:
                        frame.in_app = bool(system_frames)
                        if frame.in_app:
                            app_frames += 1
                        else:
                            system_frames += 1

        # if there is a mix of frame styles then we indicate that system frames
        # are present and should be represented as a split
        has_system_frames = app_frames and system_frames

        context_kwargs = {
            'event': event,
            'is_public': is_public,
            'newest_first': newest_first,
            'has_system_frames': has_system_frames,
        }

        exceptions = []
        last = len(self.values) - 1
        for num, e in enumerate(self.values):
            context = e.get_context(**context_kwargs)
            if e.stacktrace:
                context['stacktrace'] = e.stacktrace.get_context(
                    with_stacktrace=False, **context_kwargs)
            else:
                context['stacktrace'] = {}
            context['stack_id'] = 'exception_%d' % (num,)
            context['is_root'] = num == last
            exceptions.append(context)

        if newest_first:
            exceptions.reverse()

        if self.exc_omitted:
            first_exc_omitted, last_exc_omitted = self.exc_omitted
        else:
            first_exc_omitted, last_exc_omitted = None, None

        return {
            'newest_first': newest_first,
            'system_frames': system_frames if has_system_frames else 0,
            'exceptions': exceptions,
            'stacktrace': self.get_stacktrace(event, newest_first=newest_first),
            'first_exc_omitted': first_exc_omitted,
            'last_exc_omitted': last_exc_omitted,
        }

    def to_html(self, event, **kwargs):
        if not self.values:
            return ''

        if len(self.values) == 1 and not self.values[0].stacktrace:
            exception = self.values[0]
            context = exception.get_context(event=event, **kwargs)
            return render_to_string('sentry/partial/interfaces/exception.html', context)

        context = self.get_context(event=event, **kwargs)
        return render_to_string('sentry/partial/interfaces/chained_exception.html', context)

    def to_string(self, event, is_public=False, **kwargs):
        if not self.values:
            return ''

        output = []
        for exc in self.values:
            output.append(u'{0}: {1}\n'.format(exc.type, exc.value))
            if exc.stacktrace:
                output.append(exc.stacktrace.get_stacktrace(
                    event, system_frames=False, max_frames=5,
                    header=False) + '\n\n')
        return (''.join(output)).strip()

    def get_stacktrace(self, *args, **kwargs):
        exc = self.values[0]
        if exc.stacktrace:
            return exc.stacktrace.get_stacktrace(*args, **kwargs)
        return ''

def trim_exceptions(data, max_values=settings.SENTRY_MAX_EXCEPTIONS):
    # TODO: this doesnt account for cases where the client has already omitted
    # exceptions
    values = data['values']
    exc_len = len(values)

    if exc_len <= max_values:
        return

    half_max = max_values / 2

    data['exc_omitted'] = (half_max, exc_len - half_max)

    for n in xrange(half_max, exc_len - half_max):
        del values[half_max]


text:
module Facts
  module Windows
    module Memory
      module System
        class Capacity
          FACT_NAME = 'memory.system.capacity'

          def call_the_resolver
            fact_value = Facter::Resolvers::Memory.resolve(:capacity)

            Facter::ResolvedFact.new(FACT_NAME, fact_value)
          end
        end
      end
    end
  end
end


text:
select *
from nation b
join customer a on b.n_nationkey = a.c_nationkey


text:
package halive.nativeloader;

import javax.swing.ProgressMonitor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * The Native Loader Extracts nativeFiles like .dll or .so from a jar file
 * and copies them into a external natives Folder.
 *

 * The Status of the loading Prograss can be displayed using a ProgressMonition
 *

 * Currently the Programm cannot Handle Folders wit Letters like ö, ä or ü
 */
public class NativeLoader {

    /**
     * Stores a Static list of valid File Endings.
     * It Contians the following file endings:
     * - .dll
     * - .so
     * - .dylib
     */
    public static String[] VALID_ENDINGS = new String[]{"dll", "so", "dylib"};

    private JarFile jarFile;

    /**
     * Creates a new NativeLoader
     *
     * @param resourceClass The Jar File that contains this Class will be used as a Jar File to extract natives from
     * @throws IOException
     */
    public NativeLoader(Class resourceClass) throws IOException {
        String cName = resourceClass.getName();
        String resName = cName.replace('.', '/') + ".class";
        String[] path = getClass().getClassLoader().getResource(resName).getPath().replace("file:/", "").replace("%20", " ").split("!");
        if (path.length != 2) {
            throw new IOException("Invalid Resource Path or the program vas not started from a JAR");
        }
        loadFromString(path[0]);
    }

    /**
     * Creates a new NativeLoader from a Jar File Given as a File Object
     *
     * @param nativesFile
     * @throws IOException
     */
    public NativeLoader(File nativesFile) throws IOException {
        loadFromString(nativesFile.getPath());
    }

    /**
     * Creates a new NativeLoader using the given string as the Filepath
     *
     * @param filePath
     * @throws IOException
     */
    public NativeLoader(String filePath) throws IOException {
        loadFromString(filePath);
    }

    private void loadFromString(String path) throws IOException {
        String jarPath = path;
        if (!(System.getProperty("os.name").toLowerCase().contains("windows"))) {
            jarPath = "/" + jarPath;
        }
        File f = new File(jarPath);
        JarFile file = new JarFile(f);
        jarFile = file;
    }

    /**
     * Returns a list of Valid JarFileEntries that
     *
     * @return
     */
    public ArrayList<JarEntry> getValidFiles() {
        ArrayList<JarEntry> list = new ArrayList<>();
        Enumeration e = jarFile.entries();
        while (e.hasMoreElements()) {
            JarEntry entry = (JarEntry) e.nextElement();
            if (isValidFile(entry)) {
                list.add(entry);
            }
        }
        return list;
    }

    /**
     * Copies the Natives in the Previously defined JarFile into the given Folder.
     * The ProgressMonitor can be used to Monitor the Progress of the Copying operation
     *
     * @param folder The folder to Copy the natives to.
     * @param mon    the ProgressMonitor to display the current status with. is ths is null no ProgressMonitor is used
     * @throws IOException
     */
    public void copyNatives(File folder, ProgressMonitor mon) throws IOException {
        if (folder.isFile()) {
            return;
        }
        if (!folder.exists()) {
            folder.mkdirs();
        }
        ArrayList<JarEntry> validFiles = getValidFiles();
        if (mon != null) {
            mon.setMaximum(validFiles.size());
        }
        int pos = 0;
        for (JarEntry entry : validFiles) {
            String[] namePath = entry.getName().split("/");
            String filename = namePath[namePath.length - 1];
            File nativeFile = new File(folder.getPath() + "/" + filename);
            if (mon != null) {
                mon.setProgress(pos);
                mon.setNote("Extracting " + filename);
            }
            if (!nativeFile.exists()) {
                InputStream in = jarFile.getInputStream(entry);
                FileOutputStream out = new FileOutputStream(nativeFile);
                int data = 0;
                while ((data = in.read()) != -1) {
                    out.write(data);
                }
                out.close();
                in.close();
            }
            pos++;
        }
    }

    /**
     * Same as copyNatives(File, ProgressMonitor) ist just sets the PRogresmonitor to null
     *
     * @param folder
     * @throws IOException
     */
    public void copyNatives(File folder) throws IOException {
        copyNatives(folder, null);
    }

    /**
     * Checks if the Given JarEntry is a Valid native
     *
     * @param entry
     * @return true if the JarEntry is a Valid NAtive (has a valid File Ending.)
     */
    public boolean isValidFile(JarEntry entry) {
        for (String s : VALID_ENDINGS) {
            if (entry.getName().toLowerCase().endsWith("." + s)) {
                return true;
            }
        }
        return false;
    }
}


text:
/**
 *
 */
/**
 * @author l.biava
 *
 */
package it.prisma.businesslayer.orchestrator.bpm.ejbcommands.dal;


text:
'use strict';

const Linter = require('../lib/linter');
const path = require('path');

describe('Linter', function() {

  function fooMatcher(name) {
    return name === 'foo';
  }

  function getFileName(filePath) {
    return path.parse(filePath).name;
  }

  function getFilePathParts(filePath) {
    const parsed = path.parse(filePath);
    return parsed.dir.split('/').concat(parsed.name);
  }

  describe('#testFilePath', function() {
    it('uses given pathParser and test to match filePath', function() {
      const linter = new Linter({
        pathParser: getFileName,
        matcher: fooMatcher
      });
      expect(linter.filePathTest('foo')).toBe(true);
      expect(linter.filePathTest('foo.png')).toBe(true);
      expect(linter.filePathTest('wibble/foo.png')).toBe(true);
      expect(linter.filePathTest('foo/bar.png')).toBe(false);
    });

    it('path parsers can return multiple strings to test', function() {
      const linter = new Linter({
        pathParser: getFilePathParts,
        matcher: fooMatcher
      });
      expect(linter.filePathTest('/foo/foo/foo.png')).toBe(true);
      expect(linter.filePathTest('/foo/bar/foo.png')).toBe(false);
    });

    it('if no parser is passed it uses entire path', function() {
      const matcher = jasmine.createSpy('matcher');
      const linter = new Linter({
        matcher: matcher
      });
      linter.filePathTest('foo/bar.png');
      expect(matcher).toHaveBeenCalledWith('foo/bar.png');
    });
  });

  describe('#lint', function() {
    it('lints failing files and returns results object from file linting', function() {
      const linter = new Linter({
        pathParser: getFileName,
        matcher: fooMatcher
      });

      const result = linter.lint(['foo', 'foo', 'bar']);
      expect(result.ok).toBe(false);
      expect(result.passing[0]).toBe('foo');
      expect(result.passing[1]).toBe('foo');
      expect(result.failing).toContain('bar');
    });

    it('lints passing files and returns results object from file linting', function() {
      const linter = new Linter({
        pathParser: getFileName,
        matcher: fooMatcher
      });

      const result = linter.lint(['foo', 'foo', 'foo']);
      expect(result.ok).toBe(true);
      expect(result.passing[0]).toBe('foo');
      expect(result.passing[1]).toBe('foo');
      expect(result.passing[2]).toBe('foo');
      expect(result.failing.length).toBe(0);
    });
  });

});


text:
/*==================================================
 *  Simile Exhibit Map Extension
 *==================================================
 */

(function() {
    var isCompiled = ("Exhibit_MapExtension_isCompiled" in window) &&
                    window.Exhibit_MapExtension_isCompiled;

    Exhibit.MapExtension = {
        params: {
            bundle:     true,
            service:    "google"
        }
    };

    var javascriptFiles = [
        "map-view.js",
        "vemap-view.js",
        "olmap-view.js"
    ];
    var cssFiles = [
        "map-view.css",
        "olmap-view.css"
    ];

    var paramTypes = { bundle: Boolean };
    if (typeof Exhibit_MapExtension_urlPrefix == "string") {
        Exhibit.MapExtension.urlPrefix = Exhibit_MapExtension_urlPrefix;
        if ("Exhibit_MapExtension_parameters" in window) {
            SimileAjax.parseURLParameters(Exhibit_MapExtension_parameters,
                                          Exhibit.MapExtension.params,
                                          paramTypes);
        }
    } else {
        var url = SimileAjax.findScript(document, "/map-extension.js");
        if (url == null) {
            SimileAjax.Debug.exception(new Error("Failed to derive URL prefix for Simile Exhibit Map Extension code files"));
            return;
        }
        Exhibit.MapExtension.urlPrefix = url.substr(0, url.indexOf("map-extension.js"));

        SimileAjax.parseURLParameters(url, Exhibit.MapExtension.params, paramTypes);
    }

    var scriptURLs = [];
    var cssURLs = [];

    if (Exhibit.MapExtension.params.service == "google") {
        if (Exhibit.params.gmapkey) {
            scriptURLs.push("http://maps.google.com/maps?file=api&v=2&key=" + Exhibit.params.gmapkey);
        } else if (Exhibit.MapExtension.params.gmapkey) {
            scriptURLs.push("http://maps.google.com/maps?file=api&v=2&key=" + Exhibit.MapExtension.params.gmapkey);
        } else if (!("GMap2" in window)) {
            scriptURLs.push("http://maps.google.com/maps?file=api&v=2");
        }
    } else if (Exhibit.MapExtension.params.service == "openlayers") {
	scriptURLs.push("http://www.openlayers.org/api/OpenLayers.js");
        scriptURLs.push("http://www.openstreetmap.org/openlayers/OpenStreetMap.js");
    } else {
        scriptURLs.push("http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=5");
    }

    if (Exhibit.MapExtension.params.bundle) {
        scriptURLs.push(Exhibit.MapExtension.urlPrefix + "map-extension-bundle.js");
        cssURLs.push(Exhibit.MapExtension.urlPrefix + "map-extension-bundle.css");
    } else {
        SimileAjax.prefixURLs(scriptURLs, Exhibit.MapExtension.urlPrefix + "scripts/", javascriptFiles);
        SimileAjax.prefixURLs(cssURLs, Exhibit.MapExtension.urlPrefix + "styles/", cssFiles);
    }

    for (var i = 0; i < Exhibit.locales.length; i++) {
        scriptURLs.push(Exhibit.MapExtension.urlPrefix + "locales/" + Exhibit.locales[i] + "/map-locale.js");
    };

    if (!isCompiled) {
        SimileAjax.includeJavascriptFiles(document, "", scriptURLs);
        SimileAjax.includeCssFiles(document, "", cssURLs);
    }
})();


text:
bugfree-dangerzone
==================

lets keep it bug free


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#B2C2CA</color>
    <color name="colorPrimaryDark">#96ACB7</color>
    <color name="colorAccent">#F58A88</color>

    <color name="headerBackground">#E3E8EB</color>
    <color name="headerText">#000000</color>
</resources>


text:
/*                                                                      *\
** Squants                                                              **
**                                                                      **
** Scala Quantities and Units of Measure Library and DSL                **
** (c) 2013-2015, Gary Keorkunian                                       **
**                                                                      **
\*                                                                      */

package squants.time

/**
 * Represents an intermediate value used in 2nd derivative time calculations
 *
 * Create objects by calling the Time.squared method.
 *
 * q1 / TimeSquared(t1, t2) == q1 / t1 / t2 == q1 / (t1 * t2)
 *
 * q2 * TimeSquared(t1, t2) == q2 * t1 * t2
 *
 * q1 / t1.squared == q1 / t1 / t1
 *
 * q2 * t1.squared == q2 * t1 * t1
 *
 * where q1 is a second degree time integral
 * and q2 is a second degree time derivative
 *
 * @param time1 Time
 * @param time2 Time
 *
 * @author garyKeorkunian
 * @since 0.5.1
 */
case class TimeSquared(time1: Time, time2: Time) {
  def squareRoot = time1.unit(math.sqrt(time1.value * time2.to(time1.unit)))
  def *(that: SecondTimeDerivative[_]) = that * (time1 * time2)
}

object TimeSquared {
  def apply(time: Time): TimeSquared = TimeSquared(time, time)
}

trait TimeSquaredUnit {
  protected def timeUnit: TimeUnit
  def apply(value: Double): TimeSquared = TimeSquared(timeUnit(value), timeUnit(value))
}
object SecondsSquared extends TimeSquaredUnit {
  protected def timeUnit = Seconds
}
object MinutesSquared extends TimeSquaredUnit {
  protected def timeUnit = Minutes
}
object HoursSquared extends TimeSquaredUnit {
  protected def timeUnit = Hours
}


text:
<!DOCTYPE html>

    <?php
    $root = './';
    $templatePath = $root . 'templates/';
    include($root . 'common.php');
    // map of articles to category to use in page title
    include($root . 'content/details/mappings.php');
    $sectionTitle = $titles[$_GET['id']];
    include($templatePath . '_head.php');
    ?>

        <?php
        $navActive = '';
        $navLeftActive = '';
        include($templatePath . '_header.php');
        ?>

                    Marshall Farrier's tech blog

Commentary, coding tips, libraries and utilities

                             <?php
                             $articleUrl = 'content/details/_' . $_GET['id'] . '.php';
                             if (is_readable($articleUrl)) {
                                 include($articleUrl);
                             }
                             else {
                                 echo '
';
                                 echo '
Article unavailable. ';
                                 echo 'Please return to the home page ';
                                 echo 'for links to available content.
';
                                 echo '
';
                             }
                             ?>

                        <?php
                        include('templates/_sidebar.php');
                        ?>

        <?php
            include($templatePath . '_requirejspath.php');
        ?>


text:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;

/**
 * Somewhat sneaky code to start a ClassServer as a daemon thread,
 * requiring the caller to only have createClassLoader permission. This
 * is to avoid requiring the caller to have permission to read the JSK
 * tools.jar, because its location isn't a constant that we can embed
 * in security policy files, and we don't want to have to grant tests
 * permission to read all files.
 */
public class HTTPD {
    /** default HTTPD port, can be overridden by jsk.port in test.props */
    private static int defaultPort = 8081;

    static {
	String port = TestLibrary.getExtraProperty("jsk.port", null);
	if (port != null) {
	    try {
		defaultPort = Integer.decode(port).intValue();
	    } catch (NumberFormatException e) {
		e.printStackTrace();
	    }
	}
    }

    /** the port being used */
    private int port;
    /** the ClassServer instance */
    private Thread daemon;

    /**
     * Create an instance using the default port, serving up the files
     * in the lib directory of jsk.home (as specified in test.props).
     */
    public HTTPD() throws IOException {
	this(getDefaultPort(), getDefaultDir());
    }

    /**
     * Create an instance on the specified port, serving up the files
     * in the specified directory.
     */
    public HTTPD(int port, String dir) throws IOException {
	this.port = port;
	String libDir =
	    TestLibrary.getExtraProperty("jsk.home", TestLibrary.jskHome) +
	    File.separator + "lib";
	String toolsJar = libDir + File.separator + "tools.jar";
	String jsklibJar = libDir + File.separator + "jsk-lib.jar";
	System.err.println("HTTPD: using " + toolsJar +
			   " on port " + port + " serving " + dir);
	ClassLoader ld = new Loader0(toolsJar, jsklibJar, port, dir);
	try {
	    Class cl = Class.forName("HTTPD$Daemon", false, ld);
	    Method m = cl.getMethod("create",
				    new Class[]{String.class, int.class,
						String.class});
	    try {
		daemon = (Thread) m.invoke(null,
					   new Object[]{toolsJar,
							new Integer(port),
							dir});
	    } catch (InvocationTargetException e) {
		Throwable cause = e.getCause();
		if (cause instanceof Error) {
		    throw (Error) cause;
		} else {
		    throw (Exception) cause;
		}
	    }
	} catch (RuntimeException e) {
	    throw e;
	} catch (IOException e) {
	    throw e;
	} catch (Exception e) {
	    IOException ee = new IOException("oops"); // hack
	    ee.initCause(e);
	    throw ee;
	}
    }

    /** Returns the default port for serving up davis files */
    public static int getDefaultPort() {
	return defaultPort;
    }

    /** Returns the default directory for serving up davis files */
    public static String getDefaultDir() {
	return (TestLibrary.getExtraProperty("jsk.home", TestLibrary.jskHome) +
		File.separator + "lib-dl");
    }

    /** Shut it down */
    public void stop() throws IOException {
	Socket sock = new Socket(InetAddress.getLocalHost(), port);
	try {
	    DataOutputStream out =
		new DataOutputStream(sock.getOutputStream());
	    out.writeBytes("SHUTDOWN *\r\n\r\n");
	    out.flush();
	} finally {
	    try {
		sock.close();
	    } catch (IOException e) {
	    }
	}
    }

    /**
     * This class is loaded into a Loader0 classloader. This is a
     * bootstrap process so that the caller only has to have
     * createClassLoader permission, and other permissions can be
     * granted to this class by Loader0.
     */
    public static class Daemon {
	/**
	 * Returns a daemon thread running the ClassServer from the
	 * specified toolsJar file, on the specified port, serving
	 * up files from the specified directory.
	 */
	public static Thread create(final String toolsJar,
				    final int port,
				    final String dir)
	    throws Exception
	{
	    Thread t;
	    try {
		t = (Thread) AccessController.doPrivileged(
		    new PrivilegedExceptionAction() {
		    public Object run() throws Exception {
			ClassLoader ld = new Loader(
			    new URL[]{new File(toolsJar).toURI().toURL()},
			    port, dir);
			Class cl =
			    Class.forName("com.sun.jini.tool.ClassServer",
					  false, ld);
			Constructor cons =
			    cl.getConstructor(new Class[]{int.class,
							  dir.getClass(),
							  boolean.class,
							  boolean.class});
			try {
			    return cons.newInstance(
					new Object[]{new Integer(port), dir,
						     Boolean.FALSE,
						     Boolean.FALSE});
			} catch (InvocationTargetException e) {
			    Throwable cause = e.getCause();
			    if (cause instanceof Error) {
				throw (Error) cause;
			    } else {
				throw (Exception) cause;
			    }
			}
		    }
		});
		t.setDaemon(true);
		t.start();
		return t;
	    } catch (PrivilegedActionException e) {
		throw e.getException();
	    }
	}
    }

    /** ClassLoader that grants extra permissions to loaded code */
    private static class Loader extends URLClassLoader {
	private int port;
	private String dir;

	Loader(URL[] urls, int port, String dir)
	    throws MalformedURLException
	{
	    super(urls);
	    this.port = port;
	    this.dir = dir;
	}

	protected PermissionCollection getPermissions(CodeSource cs) {
	    PermissionCollection perms = super.getPermissions(cs);
	    perms.add(new SocketPermission("localhost:" + port, "listen"));
	    perms.add(new SocketPermission("*", "accept"));
	    perms.add(new FilePermission(dir + File.separator + "-", "read"));
	    return perms;
	}
    }

    /**
     * ClassLoader that prefers all HTTPD nested classes and grants
     * permission to read toolsJar.
     */
    private static class Loader0 extends Loader {
	private String toolsJar;
	private String jsklibJar;

        Loader0(String toolsJar, String jsklibJar, int port, String dir)
	    throws MalformedURLException
	{
	    super(new URL[]{new File(TestParams.testClasses).toURI().toURL()},
		  port, dir);
	    this.toolsJar = toolsJar;
	    this.jsklibJar = jsklibJar;
	}

	protected synchronized Class loadClass(String name, boolean resolve)
	    throws ClassNotFoundException
	{
	    if (name.startsWith("HTTPD")) {
		Class c = findLoadedClass(name);
		if (c == null) {
		    c = findClass(name);
		}
		if (resolve) {
		    resolveClass(c);
		}
		return c;
	    } else {
		return super.loadClass(name, resolve);
	    }
	}

	protected PermissionCollection getPermissions(CodeSource cs) {
	    PermissionCollection perms = super.getPermissions(cs);
	    perms.add(new FilePermission(toolsJar, "read"));
	    perms.add(new FilePermission(jsklibJar, "read"));
	    return perms;
	}
    }
}


text:
import os
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', ]

# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'{{ cookiecutter.project_name }}'
copyright = u'{{ cookiecutter.year }}, {{ cookiecutter.author }}'
version = u'{{ cookiecutter.version }}'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# -- Options for HTML output --------------------------------------------------

# The theme to use for HTML and HTML Help pages.  Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
# html_theme = '_theme'
# html_static_path = ['static']

# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [('index', '%s.tex' % project, u'%s Documentation' % project, u'OpenStack Foundation', 'manual'), ]

# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}


text:
#ifndef INCLUDED_flixel_util_FlxPath
#define INCLUDED_flixel_util_FlxPath

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
HX_DECLARE_CLASS1(flixel,FlxBasic)
HX_DECLARE_CLASS1(flixel,FlxObject)
HX_DECLARE_CLASS2(flixel,math,FlxPoint)
HX_DECLARE_CLASS2(flixel,util,FlxPath)
HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable)
HX_DECLARE_CLASS2(flixel,util,IFlxPooled)
namespace flixel{
namespace util{

class HXCPP_CLASS_ATTRIBUTES  FlxPath_obj : public hx::Object{
	public:
		typedef hx::Object super;
		typedef FlxPath_obj OBJ_;
		FlxPath_obj();
		Void __construct(Array< ::Dynamic > Nodes);

	public:
		inline void *operator new( size_t inSize, bool inContainer=true,const char *inName="flixel.util.FlxPath")
			{ return hx::Object::operator new(inSize,inContainer,inName); }
		static hx::ObjectPtr< FlxPath_obj > __new(Array< ::Dynamic > Nodes);
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		//~FlxPath_obj();

		HX_DO_RTTI_ALL;
		Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);
		static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
		Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp);
		static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
		void __GetFields(Array< ::String> &outFields);
		static void __register();
		void __Mark(HX_MARK_PARAMS);
		void __Visit(HX_VISIT_PARAMS);
		hx::Object *__ToInterface(const hx::type_info &inType);
		operator ::flixel::util::IFlxDestroyable_obj *();
		::String __ToString() const { return HX_HCSTRING("FlxPath","\x17","\x1f","\xaa","\xda"); }

		static void __boot();
		static int FORWARD;
		static int BACKWARD;
		static int LOOP_FORWARD;
		static int LOOP_BACKWARD;
		static int YOYO;
		static int HORIZONTAL_ONLY;
		static int VERTICAL_ONLY;
		static ::flixel::math::FlxPoint _point;
		Array< ::Dynamic > _nodes;
		Float speed;
		Float angle;
		bool autoCenter;
		bool active;
		Dynamic onComplete;
		Dynamic &onComplete_dyn() { return onComplete;}
		int nodeIndex;
		bool finished;
		int _mode;
		int _inc;
		bool _autoRotate;
		Dynamic _wasObjectImmovable;
		bool _firstUpdate;
		::flixel::FlxObject object;
		virtual ::flixel::util::FlxPath reset( );
		Dynamic reset_dyn();

		virtual ::flixel::util::FlxPath setProperties( hx::Null< Float >  Speed,hx::Null< int >  Mode,hx::Null< bool >  AutoRotate);
		Dynamic setProperties_dyn();

		virtual ::flixel::util::FlxPath start( Array< ::Dynamic > Nodes,hx::Null< Float >  Speed,hx::Null< int >  Mode,hx::Null< bool >  AutoRotate,hx::Null< bool >  NodesAsReference);
		Dynamic start_dyn();

		virtual ::flixel::util::FlxPath restart( );
		Dynamic restart_dyn();

		virtual ::flixel::util::FlxPath setNode( int NodeIndex);
		Dynamic setNode_dyn();

		virtual Void update( Float elapsed);
		Dynamic update_dyn();

		virtual Void calculateVelocity( ::flixel::math::FlxPoint node,bool horizontalOnly,bool verticalOnly);
		Dynamic calculateVelocity_dyn();

		virtual ::flixel::math::FlxPoint advancePath( hx::Null< bool >  Snap);
		Dynamic advancePath_dyn();

		virtual ::flixel::util::FlxPath cancel( );
		Dynamic cancel_dyn();

		virtual Void onEnd( );
		Dynamic onEnd_dyn();

		virtual Void destroy( );
		Dynamic destroy_dyn();

		virtual ::flixel::util::FlxPath add( Float X,Float Y);
		Dynamic add_dyn();

		virtual ::flixel::util::FlxPath addAt( Float X,Float Y,int Index);
		Dynamic addAt_dyn();

		virtual ::flixel::util::FlxPath addPoint( ::flixel::math::FlxPoint Node,hx::Null< bool >  AsReference);
		Dynamic addPoint_dyn();

		virtual ::flixel::util::FlxPath addPointAt( ::flixel::math::FlxPoint Node,int Index,hx::Null< bool >  AsReference);
		Dynamic addPointAt_dyn();

		virtual ::flixel::math::FlxPoint remove( ::flixel::math::FlxPoint Node);
		Dynamic remove_dyn();

		virtual ::flixel::math::FlxPoint removeAt( int Index);
		Dynamic removeAt_dyn();

		virtual ::flixel::math::FlxPoint head( );
		Dynamic head_dyn();

		virtual ::flixel::math::FlxPoint tail( );
		Dynamic tail_dyn();

		virtual Array< ::Dynamic > get_nodes( );
		Dynamic get_nodes_dyn();

		virtual Array< ::Dynamic > set_nodes( Array< ::Dynamic > Nodes);
		Dynamic set_nodes_dyn();

};

} // end namespace flixel
} // end namespace util

#endif /* INCLUDED_flixel_util_FlxPath */


text:
FIREFOX_VERSION=2.0.0.3
FIREFOX_HOME=/opt/firefox-$FIREFOX_VERSION/firefox
export PATH="$FIREFOX_HOME:$PATH"
export LD_LIBRARY_PATH="$FIREFOX_HOME:$LD_LIBRARY_PATH"


text:
import numpy as np
import common_libs.utilities as ut
import random
import torch.nn as nn
import torch.autograd as autograd
import torch.optim as optim
import torch
import math

class ModelAbs(nn.Module):

    """
    Abstract model without the forward method.

    lstm for processing tokens in sequence and linear layer for output generation
    lstm is a uni-directional single layer lstm

    num_classes = 1 - for regression
    num_classes = n - for classifying into n classes

    """

    def __init__(self, hidden_size, embedding_size, num_classes):

        super(ModelAbs, self).__init__()
        self.hidden_size = hidden_size
        self.name = 'should be overridden'

        #numpy array with batchsize, embedding_size
        self.embedding_size = embedding_size
        self.num_classes = num_classes

        #lstm - input size, hidden size, num layers
        self.lstm_token = nn.LSTM(self.embedding_size, self.hidden_size)

        #hidden state for the rnn
        self.hidden_token = self.init_hidden()

        #linear layer for regression - in_features, out_features
        self.linear = nn.Linear(self.hidden_size, self.num_classes)

    def init_hidden(self):
        return (autograd.Variable(torch.zeros(1, 1, self.hidden_size)),
                autograd.Variable(torch.zeros(1, 1, self.hidden_size)))

    #this is to set learnable embeddings
    def set_learnable_embedding(self, mode, dictsize, seed = None):

        self.mode = mode

        if mode != 'learnt':
            embedding = nn.Embedding(dictsize, self.embedding_size)

        if mode == 'none':
            print 'learn embeddings form scratch...'
            initrange = 0.5 / self.embedding_size
            embedding.weight.data.uniform_(-initrange, initrange)
            self.final_embeddings = embedding
        elif mode == 'seed':
            print 'seed by word2vec vectors....'
            embedding.weight.data = torch.FloatTensor(seed)
            self.final_embeddings = embedding
        else:
            print 'using learnt word2vec embeddings...'
            self.final_embeddings = seed

    #remove any references you may have that inhibits garbage collection
    def remove_refs(self, item):
        return

class ModelSequentialRNN(ModelAbs):

    """
    Prediction at every hidden state of the unrolled rnn.

    Input - sequence of tokens processed in sequence by the lstm
    Output - predictions at the every hidden state

    uses lstm and linear setup of ModelAbs
    each hidden state is given as a seperate batch to the linear layer

    """

    def __init__(self, hidden_size, embedding_size, num_classes, intermediate):
        super(ModelSequentialRNN, self).__init__(hidden_size, embedding_size, num_classes)
        if intermediate:
            self.name = 'sequential RNN intermediate'
        else:
            self.name = 'sequential RNN'
        self.intermediate = intermediate

    def forward(self, item):

        self.hidden_token = self.init_hidden()

        #convert to tensor
        if self.mode == 'learnt':
            acc_embeds = []
            for token in item.x:
                acc_embeds.append(self.final_embeddings[token])
            embeds = torch.FloatTensor(acc_embeds)
        else:
            embeds = self.final_embeddings(torch.LongTensor(item.x))

        #prepare for lstm - seq len, batch size, embedding size
        seq_len = embeds.shape[0]
        embeds_for_lstm = embeds.unsqueeze(1)

        #lstm outputs
        #output, (h_n,c_n)
        #output - (seq_len, batch = 1, hidden_size * directions) - h_t for each t final layer only
        #h_n - (layers * directions, batch = 1, hidden_size) - h_t for t = seq_len
        #c_n - (layers * directions, batch = 1, hidden_size) - c_t for t = seq_len

        #lstm inputs
        #input, (h_0, c_0)
        #input - (seq_len, batch, input_size)

        lstm_out, self.hidden_token = self.lstm_token(embeds_for_lstm, self.hidden_token)

        if self.intermediate:
            #input to linear - seq_len, hidden_size (seq_len is the batch size for the linear layer)
            #output - seq_len, num_classes
            values = self.linear(lstm_out[:,0,:].squeeze()).squeeze()
        else:
            #input to linear - hidden_size
            #output - num_classes
            values = self.linear(self.hidden_token[0].squeeze()).squeeze()

        return values

class ModelHierarchicalRNN(ModelAbs):

    """
    Prediction at every hidden state of the unrolled rnn for instructions.

    Input - sequence of tokens processed in sequence by the lstm but seperated into instructions
    Output - predictions at the every hidden state

    lstm predicting instruction embedding for sequence of tokens
    lstm_ins processes sequence of instruction embeddings
    linear layer process hidden states to produce output

    """

    def __init__(self, hidden_size, embedding_size, num_classes, intermediate):
        super(ModelHierarchicalRNN, self).__init__(hidden_size, embedding_size, num_classes)

        self.hidden_ins = self.init_hidden()
        self.lstm_ins = nn.LSTM(self.hidden_size, self.hidden_size)

        if intermediate:
            self.name = 'hierarchical RNN intermediate'
        else:
            self.name = 'hierarchical RNN'
        self.intermediate = intermediate

    def copy(self, model):

        self.linear = model.linear
        self.lstm_token = model.lstm_token
        self.lstm_ins = model.lstm_ins

    def forward(self, item):

        self.hidden_token = self.init_hidden()
        self.hidden_ins = self.init_hidden()

        ins_embeds = autograd.Variable(torch.zeros(len(item.x),self.embedding_size))
        for i, ins in enumerate(item.x):

            if self.mode == 'learnt':
                acc_embeds = []
                for token in ins:
                    acc_embeds.append(self.final_embeddings[token])
                token_embeds = torch.FloatTensor(acc_embeds)
            else:
                token_embeds = self.final_embeddings(torch.LongTensor(ins))

            #token_embeds = torch.FloatTensor(ins)
            token_embeds_lstm = token_embeds.unsqueeze(1)
            out_token, hidden_token = self.lstm_token(token_embeds_lstm,self.hidden_token)
            ins_embeds[i] = hidden_token[0].squeeze()

        ins_embeds_lstm = ins_embeds.unsqueeze(1)

        out_ins, hidden_ins = self.lstm_ins(ins_embeds_lstm, self.hidden_ins)

        if self.intermediate:
            values = self.linear(out_ins[:,0,:]).squeeze()
        else:
            values = self.linear(hidden_ins[0].squeeze()).squeeze()

        return values

class ModelHierarchicalRNNRelational(ModelAbs):

    def __init__(self, embedding_size, num_classes):
        super(ModelHierarchicalRNNRelational, self).__init__(embedding_size, num_classes)

        self.hidden_ins = self.init_hidden()
        self.lstm_ins = nn.LSTM(self.hidden_size, self.hidden_size)

        self.linearg1 = nn.Linear(2 * self.hidden_size, self.hidden_size)
        self.linearg2 = nn.Linear(self.hidden_size, self.hidden_size)

    def forward(self, item):

        self.hidden_token = self.init_hidden()
        self.hidden_ins = self.init_hidden()

        ins_embeds = autograd.Variable(torch.zeros(len(item.x),self.hidden_size))
        for i, ins in enumerate(item.x):

            if self.mode == 'learnt':
                acc_embeds = []
                for token in ins:
                    acc_embeds.append(self.final_embeddings[token])
                token_embeds = torch.FloatTensor(acc_embeds)
            else:
                token_embeds = self.final_embeddings(torch.LongTensor(ins))

            #token_embeds = torch.FloatTensor(ins)
            token_embeds_lstm = token_embeds.unsqueeze(1)
            out_token, hidden_token = self.lstm_token(token_embeds_lstm,self.hidden_token)
            ins_embeds[i] = hidden_token[0].squeeze()

        ins_embeds_lstm = ins_embeds.unsqueeze(1)

        out_ins, hidden_ins = self.lstm_ins(ins_embeds_lstm, self.hidden_ins)

        seq_len = len(item.x)

        g_variable = autograd.Variable(torch.zeros(self.hidden_size))

        for i in range(seq_len):
            for j in range(i,seq_len):

                concat = torch.cat((out_ins[i].squeeze(),out_ins[j].squeeze()),0)
                g1 = nn.functional.relu(self.linearg1(concat))
                g2 = nn.functional.relu(self.linearg2(g1))

                g_variable += g2

        output = self.linear(g_variable)

        return output

class ModelSequentialRNNComplex(nn.Module):

    """
    Prediction using the final hidden state of the unrolled rnn.

    Input - sequence of tokens processed in sequence by the lstm
    Output - the final value to be predicted

    we do not derive from ModelAbs, but instead use a bidirectional, multi layer
    lstm and a deep MLP with non-linear activation functions to predict the final output

    """

    def __init__(self, embedding_size):
        super(ModelFinalHidden, self).__init__()

        self.name = 'sequential RNN'
        self.hidden_size = 256
        self.embedding_size = embedding_size

        self.layers = 2
        self.directions = 1
        self.is_bidirectional = (self.directions == 2)
        self.lstm_token = torch.nn.LSTM(input_size = self.embedding_size,
                                  hidden_size = self.hidden_size,
                                  num_layers = self.layers,
                                  bidirectional = self.is_bidirectional)
        self.linear1 = nn.Linear(self.layers * self. directions * self.hidden_size, self.hidden_size)
        self.linear2 = nn.Linear(self.hidden_size,1)
        self.hidden_token = self.init_hidden()

    def init_hidden(self):
        return (autograd.Variable(torch.zeros(self.layers * self.directions, 1, self.hidden_size)),
                autograd.Variable(torch.zeros(self.layers * self.directions, 1, self.hidden_size)))

    def forward(self, item):

        self.hidden_token = self.init_hidden()

        #convert to tensor
        if self.mode == 'learnt':
            acc_embeds = []
            for token in item.x:
                acc_embeds.append(self.final_embeddings[token])
            embeds = torch.FloatTensor(acc_embeds)
        else:
            embeds = self.final_embeddings(torch.LongTensor(item.x))

        #prepare for lstm - seq len, batch size, embedding size
        seq_len = embeds.shape[0]
        embeds_for_lstm = embeds.unsqueeze(1)

        lstm_out, self.hidden_token = self.lstm_token(embeds_for_lstm, self.hidden_token)

        f1 = nn.functional.relu(self.linear1(self.hidden_token[0].squeeze().view(-1)))
        f2 = self.linear2(f1)
        return f2


text:
/**
 * machina - A library for creating powerful and flexible finite state machines. Loosely inspired by Erlang/OTP's gen_fsm behavior.
 * Author: Jim Cowart (http://ifandelse.com)
 * Version: v1.0.0-2
 * Url: http://machina-js.org/
 * License(s): MIT, GPL
 */

(function (root, factory) { /* istanbul ignore if  */
    if (typeof define === "function" && define.amd) {
        // AMD. Register as an anonymous module.
        define(["lodash"], function (_) {
            return factory(_, root);
        }); /* istanbul ignore else  */
    } else if (typeof module === "object" && module.exports) {
        // Node, or CommonJS-Like environments
        module.exports = factory(require("lodash"));
    } else {
        // Browser globals
        root.machina = factory(root._, root);
    }
}(this, function (_, global, undefined) {
    var slice = [].slice;
    var NEXT_TRANSITION = "transition";
    var HANDLING = "handling";
    var HANDLED = "handled";
    var NO_HANDLER = "nohandler";
    var TRANSITION = "transition";
    var INVALID_STATE = "invalidstate";
    var DEFERRED = "deferred";
    var NEW_FSM = "newfsm";

    function getDefaultBehavioralOptions() {
        return {
            initialState: "uninitialized",
            eventListeners: {
                "*": []
            },
            states: {},
            namespace: utils.makeFsmNamespace(),
            useSafeEmit: false,
            hierarchy: {},
            pendingDelegations: {}
        };
    }

    function getDefaultClientMeta() {
        return {
            inputQueue: [],
            targetReplayState: "",
            state: undefined,
            priorState: undefined,
            priorAction: "",
            currentAction: "",
            currentActionArgs: undefined,
            inExitHandler: false
        };
    }

    function getLeaklessArgs(args, startIdx) {
        var result = [];
        for (var i = (startIdx || 0); i < args.length; i++) {
            result[i] = args[i];
        }
        return result;
    }

    function getChildFsmInstance(config) {
        if (!config) {
            return;
        }
        var childFsmDefinition = {};
        if (typeof config === "object") {
            // is this a config object with a factory?
            if (config.factory) {
                childFsmDefinition = config;
            } else {
                // assuming this is a machina instance
                childFsmDefinition.factory = function () {
                    return config;
                };
            }
        } else if (typeof config === "function") {
            childFsmDefinition.factory = config;
        }
        childFsmDefinition.instance = childFsmDefinition.factory();
        return childFsmDefinition;
    }

    function listenToChild(fsm, child) {
        return child.on("*", function (eventName, data) {
            switch (eventName) {
            case "nohandler":
                if (!data.ticket && !data.delegated && data.namespace !== fsm.namespace) {
                    // Ok - we're dealing w/ a child handling input that should bubble up
                    data.args[1].bubbling = true;
                }
                // we do NOT bubble _reset inputs up to the parent
                if (data.inputType !== "_reset") {
                    fsm.handle.apply(fsm, data.args);
                }
                break;
            case "handling":
                var ticket = data.ticket;
                if (ticket && fsm.pendingDelegations[ticket]) {
                    delete fsm.pendingDelegations[ticket];
                }
                fsm.emit(eventName, data); // possibly transform payload?
                break;
            default:
                fsm.emit(eventName, data); // possibly transform payload?
                break;
            }
        });
    }

    // _machKeys are members we want to track across the prototype chain of an extended FSM constructor
    // Since we want to eventually merge the aggregate of those values onto the instance so that FSMs
    // that share the same extended prototype won't share state *on* those prototypes.
    var _machKeys = ["states", "initialState"];
    var extend = function (protoProps, staticProps) {
        var parent = this;
        var fsm; // placeholder for instance constructor
        var machObj = {}; // object used to hold initialState & states from prototype for instance-level merging
        var ctor = function () {}; // placeholder ctor function used to insert level in prototype chain
        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent's constructor.
        if (protoProps && protoProps.hasOwnProperty('constructor')) {
            fsm = protoProps.constructor;
        } else {
            // The default machina constructor (when using inheritance) creates a
            // deep copy of the states/initialState values from the prototype and
            // extends them over the instance so that they'll be instance-level.
            // If an options arg (args[0]) is passed in, a states or intialState
            // value will be preferred over any data pulled up from the prototype.
            fsm = function () {
                var args = slice.call(arguments, 0);
                args[0] = args[0] || {};
                var blendedState;
                var instanceStates = args[0].states || {};
                blendedState = _.merge(_.cloneDeep(machObj), {
                    states: instanceStates
                });
                blendedState.initialState = args[0].initialState || this.initialState;
                _.extend(args[0], blendedState);
                parent.apply(this, args);
            };
        }

        // Inherit class (static) properties from parent.
        _.merge(fsm, parent);

        // Set the prototype chain to inherit from `parent`, without calling
        // `parent`'s constructor function.
        ctor.prototype = parent.prototype;
        fsm.prototype = new ctor();

        // Add prototype properties (instance properties) to the subclass,
        // if supplied.
        if (protoProps) {
            _.extend(fsm.prototype, protoProps);
            _.merge(machObj, _.transform(protoProps, function (accum, val, key) {
                if (_machKeys.indexOf(key) !== -1) {
                    accum[key] = val;
                }
            }));
        }

        // Add static properties to the constructor function, if supplied.
        if (staticProps) {
            _.merge(fsm, staticProps);
        }

        // Correctly set child's `prototype.constructor`.
        fsm.prototype.constructor = fsm;

        // Set a convenience property in case the parent's prototype is needed later.
        fsm.__super__ = parent.prototype;
        return fsm;
    };

    function createUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        return s.join("");
    }

    var utils = {
        makeFsmNamespace: (function () {
            var machinaCount = 0;
            return function () {
                return "fsm." + machinaCount++;
            };
        })(),
        listenToChild: listenToChild,
        getLeaklessArgs: getLeaklessArgs,
        getDefaultOptions: getDefaultBehavioralOptions,
        getDefaultClientMeta: getDefaultClientMeta,
        createUUID: createUUID
    };

    var emitter = {

        emit: function (eventName) {
            var args = getLeaklessArgs(arguments);
            if (this.eventListeners["*"]) {
                _.each(this.eventListeners["*"], function (callback) {
                    if (!this.useSafeEmit) {
                        callback.apply(this, args);
                    } else {
                        try {
                            callback.apply(this, args);
                        } catch (exception) { /* istanbul ignore else  */
                            if (console && typeof console.log !== "undefined") {
                                console.log(exception.stack);
                            }
                        }
                    }
                }, this);
            }
            if (this.eventListeners[eventName]) {
                _.each(this.eventListeners[eventName], function (callback) {
                    if (!this.useSafeEmit) {
                        callback.apply(this, args.slice(1));
                    } else {
                        try {
                            callback.apply(this, args.slice(1));
                        } catch (exception) { /* istanbul ignore else  */
                            if (console && typeof console.log !== "undefined") {
                                console.log(exception.stack);
                            }
                        }
                    }
                }, this);
            }
        },

        on: function (eventName, callback) {
            var self = this;
            self.eventListeners = self.eventListeners || {
                "*": []
            };
            if (!self.eventListeners[eventName]) {
                self.eventListeners[eventName] = [];
            }
            self.eventListeners[eventName].push(callback);
            return {
                eventName: eventName,
                callback: callback,
                off: function () {
                    self.off(eventName, callback);
                }
            };
        },

        off: function (eventName, callback) {
            this.eventListeners = this.eventListeners || {
                "*": []
            };
            if (!eventName) {
                this.eventListeners = {};
            } else {
                if (callback) {
                    this.eventListeners[eventName] = _.without(this.eventListeners[eventName], callback);
                } else {
                    this.eventListeners[eventName] = [];
                }
            }
        },
    };

    var MACHINA_PROP = "__machina__";

    function BehavioralFsm(options) {
        _.extend(this, options);
        _.defaults(this, getDefaultBehavioralOptions());
        this.initialize.apply(this, arguments);
        machina.emit(NEW_FSM, this);
    }

    _.extend(BehavioralFsm.prototype, {
        initialize: function () {},

        initClient: function initClient(client) {
            var initialState = this.initialState;
            if (!initialState) {
                throw new Error("You must specify an initial state for this FSM");
            }
            if (!this.states[initialState]) {
                throw new Error("The initial state specified does not exist in the states object.");
            }
            this.transition(client, initialState);
        },

        ensureClientMeta: function ensureClientMeta(client) {
            if (typeof client !== "object") {
                throw new Error("An FSM client must be an object.");
            }
            client[MACHINA_PROP] = client[MACHINA_PROP] || {};
            if (!client[MACHINA_PROP][this.namespace]) {
                client[MACHINA_PROP][this.namespace] = _.cloneDeep(utils.getDefaultClientMeta());
                this.initClient(client);
            }
            return client[MACHINA_PROP][this.namespace];
        },

        buildEventPayload: function (client, data) {
            if (_.isPlainObject(data)) {
                return _.extend(data, {
                    client: client,
                    namespace: this.namespace
                });
            } else {
                return {
                    client: client,
                    data: data || null,
                    namespace: this.namespace
                };
            }
        },

        getHandlerArgs: function (args, isCatchAll) {
            // index 0 is the client, index 1 is inputType
            // if we're in a catch-all handler, input type needs to be included in the args
            // inputType might be an object, so we need to just get the inputType string if so
            var _args = args.slice(0);
            var input = _args[1];
            if (typeof input === "object") {
                _args.splice(1, 1, input.inputType);
            }
            return isCatchAll ? _args : [_args[0]].concat(_args.slice(2));
        },

        handle: function (client, input) {
            var inputType;
            var delegated;
            var ticket;
            var inputDef = input;
            if (typeof input === "string") {
                inputDef = {
                    inputType: input,
                    delegated: false,
                    ticket: undefined
                };
            }
            var clientMeta = this.ensureClientMeta(client);
            var args = getLeaklessArgs(arguments);
            if (typeof input !== "object") {
                args.splice(1, 1, inputDef);
            }
            clientMeta.currentActionArgs = args.slice(1);
            var currentState = clientMeta.state;
            var stateObj = this.states[currentState];
            var handlerName;
            var handler;
            var isCatchAll = false;
            var child;
            var result;
            if (!clientMeta.inExitHandler) {
                child = stateObj._child && stateObj._child.instance;
                if (child && !this.pendingDelegations[inputDef.ticket] && !inputDef.bubbling) {
                    inputDef.ticket = (inputDef.ticket || utils.createUUID());
                    inputDef.delegated = true;
                    this.pendingDelegations[inputDef.ticket] = {
                        delegatedTo: child.namespace
                    };
                    // WARNING - returning a value from `handle` on child FSMs is not really supported.
                    // If you need to return values from child FSM input handlers, use events instead.
                    result = child.handle.apply(child, args);
                } else {
                    if (inputDef.ticket && this.pendingDelegations[inputDef.ticket]) {
                        delete this.pendingDelegations[inputDef.ticket];
                    }
                    handlerName = stateObj[inputDef.inputType] ? inputDef.inputType : "*";
                    isCatchAll = (handlerName === "*");
                    handler = (stateObj[handlerName] || this[handlerName]) || this["*"];
                    action = clientMeta.state + "." + handlerName;
                    clientMeta.currentAction = action;
                    var eventPayload = this.buildEventPayload(
                    client, {
                        inputType: inputDef.inputType,
                        delegated: inputDef.delegated,
                        ticket: inputDef.ticket
                    });
                    if (!handler) {
                        this.emit(NO_HANDLER, _.extend({
                            args: args
                        }, eventPayload));
                    } else {
                        this.emit(HANDLING, eventPayload);
                        if (typeof handler === "function") {
                            result = handler.apply(this, this.getHandlerArgs(args, isCatchAll));
                        } else {
                            result = handler;
                            this.transition(client, handler);
                        }
                        this.emit(HANDLED, eventPayload);
                    }
                    clientMeta.priorAction = clientMeta.currentAction;
                    clientMeta.currentAction = "";
                }
            }
            return result;
        },

        transition: function (client, newState) {
            var clientMeta = this.ensureClientMeta(client);
            var curState = clientMeta.state;
            var curStateObj = this.states[curState];
            var newStateObj = this.states[newState];
            var childDef;
            var child;
            if (!clientMeta.inExitHandler && newState !== curState) {
                if (newStateObj) {
                    if (newStateObj._child) {
                        newStateObj._child = getChildFsmInstance(newStateObj._child);
                        child = newStateObj._child && newStateObj._child.instance;
                    }
                    if (curStateObj && curStateObj._onExit) {
                        clientMeta.inExitHandler = true;
                        curStateObj._onExit.call(this, client);
                        clientMeta.inExitHandler = false;
                    }
                    if (curStateObj && curStateObj._child && curStateObj._child.instance && this.hierarchy[curStateObj._child.instance.namespace]) {
                        this.hierarchy[curStateObj._child.instance.namespace].off();
                    }
                    clientMeta.targetReplayState = newState;
                    clientMeta.priorState = curState;
                    clientMeta.state = newState;
                    if (child) {
                        this.hierarchy[child.namespace] = utils.listenToChild(this, child);
                    }
                    var eventPayload = this.buildEventPayload(client, {
                        fromState: clientMeta.priorState,
                        action: clientMeta.currentAction,
                        toState: newState
                    });
                    this.emit(TRANSITION, eventPayload);
                    if (newStateObj._onEnter) {
                        newStateObj._onEnter.call(this, client);
                    }
                    if (child) {
                        child.handle(client, "_reset");
                    }
                    if (clientMeta.targetReplayState === newState) {
                        this.processQueue(client, NEXT_TRANSITION);
                    }
                    return;
                }
                this.emit(INVALID_STATE, this.buildEventPayload(client, {
                    state: clientMeta.state,
                    attemptedState: newState
                }));
            }
        },

        deferUntilTransition: function (client, stateName) {
            var clientMeta = this.ensureClientMeta(client);
            if (clientMeta.currentActionArgs) {
                var queued = {
                    type: NEXT_TRANSITION,
                    untilState: stateName,
                    args: clientMeta.currentActionArgs
                };
                clientMeta.inputQueue.push(queued);
                var eventPayload = this.buildEventPayload(client, {
                    state: clientMeta.state,
                    queuedArgs: queued
                });
                this.emit(DEFERRED, eventPayload);
            }
        },

        deferAndTransition: function (client, stateName) {
            this.deferUntilTransition(client, stateName);
            this.transition(client, stateName);
        },

        processQueue: function (client) {
            var clientMeta = this.ensureClientMeta(client);
            var filterFn = function (item) {
                return ((!item.untilState) || (item.untilState === clientMeta.state));
            };
            var toProcess = _.filter(clientMeta.inputQueue, filterFn);
            clientMeta.inputQueue = _.difference(clientMeta.inputQueue, toProcess);
            _.each(toProcess, function (item) {
                this.handle.apply(this, [client].concat(item.args));
            }, this);
        },

        clearQueue: function (client, name) {
            var clientMeta = this.ensureClientMeta(client);
            if (!name) {
                clientMeta.inputQueue = [];
            } else {
                var filter = function (evnt) {
                    return (name ? evnt.untilState !== name : true);
                };
                clientMeta.inputQueue = _.filter(clientMeta.inputQueue, filter);
            }
        }
    }, emitter);

    BehavioralFsm.extend = extend;

    var Fsm = BehavioralFsm.extend({
        constructor: function () {
            BehavioralFsm.apply(this, arguments);
            this.ensureClientMeta();
        },
        initClient: function initClient() {
            var initialState = this.initialState;
            if (!initialState) {
                throw new Error("You must specify an initial state for this FSM");
            }
            if (!this.states[initialState]) {
                throw new Error("The initial state specified does not exist in the states object.");
            }
            this.transition(initialState);
        },
        ensureClientMeta: function ensureClientMeta() {
            if (!this._stamped) {
                this._stamped = true;
                _.defaults(this, _.cloneDeep(getDefaultClientMeta()));
                this.initClient();
            }
            return this;
        },

        ensureClientArg: function (args) {
            var _args = args;
            // we need to test the args and verify that if a client arg has
            // been passed, it must be this FSM instance (this isn't a behavioral FSM)
            if (typeof _args[0] === "object" && !("inputType" in _args[0]) && _args[0] !== this) {
                _args.splice(0, 1, this);
            } else if (typeof _args[0] !== "object" || (typeof _args[0] === "object" && ("inputType" in _args[0]))) {
                _args.unshift(this);
            }
            return _args;
        },

        getHandlerArgs: function (args, isCatchAll) {
            // index 0 is the client, index 1 is inputType
            // if we're in a catch-all handler, input type needs to be included in the args
            // inputType might be an object, so we need to just get the inputType string if so
            var _args = args;
            var input = _args[1];
            if (typeof inputType === "object") {
                _args.splice(1, 1, input.inputType);
            }
            return isCatchAll ? _args.slice(1) : _args.slice(2);
        },
        // "classic" machina FSM do not emit the client property on events (which would be the FSM itself)
        buildEventPayload: function () {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            var data = args[1];
            if (_.isPlainObject(data)) {
                return _.extend(data, {
                    namespace: this.namespace
                });
            } else {
                return {
                    data: data || null,
                    namespace: this.namespace
                };
            }
        },
        handle: function (inputType) {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            return BehavioralFsm.prototype.handle.apply(this, args);
        },
        transition: function (newState) {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            return BehavioralFsm.prototype.transition.apply(this, args);
        },
        deferUntilTransition: function (stateName) {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            return BehavioralFsm.prototype.deferUntilTransition.apply(this, args);
        },
        processQueue: function () {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            return BehavioralFsm.prototype.processQueue.apply(this, args);
        },
        clearQueue: function (stateName) {
            var args = this.ensureClientArg(utils.getLeaklessArgs(arguments));
            return BehavioralFsm.prototype.clearQueue.apply(this, args);
        }
    });

    var machina = _.merge(emitter, {
        Fsm: Fsm,
        BehavioralFsm: BehavioralFsm,
        utils: utils,
        eventListeners: {
            newFsm: []
        }
    });

    return machina;
}));


text:
<!DOCTYPE html>

<title>How do I view my messages?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.messages" name="description">
<meta content="course mail, email" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/neo-default/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I view my messages?

Go to Messages.

Select the Messages tool from the Tool Menu in your site.

Go to Received folder.

Select the Received folder to view a list of your received messages.

Open the message.

New messages will appear in bold text. Select the subject of the message you would like to view. In this case, Unit 1 Exam is selected.

Note: The paperclip icon next to the message indicates that there is a file attached.

View the message.

The contents of the message will appear. The following options will also be available to you:

Reply. Select Reply to reply to the original sender with a message of your own.

Reply to all. Select Reply to all to reply to the original sender and any other course members included on the message.

Forward. Select Forward to forward the message to another member of the course.

Move to folder. Select Move to folder to move the message from one folder to another.

Delete. Select Delete to delete the message.

Open an attachment. Select the file name to open an attachment. In this case, Exam 1.docx is selected.


text:
import os
import platform

from distutils.version import StrictVersion

import cffi

if StrictVersion(cffi.__version__) < StrictVersion('1.0.0'):
    raise RuntimeError(
        'pyspotify-connect requires cffi >= 1.0, but found %s' %
        cffi.__version__)

# Options are armv6l or armv7l
machine = str(platform.machine())
# If travis deploy change x86_64 to armv7l to allow build the source package
if os.getenv('DEPLOY') == 'travis':
    machine = 'armv7l'
if machine == 'armv6l' or machine == 'armv7l':
    header = '#include "spotify.%s.h"' % machine
    header_processed = 'spotify.processed.%s.h' % machine
else:
    raise RuntimeError(
        'pyspotify-connect not available for platform %s' %
        machine)

header_file = os.path.join(os.path.dirname(__file__), header_processed)

with open(header_file) as fh:
    header = fh.read()

ffi = cffi.FFI()
ffi.cdef(header)
ffi.cdef("""
void *malloc(size_t size);
void exit(int status);
""")

ffi.set_source(
    'spotifyconnect._spotifyconnect',
    header,
    libraries=['spotify_embedded_shared'],
    include_dirs=[
        os.path.dirname(__file__)])

if __name__ == '__main__':
    ffi.compile()  # pragma: no cover


text:
license: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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.
---

# SplashScreen.Hide

Schließen Sie den Splash-Screen.

    navigator.splashscreen.hide();

## Beschreibung

Diese Methode weist Begrüßungsbildschirm der Anwendung.

## Unterstützte Plattformen

*   Android
*   BlackBerry 10
*   iOS
*   Windows Phone 7 und 8
*   Windows 8

## Kleines Beispiel

    navigator.splashscreen.hide();

## Vollständiges Beispiel

    <!DOCTYPE html>

        <title>Splashscreen Example</title>

Example

## iOS Quirk

Die `config.xml` Datei `AutoHideSplashScreen` muss `false` . Verstecken den Splash-Screen für zwei Sekunden Verzögerung, fügen Sie einen Timer wie die folgende in der `deviceready` -Ereignishandler:

        setTimeout(function() {
            navigator.splashscreen.hide();
        }, 2000);


text:
package com.albedinsky.android.imageloader;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import com.squareup.picasso.Transformation;

import java.io.IOException;

/**
 * A {@link BaseImageTask} implementation that can be used to load remote image with <b>Url</b> target.
 *
 * @author Martin Albedinsky
 */
public final class ImageTask extends BaseImageTask<Picasso, String, Transformation> {

	/**
	 * Interface ===================================================================================
	 */

	/**
	 * Constants ===================================================================================
	 */

	/**
	 * Log TAG.
	 */
	private static final String TAG = "ImageTask";

	/**
	 * Static members ==============================================================================
	 */

	/**
	 * Target implementation used for asynchronous loading without image view provided.
	 */
	private static final Target ASYNC_TARGET = new Target() {

		/**
		 */
		@Override
		public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
			// Ignored.
		}

		/**
		 */
		@Override
		public void onBitmapFailed(Drawable errorDrawable) {
			// Ignored.
		}

		/**
		 */
		@Override
		public void onPrepareLoad(Drawable placeHolderDrawable) {
			// Ignored.
		}
	};

	/**
	 * Members =====================================================================================
	 */

	/**
	 * Constructors ================================================================================
	 */

	/**
	 * Methods =====================================================================================
	 */

	/**
	 */
	@Override
	protected boolean onLoad(@NonNull Picasso loader, @Nullable final ImageLoader.Callback callback) {
		ensureHasTargetOrThrow();
		final RequestCreator requestCreator = onPrepareRequestCreator(loader);
		if (mView != null) requestCreator.into(mView, callback != null ? new Listener(this, callback) : null);
		else requestCreator.into(new Target() {

			/**
			 */
			@Override
			public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
				if (callback != null) callback.onImageLoadFinished(ImageTask.this, bitmap);
			}

			/**
			 */
			@Override
			public void onBitmapFailed(Drawable errorDrawable) {
				if (callback != null) callback.onImageLoadFailed(
						ImageTask.this,
						new ImageLoader.Error(
								ImageLoader.Error.REASON_UNKNOWN,
								"Failed to load image."
						)
				);
			}

			/**
			 */
			@Override
			public void onPrepareLoad(Drawable placeHolderDrawable) {
				// Ignored.
			}
		});
		return true;
	}

	/**
	 */
	@Override
	protected Bitmap onLoad(@NonNull Picasso loader) {
		ensureHasTargetOrThrow();
		final RequestCreator requestCreator = onPrepareRequestCreator(loader);
		try {
			return requestCreator.get();
		} catch (IOException e) {
			throw new ImageLoader.Error(
					ImageLoader.Error.REASON_IO,
					"Failed to load image.",
					e
			);
		}
	}

	/**
	 * Prepares loading request creator with configuration based on this task's parameters.
	 *
	 * @param loader Loader used to obtain the creator.
	 * @return Prepared image loading request creator to be executed.
	 */
	@NonNull
	protected RequestCreator onPrepareRequestCreator(@NonNull Picasso loader) {
		final RequestCreator creator = loader.load(mTarget);
		if (mPlaceholderRes != NO_RESOURCE_ID) creator.error(mPlaceholderRes);
		if (mPlaceholder != null) creator.error(mPlaceholder);
		if (mErrorRes != NO_RESOURCE_ID) creator.placeholder(mErrorRes);
		if (mError != null) creator.placeholder(mError);
		if (mTransformation != null) creator.transform(mTransformation);
		if (hasRequest(REQUEST_DO_NOT_ANIMATE)) creator.noFade();
		return creator;
	}

	/**
	 */
	@Override
	protected boolean onRemove(@NonNull Picasso loader) {
		throw new UnsupportedOperationException("Picasso image loader does not support removing of loaded images.");
	}

	/**
	 * Inner classes ===============================================================================
	 */

	/**
	 * Listener that wraps implementation of {@link Callback} for a specific {@link ImageLoader.Task}
	 * and {@link ImageLoader.Callback}.
	 */
	private static final class Listener implements Callback {

		/**
		 * Task for which has been loading performed.
		 */
		final ImageLoader.Task task;

		/**
		 * Loader callback to be invoked in case of finished loading or failed loading.
		 */
		final ImageLoader.Callback callback;

		/**
		 * Creates a new Listener wrapper for the given <var>task</var> and <var>callback</var>.
		 *
		 * @param task     The task for which has been loading performed.
		 * @param callback The loader callback to be invoked in case of finished loading or failed loading.
		 */
		Listener(ImageLoader.Task task, ImageLoader.Callback callback) {
			this.task = task;
			this.callback = callback;
		}

		/**
		 */
		@Override
		@SuppressWarnings("ConstantConditions")
		public void onSuccess() {
			final Drawable image = task.view().getDrawable();
			final Bitmap bitmap = image instanceof BitmapDrawable ? ((BitmapDrawable) image).getBitmap() : null;
			if (bitmap == null) {
				Log.w(TAG, "Failed to retrieve loaded bitmap from ImageView. Image drawable(" + image + ") is not instance of BitmapDrawable.");
			}
			callback.onImageLoadFinished(task, bitmap);
		}

		/**
		 */
		@Override
		public void onError() {
			callback.onImageLoadFailed(
					task,
					new ImageLoader.Error(
							ImageLoader.Error.REASON_UNKNOWN,
							"Failed to load image."
					)
			);
		}
	}
}


text:
% declare document class and geometry
\documentclass[12pt]{article} % use larger type; default would be 10pt
\usepackage[margin=1in]{geometry} % handle page geometry

\input{../header2.tex}

\title{Phys 220A -- Classical Mechanics -- Lec07}
\author{UCLA, Fall 2014}
\date{\formatdate{23}{10}{2014}} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed

\begin{document}
\setlength{\unitlength}{1mm}
\maketitle

%\section{Lagrange points}

%Placed in Lec06 material

\section{Parametric resonance}

Question: If a swing has a stable equilibrium how can you make it swing higher and higher?

Let's look at a simple example where we set the mass equal to 1
\begin{eqn}
L = \frac{1}{2} \dot{q}^2 - \frac{1}{2} \omega(t)^2 q^2
\end{eqn}
where $\omega(t + T) = \omega(t)$, i.e. is a periodic function. The simplest example of this is
\begin{eqn}
\omega(t)^2 = \omega_0^2 \left[ 1 + \epsilon \cos\left(\frac{2\pi t}{T}\right) \right]
\end{eqn}
where $\epsilon$ is small. We will simplify by making the choice $T = 2\pi$.

Our equation of motion is thus
\begin{eqn}
\ddot{q} + \omega(t)^2 q = 0
\end{eqn}
We can rewrite this as a first order system
\begin{eqn}
x_1 = q, \qquad
x_2 = \dot{q}
\end{eqn}
with dynamics given by
\begin{eqn}
\dot{x_1} = x_2, \qquad
\dot{x_2} = -\omega(t)^2 x_1.
\end{eqn}
Denoting
\begin{eqn}
\v x = \pmat{ x_1 \\ x_2 },
\end{eqn}
our equation becomes
\begin{eqn}
\dot{\v x} = M(t) \v x
\end{eqn}
where $M(t)$ is also a periodic function. The solution is a matrix integral
\begin{eqn}
\v x(t) = P e^{\int_0^t \dif{t'} \, M(t')} \v x(0)
\end{eqn}
But we know that the solution is periodic so that
\begin{eqn}
x(t + 2\pi) = A\v x(t)
\end{eqn}
for some matrix $A$. More generally we have
\begin{eqn}
x(t + 2\pi n) = A^n\v x(t).
\end{eqn}
Now, for a general $2 \times 2$ matrix the characteristic equation is given by
\begin{eqn}
\lambda^2 - \tr(A) \lambda + \det(A) = 0.
\end{eqn}
Thus we have
\begin{eqn}
\lambda_\pm = \frac{\tr A}{2} \pm \sqrt{ \frac{(\tr A)^2}{4}  - 1},
\end{eqn}
where we can see that the determinant should be $1$ from the Hamiltonian. Thus for real eigenvalues our solutions will be stable for $\abs{\tr A} < 2$ and unstable for $\abs{\tr A} > 2$.

For a general $\omega(t)$ the analysis is difficult, but it's simple if we consider a small perturbation. First consider the unperturbed case $\omega^2(t) = \omega_0^2$ so that the dynamical system is given by
\begin{eqn}
\dot{x_1} = x_2, \qquad
\dot{x_2} = -\omega_0^2 x_1
\end{eqn}
or represented by
\begin{eqn}
M = \left( \begin{array}{cc} 0 & 1 \\ -\omega_0^2 & 0  \end{array} \right).
\end{eqn}
Then we have
\begin{gather}
A(t) = \exp(Mt) =
\begin{pmatrix}
\cos \omega_0 t & \frac{1}{\omega_0} \sin \omega_0 t \\
-\omega_0 \sin \omega_0 t & \cos \omega_0 t
\end{pmatrix}, \\
A(t = 2\pi) =
\begin{pmatrix}
\cos 2\pi \omega_0 & \frac{1}{\omega_0} \sin 2\pi \omega_0 \\
-\omega_0 \sin 2\pi \omega_0 & \cos 2\pi \omega_0
\end{pmatrix}
\end{gather}
and thus we have $\det A = 1$ as expected and $\tr A = 2 \cos 2\pi \omega_0$. Therefore, we have marginal stability when $\abs{\tr A} = 2$ so that $\abs{\cos 2\pi \omega_0} = 1$, thus
\begin{eqn}
\omega_0 = 0, \frac{1}{2}, 1, \frac{3}{2}, \dots.
\end{eqn}
So, away from $\omega_0$ the motion is stable even for small $\epsilon$. But for perturbations at or very near these \emph{parametric resonance frequencies}, we have instability.

\section{Legendre transform (for Hamiltonian mechanics)}

Given a function $f(x)$, we say that it is convex if $f''(x) > 0$. If it is, then we will have a Legendre transform
\begin{eqn}
\mathcal{L} : f(x) \mapsto (\mathcal{L}f)(p)
\end{eqn}
taking $f(x)$ from position space to a function $(\mathcal{L}f)(p)$ in momentum space. Define
\begin{eqn}
F(p,x) = px - f(x),
\end{eqn}
which we picture as the difference between a line of slope $p$ and the convex function $f(x)$. Then the Legendre transformed function is defined as
\begin{eqn}
(\mathcal{L}f)(p) = \sup_{x \in \reals} F(p,x).
\end{eqn}
Put another way, given $p$ there exists some $x(p)$ which maximizes $F(p,x)$, i.e.
\begin{eqn}
\eval[3]{\pd{F}{x}(p,x)}_{x = x(p)} = 0,
\end{eqn}
Then we have
\begin{eqn}
\mathcal{L}f(p) = F(p,x(p)).
\end{eqn}

[missed examples here: $f(x) = ax^2$ and $f(x) = x^a / a$]

An important property of Legendre transforms is that they are \textit{involutions}, that is the Legendre transform squares to the identity. In other words,
\begin{eqn}
\mathcal{L}^2 f(x) = \mathcal{L}(\mathcal{L}f)(x) = f(x).
\end{eqn}
Another useful property is \textit{Young's inequality},
\begin{eqn}
px - f(x) \leq \mathcal{L}f(p).
\end{eqn}

\end{document}


text:
package certificate

import (
	"testing"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	k8sFake "k8s.io/client-go/kubernetes/fake"
)

func TestCreateClusterCertificateCredentials(t *testing.T) {
	tests := []struct {
		name         string
		createClient func() kubernetes.Interface
		expected     bool
	}{
		{
			name: "create cluster certificate success",
			createClient: func() kubernetes.Interface {
				return k8sFake.NewSimpleClientset(&corev1.Secret{
					TypeMeta: metav1.TypeMeta{},
					ObjectMeta: metav1.ObjectMeta{
						Namespace: metav1.NamespaceSystem,
					},
					Data: map[string][]uint8{corev1.ServiceAccountRootCAKey: {1, 2, 3}},
				})
			},
			expected: true,
		},
		{
			name: "create cluster certificate fail",
			createClient: func() kubernetes.Interface {
				return k8sFake.NewSimpleClientset()
			},
			expected: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			client := test.createClient()
			_, _, _, err := CreateClusterCertificateCredentials(client)
			success := err == nil

			if success != test.expected {
				t.Fatalf("Expected %v, but got result %v: %v", test.expected, success, err)
			}
		})
	}
}