text:
'use strict';

define(['angular', 'common'], function (angular) {
  angular.module('jakdukCommon', [])
    .config(['$interpolateProvider', '$httpProvider', function ($interpolateProvider, $httpProvider) {
      $interpolateProvider.startSymbol('{%');
      $interpolateProvider.endSymbol('%}');
      $httpProvider.defaults.withCredentials = true;
    }])
    // mongodb id의 앞 8자리(16진수)로 Date 객체 생성.
    .filter('dateFromObjectId', function () {
      return function (objectId) {
        return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
      };
    })
    // mongodb id의 앞 8자리(16진수)를 int로 변환.
    .filter('intFromObjectId', function () {
      return function (objectId) {
        return parseInt(objectId.substring(0, 8), 16) * 1000;
      };
    })
    .filter('objectIdFromDate', function () {
      return function (date) {
        return Math.floor(date.getTime() / 1000).toString(16) + '0000000000000000';
      };
    })
    .filter('filesize', function () {
      return function (bytes, precision) {
        if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) {
          return '-';
        }
        if (typeof precision === 'undefined') {
          precision = 1;
        }

        var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
        var number = Math.floor(Math.log(bytes) / Math.log(1024));

        return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number];
      };
    })
    .controller('headerCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window) {
      var port = $location.port();
      var prefix = $location.protocol() + '://' + $location.host();
      var prefixPath = (port === 80 || port === 443) ? prefix : prefix + ':' + $location.port();
      var absUrl = $location.absUrl();
      var path = absUrl.slice(prefixPath.length);

      $scope.isActive = function (viewLocation) {
        return path.match(viewLocation);
      };

      $scope.btnEnterOnHeaderSearch = function () {
        if ($scope.searchOnHeader.trim() < 1) {
          return;
        }

        $window.location = '/search?q=' + $scope.searchOnHeader.trim() + '&w=PO;CO;GA;';
      };

      $scope.toggleSearchOnHeader = function () {
        $scope.searchFocusOnHeader = !$scope.searchFocusOnHeader;
      };
    }])
    .directive('focusy', [function () {
      return {
        require: 'ngModel',
        restrict: 'A',
        scope: {
          focusy: '='
        },
        link: function (scope, element) {
          scope.$watch('focusy', function (newValue) {
            if (newValue) {
              element.focus();
            }
          });
        }
      };
    }])
    .directive('autofillFixer', [function () {
      return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ngModel) {
          if (elem.val()) {
            ngModel.$setViewValue(elem.val());
          }
        }
      };
    }])
    .directive('ngThumb', ['$window', function($window) {
      var helper = {
        support: !!($window.FileReader && $window.CanvasRenderingContext2D),
        isFile: function(item) {
          return angular.isObject(item) && item instanceof $window.File;
        },
        isImage: function(file) {
          var type =  '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
          return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
      };

      return {
        restrict: 'A',
        template: '<canvas/>',
        link: function(scope, element, attributes) {
          if (!helper.support) return;

          var params = scope.$eval(attributes.ngThumb);

          if (!helper.isFile(params.file)) return;
          if (!helper.isImage(params.file)) return;

          var canvas = element.find('canvas');
          var reader = new FileReader();

          reader.onload = onLoadFile;
          reader.readAsDataURL(params.file);

          function onLoadFile(event) {
            var img = new Image();
            img.onload = onLoadImage;
            img.src = event.target.result;
          }

          function onLoadImage() {
            var width = params.width || this.width / this.height * params.height;
            var height = params.height || this.height / this.width * params.width;
            canvas.attr({ width: width, height: height });
            canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
          }
        }
      };
    }]);;

  window.Jakduk = {
    BoardCommentSize: 30,
    BoardCommentContentLengthMin: 3, // 게시판 댓글 입력 가능한 최소한의 문자열 수
    BoardCommentContentLengthMax: 800, // 게시판 댓글 입력 가능한 최대 문자열 수
    SummernoteContentsMinSize: 5,
    FormEmailLengthMin: 6,
    FormEmailLengthMax: 30,
    FormPasswordLengthMin: 4,
    FormPasswordLengthMax: 20,
    FormUsernameLengthMin: 2,
    FormUsernameLengthMax: 20,
    ItemsPerPageOnSearch: 10, // 찾기에서 페이지 당 아이템 수
    ItemsPerPageOnSearchGallery: 12, // 찾기에서 사진첩의 페이지 당 아이템 수
    ItemsPerPageOnGallery: 24, // 사진첩에서 한번 로딩할때 가져오는 그림의 수
    ItemsPerPageOnBoardComments: 10,
    isEmpty: function (str) {
      return !str;
    },
    needLogin: function (message) {
      if (window.confirm(message)) {
        window.location = '/board/free/write';
      }
    }
  };

  return window.Jakduk;
});


text:
module KeywordsHelper
  def render_keyword_link(keyword)
    label = conditional_strikethrough(keyword.keyword, !keyword.published?)
    link_to label, edit_admin_keyword_path(keyword)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package mem

import (
	"os/exec"
	"strconv"
	"strings"
	"syscall"
)

// Runs vm_stat and returns Free and inactive pages
func getVMStat(vms *VirtualMemoryStat) error {
	vm_stat, err := exec.LookPath("vm_stat")
	if err != nil {
		return err
	}
	out, err := invoke.Command(vm_stat)
	if err != nil {
		return err
	}
	return parseVMStat(string(out), vms)
}

func parseVMStat(out string, vms *VirtualMemoryStat) error {
	var err error

	lines := strings.Split(out, "\n")
	pagesize := uint64(syscall.Getpagesize())
	for _, line := range lines {
		fields := strings.Split(line, ":")
		if len(fields) < 2 {
			continue
		}
		key := strings.TrimSpace(fields[0])
		value := strings.Trim(fields[1], " .")
		switch key {
		case "Pages free":
			free, e := strconv.ParseUint(value, 10, 64)
			if e != nil {
				err = e
			}
			vms.Free = free * pagesize
		case "Pages inactive":
			inactive, e := strconv.ParseUint(value, 10, 64)
			if e != nil {
				err = e
			}
			vms.Inactive = inactive * pagesize
		case "Pages active":
			active, e := strconv.ParseUint(value, 10, 64)
			if e != nil {
				err = e
			}
			vms.Active = active * pagesize
		case "Pages wired down":
			wired, e := strconv.ParseUint(value, 10, 64)
			if e != nil {
				err = e
			}
			vms.Wired = wired * pagesize
		}
	}
	return err
}

// VirtualMemory returns VirtualmemoryStat.
func VirtualMemory() (*VirtualMemoryStat, error) {
	ret := &VirtualMemoryStat{}

	total, err := getHwMemsize()
	if err != nil {
		return nil, err
	}
	err = getVMStat(ret)
	if err != nil {
		return nil, err
	}

	ret.Available = ret.Free + ret.Inactive
	ret.Total = total

	ret.Used = ret.Total - ret.Available
	ret.UsedPercent = 100 * float64(ret.Used) / float64(ret.Total)

	return ret, nil
}


text:
import debug from 'debug';
import gulp from 'gulp';
import babel from 'gulp-babel';
import plumber from 'gulp-plumber';
import config from '../config';
import { changed } from '../plugin/changed';
import { log } from '../plugin/log';
const debugLog = debug('mppack:task:js');

export const javascript = () => {
  const { javascript, output } = config;
  debugLog('output: %s, javascript:%j', output, javascript);

  return gulp
    .src(javascript)
    .pipe(plumber())
    .pipe(changed())
    .pipe(log({ prefix: 'js' }))
    .pipe(
      babel({
        plugins: ['mpapp-pack']
      })
    )
    .pipe(gulp.dest(output));
};


text:
"""A light REST API to query the backed data.

This is not production-quality software, but intended as a proof-of-concept.
This is intentionally mimiking the Google Maps Engine API.
Currently supports only the Tables.features list operation at url:
/tables/{db}:{table}/features

Supports the following path parameters:
* id

Supports the following query parameters:
* limit
* orderBy
* select
* where

All other query parameters are ignored.
"""

import calendar, datetime, json
import logging
import os
import traceback
import MySQLdb

# flask, geojson,geomet and sqlparse are external dependencies.
# Install them by running pip install -r requirements.txt -t lib
import flask
import geojson
import geomet.wkt
import sqlparse

import datetime
import decimal

# This is your CloudSQL instance
_INSTANCE = 'titan-sci:capasgeograficas'
_GEOMETRY_FIELD = 'SHAPE'
# This is the host to connect to in the dev server.
# This can be the IP address of your CloudSQL server, if you want to test that.
_MYSQL_HOST = 'localhost'
_MYSQL_USER = 'davasqueza'
_MYSQL_PASSWORD = '7oTYDkbdg1'

# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
app = flask.Flask(__name__)

def outputJSON(obj):
    """Default JSON serializer."""
    if isinstance(obj, datetime.date):
        dateInfo=str(obj).split("-")
        date={}
        date["year"]=int(dateInfo[0])
        date["month"]=int(dateInfo[1])
        date["day"]=int(dateInfo[2])
        obj=date
    elif isinstance(obj, datetime.timedelta):
        hourInfo=str(obj).split(":")
        time={}
        time["hour"]=int(hourInfo[0])
        time["minute"]=int(hourInfo[1])
        time["second"]=int(hourInfo[2])
        obj=time
    elif isinstance(obj, decimal.Decimal):
        obj = int(obj)
    elif not isinstance(obj, int) and not isinstance(obj, float):
        obj=str(obj)
    #else:
    #    obj=str(obj)
    return obj

@app.route('/tables/<database>:<table>/features')
def do_features_list(database, table):
    """Handle the parsing of the request and return the geojson.

    This routes all the /tables/... requests to the handler.
    See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route

    Args:
      database: The name of the database to use, this is picked from the URL.
      table: The database table to query from, this is picked from the URL.
    Returns:
      A flask.Response object with the GeoJSON to be returned, or an error JSON.
    """
    where = flask.request.args.get('where', default='true')
    select = flask.request.args.get('select', default='')
    limit = flask.request.args.get('limit')
    order_by = flask.request.args.get('orderBy')
    encoding = flask.request.args.get('encoding', default='utf8')

    try:
      f = Features(_INSTANCE, database)
    except MySQLdb.OperationalError as e:
      error = {'error': 'Database Error %s' % str(e)}
      return flask.Response(response=json.dumps(error),
                            mimetype='application/json',
                            status=500)

    feature_collection = f.list(table, select, where,
                                limit=limit, order_by=order_by)
    if 'error' in feature_collection:
        return flask.Response(response=json.dumps(feature_collection),
                              mimetype='application/json',
                              status=500)
    else:
		response = flask.Response(response=geojson.dumps(feature_collection, sort_keys=True, encoding=encoding, default=outputJSON),mimetype='application/json',status=200)
		response.headers.add("Access-Control-Allow-Origin", "*")
		return response

@app.route('/pip/<database>:<table>')
def do_pip(database, table):
    """Handle the parsing of the point in polygon request and return a polygon.

    This routes all the /pip/... requests to the handler.
    See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route

    Args:
      database: The name of the database to use, this is picked from the URL.
      table: The database table to query from, this is picked from the URL.
    Returns:
      A flask.Response object with the GeoJSON to be returned, or an error JSON.
    """
    lat = float(flask.request.args.get('lat', default=0.0))
    lng = float(flask.request.args.get('lng', default=0.0))
    select = flask.request.args.get('select', default='')
    encoding = flask.request.args.get('encoding', default='utf8')
    try:
      pip = PointInPolygon(_INSTANCE, database, table)
    except MySQLdb.OperationalError as e:
      error = {'error': 'Database Error %s' % str(e)}
      return flask.Response(response=json.dumps(error),
                            mimetype='application/json',
                            status=500)

    polygon = pip.pip(lat, lng, select)
    if 'error' in polygon:
        return flask.Response(response=json.dumps(polygon),
                              mimetype='application/json',
                              status=500)
    else:
		response = flask.Response(response=geojson.dumps(polygon, sort_keys=True , encoding=encoding, default=outputJSON),mimetype='application/json',status=200)
		response.headers.add("Access-Control-Allow-Origin", "*")
		return response

@app.errorhandler(404)
def page_not_found(_):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404

@app.errorhandler(500)
def internal_error(_):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error: {}'.format(traceback.format_exc()), 500

class Features(object):
    """Implements the tables endpoint in the REST API.

    This class handles all tables/{db}:{table}/features requests.
    """

    def __init__(self, instance, database):
        """Set up a database connection to the cloud SQL server.

        Args:
          instance: The name of the CloudSQL instance.
          database: The name of the database to use.
        """
        # Keep track of the db instance.
        self._instance = instance
        # The name of the database to use.
        self._database = database
        self._connect()

    def _connect(self):
        if (os.getenv('SERVER_SOFTWARE') and
            os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
            socket_name = '/cloudsql/%s' % self._instance
            self._db = MySQLdb.connect(unix_socket=socket_name,
                                       db=self._database, user='root')
        else:
            self._db = MySQLdb.connect(host=_MYSQL_HOST, port=3306,
                                       db=self._database, user=_MYSQL_USER,
                                       passwd=_MYSQL_PASSWORD)

    def __del__(self):
        self._db.close()

    # TODO: Add more methods for Create/Update/Delete features, and tables.
    def list(self, table, select, where, limit=None, order_by=None):
        """Send the query to the database and return the result as GeoJSON.

        Args:
          table: The Table to use.
          select: A comma-separated list of columns to use. Anything that is
              valid SQL is accepted. This value needs rigorous error checking.
          where: A valid SQL where statement. Also needs a lot of checking.
          limit: The limit the number of returned entries.
          order_by: A valid SQL order by statement.

        Returns:
          A GeoJSON FeatureCollection representing the returned features, or
              a dict explaining the error.
        """

        cursor = self._db.cursor()
        features = []
        cols = []
        # Add the geometry column to the query. This assumes that geometry is
        # not in the selected columns.
        if select:
            select = '%s,AsWKT(%s) as wktgeom' % (select, _GEOMETRY_FIELD)
        else:
            select = 'AsWKT(%s) as wktgeom' % _GEOMETRY_FIELD

        # Build the query.
        query = ['select %(select)s from %(id)s where %(where)s' % {
            'id': table,
            'select': select,
            'where': where
        }]
        if order_by:
            query.append('order by %s' % order_by)
        if limit:
            query.append('limit %s' % limit)

        # Convert the list to a string.
        query_string = ' '.join(query)
        logging.info('query = "%s"', query_string)
        if len(sqlparse.split(query_string)) > 1:
          return {'error': 'invalid parameter'}
        rows = []
        try:
            cursor.execute(' '.join(query))
            cols = [i[0] for i in cursor.description]
            rows = cursor.fetchall()
        except MySQLdb.Error as e:
            # This error should probably be made better in a production system.
            return {'error': 'Something went wrong: {}'.format(e)}

        # Give each feature a unique ID.
        feature_id = 0
        # now we read the rows and generate geojson out of them.
        for row in rows:
            wktgeom = row[-1]
            props = dict(zip(cols[:-1], row[:-1]))
            # geomet.wkt.loads returns a dict which corresponds to the geometry
            # We dump this as a string, and let geojson parse it
            geom = geojson.loads(json.dumps(geomet.wkt.loads(wktgeom)))
            # Turn the geojson geometry into a proper GeoJSON feature
            feature = geojson.Feature(geometry=geom, properties=props,
                                      id=feature_id)
            feature_id += 1
            # Add the feature to our list of features.
            features.append(feature)
        # Close the cursor, now that we are done with it.
        cursor.close()
        # Return the list of features as a FeatureCollection.
        return geojson.FeatureCollection(features)

class PointInPolygon(object):
    """This class handles the pip requests.

    It uses Features to query the db.
    """

    def __init__(self, instance, database, table):
        """Create a Features instance and store the table.

        Args:
          instance: The name of the CloudSQL instance.
          database: The name of the database to use.
          table: The table that contains the features that we want to look up.
        """
        self._features = Features(instance, database)
        self._table = table

    def pip(self, lat, lng, fields):
        """This method returns the polygon that contains the given coordinate.

        It uses the Feature class to make the actual query.

        Args:
          lat: The latitude
          lng: The longitude
          fields: The fields to select as data

        Returns:
          A geojson polygon or an error dict.
        """
        point = "GeomFromText('POINT(%f %f)')" % (lng, lat)
        return self._features.list(
            self._table, fields,
            'ST_CONTAINS(%s,%s)' % (_GEOMETRY_FIELD, point),
            limit=1)


text: mypack.fun<caret>


text:
export const BASE_URL =
    "https://test-env.getbooqed.com/"
    // "https://superroman.localtunnel.me";
    // "http://localhost:3000";


text:
from typing import Callable
from _pytest.pytester import RunResult

def test_shell_help(run: Callable[..., RunResult]):
    output = run("shell", "--help")

    help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
                  [--conversation-id CONVERSATION_ID] [-m MODEL]
                  [--log-file LOG_FILE] [--use-syslog]
                  [--syslog-address SYSLOG_ADDRESS]
                  [--syslog-port SYSLOG_PORT]
                  [--syslog-protocol SYSLOG_PROTOCOL] [--endpoints ENDPOINTS]
                  [-i INTERFACE] [-p PORT] [-t AUTH_TOKEN]
                  [--cors [CORS [CORS ...]]] [--enable-api]
                  [--response-timeout RESPONSE_TIMEOUT]
                  [--remote-storage REMOTE_STORAGE]
                  [--ssl-certificate SSL_CERTIFICATE]
                  [--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
                  [--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
                  [--connector CONNECTOR] [--jwt-secret JWT_SECRET]
                  [--jwt-method JWT_METHOD]
                  {nlu} ... [model-as-positional-argument]"""

    lines = help_text.split("\n")
    # expected help text lines should appear somewhere in the output
    printed_help = set(output.outlines)
    for line in lines:
        assert line in printed_help

def test_shell_nlu_help(run: Callable[..., RunResult]):
    output = run("shell", "nlu", "--help")

    help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
                      [model-as-positional-argument]"""

    lines = help_text.split("\n")
    # expected help text lines should appear somewhere in the output
    printed_help = set(output.outlines)
    for line in lines:
        assert line in printed_help


text:
package redis_counter

import "math"
import "github.com/alecthomas/log4go"
import "github.com/gnagel/dog_pool/dog_pool"
import "testing"
import "github.com/orfjackal/gospec/src/gospec"

func TestRedisHashMFieldsCounterInt64Specs(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in benchmark mode.")
		return
	}
	r := gospec.NewRunner()
	r.AddSpec(RedisHashMFieldsCounterInt64Specs)
	gospec.MainGoTest(r, t)
}

func RedisHashMFieldsCounterInt64Specs(c gospec.Context) {

	c.Specify("[RedisHashMFieldsCounterInt64][Make] Makes new instance", func() {
		value, err := MakeRedisHashMFieldsCounterInt64(nil, "")
		c.Expect(err.Error(), gospec.Equals, "Nil redis connection")
		c.Expect(value, gospec.Satisfies, nil == value)

		value, err = MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "")
		c.Expect(err.Error(), gospec.Equals, "Empty redis key")
		c.Expect(value, gospec.Satisfies, nil == value)

		value, err = MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "Key", "")
		c.Expect(err.Error(), gospec.Equals, "Empty redis field[0]")
		c.Expect(value, gospec.Satisfies, nil == value)

		value, err = MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "Key", "Bob")
		c.Expect(err, gospec.Equals, nil)
		c.Expect(value, gospec.Satisfies, nil != value)
		c.Expect(value.KEY, gospec.Equals, "Key")
		c.Expect(len(value.FIELDS), gospec.Equals, 1)
		c.Expect(value.FIELDS[0], gospec.Equals, "Bob")
	})

	c.Specify("[RedisHashMFieldsCounterInt64][String] Formats string", func() {
		value, _ := MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "Key", "Bob", "Gary", "AAA", "Missing")

		// Order of FIELDS determines output order
		c.Expect(value.String(), gospec.Equals, "Key[Bob = NaN, Gary = NaN, AAA = NaN, Missing = NaN]")

		counter := int64(123)
		value.Cache.Set("AAA", &counter)
		value.Cache.Set("Bob", &counter)
		value.Cache.Set("Gary", &counter)

		// Order of FIELDS determines output order
		c.Expect(value.String(), gospec.Equals, "Key[Bob = 123, Gary = 123, AAA = 123, Missing = NaN]")
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MExists] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		oks, err := value.MExists()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(oks), gospec.Equals, len(value.FIELDS))
		for _, ok := range oks {
			c.Expect(ok, gospec.Equals, true)
		}
		c.Expect(value.Cache.Len(), gospec.Equals, 0)

		// Cache Miss
		server.Connection().Cmd("HDEL", value.KEY, value.FIELDS)
		oks, err = value.MExists()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(oks), gospec.Equals, len(value.FIELDS))
		for _, ok := range oks {
			c.Expect(ok, gospec.Equals, false)
		}
		c.Expect(value.Cache.Len(), gospec.Equals, 0)
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MInt64] Gets value from Redis", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for i, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, 123*math.Pow10(i))
		}

		counters, err := value.MInt64()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, field := range value.FIELDS {
			counter := counters[i]
			c.Expect(counter, gospec.Equals, int64(123*math.Pow10(i)))

			ptr := value.Cache.Value(field)
			c.Expect(*ptr, gospec.Equals, int64(123*math.Pow10(i)))
		}

		// Cache Miss
		server.Connection().Cmd("HDEL", value.KEY, value.FIELDS)
		counters, err = value.MInt64()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(value.Cache.Len(), gospec.Equals, 0)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for _, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(0))
		}

		// Parsing error:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "Gary")
		}

		counters, err = value.MInt64()
		c.Expect(err, gospec.Satisfies, nil != err)
		c.Expect(len(counters), gospec.Equals, 0)
		c.Expect(value.Cache.Len(), gospec.Equals, 0)
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MGet] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for i, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, 123*math.Pow10(i))
		}

		counters, err := value.MGet()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, field := range value.FIELDS {
			counter := counters[i]
			c.Expect(counter, gospec.Equals, int64(123*math.Pow10(i)))

			ptr := value.Cache.Value(field)
			c.Expect(*ptr, gospec.Equals, int64(123*math.Pow10(i)))
		}

		// Cache Miss
		server.Connection().Cmd("HDEL", value.KEY, value.FIELDS)
		counters, err = value.MGet()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(value.Cache.Len(), gospec.Equals, 0)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for _, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(0))
		}

		// Parsing error:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "Gary")
		}

		counters, err = value.MGet()
		c.Expect(err, gospec.Satisfies, nil != err)
		c.Expect(len(counters), gospec.Equals, 0)
		c.Expect(value.Cache.Len(), gospec.Equals, 0)
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MDelete] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		err := value.MDelete()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(value.Cache.Len(), gospec.Equals, 0)

		for _, field := range value.FIELDS {
			ok, _ := server.Connection().Cmd("HEXISTS", value.KEY, field).Int()
			c.Expect(ok, gospec.Equals, 0)
		}
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MSet] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		counters, err := value.MSet(123)
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(123))

			value := value.Cache.Value(value.FIELDS[i])
			c.Expect(value, gospec.Satisfies, nil != value)
			c.Expect(*value, gospec.Equals, int64(123))
		}

		list, list_err := server.Connection().Cmd("HMGET", value.KEY, value.FIELDS).List()
		c.Expect(list_err, gospec.Equals, nil)
		c.Expect(len(list), gospec.Equals, len(value.FIELDS))

		for _, list_value := range list {
			c.Expect(list_value, gospec.Equals, "123")
		}
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MAdd] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		counters, err := value.MAdd(555)
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(123+555))

			value := value.Cache.Value(value.FIELDS[i])
			c.Expect(value, gospec.Satisfies, nil != value)
			c.Expect(*value, gospec.Equals, int64(123+555))
		}

		list, list_err := server.Connection().Cmd("HMGET", value.KEY, value.FIELDS).List()
		c.Expect(list_err, gospec.Equals, nil)
		c.Expect(len(list), gospec.Equals, len(value.FIELDS))

		for _, list_value := range list {
			c.Expect(list_value, gospec.Equals, "678")
		}
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MSub] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		counters, err := value.MSub(555)
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(123-555))

			value := value.Cache.Value(value.FIELDS[i])
			c.Expect(value, gospec.Satisfies, nil != value)
			c.Expect(*value, gospec.Equals, int64(123-555))
		}

		list, list_err := server.Connection().Cmd("HMGET", value.KEY, value.FIELDS).List()
		c.Expect(list_err, gospec.Equals, nil)
		c.Expect(len(list), gospec.Equals, len(value.FIELDS))

		for _, list_value := range list {
			c.Expect(list_value, gospec.Equals, "-432")
		}
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MIncrement] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		counters, err := value.MIncrement()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(123+1))

			value := value.Cache.Value(value.FIELDS[i])
			c.Expect(value, gospec.Satisfies, nil != value)
			c.Expect(*value, gospec.Equals, int64(123+1))
		}

		list, list_err := server.Connection().Cmd("HMGET", value.KEY, value.FIELDS).List()
		c.Expect(list_err, gospec.Equals, nil)
		c.Expect(len(list), gospec.Equals, len(value.FIELDS))

		for _, list_value := range list {
			c.Expect(list_value, gospec.Equals, "124")
		}
	})

	c.Specify("[RedisHashMFieldsCounterInt64][MDecrement] Redis Operation", func() {
		logger := log4go.NewDefaultLogger(log4go.CRITICAL)
		server, server_err := dog_pool.StartRedisServer(&logger)
		if nil != server_err {
			panic(server_err)
		}
		defer server.Close()

		value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

		// Valid number:
		for _, field := range value.FIELDS {
			server.Connection().Cmd("HSET", value.KEY, field, "123")
		}

		counters, err := value.MDecrement()
		c.Expect(err, gospec.Equals, nil)
		c.Expect(len(counters), gospec.Equals, len(value.FIELDS))
		for i, counter := range counters {
			c.Expect(counter, gospec.Equals, int64(123-1))

			value := value.Cache.Value(value.FIELDS[i])
			c.Expect(value, gospec.Satisfies, nil != value)
			c.Expect(*value, gospec.Equals, int64(123-1))
		}

		list, list_err := server.Connection().Cmd("HMGET", value.KEY, value.FIELDS).List()
		c.Expect(list_err, gospec.Equals, nil)
		c.Expect(len(list), gospec.Equals, len(value.FIELDS))

		for _, list_value := range list {
			c.Expect(list_value, gospec.Equals, "122")
		}
	})

}

func Benchmark_RedisHashMFieldsCounterInt64_MMake(b *testing.B) {
	for i := 0; i < b.N; i++ {
		MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "Key", "Bob", "George", "Alex", "Applause")
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MString(b *testing.B) {
	value, _ := MakeRedisHashMFieldsCounterInt64(&dog_pool.RedisConnection{}, "Key", "Bob", "George", "Alex", "Applause")
	for i := 0; i < b.N; i++ {
		value.String()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MExists(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	// Valid number:
	for _, field := range value.FIELDS {
		server.Connection().Cmd("HSET", value.KEY, field, "123")
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MExists()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MInt64_ValidNumber(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	// Valid number:
	for _, field := range value.FIELDS {
		server.Connection().Cmd("HSET", value.KEY, field, "123")
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MInt64()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MInt64_CacheMiss(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MInt64()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MInt64_InvalidNumber(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	// Valid number:
	for _, field := range value.FIELDS {
		server.Connection().Cmd("HSET", value.KEY, field, "Gary")
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MInt64()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MGet(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	// Valid number:
	for _, field := range value.FIELDS {
		server.Connection().Cmd("HSET", value.KEY, field, "123")
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MGet()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MSet(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	// Valid number:
	for _, field := range value.FIELDS {
		server.Connection().Cmd("HSET", value.KEY, field, "000")
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MSet(123)
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MDelete(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MDelete()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MAdd(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MAdd(555)
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MSub(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MSub(555)
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MIncrement(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MIncrement()
	}
}

func Benchmark_RedisHashMFieldsCounterInt64_MDecrement(b *testing.B) {
	logger := log4go.NewDefaultLogger(log4go.CRITICAL)
	server, err := dog_pool.StartRedisServer(&logger)
	if nil != err {
		panic(err)
	}
	defer server.Close()

	value, _ := MakeRedisHashMFieldsCounterInt64(server.Connection(), "Key", "Bob", "George", "Alex", "Applause")

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		value.MDecrement()
	}
}


text:
package rest

import (
	"k8s.io/apiserver/pkg/registry/generic"
	"k8s.io/apiserver/pkg/registry/rest"
	genericapiserver "k8s.io/apiserver/pkg/server"
	serverstorage "k8s.io/apiserver/pkg/server/storage"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apis/networking"
	networkingapiv1 "k8s.io/kubernetes/pkg/apis/networking/v1"
	networkpolicystore "k8s.io/kubernetes/pkg/registry/networking/networkpolicy/storage"
)

type RESTStorageProvider struct{}

func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) {
	apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(networking.GroupName, api.Registry, api.Scheme, api.ParameterCodec, api.Codecs)

	if apiResourceConfigSource.AnyResourcesForVersionEnabled(networkingapiv1.SchemeGroupVersion) {
		apiGroupInfo.VersionedResourcesStorageMap[networkingapiv1.SchemeGroupVersion.Version] = p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter)
		apiGroupInfo.GroupMeta.GroupVersion = networkingapiv1.SchemeGroupVersion
	}

	return apiGroupInfo, true
}

func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {
	version := networkingapiv1.SchemeGroupVersion

	storage := map[string]rest.Storage{}
	if apiResourceConfigSource.ResourceEnabled(version.WithResource("networkpolicies")) {
		networkPolicyStorage := networkpolicystore.NewREST(restOptionsGetter)
		storage["networkpolicies"] = networkPolicyStorage
	}
	return storage
}

func (p RESTStorageProvider) GroupName() string {
	return networking.GroupName
}


text:
"""
Manages calls to the Storage API relating to workspaces.

Full documentation `here`.

.. _here:
    http://docs.keboola.apiary.io/#reference/workspaces/
"""
from kbcstorage.base import Endpoint

def _make_body(mapping):
    """
    Given a dict mapping Keboola tables to aliases, construct the body of
    the HTTP request to load said tables.

    Args:
        mapping(:obj:`dict`): Keys contain the full names of the tables to
            be loaded (ie. 'in.c-bucker.table_name') and values contain the
            aliases to which they will be loaded (ie. 'table_name').
    """
    body = {}
    template = 'input[{0}][{1}]'
    for i, (k, v) in enumerate(mapping.items()):
        body[template.format(i, 'source')] = k
        body[template.format(i, 'destination')] = v

    return body

class Workspaces(Endpoint):
    """
    Workspaces Endpoint
    """
    def __init__(self, root_url, token):
        """
        Create a Workspaces endpoint.

        Args:
            root_url (:obj:`str`): The base url for the API.
            token (:obj:`str`): A storage API key.
        """
        super().__init__(root_url, 'workspaces', token)

    def list(self):
        """
        List the details of all workspaces in the project.

        Returns:
            response_body: The json from the HTTP response.

        Raises:
            requests.HTTPError: If the API request fails.
        """
        headers = {'X-StorageApi-Token': self.token}
        return self.get(self.base_url, headers=headers)

    def detail(self, workspace_id):
        """
        Retrieves information about a given workspace.

        Note that the password to the workspace can only be retrieved when the
        workspace is created.

        Args:
            workspace_id (int or str): The id of the workspace.

        Raises:
            requests.HTTPError: If the API request fails.
        """
        headers = {'X-StorageApi-Token': self.token}
        url = '{}/{}'.format(self.base_url, workspace_id)
        return self.get(url, headers=headers)

    def create(self, backend=None, timeout=None):
        """
        Create a new Workspace and return the credentials.

        Args:
            backend (:obj:`str`): The type of engine for the workspace.
                'redshift' or 'snowflake'. Default redshift.
            timeout (int): The timeout, in seconds, for SQL statements.
                Only supported by snowflake backends.

        Raises:
            requests.HTTPError: If the API request fails.
        """
        headers = {
            'X-StorageApi-Token': self.token,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        body = {
            'backend': backend,
            'statementTimeoutSeconds': timeout
        }

        return self.post(self.base_url, data=body, headers=headers)

    def delete(self, workspace_id):
        """
        Deletes a workspace.

        This also irreversibly removes workspace content.

        Args:
            workspace_id (int or str): The id of the workspace to be deleted.

        Raises:
            requests.HTTPError: If the API request fails.
        """
        headers = {
            'X-StorageApi-Token': self.token,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        url = '{}/{}'.format(self.base_url, workspace_id)

        # This shadows the superclass...
        return super().delete(url, headers=headers)

    def reset_password(self, workspace_id):
        """
        Generate a new password for the workspace.

        Args:
            workspace_id (int or str): The id of the workspace for which the
                password should be reset.

        Raises:
            requests.HTTPError: If the API request fails.
        """
        headers = {
            'X-StorageApi-Token': self.token,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        url = '{}/{}/password'.format(self.base_url, workspace_id)
        return self.post(url, headers=headers)

    def load_tables(self, workspace_id, table_mapping, preserve=None):
        """
        Load tabes from storage into a workspace.

        Args:
            workspace_id (int or str): The id of the workspace to which to load
                the tables.
            table_mapping (:obj:`dict`): Source table names mapped to
                destination table names.
            preserve (bool): If False, drop tables, else keep tables in
                workspace.

        Raises:
            requests.HTTPError: If the API request fails.

        Todo:
            * Column data types.
        """
        headers = {
            'X-StorageApi-Token': self.token,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        body = _make_body(table_mapping)
        body['preserve'] = preserve
        url = '{}/{}/load'.format(self.base_url, workspace_id)

        return self.post(url, data=body, headers=headers)


text:
<?php
/* @var $this AlmabCustomersController */
/* @var $model AlmabCustomers */

$this->breadcrumbs=array(
	'Almab Customers'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>' List AlmabCustomers', 'url'=>array('index')),
	array('label'=>' Create AlmabCustomers', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#almab-customers-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Almab Customers

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'almab-customers-grid',
        'itemsCssClass'=>'table table-striped table-bordered table-hover',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'id',
		'descr',
		'email',
		'guid',
		'updatefrom',
		'updateto',
		/*
		'dbserial',
		*/
                'iscustom',
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
<?php

if (!interface_exists('RokMenuFormatter')) {
    /**
     *
     */
    interface RokMenuFormatter {
        /**
         * @abstract
         * @param  $args
         * @return void
         */
        public function __construct(&$args);

        /**
         * @abstract
         * @param  $menu
         * @return void
         */
        public function format_tree(&$menu);

        /**
         * @abstract
         * @param RokMenuNodeTree $menu
         * @return void
         */
        public function format_menu(&$menu);

        /**
         * @abstract
         * @param RokMenuNode $node
         * @return void
         */
        public function format_subnode(&$node);

        /**
         * @abstract
         * @param  array $active_branch
         * @return void
         */
        public function setActiveBranch(array $active_branch);

        /**
         * @abstract
         * @param  int $current_node
         * @return void
         */
        public function setCurrentNodeId($current_node);
    }
}


text:
const configure = require('./webpack.base.js').default;

module.exports = configure({
  environment: 'development',
  publicPath: '/release/',
});


text:
package com.googlecode.common.admin.protocol.user;

import com.googlecode.common.protocol.Requests;

/**
 * Contains users requests' path constants.
 */
public final class UserRequests extends Requests {

    public static final String  GET_COMPANY_USERS   = "/user/list/company/{id}";
    public static final String  GET_SYSTEM_USERS    = "/user/list/{id}/{groupId}";
    public static final String  CREATE_NEW_USER     = "/user/{id}/user/{groupId}";
    public static final String  CREATE_NEW_GROUP    = "/user/{id}/group/{groupId}";
    public static final String  GET_ALL_GROUPS      = "/user/{id}/groups";
    public static final String  DELETE_GROUP        = "/user/group/{id}/delete";
    public static final String  RENAME_GROUP        = "/user/group/rename";
    public static final String  MOVE_USERS          = "/user/move";
    public static final String  CHANGE_PASSWORD     = "/user/changepass";
    public static final String  GET_ALL_LDAP_USERS  = "/user/list/ldap";

    public static final String  GET_USER_ROLES      = "/user/{id}/roles/user/{userId}/{isAllPerm}";
    public static final String  GET_GROUP_ROLES     = "/user/{id}/roles/group/{groupId}/{isAllPerm}";

    public static final String  UPDATE_USER_ROLES   = "/user/roles/user";
    public static final String  UPDATE_GROUP_ROLES  = "/user/roles/group";

    // Parameters names

    public static final String  PARAM_ALL_PERM      = "isAllPerm";
    public static final String  PARAM_GROUP         = "groupId";
    public static final String  PARAM_USER          = "userId";

    private UserRequests() {
    }

}


text:
var path = require('path');
var fs = require('fs');

var debug = require('debug')('nameless:model-fac');

var ccModel = require('./CCModel');
var dbUtils = require('./dbUtils');
var config = require('../config');

var preparedModels = {};

var model = exports = module.exports = {};

var connection = dbUtils.connectDB();

/**
 * Makes Model Object Fitting to the Model Object with the same name.
 * @param {String} name     Model name.
 * @return {Object}         ccModel Object.
 *
 */
model.make = function (name) {
    var modelPath = path.join(config.rootPath, 'models', name + '_model.js');
    if(!fs.existsSync(modelPath)) {
        debug('No model found: ' + modelPath);
        return null;
    }

    var modelData = require(modelPath);

    return getModel(name, modelData);
};

/**
 * Returns the prepeared Data for CCModel.
 * If not created it creates Data from the model in the root/model directorey.
 * @param  {String} name        Model name
 * @return {CCModel}            CCModel
 */
model.getModel = function (name) {
    if(preparedModels[name]) {
        return preparedModels[name];
    }

    return null;
};

/**
 * Returns the prepeared Data for CCModel.
 * If not created it creates Data from the model in the root/model directorey.
 * @param  {String} name        Model name
 * @param  {Object} modelData   Model from root/model directorey
 * @return {CCModel}            CCModel
 */
function getModel(name, modelData) {
    debug(name);
    if(!preparedModels[name]) {
        modelData = createModelSchema(name, modelData);
        preparedModels[name] = new ccModel(connection, modelData);
    }

    return preparedModels[name];
}

var PRESAVE_CONSTRUCTOR = /^(preSave)|(constuctor)$/;
var METHODS = /^__proto$/;
var SETTER = /^([^_]*)(_setter)$/;

var createModelSchema = function (name, modelData) {
    var schemaObj = {
        fkList: {}
    };
    var dbEvents = {
        setter: []
    };

    var files = [];
    var methods = [];
    var children = [];
    var staticFunctions = [];

    var forbiddenKeys = new RegExp('^(' + config.forbiddenKeys.join(')|(') + ')$');

    for (var i in modelData) {
        if((i + '').match(forbiddenKeys)) {
            console.final_error('Forbidden Model Elemnt: ' + config.forbiddenKeys.join(', '));
            return;
        }
        if((i + '').match(PRESAVE_CONSTRUCTOR)) {
            dbEvents[i] = modelData[i];
        }
        else if((i + '').match(SETTER)) {
            dbEvents.setter[SETTER.exec(i)[1]] = modelData[i];
        }
        else if((i + '').match(METHODS)) {
            for (var l in modelData[i]) {
                methods[l] = modelData[i][l];
            }
        } else if(typeof modelData[i] !== 'function') {
            var tempModel;
            if(typeof modelData[i] === 'string' || modelData instanceof Array) {
                tempModel = {
                    type: modelData[i]
                };
            }
            else {
                tempModel = modelData[i];
            }

            if(tempModel.type === 'FILE') {
                files.push(i);
            } else if(!isValideSqlKey(tempModel.type)) {
                schemaObj[i] = tempModel;
                var childName = tempModel.type instanceof Array ? tempModel.type[0] : tempModel.type;
                schemaObj.fkList[childName] = i;

                debug(schemaObj[i]);
                debug(childName);

                var child = model.make(childName);

                children.push(child);
                schemaObj[i].isFk = true;
            } else {
                schemaObj[i] = tempModel;
            }
        } else if(typeof modelData[i] === 'function') {
            staticFunctions.push({
                                     func: modelData[i],
                                     name: i
                                 });
        }
    }

    return {
        db: schemaObj,
        files: files,
        methods: methods,
        dbEvents: dbEvents,
        name: name,
        children: children,
        staticFunctions: staticFunctions
    };
};

var isValideSqlKey = function (key) {
    if(key instanceof Array) {
        return false;
    }
    for (var i = 0; i < config.mysql.keys.length; ++i) {
        if(key.match(config.mysql.keys[i])) {
            return true;
        }

    }

    return false;
};


text:
<?php

namespace Code16\Sharp\Form\Layout;

class FormLayoutFieldset implements HasLayout
{
    use HasFieldRows;

    protected string $legend;

    public function __construct(string $legend)
    {
        $this->legend = $legend;
    }

    public function toArray(): array
    {
        return array_merge(
            ['legend' => $this->legend],
            $this->fieldsToArray(),
        );
    }
}


text:
package org.wso2.andes.server.binding;

import org.apache.log4j.Logger;
import org.wso2.andes.AMQException;
import org.wso2.andes.AMQInternalException;
import org.wso2.andes.AMQSecurityException;
import org.wso2.andes.amqp.AMQPUtils;
import org.wso2.andes.amqp.QpidAndesBridge;
import org.wso2.andes.configuration.qpid.BindingConfig;
import org.wso2.andes.configuration.qpid.BindingConfigType;
import org.wso2.andes.configuration.qpid.ConfigStore;
import org.wso2.andes.configuration.qpid.ConfiguredObject;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.FieldTable;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.server.NameValidationUtils;
import org.wso2.andes.server.exchange.Exchange;
import org.wso2.andes.server.exchange.TopicExchange;
import org.wso2.andes.server.logging.actors.CurrentActor;
import org.wso2.andes.server.logging.messages.BindingMessages;
import org.wso2.andes.server.logging.subjects.BindingLogSubject;
import org.wso2.andes.server.queue.AMQQueue;
import org.wso2.andes.server.store.DurableConfigurationStore;
import org.wso2.andes.server.virtualhost.VirtualHost;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BindingFactory {
    private final VirtualHost _virtualHost;
    private final DurableConfigurationStore.Source _configSource;
    private final Exchange _defaultExchange;

    private static final Logger _logger = Logger.getLogger(BindingFactory.class);
    private final ConcurrentHashMap<BindingImpl, BindingImpl> _bindings = new ConcurrentHashMap<BindingImpl, BindingImpl>();

    public BindingFactory(final VirtualHost vhost) {
        this(vhost, vhost.getExchangeRegistry().getDefaultExchange());
    }

    public BindingFactory(final DurableConfigurationStore.Source configSource, final Exchange defaultExchange) {
        _configSource = configSource;
        _defaultExchange = defaultExchange;
        if (configSource instanceof VirtualHost) {
            _virtualHost = (VirtualHost) configSource;
        } else {
            _virtualHost = null;
        }
    }

    public VirtualHost getVirtualHost() {
        return _virtualHost;
    }

    private final class BindingImpl extends Binding implements AMQQueue.Task, Exchange.Task, BindingConfig {
        private final BindingLogSubject _logSubject;
        //TODO : persist creation time
        private long _createTime = System.currentTimeMillis();

        private BindingImpl(String bindingKey, final AMQQueue queue, final Exchange exchange, final Map<String, Object> arguments) {
            super(queue.getVirtualHost().getConfigStore().createId(), bindingKey, queue, exchange, arguments);
            _logSubject = new BindingLogSubject(bindingKey, exchange, queue);

        }

        public void doTask(final AMQQueue queue) throws AMQException {
            removeBinding(this);
        }

        public void onClose(final Exchange exchange) throws AMQSecurityException, AMQInternalException {
            removeBinding(this);
        }

        void logCreation() {
            CurrentActor.get().message(_logSubject, BindingMessages.CREATED(String.valueOf(getArguments()), getArguments() != null && !getArguments().isEmpty()));
        }

        void logDestruction() {
            CurrentActor.get().message(_logSubject, BindingMessages.DELETED());
        }

        public String getOrigin() {
            return (String) getArguments().get("qpid.fed.origin");
        }

        public long getCreateTime() {
            return _createTime;
        }

        public BindingConfigType getConfigType() {
            return BindingConfigType.getInstance();
        }

        public ConfiguredObject getParent() {
            return _virtualHost;
        }

        public boolean isDurable() {
            return getQueue().isDurable() && getExchange().isDurable();
        }

    }

    public boolean addBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments)
            throws AMQSecurityException, AMQInternalException {
        boolean bindingAdded = makeBinding(bindingKey, queue, exchange, arguments, false, false);
        //tell Andes kernel to create binding
        QpidAndesBridge.createBinding(exchange, new AMQShortString(bindingKey), queue);
        return bindingAdded;
    }

    public boolean replaceBinding(final String bindingKey,
                                  final AMQQueue queue,
                                  final Exchange exchange,
                                  final Map<String, Object> arguments) throws AMQSecurityException,
                                  AMQInternalException {
        boolean isBindingAdded = makeBinding(bindingKey, queue, exchange, arguments, false, true);
        //tell Andes kernel to create binding
        QpidAndesBridge.createBinding(exchange, new AMQShortString(bindingKey), queue);
        return isBindingAdded;
    }

    private synchronized boolean makeBinding(String bindingKey, AMQQueue queue, Exchange exchange,
                                             Map<String, Object> arguments, boolean restore, boolean force)
            throws AMQSecurityException, AMQInternalException {

        assert queue != null;
        if (bindingKey == null) {
            bindingKey = "";
        }
        if (exchange == null) {
            exchange = _defaultExchange;
        }
        if (arguments == null) {
            arguments = Collections.emptyMap();
        }

        /*
         * We should check cluster-wide if the queue has a binding with a key A and now it is going to bind with a different key
         * (say B) we should not allow it. It is enough to check with local bindings as whenever we create a binding in cluster
         * it is syned and created locally. We test it before binding authorization to avoid
         * creating registry entries.
         */
        if (exchange.getName().equalsIgnoreCase("amq.topic") && queue.isDurable()) {
            if (checkIfQueueHasBoundToDifferentTopic(bindingKey, queue)) {
                throw new AMQInternalException("An Exclusive Bindings already exists for different topic. Not permitted.");
            }
        }

        BindingImpl binding = new BindingImpl(bindingKey, queue, exchange, arguments);
        BindingImpl existingMapping = _bindings.putIfAbsent(binding, binding);
        if (existingMapping == null || force) {
            if (existingMapping != null) {
                //TODO - we should not remove the existing binding
                removeBinding(existingMapping);
            }

            if (_logger.isDebugEnabled()) {
                _logger.debug("bindingKey: " + bindingKey + ", queue: " + queue + ", exchange: " + exchange);
            }

            // Prevent creating topics, if topic name is invalid
            if (exchange.getType() == TopicExchange.TYPE) {
                if (!NameValidationUtils.isValidTopicName(bindingKey)) {
                    _virtualHost.getQueueRegistry().unregisterQueue(queue.getNameShortString());
                    throw new AMQInternalException("\nTopic name: "
                            + NameValidationUtils.getNameWithoutTenantDomain(bindingKey)
                            + " can contain only alphanumeric characters and star(*) "
                            + "delimited by dots. Names can ends with any of these or, with '#' ");
                }
            }

            //Perform ACLs ONLY after removing/updating any existing bindings.
            if (!getVirtualHost().getSecurityManager().authoriseBind(exchange, queue, new AMQShortString(bindingKey))) {
                throw new AMQSecurityException("Permission denied: binding " + bindingKey);
            }

            //save only durable bindings
            if (binding.isDurable() && !restore) {
                _configSource.getDurableConfigurationStore().bindQueue
                        (exchange, new AMQShortString(bindingKey), queue, FieldTable.convertToFieldTable(arguments));
            }

            queue.addQueueDeleteTask(binding);
            exchange.addCloseTask(binding);
            queue.addBinding(binding);
            exchange.addBinding(binding);
            getConfigStore().addConfiguredObject(binding);
            binding.logCreation();

            return true;
        } else {
            return false;
        }
    }

    private boolean checkIfQueueHasBoundToDifferentTopic(String bindingKey, AMQQueue queue) {
        boolean isAlreadyABindingExistsForDifferentKey = false;
        List<Binding> bindingList = queue.getBindings();
        for (Binding b : bindingList) {
            if (b.getExchange().getName().equals(AMQPUtils.TOPIC_EXCHANGE_NAME) && !b.getBindingKey().equals(bindingKey)) {
                isAlreadyABindingExistsForDifferentKey = true;
                break;
            }
        }
        return isAlreadyABindingExistsForDifferentKey;
    }

    private ConfigStore getConfigStore() {
        return getVirtualHost().getConfigStore();
    }

    public void restoreBinding(final String bindingKey, final AMQQueue queue,
                               final Exchange exchange, final Map<String, Object> argumentMap)
            throws AMQSecurityException, AMQInternalException {
        makeBinding(bindingKey, queue, exchange, argumentMap, true, false);
    }

    public void removeBinding(final Binding b) throws AMQSecurityException, AMQInternalException {
        removeBinding(b.getBindingKey(), b.getQueue(), b.getExchange(), b.getArguments(), true);
    }

    public synchronized Binding removeBinding(String bindingKey, AMQQueue queue, Exchange exchange,
                                 Map<String, Object> arguments, boolean isLocal) throws AMQSecurityException, AMQInternalException {
        assert queue != null;
        if (bindingKey == null) {
            bindingKey = "";
        }
        if (exchange == null) {
            exchange = _defaultExchange;
        }
        if (arguments == null) {
            arguments = Collections.emptyMap();
        }

        // Check access
        if (!getVirtualHost().getSecurityManager().authoriseUnbind(exchange,
                new AMQShortString(bindingKey), queue)) {
            throw new AMQSecurityException("Permission denied: binding " + bindingKey);
        }

        BindingImpl binding = _bindings.remove(new BindingImpl(bindingKey, queue, exchange, arguments));

        try {
            if (binding != null) {
                if (binding.isDurable()) {
                    _configSource.getDurableConfigurationStore().unbindQueue(exchange,
                            new AMQShortString(bindingKey),
                            queue,
                            FieldTable.convertToFieldTable(arguments));
                }

                if(isLocal) {
                    //inform andes kernel to remove binding.
                    QpidAndesBridge.removeBinding(binding);
                }

                exchange.removeBinding(binding);
                queue.removeBinding(binding);
                exchange.removeCloseTask(binding);
                queue.removeQueueDeleteTask(binding);

                binding.logDestruction();
                getConfigStore().removeConfiguredObject(binding);
            }
            return binding;
        } catch (AndesException e) {
            throw new AMQInternalException("Error while removing binding.", e);
        }
    }

    public Binding getBinding(String bindingKey, AMQQueue queue, Exchange exchange, Map<String, Object> arguments) {
        assert queue != null;
        if (bindingKey == null) {
            bindingKey = "";
        }
        if (exchange == null) {
            exchange = _defaultExchange;
        }
        if (arguments == null) {
            arguments = Collections.emptyMap();
        }

        BindingImpl b = new BindingImpl(bindingKey, queue, exchange, arguments);
        return _bindings.get(b);
    }
}


text:
The Aim of this project is to provide a collection of reusable Algorithms which can be used effectively in different scenarios. It is purely used for Educational purposes.

As of now the languages supported are,
1. Java
2. Python
3. JavaScript
4. Scala
5. Kotlin

If you want to add more languages please message me.

# Features
1. Reusable codes
2. Tested the Algorithm implementations with different set of datas and provided the statistics in the header comment, so that developers can choose and reuse the algorithm which solve their business problem

This project is Migrated from sourceforge. It is a 11 Year old project (https://sourceforge.net/projects/algorithmdb/)

# For Developers who want to contribute to the project

Feel free to write me arunan.healtheworld@gmail.com


text:
layout: post
title: JBrowse updated to v1.12.0
categories: announcement
tags:
- jbrowse
- tools
author: Terry Mun
summary: We have successfully upgraded our JBrowse installation, used to power visualization of the L. japonicus genome, to version 1.12.0.
---

Just upgraded the Lotus japonicus #genome browser to the latest version of JBrowse, v1.12.0 https://t.co/ttAO0z7O8o—thank you, @usejbrowse!
— LotusBase (@lotusbase) March 1, 2016

We have successfully upgraded our jBrowse installation, used to power visualization of the [*L. japonicus* genome](/genome), to [version 1.12.0](http://jbrowse.org/jbrowse-1-12-0/). The new version comes with several exciting features, such as:

> - Added ability to open a new genome in FASTA format from the browser. Also supports indexed FASTA.
> - Support for inline reference sequence configurations.
>
Source: http://jbrowse.org/jbrowse-1-12-0/


text:
namespace {

Browser* FindOneOtherBrowserForProfile(Profile* profile,
                                       Browser* not_this_browser) {
  for (chrome::BrowserIterator it; !it.done(); it.Next()) {
    if (*it != not_this_browser && it->profile() == profile)
      return *it;
  }
  return NULL;
}

// We need to serve the test files so that PRE_Test and Test can access the same
// page using the same URL. In addition, perceived security origin of the page
// needs to stay the same, so e.g., redirecting the URL requests doesn't
// work. (If we used a test server, the PRE_Test and Test would have separate
// instances running on separate ports.)

base::LazyInstance<std::map<std::string, std::string> > g_file_contents =
    LAZY_INSTANCE_INITIALIZER;

net::URLRequestJob* URLRequestFaker(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const std::string& scheme) {
  return new net::URLRequestTestJob(
      request, network_delegate, net::URLRequestTestJob::test_headers(),
      g_file_contents.Get()[request->url().path()], true);
}

base::LazyInstance<std::string> g_last_upload_bytes = LAZY_INSTANCE_INITIALIZER;

net::URLRequestJob* URLRequestFakerForPostRequests(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const std::string& scheme) {
  // Read the uploaded data and store it to g_last_upload_bytes.
  const net::UploadDataStream* upload_data = request->get_upload();
  g_last_upload_bytes.Get().clear();
  if (upload_data) {
    const ScopedVector<net::UploadElementReader>& readers =
        upload_data->element_readers();
    for (size_t i = 0; i < readers.size(); ++i) {
      const net::UploadBytesElementReader* bytes_reader =
          readers[i]->AsBytesReader();
      if (bytes_reader) {
        g_last_upload_bytes.Get() +=
            std::string(bytes_reader->bytes(), bytes_reader->length());
      }
    }
  }
  return new net::URLRequestTestJob(
      request, network_delegate, net::URLRequestTestJob::test_headers(),
      "<title>PASS</title>Data posted",
      true);
}

}  // namespace

class BetterSessionRestoreTest : public InProcessBrowserTest {
 public:
  BetterSessionRestoreTest()
      : fake_server_address_("http://www.test.com/"),
        test_path_("session_restore/"),
        title_pass_(ASCIIToUTF16("PASS")),
        title_storing_(ASCIIToUTF16("STORING")),
        title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
        title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")) {
    // Set up the URL request filtering.
    std::vector<std::string> test_files;
    test_files.push_back("common.js");
    test_files.push_back("cookies.html");
    test_files.push_back("local_storage.html");
    test_files.push_back("post.html");
    test_files.push_back("post_with_password.html");
    test_files.push_back("session_cookies.html");
    test_files.push_back("session_storage.html");
    base::FilePath test_file_dir;
    CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &test_file_dir));
    test_file_dir =
        test_file_dir.AppendASCII("chrome/test/data").AppendASCII(test_path_);

    for (std::vector<std::string>::const_iterator it = test_files.begin();
         it != test_files.end(); ++it) {
      base::FilePath path = test_file_dir.AppendASCII(*it);
      std::string contents;
      CHECK(file_util::ReadFileToString(path, &contents));
      g_file_contents.Get()["/" + test_path_ + *it] = contents;
      net::URLRequestFilter::GetInstance()->AddUrlHandler(
          GURL(fake_server_address_ + test_path_ + *it),
          &URLRequestFaker);
    }
    net::URLRequestFilter::GetInstance()->AddUrlHandler(
        GURL(fake_server_address_ + test_path_ + "posted.php"),
        &URLRequestFakerForPostRequests);
  }

 protected:
  void StoreDataWithPage(const std::string& filename) {
    StoreDataWithPage(browser(), filename);
  }

  void StoreDataWithPage(Browser* browser, const std::string& filename) {
    content::WebContents* web_contents =
        browser->tab_strip_model()->GetActiveWebContents();
    content::TitleWatcher title_watcher(web_contents, title_storing_);
    title_watcher.AlsoWaitForTitle(title_pass_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    ui_test_utils::NavigateToURL(
        browser, GURL(fake_server_address_ + test_path_ + filename));
    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(title_storing_, final_title);
  }

  void NavigateAndCheckStoredData(const std::string& filename) {
    NavigateAndCheckStoredData(browser(), filename);
  }

  void NavigateAndCheckStoredData(Browser* browser,
                                  const std::string& filename) {
    // Navigate to a page which has previously stored data; check that the
    // stored data can be accessed.
    content::WebContents* web_contents =
        browser->tab_strip_model()->GetActiveWebContents();
    content::TitleWatcher title_watcher(web_contents, title_pass_);
    title_watcher.AlsoWaitForTitle(title_storing_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    ui_test_utils::NavigateToURL(
        browser, GURL(fake_server_address_ + test_path_ + filename));
    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(title_pass_, final_title);
  }

  void CheckReloadedPageRestored() {
    CheckTitle(browser(), title_pass_);
  }

  void CheckReloadedPageRestored(Browser* browser) {
    CheckTitle(browser, title_pass_);
  }

  void CheckReloadedPageNotRestored() {
    CheckTitle(browser(), title_storing_);
  }

  void CheckTitle(Browser* browser, const string16& expected_title) {
    content::WebContents* web_contents =
        browser->tab_strip_model()->GetWebContentsAt(0);
    content::TitleWatcher title_watcher(web_contents, expected_title);
    title_watcher.AlsoWaitForTitle(title_pass_);
    title_watcher.AlsoWaitForTitle(title_storing_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    // It's possible that the title was already the right one before
    // title_watcher was created.
    string16 first_title = web_contents->GetTitle();
    if (first_title != title_pass_ &&
        first_title != title_storing_ &&
        first_title != title_error_write_failed_ &&
        first_title != title_error_empty_) {
      string16 final_title = title_watcher.WaitAndGetTitle();
      EXPECT_EQ(expected_title, final_title);
    } else {
      EXPECT_EQ(expected_title, first_title);
    }
  }

  void PostFormWithPage(const std::string& filename, bool password_present) {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::TitleWatcher title_watcher(web_contents, title_pass_);
    ui_test_utils::NavigateToURL(
        browser(), GURL(fake_server_address_ + test_path_ + filename));
    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(title_pass_, final_title);
    EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-text") !=
                std::string::npos);
    EXPECT_TRUE(g_last_upload_bytes.Get().find("text-entered") !=
                std::string::npos);
    if (password_present) {
      EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-password") !=
                  std::string::npos);
      EXPECT_TRUE(g_last_upload_bytes.Get().find("password-entered") !=
                  std::string::npos);
    }
  }

  void CheckFormRestored(bool text_present, bool password_present) {
    CheckReloadedPageRestored();
    if (text_present) {
      EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-text") !=
                  std::string::npos);
      EXPECT_TRUE(g_last_upload_bytes.Get().find("text-entered") !=
                  std::string::npos);
    } else {
      EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-text") ==
                  std::string::npos);
      EXPECT_TRUE(g_last_upload_bytes.Get().find("text-entered") ==
                  std::string::npos);
    }
    if (password_present) {
      EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-password") !=
                  std::string::npos);
      EXPECT_TRUE(g_last_upload_bytes.Get().find("password-entered") !=
                  std::string::npos);
    } else {
      EXPECT_TRUE(g_last_upload_bytes.Get().find("posted-password") ==
                  std::string::npos);
      EXPECT_TRUE(g_last_upload_bytes.Get().find("password-entered") ==
                  std::string::npos);
    }
  }

  std::string fake_server_address() {
    return fake_server_address_;
  }

  std::string test_path() {
    return test_path_;
  }

 private:
  const std::string fake_server_address_;
  const std::string test_path_;
  const string16 title_pass_;
  const string16 title_storing_;
  const string16 title_error_write_failed_;
  const string16 title_error_empty_;

  DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};

class ContinueWhereILeftOffTest : public BetterSessionRestoreTest {
 public:
  ContinueWhereILeftOffTest() { }

  virtual void SetUpOnMainThread() OVERRIDE {
    BetterSessionRestoreTest::SetUpOnMainThread();
    SessionStartupPref::SetStartupPref(
        browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
  }

  DISALLOW_COPY_AND_ASSIGN(ContinueWhereILeftOffTest);
};

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PRE_SessionCookies) {
  // Set the startup preference to "continue where I left off" and visit a page
  // which stores a session cookie.
  StoreDataWithPage("session_cookies.html");
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, SessionCookies) {
  // The browsing session will be continued; just wait for the page to reload
  // and check the stored data.
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PRE_SessionStorage) {
  StoreDataWithPage("session_storage.html");
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, SessionStorage) {
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest,
                       PRE_PRE_LocalStorageClearedOnExit) {
  StoreDataWithPage("local_storage.html");
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest,
                       PRE_LocalStorageClearedOnExit) {
  // Normally localStorage is restored.
  CheckReloadedPageRestored();
  // ... but not if it's set to clear on exit.
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, LocalStorageClearedOnExit) {
  CheckReloadedPageNotRestored();
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest,
                       PRE_PRE_CookiesClearedOnExit) {
  StoreDataWithPage("cookies.html");
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PRE_CookiesClearedOnExit) {
  // Normally cookies are restored.
  CheckReloadedPageRestored();
  // ... but not if the content setting is set to clear on exit.
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, CookiesClearedOnExit) {
  CheckReloadedPageNotRestored();
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PRE_Post) {
  PostFormWithPage("post.html", false);
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, Post) {
  CheckFormRestored(true, false);
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PRE_PostWithPassword) {
  PostFormWithPage("post_with_password.html", true);
}

IN_PROC_BROWSER_TEST_F(ContinueWhereILeftOffTest, PostWithPassword) {
  CheckReloadedPageRestored();
  // The form data contained passwords, so it's removed completely.
  CheckFormRestored(false, false);
}

class RestartTest : public BetterSessionRestoreTest {
 public:
  RestartTest() { }
  virtual ~RestartTest() { }
 protected:
  void Restart() {
    // Simluate restarting the browser, but let the test exit peacefully.
    for (chrome::BrowserIterator it; !it.done(); it.Next())
      content::BrowserContext::SaveSessionState(it->profile());
    PrefService* pref_service = g_browser_process->local_state();
    pref_service->SetBoolean(prefs::kWasRestarted, true);
#if defined(OS_WIN)
    if (pref_service->HasPrefPath(prefs::kRestartSwitchMode))
      pref_service->SetBoolean(prefs::kRestartSwitchMode, false);
#endif
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(RestartTest);
};

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_SessionCookies) {
  StoreDataWithPage("session_cookies.html");
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, SessionCookies) {
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_SessionStorage) {
  StoreDataWithPage("session_storage.html");
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, SessionStorage) {
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_LocalStorageClearedOnExit) {
  StoreDataWithPage("local_storage.html");
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, LocalStorageClearedOnExit) {
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_CookiesClearedOnExit) {
  StoreDataWithPage("cookies.html");
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, CookiesClearedOnExit) {
  CheckReloadedPageRestored();
}

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_Post) {
  PostFormWithPage("post.html", false);
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, Post) {
  CheckFormRestored(true, false);
}

IN_PROC_BROWSER_TEST_F(RestartTest, PRE_PostWithPassword) {
  PostFormWithPage("post_with_password.html", true);
  Restart();
}

IN_PROC_BROWSER_TEST_F(RestartTest, PostWithPassword) {
  // The form data contained passwords, so it's removed completely.
  CheckFormRestored(false, false);
}

// These tests ensure that the Better Session Restore features are not triggered
// when they shouldn't be.
class NoSessionRestoreTest : public BetterSessionRestoreTest {
 public:
  NoSessionRestoreTest() { }

  virtual void SetUpOnMainThread() OVERRIDE {
    BetterSessionRestoreTest::SetUpOnMainThread();
    SessionStartupPref::SetStartupPref(
        browser()->profile(), SessionStartupPref(SessionStartupPref::DEFAULT));
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(NoSessionRestoreTest);
};

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, PRE_SessionCookies) {
  StoreDataWithPage("session_cookies.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, SessionCookies) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  // When we navigate to the page again, it doens't see the data previously
  // stored.
  StoreDataWithPage("session_cookies.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, PRE_SessionStorage) {
  StoreDataWithPage("session_storage.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, SessionStorage) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  StoreDataWithPage("session_storage.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest,
                       PRE_PRE_LocalStorageClearedOnExit) {
  StoreDataWithPage("local_storage.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, PRE_LocalStorageClearedOnExit) {
  // Normally localStorage is persisted.
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  NavigateAndCheckStoredData("local_storage.html");
  // ... but not if it's set to clear on exit.
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, LocalStorageClearedOnExit) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  StoreDataWithPage("local_storage.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, PRE_PRE_CookiesClearedOnExit) {
  StoreDataWithPage("cookies.html");
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, PRE_CookiesClearedOnExit) {
  // Normally cookies are restored.
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  NavigateAndCheckStoredData("cookies.html");
  // ... but not if the content setting is set to clear on exit.
  CookieSettings::Factory::GetForProfile(browser()->profile())->
      SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
}

IN_PROC_BROWSER_TEST_F(NoSessionRestoreTest, CookiesClearedOnExit) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_EQ(std::string(content::kAboutBlankURL),
            web_contents->GetURL().spec());
  StoreDataWithPage("local_storage.html");
}


text:
package org.stqa.pft.sandbox;

public class MyFirstProgram {
	public static void main(String[] args){
		System.out.println("Hello, world!");
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace Telerik.UI.Xaml.Controls.Primitives.Menu
{
    internal class RadialSegment
    {
        internal RadialLayoutSlot LayoutSlot { get; set; }

        internal RadialMenuItem TargetItem { get; set; }

        internal object Visual { get; set; }
    }
}


text: Please see http://www.appccelerate.com/bootstrapper.html for documentation.


text:
class CreatePoems < ActiveRecord::Migration
  def change
    create_table :poems do |t|
      t.string :title
      t.string :first_line
      t.text   :content
      t.string :poet
      t.string :isbn

      t.timestamps
    end
  end
end


text:
// Copyright (c) 2014 Patrick Pulka
// License: https://raw.githubusercontent.com/ermac0/FxConnectProxy/master/LICENSE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FxConnectProxy.Samples
{
    public partial class MainForm : Form
    {
        private const string __FolderName = "FxConnectProxy.Samples";
        private const string __ConfigFile = "config.js";

        private Config Config { get; set; }

        public MainForm()
        {
            InitializeComponent();

            this.Config = this.LoadConfig();
            this.PopulateDemos();
        }

        private void PopulateDemos()
        {
            var examples = this.GetType().Assembly.GetTypes()
                .Where(x => !x.IsAbstract && !x.IsInterface && typeof(IExample).IsAssignableFrom(x))
                .Select(x => Activator.CreateInstance(x) as IExample);

            this.listBox1.Items.Clear();

            foreach (var e in examples.OrderBy(x => x.Order).ThenBy(x => x.Name))
            {
                if (e.IsHidden)
                {
                    continue;
                }

                this.listBox1.Items.Add(new ListItem(e.Name, e.GetType()));
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.ShowConfigDialog();
        }

        private void ShowConfigDialog()
        {
            var dialog = new ConfigForm();

            dialog.SaveClicked += this.OnSaveClicked;
            dialog.Setup(this.Config);

            this.Hide();
            dialog.ShowDialog(this);
            this.Show();
        }

        void OnSaveClicked(object sender, SaveConfigEventArgs e)
        {
            this.Config = e.Config;
            this.SaveConfig(this.Config);
        }

        private void SaveConfig(Config config)
        {
            var baseDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), __FolderName);
            Directory.CreateDirectory(baseDir);

            if (!config.SavePassword)
            {
                config.Password = null;
            }

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Config));

            using (var s = File.Open(Path.Combine(baseDir, __ConfigFile), FileMode.Create))
            {
                serializer.WriteObject(s, config);
            }
        }

        private Config LoadConfig()
        {
            var baseDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), __FolderName);
            var path = Path.Combine(baseDir, __ConfigFile);

            if (File.Exists(path))
            {
                var config = new Config();
                var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(config.GetType());

                using (var s = File.OpenRead(path))
                {
                    config = (Config)serializer.ReadObject(s);
                }

                return config;
            }

            return null;
        }

        class ListItem
        {
            public string Text { get; set; }

            public Type Type { get; set; }

            public override string  ToString()
            {
 	             return "  " + (string.IsNullOrEmpty(this.Text) ? "Item" : this.Text);
            }

            public ListItem()
            {
            }

            public ListItem(string text, Type type)
            {
                this.Text = text;
                this.Type = type;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.LaunchExample();
        }

        private void LaunchExample()
        {
            // Validate config.
            if (this.Config == null)
            {
                MessageBox.Show("Configure account first.", "Error");
                return;
            }

            if (string.IsNullOrEmpty(this.Config.Username))
            {
                MessageBox.Show("Provide User.", "Error");
                return;
            }
            if (string.IsNullOrEmpty(this.Config.Url))
            {
                MessageBox.Show("Provide URL.", "Error");
                return;
            }
            if (string.IsNullOrEmpty(this.Config.AccountType))
            {
                MessageBox.Show("Provide Account Type.", "Error");
                return;
            }

            var confirmed = false;

            if (string.IsNullOrEmpty(this.Config.Password))
            {
                var passForm = new PasswordForm();
                passForm.ConfirmClicked += (s, e) =>
                    {
                        this.Config.Password = e.Password;

                        // Allow for an empty password if user confirms!
                        confirmed = true;
                    };
                passForm.ShowDialog(this);
            }

            if (string.IsNullOrEmpty(this.Config.Password) && !confirmed)
            {
                MessageBox.Show("Password not provided.", "Error");
                return;
            }

            var t = this.listBox1.SelectedItem as ListItem;
            if (t == null)
            {
                MessageBox.Show("Select example to run.", "Error");
                return;
            }

            var form = new ExampleForm();
            form.Setup(t.Type, this.Config);
            this.Hide();
            form.ShowDialog(this);
            this.Show();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = this.listBox1.SelectedItem as ListItem;
            if (item != null)
            {
                var inst = Activator.CreateInstance(item.Type) as IExample;
                this.textBox1.Text = inst.Description;
            }
        }
    }
}


text:
namespace System.IO.Pipelines
{
    internal struct SegmentEnumerator
    {
        private BufferSegment _segment;
        private SegmentPart _current;
        private int _startIndex;
        private readonly int _endIndex;
        private readonly BufferSegment _endSegment;

        /// <summary>
        ///
        /// </summary>
        public SegmentEnumerator(ReadCursor start, ReadCursor end)
        {
            _startIndex = start.Index;
            _segment = start.Segment;
            _endSegment = end.Segment;
            _endIndex = end.Index;
            _current = default(SegmentPart);
        }

        /// <summary>
        /// The current <see cref="Memory{Byte}"/>
        /// </summary>
        public SegmentPart Current => _current;

        /// <summary>
        /// Moves to the next <see cref="Memory{Byte}"/> in the <see cref="ReadableBuffer"/>
        /// </summary>
        /// <returns></returns>
        public bool MoveNext()
        {
            if (_segment == null)
            {
                return false;
            }

            int start = _segment.Start;
            int end = _segment.End;

            if (_startIndex != 0)
            {
                start = _startIndex;
                _startIndex = 0;
            }

            if (_segment == _endSegment)
            {
                end = _endIndex;
            }

            _current = new SegmentPart()
            {
                Segment = _segment,
                Start = start,
                End = end,
            };

            if (_segment == _endSegment)
            {
                _segment = null;
            }
            else
            {
                _segment = _segment.Next;
                if (_segment == null)
                {
                    throw new InvalidOperationException("Segments ended by end was never seen");
                }
            }

            return true;
        }

        public SegmentEnumerator GetEnumerator()
        {
            return this;
        }

        /// <summary>
        ///
        /// </summary>
        public void Reset()
        {
            ThrowHelper.ThrowNotSupportedException();
        }

        internal struct SegmentPart
        {
            public BufferSegment Segment;
            public int Start;
            public int End;

            public int Length => End - Start;
        }
    }
}