text:
<?php
namespace Zeomatics;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Application;

class Module
{   /*Code to handle all 404 errors*/
//    public function onBootstrap(MvcEvent $e)
//    {
//        $eventManager = $e->getApplication()->getEventManager();
//        $sharedManager = $eventManager->getSharedManager();
//        //controller can't dispatch request action that passed to the url
//        $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController',
//               'dispatch',
//               array($this, 'handleControllerCannotDispatchRequest' ), 101);
//        //controller not found, invalid, or route is not matched anymore
//        $eventManager->attach('dispatch.error',
//               array($this,
//              'handleControllerNotFoundAndControllerInvalidAndRouteNotFound' ), 100);
//    }
//
//    public function handleControllerCannotDispatchRequest(MvcEvent $e)
//    {
//        $action = $e->getRouteMatch()->getParam('action');
//        $controller = get_class($e->getTarget());
//
//        // error-controller-cannot-dispatch
//        if (! method_exists($e->getTarget(), $action.'Action')) {
//            $logText = 'The requested controller '.
//                        $controller.' was unable to dispatch the request : '.$action.'Action';
//            //you can do logging, redirect, etc here..
//             echo $logText;
//        }
//    }
//
//    public function handleControllerNotFoundAndControllerInvalidAndRouteNotFound(MvcEvent $e)
//    {
//        $error  = $e->getError();
//        if ($error == Application::ERROR_CONTROLLER_NOT_FOUND) {
//            //there is no controller named $e->getRouteMatch()->getParam('controller')
//            $logText =  'The requested controller '
//                        .$e->getRouteMatch()->getParam('controller'). '  could not be mapped to an existing controller class.';
//
//            //you can do logging, redirect, etc here..
//            echo $logText;
//        }
//
//        if ($error == Application::ERROR_CONTROLLER_INVALID) {
//            //the controller doesn't extends AbstractActionController
//            $logText =  'The requested controller '
//                        .$e->getRouteMatch()->getParam('controller'). ' is not dispatchable';
//
//            //you can do logging, redirect, etc here..
//            echo $logText;
//        }
//
//        if ($error == Application::ERROR_ROUTER_NO_MATCH) {
//            // the url doesn't match route, for example, there is no /foo literal of route
//            $logText =  'The requested URL could not be matched by routing.';
//            //you can do logging, redirect, etc here...
//            echo $logText;
//        }
//    } /*404 error ends*/

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

//    public function getServiceConfig(){
//         return array(
//             'factories' => array(
//                 'Navigation' => 'Zeomatics\Navigation\ZeomaticsNavigationFactory',
//             ),
//         );
//     }

     /*Code from samsonasik example for navigation*/
     public function getServiceConfig()
    {
        return array(
            'initializers' => array(
                function ($instance, $sm) {
                    if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
                        $instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
                    }
                }
            ),
            'invokables' => array(
                 'menu' => 'Zeomatics\Model\MenuTable'
            ),
            'factories' => array(
                'Navigation' => 'Zeomatics\Navigation\MyNavigationFactory'
            )
          );
    }

    /*Code from stackoverflow example for navigation*/
//    public function getServiceConfig()
//    {
//        return array(
//                'initializers' => array(
//                        function ($instance, $sm) {
//                            if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
//                                $instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
//                            }
//                        }
//                ),
//                'invokables' => array(
//                        'menu' => 'Zeomatics\Model\MenuTable',
//
//                ),
//
//                'factories' => array(
//                        'Navigation' => 'Zeomatics\Navigation\MyNavigationFactory'
//                )
//        );
//    }
}


text:
from __future__ import unicode_literals

"""This file is part of the django ERP project.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from django.test import TestCase

from ..forms import *

__author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>'
__copyright__ = 'Copyright (c) 2013-2015, django ERP Team'
__version__ = '0.0.1'

class SelectPluggetSourceFormTestCase(TestCase):
    def test_populate_source_choices(self):
        """Tests correct populating of source choices.
        """
        registry.clear()
        registry.discovered = True

        source_title1 = "Source 1"
        source_title2 = "Source 2"

        registry.register_simple_plugget_source(source_title1)
        registry.register_simple_plugget_source(source_title2)

        f = SelectPluggetSourceForm()
        choices = f.fields['source_uid'].choices

        self.assertEqual(len(choices), 2)
        self.assertTrue((source_title1, source_title1) in choices)
        self.assertTrue((source_title2, source_title2) in choices)

class CustomizePluggetSettingsFormTestCase(TestCase):
    def setUp(self):
        self.r = Region.objects.create(slug="r")
        self.p = Plugget.objects.create(title="Plugget", source="", region=self.r)

    def test_set_region(self):
        """Tests correct setting of region attribute via "region" kwarg.
        """
        f = CustomizePluggetSettingsForm()

        self.assertEqual(f.region, None)

        f = CustomizePluggetSettingsForm(region="My Region")

        self.assertEqual(f.region, "My Region")

    def test_clean_title_when_title_is_new(self):
        """Tests correct validation of title field when its value is a new one.
        """
        f = CustomizePluggetSettingsForm({"title": "A new plugget"}, region=self.r)

        self.assertTrue(f.is_valid())

    def test_raise_error_when_title_already_exists(self):
        """Tests correct validation of title field when its value is already used.
        """
        f = CustomizePluggetSettingsForm({"title": "Plugget"}, region=self.r)

        self.assertFalse(f.is_valid())
        # self.assertRaises(ValidationError, f.clean_title)
        self.assertTrue("This title is already in use." in f.errors.get("title", []))

    def test_correct_title_validation_on_plugget_editing(self):
        """Tests correct validation of title field on plugget editing.
        """
        f = CustomizePluggetSettingsForm({"title": "Plugget"}, instance=self.p)

        self.assertTrue(f.is_valid())

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.android;

import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.Processor;
import org.jetbrains.android.resourceManagers.LocalResourceManager;
import org.jetbrains.android.util.AndroidCommonUtils;
import org.jetbrains.annotations.NotNull;

/**
 * @author Eugene.Kudelevsky
 */
public class AndroidReferenceSearchExecutor extends QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters> {
  public AndroidReferenceSearchExecutor() {
    super(true);
  }

  @Override
  public void processQuery(@NotNull ReferencesSearch.SearchParameters params, @NotNull Processor<PsiReference> consumer) {
    final PsiElement refElement = params.getElementToSearch();

    if (!(refElement instanceof PsiFile)) {
      return;
    }
    final VirtualFile vFile = ((PsiFile)refElement).getVirtualFile();
    if (vFile == null) {
      return;
    }
    LocalResourceManager manager = LocalResourceManager.getInstance(refElement);
    if (manager == null) {
      return;
    }

    String resType = manager.getFileResourceType((PsiFile)refElement);
    if (resType != null) {
      String resName = AndroidCommonUtils.getResourceName(resType, vFile.getName());
      // unless references can be found by a simple CachedBasedRefSearcher
      if (!resName.equals(vFile.getNameWithoutExtension()) && StringUtil.isNotEmpty(resName)) {
        params.getOptimizer().searchWord(resName, params.getEffectiveSearchScope(), true, refElement);
      }
    }
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.projectsontracks.utils;

import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author f7gupa
 */
public class DatabaseUtils {

    /*
     * From an input like SCHEMA.TABLENAME returns the schema name
     */
    public static String getSchemaName(String tableName) {
        String tOwner = null;
        if (StringUtils.isNotBlank(tableName)) {
            if (tableName.contains(".")) {
                tOwner = StringUtils.substringBefore(tableName, ".");
            }
        }
        //System.out.println("*** Schema: " + tOwner);
        return (tOwner);
    }//getSchemaName

    /*
     * From an input like SCHEMA.TABLENAME returns the table name
     */
    public static String getTableName(String tableName) {
        String table = tableName;
        if (StringUtils.isNotBlank(tableName)) {
            if (tableName.contains(".")) {
                table = StringUtils.substringAfterLast(tableName, ".");
            }
        }
        //System.out.println("*** Table: " + table);
        return (table);
    }//getTableName

    /*
     * From an input like OWNER.TABLENAME returns a query for the DESCR command
     */
    public static String getOracleOwnerAndTableQuery(String tableName) {
        String query = "";
        if (StringUtils.isNotBlank(tableName)) {
            String tName = getTableName(tableName);
            String tOwner = getSchemaName(tableName);
            if (tName != null) {
                if (tName.contains("%")) {
                    query = " UPPER(TABLE_NAME) like '%" + tName.toUpperCase() + "%' ";
                } else {
                    query = " UPPER(TABLE_NAME)='" + tName.toUpperCase() + "' ";
                }
            }
            if (tOwner != null) {
                if (tOwner.contains("%")) {
                    query = query + " AND UPPER(OWNER) like '" + tOwner.toUpperCase() + "' ";
                } else {
                    query = query + " AND UPPER(OWNER)='" + tOwner.toUpperCase() + "' ";
                }
            }
        }
        return (query);
    }//getOracleOwnerAndTableQuery

    /**
     * Defines a table name for a SQL query
     * @param query a valid SQL query
     * @return
     */
    public static String getTableNameFromQuery(String query) {
        String tableName = StringUtils.substringAfter(query.toUpperCase(), "FROM ");
        String tmpTableName = StringUtils.substringBefore(tableName, " ");
        if (tmpTableName != null && !"".equals(tmpTableName.trim())) {
            tableName = tmpTableName.trim().toUpperCase();
        } else {
            tableName = tableName.trim().toUpperCase();
            if ("".equals(tableName)) {
                tableName = "Data";
            }
        }
        return(tableName);
    }//getTableNameFromQuery
}


text:
My Markets

<form name="addForm" ng-submit="addMarket(addForm.$valid)" novalidate>

  {{addForm.symbol.$pristine}}

    <input type="text" ng-model="newMarketSymb" required name="symbol" placeholder="Market Symbol" class="form-control" >

Symbol is required.

  <button type="submit" class="btn btn-primary" ng-disabled="addForm.symbol.$pristine">Add</button>
</form>

{{test}}

Symbol	Currency	24 Avg	High	Low

    {{market.symbol}}
    {{market.currency}}
    {{market.avg | currency:''}}
    {{market.high | currency:''}}
    {{market.low | currency:''}}
    Remove


text:
package org.zaproxy.zap.extension.pscan.scanner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Source;

import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;

public class RegexAutoTagScanner extends PluginPassiveScanner {

    // protected static final int PATTERN_SCAN = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE;
    protected static final int PATTERN_SCAN = Pattern.CASE_INSENSITIVE;

	public enum TYPE {ALERT, TAG, TECH};

	private String name = null;
	private String requestUrlRegex = null;
	private String requestHeaderRegex = null;
	private String responseHeaderRegex = null;
	private String responseBodyRegex = null;

	private Pattern requestUrlPattern = null;
	private Pattern requestHeaderPattern = null;
	private Pattern responseHeaderPattern = null;
	private Pattern responseBodyPattern = null;

	private TYPE type = null;
	private String config = null;

	private PassiveScanThread parent = null;

	public RegexAutoTagScanner() {
		// Null constructor to prevent error being logged;)
	}

	public RegexAutoTagScanner(String name, TYPE type, String config) {
		super();
		this.name = name;
		this.type = type;
		this.config = config;
	}

	public RegexAutoTagScanner(String name, TYPE type, String config,
			String requestUrlregex, String requestHeaderRegex,
			String responseHeaderRegex, String responseBodyRegex,
			boolean enabled) {
		super();
		this.name = name;
		this.setRequestUrlRegex(requestUrlregex);
		this.setRequestHeaderRegex(requestHeaderRegex);
		this.setResponseHeaderRegex(responseHeaderRegex);
		this.setResponseBodyRegex(responseBodyRegex);
		this.type = type;
		this.config = config;
		setEnabled(enabled);
	}

	public RegexAutoTagScanner(RegexAutoTagScanner scanner) {
		this(scanner.name, scanner.type, scanner.config,
				scanner.requestUrlRegex, scanner.requestHeaderRegex,
				scanner.responseHeaderRegex, scanner.responseBodyRegex,
				scanner.isEnabled());
	}

	public Pattern getRequestUrlPattern() {
		return requestUrlPattern;
	}

	public Pattern getRequestHeaderPattern() {
		return requestHeaderPattern;
	}

	public Pattern getResponseHeaderPattern() {
		return responseHeaderPattern;
	}

	public Pattern getResponseBodyPattern() {
		return responseBodyPattern;
	}

	public TYPE getType() {
		return type;
	}

	public void setType(TYPE type) {
		this.type = type;
	}

	public String getConf() {
		return config;
	}

	public void setConf(String config) {
		this.config = config;
	}

	public String getRequestUrlRegex() {
		return requestUrlRegex;
	}
	public void setRequestUrlRegex(String requestUrlregex) {
		this.requestUrlRegex = requestUrlregex;
		if (requestUrlregex == null || requestUrlregex.length() == 0) {
			this.requestUrlPattern = null;
		} else {
			this.requestUrlPattern = Pattern.compile(requestUrlregex, PATTERN_SCAN);
		}
	}
	public String getRequestHeaderRegex() {
		return requestHeaderRegex;
	}
	public void setRequestHeaderRegex(String requestHeaderRegex) {
		this.requestHeaderRegex = requestHeaderRegex;
		if (requestHeaderRegex == null || requestHeaderRegex.length() == 0) {
			this.requestHeaderPattern = null;
		} else {
			this.requestHeaderPattern = Pattern.compile(requestHeaderRegex, PATTERN_SCAN);
		}
	}
	public String getResponseHeaderRegex() {
		return responseHeaderRegex;
	}
	public void setResponseHeaderRegex(String responseHeaderRegex) {
		this.responseHeaderRegex = responseHeaderRegex;
		if (responseHeaderRegex == null || responseHeaderRegex.length() == 0) {
			this.responseHeaderPattern = null;
		} else {
			this.responseHeaderPattern = Pattern.compile(responseHeaderRegex, PATTERN_SCAN);
		}
	}
	public String getResponseBodyRegex() {
		return responseBodyRegex;
	}
	public void setResponseBodyRegex(String responseBodyRegex) {
		this.responseBodyRegex = responseBodyRegex;
		if (responseBodyRegex == null || responseBodyRegex.length() == 0) {
			this.responseBodyPattern = null;
		} else {
			this.responseBodyPattern = Pattern.compile(responseBodyRegex, PATTERN_SCAN);
		}
	}

	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void scanHttpRequestSend(HttpMessage msg, int id) {
		if (! this.isEnabled()) {
			return;
		}
		if (getRequestHeaderPattern() != null) {
			Matcher m = getRequestHeaderPattern().matcher(
					msg.getRequestHeader().toString());
			if (m.find()) {
				// Scanner matches, so do what it wants...
				parent.addTag(id, this.getConf());
				return;
			}
		}
		if (getRequestUrlPattern() != null) {
			Matcher m = getRequestUrlPattern().matcher(
					msg.getRequestHeader().getURI().toString());
			if (m.find()) {
				// Scanner matches, so do what it wants...
				parent.addTag(id, this.getConf());
				return;
			}
		}
	}

	public Alert getAlert(HttpMessage msg) {
		return null;
	}

	@Override
	public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
		if (! this.isEnabled()) {
			return;
		}
		if (getResponseHeaderPattern() != null) {
			Matcher m = getResponseHeaderPattern().matcher(
					msg.getResponseHeader().toString());
			if (m.find()) {
				// Scanner matches, so do what it wants...
				parent.addTag(id, this.getConf());
				return;
			}
		}
		if (getResponseBodyPattern() != null) {
			Matcher m = getResponseBodyPattern().matcher(
					msg.getResponseBody().toString());
			if (m.find()) {
				// Scanner matches, so do what it wants...
				parent.addTag(id, this.getConf());
				return;
			}
		}
	}

	@Override
	public void setParent(PassiveScanThread parent) {
		this.parent = parent;
	}

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + ((config == null) ? 0 : config.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((requestHeaderRegex == null) ? 0 : requestHeaderRegex.hashCode());
        result = prime * result + ((requestUrlRegex == null) ? 0 : requestUrlRegex.hashCode());
        result = prime * result + ((responseBodyRegex == null) ? 0 : responseBodyRegex.hashCode());
        result = prime * result + ((responseHeaderRegex == null) ? 0 : responseHeaderRegex.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (!super.equals(object)) {
            return false;
        }
        if (getClass() != object.getClass()) {
            return false;
        }
        RegexAutoTagScanner other = (RegexAutoTagScanner) object;
        if (config == null) {
            if (other.config != null) {
                return false;
            }
        } else if (!config.equals(other.config)) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        if (requestHeaderRegex == null) {
            if (other.requestHeaderRegex != null) {
                return false;
            }
        } else if (!requestHeaderRegex.equals(other.requestHeaderRegex)) {
            return false;
        }
        if (requestUrlRegex == null) {
            if (other.requestUrlRegex != null) {
                return false;
            }
        } else if (!requestUrlRegex.equals(other.requestUrlRegex)) {
            return false;
        }
        if (responseBodyRegex == null) {
            if (other.responseBodyRegex != null) {
                return false;
            }
        } else if (!responseBodyRegex.equals(other.responseBodyRegex)) {
            return false;
        }
        if (responseHeaderRegex == null) {
            if (other.responseHeaderRegex != null) {
                return false;
            }
        } else if (!responseHeaderRegex.equals(other.responseHeaderRegex)) {
            return false;
        }
        if (type != other.type) {
            return false;
        }
        return true;
    }

}


text:
using appfactum.core;
using MySql.Data.MySqlClient;
using System;

namespace appfactum.data.mysql
{
    public class MySQLDatabase : BaseDatabase, IDatabase
    {
        private MySQLTranslator _translator = new MySQLTranslator();

        public ITranslator Translator { get { return _translator; } }

        public MySQLConnection GetConnection() { return new MySQLConnection(this); }

        public bool Exists
        {
            get
            {

                bool exist = false;

                // zuerst versuchen eine FbConnection zur Datenbank herzustellen
                using (MySqlConnection connect = new MySqlConnection(Configuration.ConnectionString))
                {
                    try
                    {
                        connect.Open();
                        exist = true;
                    }
                    catch (MySqlException exfb)
                    {
                        if (exfb.ErrorCode == 335544379) // unsupported on-disk structure
                        {
                            throw new Exception("Datenbank ist neuer als installierte FirebirdSQL Version. Bitte FirebirdSQL aktualisieren.");
                        }

                        if (exfb != null)
                            exist = false;
                    }
                }

                return exist;

            }
        }

        /// <summary>
        /// Prüft ob die Datenbank existiert und legt diese ggf. neu an...
        /// </summary>
        public void Create()
        {
            using (MySqlConnection conn = new MySqlConnection(Configuration.ConnectionString))
            {
                var cmd = new MySqlCommand($"CREATE DATABASE IF NOT EXISTS {((MySQLConfiguration)Configuration).Builder.Database};", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }

            //using (IConnection connection = GetConnection())
            //{
            //    connection.Check<SystemDatabaseInformation>();
            //}
        }
    }
}


text:
The provided `Dockerfile` creates a container with the default development installation of the [frab - conference management system](https://github.com/frab/frab).

## build the container

    git clone https://github.com/SubOptimal/frab-docker
    cd frab-docker
    docker build -t suboptimal/frab-docker .

In case you are behind a proxy start the build as

    docker build --build-arg http_proxy=http://your.proxy.host:8080 -t suboptimal/frab-docker .

## start the container

    docker run -ti -p 3000:3000 --name frab-devl-demo suboptimal/frab-docker su -l frab

## initial setup of frab

    # inside the container
    cd ~/frab-master
    ~/setup_frab.sh

In case you are behind a proxy

    # inside the container
    cd ~/frab-master
    bundle config github.https true
    export http_proxy=http://your.proxy.host:8080
    ~/setup_frab.sh

## starting frab

`frab` is not started automatically when the container is started, in case you want to replace the SQLite database file for testing purpose.

    # inside the container
    ~/run_frab.sh

As soon frab is started navigate to [http://localhost:3000/](http://localhost:3000/) and login as user `admin@example.org` with password `test123`.

## replace the SQLite database file

The container must be up and running, but frab must not be running.

    # on your host
    docker cp your_database.sqlite3 <your_container_id>:/home/frab/frab-master/db/development.sqlite3
    docker exec <your_container_id> chown frab.frab /home/frab/frab-master/db/development.sqlite3


text:
KadOHui = (typeof KadOHui !== 'undefined') ? KadOHui : {};

KadOHui.Control = function(node) {
  this.node = node;
  this.control = $("#control");

  this.joinBtn    = $("#join_btn").button();

  this.putBtn     = $("#put_btn").button();
  this.putValue   = $("#put_value");
  this.putKey     = $("#put_key");
  this.putResult  = $("#put_result");

  this.getBtn     = $("#get_btn").button();
  this.getKey     = $("#get_key");
  this.getResult  = $("#get_result");

  this.pingBtn     = $("#ping_btn").button();
  this.pingAddress = $("#ping_address");
  this.pingResult  = $("#ping_result");

  this.initJoin()
      .initGet()
      .initPut()
      .initPing();
};

KadOHui.Control.prototype = {
  initJoin: function() {
    var that = this;
    var onJoin = function() {
      that.joinBtn.unbind('click', onJoin);
      that.joinBtn.button('loading');
      that.node.join(function() {
        that.joinBtn.button('complete').button('toggle');
      });
    };
    this.joinBtn.click(onJoin);
    return this;
  },

  initGet: function() {
    var that = this;
    var result = this.getResult;
    var loader = result.find('.loader');
    var content = result.find('.content');
    result.hide();
    var onGet = function() {
      that.getBtn.unbind('click', onGet)
                 .button('toggle');
      var key = that.getKey.val();
      content.hide();
      loader.show();
      result.show();
      that.node.get(key, function(value) {
        var text;
        if (!value) {
          text = 'value not found for key '+KadOHui.util.escapeHTML(key)+'';
        } else {
          text = value;
        }
        content.html('
Result

'+text+'
');
        loader.hide();
        content.show();
        that.getBtn.click(onGet)
                   .button('toggle');
      });
    };
    this.getBtn.click(onGet);
    return this;
  },

  initPut: function() {
    var that = this;
    var tbody = this.putResult.find('tbody');
    var onPut = function() {
      that.putBtn.unbind('click', onPut)
                 .button('toggle');
      var value = that.putValue.val();
      that.node.put(null, value, null, function(key) {
        tbody.append(
          "
" +
          ""+key+"	" +
          ""+value.slice(0, 20)+(value.length > 20 ? "..." : "")+"	" +
          "
");
        that.putBtn.click(onPut)
                   .button('toggle');
      });
    };
    this.putBtn.click(onPut);
    return this;
  },

  initPing: function() {
    var that = this;
    var onPing = function() {
      that.pingBtn.unbind('click', onPing)
                  .button('toggle');
      that.pingResult.empty();
      var address = that.pingAddress.val();
      var peer = new (require('/lib/dht/bootstrap-peer'))(address);
      var ping = new (require('/lib/network/rpc/ping'))(peer);

      ping.then(function() {
        that.pingResult.html(''+
                             ''+ping.getQueried().getID()+'');
      }, function() {
        that.pingResult.html('');
      }).always(function() {
        that.pingBtn.click(onPing)
                    .button('toggle');
      });

      that.node._reactor.sendRPC(ping)
    };
    this.pingBtn.click(onPing);
    return this;
  },

};


text:
{% set title = "About" %}
{% include head/serversub.html %}

    ToiletStreamer

    Pampers Edition {{version}}

    Tribute to  & Toilets everywhere

       "May you sit in peace..."

{% include foot/foot.html %}


text:
"""
https://leetcode.com/discuss/22898/the-bottom-up-o-n-solution-would-be-better
method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned. According to the leftHeight and rightHeight of the two children, the parent node could check if the sub tree is balanced, and decides its return value.
"""

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.dfsHeight(root) != -1

    def dfsHeight(self, node):
        if not node: return 0

        leftHeight = self.dfsHeight(node.left)
        if leftHeight == -1: return -1

        rightHeight = self.dfsHeight(node.right)
        if rightHeight == -1: return -1

        if abs(leftHeight - rightHeight) > 1: return -1

        return max(leftHeight, rightHeight) + 1


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35 || SILVERLIGHT)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif

namespace Newtonsoft.Json.Tests
{
  [TestFixture]
  public class JsonConvertTest : TestFixtureBase
  {
    [Test]
    public void DeserializeObject_EmptyString()
    {
      object result = JsonConvert.DeserializeObject(string.Empty);
      Assert.IsNull(result);
    }

    [Test]
    public void DeserializeObject_Integer()
    {
      object result = JsonConvert.DeserializeObject("1");
      Assert.AreEqual(1L, result);
    }

    [Test]
    public void DeserializeObject_Integer_EmptyString()
    {
      int? value = JsonConvert.DeserializeObject<int?>("");
      Assert.IsNull(value);
    }

    [Test]
    public void DeserializeObject_Decimal_EmptyString()
    {
      decimal? value = JsonConvert.DeserializeObject<decimal?>("");
      Assert.IsNull(value);
    }

    [Test]
    public void DeserializeObject_DateTime_EmptyString()
    {
      DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
      Assert.IsNull(value);
    }

    [Test]
    public void EscapeJavaScriptString()
    {
      string result;

      result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true);
      Assert.AreEqual(@"""How now brown cow?""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true);
      Assert.AreEqual(@"""How now 'brown' cow?""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true);
      Assert.AreEqual(@"""How now <brown> cow?""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString(@"How
now brown cow?", '"', true);
      Assert.AreEqual(@"""How \r\nnow brown cow?""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true);
      Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);

      result =
        JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true);
      Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);

      result =
        JavaScriptUtils.ToEscapedJavaScriptString(
          "\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true);
      Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);

      result =
        JavaScriptUtils.ToEscapedJavaScriptString(
          "!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true);
      Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true);
      Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);

      string data =
        "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
      string expected =
        @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";

      result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true);
      Assert.AreEqual(expected, result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true);
      Assert.AreEqual(result, @"'Fred\'s cat.'");

      result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true);
      Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");

      result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true);
      Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");

      result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true);
      Assert.AreEqual(result, @"'Fred\'s ""cat"".'");

      result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress");
      Assert.AreEqual(result, @"""\u001farray<address""");
    }

    [Test]
    public void EscapeJavaScriptString_UnicodeLinefeeds()
    {
      string result;

      result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true);
      Assert.AreEqual(@"""before\u0085after""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true);
      Assert.AreEqual(@"""before\u2028after""", result);

      result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true);
      Assert.AreEqual(@"""before\u2029after""", result);
    }

    [Test]
    public void ToStringInvalid()
    {
      ExceptionAssert.Throws<ArgumentException>("Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
      () =>
      {
        JsonConvert.ToString(new Version(1, 0));
      });
    }

    [Test]
    public void GuidToString()
    {
      Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
      string json = JsonConvert.ToString(guid);
      Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
    }

    [Test]
    public void EnumToString()
    {
      string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
      Assert.AreEqual("1", json);
    }

    [Test]
    public void ObjectToString()
    {
      object value;

      value = 1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = 1.1;
      Assert.AreEqual("1.1", JsonConvert.ToString(value));

      value = 1.1m;
      Assert.AreEqual("1.1", JsonConvert.ToString(value));

      value = (float)1.1;
      Assert.AreEqual("1.1", JsonConvert.ToString(value));

      value = (short)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (long)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (byte)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (uint)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (ushort)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (sbyte)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = (ulong)1;
      Assert.AreEqual("1", JsonConvert.ToString(value));

      value = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
      Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));

      value = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
      Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));

#if !PocketPC && !NET20
      value = new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero);
      Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));

      value = new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero);
      Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif

      value = null;
      Assert.AreEqual("null", JsonConvert.ToString(value));

#if !(NETFX_CORE || PORTABLE)
      value = DBNull.Value;
      Assert.AreEqual("null", JsonConvert.ToString(value));
#endif

      value = "I am a string";
      Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));

      value = true;
      Assert.AreEqual("true", JsonConvert.ToString(value));

      value = 'c';
      Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
    }

    [Test]
    public void TestInvalidStrings()
    {
      ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.",
      () =>
      {
        string orig = @"this is a string ""that has quotes"" ";

        string serialized = JsonConvert.SerializeObject(orig);

        // *** Make string invalid by stripping \" \"
        serialized = serialized.Replace(@"\""", "\"");

        JsonConvert.DeserializeObject<string>(serialized);
      });
    }

    [Test]
    public void DeserializeValueObjects()
    {
      int i = JsonConvert.DeserializeObject<int>("1");
      Assert.AreEqual(1, i);

#if !PocketPC && !NET20
      DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
      Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif

      bool b = JsonConvert.DeserializeObject<bool>("true");
      Assert.AreEqual(true, b);

      object n = JsonConvert.DeserializeObject<object>("null");
      Assert.AreEqual(null, n);

      object u = JsonConvert.DeserializeObject<object>("undefined");
      Assert.AreEqual(null, u);
    }

    [Test]
    public void FloatToString()
    {
      Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
      Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
      Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
      Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
      Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
      Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
      Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
      Assert.AreEqual("1.0", JsonConvert.ToString(1d));
      Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
      Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
      Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
      Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
      Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
      Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
    }

    [Test]
    public void DecimalToString()
    {
      Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
      Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
      Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
      Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
      Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
      Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
      Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
      Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
      Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
      Assert.AreEqual("1.0", JsonConvert.ToString(1m));
      Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
      Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
      Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
      Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
    }

    [Test]
    public void StringEscaping()
    {
      string v = @"It's a good day
""sunshine""";

      string json = JsonConvert.ToString(v);
      Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
    }

    [Test]
    public void WriteDateTime()
    {
      DateTimeResult result = null;

      result = TestDateTime("DateTime Max", DateTime.MaxValue);
      Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
      Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
      Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);

      DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
      string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

      result = TestDateTime("DateTime Local", year2000local);
      Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
      Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
      Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);

      DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
      localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

      result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
      Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
      Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
      Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);

      DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);
      localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");

      result = TestDateTime("DateTime Local with ticks", ticksLocal);
      Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
      Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
      Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);

      DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);

      result = TestDateTime("DateTime Unspecified", year2000Unspecified);
      Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
      Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
      Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);

      DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
      string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");

      result = TestDateTime("DateTime Utc", year2000Utc);
      Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
      Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
      Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);

      DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
      utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");

      result = TestDateTime("DateTime Unix Epoc", unixEpoc);
      Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
      Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
      Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);

      result = TestDateTime("DateTime Min", DateTime.MinValue);
      Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
      Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
      Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);

      result = TestDateTime("DateTime Default", default(DateTime));
      Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
      Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
      Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
      Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
      Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
      Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);

#if !NET20
      result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
      Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
      Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
      Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
      Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
      Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
      Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
      Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);

      result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
      Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
      Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
    }

    public class DateTimeResult
    {
      public string IsoDateRoundtrip { get; set; }
      public string IsoDateLocal { get; set; }
      public string IsoDateUnspecified { get; set; }
      public string IsoDateUtc { get; set; }

      public string MsDateRoundtrip { get; set; }
      public string MsDateLocal { get; set; }
      public string MsDateUnspecified { get; set; }
      public string MsDateUtc { get; set; }
    }

    private DateTimeResult TestDateTime<T>(string name, T value)
    {
      Console.WriteLine(name);

      DateTimeResult result = new DateTimeResult();

      result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
      if (value is DateTime)
      {
        result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
        result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
        result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
      }

      result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
      if (value is DateTime)
      {
        result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
        result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
        result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
      }

      TestDateTimeFormat(value, new IsoDateTimeConverter());

#if !NETFX_CORE
      if (value is DateTime)
      {
        Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
      }
      else
      {
        Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
      }
#endif

#if !NET20
      MemoryStream ms = new MemoryStream();
      DataContractSerializer s = new DataContractSerializer(typeof(T));
      s.WriteObject(ms, value);
      string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
      Console.WriteLine(json);
#endif

      Console.WriteLine();

      return result;
    }

    private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
    {
      string date = null;

      if (value is DateTime)
      {
        date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
      }
      else
      {
#if !NET20
        date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
      }

      Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);

      if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
      {
        T parsed = JsonConvert.DeserializeObject<T>(date);
        try
        {
          Assert.AreEqual(value, parsed);
        }
        catch (Exception ex)
        {
          long valueTicks = GetTicks(value);
          long parsedTicks = GetTicks(parsed);

          valueTicks = (valueTicks/10000)*10000;

          Assert.AreEqual(valueTicks, parsedTicks);
        }
      }

      return date.Trim('"');
    }

    private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
    {
      string date = Write(value, converter);

      Console.WriteLine(converter.GetType().Name + ": " + date);

      T parsed = Read<T>(date, converter);

      try
      {
        Assert.AreEqual(value, parsed);
      }
      catch (Exception ex)
      {
        // JavaScript ticks aren't as precise, recheck after rounding
        long valueTicks = GetTicks(value);
        long parsedTicks = GetTicks(parsed);

        valueTicks = (valueTicks / 10000) * 10000;

        Assert.AreEqual(valueTicks, parsedTicks);
      }
    }

    public static long GetTicks(object value)
    {
      return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
    }

    public static string Write(object value, JsonConverter converter)
    {
      StringWriter sw = new StringWriter();
      JsonTextWriter writer = new JsonTextWriter(sw);
      converter.WriteJson(writer, value, null);

      writer.Flush();
      return sw.ToString();
    }

    public static T Read<T>(string text, JsonConverter converter)
    {
      JsonTextReader reader = new JsonTextReader(new StringReader(text));
      reader.ReadAsString();

      return (T)converter.ReadJson(reader, typeof(T), null, null);
    }

#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
    [Test]
    public void Async()
    {
      Task<string> task = null;

      task = JsonConvert.SerializeObjectAsync(42);
      task.Wait();

      Assert.AreEqual("42", task.Result);

      task = JsonConvert.SerializeObjectAsync(new[] {1, 2, 3, 4, 5}, Formatting.Indented);
      task.Wait();

      Assert.AreEqual(@"[
  1,
  2,
  3,
  4,
  5
]", task.Result);

      task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
        {
          DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        });
      task.Wait();

      Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);

      var taskObject = JsonConvert.DeserializeObjectAsync("[]");
      taskObject.Wait();

      CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);

      Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
        {
          Converters = {new VersionConverter()}
        });
      taskVersionArray.Wait();

      Version[] versionArray = (Version[])taskVersionArray.Result;

      Assert.AreEqual(1, versionArray.Length);
      Assert.AreEqual(2, versionArray[0].Major);

      Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
      taskInt.Wait();

      Assert.AreEqual(5, taskInt.Result);

      var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
        {
          Converters = {new VersionConverter()}
        });
      taskVersion.Wait();

      Assert.AreEqual(2, taskVersion.Result.Major);

      Movie p = new Movie();
      p.Name = "Existing,";

      Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
      {
        Converters = new List<JsonConverter> { new JsonSerializerTest.StringAppenderConverter() }
      });

      taskVoid.Wait();

      Assert.AreEqual("Existing,Appended", p.Name);
    }
#endif

    [Test]
    public void SerializeObjectDateTimeZoneHandling()
    {
      string json = JsonConvert.SerializeObject(
        new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
        new JsonSerializerSettings
        {
          DateTimeZoneHandling = DateTimeZoneHandling.Utc
        });

      Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
    }

    //[Test]
    public void StackOverflowTest()
    {
      StringBuilder sb = new StringBuilder();

      int depth = 900;
      for (int i = 0; i < depth; i++)
      {
        sb.Append("{'A':");
      }

      // invalid json
      sb.Append("{***}");
      for (int i = 0; i < depth; i++)
      {
        sb.Append("}");
      }

      string json = sb.ToString();
      JsonSerializer serializer = new JsonSerializer() { };
      serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
    }

    public class Nest
    {
      public Nest A { get; set; }
    }
  }
}


text:
<form id="nueva" class="smart-form"  novalidate="novalidate" method="POST" action="/bo/premios/actualizar" enctype="multipart/form-data">
							<fieldset>
							<?php $nombre_completo = $premio[0]->imagen;
			  $nombre = substr ( $premio[0]->imagen,15);?>

			  	<input name="nombre_archivo" class="hide" type="text" id="nombre_archivo" value='<?php echo $nombre;?>'>
			<input name="nombre_completo" class="hide" type="text" id="nombre_completo" value='<?php echo $nombre_completo;?>'>

									<input style="width: 25rem;" required class="hide" type="text" name="id" value='<?php echo $premio[0]->id?>' class="form-control" required>

									Nombre
									<input style="width: 25rem;" required type="text" name="nombre" value='<?php echo $premio[0]->nombre?>' class="form-control" required>

										Descripcion

											<textarea required rows="3" class="custom-scroll" name="desc_frm"><?php echo $premio[0]->descripcion?></textarea>

									Nivel de profundidad
									<input style="width: 25rem;" required type="number" name="nivel" value='<?php echo $premio[0]->nivel?>' class="form-control" required>

									Cantidad de afiliados necesarios
									<input style="width: 25rem;" required type="number" name="cantidad" value='<?php echo $premio[0]->num_afiliados?>'class="form-control" required>

								Selecione Red

									<select style="width: 25rem;" name="red" required>
										<?php foreach ($redes as $red){

											if ($red->id==$premio[0]->id_red){?>
												<option selected value="<?php echo $red->id; ?>"><?php echo $red->nombre; ?></option>
											<?php } else { ?>
												<option value="<?php echo $red->id; ?>"><?php echo $red->nombre; ?></option>
										<?php }
										} ?>
									</select>

								Frecuencia

									<select style="width: 25rem;" name="frecuencia" required>
									<?php if ($premio[0]->frecuencia=='Mensual'){?>
										<option selected value="Mensual">Mensual</option>
										<option value="Anual">Anual</option>
										<?php } else{?>
										<option value="Mensual">Mensual</option>
										<option selected value="Anual">Anual</option>
										<?php }?>
									</select>

						        		Imágen actual

<img style="max-height: 150px;" src='<?php echo $premio[0]->imagen;?>'>

									 Imágen

										 <input id="file" name="userfile"
											onchange="this.parentNode.nextSibling.value = this.value"
											type="file" multiple>Buscar
										<input id="file_frm" name="file_nme"
											placeholder='<?php echo $nombre;?>' type="text">

									Para ver el archivo que va a cargar, pulse con el puntero en el boton de "Buscar"

											<input type="submit" class="btn btn-success" style="margin-left: 6% ! important; width: 40%;" id="boton_subir" value="Agregar">

							</fieldset>

						</form>


text:
package nz.ac.waikato.modeljunit.examples;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.ArrayList;

/** A simple implementation of a set of strings.
 *  It does not allow null strings in the set.
 *
 *  The purpose of this class is just to be an example implementation
 *  of Set<String>, which we can run tests on, insert errors into,
 *  measure the coverage of the tests etc.
 *
 *  This class has an intentional bug: the equals method contains an
 *  off-by-one error.
 *
 * @author marku  April 2007 for COMP551
 *
 */
public class StringSetBuggy extends AbstractSet<String>
{
  private ArrayList<String> contents = new ArrayList<String>();

  @Override
  public Iterator<String> iterator()
  {
    return contents.iterator();
  }

  @Override
  public int size()
  {
    return contents.size();
  }

  @Override
  public boolean equals(Object arg0)
  {
    boolean same = false;
    if (arg0 instanceof Set) {
      Set<String> other = (Set<String>) arg0;
      same = size() == other.size();
      // NOTE: this loop is intended to have a bug: i>0 should be i>=0.
      for (int i = contents.size() - 1; same && i > 0; i--) {
        if (!other.contains(contents.get(i)))
          same = false;
      }
    }
    return same;
  }

  @Override
  public void clear()
  {
    contents.clear();
  }

  @Override
  public boolean contains(Object arg0)
  {
    for (int i = contents.size() - 1; i >= 0; i--) {
      if (contents.get(i).equals(arg0))
        return true; // return immediately
    }
    return false; // none match
  }

  @Override
  public boolean isEmpty()
  {
    return contents.size() == 0;
  }

  @Override
  public boolean add(String e)
  {
    if (e == null) {
      throw new NullPointerException();
    }
    if (contents.contains(e)) {
      return false;
    }
    else {
      return contents.add(e); // always adds to end
    }
  }

  @Override
  public boolean remove(Object o)
  {
    if (contents.isEmpty())
      return false;
    else
      return contents.remove(o);
  }
}


text:
<?php

namespace MediaVorus;

use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser;
use MediaVorus\Utils\RawImageMimeTypeGuesser;
use MediaVorus\Utils\PostScriptMimeTypeGuesser;
use MediaVorus\Utils\AudioMimeTypeGuesser;
use MediaVorus\Utils\VideoMimeTypeGuesser;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static $registered = false;

    public function setUp()
    {
        if (!static::$registered) {
            $guesser = MimeTypeGuesser::getInstance();

            $guesser->register(new FileBinaryMimeTypeGuesser());
            $guesser->register(new RawImageMimeTypeGuesser());
            $guesser->register(new PostScriptMimeTypeGuesser());
            $guesser->register(new AudioMimeTypeGuesser());
            $guesser->register(new VideoMimeTypeGuesser());

            static::$registered = true;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace ShlinkioTest\Shlink\CLI\Command\Api;

use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\CLI\Command\Api\ListKeysCommand;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class ListKeysCommandTest extends TestCase
{
    private CommandTester $commandTester;
    private ObjectProphecy $apiKeyService;

    public function setUp(): void
    {
        $this->apiKeyService = $this->prophesize(ApiKeyServiceInterface::class);
        $command = new ListKeysCommand($this->apiKeyService->reveal());
        $app = new Application();
        $app->add($command);
        $this->commandTester = new CommandTester($command);
    }

    /** @test */
    public function everythingIsListedIfEnabledOnlyIsNotProvided(): void
    {
        $this->apiKeyService->listKeys(false)->willReturn([
            new ApiKey(),
            new ApiKey(),
            new ApiKey(),
        ])->shouldBeCalledOnce();

        $this->commandTester->execute([]);
        $output = $this->commandTester->getDisplay();

        $this->assertStringContainsString('Key', $output);
        $this->assertStringContainsString('Is enabled', $output);
        $this->assertStringContainsString(' +++ ', $output);
        $this->assertStringNotContainsString(' --- ', $output);
        $this->assertStringContainsString('Expiration date', $output);
    }

    /** @test */
    public function onlyEnabledKeysAreListedIfEnabledOnlyIsProvided(): void
    {
        $this->apiKeyService->listKeys(true)->willReturn([
            (new ApiKey())->disable(),
            new ApiKey(),
        ])->shouldBeCalledOnce();

        $this->commandTester->execute([
            '--enabledOnly' => true,
        ]);
        $output = $this->commandTester->getDisplay();

        $this->assertStringContainsString('Key', $output);
        $this->assertStringNotContainsString('Is enabled', $output);
        $this->assertStringNotContainsString(' +++ ', $output);
        $this->assertStringNotContainsString(' --- ', $output);
        $this->assertStringContainsString('Expiration date', $output);
    }
}


text:
<?php

class Yo {

    protected $_apiKey;

    private $urls = array(
        'all' => 'http://api.justyo.co/yoall/',
        'user' => 'http://api.justyo.co/yo/',
        'subscribers' => 'http://api.justyo.co/subscribers_count/'
    );

    public function __construct($apiKey) {
        $this->_apiKey = $apiKey;
    }

    public function user($username, $link = null) {
        if ($username != '') {
            $this->processRequest($username, $link, null);
        }
    }

    public function userWithLocation($username, $location = null) {
        if ($username != '') {
            $this->processRequest($username, null, $location);
        }
    }

    public function all($link = null) {
        $this->processRequest($username = null, $link, null);
    }

    public function subscribers() {
        $url = $this->urls['subscribers'];

        $url .= '?api_token=' . $this->_apiKey;

        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
        );

        $curl = curl_init();
        curl_setopt_array($curl, $options);
        $result = curl_exec($curl);
        curl_close($curl);

        // Result is in format {"result": 1 }
        $result = json_decode($result, true);

        if (isset($result['result'])) {
            return $result['result'];
        }

        return false;
    }

    private function processRequest($username = null, $link = null, $location = null) {
        $postFields = array(
            'api_token' => $this->_apiKey
        );

        $url = $this->urls['all'];

        if ($username != null) {
            $postFields['username'] = $username;
            $url = $this->urls['user'];
        }

        if ($link != null) {
        	$postFields['link'] = $link;
        }

        if ($location != null) {
            $postFields['location'] = $location;
        }

        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postFields
        );

        $result = '';

        $curl = curl_init();
        curl_setopt_array($curl, $options);
        $result = curl_exec($curl);
        curl_close($curl);

        return $result;
    }

}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > The Engraved Lighter

						Expand All | Collapse All

The Engraved Lighter

  He was going to move to LA in a month. He was going to start a new life. He was excited. His girlfriend was excited, too. She couldn't wait to go to Disneyland and visit Hollywood. His birthday was a week away. She bought him an expensive cigarette lighter. She got it engraved. The engraving said, "To Ross, with Love, from Trish." On his birthday, she gave him his gift. He opened the box. He looked at the lighter. He loved it. "This is a beautiful lighter," he said. She told him to look on the other side. He turned it over. He saw the engraving. His face changed. "What's the matter?" she asked. He said she shouldn't have spent the extra money to engrave it. A week later he told her the truth. He wanted to break up. He moved to LA without her. He never used the lighter.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package main

// TODO: This does not support recursive embedded interfaces.
// TODO: This does not support embedding package-local interfaces in a separate file.

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"go/token"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"unicode"

	"github.com/golang/mock/mockgen/model"

	toolsimports "golang.org/x/tools/imports"
)

const (
	gomockImportPath = "github.com/golang/mock/gomock"
)

var (
	version = ""
	commit  = "none"
	date    = "unknown"
)

var (
	source          = flag.String("source", "", "(source mode) Input Go source file; enables source mode.")
	destination     = flag.String("destination", "", "Output file; defaults to stdout.")
	mockNames       = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.")
	packageOut      = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.")
	selfPackage     = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.")
	writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.")
	copyrightFile   = flag.String("copyright_file", "", "Copyright file used to add copyright header")

	debugParser = flag.Bool("debug_parser", false, "Print out parser results only.")
	showVersion = flag.Bool("version", false, "Print version.")
)

func main() {
	flag.Usage = usage
	flag.Parse()

	if *showVersion {
		printVersion()
		return
	}

	var pkg *model.Package
	var err error
	var packageName string
	if *source != "" {
		pkg, err = sourceMode(*source)
	} else {
		if flag.NArg() != 2 {
			usage()
			log.Fatal("Expected exactly two arguments")
		}
		packageName = flag.Arg(0)
		if packageName == "." {
			dir, err := os.Getwd()
			if err != nil {
				log.Fatalf("Get current directory failed: %v", err)
			}
			packageName, err = packageNameOfDir(dir)
			if err != nil {
				log.Fatalf("Parse package name failed: %v", err)
			}
		}
		pkg, err = reflectMode(packageName, strings.Split(flag.Arg(1), ","))
	}
	if err != nil {
		log.Fatalf("Loading input failed: %v", err)
	}

	if *debugParser {
		pkg.Print(os.Stdout)
		return
	}

	dst := os.Stdout
	if len(*destination) > 0 {
		if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
			log.Fatalf("Unable to create directory: %v", err)
		}
		f, err := os.Create(*destination)
		if err != nil {
			log.Fatalf("Failed opening destination file: %v", err)
		}
		defer f.Close()
		dst = f
	}

	outputPackageName := *packageOut
	if outputPackageName == "" {
		// pkg.Name in reflect mode is the base name of the import path,
		// which might have characters that are illegal to have in package names.
		outputPackageName = "mock_" + sanitize(pkg.Name)
	}

	// outputPackagePath represents the fully qualified name of the package of
	// the generated code. Its purposes are to prevent the module from importing
	// itself and to prevent qualifying type names that come from its own
	// package (i.e. if there is a type called X then we want to print "X" not
	// "package.X" since "package" is this package). This can happen if the mock
	// is output into an already existing package.
	outputPackagePath := *selfPackage
	if outputPackagePath == "" && *destination != "" {
		dstPath, err := filepath.Abs(filepath.Dir(*destination))
		if err != nil {
			log.Fatalf("Unable to determine destination file path: %v", err)
		}
		outputPackagePath, err = parsePackageImport(dstPath)
		if err != nil {
			log.Fatalf("Unable to determine destination file path: %v", err)
		}
	}

	g := new(generator)
	if *source != "" {
		g.filename = *source
	} else {
		g.srcPackage = packageName
		g.srcInterfaces = flag.Arg(1)
	}
	g.destination = *destination

	if *mockNames != "" {
		g.mockNames = parseMockNames(*mockNames)
	}
	if *copyrightFile != "" {
		header, err := ioutil.ReadFile(*copyrightFile)
		if err != nil {
			log.Fatalf("Failed reading copyright file: %v", err)
		}

		g.copyrightHeader = string(header)
	}
	if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil {
		log.Fatalf("Failed generating mock: %v", err)
	}
	if _, err := dst.Write(g.Output()); err != nil {
		log.Fatalf("Failed writing to destination: %v", err)
	}
}

func parseMockNames(names string) map[string]string {
	mocksMap := make(map[string]string)
	for _, kv := range strings.Split(names, ",") {
		parts := strings.SplitN(kv, "=", 2)
		if len(parts) != 2 || parts[1] == "" {
			log.Fatalf("bad mock names spec: %v", kv)
		}
		mocksMap[parts[0]] = parts[1]
	}
	return mocksMap
}

func usage() {
	_, _ = io.WriteString(os.Stderr, usageText)
	flag.PrintDefaults()
}

const usageText = `mockgen has two modes of operation: source and reflect.

Source mode generates mock interfaces from a source file.
It is enabled by using the -source flag. Other flags that
may be useful in this mode are -imports and -aux_files.
Example:
	mockgen -source=foo.go [other options]

Reflect mode generates mock interfaces by building a program
that uses reflection to understand interfaces. It is enabled
by passing two non-flag arguments: an import path, and a
comma-separated list of symbols.
Example:
	mockgen database/sql/driver Conn,Driver

`

type generator struct {
	buf                       bytes.Buffer
	indent                    string
	mockNames                 map[string]string // may be empty
	filename                  string            // may be empty
	destination               string            // may be empty
	srcPackage, srcInterfaces string            // may be empty
	copyrightHeader           string

	packageMap map[string]string // map from import path to package name
}

func (g *generator) p(format string, args ...interface{}) {
	fmt.Fprintf(&g.buf, g.indent+format+"\n", args...)
}

func (g *generator) in() {
	g.indent += "\t"
}

func (g *generator) out() {
	if len(g.indent) > 0 {
		g.indent = g.indent[0 : len(g.indent)-1]
	}
}

func removeDot(s string) string {
	if len(s) > 0 && s[len(s)-1] == '.' {
		return s[0 : len(s)-1]
	}
	return s
}

// sanitize cleans up a string to make a suitable package name.
func sanitize(s string) string {
	t := ""
	for _, r := range s {
		if t == "" {
			if unicode.IsLetter(r) || r == '_' {
				t += string(r)
				continue
			}
		} else {
			if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
				t += string(r)
				continue
			}
		}
		t += "_"
	}
	if t == "_" {
		t = "x"
	}
	return t
}

func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPackagePath string) error {
	if outputPkgName != pkg.Name && *selfPackage == "" {
		// reset outputPackagePath if it's not passed in through -self_package
		outputPackagePath = ""
	}

	if g.copyrightHeader != "" {
		lines := strings.Split(g.copyrightHeader, "\n")
		for _, line := range lines {
			g.p("// %s", line)
		}
		g.p("")
	}

	g.p("// Code generated by MockGen. DO NOT EDIT.")
	if g.filename != "" {
		g.p("// Source: %v", g.filename)
	} else {
		g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces)
	}
	g.p("")

	// Get all required imports, and generate unique names for them all.
	im := pkg.Imports()
	im[gomockImportPath] = true

	// Only import reflect if it's used. We only use reflect in mocked methods
	// so only import if any of the mocked interfaces have methods.
	for _, intf := range pkg.Interfaces {
		if len(intf.Methods) > 0 {
			im["reflect"] = true
			break
		}
	}

	// Sort keys to make import alias generation predictable
	sortedPaths := make([]string, len(im))
	x := 0
	for pth := range im {
		sortedPaths[x] = pth
		x++
	}
	sort.Strings(sortedPaths)

	packagesName := createPackageMap(sortedPaths)

	g.packageMap = make(map[string]string, len(im))
	localNames := make(map[string]bool, len(im))
	for _, pth := range sortedPaths {
		base, ok := packagesName[pth]
		if !ok {
			base = sanitize(path.Base(pth))
		}

		// Local names for an imported package can usually be the basename of the import path.
		// A couple of situations don't permit that, such as duplicate local names
		// (e.g. importing "html/template" and "text/template"), or where the basename is
		// a keyword (e.g. "foo/case").
		// try base0, base1, ...
		pkgName := base
		i := 0
		for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() {
			pkgName = base + strconv.Itoa(i)
			i++
		}

		// Avoid importing package if source pkg == output pkg
		if pth == pkg.PkgPath && outputPackagePath == pkg.PkgPath {
			continue
		}

		g.packageMap[pth] = pkgName
		localNames[pkgName] = true
	}

	if *writePkgComment {
		g.p("// Package %v is a generated GoMock package.", outputPkgName)
	}
	g.p("package %v", outputPkgName)
	g.p("")
	g.p("import (")
	g.in()
	for pkgPath, pkgName := range g.packageMap {
		if pkgPath == outputPackagePath {
			continue
		}
		g.p("%v %q", pkgName, pkgPath)
	}
	for _, pkgPath := range pkg.DotImports {
		g.p(". %q", pkgPath)
	}
	g.out()
	g.p(")")

	for _, intf := range pkg.Interfaces {
		if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil {
			return err
		}
	}

	return nil
}

// The name of the mock type to use for the given interface identifier.
func (g *generator) mockName(typeName string) string {
	if mockName, ok := g.mockNames[typeName]; ok {
		return mockName
	}

	return "Mock" + typeName
}

func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error {
	mockType := g.mockName(intf.Name)

	g.p("")
	g.p("// %v is a mock of %v interface.", mockType, intf.Name)
	g.p("type %v struct {", mockType)
	g.in()
	g.p("ctrl     *gomock.Controller")
	g.p("recorder *%vMockRecorder", mockType)
	g.out()
	g.p("}")
	g.p("")

	g.p("// %vMockRecorder is the mock recorder for %v.", mockType, mockType)
	g.p("type %vMockRecorder struct {", mockType)
	g.in()
	g.p("mock *%v", mockType)
	g.out()
	g.p("}")
	g.p("")

	// TODO: Re-enable this if we can import the interface reliably.
	// g.p("// Verify that the mock satisfies the interface at compile time.")
	// g.p("var _ %v = (*%v)(nil)", typeName, mockType)
	// g.p("")

	g.p("// New%v creates a new mock instance.", mockType)
	g.p("func New%v(ctrl *gomock.Controller) *%v {", mockType, mockType)
	g.in()
	g.p("mock := &%v{ctrl: ctrl}", mockType)
	g.p("mock.recorder = &%vMockRecorder{mock}", mockType)
	g.p("return mock")
	g.out()
	g.p("}")
	g.p("")

	// XXX: possible name collision here if someone has EXPECT in their interface.
	g.p("// EXPECT returns an object that allows the caller to indicate expected use.")
	g.p("func (m *%v) EXPECT() *%vMockRecorder {", mockType, mockType)
	g.in()
	g.p("return m.recorder")
	g.out()
	g.p("}")

	g.GenerateMockMethods(mockType, intf, outputPackagePath)

	return nil
}

type byMethodName []*model.Method

func (b byMethodName) Len() int           { return len(b) }
func (b byMethodName) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name }

func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride string) {
	sort.Sort(byMethodName(intf.Methods))
	for _, m := range intf.Methods {
		g.p("")
		_ = g.GenerateMockMethod(mockType, m, pkgOverride)
		g.p("")
		_ = g.GenerateMockRecorderMethod(mockType, m)
	}
}

func makeArgString(argNames, argTypes []string) string {
	args := make([]string, len(argNames))
	for i, name := range argNames {
		// specify the type only once for consecutive args of the same type
		if i+1 < len(argTypes) && argTypes[i] == argTypes[i+1] {
			args[i] = name
		} else {
			args[i] = name + " " + argTypes[i]
		}
	}
	return strings.Join(args, ", ")
}

// GenerateMockMethod generates a mock method implementation.
// If non-empty, pkgOverride is the package in which unqualified types reside.
func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error {
	argNames := g.getArgNames(m)
	argTypes := g.getArgTypes(m, pkgOverride)
	argString := makeArgString(argNames, argTypes)

	rets := make([]string, len(m.Out))
	for i, p := range m.Out {
		rets[i] = p.Type.String(g.packageMap, pkgOverride)
	}
	retString := strings.Join(rets, ", ")
	if len(rets) > 1 {
		retString = "(" + retString + ")"
	}
	if retString != "" {
		retString = " " + retString
	}

	ia := newIdentifierAllocator(argNames)
	idRecv := ia.allocateIdentifier("m")

	g.p("// %v mocks base method.", m.Name)
	g.p("func (%v *%v) %v(%v)%v {", idRecv, mockType, m.Name, argString, retString)
	g.in()
	g.p("%s.ctrl.T.Helper()", idRecv)

	var callArgs string
	if m.Variadic == nil {
		if len(argNames) > 0 {
			callArgs = ", " + strings.Join(argNames, ", ")
		}
	} else {
		// Non-trivial. The generated code must build a []interface{},
		// but the variadic argument may be any type.
		idVarArgs := ia.allocateIdentifier("varargs")
		idVArg := ia.allocateIdentifier("a")
		g.p("%s := []interface{}{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "))
		g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1])
		g.in()
		g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg)
		g.out()
		g.p("}")
		callArgs = ", " + idVarArgs + "..."
	}
	if len(m.Out) == 0 {
		g.p(`%v.ctrl.Call(%v, %q%v)`, idRecv, idRecv, m.Name, callArgs)
	} else {
		idRet := ia.allocateIdentifier("ret")
		g.p(`%v := %v.ctrl.Call(%v, %q%v)`, idRet, idRecv, idRecv, m.Name, callArgs)

		// Go does not allow "naked" type assertions on nil values, so we use the two-value form here.
		// The value of that is either (x.(T), true) or (Z, false), where Z is the zero value for T.
		// Happily, this coincides with the semantics we want here.
		retNames := make([]string, len(rets))
		for i, t := range rets {
			retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i))
			g.p("%s, _ := %s[%d].(%s)", retNames[i], idRet, i, t)
		}
		g.p("return " + strings.Join(retNames, ", "))
	}

	g.out()
	g.p("}")
	return nil
}

func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) error {
	argNames := g.getArgNames(m)

	var argString string
	if m.Variadic == nil {
		argString = strings.Join(argNames, ", ")
	} else {
		argString = strings.Join(argNames[:len(argNames)-1], ", ")
	}
	if argString != "" {
		argString += " interface{}"
	}

	if m.Variadic != nil {
		if argString != "" {
			argString += ", "
		}
		argString += fmt.Sprintf("%s ...interface{}", argNames[len(argNames)-1])
	}

	ia := newIdentifierAllocator(argNames)
	idRecv := ia.allocateIdentifier("mr")

	g.p("// %v indicates an expected call of %v.", m.Name, m.Name)
	g.p("func (%s *%vMockRecorder) %v(%v) *gomock.Call {", idRecv, mockType, m.Name, argString)
	g.in()
	g.p("%s.mock.ctrl.T.Helper()", idRecv)

	var callArgs string
	if m.Variadic == nil {
		if len(argNames) > 0 {
			callArgs = ", " + strings.Join(argNames, ", ")
		}
	} else {
		if len(argNames) == 1 {
			// Easy: just use ... to push the arguments through.
			callArgs = ", " + argNames[0] + "..."
		} else {
			// Hard: create a temporary slice.
			idVarArgs := ia.allocateIdentifier("varargs")
			g.p("%s := append([]interface{}{%s}, %s...)",
				idVarArgs,
				strings.Join(argNames[:len(argNames)-1], ", "),
				argNames[len(argNames)-1])
			callArgs = ", " + idVarArgs + "..."
		}
	}
	g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, m.Name, callArgs)

	g.out()
	g.p("}")
	return nil
}

func (g *generator) getArgNames(m *model.Method) []string {
	argNames := make([]string, len(m.In))
	for i, p := range m.In {
		name := p.Name
		if name == "" || name == "_" {
			name = fmt.Sprintf("arg%d", i)
		}
		argNames[i] = name
	}
	if m.Variadic != nil {
		name := m.Variadic.Name
		if name == "" {
			name = fmt.Sprintf("arg%d", len(m.In))
		}
		argNames = append(argNames, name)
	}
	return argNames
}

func (g *generator) getArgTypes(m *model.Method, pkgOverride string) []string {
	argTypes := make([]string, len(m.In))
	for i, p := range m.In {
		argTypes[i] = p.Type.String(g.packageMap, pkgOverride)
	}
	if m.Variadic != nil {
		argTypes = append(argTypes, "..."+m.Variadic.Type.String(g.packageMap, pkgOverride))
	}
	return argTypes
}

type identifierAllocator map[string]struct{}

func newIdentifierAllocator(taken []string) identifierAllocator {
	a := make(identifierAllocator, len(taken))
	for _, s := range taken {
		a[s] = struct{}{}
	}
	return a
}

func (o identifierAllocator) allocateIdentifier(want string) string {
	id := want
	for i := 2; ; i++ {
		if _, ok := o[id]; !ok {
			o[id] = struct{}{}
			return id
		}
		id = want + "_" + strconv.Itoa(i)
	}
}

// Output returns the generator's output, formatted in the standard Go style.
func (g *generator) Output() []byte {
	src, err := toolsimports.Process(g.destination, g.buf.Bytes(), nil)
	if err != nil {
		log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String())
	}
	return src
}

// createPackageMap returns a map of import path to package name
// for specified importPaths.
func createPackageMap(importPaths []string) map[string]string {
	var pkg struct {
		Name       string
		ImportPath string
	}
	pkgMap := make(map[string]string)
	b := bytes.NewBuffer(nil)
	args := []string{"list", "-json"}
	args = append(args, importPaths...)
	cmd := exec.Command("go", args...)
	cmd.Stdout = b
	cmd.Run()
	dec := json.NewDecoder(b)
	for dec.More() {
		err := dec.Decode(&pkg)
		if err != nil {
			log.Printf("failed to decode 'go list' output: %v", err)
			continue
		}
		pkgMap[pkg.ImportPath] = pkg.Name
	}
	return pkgMap
}

func printVersion() {
	if version != "" {
		fmt.Printf("v%s\nCommit: %s\nDate: %s\n", version, commit, date)
	} else {
		printModuleVersion()
	}
}


text:
(function() {
  'use strict';
  angular.module('utils', [])
    .factory('$localstorage', LocalStorage);

  LocalStorage.$inject = ['$log', '$window'];
  function LocalStorage($log, $window) {
    $log.debug('loading $localstorage');

    return {
      get: get,
      set: set,
      getObject: getObject,
      setObject: setObject,
      clear: clear
    };

    function get(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    }
    function set(key, value) {
      $window.localStorage[key] = value;

    }
    function getObject(key) {
      var object = $window.localStorage[key];

      return object ? JSON.parse(object) : null;
    }
    function setObject(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    }
    function clear() {
      $window.localStorage.clear();
    }
  }
})();