text:
import { Injectable } from '@angular/core';
import { Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthHttp } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw'
import 'rxjs/add/observable/never'

import { Template } from '../models/template.model';
import { TemplateField } from '../models/template-field.model';
import { environment } from '../../environments/environment';
import { Notify } from '../common/notify';

@Injectable()
export class TemplateService {
    private api: string = environment.api_url;

    constructor(private router: Router, private http: AuthHttp) {
        console.log(this.constructor.name, 'API URL:', this.api);
    }

    listAllTemplates(): Observable<Template[]> {
        return this.http.get(this.api + 'templates').map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    getTemplate(templateId: number): Observable<Template> {
        return this.http.get(this.api + 'templates/' + templateId).map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    getTemplateFields(templateId: number): Observable<TemplateField[]> {
        return this.http.get(this.api + 'templates/' + templateId + '/fields').map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    createTemplate(template: Template): Observable<Template> {
        return this.http.post(this.api + 'templates', JSON.stringify(template)).map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    updateTemplate(template: Template): Observable<Template> {
        return this.http.put(this.api + 'templates/' + template.id, JSON.stringify(template)).map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    deleteTemplate(templateId: number): Observable<any> {
        return this.http.delete(this.api + 'templates/' + templateId).map(response => response).catch(error => this.handleError(error, this.router));
    }

    createTemplateField(field: TemplateField, templateId: number): Observable<TemplateField> {
        return this.http.post(this.api + 'fields/' + templateId, JSON.stringify(field)).map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    updateTemplateField(field: TemplateField): Observable<TemplateField> {
        return this.http.put(this.api + 'fields/' + field.id, JSON.stringify(field)).map(response => response.json()).catch(error => this.handleError(error, this.router));
    }

    deleteTemplateField(fieldId: number): Observable<any> {
        return this.http.delete(this.api + 'fields/' + fieldId).map(response => response).catch(error => this.handleError(error, this.router));
    }

    upDownTemplateField(fieldId: number, up: boolean): Observable<any> {
        return this.http.get(this.api + 'fields/' + fieldId + (up ? '/up' : '/down')).map(response => response).catch(error => this.handleError(error, this.router));
    }

    private handleError(error: Response, router: Router) {
        console.error(this.constructor.name, 'handleError:', error);
        if(error.status === 401 || error.status === 403) {
            router.navigate(['/login']); // THIS.router = NULL? WHY???
            Notify.notifyRetryLogin();
            return <Observable<any>>Observable.never();
        }
        return Observable.throw(error);
    }
}


text:
import * as $ from "jquery";

$.fn.stick = function(options){
    if($(this).length>0){

        var tt = $(this).offset().top;
        var target = $(this);
        var defaults = {
            to:0,
            cssCached:{
                width:"100%",
                top:$(this).css("top"),
                position:$(this).css("position"),
                "z-index":$(this).css("z-index"),
                height:$(this).outerHeight(),
                nextPaddingTop:target.next("*").css("padding-top")
            }
        }
        options = Object.assign(defaults, options);

        target.wrap("

")

        target.parent().css({
            "height":options.cssCached.height,
            position:"relative"
        })

        if(typeof options.to === "object"){
            options.to = $(options.to).outerHeight()
        }

        $(window).on("scroll", function(e){
            var st = $(this).scrollTop() + options.to;
            if(st>=tt){
                target.css({
                    position:"fixed",
                    top:options.to+"px",
                    "z-index":9999,
                    width:"100%"
                })
            }
            else if(st<=tt){
                target.css(Object.assign(
                    options.cssCached
                ));
            }
        })

    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'base.html' %}
{% load static %}
{% block title %}You are here.{% endblock %}

{% block content %}

Outside Illinois? Go to Tribune Tower or drag the pin on the map!

        Demo
        API
        Source
        About

You are here.

        {% include '_demo.html' %}

        {% include '_api.html' %}

        {% include '_src.html' %}

        {% include '_about.html' %}

{% endblock %}
{% block foot %}

{% endblock %}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { IComponent } from '../../model/capability.model';
import { ComponentService } from '../component.service';

@Component({
  selector: 'app-component-list',
  templateUrl: './component-list.component.html',
  styleUrls: ['./component-list.component.css']
})
export class ComponentListComponent implements OnInit, OnDestroy {
  subscription: Subscription;
  components: IComponent[]= [];
  dataReady = false;

  constructor(private service: ComponentService) { }

  ngOnInit() {
    this.subscription = this.service.getComponents().subscribe(
        components => this.components = components,
        e => console.log('onError %s', e),
        () => { this.dataReady = true; }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  editComponent(comp: IEditableComponent) {
    comp.editEnabled = !comp.editEnabled;
  }
}

export interface IEditableComponent extends IComponent {
  editEnabled: Boolean;
}


text:
from openerp.tests import common

class TestNote(common.TransactionCase):

    def test_bug_lp_1156215(self):
        """ensure any users can create new users"""
        cr, uid = self.cr, self.uid
        IMD = self.registry('ir.model.data')
        Users = self.registry('res.users')

        _, demo_user = IMD.get_object_reference(cr, uid, 'base', 'user_demo')
        _, group_id = IMD.get_object_reference(cr, uid, 'base', 'group_erp_manager')

        Users.write(cr, uid, [demo_user], {
            'groups_id': [(4, group_id)],
        })

        # must not fail
        Users.create(cr, demo_user, {
            'name': 'test bug lp:1156215',
            'login': 'lp_1156215',
        })


text:
'use strict';
var ObjectManage = require('object-manage')
  , fs = require('fs')

var config = new ObjectManage()
config.load({
  port: 3000
})

if(fs.existsSync('./config.user.js')){
  config.load(require('./config.user'))
}

module.exports = config


text:
typedef enum {
    LPGoogleVehicleTypeRAIL,
    LPGoogleVehicleTypeMETRO_RAIL,
    LPGoogleVehicleTypeSUBWAY,
    LPGoogleVehicleTypeTRAM,
    LPGoogleVehicleTypeMONORAIL,
    LPGoogleVehicleTypeHEAVY_RAIL,
    LPGoogleVehicleTypeCOMMUTER_TRAIN,
    LPGoogleVehicleTypeHIGH_SPEED_TRAIN,
    LPGoogleVehicleTypeBUS,
    LPGoogleVehicleTypeINTERCITY_BUS,
    LPGoogleVehicleTypeTROLLEYBUS,
    LPGoogleVehicleTypeSHARE_TAXI,
    LPGoogleVehicleTypeFERRY,
    LPGoogleVehicleTypeCABLE_CAR,
    LPGoogleVehicleTypeGONDOLA_LIFT,
    LPGoogleVehicleTypeFUNICULAR,
    LPGoogleVehicleTypeOTHER
} LPGoogleVehicleType;

@interface LPVehicle : NSObject <NSCoding>

@property (nonatomic, strong) NSString *icon;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) LPGoogleVehicleType type;

+ (LPGoogleVehicleType)getGoogleVehicleTypeFromString:(NSString *)type;
+ (NSString *)getGoogleVehicleType:(LPGoogleVehicleType)type;

+ (id)vehicleWithObjects:(NSDictionary *)dictionary;

- (NSDictionary *)dictionary;

- (id)copyWithZone:(NSZone *)zone;

@end


text:
import Parse from 'parse';
import * as StateManager from 'lib/stores/StateManager';

let stores = {};
let subCount = 0;

export function registerStore(name, store, isGlobal) {
  if (stores[name]) {
    throw new Error(
      'Conflict! Attempted to register multiple stores with the name ' + name
    );
  }

  stores[name] = {
    store: store,
    subscribers: {},
    isGlobal: !!isGlobal
  };
}

export function getStore(name) {
  let storeData = stores[name];
  if (!storeData) {
    throw new Error(
      'Unknown store! Attempted to retrieve store with the name ' + name
    );
  }

  let stateGetter = (storeData.isGlobal ?
    StateManager.getGlobalState :
    StateManager.getAppState
  );
  let stateSetter = (storeData.isGlobal ?
    StateManager.setGlobalState :
    StateManager.setAppState
  );

  return {
    getData: stateGetter.bind(null, name),
    isGlobal: storeData.isGlobal,
    dispatch(type, params, app) {
      let action = {...params, type, app};
      let newState = storeData.store(stateGetter(name, app), action);
      if (newState instanceof Parse.Promise) {
        return newState.then((result) => {
          if (storeData.isGlobal) {
            StateManager.setGlobalState(name, result);
          } else {
            StateManager.setAppState(name, app, result);
          }
          for (let id in storeData.subscribers) {
            storeData.subscribers[id](result);
          }
        });
      } else {
        if (storeData.isGlobal) {
          StateManager.setGlobalState(name, newState);
        } else {
          StateManager.setAppState(name, app, newState);
        }
        for (let id in storeData.subscribers) {
          storeData.subscribers[id](newState);
        }
      }
    },
    subscribe(cb) {
      let id = 'sub' + subCount++;
      storeData.subscribers[id] = cb;
      return id;
    },
    unsubscribe(id) {
      delete storeData.subscribers[id];
    }
  }
}


text:
package org.apache.flink.runtime.state.heap;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.runtime.state.StateSnapshotTransformer;

import javax.annotation.Nonnull;

import java.util.List;

/**
 * This class represents the snapshot of a {@link CopyOnWriteStateTable} and has a role in operator
 * state checkpointing. This class is also responsible for writing the state in the process of
 * checkpointing.
 *
 * @param <K> type of key
 * @param <N> type of namespace
 * @param <S> type of state
 */
@Internal
public class CopyOnWriteStateTableSnapshot<K, N, S> extends AbstractStateTableSnapshot<K, N, S> {

    /** The offset to the contiguous key groups. */
    private final int keyGroupOffset;

    /** Snapshots of state partitioned by key-group. */
    @Nonnull private final List<CopyOnWriteStateMapSnapshot<K, N, S>> stateMapSnapshots;

    /**
     * Creates a new {@link CopyOnWriteStateTableSnapshot}.
     *
     * @param owningStateTable the {@link CopyOnWriteStateTable} for which this object represents a
     *     snapshot.
     */
    CopyOnWriteStateTableSnapshot(
            CopyOnWriteStateTable<K, N, S> owningStateTable,
            TypeSerializer<K> localKeySerializer,
            TypeSerializer<N> localNamespaceSerializer,
            TypeSerializer<S> localStateSerializer,
            StateSnapshotTransformer<S> stateSnapshotTransformer) {
        super(
                owningStateTable,
                localKeySerializer,
                localNamespaceSerializer,
                localStateSerializer,
                stateSnapshotTransformer);

        this.keyGroupOffset = owningStateTable.getKeyGroupOffset();
        this.stateMapSnapshots = owningStateTable.getStateMapSnapshotList();
    }

    @Override
    protected StateMapSnapshot<K, N, S, ? extends StateMap<K, N, S>> getStateMapSnapshotForKeyGroup(
            int keyGroup) {
        int indexOffset = keyGroup - keyGroupOffset;
        CopyOnWriteStateMapSnapshot<K, N, S> stateMapSnapshot = null;
        if (indexOffset >= 0 && indexOffset < stateMapSnapshots.size()) {
            stateMapSnapshot = stateMapSnapshots.get(indexOffset);
        }

        return stateMapSnapshot;
    }

    @Override
    public void release() {
        for (CopyOnWriteStateMapSnapshot snapshot : stateMapSnapshots) {
            if (!snapshot.isReleased()) {
                snapshot.release();
            }
        }
    }
}


text:
package net.razorvine.serpent.ast;

public interface INodeVisitor
{
	void visit(ComplexNumberNode complex);
	void visit(DictNode dict);
	void visit(ListNode list);
	void visit(NoneNode none);
	void visit(IntegerNode value);
	void visit(LongNode value);
	void visit(DoubleNode value);
	void visit(BooleanNode value);
	void visit(StringNode value);
	void visit(BytesNode value);
	void visit(SetNode setnode);
	void visit(TupleNode tuple);
	void visit(BigIntNode value);
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: ww
 * Date: 13.10.15
 * Time: 4:15
 */
namespace Gearman\Conveyor\Inventory;

class GearmanErrorsConstants
{
    const RECEIVED_NOT_SERIALIZED_DATA = "Received not serialized data";

}


text:
struct HeapProfileStats {
  // Returns true if the two HeapProfileStats are semantically equal.
  bool Equivalent(const HeapProfileStats& other) const {
    return allocs - frees == other.allocs - other.frees &&
        alloc_size - free_size == other.alloc_size - other.free_size;
  }

  int32 allocs;      // Number of allocation calls.
  int32 frees;       // Number of free calls.
  int64 alloc_size;  // Total size of all allocated objects so far.
  int64 free_size;   // Total size of all freed objects so far.
};

// Allocation and deallocation statistics per each stack trace.
struct HeapProfileBucket : public HeapProfileStats {
  // Longest stack trace we record.
  static const int kMaxStackDepth = 32;

  uintptr_t hash;           // Hash value of the stack trace.
  int depth;                // Depth of stack trace.
  const void** stack;       // Stack trace.
  HeapProfileBucket* next;  // Next entry in hash-table.
};

#endif  // HEAP_PROFILE_STATS_H_


text:
package org.apache.hadoop.mapreduce.approx.index;

import java.lang.Exception;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.reduce.IntSumReducer;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;

import org.apache.hadoop.mapreduce.approx.index.IndexPartitioner;
import org.apache.hadoop.mapreduce.approx.index.IndexMapper;
import org.apache.hadoop.mapreduce.approx.index.IndexReducer;

import org.apache.log4j.PropertyConfigurator;

public class Index {
	/**
	 * Launch wikipedia page rank.
	 */
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		//PropertyConfigurator.configure("conf/log4j.properties");
		// Parsing options
		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

		Options options = new Options();
		options.addOption("s", "segment", true, "segment size");
		options.addOption("d", "delimiter", true, "fields delimiter");
		options.addOption("f", "fields", true, "fields to compute histogram, ex. 0-2-4, 0th,2th,4th field");
		options.addOption("i", "input",    true,  "Input file");
		options.addOption("t", "table",   true,  "table name");

		try {
			CommandLine cmdline = new GnuParser().parse(options, otherArgs);
			String input  = cmdline.getOptionValue("i");
			String table = cmdline.getOptionValue("t");
			String output = "/index/table/"+table;
			int numReducer = 1;
			if (input == null || output == null) {
				throw new ParseException("No input/output option");
			}
			if(cmdline.hasOption("s")) {
				long segSize = Long.parseLong(cmdline.getOptionValue("s"));
				conf.setLong("map.input.segment.size", segSize);
			}
			if(cmdline.hasOption("d")) {
				conf.set("map.input.delimiter", cmdline.getOptionValue("d"));
			}
			if(cmdline.hasOption("f")) {
				conf.set("map.input.index.fields", cmdline.getOptionValue("f"));
				numReducer = cmdline.getOptionValue("f").split("-").length;
			}

			//cmdline.getOptionValue

			Job job = new Job(conf, "Build histogram");
			job.setJarByClass(Index.class);
			job.setNumReduceTasks(numReducer);
			job.setMapperClass(IndexMapper.class);
			job.setReducerClass(IndexReducer.class);

			job.setMapOutputKeyClass(Text.class);
			job.setMapOutputValueClass(Text.class);
			job.setOutputKeyClass(NullWritable.class);
			job.setOutputValueClass(Text.class);

			job.setPartitionerClass(IndexPartitioner.class);

			job.setInputFormatClass(TextInputFormat.class);

			FileInputFormat.setInputPaths(job,   new Path(input));
			FileOutputFormat.setOutputPath(job, new Path(output));
			System.exit(job.waitForCompletion(true) ? 0 : 1);

		} catch (ParseException exp){
			System.err.println("Error parsing command line: " + exp.getMessage());
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp(Index.class.toString(), options);
			ToolRunner.printGenericCommandUsage(System.out);
			System.exit(2);
		}
	}

}


text:
package krasa.svn.frontend.component.table;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;

/**
 * @author Vojtech Krasa
 */
public class FixedModalWindow extends ModalWindow {

	private static final long serialVersionUID = 1L;

	public FixedModalWindow(String id) {
		super(id);
		setInitialWidth(1000);
		setInitialHeight(1000);
		showUnloadConfirmation(false);
		setCloseButtonCallback(new CloseButtonCallback() {

			@Override
			public boolean onCloseButtonClicked(AjaxRequestTarget target) {
				target.appendJavaScript("$('body').css('overflow','auto');");
				return true;
			}
		});
	}

	@Override
	protected CharSequence getShowJavaScript() {
		// Hack in some JS to remove the onMove handlers
		StringBuilder showJS = new StringBuilder();
		showJS.append((String) super.getShowJavaScript());
		showJS.append("$('body').css('overflow','hidden');");
		return showJS.toString();
	}

	@Override
	protected String getCloseJavacript() {
		StringBuilder closeJS = new StringBuilder();
		closeJS.append(super.getCloseJavacript());
		closeJS.append("$('body').css('overflow','auto');");
		return closeJS.toString();
	}
}


text:
package skinny.controller.feature

import skinny.micro.SkinnyMicroBase
import skinny.micro.context.SkinnyContext
import skinny.micro.contrib.{ AsyncCSRFTokenSupport, CSRFTokenSupport }
import skinny.logging.LoggerProvider

object AsyncCSRFProtectionFeature {

  // follows Rails default
  val DEFAULT_KEY: String = "csrf-token"

}

/**
  * Provides Cross-Site Request Forgery (CSRF) protection.
  */
trait AsyncCSRFProtectionFeature extends AsyncCSRFTokenSupport {

  self: SkinnyMicroBase
    with ActionDefinitionFeature
    with AsyncBeforeAfterActionFeature
    with RequestScopeFeature
    with LoggerProvider =>

  /**
    * Overrides Scalatra's default key name.
    */
  override def csrfKey: String = CSRFProtectionFeature.DEFAULT_KEY

  /**
    * Enabled if true.
    */
  private[this] var forgeryProtectionEnabled: Boolean = false

  /**
    * Excluded actions.
    */
  private[this] val forgeryProtectionExcludedActionNames = new scala.collection.mutable.ArrayBuffer[Symbol]

  /**
    * Included actions.
    */
  private[this] val forgeryProtectionIncludedActionNames = new scala.collection.mutable.ArrayBuffer[Symbol]

  /**
    * Declarative activation of CSRF protection. Of course, highly inspired by Ruby on Rails.
    *
    * @param only should be applied only for these action methods
    * @param except should not be applied for these action methods
    */
  def protectFromForgery(only: Seq[Symbol] = Nil, except: Seq[Symbol] = Nil): Unit = {
    forgeryProtectionEnabled = true
    forgeryProtectionIncludedActionNames ++= only
    forgeryProtectionExcludedActionNames ++= except
  }

  /**
    * Overrides to skip execution when the current request matches excluded patterns.
    */
  override def handleForgery()(implicit ctx: SkinnyContext): Unit = {
    if (forgeryProtectionEnabled) {
      logger.debug {
        s"""
        | ------------------------------------------
        |  [CSRF Protection Enabled]
        |  method      : ${request(context).getMethod}
        |  requestPath : ${requestPath(context)}
        |  actionName  : ${currentActionName}
        |  only        : ${forgeryProtectionIncludedActionNames.mkString(", ")}
        |  except      : ${forgeryProtectionExcludedActionNames.mkString(", ")}
        | ------------------------------------------
        |""".stripMargin
      }

      currentActionName
        .map { name =>
          val currentPathShouldBeExcluded = forgeryProtectionExcludedActionNames.exists(_ == name)
          if (!currentPathShouldBeExcluded) {
            val allPathShouldBeIncluded     = forgeryProtectionIncludedActionNames.isEmpty
            val currentPathShouldBeIncluded = forgeryProtectionIncludedActionNames.exists(_ == name)
            if (allPathShouldBeIncluded || currentPathShouldBeIncluded) {
              handleForgeryIfDetected()
            }
          }
        }
        .getOrElse {
          handleForgeryIfDetected()
        }
    }
  }

  /**
    * Handles when CSRF is detected.
    */
  def handleForgeryIfDetected(): Unit = halt(403)

  // Registers csrfKey & csrfToken to request scope.
  beforeAction() { implicit ctx =>
    if (getFromRequestScope(RequestScopeFeature.ATTR_CSRF_KEY)(context).isEmpty) {
      set(RequestScopeFeature.ATTR_CSRF_KEY, csrfKey)(context)
      set(RequestScopeFeature.ATTR_CSRF_TOKEN, prepareCsrfToken())(context)
    }
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>


text:
<?php

namespace Native5\Identity;

/**
 * SimpleAuthInfo
 *
 * @category  Identity
 * @package   Native5\<package>
 * @author    Barada Sahu <barry@native5.com>
 * @copyright 2012 Native5. All Rights Reserved
 * @license   See attached NOTICE.md for details
 * @version   Release: 1.0
 * @link      http://www.docs.native5.com
 * Created : 27-11-2012
 * Last Modified : Fri Dec 21 09:11:53 2012
 */
class SimpleAuthInfo implements AuthInfo
{

    private $_principals;

    private $_credentials;

    /**
     * Default Constructor
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        $this->_principals  = array();
        $this->_credentials = array();

    }//end __construct()

    /**
     * addPrincipal
     *
     * @param mixed $principal The Principal to add
     *
     * @access public
     * @return void
     */
    public function addPrincipal($principal)
    {
        $this->_principals[] = $principal;

    }//end addPrincipal()

    /**
     * setPrincipals
     *
     * @param mixed $principals The principals to set
     *
     * @access public
     * @return void
     */
    public function setPrincipals($principals)
    {
        $this->_principals = $principals;

    }//end setPrincipals()

    /**
     * setCredentials
     *
     * @param mixed $credentials The credentials to set.
     *
     * @access public
     * @return void
     */
    public function setCredentials($credentials)
    {
        $this->_credentials = $credentials;

    }//end setCredentials()

    /**
     * getPrincipals
     *
     * @access public
     * @return void
     */
    public function getPrincipals()
    {
        return $this->_principals;

    }//end getPrincipals()

    /**
     * getCredentials
     *
     * @access public
     * @return void
     */
    public function getCredentials()
    {
        return $this->_credentials;

    }//end getCredentials()

}//end class

?>


text:
"""
modelviz.py - DOT file generator for Django Models

Based on:
  Django model to DOT (Graphviz) converter
  by Antonio Cavedoni <antonio@cavedoni.org>
  Adapted to be used with django-extensions
"""

import datetime
import os
import re

from django.apps import apps
from django.db.models import deletion
from django.db.models.fields.related import (
    ForeignKey, ManyToManyField, OneToOneField, RelatedField,
)
from django.db.models.fields.reverse_related import (
    OneToOneRel, ManyToOneRel,
)
from django.contrib.contenttypes.fields import GenericRelation
from django.template import Context, Template, loader
from django.utils.encoding import force_str
from django.utils.safestring import mark_safe
from django.utils.translation import activate as activate_language

__version__ = "1.1"
__license__ = "Python"
__author__ = "Bas van Oostveen <v.oostveen@gmail.com>",
__contributors__ = [
    "Antonio Cavedoni <http://cavedoni.com/>"
    "Stefano J. Attardi <http://attardi.org/>",
    "limodou <http://www.donews.net/limodou/>",
    "Carlo C8E Miron",
    "Andre Campos <cahenan@gmail.com>",
    "Justin Findlay <jfindlay@gmail.com>",
    "Alexander Houben <alexander@houben.ch>",
    "Joern Hees <gitdev@joernhees.de>",
    "Kevin Cherepski <cherepski@gmail.com>",
    "Jose Tomas Tocino <theom3ga@gmail.com>",
    "Adam Dobrawy <naczelnik@jawnosc.tk>",
    "Mikkel Munch Mortensen <https://www.detfalskested.dk/>",
    "Andrzej Bistram <andrzej.bistram@gmail.com>",
    "Daniel Lipsitt <danlipsitt@gmail.com>",
    "Tobias Mitterdorfer <tobias.mitterdorfer97@gmail.com>"
]

ON_DELETE_COLORS = {
    deletion.CASCADE: 'red',
    deletion.PROTECT: 'blue',
    deletion.SET_NULL: 'orange',
    deletion.SET_DEFAULT: 'green',
    deletion.SET: 'yellow',
    deletion.DO_NOTHING: 'grey',
    deletion.RESTRICT: 'purple',
}

def parse_file_or_list(arg):
    if not arg:
        return []
    if isinstance(arg, (list, tuple, set)):
        return arg
    if ',' not in arg and os.path.isfile(arg):
        return [e.strip() for e in open(arg).readlines()]
    return [e.strip() for e in arg.split(',')]

class ModelGraph:
    def __init__(self, app_labels, **kwargs):
        self.graphs = []
        self.cli_options = kwargs.get('cli_options', None)
        self.disable_fields = kwargs.get('disable_fields', False)
        self.disable_abstract_fields = kwargs.get('disable_abstract_fields', False)
        self.include_models = parse_file_or_list(
            kwargs.get('include_models', "")
        )
        self.all_applications = kwargs.get('all_applications', False)
        self.use_subgraph = kwargs.get('group_models', False)
        self.verbose_names = kwargs.get('verbose_names', False)
        self.inheritance = kwargs.get('inheritance', True)
        self.relations_as_fields = kwargs.get("relations_as_fields", True)
        self.relation_fields_only = kwargs.get("relation_fields_only", False)
        self.sort_fields = kwargs.get("sort_fields", True)
        self.language = kwargs.get('language', None)
        if self.language is not None:
            activate_language(self.language)
        self.exclude_columns = parse_file_or_list(
            kwargs.get('exclude_columns', "")
        )
        self.exclude_models = parse_file_or_list(
            kwargs.get('exclude_models', "")
        )
        self.hide_edge_labels = kwargs.get('hide_edge_labels', False)
        self.arrow_shape = kwargs.get("arrow_shape")
        self.color_code_deletions = kwargs.get("color_code_deletions", False)
        if self.all_applications:
            self.app_labels = [app.label for app in apps.get_app_configs()]
        else:
            self.app_labels = app_labels
        self.rankdir = kwargs.get("rankdir")

    def generate_graph_data(self):
        self.process_apps()

        nodes = []
        for graph in self.graphs:
            nodes.extend([e['name'] for e in graph['models']])

        for graph in self.graphs:
            for model in graph['models']:
                for relation in model['relations']:
                    if relation is not None:
                        if relation['target'] in nodes:
                            relation['needs_node'] = False

    def get_graph_data(self, as_json=False):
        now = datetime.datetime.now()
        graph_data = {
            'created_at': now.strftime("%Y-%m-%d %H:%M"),
            'cli_options': self.cli_options,
            'disable_fields': self.disable_fields,
            'disable_abstract_fields': self.disable_abstract_fields,
            'use_subgraph': self.use_subgraph,
            'rankdir': self.rankdir,
        }

        if as_json:
            # We need to remove the model and field class because it is not JSON serializable
            graphs = [context.flatten() for context in self.graphs]
            for context in graphs:
                for model_data in context['models']:
                    model_data.pop('model')
                    for field_data in model_data['fields']:
                        field_data.pop('field')
            graph_data['graphs'] = graphs
        else:
            graph_data['graphs'] = self.graphs

        return graph_data

    def add_attributes(self, field, abstract_fields):
        if self.verbose_names and field.verbose_name:
            label = force_str(field.verbose_name)
            if label.islower():
                label = label.capitalize()
        else:
            label = field.name

        t = type(field).__name__
        if isinstance(field, (OneToOneField, ForeignKey)):
            t += " ({0})".format(field.remote_field.field_name)
        # TODO: ManyToManyField, GenericRelation

        return {
            'field': field,
            'name': field.name,
            'label': label,
            'type': t,
            'blank': field.blank,
            'abstract': any(
                field.creation_counter == abstract_field.creation_counter
                for abstract_field in abstract_fields
            ),
            'relation': isinstance(field, RelatedField),
            'primary_key': field.primary_key,
        }

    def add_relation(self, field, model, extras="", color=None):
        if self.verbose_names and field.verbose_name:
            label = force_str(field.verbose_name)
            if label.islower():
                label = label.capitalize()
        else:
            label = field.name

        # show related field name
        if hasattr(field, 'related_query_name'):
            related_query_name = field.related_query_name()
            if self.verbose_names and related_query_name.islower():
                related_query_name = related_query_name.replace('_', ' ').capitalize()
            label = u'{} ({})'.format(label, force_str(related_query_name))
        if self.hide_edge_labels:
            label = ''

        # handle self-relationships and lazy-relationships
        if isinstance(field.remote_field.model, str):
            if field.remote_field.model == 'self':
                target_model = field.model
            else:
                if '.' in field.remote_field.model:
                    app_label, model_name = field.remote_field.model.split('.', 1)
                else:
                    app_label = field.model._meta.app_label
                    model_name = field.remote_field.model
                target_model = apps.get_model(app_label, model_name)
        else:
            target_model = field.remote_field.model

        if color:
            extras = '[{}, color={}]'.format(extras[1:-1], color)

        _rel = self.get_relation_context(target_model, field, label, extras)

        if _rel not in model['relations'] and self.use_model(_rel['target']):
            return _rel

    def get_abstract_models(self, appmodels):
        abstract_models = []
        for appmodel in appmodels:
            abstract_models += [
                abstract_model for abstract_model in appmodel.__bases__
                if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract
            ]
        abstract_models = list(set(abstract_models))  # remove duplicates
        return abstract_models

    def get_app_context(self, app):
        return Context({
            'name': '"%s"' % app.name,
            'app_name': "%s" % app.name,
            'cluster_app_name': "cluster_%s" % app.name.replace(".", "_"),
            'models': []
        })

    def get_appmodel_attributes(self, appmodel):
        if self.relations_as_fields:
            attributes = [field for field in appmodel._meta.local_fields]
        else:
            # Find all the 'real' attributes. Relations are depicted as graph edges instead of attributes
            attributes = [field for field in appmodel._meta.local_fields if not
                          isinstance(field, RelatedField)]
        return attributes

    def get_appmodel_abstracts(self, appmodel):
        return [
            abstract_model.__name__ for abstract_model in appmodel.__bases__
            if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract
        ]

    def get_appmodel_context(self, appmodel, appmodel_abstracts):
        context = {
            'model': appmodel,
            'app_name': appmodel.__module__.replace(".", "_"),
            'name': appmodel.__name__,
            'abstracts': appmodel_abstracts,
            'fields': [],
            'relations': []
        }

        if self.verbose_names and appmodel._meta.verbose_name:
            context['label'] = force_str(appmodel._meta.verbose_name)
        else:
            context['label'] = context['name']

        return context

    def get_bases_abstract_fields(self, c):
        _abstract_fields = []
        for e in c.__bases__:
            if hasattr(e, '_meta') and e._meta.abstract:
                _abstract_fields.extend(e._meta.fields)
                _abstract_fields.extend(self.get_bases_abstract_fields(e))
        return _abstract_fields

    def get_inheritance_context(self, appmodel, parent):
        label = "multi-table"
        if parent._meta.abstract:
            label = "abstract"
        if appmodel._meta.proxy:
            label = "proxy"
        label += r"\ninheritance"
        if self.hide_edge_labels:
            label = ''
        return {
            'target_app': parent.__module__.replace(".", "_"),
            'target': parent.__name__,
            'type': "inheritance",
            'name': "inheritance",
            'label': label,
            'arrows': '[arrowhead=empty, arrowtail=none, dir=both]',
            'needs_node': True,
        }

    def get_models(self, app):
        appmodels = list(app.get_models())
        return appmodels

    def get_relation_context(self, target_model, field, label, extras):
        return {
            'target_app': target_model.__module__.replace('.', '_'),
            'target': target_model.__name__,
            'type': type(field).__name__,
            'name': field.name,
            'label': label,
            'arrows': extras,
            'needs_node': True
        }

    def process_attributes(self, field, model, pk, abstract_fields):
        newmodel = model.copy()
        if self.skip_field(field) or pk and field == pk:
            return newmodel
        newmodel['fields'].append(self.add_attributes(field, abstract_fields))
        return newmodel

    def process_apps(self):
        for app_label in self.app_labels:
            app = apps.get_app_config(app_label)
            if not app:
                continue
            app_graph = self.get_app_context(app)
            app_models = self.get_models(app)
            abstract_models = self.get_abstract_models(app_models)
            app_models = abstract_models + app_models

            for appmodel in app_models:
                if not self.use_model(appmodel._meta.object_name):
                    continue
                appmodel_abstracts = self.get_appmodel_abstracts(appmodel)
                abstract_fields = self.get_bases_abstract_fields(appmodel)
                model = self.get_appmodel_context(appmodel, appmodel_abstracts)
                attributes = self.get_appmodel_attributes(appmodel)

                # find primary key and print it first, ignoring implicit id if other pk exists
                pk = appmodel._meta.pk
                if pk and not appmodel._meta.abstract and pk in attributes:
                    model['fields'].append(self.add_attributes(pk, abstract_fields))

                for field in attributes:
                    model = self.process_attributes(field, model, pk, abstract_fields)

                if self.sort_fields:
                    model = self.sort_model_fields(model)

                for field in appmodel._meta.local_fields:
                    model = self.process_local_fields(field, model, abstract_fields)

                for field in appmodel._meta.local_many_to_many:
                    model = self.process_local_many_to_many(field, model)

                if self.inheritance:
                    # add inheritance arrows
                    for parent in appmodel.__bases__:
                        model = self.process_parent(parent, appmodel, model)

                app_graph['models'].append(model)
            if app_graph['models']:
                self.graphs.append(app_graph)

    def process_local_fields(self, field, model, abstract_fields):
        newmodel = model.copy()
        if field.attname.endswith('_ptr_id') or field in abstract_fields or self.skip_field(field):
            # excluding field redundant with inheritance relation
            # excluding fields inherited from abstract classes. they too show as local_fields
            return newmodel

        color = None
        if self.color_code_deletions and isinstance(field, (OneToOneField, ForeignKey)):
            field_on_delete = getattr(field.remote_field, 'on_delete', None)
            color = ON_DELETE_COLORS.get(field_on_delete)

        if isinstance(field, OneToOneField):
            relation = self.add_relation(
                field, newmodel, '[arrowhead=none, arrowtail=none, dir=both]', color
            )
        elif isinstance(field, ForeignKey):
            relation = self.add_relation(
                field,
                newmodel,
                '[arrowhead=none, arrowtail={}, dir=both]'.format(
                    self.arrow_shape
                ),
                color
            )
        else:
            relation = None
        if relation is not None:
            newmodel['relations'].append(relation)
        return newmodel

    def process_local_many_to_many(self, field, model):
        newmodel = model.copy()
        if self.skip_field(field):
            return newmodel
        relation = None
        if isinstance(field, ManyToManyField):
            if hasattr(field.remote_field.through, '_meta') and field.remote_field.through._meta.auto_created:
                relation = self.add_relation(
                    field,
                    newmodel,
                    '[arrowhead={} arrowtail={}, dir=both]'.format(
                        self.arrow_shape, self.arrow_shape
                    ),
                )
        elif isinstance(field, GenericRelation):
            relation = self.add_relation(field, newmodel, mark_safe('[style="dotted", arrowhead=normal, arrowtail=normal, dir=both]'))
        if relation is not None:
            newmodel['relations'].append(relation)
        return newmodel

    def process_parent(self, parent, appmodel, model):
        newmodel = model.copy()
        if hasattr(parent, "_meta"):  # parent is a model
            _rel = self.get_inheritance_context(appmodel, parent)
            # TODO: seems as if abstract models aren't part of models.getModels, which is why they are printed by this without any attributes.
            if _rel not in newmodel['relations'] and self.use_model(_rel['target']):
                newmodel['relations'].append(_rel)
        return newmodel

    def sort_model_fields(self, model):
        newmodel = model.copy()
        newmodel['fields'] = sorted(newmodel['fields'], key=lambda field: (not field['primary_key'], not field['relation'], field['label']))
        return newmodel

    def use_model(self, model_name):
        """
        Decide whether to use a model, based on the model name and the lists of
        models to exclude and include.
        """
        # Check against include list.
        if self.include_models:
            for model_pattern in self.include_models:
                model_pattern = '^%s$' % model_pattern.replace('*', '.*')
                if re.search(model_pattern, model_name):
                    return True
        # Check against exclude list.
        if self.exclude_models:
            for model_pattern in self.exclude_models:
                model_pattern = '^%s$' % model_pattern.replace('*', '.*')
                if re.search(model_pattern, model_name):
                    return False
        # Return `True` if `include_models` is falsey, otherwise return `False`.
        return not self.include_models

    def skip_field(self, field):
        if self.exclude_columns:
            if self.verbose_names and field.verbose_name:
                if field.verbose_name in self.exclude_columns:
                    return True
            if field.name in self.exclude_columns:
                return True
        if self.relation_fields_only:
            if not isinstance(
                field,
                (ForeignKey, ManyToManyField, OneToOneField, RelatedField, OneToOneRel, ManyToOneRel)
            ):
                return True
        return False

def generate_dot(graph_data, template='django_extensions/graph_models/digraph.dot'):
    if isinstance(template, str):
        template = loader.get_template(template)

    if not isinstance(template, Template) and not (hasattr(template, 'template') and isinstance(template.template, Template)):
        raise Exception("Default Django template loader isn't used. "
                        "This can lead to the incorrect template rendering. "
                        "Please, check the settings.")

    c = Context(graph_data).flatten()
    dot = template.render(c)

    return dot

def generate_graph_data(*args, **kwargs):
    generator = ModelGraph(*args, **kwargs)
    generator.generate_graph_data()
    return generator.get_graph_data()

def use_model(model, include_models, exclude_models):
    generator = ModelGraph([], include_models=include_models, exclude_models=exclude_models)
    return generator.use_model(model)


text:
date: "2012-09-28 11:47:00 UTC"
published: true
title: "RSpec Sitemap matchers for your SEO goodness"
authors:
  - "Attila Gyorffy"
tags:
  - Rails
---

Not that long ago we [released our new website at Unboxed](http://www.unboxedconsulting.com). We took the time to carefully think about how our new site was going to be structured, how our URIs were going to look. We introduced new pages and deprecated or merged others.

Needless to say that we also had to rework our URL structure, our unique URIs, etc. In order not to lose our previous SEO scores and to make sure Google will pick the new URIs up as quickly as possible, we made use of the [Sitemap protocol](http://www.sitemaps.org/protocol.html).

A sitemap is essentially nothing more than an XML file in your domain's root that helps informing search engines about the available pages on your site for crawling. This data is then processed by search giants like [Google](http://google.com), [Yahoo!](http://search.yahoo.com/) or even Microsoft's [Bing](http://www.bing.com/).

Let me pull in the description from the official sitemap domain:

"In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site".

We took a TDD approach to drive out our method to generate our sitemap dynamically. Our sitemap incorporates our main pages, such as the homepage, case studies and many more. Go on, have a look at [it](http://www.unboxedconsulting.com/sitemap.xml) yourself.

Now, in order to not need to fiddle around much with Nokogiri  when testing our sitemap's XML data, I felt the need of a simpler way to write my tests in RSpec.

The end result is a new gem that can help you write meaningful and more semantic code when you are testing your sitemaps:

[http://rubygems.org/gems/rspec-sitemap-matchers](http://rubygems.org/gems/rspec-sitemap-matchers)

```
it { should include_url('http://www.example.com').priority(0.5) }
```

The project is not fully feature complete but is already usable and it is under development. Please see the documentation on the project's [github page](https://github.com/unboxed/rspec-sitemap-matchers), fork, write tests and contribute with code.


text:
require 'spec_helper'

describe Docks::Processors::JoinWithBlanks do
  subject { Docks::Processors::JoinWithBlanks }

  it 'correctly joins an array with blanks' do
    array = %w(one two three)
    expect(subject.process(array)).to eq array.join('')
  end

  it 'correctly returns a non-array argument' do
    non_array = "I'm not an array!"
    expect(subject.process(non_array)).to eq non_array
  end

  it 'correctly returns nil for an empty array' do
    expect(subject.process([])).to be nil
  end

  it 'correctly returns nil for an array containing only whitespace strings' do
    expect(subject.process([' '])).to be nil
    expect(subject.process([' ', '   '])).to be nil
  end
end


text:
namespace sieve
{

ASTSieve::ASTSieve( yy::location location )
    : ASTNode( location )
{
}

void ASTSieve::accept( ASTVisitor &visitor ) {
    visitor.visit(this);
}

} // namespace sieve


text:
package org.asteriskjava.manager.action;

/**
 * The MeetMeUnmuteAction unmutes a user in a conference.

 * Defined in apps/app_meetme.c

 * Available since Asterisk 1.4.
 *
 * @author srt
 * @version $Id$
 */
public class MeetMeUnmuteAction extends AbstractMeetMeMuteAction
{
    /**
     * Serializable version identifier
     */
    private static final long serialVersionUID = -3843949939190283779L;

    /**
     * Creates a new empty MeetMeUnmuteAction.
     */
    public MeetMeUnmuteAction()
    {
        super();
    }

    /**
     * Creates a new MeetMeUnmuteAction.
     *
     * @param meetMe the conference number.
     * @param userNum the index of the user in the conference.
     */
    public MeetMeUnmuteAction(String meetMe, Integer userNum)
    {
        super(meetMe, userNum);
    }

    /**
     * Returns the name of this action, i.e. "MeetMeUnmute".
     */
    @Override
   public String getAction()
    {
        return "MeetMeUnmute";
    }
}


text:
import sys
import paddle.v2 as paddle

def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
    data = paddle.layer.data("word",
                             paddle.data_type.integer_value_sequence(input_dim))
    emb = paddle.layer.embedding(input=data, size=emb_dim)
    conv_3 = paddle.networks.sequence_conv_pool(
        input=emb, context_len=3, hidden_size=hid_dim)
    conv_4 = paddle.networks.sequence_conv_pool(
        input=emb, context_len=4, hidden_size=hid_dim)
    output = paddle.layer.fc(input=[conv_3, conv_4],
                             size=class_dim,
                             act=paddle.activation.Softmax())
    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
    return cost

def stacked_lstm_net(input_dim,
                     class_dim=2,
                     emb_dim=128,
                     hid_dim=512,
                     stacked_num=3):
    """
    A Wrapper for sentiment classification task.
    This network uses bi-directional recurrent network,
    consisting three LSTM layers. This configure is referred to
    the paper as following url, but use fewer layrs.
        http://www.aclweb.org/anthology/P15-1109

    input_dim: here is word dictionary dimension.
    class_dim: number of categories.
    emb_dim: dimension of word embedding.
    hid_dim: dimension of hidden layer.
    stacked_num: number of stacked lstm-hidden layer.
    """
    assert stacked_num % 2 == 1

    layer_attr = paddle.attr.Extra(drop_rate=0.5)
    fc_para_attr = paddle.attr.Param(learning_rate=1e-3)
    lstm_para_attr = paddle.attr.Param(initial_std=0., learning_rate=1.)
    para_attr = [fc_para_attr, lstm_para_attr]
    bias_attr = paddle.attr.Param(initial_std=0., l2_rate=0.)
    relu = paddle.activation.Relu()
    linear = paddle.activation.Linear()

    data = paddle.layer.data("word",
                             paddle.data_type.integer_value_sequence(input_dim))
    emb = paddle.layer.embedding(input=data, size=emb_dim)

    fc1 = paddle.layer.fc(input=emb,
                          size=hid_dim,
                          act=linear,
                          bias_attr=bias_attr)
    lstm1 = paddle.layer.lstmemory(
        input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)

    inputs = [fc1, lstm1]
    for i in range(2, stacked_num + 1):
        fc = paddle.layer.fc(input=inputs,
                             size=hid_dim,
                             act=linear,
                             param_attr=para_attr,
                             bias_attr=bias_attr)
        lstm = paddle.layer.lstmemory(
            input=fc,
            reverse=(i % 2) == 0,
            act=relu,
            bias_attr=bias_attr,
            layer_attr=layer_attr)
        inputs = [fc, lstm]

    fc_last = paddle.layer.pooling(
        input=inputs[0], pooling_type=paddle.pooling.Max())
    lstm_last = paddle.layer.pooling(
        input=inputs[1], pooling_type=paddle.pooling.Max())
    output = paddle.layer.fc(input=[fc_last, lstm_last],
                             size=class_dim,
                             act=paddle.activation.Softmax(),
                             bias_attr=bias_attr,
                             param_attr=para_attr)

    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
    return cost

if __name__ == '__main__':
    # init
    paddle.init(use_gpu=False)

    #data
    print 'load dictionary...'
    word_dict = paddle.dataset.imdb.word_dict()
    dict_dim = len(word_dict)
    class_dim = 2
    train_reader = paddle.batch(
        paddle.reader.shuffle(
            lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
        batch_size=100)
    test_reader = paddle.batch(
        lambda: paddle.dataset.imdb.test(word_dict), batch_size=100)

    feeding = {'word': 0, 'label': 1}

    # network config
    # Please choose the way to build the network
    # by uncommenting the corresponding line.
    cost = convolution_net(dict_dim, class_dim=class_dim)
    # cost = stacked_lstm_net(dict_dim, class_dim=class_dim, stacked_num=3)

    # create parameters
    parameters = paddle.parameters.create(cost)

    # create optimizer
    adam_optimizer = paddle.optimizer.Adam(
        learning_rate=2e-3,
        regularization=paddle.optimizer.L2Regularization(rate=8e-4),
        model_average=paddle.optimizer.ModelAverage(average_window=0.5))

    # End batch and end pass event handler
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 100 == 0:
                print "\nPass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics)
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
        if isinstance(event, paddle.event.EndPass):
            result = trainer.test(reader=test_reader, feeding=feeding)
            print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

    # create trainer
    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=adam_optimizer)

    trainer.train(
        reader=train_reader,
        event_handler=event_handler,
        feeding=feeding,
        num_passes=2)


text:
package jp.pgw.develop.swallow.example.web.servlet.support;

import org.springframework.core.annotation.Order;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import java.util.EnumSet;

/**
 * Created by kazamage on 2015/06/28.
 */
@Order(1)
public class WebSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    /**
     * {@inheritDoc}
     */
    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
        super.beforeSpringSecurityFilterChain(servletContext);
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
        registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC), false, "/*");
    }

}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>

<!--Parts from the iGEM Registry of Standard Biological Parts-->
<rsbpml>
<part_list>
<part>
<part_id>4968</part_id>
<part_name>BBa_I14017</part_name>
<part_short_name>I14017</part_short_name>
<part_short_desc>P(Rhl)</part_short_desc>
<part_type>Regulatory</part_type>
<release_status>Released HQ 2013</release_status>
<sample_status>In stock</sample_status>
<part_results>None</part_results>
<part_nickname>RhI</part_nickname>
<part_rating>1</part_rating>
<part_url>http://parts.igem.org/Part:BBa_I14017</part_url>
<part_entered>2004-08-02</part_entered>
<part_author>Vikram Vijayan, Allen Hsu, Lawrence Fomundam</part_author>
<deep_subparts></deep_subparts>
<specified_subparts></specified_subparts>
<specified_subscars></specified_subscars>
<sequences>
<seq_data>tcctgcatgaattggtaggcttacgcaagaaaatggtttgttatagtcgaa
</seq_data></sequences>
<features>
<feature>
<id>1043006</id>
<title>modified P(Rhl)</title>
<type>operator</type>
<direction>forward</direction>
<startpos>1</startpos>
<endpos>51</endpos></feature>
<feature>
<id>1043005</id>
<title>RhlR</title>
<type>binding</type>
<direction>forward</direction>
<startpos>1</startpos>
<endpos>20</endpos></feature>
<feature>
<id>1043007</id>
<title>-35</title>
<type>promoter</type>
<direction>forward</direction>
<startpos>21</startpos>
<endpos>50</endpos></feature></features>
<parameters>
<!-- NOTE: Currently, each parameter name can have only one value.-->
<!--This will change as we fully support the context of a parameter. RDR 4/2010 -->
<parameter>
<name>negative_regulators</name>
<value>NA</value>
<units></units>
<url></url>
<id>5477</id>
<m_date>2008-12-09 15:47:12</m_date>
<user_id>135</user_id>
<user_name>bcanton</user_name></parameter>
<parameter>
<name>positive_regulators</name>
<value>1</value>
<units></units>
<url></url>
<id>4945</id>
<m_date>2008-12-09 15:46:49</m_date>
<user_id>135</user_id>
<user_name>bcanton</user_name></parameter></parameters>
<categories>
<category>//rnap/prokaryote/ecoli/sigma70</category>
<category>//direction/forward</category>
<category>//chassis/prokaryote/ecoli</category>
<category>//promoter</category>
<category>//regulation/positive</category>
<category>//classic/regulatory/uncategorized</category>
<category>//function/cellsignalling/RhlR</category></categories>
<twins>
<twin>BBa_J06403</twin></twins>
<samples>
<!--Samples have been turned off for now - rdr 2013--></samples>
<references>
<!--References are not available yet - rdr 2013--></references>
<groups>
<!-- Group access information is not yet available - rdr 2013--></groups></part></part_list></rsbpml>


text:
package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"gopkg.in/yaml.v2"
)

var (
	errConfigNil       = errors.New("config nil")
	errConfigRunNotSet = errors.New("config run not set")
)

type config struct {
	RequiredEnvVars []string     `json:"required_env_vars,omitempty" yaml:"required_env_vars,omitempty"`
	Run             []*cmdConfig `json:"run,omitempty" yaml:"run,omitempty"`
}

type cmdConfig struct {
	Command string `json:"command,omitempty" yaml:"command,omitempty"`
	SleepMs int    `json:"sleep_ms,omitempty" yaml:"sleep_ms,omitempty"`
	Input   string `json:"input,omitempty" yaml:"input,omitempty"`
	Output  string `json:"output,omitempty" yaml:"output,omitempty"`
}

func newConfig(configFilePath string) (*config, error) {
	data, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}
	config := &config{}
	if err := yaml.Unmarshal(data, config); err != nil {
		return nil, err
	}
	if err := config.validate(); err != nil {
		return nil, err
	}
	return config, nil
}

func (c *config) Cmds(dir string, debug bool) ([]*cmd, error) {
	cmds := make([]*cmd, 0, len(c.Run))
	for _, cmdConfig := range c.Run {
		cmd, err := newCmd(cmdConfig, dir, debug)
		if err != nil {
			return nil, err
		}
		cmds = append(cmds, cmd)
	}
	return cmds, nil
}

func (c *config) validate() error {
	if c == nil {
		return errConfigNil
	}
	if len(c.Run) == 0 {
		return errConfigRunNotSet
	}
	for _, requiredEnvVar := range c.RequiredEnvVars {
		if os.Getenv(requiredEnvVar) == "" {
			return fmt.Errorf("environment variable %s must be set", requiredEnvVar)
		}
	}
	return nil
}


text:
/*
 * @author: mwenbao@gmail.com
 * @license: see LICENSE.txt
 * @depend: jquery 1.10+
 * @issues: Chrome39 behaves weird when showing/hiding fixed sidebar toc list.
 *          Search `@TODO check Chrome39+' for detailed comments on this problem.
 *
 */

// set theme path, got from http://stackoverflow.com/questions/8523200/javascript-get-current-filescript-path
(function() {
    var scriptEls = document.getElementsByTagName('script');
    var thisScriptEl = scriptEls[scriptEls.length - 1];
    var scriptPath = thisScriptEl.src;
    window.gThemePath = scriptPath.substr(0, scriptPath.lastIndexOf('/js/'));
})();

window.gEnableTocStatusUpdate = true;
window.gEnableTocListAutoScroll = true;
window.gMouseInSidebarTocList = false;
window.gToolbarHidden = true;
window.gToolbarAnimationEnabled = true;
window.gFixedHeaderHeight = 32;
window.gFixedTocListOffsetTop = 111;
window.gFootnotePopoverMaxWidth = 300;
window.gAutoScrollDuration = 400;
window.gActiveTocClass = 'niu2-active-toc';
window.gCurrHighlightedElem = null;
window.gCurrHighlightedBackref = null;
window.gCurrTocId = '';
window.gSidebarCtrlButtonEnabled = true;
window.gMousePositionX = 0;
window.gMousePositionY = 0;

$(document).ready(function() {
    initGoogleCSEAnimation();
});

function onContentLoaded() {
    initPygments();
    initHermitPlayer();
    initLazyLoad();
    initFootnote();
    initHeaderAnchors();
    $(window).scroll(function() {
        toggleSidebarTocFixed();
        locateTocInViewport();
    });
    //window.setInterval(updateFootnoteStatus, 500);
    updateFootnoteStatus();

    // detach toc list before inserting many
    // toc index , for performance reason
    getTocList().detach();
    initTocListIndex(getTocList());
    getTocList().appendTo(getSidebarToc());

    setSidebarTocSize();
    setTocOverflowedTitle();

    initTocLinkScrollAnimation();
    initAllTocsCtrl();
    locateTocInViewport();

    initToolbar();
}

function initPygments() {
    if ($('pre')[0]) {
        appendCssFileToHead('/css/pygments.min/' + $('#niu2-pygments').data('theme') + '.min.css');
    }
}

function initHermitPlayer() {
    if ($('.hermit')[0]) {
        appendCssFileToHead('/hermit/assets/style/hermit.min.css');
        window.hermit = {
            'url': window.gThemePath + '/soundmanager2/swf'
            //'debugMode': true,
            //'debugFlash': true,
            //'flashVersion': 9,
            //'preferFlash': true
        }; // hermit should be global
        appendJsFileToBody('/soundmanager2/script/soundmanager2.min.js');
        appendJsFileToBody('/hermit/assets/script/hermit.min.js');
    }
}

function initToolbar() {
    if (getToolbar()) {
        var rightContainers = $('.niu2-right-container');
        var showSidebarTitle = $('#niu2-toolbar-showsidebar').data('title');
        var hideSidebarTitle = $('#niu2-toolbar-ctrlsidebar').attr('title');

        var docPath = window.location.pathname.replace(/html$/, 'md');
        if (-1 == docPath.replace(/^\//, '').search('/')) {
            // is a page
            docPath = '/pages' + docPath;
        }

        // init raw link and revision link
        var githubRepo = $('#niu2-toolbar-github').data('repo').replace(/\/+$/g, '');
        var bitbucketRepo = $('#niu2-toolbar-bitbucket').data('repo').replace(/\/+$/g, '');
        if ('' != githubRepo) {
            // a github repository
            $('#niu2-toolbar-revhistory').attr('href', 'https://github.com/' + githubRepo + '/commits/master/content' + docPath);
            $('#niu2-toolbar-viewsource').attr('href', 'https://raw.githubusercontent.com/' + githubRepo + '/master/content' + docPath);
        } else if ('' != bitbucketRepo) {
            // a bitbucket repository
            $('#niu2-toolbar-revhistory').attr('href', 'https://bitbucket.org/' + bitbucketRepo + '/history-node/master/content' + docPath);
            $('#niu2-toolbar-viewsource').attr('href', 'https://bitbucket.org/' + bitbucketRepo + '/raw/master/content' + docPath);
        }

        // init load-pic overly
        $('

').appendTo('body');

        var leftContainer = $('#niu2-left-container');
        var footer = $('#body-footer');
        var ctrlIcon = $('#niu2-toolbar-ctrlsidebar i');
        var ctrlSidebar = $('#niu2-toolbar-ctrlsidebar');
        var leftCSlideDuration = 300;
        var loadingOverly = $('#niu2-loading-overly');

        // init sidebar controller
        window.gSidebarCtrlButtonColor = $('#niu2-toolbar-ctrlsidebar').css('color');
        $('#niu2-toolbar-ctrlsidebar').click(function(e) {
            e.preventDefault();
            if (!window.gSidebarCtrlButtonEnabled) {
                return;
            }
            loadingOverly.show();
            disableSidebarCtrlButton();
            if (!rightContainers.is(':hidden')) {
                markVerticalPosition();
                rightContainers.fadeOut('fast');
                leftContainer.removeClass('with-right-border');
                leftContainer.animate({width: '65%'}, leftCSlideDuration, complete=function() {
                    restoreVerticalPosition(function() {
                        enableSidebarCtrlButton();
                        ctrlIcon.attr('class', 'fa fa-3x fa-chevron-circle-left');
                        ctrlSidebar.attr('title', showSidebarTitle);
                        loadingOverly.hide();
                    });
                });
                footer.animate({width: '50%'}, leftCSlideDuration);
            } else {
                markVerticalPosition();
                leftContainer.animate({width: '50%'}, leftCSlideDuration, complete=function() {
                    var sidebarElems = $('.niu2-right-container');
                    var sidebarParent = sidebarElems.parent();
                    // @TODO: check Chrome39+
                    // We have to detach fixed sidebar before doing the fadein animation,
                    // otherwise Chrome39 will behave weird(showing duplicate sidebar toc).
                    sidebarElems.detach();
                    leftContainer.addClass('with-right-border');
                    window.gEnableTocStatusUpdate = false;
                    rightContainers.fadeIn('fast', complete=function() {
                        sidebarElems.appendTo(sidebarParent);
                        toggleSidebarTocFixed();
                    });
                    restoreVerticalPosition(function() {
                        enableSidebarCtrlButton();
                        ctrlIcon.attr('class', 'fa fa-3x fa-chevron-circle-right');
                        ctrlSidebar.attr('title', hideSidebarTitle);
                        window.gEnableTocStatusUpdate = true;
                        locateTocInViewport();
                        loadingOverly.hide();
                    });
                });
                footer.animate({width: '50%'}, leftCSlideDuration);
            }
            // must reset cached objects of footnote refs and backrefs
            resetFootnoteRefs();
            resetFootnoteBackRefs();
            resetFootnoteRefMap();
        });
    }
}

function initLazyLoad() {
    var imageNodes = $('#niu2-main-content img.lazy');
    if (0 != imageNodes.length && $('#niu2-lazy-load-text')[0]) {
        // add lazyload js file
        appendJsFileToBody('/js/jquery.lazyload.min.js');
        // add colorbox js/css file
        appendCssFileToHead('/colorbox/colorbox.min.css');
        appendJsFileToBody('/colorbox/jquery.colorbox.min.js');
        // find all the images and prepare for lazyload.js
        var imgWidthLimit = getMainContent().getBoundingClientRect().width;
        var imgHoverText = $('#niu2-lazy-load-text').data('loading');
        imageNodes.each(function(i, elem) {
            var imgRealWidth = parseInt($(elem).data('width'));
            var imgRealHeight = parseInt($(elem).data('height'));
            var imgHeightLimit = (imgRealWidth > imgWidthLimit) ? (imgWidthLimit / imgRealWidth * imgRealHeight) : imgRealHeight;
            imgHeightLimit = imgHeightLimit.toFixed();
            $(elem).attr('height',  imgHeightLimit + 'px');
            // show loading text
            $(elem).parent().addClass('image-cover-box');
            var imgCover = $('' + imgHoverText + '').insertAfter($(elem));
            imgCover.css('top', ((imgHeightLimit - imgCover.height()) / 2 - 3) + 'px');
            imgCover.css('width', (imgWidthLimit > imgRealWidth ? imgRealWidth : imgWidthLimit) + 'px');
        });
        // enable lazy load
        imageNodes.lazyload({
            threshold : 0,
            effect : 'fadeIn',
            load: function() {
                var img = $(this);
                var imgOverly = img.next('.image-cover');
                var par = img.parent();
                // before detaching the img node, we should reserve
                // the image's vertical space for its parent node
                par.css('height', img.css('height'));
                img.detach();
                // reset height after image loaded
                img.css('height', 'auto');
                img.attr('height', '');
                // remove hover text
                par.removeClass('image-cover-box');
                imgOverly.hide();
                // init colorbox
                var imageLink = $('');
                img.appendTo(imageLink);
                imageLink.colorbox({
                    href: img.attr('src'),
                    returnFocus: false,
                    scalePhotos: true,
                    maxWidth: '95%',
                    maxHeight: '100%',
                });
                imageLink.appendTo(par);
                // reset parent node's height
                par.css('height', 'auto');
            }
        });
    }
}

function appendCssFileToHead(path) {
    $('<link rel="stylesheet" href="' + window.gThemePath + path + '" type="text/css"/>').appendTo($('head'));
}

function appendJsFileToBody(path) {
    $('').appendTo($('body'));
}

function initHeaderAnchors() {
    getMainContentHeaders().each(function(i, elem) {
        $('¶').appendTo($(elem));
    });
    initHeaderScrollAnimation(getMainContentHeaders().children('.niu2-header-anchor'));
}

function getMainContentHeaders() {
    if (window.gMainContentHeaders == undefined) {
        window.gMainContentHeaders = $('#niu2-main-content').find(':header');
    }
    return window.gMainContentHeaders;
}

function setSidebarTocSize() {
    getSidebarToc().attr('style', 'max-width:' + getSidebarToc().width() + 'px;');
}

function resetSidebarToc() {
    var sidebarToc = $('#niu2-sidebar-toc');
}

function toggleSidebarTocFixed() {
    var sidebarToc = $('#niu2-sidebar-toc');
    var sidebarMeta = $('#niu2-sidebar-meta');
    if (sidebarToc.length == 0 || sidebarMeta.length == 0) {
        return;
    }
    var vtop = $(window).scrollTop();
    var vpos = sidebarMeta.offset().top + sidebarMeta.height() - 55;
    if (!sidebarToc.is(':hidden') && vtop > vpos && 'niu2-sidebar' == sidebarToc.attr('class')) {
        var sidebarParent = sidebarToc.parent();
        // @TODO: check Chrome39+
        // We have to detach sidebar toc before setting its position to fixed,
        // otherwise Chrome39 will behave weird(showing duplicate sidebar toc).
        sidebarToc.detach();
        sidebarToc.attr('class', 'niu2-sidebar niu2-sidebar-toc-fixed');
        sidebarToc.appendTo(sidebarParent);
    } else if (vtop <= vpos && 'niu2-sidebar' != sidebarToc.attr('class')) {
        sidebarToc.attr('class', 'niu2-sidebar');
    }
}

// toggle the google cse input box
function showCSE() {
    if (!$("#niu2-cse-search-input").is(":visible")) {
        $("#niu2-cse-search-input").val("");
        $("#niu2-cse-search-input").show(300, function() {
            $("#niu2-cse-search-input").focus();
        });
        $("#niu2-cse-search-image").hide(300);
    }
}

function hideCSE() {
    if ($("#niu2-cse-search-input").is(":visible")) {
        $("#niu2-cse-search-input").hide(300);
        $("#niu2-cse-search-image").show(300);
    }
}

function disableSidebarCtrlButton() {
    window.gSidebarCtrlButtonEnabled = false;
    $('#niu2-toolbar-ctrlsidebar').attr('style', 'color: ' + window.gSidebarCtrlButtonColor);
}

function enableSidebarCtrlButton() {
    window.gSidebarCtrlButtonEnabled = true;
    $('#niu2-toolbar-ctrlsidebar').attr('style', '');
}

function markVerticalPosition() {
    window.gCurrElemInViewport = null;
    var currTocElem = $('#' + window.gCurrTocId);
    if (currTocElem[0].getBoundingClientRect().top == 0) {
        window.gCurrElemInViewport = currTocElem;
        window.gCurrElemTopInViewport = 0;
        return;
    }
    var followingElems;
    if (window.gCurrTocId == 'content-heading') {
        followingElems = $('#niu2-main-content').children();
    } else if (window.gCurrTocId == 'content-comments') {
        // only support duoshuo comment service for now
        var duoshuoMain = $('#ds-reset');
        if (duoshuoMain.length == 0) {
            return;
        }
        followingElems = duoshuoMain.children().first().nextUntil('.ds-comments').andSelf().add('.ds-comments');
    } else {
        followingElems = currTocElem.nextAll();
    }
    var numFollowingElems = followingElems.length;
    followingElems.each(function(i, e) {
        var currSib = $(e);
        var currSibTop = e.getBoundingClientRect().top;
        if (currSibTop > 0) {
            window.gCurrElemInViewport = currSib.prev();
            if (window.gCurrElemInViewport.length == 0) {
                window.gCurrElemInViewport = null;
                return false;
            }
            window.gCurrElemHeightInViewport = window.gCurrElemInViewport.height();
            window.gCurrElemTopInViewport = window.gCurrElemInViewport[0].getBoundingClientRect().top;
            return false;
        }
        if (i + 1 == numFollowingElems) {
            window.gCurrElemInViewport = currSib;
            window.gCurrElemHeightInViewport = window.gCurrElemInViewport.height();
            window.gCurrElemTopInViewport = window.gCurrElemInViewport[0].getBoundingClientRect().top;
        }
    });
}

function restoreVerticalPosition(complete) {
    if (window.gCurrElemInViewport == null) {
        complete();
        return;
    }
    var currElemTop = 0;
    if (window.gCurrElemTopInViewport != 0) {
        var currElemHeight = window.gCurrElemInViewport.height();
        currElemTop = currElemHeight / window.gCurrElemHeightInViewport * -1 * window.gCurrElemTopInViewport;
    }
    currElemScrollTop = currElemTop + window.gCurrElemInViewport.offset().top;
    window.gEnableTocListAutoScroll = false;
    $('body, html').animate(
        { scrollTop: currElemScrollTop },
        window.gAutoScrollDuration,
        function() { window.gEnableTocListAutoScroll = true; complete(); }
    );
}

function setTocOverflowedTitle() {
    getSidebarTocLinks().each(function(i, e) {
        $(e).mouseenter(function() {
            var currLink = $(this);
            if (isOverflowed(this) && !currLink.attr('title')) {
                currLink.attr('title', currLink.text());
            }
        });
    });
}

function isOverflowed(elem) {
    if (elem.scrollHeight > elem.offsetHeight || elem.scrollWidth > elem.offsetWidth) {
        return true;
    }
    return false;
}

function toggleTopIcon() {
    $(this).children(":first").toggleClass("niu2-top-icon-hidden");
}

function initGoogleCSEAnimation() {
    $("#niu2-cse-ctrl-box").click(showCSE);
    $("#niu2-cse-ctrl-box").focus(showCSE);
    $("#niu2-cse-search-input").hide();
    $("#niu2-cse-search-input").focusout(hideCSE);
    $(document).keyup(function(e) {
        e = e || window.event;
        if (e.keyCode == 27) {
            hideCSE();
        }
    });
}

function getToolbar() {
    if (!window.gToolbar) {
        window.gToolbar = $('#niu2-toolbar')[0];
    }
    return window.gToolbar;
}

function getMainContent() {
    if (!window.gMainContent) {
        window.gMainContent = $('#niu2-main-content')[0];
    }
    return window.gMainContent;
}

function getHtmlHeaders() {
    if (!window.gHtmlHeaders) {
        window.gHtmlHeaders = $(':header');

        if (getFootnoteRefs().length > 0) {
            window.gHtmlHeaders.push($('#content-references')[0]);
        }

        var commentsNode = $('#content-comments')[0];
        if (commentsNode) {
            window.gHtmlHeaders.push(commentsNode);
        }
    }
    return window.gHtmlHeaders;
}

function locateTocInViewport() {
    if (!window.gEnableTocStatusUpdate) {
        return;
    }
    var headerList = getHtmlHeaders();
    var currTocId;
    for (var i = 0; i < headerList.length; i++) {
        var elem = headerList[i];
        if (elem.getBoundingClientRect().top >= window.gFixedHeaderHeight) {
            if (i > 0) {
                elem = headerList[i - 1];
            }
            currTocId = elem.id;
            break;
        }
    }
    if (!currTocId) {
        currTocId = headerList.last().attr('id');
    }

    window.gCurrTocId = currTocId;
    resetTocListHeight();
    updateTocLinkStatus(currTocId);
    autoscrollTocList();
}

function getSidebarTocLinks() {
    if (!window.gSidebarTocLinks) {
        window.gSidebarTocLinks = $('#niu2-sidebar-toc-list a');
    }
    return window.gSidebarTocLinks;
}

function getSidebarToc() {
    if (!window.gSidebarToc) {
        window.gSidebarToc = $('#niu2-sidebar-toc');
    }
    return window.gSidebarToc;
}

function getTocList() {
    if (!window.gTocList) {
        window.gTocList = $('#niu2-sidebar-toc-list');
    }
    return window.gTocList;
}

function initTocListIndex(list, baseIndex) {
    if (baseIndex && '' != baseIndex) {
        baseIndex += '.';
    } else {
        baseIndex = '';
    }

    // iterate on list
    list.children().each(function(i, e) {
        var li = $(e);
        // prepend a index span in front of each  of

        var liIndex = baseIndex + (i + 1);
        li.prepend('' + liIndex + '.');

        // recursion on child list
        var subLiChildren = li.children();
        if (2 < subLiChildren.length) {
            initTocListIndex($(subLiChildren[2]), liIndex);
        }
    });
}

function unhighlightActiveToc() {
    var activeToc = $('.' + window.gActiveTocClass).first();
    if (activeToc.length != 0) {
        activeToc.attr('class', '');
    }
}

function updateTocLinkStatus(anchor) {
    if (isAllTocsClosed()) {
        closeAllTocs();
    }
    getSidebarTocLinks().each(function(li, lelem) {
        var cLink = $(lelem);
        if (anchor == cLink.attr('href').substr(cLink.attr('href').indexOf('#') + 1)) {
            cLink.attr('class', window.gActiveTocClass);
            if (isAllTocsClosed()) {
                openActiveTocList(cLink.parent());
            }
        } else if ('' != cLink.attr('class')) {
            cLink.attr('class', '');
        }
    });
}

function resetTocListHeight() {
    var tocListHeight = $(window).height() - window.gFixedTocListOffsetTop + 20;
    if (getTocList().height() >= tocListHeight) {
        getTocList().attr('style', 'height: ' + tocListHeight + 'px;');
    } else {
        getTocList().attr('style', '');
    }
}

function autoscrollTocList() {
    if (!window.gEnableTocListAutoScroll || window.gMouseInSidebarTocList) {
        return;
    }

    var activeToc = $('.' + window.gActiveTocClass).first();
    if (activeToc.length == 0) {
        return;
    }
    var activeTocXY = activeToc[0].getBoundingClientRect();
    var tocListXY = getTocList()[0].getBoundingClientRect();

    var scrollHeight = activeTocXY.top - (tocListXY.top + tocListXY.bottom) / 2;
    var heightSign = (scrollHeight > 0) ? 1 : -1;
    scrollHeight += heightSign * tocListXY.height / 5;

    if (activeTocXY.top < tocListXY.top + 15 || activeTocXY.bottom > tocListXY.bottom - 15) {
        window.gEnableTocListAutoScroll = false;
        getTocList().animate(
                { scrollTop: getTocList().scrollTop() + scrollHeight },
                window.gAutoScrollDuration,
                function() { window.gEnableTocListAutoScroll = true; }
        );
    }
}

function openActiveTocList(activeLi) {
    // show next level tocs
    var activeChilds = activeLi.children();
    if (activeChilds.length > 2 && $(activeChilds[2]).is('ol')) {
        showToc($(activeChilds[2]));  // show ol
        showToc($(activeChilds[2]).children()); // show ol li
    }

    // show active toc and his sibling tocs
    showToc(activeLi);
    showToc(activeLi.siblings());

    // show active toc's parent toc and the parent toc's sibling tocs(only the top level)
    activeLi.parents().each(function(i, elem) {
        if ('niu2-sidebar-toc-list' == elem.id) {
            return false;
        }
        showToc($(elem));
        if ($(elem).is('li')) {
            showToc($(elem).siblings());
        }
    });
}

function closeAllTocs() {
    hideToc($('#niu2-sidebar-toc-list ol li'));
    hideToc($('#niu2-sidebar-toc-list li ol'));
}

function openAllTocs() {
    showToc($('#niu2-sidebar-toc-list ol li'));
    showToc($('#niu2-sidebar-toc-list li ol'));
}

function initHeaderScrollAnimation(targets) {
    initScrollAnimation(
        targets,
        function(target) { return target.offset().top; },
        window.gAutoScrollDuration,
        function() {
            updateFootnoteStatus();
            window.gEnableTocStatusUpdate = true;
            locateTocInViewport();
        }
    );
}

// toc scroll anamation
function initTocLinkScrollAnimation() {
    initHeaderScrollAnimation(getSidebarTocLinks());
}

function initFootnote() {
    // insert footnote title node
    if (getFootnoteRefs().length > 0) {
        var ftTitle = '脚注';
        getTocList().children(':last').before('
' + ftTitle + '
');
        $('.footnote').before('
' + ftTitle + '
');
    }

    initFootnoteBackRefLinks();
    initFootnoteBackRefAnimation();
    initMouseXYRecord();
    initFootnoteRefPopover();
    initFootnoteRefAnimation();
}

function updateFootnoteStatus() {
    unhighlightFootnote();
    highlightFootnote();
}

function unhighlightCurrHighlighted() {
    if (window.gCurrHighlightedElem) {
        unhighlightElement(window.gCurrHighlightedElem);
    }
    if (window.gCurrHighlightedBackref) {
        unhighlightSubBackref(window.gCurrHighlightedBackref);
    }
}

function highlightElement(obj) {
    obj.addClass('alert-success');
    window.gCurrHighlightedElem = obj;
}

function unhighlightElement(obj) {
    obj.removeClass('alert-success');
}

function highlightSubBackref(obj) {
    obj.addClass('activeSubBackref');
    window.gCurrHighlightedBackref = obj;
}

function unhighlightSubBackref(obj) {
    obj.removeClass('activeSubBackref');
}

function getFootnoteHlIndex() {
    // the second element in footnote list li
    // is
, the valid footnote, while the
    // first one is the footntoe backref link.
    return 1;
}

function highlightFtSubBackrefs(ftLiNode) {
    if (null != window.gCurrFootnoteRefPos) {
        var currBackref = $(ftLiNode.children('.backref-span').children('.sub-backref-link').children()[window.gCurrFootnoteRefPos]);
        if (currBackref[0]) {
            highlightSubBackref(currBackref);
            window.gHlFootnoteSubBackref = currBackref;
        }
    }
}

function highlightFootnote() {
    var ftHlId = window.location.hash.substring(1);
    // highlight footnote ref link
    if (null != window.gCurrFootnoteHlPos) {
        var currSupNodes = $(getFootnoteRefs().parent().filter('[id="' + ftHlId + '"]'));
        if (currSupNodes.length > window.gCurrFootnoteHlPos) {
            window.gHlFootnoteRef = $(currSupNodes[window.gCurrFootnoteHlPos]);
            unhighlightCurrHighlighted();
            highlightElement(window.gHlFootnoteRef);
            return;
        }
    }

    // highlight footnote and current sub-backref link
    getFootnoteList().each(function(i, e) {
        var currLi = $(e);
        if (currLi.attr('id') == ftHlId) {
            unhighlightCurrHighlighted();
            highlightElement($(currLi));
            highlightFtSubBackrefs(currLi);
            window.gHlFootnote = currLi;
            return false;
        }
    });
}

function unhighlightFootnote() {
    if (window.gHlFootnoteRef) {
        if ('#' + window.gHlFootnoteRef.attr('id') == window.location.hash) {
            return false;
        }
        unhighlightElement(window.gHlFootnoteRef);
        window.gHlFootnoteRef = null;
        return;
    }

    if (window.gHlFootnote) {
        if ('#' + window.gHlFootnote.attr('id') == window.location.hash) {
            return false;
        }
        var currP = $(window.gHlFootnote);
        if ('' != currP.attr('class')) {
            unhighlightElement(currP);
            window.gHlFootnote = null;
        }
    }

    if (window.gHlFootnoteSubBackref) {
        unhighlightSubBackref(window.gHlFootnoteSubBackref);
        return;
    }
}

function resetFootnoteRefs() {
    window.gFootnoteRefs = $('.footnote-ref');
}

function getFootnoteRefs() {
    if (!window.gFootnoteRefs) {
        resetFootnoteRefs();
    }
    return window.gFootnoteRefs;
}

function resetFootnoteRefMap() {
    window.gFootnoteIdMap = {};
    getFootnoteRefs().each(function(i, e) {
        var refNode = $(e);
        var supNode = refNode.parent();
        // footnote => {ref link id, [footnote ref link offset]}
        var footnoteId = refNode.attr('href').substring(1);
        if (!window.gFootnoteIdMap[footnoteId]) {
            window.gFootnoteIdMap[footnoteId] = {};
            window.gFootnoteIdMap[footnoteId].id = supNode.attr('id');
            window.gFootnoteIdMap[footnoteId].offsets = [];
        }
        window.gFootnoteIdMap[footnoteId].offsets.push(supNode.offset());
    });
}

// currently, the python markdown footnote extension may
// generate multiple footnote reference links with the
// same id
function getFootnoteRefMap(ftId) {
    if (!window.gFootnoteIdMap) {
        resetFootnoteRefMap();
    }
    return window.gFootnoteIdMap[ftId];
}

function resetFootnoteBackRefs() {
    window.gFootnoteBackRefs = $('.footnote-backref');
}

function getFootnoteBackRefs() {
    if (!window.gFootnoteBackRefs) {
        resetFootnoteBackRefs();
    }
    return window.gFootnoteBackRefs;
}

function getFootnoteList() {
    if (!window.gFootnoteList) {
        window.gFootnoteList = $('.footnote li');
    }
    return window.gFootnoteList;
}

// add a backref span to footnote ref
function initFootnoteBackRefLinks() {
    // create backref links
    getFootnoteList().each(function(i, e) {
        var ftLiNode = $(e);
        var ftLiNodeId = ftLiNode.attr('id');
        var ftRefLinksMap = getFootnoteRefMap(ftLiNode.attr('id'));
        var ftRefLinksNum = ftRefLinksMap.offsets.length;
        var backrefSpan = '';
        if (1 == (ftRefLinksNum)) {
            backrefSpan += '';
        } else {
            backrefSpan += '';
            for (var i = 0; i < ftRefLinksNum; i++) {
                backrefSpan += '' + (i + 1) + ' ';
            }
            backrefSpan += '';
        }
        backrefSpan += '';
        ftLiNode.prepend(backrefSpan);
    });

}

function initFootnoteBackRefAnimation() {
    // init backref links animation
    initScrollAnimation(
        getFootnoteBackRefs(),
        function(target, source) {
            var ftRefLinksMap = getFootnoteRefMap(source.attr('data-source'));
            if (1 == ftRefLinksMap.offsets.length) {
                return ftRefLinksMap.offsets[0].top - window.gFixedHeaderHeight;
            } else {
                return ftRefLinksMap.offsets[parseInt(source.text()) - 1].top - window.gFixedHeaderHeight;
            }
        },
        window.gAutoScrollDuration,
        function(source) {
            if ("" != source.text()) {
                window.gCurrFootnoteHlPos = parseInt(source.text()) - 1;
            } else {
                window.gCurrFootnoteHlPos = 0;
            }
            updateFootnoteStatus();
            window.gEnableTocStatusUpdate = true;
            locateTocInViewport();
        }
    );
}

function initFootnoteRefAnimation() {
    // footnote ref link click event
    initScrollAnimation(
        getFootnoteRefs(),
        function(target) { return target.offset().top - 100 - window.gFixedHeaderHeight; },
        window.gAutoScrollDuration,
        function(source) {
            // find current sub-backref link
            var currFtSups = getFootnoteRefs().parent().filter('[id="' + source.parent().attr('id') + '"]');
            currFtSups.each(function(i, e) {
                if (source[0] == $(e).children()[0]) {
                    window.gCurrFootnoteRefPos = i;
                    return false;
                }
            });
            updateFootnoteStatus();
            window.gEnableTocStatusUpdate = true;
            locateTocInViewport();
        }
    );
}

function initFootnoteRefPopover() {
    getFootnoteRefs().each(function(i, e) {
        var ftRefLink = $(e);
        var ftLiNode = $(document.getElementById(ftRefLink.attr('href').substring(1)));
        var ftNode = $(ftLiNode.children()[getFootnoteHlIndex()]);
        ftRefLink.popover({
            'trigger': 'hover',
            'placement': 'auto top',
            'html': true,
            'container': 'body',
            'content': ftNode.html()
        });
        // do not hide popover
        ftRefLink.on('hide.bs.popover', function() {
            if (window.gFootnotePopoverLink) {
                return false;
            }
            return true;
        });

        ftRefLink.mouseleave(function() {
        });

        // record mouse position on footnote ref hover
        ftRefLink.mouseenter(function() {
            var currRefLink = $(this);
            // close previous popover first
            if (window.gFootnotePopoverLink && window.gFootnotePopoverLink[0] != currRefLink[0]) {
                hideFootnotePopover();
            }
            var ftPopoverNode = $('.popover')[0];
            if (ftPopoverNode) {
                window.gEnableMouseXYRecord = true;
                window.gFootnotePopoverLink = currRefLink;
                var popoverXY = ftPopoverNode.getBoundingClientRect();
                var refLinkXY = e.getBoundingClientRect();

                window.gPopoverXY = {}
                window.gPopoverXY.top = popoverXY.top < refLinkXY.top ? popoverXY.top : refLinkXY.bottom;
                window.gPopoverXY.bottom = popoverXY.top < refLinkXY.top ? refLinkXY.top : popoverXY.bottom;
                window.gPopoverXY.left = popoverXY.left < refLinkXY.left ? popoverXY.left : refLinkXY.left;
                window.gPopoverXY.right = popoverXY.right < refLinkXY.right ? refLinkXY.right : popoverXY.right;

                window.gRefLinkXY = {}
                window.gRefLinkXY.top = refLinkXY.top;
                window.gRefLinkXY.bottom = refLinkXY.bottom;
                window.gRefLinkXY.left = refLinkXY.left - 10;
                window.gRefLinkXY.right = refLinkXY.right + 10;
            }
        });
    });
}

function hideFootnotePopover() {
    var ftRefLink = window.gFootnotePopoverLink;
    window.gFootnotePopoverLink = null;
    window.gEnableFootnotePopover = false;
    ftRefLink.popover('hide');
}

function isPositionInRect(x, y, rect) {
    if (x >= rect.left &&  x <= rect.right &&
            y >= rect.top && y <= rect.bottom) {
        return true;
    }
    return false;
}

// mouse position related events
function initMouseXYRecord() {
    $(document).mousemove(function(e) {
        window.gMousePositionX = e.clientX;
        window.gMousePositionY = e.clientY;

        // footnote popover
        if (window.gEnableMouseXYRecord && window.gPopoverXY && window.gRefLinkXY) {
            if (!isPositionInRect(e.clientX, e.clientY, window.gPopoverXY) &&
                    !isPositionInRect(e.clientX, e.clientY, window.gRefLinkXY)) {
                // hide footnote popover now
                window.gEnableMouseXYRecord = false;
                hideFootnotePopover();
            }
        }

        // sidebar toc list scroll
        if (isPositionInRect(e.clientX, e.clientY, getTocList()[0].getBoundingClientRect())) {
            window.gMouseInSidebarTocList = true;
        } else {
            window.gMouseInSidebarTocList = false;
        }

        // toggle toolbar
        var mainErea = getMainContent().getBoundingClientRect();
        if (getToolbar() && e.clientY > mainErea.bottom - mainErea.height) {
            if (!window.gToolbarAnimationEnabled) {
                return;
            }
            var hideToolbarAnimationFunc = function() {
                $(getToolbar()).animate({left: '-36px'}, 500, complete=function() {
                    window.gToolbarAnimationEnabled = true;
                    window.gToolbarHidden = true;
                });
            }
            if (window.gToolbarHidden && e.clientX < mainErea.left) {
                window.gToolbarAnimationEnabled = false;
                $(getToolbar()).animate({left: '0px'}, 500, complete=function() {
                    window.gToolbarAnimationEnabled = true;
                    window.gToolbarHidden = false;
                    if (window.gMousePositionX > mainErea.left) {
                        hideToolbarAnimationFunc();
                    }
                });
            } else if (!window.gToolbarHidden && e.clientX > mainErea.left) {
                window.gToolbarAnimationEnabled = false;
                hideToolbarAnimationFunc();
            }
        }
    });
}

function initScrollAnimation(targets, calcHeightFunc, duration, callback) {
    targets.each(function(i, e) {
        $(e).click(function(ev) {
            ev.preventDefault();
            var href = $(e).attr('href');
            var anchor = href.substring(href.indexOf('#') + 1);
            // update url anchor
            if (window.location.hash != anchor && window.history.pushState) {
                window.history.pushState('toc change', anchor, '#' + anchor);
            }
            window.gEnableTocStatusUpdate = false;
            target = $(document.getElementById(anchor));
            source = $(this);
            $('body, html').animate(
                { scrollTop: calcHeightFunc(target, source) },
                duration,
                function() { callback(source); }
            );
        });
    });
}

function showToc(tocs) {
    tocs.each(function(i, elem) {
        var toc = $(elem);
        if (toc.is('li')) {
            toc.attr('style', 'display:list-item;');
        } else if (toc.is('ol')) {
            toc.attr('style', 'display:block;');
        }
    });
}

function hideToc(tocs) {
    tocs.each(function(i, elem) {
        $(elem).attr('style', 'display:none;');
    });
}

function initAllTocsCtrl() {
    if (isAllTocsClosed()) {
        closeAllTocs();
    } else {
        openAllTocs();
    }
    getSidebarTocCtrl().click(function() {
        toggleAllTocs();
    });
}

function toggleAllTocs() {
    if (isAllTocsClosed()) {
        getSidebarToc().data('status', 'open');
        getSidebarTocCtrl().attr('class', 'fa fa-minus');
        openAllTocs();
    } else {
        getSidebarToc().data('status', 'closed');
        getSidebarTocCtrl().attr('class', 'fa fa-plus');
        closeAllTocs();
    }
    locateTocInViewport();
}

function isAllTocsClosed() {
    if ('closed' == getSidebarToc().data('status')) {
        return true;
    }
    return false;
}

function getSidebarTocCtrl() {
    if (!window.gSidebarTocCtrl) {
        window.gSidebarTocCtrl = $('#niu2-sidebar-toc-ctrl');
    }
    return window.gSidebarTocCtrl;
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN' 'http://java.sun.com/j2ee/dtds/web-app_2_2.dtd'>
<!--
  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.
-->

<web-app>
    <display-name>display name</display-name>
    <description>no description</description>
    <servlet>
        <servlet-name>servletname</servlet-name>
        <display-name>servlet display name</display-name>
        <description>no description</description>
        <servlet-class>com.nowhere.Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>servletname</servlet-name>
        <url-pattern>/urlPattern</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.12.0/css/semantic.min.css"/>

From the city

To the country


text:
var mongoose = require('mongoose');

var TechniciansSchema = new mongoose.Schema({
	user_id: { type: mongoose.Schema.Types.ObjectId, ref: 'User'},
	pianoKindGrand: {type: Boolean},
	pianoKindConsole: {type: Boolean},
	pianoKindSpinet: {type: Boolean},
	pianoKindOldUpright: {type: Boolean},
	tuning: {type: Boolean},
	pitchRaise: {type: Boolean},
	repairs: {type: Boolean},
	internalCleaning: {type: Boolean},
	regulation: {type: Boolean},
	purchaseConsult: {type: Boolean},
	estimate: {type: Boolean},
	appraisal: {type: Boolean},
	other: {type: Boolean},
	comment: {type: String},
	box_elder: { type: Boolean },
	cache: {type: Boolean},
	davis: {type: Boolean},
	juab: {type: Boolean},
	morgan: {type: Boolean},
	salt_lake: {type: Boolean},
	tooele: {type: Boolean},
	utah: {type: Boolean},
	weber: {type: Boolean},
	other_cnty: {type: Boolean},
	submittedAt: { type: Date, default: Date.now}
});

TechniciansSchema.pre('update', function(next){
	this.submittedAt = new Date();
	next();
});

module.exports = mongoose.model('technician', TechniciansSchema);