text:
import * as logger from '../support/logging';
import { windowManager } from '../support/window_manager';
import { CodebasesPage } from '../page_objects/space_codebases.page';
import { SpaceDashboardInteractionsFactory } from './space_dashboard_interactions';
import { PageOpenMode } from '../page_objects/base.page';

export abstract class CodebasesInteractionsFactory {

    public static create(strategy: string, spaceName: string): CodebasesInteractions {
        return new CodebasesInteractionsImpl(strategy, spaceName);
    }
}

export interface CodebasesInteractions {

    openCodebasesPage(mode: PageOpenMode): void;

    createWorkspace(): Promise<string>;

    createAndOpenWorkspace(): Promise<string>;

    getWorkspaces(): Promise<string[]>;

    getSelectedWorkspace(): Promise<string>;
}

abstract class AbstractCodebasesInteractions implements CodebasesInteractions {

    protected strategy: string;

    protected spaceName: string;

    protected page: CodebasesPage;

    constructor(strategy: string, spaceName: string) {
        this.strategy = strategy;
        this.spaceName = spaceName;
        this.page = new CodebasesPage();
    }

    public async abstract createWorkspace(): Promise<string>;

    public async abstract createAndOpenWorkspace(): Promise<string>;

    public async openCodebasesPage(mode: PageOpenMode): Promise<void> {
        logger.info('Open codebases page');
        if (mode === PageOpenMode.UseMenu) {
            let dashboardInteractions = SpaceDashboardInteractionsFactory.create(this.strategy, this.spaceName);
            await dashboardInteractions.openSpaceDashboardPage(mode);
            await dashboardInteractions.openCodebasesPage();
            await this.page.open();
        } else {
            await this.page.open(mode);
        }
    }

    public async getWorkspaces(): Promise<string[]> {
        return this.page.getWorkspaces();
    }

    public async getSelectedWorkspace(): Promise<string> {
        return this.page.getSelectedWorkspace();
    }
}

class CodebasesInteractionsImpl extends AbstractCodebasesInteractions {

    public async createWorkspace(): Promise<string> {
        logger.info('Create and open workspace');
        try {
            logger.debug('Create workspace');
            await this.page.createWorkspace();
            logger.debug('Create workspace was successful');
        } catch (e) {
            logger.debug('Create workspace failed, trying again');
            await this.page.createWorkspace();
            logger.debug('Create workspace was successful');
        }
        return this.page.getSelectedWorkspace();
    }

    public async createAndOpenWorkspace(): Promise<string> {
        let workspace = await this.createWorkspace();
        await this.page.openWorkspace();
        await windowManager.switchToNewWindow();
        return Promise.resolve(workspace);
    }
}


text: OpenGL with GLFW and GLEW

redpajama_set_name: RedPajamaGithub


text:
package com.simplifiedlogic.nitro.jshell.json.handler;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.simplifiedlogic.nitro.jlink.data.DimData;
import com.simplifiedlogic.nitro.jlink.data.DimDetailData;
import com.simplifiedlogic.nitro.jlink.data.DimSelectData;
import com.simplifiedlogic.nitro.jlink.data.DimToleranceData;
import com.simplifiedlogic.nitro.jlink.intf.IJLDimension;
import com.simplifiedlogic.nitro.jshell.json.request.JLDimensionRequestParams;
import com.simplifiedlogic.nitro.jshell.json.response.JLDimensionResponseParams;
import com.simplifiedlogic.nitro.rpc.JLIException;

/**
 * Handle JSON requests for "dimension" functions
 *
 * @author Adam Andrews
 *
 */
public class JLJsonDimensionHandler extends JLJsonCommandHandler implements JLDimensionRequestParams, JLDimensionResponseParams {

	private IJLDimension dimHandler = null;

	/**
	 * @param dimHandler
	 */
	public JLJsonDimensionHandler(IJLDimension dimHandler) {
		this.dimHandler = dimHandler;
	}

	/* (non-Javadoc)
	 * @see com.simplifiedlogic.nitro.jshell.json.handler.JLJsonCommandHandler#handleFunction(java.lang.String, java.lang.String, java.util.Hashtable)
	 */
	public Hashtable<String, Object> handleFunction(String sessionId, String function, Hashtable<String, Object> input) throws JLIException {
		if (function==null)
			return null;

		if (function.equals(FUNC_SET)) return actionSet(sessionId, input);
		else if (function.equals(FUNC_COPY)) return actionCopy(sessionId, input);
		else if (function.equals(FUNC_LIST)) return actionList(sessionId, input);
		else if (function.equals(FUNC_LIST_DETAIL)) return actionListDetail(sessionId, input);
		else if (function.equals(FUNC_SHOW)) return actionShow(sessionId, input);
		else if (function.equals(FUNC_USER_SELECT)) return actionUserSelect(sessionId, input);
		else if (function.equals(FUNC_SET_TEXT)) return actionSetText(sessionId, input);
		else {
			throw new JLIException("Unknown function name: " + function);
		}
	}

	private Hashtable<String, Object> actionSet(String sessionId, Hashtable<String, Object> input) throws JLIException {
        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        String dimname = checkStringParameter(input, PARAM_NAME, true);
        Object value = checkParameter(input, PARAM_VALUE, false);
        boolean encoded = checkFlagParameter(input, PARAM_ENCODED, false, false);

        dimHandler.set(modelname, dimname, value, encoded, sessionId);

		return null;
	}

	private Hashtable<String, Object> actionCopy(String sessionId, Hashtable<String, Object> input) throws JLIException {
	    String modelname = checkStringParameter(input, PARAM_MODEL, false);
	    String dimname = checkStringParameter(input, PARAM_NAME, true);
	    String to_name = checkStringParameter(input, PARAM_TONAME, true);
	    String to_model = checkStringParameter(input, PARAM_TOMODEL, false);

	    dimHandler.copy(modelname, dimname, to_name, to_model, sessionId);

		return null;
	}

	private Hashtable<String, Object> actionList(String sessionId, Hashtable<String, Object> input) throws JLIException {
        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        String namePattern = checkStringParameter(input, PARAM_NAME, false);
        List<String> dimNames = null;
        Object namesObj = checkParameter(input, PARAM_NAMES, false);
        if (namesObj!=null) {
        	dimNames = getStringListValue(namesObj);
        }
        String dimType = checkStringParameter(input, PARAM_DIM_TYPE, false);
        boolean encoded = checkFlagParameter(input, PARAM_ENCODED, false, false);
        boolean select = checkFlagParameter(input, PARAM_SELECT, false, false);

        List<DimData> dims = dimHandler.list(modelname, namePattern, dimNames, dimType, encoded, select, sessionId);

		Hashtable<String, Object> out = new Hashtable<String, Object>();
        if (dims!=null) {
			Vector<Map<String, Object>> outDims = new Vector<Map<String, Object>>();
			out.put(OUTPUT_DIMLIST, outDims);
			Map<String, Object> outDim = null;
			for (DimData dim : dims) {
				outDim = new Hashtable<String, Object>();
				if (dim.getName()!=null)
					outDim.put(OUTPUT_NAME, dim.getName());
				if (dim.getValue()!=null)
					outDim.put(OUTPUT_VALUE, dim.getValue());
				outDim.put(OUTPUT_ENCODED, Boolean.valueOf(dim.isEncoded()));
				outDim.put(OUTPUT_DWG_DIM, Boolean.valueOf(dim.isDrawingDimension()));

				outDims.add(outDim);
			}

        }
		return out;
	}

	private Hashtable<String, Object> actionListDetail(String sessionId, Hashtable<String, Object> input) throws JLIException {
        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        String namePattern = checkStringParameter(input, PARAM_NAME, false);
        List<String> dimNames = null;
        Object namesObj = checkParameter(input, PARAM_NAMES, false);
        if (namesObj!=null) {
        	dimNames = getStringListValue(namesObj);
        }
        String dimType = checkStringParameter(input, PARAM_DIM_TYPE, false);
        boolean encoded = checkFlagParameter(input, PARAM_ENCODED, false, false);
        boolean select = checkFlagParameter(input, PARAM_SELECT, false, false);

        List<DimDetailData> dims = dimHandler.listDetail(modelname, namePattern, dimNames, dimType, encoded, select, sessionId);

		Hashtable<String, Object> out = new Hashtable<String, Object>();
        if (dims!=null) {
			Vector<Map<String, Object>> outDims = new Vector<Map<String, Object>>();
			out.put(OUTPUT_DIMLIST, outDims);
			Map<String, Object> outDim = null;
			for (DimDetailData dim : dims) {
				outDim = new Hashtable<String, Object>();
				if (dim.getName()!=null)
					outDim.put(OUTPUT_NAME, dim.getName());
				if (dim.getValue()!=null)
					outDim.put(OUTPUT_VALUE, dim.getValue());
				outDim.put(OUTPUT_ENCODED, Boolean.valueOf(dim.isEncoded()));
				outDim.put(OUTPUT_DWG_DIM, Boolean.valueOf(dim.isDrawingDimension()));

				DimToleranceData tol = dim.getTolerance();
				if (tol!=null) {
					if (tol.getToleranceType()!=null)
						outDim.put(OUTPUT_TOLERANCE_TYPE, tol.getToleranceType());
					if (DimToleranceData.TYPE_LIMITS.equals(tol.getToleranceType())) {
						outDim.put(OUTPUT_TOL_LOWER_LIMIT, tol.getLowerLimit());
						outDim.put(OUTPUT_TOL_UPPER_LIMIT, tol.getUpperLimit());
					}
					else if (DimToleranceData.TYPE_PLUS_MINUS.equals(tol.getToleranceType())) {
						outDim.put(OUTPUT_TOL_PLUS, tol.getPlus());
						outDim.put(OUTPUT_TOL_MINUS, tol.getMinus());
					}
					else if (DimToleranceData.TYPE_SYMMETRIC.equals(tol.getToleranceType())) {
						outDim.put(OUTPUT_TOL_SYMMETRIC_VALUE, tol.getSymmetricValue());
					}
					else if (DimToleranceData.TYPE_SYM_SUPERSCRIPT.equals(tol.getToleranceType())) {
						outDim.put(OUTPUT_TOL_SYMMETRIC_VALUE, tol.getSymmetricValue());
					}
					else if (DimToleranceData.TYPE_ISODIN.equals(tol.getToleranceType())) {
						if (tol.getTableName()!=null)
							outDim.put(OUTPUT_TOL_TABLE_NAME, tol.getTableName());
						outDim.put(OUTPUT_TOL_TABLE_COLUMN, tol.getTableColumn());
						if (tol.getTableType()!=null)
							outDim.put(OUTPUT_TOL_TABLE_TYPE, tol.getTableType());
					}
				}
				outDim.put(OUTPUT_SHEET, dim.getSheetNo());
				if (dim.getViewName()!=null)
					outDim.put(OUTPUT_VIEW_NAME, dim.getViewName());
				if (dim.getDimType()!=null)
					outDim.put(OUTPUT_DIM_TYPE, dim.getDimType());
				if (dim.getText()!=null && dim.getText().length>0)
					outDim.put(OUTPUT_TEXT, dim.getText());

				Map<String, Object> recPt = writePoint(dim.getLocation());
				if (recPt!=null)
					outDim.put(OUTPUT_LOCATION, recPt);

				outDims.add(outDim);
			}

        }
		return out;
	}

	private Hashtable<String, Object> actionShow(String sessionId, Hashtable<String, Object> input) throws JLIException {
        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        String asmname = checkStringParameter(input, PARAM_ASSEMBLY, false);
        String dimname = checkStringParameter(input, PARAM_NAME, true);
        List<Integer> pathList = getIntArray(PARAM_PATH, checkParameter(input, PARAM_PATH, false));
        int[] path = null;
        if (pathList!=null && pathList.size()>0) {
        	int len = pathList.size();
        	path = new int[len];
        	for (int i=0; i<len; i++)
        		path[i] = pathList.get(i);
        }
        boolean show = checkFlagParameter(input, PARAM_SHOW, false, true);

        dimHandler.show(modelname, asmname, dimname, path, show, sessionId);

		return null;
	}

	private Hashtable<String, Object> actionUserSelect(String sessionId, Hashtable<String, Object> input) throws JLIException {
        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        int max = checkIntParameter(input, PARAM_MAX, false, Integer.valueOf(1)).intValue();

        List<DimSelectData> dims = dimHandler.userSelect(modelname, max, sessionId);

		Hashtable<String, Object> out = new Hashtable<String, Object>();
        if (dims!=null) {
			Vector<Map<String, Object>> outDims = new Vector<Map<String, Object>>();
			out.put(OUTPUT_DIMLIST, outDims);
			Map<String, Object> outDim = null;
			for (DimSelectData dim : dims) {
				outDim = new Hashtable<String, Object>();
				if (dim.getName()!=null)
					outDim.put(OUTPUT_NAME, dim.getName());
				if (dim.getValue()!=null)
					outDim.put(OUTPUT_VALUE, dim.getValue());
				outDim.put(OUTPUT_ENCODED, Boolean.valueOf(dim.isEncoded()));

				if (dim.getModelname()!=null)
					outDim.put(PARAM_MODEL, dim.getModelname());
				if (dim.getRelationId()!=null)
					outDim.put(PARAM_RELATION_ID, dim.getRelationId());

				outDims.add(outDim);
			}

        }
		return out;
	}

	private Hashtable<String, Object> actionSetText(String sessionId, Hashtable<String, Object> input) throws JLIException {

        String modelname = checkStringParameter(input, PARAM_MODEL, false);
        String dimname = checkStringParameter(input, PARAM_NAME, true);
        Object valueObj = checkParameter(input, PARAM_TEXT, false);
//        Object prefixObj = checkParameter(input, PARAM_PREFIX, false);
//        Object suffixObj = checkParameter(input, PARAM_SUFFIX, false);
        boolean encoded = checkFlagParameter(input, PARAM_ENCODED, false, false);

//        dimHandler.setText(modelname, dimname, valueObj, prefixObj, suffixObj, encoded, sessionId);
        dimHandler.setText(modelname, dimname, valueObj, encoded, sessionId);

        return null;
	}

}


text:
package cd.go.artifact.dummy.model;

import cd.go.artifact.dummy.config.Field;
import cd.go.artifact.dummy.config.Metadata;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

import static cd.go.artifact.dummy.DummyArtifactPlugin.GSON;

public class ArtifactConfig {
    @SerializedName("Source")
    private String source;

    @SerializedName("Destination")
    private String destination;

    public String getSource() {
        return source;
    }

    public String getDestination() {
        return destination;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ArtifactConfig)) return false;

        ArtifactConfig that = (ArtifactConfig) o;

        return source != null ? source.equals(that.source) : that.source == null;
    }

    @Override
    public int hashCode() {
        return source != null ? source.hashCode() : 0;
    }

    public ValidationResult validate() {
        ValidationResult result = new ValidationResult();
        if (StringUtils.isBlank(source)) {
            result.addError("Source", "must be provided.");
        }

        if (StringUtils.isBlank(destination)) {
            result.addError("Destination", "must be provided.");
        }

        return result;
    }

    public static ArtifactConfig from(String json) {
        return GSON.fromJson(json, ArtifactConfig.class);
    }

    public static String artifactConfigMetadata() {
        return GSON.toJson(Arrays.asList(
                new Field("Source", new Metadata(true, false)),
                new Field("Destination", new Metadata(true, false))
        ));
    }
}


text:
package org.apereo.cas;

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

/**
 * This is {@link AllTestsSuite}.
 *
 * @author leeyc0
 * @since 6.2.0
 */
@SelectClasses(JdbcServletContextListenerTests.class)
@Suite
public class AllTestsSuite {
}


text:
(function($) {

    'use strict';

    $(document).ready(function() {

        d3.json('../assets/js/init-nvd3-charts.json', function(data) {
            nv.addGraph(function() {
                var chart = nv.models.cumulativeLineChart()
                .x(function(d) { return d[0] })
                .y(function(d) { return d[1]/100 }) //adjusting, 100% is 1.00, not 100 as it is in the data
                .color(d3.scale.category10().range())
                .useInteractiveGuideline(true);

                chart.xAxis
                .tickValues([1078030800000,1122782400000,1167541200000,1251691200000])
                .tickFormat(function(d) {
                    return d3.time.format('%x')(new Date(d))
                });

                chart.yAxis
                .tickFormat(d3.format(',.1%'));

                d3.select('#nvd3-line svg')
                .datum(data)
                .call(chart);

                //TODO: Figure out a good way to do this automatically
                nv.utils.windowResize(chart.update);

                return chart;
            });
        });

        d3.json('http://nvd3.org/examples/stackedAreaData.json', function(data) {
          nv.addGraph(function() {
            var chart = nv.models.stackedAreaChart()
                          .margin({right: 100})
                          .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                          .y(function(d) { return d[1] })   //...in case your data is formatted differently.
                          .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                          .rightAlignYAxis(true)      //Let's move the y-axis to the right side.
                          .transitionDuration(500)
                          .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                          .clipEdge(true);

            //Format x-axis labels with custom function.
            chart.xAxis
                .tickFormat(function(d) {
                  return d3.time.format('%x')(new Date(d))
            });

            chart.yAxis
                .tickFormat(d3.format(',.2f'));

            d3.select('#nvd3-stacked svg')
              .datum(data)
              .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
          });
        })

    });

})(window.jQuery);


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\Constraint;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Util\ThrowableToStringMapper;

#[CoversClass(ArrayHasKey::class)]
#[Small]
final class ArrayHasKeyTest extends ConstraintTestCase
{
    public function testConstraintArrayHasKey(): void
    {
        $constraint = new ArrayHasKey(0);

        $this->assertFalse($constraint->evaluate([], '', true));
        $this->assertEquals('has the key 0', $constraint->toString());
        $this->assertCount(1, $constraint);

        try {
            $constraint->evaluate([]);
        } catch (ExpectationFailedException $e) {
            $this->assertEquals(
                <<<'EOF'
Failed asserting that an array has the key 0.

EOF
                ,
                ThrowableToStringMapper::map($e)
            );

            return;
        }

        $this->fail();
    }

    public function testConstraintArrayHasKey2(): void
    {
        $constraint = new ArrayHasKey(0);

        try {
            $constraint->evaluate([], 'custom message');
        } catch (ExpectationFailedException $e) {
            $this->assertEquals(
                <<<EOF
custom message\nFailed asserting that an array has the key 0.

EOF
                ,
                ThrowableToStringMapper::map($e)
            );

            return;
        }

        $this->fail();
    }

    public function testConstraintArrayHasKey0(): void
    {
        $constraint = new ArrayHasKey(0);

        try {
            $constraint->evaluate(0, '');
        } catch (ExpectationFailedException  $e) {
            $this->assertEquals(
                <<<'EOF'
Failed asserting that an array has the key 0.

EOF
                ,
                ThrowableToStringMapper::map($e)
            );
        }
    }
}


text:
<?php

use cobisja\BootHelp\BootHelp;

$intro_text = <<<EOT
    Welcome to this simple BootHelp Demo. This demo app is designed to show you how you can
    use <stong>BootHelp classes</stong> to easily generate HTML code formatted according
    to Bootstrap specifications without to write down a lot of complicated HTML code.
EOT;

echo BootHelp::content_tag('div', ['class'=>'demo-info row'], function() use ($intro_text) {
    return [
        BootHelp::content_tag('h1', 'Introduction'),
        BootHelp::content_tag('p', $intro_text),
        BootHelp::content_tag('p', 'Check the source code and you\'ll see the amount of HTML code used '
            . 'is the minimun. No more boring HTML code!'),
        BootHelp::content_tag('p', 'This demo include 2 simple games:'),
        BootHelp::panel_row(['column_class'=>'col-sm-6'], function(){
            return [
                BootHelp::panel(['title'=>'Guess the word', 'context'=>'primary'], function(){
                    return [BootHelp::icon('hand-right'), ' Guess the hidden word selected randomly.'];
                }),
                BootHelp::panel(['title'=>'Guess the number', 'context'=>'success'], function(){
                    return [BootHelp::icon('hand-right'), ' Guess a number picked randomly between 0 and 100.'];
                })
            ];
        })
    ];
});

echo BootHelp::content_tag('div', ['class'=>'demo-info row'], function(){
    return [
        BootHelp::content_tag('p', 'General information about how BootHelp components were used to built this demo:'),
        BootHelp::panel_row(['column_class'=>'col-sm-6'], function(){
            return[
                BootHelp::panel(['title'=>'BootHelp components list used', 'context'=>'warning'], function(){
                    return
                        '

Alert box

Navbar

Modal

Button

Dropdown (within navbar)

Icon

Progress bar

Panel

Panel row

Content tag

Link to

                    ';
                }),
                BootHelp::panel(['title'=>'List of classes/scripts where you can find BootHelp components definitions', 'context'=>'danger'], function(){
                    return [
                        BootHelp::content_tag('p', 'All classes are under BootHelpDemo namespace'),
                        BootHelp::content_tag('p', 'Classes:'),
                        '

Game (Button, Icon, Panel, Modal, Content Tag, Progress Bar and Alert Box).

GuessNumberGame (Content Tag, Progress bar).

GuessWordGame (Button, Button group).

',
                        BootHelp::content_tag('p', 'Scripts:'),
                        '

about.php (Modal, Content Tag, Icon, LinkTo).

demo_info.php (Panel, Panel row, Icon).

navbar.php (Navbar, Divider, Dropdown, LinkTo, Content Tag).

',
                    ];
                })
            ];
        })
    ];
});

echo BootHelp::content_tag('div', ['class'=>'row'], function(){
    return BootHelp::content_tag('h3', 'Bootstrap + PHP = BootHelp :-D', ['class'=>'pull-right']);
});


text:
package xyz.hyperreal.markdown

import org.scalatest._
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class Combinations extends FreeSpec with ScalaCheckPropertyChecks with Matchers with Tests
{
	"examples" in
	{
		markdown( """
			|> ## This is a header.
			|>
			|> 1.   This is the first list item.
			|> 2.   This is the second list item.
			|>
			|> > This is nested blockquote.
			|>
			|>
			|> Here's some example code:
			|>
			|>     return shell_exec("echo $input | .markdown_script");
			|""".stripMargin
		) shouldBe """

This is a header.

This is the first list item.

This is the second list item.

This is nested blockquote.

Here's some example code:

return shell_exec("echo $input | .markdown_script");

"""
	}
}


text:
var normalizeArgumentsAndValidate =
    require('schemaUtils').normalizeArgumentsAndValidate
var sendRequest = require('sendRequest').sendRequest;

function extendSchema(schema) {
  var extendedSchema = $Array.slice(schema);
  $Array.unshift(extendedSchema, {'type': 'string'});
  return extendedSchema;
}

// TODO(devlin): Combine parts of this and other custom types (ChromeSetting,
// ContentSetting, etc).
function StorageArea(namespace, schema) {
  // Binds an API function for a namespace to its browser-side call, e.g.
  // storage.sync.get('foo') -> (binds to) ->
  // storage.get('sync', 'foo').
  var self = this;
  function bindApiFunction(functionName) {
    var rawFunSchema =
        $Array.filter(schema.functions,
                      function(f) { return f.name === functionName; })[0];
    // normalizeArgumentsAndValidate expects a function schema of the form
    // { name: <name>, definition: <definition> }.
    var funSchema = {
      __proto__: null,
      name: rawFunSchema.name,
      definition: rawFunSchema
    };
    self[functionName] = function() {
      var args = $Array.slice(arguments);
      args = normalizeArgumentsAndValidate(args, funSchema);
      return sendRequest(
          'storage.' + functionName,
          $Array.concat([namespace], args),
          extendSchema(funSchema.definition.parameters),
          {__proto__: null, preserveNullInObjects: true});
    };
  }
  var apiFunctions = ['get', 'set', 'remove', 'clear', 'getBytesInUse'];
  $Array.forEach(apiFunctions, bindApiFunction);
}

exports.$set('StorageArea', StorageArea);


text:
Level 12: use template engine extensions
================================================================================

There are three possible ways to provide extensions for your template engine.
Let's take jinja2 as an example.

1. Ready made extensions
-----------------------------

jinja2 comes with a lot of extensions. In order not to be the blocker in the
middle, **extensions** is allowed in moban file to initialize jinja2 engine
with desired extensions. Two extensions, expression-statement and loop-controls
are enabled by default.

The extensions syntax is::

   extensions:
     template_type:
       - template.engine.specific.extension

For example::

   extensions:
     jinja2:
       - jinja2.ext.i18n

Please also note that the following extensions are included by default:
`jinja2.ext.do`, `jinja2.ext.loopcontrols`

**Command line**

if you intend to use extensions for one off usage, please use '-e' cli option.
for example: `moban -e jinja2=your_custom_jinja2_extension <https://github.com/chfw/math-sheets/blob/master/reception/a_op_b_op_c/make.sh>`_

2. Ad-hoc declaration
-----------------------------

Let's say you are fond of some existing functions, for example, ansible's combine
filter. With moban, you can immediately include it for your template via the following
syntax:

.. code-block::

   extensions:
     jinja2:
       - filter:module.path.filter_function
       - test:module.path.test_function
       - global:identifier=module.path.variable

For example::

   extensions:
     jinja2:
       - filter:ansible.plugins.filter.core.combine
       - test:moban.externals.file_system.exists

**Command line**

.. code-block:: bash

   $ moban -e jinja2=filter:module.path.filter_function jinja2=test:module.path.test_function jinja2=global:identifier=module.path.variable

you can do this::

   $ moban -e jinja2=filter:module.path.filter_function \
              jinja2=test:module.path.test_function \
              jinja2=global:identifier=module.path.variable

3. Make your own extensions
--------------------------------

You can choose to write an extension for the template type of your choice.
For example, you can write a reusable extension for jinja2. moban will be
able to load it as it is.

If you decide that you only want to write them for moban but for your own
use, you can follow `Level 7: Custom jinja filters, tests and globals` and
write your own. When you would like to make yours avaiable for all moban
users, you can follow `moban-jinja2-github <https://github.com/moremoban/moban-jinja2-github>`_ and
`moban-ansible <https://github.com/moremoban/moban-ansible>`_

Evaluation
--------------------------------------------------------------------------------
Please go to `docs/level-12-use-template-engine-extensions` directory.

If you notice the file `a.template`, we are using a for loop control. This is
because moban comes with two default extensions loop-controls and
expression-statement.

Now, let us try to use the extension `with`. To do that, we have to enable the
extension in the `.moban.yml` file following the above syntax. Now, the
extension can be used in the jinja2 templates. One such example is shown in the
`b.template` file.

.. note::

  For some extensions, you may need to define `template environment parameters`.
  In that case, you can take help of our `user defined template types` feature.
  Please read level-18 for more info. We have explained it using an example
  here.

  Let us consider the example of `jinja2_time`. If you want to use
  `datetime_format` attribute, you need to specify the same using environmental
  parameters, *i.e*  `env.datetime_format = '%a, %d %b %Y %H:%M:%S'`. In order
  to do this, you can specify `datetime_format` using environmental parameters,
  something like::

    configuration:
      template_types:
        my_own_type:
          base_type: jinja2
          file_extensions:
            - file_type_of_my_choice
          options:
            datetime_format: %a, %d %b %Y %H:%M:%S
            extensions:
              - jinja2_time.TimeExtension
    targets:
      - a.output: a.template.file_type_of_my_choice


text:
var _ = require('lodash');
var whoAmI = require('./whoAmI');
var config = require('../config');
var getData = require('./getData');
var logData = require('./logData');
var logEvent = require('./logEvent');
var register = require('./register');
var getEvents = require('./getEvents');
var getDevices = require('./getDevices');
var resetToken = require('./resetToken');
var authDevice = require('./authDevice');
var unregister = require('./unregister');
var revokeToken = require('./revokeToken');
var claimDevice = require('./claimDevice');
var getPublicKey = require('./getPublicKey');
var securityImpl = require('./getSecurityImpl');
var createActivity = require('./createActivity');
var updateSocketId = require('./updateSocketId');
var updatePresence = require('./updatePresence');
var getLocalDevices = require('./getLocalDevices');
var getSystemStatus = require('./getSystemStatus');
var updateFromClient = require('./updateFromClient');
var generateAndStoreToken = require('./generateAndStoreToken');
var debug = require('debug')('meshblu:protocol:socketLogic');
var MessageIOClient = require('./messageIOClient');
var MeshbluEventEmitter = require('./MeshbluEventEmitter');
var SocketLogicThrottler = require('./SocketLogicThrottler');
var saveDataIfAuthorized = require('./saveDataIfAuthorized');
var clearCache = require('./clearCache');

function getActivity(topic, socket, device, toDevice){
  return createActivity(topic, socket.ipAddress, device, toDevice);
}

function getDevice(socket, callback) {
  if(socket.skynetDevice){
    whoAmI(socket.skynetDevice.uuid, true, function(device) {
      return callback(null, device);
    });
  }else{
    return callback(new Error('skynetDevice not found for socket' + socket), null);
  }
}

function socketLogic (socket, secure, skynet){
  var ipAddress = socket.handshake.headers['x-forwarded-for'] || socket.request.connection._peername.address;
  var throttler = new SocketLogicThrottler(socket);
  var meshbluEventEmitter = new MeshbluEventEmitter(config.uuid, config.forwardEventUuids, skynet.sendMessage);

  socket.ipAddress = ipAddress;
  logEvent(100, {socketid: socket.id, protocol: 'websocket'});

  socket.emit('identify', { socketid: socket.id });
  socket.on('identity', throttler.throttle(function (data) {
    socket.auto_set_online = data.auto_set_online !== false
    delete data.auto_set_online
    data = _.extend({}, data, {
      socketid: socket.id,
      ipAddress: ipAddress,
      secure: secure
    });

    if (socket.auto_set_online) {
      data.online = true;
    }

    if(!data.protocol){
      data.protocol = 'websocket';
    }
    updateSocketId(data, function(auth){

      if (auth.status != 201){
        socket.emit('notReady', {api: 'connect', status: auth.status, uuid: data.uuid});
        return
      }

      socket.skynetDevice = auth.device;

      var readyMessage = {
        api: 'connect',
        status: auth.status,
        socketid: socket.id,
        uuid: auth.device.uuid,
        token: data.token
      };

      if (data.uuid !== auth.device.uuid) {
        readyMessage.token = auth.device.token;
      }

      socket.emit('ready', readyMessage);

      //Announce presence online
      if (socket.auto_set_online) {
        var message = {
          devices: '*',
          topic: 'device-status',
          payload: {
            online: true
          }
        };
        skynet.sendMessage(auth.device, message);
      }

      debug('setting up message bus', socket.id);
      socket.messageIOClient = new MessageIOClient();
      socket.messageIOClient.on('message', function(message){
        debug(socket.id, 'relay message', message, socket.skynetDevice.uuid);
        socket.emit('message', message);
      });

      socket.messageIOClient.on('data', function(message){
        debug(socket.id, 'relay data', message, socket.skynetDevice.uuid);
        socket.emit('data', message);
      });

      socket.messageIOClient.on('config', function(message){
        debug(socket.id, 'relay config', message);
        socket.emit('config', message);
      });

      socket.messageIOClient.start()

      // Have device join its uuid room name so that others can subscribe to it
      debug(socket.id, 'subscribing to received', auth.device.uuid);
      socket.messageIOClient.subscribe(auth.device.uuid, ['received']);

      whoAmI(data.uuid, false, function(results){
        data.auth = auth;
        data.fromUuid = results.uuid;
        data.from = _.pick(results, config.preservedDeviceProperties);
        logEvent(101, data);
      });
    });
  }));

  socket.on('disconnect', function (data) {
    debug('disconnecting', socket.id);
    if (socket.messageIOClient) {
      socket.messageIOClient.close()
    }
    if (socket.auto_set_online) {
      updatePresence(socket.id, function(){
        if (socket.skynetDevice) {
          var uuid = socket.skynetDevice.uuid;
          clearCache(uuid);
          skynet.sendConfigActivity(uuid, skynet.emitToClient);
        }
      });
    }
    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, device){
      //Announce presence offline
      if (socket.auto_set_online) {
        var message = {
          devices: '*',
          topic: 'device-status',
          payload: {online: false}
        };
        skynet.sendMessage(device, message);
      }

      logEvent(102, {api: "disconnect", socketid: socket.id, device: device});
    });
  });

  socket.on('subscribe', throttler.throttle(function(message, fn) {
      fn = fn || _.noop;
      if(!message) {
        return fn({error: "not enough information to subscribe"});
      }

      var subscriptionTypes = []

      if(message.token) {
        authDevice(message.uuid, message.token, function(error, authedDevice) {
          if (!authedDevice || error) {
            return;
          }
          subscriptionTypes.push('broadcast');
          subscriptionTypes.push('received');
          subscriptionTypes.push('sent');
          socket.messageIOClient.subscribe(message.uuid, message.types || subscriptionTypes);
        });
        return;
      }

      getDevice(socket, function(err, subscribingDevice) {
        skynet.sendActivity(getActivity('subscribe', socket, subscribingDevice));

        if(err) {
          return fn({error: "can't get subscribingDevice"});
        }

        whoAmI(message.uuid, false, function(device) {
          if(device.error){
            return fn(device);
          }

          message.toUuid = device.uuid;
          message.to = _.pick(device, config.preservedDeviceProperties);
          logEvent(204, message);

          securityImpl.canReceive(subscribingDevice, device, function(error, permission) {
            if(error) {
              debug('subscribe', 'fromDevice', subscribingDevice, 'toDevice', device, "can't receive");
              return fn({error: "unauthorized access"});
            }

            if (permission) {
              subscriptionTypes.push('broadcast');
            }

            if(device.owner == subscribingDevice.uuid){
              subscriptionTypes.push('received');
              subscriptionTypes.push('sent');
            }

            socket.messageIOClient.subscribe(message.uuid, message.types || subscriptionTypes);
            fn({"api": "subscribe", "socketid": socket.id, "toUuid": message.uuid, "result": true});
          });
        });
      });
  }));

  socket.on('unsubscribe', throttler.throttle(function(data, fn) {
    fn = fn || _.noop;

    socket.messageIOClient.unsubscribe(data.uuid, data.types || ['sent', 'received', 'broadcast']);

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('unsubscribe', socket, device));
      if(err){ return; }
      data.fromUuid = device.uuid;
      data.from = _.pick(device, config.preservedDeviceProperties);
      logEvent(205, data);
    });
    try{
      fn({"api": "unsubscribe", "uuid": data.uuid});
    } catch (e){
      console.error(e);
    }
  }));

  // APIs
  socket.on('status', throttler.throttle(function (fn) {
    fn = fn || _.noop

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('status', socket, device));
      if(err){ return; }

      getSystemStatus(function(results){

        results.fromUuid = device.uuid;
        results.from = _.pick(device, config.preservedDeviceProperties);
        logEvent(200, results);
        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('device', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    if(!data || (typeof data != 'object')){
      data = {};
    }

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('device', socket, device));
      if(err){ return; }
      var reqData = data;
      getDevices(device, data, false, function(results){
        var msg = {
          fromUuid : device.uuid,
          from : device,
          device: _.first(results.devices)
        };
        logEvent(403, msg);

        try{
          fn(msg);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('devices', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    if(!data || (typeof data != 'object')){
      data = {};
    }

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('devices', socket, device));
      if(err){ return; }
      var reqData = data;
      getDevices(device, data, false, function(results){
        results.fromUuid = device.uuid;
        results.from = _.pick(device, config.preservedDeviceProperties);
        logEvent(403, results);

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('mydevices', throttler.throttle(function (data, fn) {
    fn = fn || _.noop
    data = data || {};

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('mydevices', socket, device));
      if(err){ return; }
      data.owner = device.uuid;
      getDevices(device, data, true, function(results){
        try{
          results.fromUuid = device.uuid;
          results.from = _.pick(device, config.preservedDeviceProperties);
          logEvent(403, results);
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('localdevices', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    if(!data || (typeof data != 'object')){
      data = {};
    }

    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('localdevices', socket, device));
      if(err){ return; }
      getLocalDevices(data, device, false, function(results){
        results.fromUuid = device.uuid;
        results.from = _.pick(device, config.preservedDeviceProperties);
        logEvent(403, results);

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('unclaimeddevices', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    if(!data || (typeof data != 'object')){
      data = {};
    }
    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('localdevices', socket, device));
      if(err){ return; }
      getLocalDevices(data, device, true, function(results){
        results.fromUuid = device.uuid;
        results.from = _.pick(device, config.preservedDeviceProperties);
        logEvent(403, results);

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('claimdevice', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    if(!data || (typeof data != 'object')){
      data = {};
    }
    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('claimdevice', socket, device));
      if(err){ return; }
      claimDevice(device, data, function(err, results){
        logEvent(403, {error: (err && err.message), results: results, fromUuid: device.uuid, from: device});

        try{
          fn({error: (err && err.message), results: results});
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('whoami', throttler.throttle(function (data, fn) {
    fn = fn || _.noop

    getDevice(socket, function(err, device){
      skynet.sendActivity(getActivity('whoami', socket, device));
      if(err){ return; }
      try{
        fn(device);
      } catch (e){
        console.error(e);
      }
    });
  }));

  socket.on('register', throttler.throttle(function (data, fn) {
    fn = fn || _.noop
    debug('register', data, fn);
    data = data || {};

    skynet.sendActivity(getActivity('register', socket));
    data.socketid = socket.id;
    data.ipAddress = data.ipAddress || ipAddress;
    debug('socketLogic:registering');

    register(data, function(error, device){
      try{
        fn(device);
      } catch (e){
        console.error(e);
      }
    });
  }));

  socket.on('update', throttler.throttle(function (data, fn) {
    fn = fn || _.noop
    if(!data){
      data = {};
    }
    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, fromDevice){
      skynet.sendActivity(getActivity('update', socket, fromDevice));
      if(err){ return; }

      updateFromClient(fromDevice, data, function(regData) {
        skynet.sendConfigActivity(data.uuid, skynet.emitToClient);
        try {
          fn(regData);
        } catch(error) {
          console.error(error);
        }
      });
    });
  }));

  socket.on('unregister', throttler.throttle(function (data, fn) {
    fn = fn || _.noop
    if(!data){
      data = {};
    }
    // Emit API request from device to room for subscribers
    getDevice(socket, function(err, fromDevice){
      if(err){ return; }
      var reqData = data;
      skynet.sendActivity(getActivity('unregister', socket, fromDevice));
      unregister(fromDevice, data.uuid, data.token, skynet.emitToClient, function(results){
        if(results == null || results == undefined){
          results = {};
        }
        results.fromUuid = fromDevice.uuid;
        results.from = _.pick(fromDevice, config.preservedDeviceProperties);
        logEvent(402, results);

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('events', throttler.throttle(function(data, fn) {
    fn = fn || _.noop
    authDevice(data.uuid, data.token, function(error, authedDevice){
      if(!authedDevice){
          var results = {"api": "events", "result": false};

          try{
            fn(results);
          } catch (e){
            console.error(e);
          }
          return;
      }

      // Emit API request from device to room for subscribers
      getDevice(socket, function(err, device){
        skynet.sendActivity(getActivity('events', socket, device));
        if(err){ return; }
        var reqData = data;
        reqData.api = "events";

        getEvents(data.uuid, function(results){
          try{
            fn(results);
          } catch (e){
            console.error(e);
          }
          return;
        });
      });
    });
  }));

  socket.on('authenticate', throttler.throttle(function(data, fn) {
    fn = fn || _.noop
    skynet.sendActivity(getActivity('authenticate', socket));

    authDevice(data.uuid, data.token, function(error, authedDevice){
      var results;
      if (!authedDevice) {
        try{
          fn({"uuid": data.uuid, "authentication": false});
        } catch (e){
          console.error(e);
        }
        return;
      }

      results = {"uuid": data.uuid, "authentication": true};

      data = _.extend({}, data, {
        socketid: socket.id,
        ipAddress: ipAddress,
        secure: secure,
        online: true
      });

      if(!data.protocol){
        data.protocol = "websocket";
      }

      updateSocketId(data, function() {
        socket.emit('ready', {"api": "connect", "status": 201, "socketid": socket.id, "uuid": data.uuid});
        socket.join(data.uuid);

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });

      whoAmI(data.uuid, false, function(check){
        results.toUuid = check.uuid;
        results.to = check;
        logEvent(102, results);
      });
    });
  }));

  socket.on('data', throttler.throttle(function(data, fn) {
    fn = fn || _.noop
    getDevice(socket, function(err, fromDevice){
      if(err){ return; }
      skynet.sendActivity(getActivity('data', socket, fromDevice));
      saveDataIfAuthorized(skynet.sendMessage, fromDevice, data.uuid, data, function(error){
        try{
          fn();
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('getdata', throttler.throttle(function(data, fn) {
    fn = fn || _.noop

    skynet.sendActivity(getActivity('getdata', socket));
    authDevice(data.uuid, data.token, function(error, authedDevice){
      if(!authedDevice) {
        var results = {"api": "getdata", "result": false};

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
        return;
      }

      if(!data || (typeof data != 'object')){
        data = {};
      }
      data.params = {};
      data.query = {};

      data.params.uuid = data.uuid;
      data.query.start = data.start; // time to start from
      data.query.finish = data.finish; // time to end
      data.query.limit = data.limit; // 0 bypasses the limit

      getData(data, function(results){
        if (results) {
          results.fromUuid = socket.skynetDevice.uuid;
        }

        try{
          fn(results);
        } catch (e){
          console.error(e);
        }
      });
    });
  }));

  socket.on('messageAck', throttler.throttle(function (data) {
    getDevice(socket, function(err, fromDevice){
      skynet.sendActivity(getActivity('messageAck', socket, fromDevice));
      if(fromDevice){
        whoAmI(data.devices, false, function(check){
          data.fromUuid = fromDevice.uuid;

          if(check.error){
            return;
          }
          securityImpl.canSend(fromDevice, check, function(error, permission){
            if(error || !permission){
              debug('messageAck', 'fromDevice', fromDevice, 'toDevice', check, "can't send");
              return;
            }
            skynet.emitToClient('messageAck', check, data);
          });
        });
      }
    });
  }));

  socket.on('tb', throttler.throttle(function (message) {
    if(!message){
      return;
    }

    message = message.toString();

    // Broadcast to room for pubsub
    getDevice(socket, function(err, fromDevice){
      //skynet.sendActivity(getActivity('tb', socket, fromDevice));
      if(fromDevice){
        skynet.sendMessage(fromDevice, {payload: message}, 'tb');
      }
    });
  }));

  socket.on('message', throttler.throttle(function (message) {
    if(typeof message !== 'object'){ return; }

    // Broadcast to room for pubsub
    getDevice(socket, function(err, fromDevice){
      //skynet.sendActivity(getActivity('message', socket, fromDevice));
      if(fromDevice){
        message.api = "message";
        skynet.sendMessage(fromDevice, message);
      }
    });
  }));

  socket.on('directText', throttler.throttle(function (message) {
    getDevice(socket, function(err, fromDevice){
      if(fromDevice){
        skynet.sendMessage(fromDevice, message, 'tb');
      }
    });
  }));

  socket.on('getPublicKey', throttler.throttle(getPublicKey));

  socket.on('resetToken', throttler.throttle(function(message, fn){
    fn = fn || _.noop
    getDevice(socket, function(err, fromDevice){
      if(err){ return; }

      resetToken(fromDevice, message.uuid, skynet.emitToClient, function(error, token){
        if(error) {
          return socket.emit('error', {method: 'resetToken', error: error});
        }
        fn({uuid: message.uuid, token: token});
      });
    });
  }));

  socket.on('generateAndStoreToken', throttler.throttle(function(message, fn){
    getDevice(socket, function(err, fromDevice){
      if(err){ return console.error(err); }
      generateAndStoreToken(fromDevice, message.uuid, function(error, result){
        if(error) {
          fn();
          return;
        }
        fn({uuid: message.uuid, token: result.token});
      });
    });
  }));

  socket.on('revokeToken', throttler.throttle(function(message, fn){
    getDevice(socket, function(err, fromDevice){
      if(err){ return console.error(err); }
      revokeToken(fromDevice, message.uuid, message.token, function(error, result){
        if(error) {
          fn();
          return;
        }
        fn({uuid: message.uuid});
      });
    });
  }));

}

module.exports = socketLogic;


text:
<?php
/**
 * The template for displaying 404 pages (not found)
 *
 * @package WordPress
 * @subpackage Pure
 * @since Pure 1.0
 */

get_header(); ?>

            <?php get_template_part('navbar') ?>

<?php _e( 'Oops! That page can’t be found.', 'pure' ); ?>

<?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'pure' ); ?>

                    <?php get_search_form(); ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.openxava.util.Align (OpenXava 4.9.1 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.openxava.util.Align

Packages that use Align

org.openxava.util

Uses of Align in org.openxava.util

Fields in org.openxava.util declared as Align

static Align
Align.CENTER

static Align
Align.DEFAULT

static Align
Align.LEFT

static Align
Align.RIGHT

Methods in org.openxava.util that return Align

static Align
Align.get(int code)

          Obtain align associated to indicated code.

static Align[]
Align.getAll()

          All available aligns.

Methods in org.openxava.util with parameters of type Align

static java.lang.String
Strings.fix(java.lang.String string,
    int length,
    Align align)

          Fix the length of the string filling with spaces if needed.

static java.lang.String
Strings.fix(java.lang.String string,
    int length,
    Align align,
    char fillCharacter)

          Fix the length of the string filling with the specified character if needed.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Location Schema
 */
var LocationSchema = new Schema({
	type: {
		type: String,
		default: 'unknown',
		required: 'Please fill Location type',
		trim: true
	},
	lat: {
		type: Number,
		default: 0
	},
	lng: {
		type: Number,
		default: 0
	},
	created: {
		type: Date,
		default: Date.now
	},
	info: {
		type: Schema.Types.Mixed
	}

});

mongoose.model('Location', LocationSchema);


text:
using System;
class ComparingFloats
{
    // Write a program that safely compares floating-point numbers (double)
    // with precision eps = 0.000001.
    static void Main()
    {
        double a = 5.3;
        double b = 6.01;
        bool isAequaltoB = true;
        if (Math.Abs(a - b) > 0.000001) ;
        isAequaltoB = false;
        Console.WriteLine(isAequaltoB);
    }
}


text:
package br.eti.mertz.wkhtmltopdf.wrapper.page;

public class Page {

    private String source;

    private PageType type;

    public Page(String source, PageType type) {
        this.source = source;
        this.type = type;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public PageType getType() {
        return type;
    }

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


text:
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { CoreModule } from './core/core.module';

@NgModule({
  imports:      [ BrowserModule, AppRoutingModule, CoreModule ],
  declarations: [ AppComponent, AppRoutingModule.components ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }


text:
package com.addressbook.tests;

import org.testng.annotations.Test;

public class GroupDeletionTests extends TestBase {

    @Test
    public void GroupDeletionTests() {
        app.getNavigationHelper().gotoToGroupPage();
        app.getGroupHelper().selectGroup();
        app.getGroupHelper().deleteSelectedGroups();
        app.getGroupHelper().returnToGroupPage();
    }

}


text:
package io.finch.benchmarks.service

import com.twitter.finagle.httpx.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
import io.finch._
import io.finch.request._
import io.finch.response.{EncodeResponse, BadRequest => BR, InternalServerError => ISR}

class FinchUserService(implicit
  userDecoder: DecodeRequest[User],
  newUserInfoDecoder: DecodeRequest[NewUserInfo],
  userEncoder: EncodeResponse[User],
  usersEncoder: EncodeResponse[List[User]]
) extends UserService {

  val getUser: Endpoint[User] = get("users" / long) { id: Long =>
    Ok(db.get(id).flatMap {
      case Some(user) => Future.value(user)
      case None => Future.exception(UserNotFound(id))
    })
  }

  val getUsers: Endpoint[List[User]] = get("users") {
    Ok(db.all)
  }

  val postUser: Endpoint[Unit] = post("users" ? body.as[NewUserInfo]) { u: NewUserInfo =>
    for {
      id <- db.add(u.name, u.age)
    } yield Created.withHeader("Location" -> s"/users/$id")
  }

  val deleteUser: Endpoint[String] = delete("users") {
    for {
      count <- db.delete()
    } yield Ok(s"$count users deleted")
  }

  val putUser: Endpoint[Unit] = put("users" ? body.as[User]) { u: User =>
    NoContent(db.update(u))
  }

  val users: Service[Request, Response] = (
    getUsers :+: getUser :+: postUser :+: deleteUser :+: putUser
  ).toService

  val handleExceptions = new SimpleFilter[Request, Response] {
    def apply(req: Request, service: Service[Request, Response]): Future[Response] =
      service(req).handle {
        case notFound @ UserNotFound(_) => BR(notFound.getMessage)
        case _ => ISR()
      }
  }

  val backend = handleExceptions andThen users
}


text:
import os
import re
import sys
import time
import random
import logging
import tempfile
import subprocess
import shutil
import argparse

# params overwrite priority:
#   for default:
#       default_params < blackbox|whitebox_default_params < args
#   for simple:
#       simple_default_params < blackbox|whitebox_simple_default_params < args

default_params = {
    "acquire_snapshot_one_in": 10000,
    "block_size": 16384,
    "cache_size": 1048576,
    "use_clock_cache": "false",
    "delpercent": 5,
    "destroy_db_initially": 0,
    "disable_wal": 0,
    "allow_concurrent_memtable_write": 0,
    "iterpercent": 10,
    "max_background_compactions": 20,
    "max_bytes_for_level_base": 10485760,
    "max_key": 100000000,
    "max_write_buffer_number": 3,
    "memtablerep": "prefix_hash",
    "mmap_read": lambda: random.randint(0, 1),
    "open_files": 500000,
    "prefix_size": 7,
    "prefixpercent": 5,
    "progress_reports": 0,
    "readpercent": 45,
    "reopen": 20,
    "snapshot_hold_ops": 100000,
    "sync": 0,
    "target_file_size_base": 2097152,
    "target_file_size_multiplier": 2,
    "threads": 32,
    "verify_checksum": 1,
    "write_buffer_size": 4 * 1024 * 1024,
    "writepercent": 35,
    "log2_keys_per_lock": 2,
    "subcompactions": lambda: random.randint(1, 4),
    "use_merge": lambda: random.randint(0, 1),
    "use_full_merge_v1": lambda: random.randint(0, 1),
}

def get_dbname(test_name):
    test_tmpdir = os.environ.get("TEST_TMPDIR")
    if test_tmpdir is None or test_tmpdir == "":
        dbname = tempfile.mkdtemp(prefix='rocksdb_crashtest_' + test_name)
    else:
        dbname = test_tmpdir + "/rocksdb_crashtest_" + test_name
        shutil.rmtree(dbname, True)
    return dbname

blackbox_default_params = {
    # total time for this script to test db_stress
    "duration": 6000,
    # time for one db_stress instance to run
    "interval": 120,
    # since we will be killing anyway, use large value for ops_per_thread
    "ops_per_thread": 100000000,
    "set_options_one_in": 10000,
    "test_batches_snapshots": 1,
}

whitebox_default_params = {
    "duration": 10000,
    "log2_keys_per_lock": 10,
    "nooverwritepercent": 1,
    "ops_per_thread": 200000,
    "test_batches_snapshots": lambda: random.randint(0, 1),
    "write_buffer_size": 4 * 1024 * 1024,
    "subcompactions": lambda: random.randint(1, 4),
    "random_kill_odd": 888887,
}

simple_default_params = {
    "block_size": 16384,
    "cache_size": 1048576,
    "use_clock_cache": "false",
    "column_families": 1,
    "delpercent": 5,
    "destroy_db_initially": 0,
    "disable_wal": 0,
    "allow_concurrent_memtable_write": lambda: random.randint(0, 1),
    "iterpercent": 10,
    "max_background_compactions": 1,
    "max_bytes_for_level_base": 67108864,
    "max_key": 100000000,
    "max_write_buffer_number": 3,
    "memtablerep": "skip_list",
    "mmap_read": lambda: random.randint(0, 1),
    "prefix_size": 0,
    "prefixpercent": 0,
    "progress_reports": 0,
    "readpercent": 50,
    "reopen": 20,
    "sync": 0,
    "target_file_size_base": 16777216,
    "target_file_size_multiplier": 1,
    "test_batches_snapshots": 0,
    "threads": 32,
    "verify_checksum": 1,
    "write_buffer_size": 32 * 1024 * 1024,
    "writepercent": 35,
    "subcompactions": lambda: random.randint(1, 4),
}

blackbox_simple_default_params = {
    "duration": 6000,
    "interval": 120,
    "open_files": -1,
    "ops_per_thread": 100000000,
    "set_options_one_in": 0,
    "test_batches_snapshots": 0,
}

whitebox_simple_default_params = {
    "duration": 10000,
    "log2_keys_per_lock": 10,
    "nooverwritepercent": 1,
    "open_files": 500000,
    "ops_per_thread": 200000,
    "write_buffer_size": 32 * 1024 * 1024,
    "subcompactions": lambda: random.randint(1, 4),
}

def finalize_and_sanitize(src_params):
    dest_params = dict([(k,  v() if callable(v) else v)
                        for (k, v) in src_params.items()])
    if dest_params.get("allow_concurrent_memtable_write", 1) == 1:
        dest_params["memtablerep"] = "skip_list"
    return dest_params

def gen_cmd_params(args):
    params = {}

    if args.simple:
        params.update(simple_default_params)
        if args.test_type == 'blackbox':
            params.update(blackbox_simple_default_params)
        if args.test_type == 'whitebox':
            params.update(whitebox_simple_default_params)

    if not args.simple:
        params.update(default_params)
        if args.test_type == 'blackbox':
            params.update(blackbox_default_params)
        if args.test_type == 'whitebox':
            params.update(whitebox_default_params)

    for k, v in vars(args).items():
        if v is not None:
            params[k] = v
    return params

def gen_cmd(params):
    cmd = ['./db_stress'] + [
        '--{0}={1}'.format(k, v)
        for k, v in finalize_and_sanitize(params).items()
        if k not in set(['test_type', 'simple', 'duration', 'interval',
                         'random_kill_odd'])
        and v is not None]
    return cmd

# This script runs and kills db_stress multiple times. It checks consistency
# in case of unsafe crashes in RocksDB.
def blackbox_crash_main(args):
    cmd_params = gen_cmd_params(args)
    dbname = get_dbname('blackbox')
    exit_time = time.time() + cmd_params['duration']

    print("Running blackbox-crash-test with \n"
          + "interval_between_crash=" + str(cmd_params['interval']) + "\n"
          + "total-duration=" + str(cmd_params['duration']) + "\n"
          + "threads=" + str(cmd_params['threads']) + "\n"
          + "ops_per_thread=" + str(cmd_params['ops_per_thread']) + "\n"
          + "write_buffer_size=" + str(cmd_params['write_buffer_size']) + "\n"
          + "subcompactions=" + str(cmd_params['subcompactions']) + "\n")

    while time.time() < exit_time:
        run_had_errors = False
        killtime = time.time() + cmd_params['interval']

        cmd = gen_cmd(dict(cmd_params.items() + {'db': dbname}.items()))

        child = subprocess.Popen(cmd, stderr=subprocess.PIPE)
        print("Running db_stress with pid=%d: %s\n\n"
              % (child.pid, ' '.join(cmd)))

        stop_early = False
        while time.time() < killtime:
            if child.poll() is not None:
                print("WARNING: db_stress ended before kill: exitcode=%d\n"
                      % child.returncode)
                stop_early = True
                break
            time.sleep(1)

        if not stop_early:
            if child.poll() is not None:
                print("WARNING: db_stress ended before kill: exitcode=%d\n"
                      % child.returncode)
            else:
                child.kill()
                print("KILLED %d\n" % child.pid)
                time.sleep(1)  # time to stabilize after a kill

        while True:
            line = child.stderr.readline().strip()
            if line != '' and not line.startswith('WARNING'):
                run_had_errors = True
                print('stderr has error message:')
                print('***' + line + '***')
            else:
                break

        if run_had_errors:
            sys.exit(2)

        time.sleep(1)  # time to stabilize before the next run

    # we need to clean up after ourselves -- only do this on test success
    shutil.rmtree(dbname, True)

# This python script runs db_stress multiple times. Some runs with
# kill_random_test that causes rocksdb to crash at various points in code.
def whitebox_crash_main(args):
    cmd_params = gen_cmd_params(args)
    dbname = get_dbname('whitebox')

    cur_time = time.time()
    exit_time = cur_time + cmd_params['duration']
    half_time = cur_time + cmd_params['duration'] / 2

    print("Running whitebox-crash-test with \n"
          + "total-duration=" + str(cmd_params['duration']) + "\n"
          + "threads=" + str(cmd_params['threads']) + "\n"
          + "ops_per_thread=" + str(cmd_params['ops_per_thread']) + "\n"
          + "write_buffer_size=" + str(cmd_params['write_buffer_size']) + "\n"
          + "subcompactions=" + str(cmd_params['subcompactions']) + "\n")

    total_check_mode = 4
    check_mode = 0
    kill_random_test = cmd_params['random_kill_odd']
    kill_mode = 0

    while time.time() < exit_time:
        if check_mode == 0:
            additional_opts = {
                # use large ops per thread since we will kill it anyway
                "ops_per_thread": 100 * cmd_params['ops_per_thread'],
            }
            # run with kill_random_test, with three modes.
            # Mode 0 covers all kill points. Mode 1 covers less kill points but
            # increases change of triggering them. Mode 2 covers even less
            # frequent kill points and further increases triggering change.
            if kill_mode == 0:
                additional_opts.update({
                    "kill_random_test": kill_random_test,
                })
            elif kill_mode == 1:
                additional_opts.update({
                    "kill_random_test": (kill_random_test / 10 + 1),
                    "kill_prefix_blacklist": "WritableFileWriter::Append,"
                    + "WritableFileWriter::WriteBuffered",
                })
            elif kill_mode == 2:
                # TODO: May need to adjust random odds if kill_random_test
                # is too small.
                additional_opts.update({
                    "kill_random_test": (kill_random_test / 5000 + 1),
                    "kill_prefix_blacklist": "WritableFileWriter::Append,"
                    "WritableFileWriter::WriteBuffered,"
                    "PosixMmapFile::Allocate,WritableFileWriter::Flush",
                })
            # Run kill mode 0, 1 and 2 by turn.
            kill_mode = (kill_mode + 1) % 3
        elif check_mode == 1:
            # normal run with universal compaction mode
            additional_opts = {
                "kill_random_test": None,
                "ops_per_thread": cmd_params['ops_per_thread'],
                "compaction_style": 1,
            }
        elif check_mode == 2:
            # normal run with FIFO compaction mode
            # ops_per_thread is divided by 5 because FIFO compaction
            # style is quite a bit slower on reads with lot of files
            additional_opts = {
                "kill_random_test": None,
                "ops_per_thread": cmd_params['ops_per_thread'] / 5,
                "compaction_style": 2,
            }
        else:
            # normal run
            additional_opts = additional_opts = {
                "kill_random_test": None,
                "ops_per_thread": cmd_params['ops_per_thread'],
            }

        cmd = gen_cmd(dict(cmd_params.items() + additional_opts.items()
                           + {'db': dbname}.items()))

        print "Running:" + ' '.join(cmd) + "\n"

        popen = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
        stdoutdata, stderrdata = popen.communicate()
        retncode = popen.returncode
        msg = ("check_mode={0}, kill option={1}, exitcode={2}\n".format(
               check_mode, additional_opts['kill_random_test'], retncode))
        print msg
        print stdoutdata

        expected = False
        if additional_opts['kill_random_test'] is None and (retncode == 0):
            # we expect zero retncode if no kill option
            expected = True
        elif additional_opts['kill_random_test'] is not None and retncode < 0:
            # we expect negative retncode if kill option was given
            expected = True

        if not expected:
            print "TEST FAILED. See kill option and exit code above!!!\n"
            sys.exit(1)

        stdoutdata = stdoutdata.lower()
        errorcount = (stdoutdata.count('error') -
                      stdoutdata.count('got errors 0 times'))
        print "#times error occurred in output is " + str(errorcount) + "\n"

        if (errorcount > 0):
            print "TEST FAILED. Output has 'error'!!!\n"
            sys.exit(2)
        if (stdoutdata.find('fail') >= 0):
            print "TEST FAILED. Output has 'fail'!!!\n"
            sys.exit(2)

        # First half of the duration, keep doing kill test. For the next half,
        # try different modes.
        if time.time() > half_time:
            # we need to clean up after ourselves -- only do this on test
            # success
            shutil.rmtree(dbname, True)
            check_mode = (check_mode + 1) % total_check_mode

        time.sleep(1)  # time to stabilize after a kill

def main():
    parser = argparse.ArgumentParser(description="This script runs and kills \
        db_stress multiple times")
    parser.add_argument("test_type", choices=["blackbox", "whitebox"])
    parser.add_argument("--simple", action="store_true")

    all_params = dict(default_params.items()
                      + blackbox_default_params.items()
                      + whitebox_default_params.items()
                      + simple_default_params.items()
                      + blackbox_simple_default_params.items()
                      + whitebox_simple_default_params.items())

    for k, v in all_params.items():
        parser.add_argument("--" + k, type=type(v() if callable(v) else v))
    args = parser.parse_args()

    if args.test_type == 'blackbox':
        blackbox_crash_main(args)
    if args.test_type == 'whitebox':
        whitebox_crash_main(args)

if __name__ == '__main__':
    main()


text:
$(function(){

	$('.formulario').on('submit',function(e){
		e.preventDefault();
		var $form = $(this),
			url = $form.attr('action');
			data = $form.serialize();
		$.post(url,data,function(data){
			console.log(data);
			$('.invitacion').text('Gracias por registrarte '+data.name).addClass('finish');
		});
	});
	$('.vermas').on('click',function(e){
		e.preventDefault();
		var $boton = $(this);
		var $escenario = $boton.parents('.escenario');
		if(!$escenario.hasClass('active')){
			var url  = $boton.attr('href');
			$.get(url,function(data){
				$escenario.addClass('active');
				$escenario.after(data);
			});
		}

	});

});


text:
Editor widget for blessed used by the [slap](https://github.com/slap-editor/slap) text editor

## Example

```js
const blessed = require('blessed');
const Editor = require('editor-widget');

const screen = blessed.screen({smartCSR: true, title: "editor-widget example"});
const editor = new Editor({
  // normal blessed widget, use like you would any other blessed element
  parent: screen,
  top: 0,
  left: 0,
  width: '100%',
  height: '100%'
});

const filePath = './file.txt';
editor.open(filePath);
screen.key(['C-s'], (ch, key) => { editor.save(filePath); });

screen.key(['escape', 'q', 'C-c'], (ch, key) => { process.exit(0); });
screen.render();
```

## In use
Here are some projects that use editor-widget:

* [slap](https://github.com/slap-editor/slap)
* [derhuerst/js-playgrounds](https://github.com/derhuerst/js-playgrounds)


text:
package vindexes

import "fmt"

func init() {
	Register("lookup_hash", NewLookupHash)
	Register("lookup_hash_unique", NewLookupHashUnique)
}

//====================================================================

// LookupHash defines a vindex that uses a lookup table.
// The table is expected to define the id column as unique. It's
// NonUnique and a Lookup.
type LookupHash struct {
	name string
	lkp  lookup
}

// NewLookupHash creates a LookupHash vindex.
func NewLookupHash(name string, m map[string]interface{}) (Vindex, error) {
	lhu := &LookupHash{name: name}
	lhu.lkp.Init(m)
	return lhu, nil
}

// String returns the name of the vindex.
func (vind *LookupHash) String() string {
	return vind.name
}

// Cost returns the cost of this vindex as 20.
func (vind *LookupHash) Cost() int {
	return 20
}

// Map returns the corresponding KeyspaceId values for the given ids.
func (vind *LookupHash) Map(vcursor VCursor, ids []interface{}) ([][][]byte, error) {
	return vind.lkp.Map2(vcursor, ids)
}

// Verify returns true if id maps to ksid.
func (vind *LookupHash) Verify(vcursor VCursor, id interface{}, ksid []byte) (bool, error) {
	return vind.lkp.Verify(vcursor, id, ksid)
}

// Create reserves the id by inserting it into the vindex table.
func (vind *LookupHash) Create(vcursor VCursor, id interface{}, ksid []byte) error {
	return vind.lkp.Create(vcursor, id, ksid)
}

// Delete deletes the entry from the vindex table.
func (vind *LookupHash) Delete(vcursor VCursor, ids []interface{}, ksid []byte) error {
	return vind.lkp.Delete(vcursor, ids, ksid)
}

//====================================================================

// LookupHashUnique defines a vindex that uses a lookup table.
// The table is expected to define the id column as unique. It's
// Unique and a Lookup.
type LookupHashUnique struct {
	name string
	lkp  lookup
}

// NewLookupHashUnique creates a LookupHashUnique vindex.
func NewLookupHashUnique(name string, m map[string]interface{}) (Vindex, error) {
	lhu := &LookupHashUnique{name: name}
	lhu.lkp.Init(m)
	return lhu, nil
}

// String returns the name of the vindex.
func (vind *LookupHashUnique) String() string {
	return vind.name
}

// Cost returns the cost of this vindex as 10.
func (vind *LookupHashUnique) Cost() int {
	return 10
}

// Map returns the corresponding KeyspaceId values for the given ids.
func (vind *LookupHashUnique) Map(vcursor VCursor, ids []interface{}) ([][]byte, error) {
	return vind.lkp.Map1(vcursor, ids)
}

// Verify returns true if id maps to ksid.
func (vind *LookupHashUnique) Verify(vcursor VCursor, id interface{}, ksid []byte) (bool, error) {
	return vind.lkp.Verify(vcursor, id, ksid)
}

// Create reserves the id by inserting it into the vindex table.
func (vind *LookupHashUnique) Create(vcursor VCursor, id interface{}, ksid []byte) error {
	return vind.lkp.Create(vcursor, id, ksid)
}

// Delete deletes the entry from the vindex table.
func (vind *LookupHashUnique) Delete(vcursor VCursor, ids []interface{}, ksid []byte) error {
	return vind.lkp.Delete(vcursor, ids, ksid)
}

//====================================================================

// lookup implements the functions for the Lookup vindexes.
type lookup struct {
	Table, From, To    string
	sel, ver, ins, del string
}

func (lkp *lookup) Init(m map[string]interface{}) {
	get := func(name string) string {
		v, _ := m[name].(string)
		return v
	}
	t := get("Table")
	from := get("From")
	to := get("To")

	lkp.Table = t
	lkp.From = from
	lkp.To = to
	lkp.sel = fmt.Sprintf("select %s from %s where %s = :%s", to, t, from, from)
	lkp.ver = fmt.Sprintf("select %s from %s where %s = :%s and %s = :%s", from, t, from, from, to, to)
	lkp.ins = fmt.Sprintf("insert into %s(%s, %s) values(:%s, :%s)", t, from, to, from, to)
	lkp.del = fmt.Sprintf("delete from %s where %s = :%s and %s = :%s", t, from, from, to, to)
}

// Map1 is for a unique vindex.
func (lkp *lookup) Map1(vcursor VCursor, ids []interface{}) ([][]byte, error) {
	out := make([][]byte, 0, len(ids))
	for _, id := range ids {
		result, err := vcursor.Execute(lkp.sel, map[string]interface{}{
			lkp.From: id,
		})
		if err != nil {
			return nil, fmt.Errorf("lookup.Map: %v", err)
		}
		if len(result.Rows) == 0 {
			out = append(out, []byte{})
			continue
		}
		if len(result.Rows) != 1 {
			return nil, fmt.Errorf("lookup.Map: unexpected multiple results from vindex %s: %v", lkp.Table, id)
		}
		num, err := getNumber(result.Rows[0][0].ToNative())
		if err != nil {
			return nil, fmt.Errorf("lookup.Map: %v", err)
		}
		out = append(out, vhash(num))
	}
	return out, nil
}

// Map2 is for a non-unique vindex.
func (lkp *lookup) Map2(vcursor VCursor, ids []interface{}) ([][][]byte, error) {
	out := make([][][]byte, 0, len(ids))
	for _, id := range ids {
		result, err := vcursor.Execute(lkp.sel, map[string]interface{}{
			lkp.From: id,
		})
		if err != nil {
			return nil, fmt.Errorf("lookup.Map: %v", err)
		}
		var ksids [][]byte
		for _, row := range result.Rows {
			num, err := getNumber(row[0].ToNative())
			if err != nil {
				return nil, fmt.Errorf("lookup.Map: %v", err)
			}
			ksids = append(ksids, vhash(num))
		}
		out = append(out, ksids)
	}
	return out, nil
}

// Verify returns true if id maps to ksid.
func (lkp *lookup) Verify(vcursor VCursor, id interface{}, ksid []byte) (bool, error) {
	val, err := vunhash(ksid)
	if err != nil {
		return false, fmt.Errorf("lookup.Verify: %v", err)
	}
	result, err := vcursor.Execute(lkp.ver, map[string]interface{}{
		lkp.From: id,
		lkp.To:   val,
	})
	if err != nil {
		return false, fmt.Errorf("lookup.Verify: %v", err)
	}
	if len(result.Rows) == 0 {
		return false, nil
	}
	return true, nil
}

// Create creates an association between id and ksid by inserting a row in the vindex table.
func (lkp *lookup) Create(vcursor VCursor, id interface{}, ksid []byte) error {
	val, err := vunhash(ksid)
	if err != nil {
		return fmt.Errorf("lookup.Create: %v", err)
	}
	if _, err := vcursor.Execute(lkp.ins, map[string]interface{}{
		lkp.From: id,
		lkp.To:   val,
	}); err != nil {
		return fmt.Errorf("lookup.Create: %v", err)
	}
	return nil
}

// Delete deletes the association between ids and ksid.
func (lkp *lookup) Delete(vcursor VCursor, ids []interface{}, ksid []byte) error {
	val, err := vunhash(ksid)
	if err != nil {
		return fmt.Errorf("lookup.Delete: %v", err)
	}
	bindvars := map[string]interface{}{
		lkp.To: val,
	}
	for _, id := range ids {
		bindvars[lkp.From] = id
		if _, err := vcursor.Execute(lkp.del, bindvars); err != nil {
			return fmt.Errorf("lookup.Delete: %v", err)
		}
	}
	return nil
}


text:
published: true
title: Using Blazor WebAssembly in the old ASP.NET
description: One of example how to add Blazor WebAssembly app in existing old ASP.NET MVC solution
layout: post
tags: [csharp, blazor, webassembly, aspnet]
comments: true
---

The building of a rich user interface is not always easy for `.NET` developers, especially if you dive deep to use `React`, `Angular`, `webpack` and friends. `Blazor` gives a nice trade-off bringing `Razor`-like templates and `C#` to a browser utilizing [WebAssembly](https://en.wikipedia.org/wiki/WebAssembly).

> `Blazor` is a free and open-source web framework that enables developers to create web apps using `C#` and `HTML`. It is being developed by `Microsoft` — [Wikipedia](https://en.wikipedia.org/wiki/Blazor)

## Problem

Currently, I'm working with legacy projects, which cannot be easily ported to `.NET Core` to make use of the newest technologies. However, it is possible to run `Blazor WebAssembly` even in old-fashioned `ASP.NET Web Forms` or `ASP.NET MVC` and I'm going to show how. The following approach has been tested on production so it should work fine for you :)

## Solution

As a starting point, I'm going to create `ASP.NET MVC` project from one of the default templates. [Here is it](https://github.com/gaevoy/Gaev.BlazorOnAspNet/tree/master/OldAspNetApp), our playground is ready and I call it `OldAspNetApp`. For instance, `About.cshtml` page looks like this:

```html
@{
    ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>
```

Let's add `Blazor WebAssembly` app now. The easiest way is to use `blazorwasm` template for `.NET Core` client, [read more](https://docs.microsoft.com/en-us/aspnet/core/blazor/get-started?view=aspnetcore-3.0&tabs=netcore-cli). Additionally, I added [web.config](https://github.com/gaevoy/Gaev.BlazorOnAspNet/blob/blazor-app/BlazorWasmApp/web.config) that fits our needs. Basically, it is almost the same as what `dotnet publish` produces. Our new `Blazor` projects I called `BlazorWasmApp`. As an example, `About.razor` page is:

```html
@page "/Home/About"

<div class="panel panel-primary">
    <div class="panel-heading">
        Blazor WASM app
    </div>
    <div class="panel-body">
        <p>Current count: @currentCount</p>
        <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    </div>
</div>

@code {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}
```

In order to reference `BlazorWasmApp` to `OldAspNetApp` I added [Post-Build action](https://github.com/gaevoy/Gaev.BlazorOnAspNet/pull/1/files#diff-c35ae0503b58019deae8124bcf0f4557R19-R22) for `BlazorWasmApp.csproj`.

```xml
<Target Name="CopyToOldAspNetApp" AfterTargets="Build">
    <Exec Command="xcopy $(TargetDir)web.config $(TargetDir)dist\_framework\ /Y" />
    <Exec Command="xcopy $(TargetDir)dist $(SolutionDir)OldAspNetApp /Y /S" />
</Target>
```

It just copies all files `BlazorWasmApp` project produces into `OldAspNetApp` folder including `web.config`.

To render `Blazor` page in `OldAspNetApp` I need only this:

```html
<BlazorWasmApp>Blazor WASM app loading...</BlazorWasmApp>
<base href="/"/>
<script src="/_framework/blazor.webassembly.js"></script>
```

 In order to reuse easily, I'm going to put these 3 lines into a shared partial view (`BlazorWasmApp.cshtml`). As a result, `About.cshtml` page of `OldAspNetApp` becomes this:

 ```html
@{
    ViewBag.Title = "About";
}

@Html.Partial("BlazorWasmApp")

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>
```

By default, `Blazor` app intercepts all clicks to prevent a full page reload. In my case, it breaks `OldAspNetApp` so I disabled it [here](https://github.com/gaevoy/Gaev.BlazorOnAspNet/pull/1/files#diff-8d952ee206db0390c0972cba01ba6936R12) via overriding default implementation of [INavigationInterception](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.routing.inavigationinterception).

Finally, it is done. I have created [the pull request](https://github.com/gaevoy/Gaev.BlazorOnAspNet/pull/1/files) for an easier understanding of what has been changed. Complete source code is in [blazor-app](https://github.com/gaevoy/Gaev.BlazorOnAspNet/tree/blazor-app)  branch of `Gaev.BlazorOnAspNet` project.

![Blazor WASM in old ASP.NET app](/img/blazor/blazor-in-old-aspnet.png "Blazor WASM in old ASP.NET app" ){:style="max-width:1324px; width:100%;" class="block-center"}

## Pitfalls

`Gaev.BlazorOnAspNet` solution should be opened by `Visual Studio 2019` version `16.3+`. Before that specific version, you will get a compilation error, like the following. Most probably, `Visual Studio 2017` will show the same error.

```
Error CS0246: The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?)
```

Make sure `.Net Core SDK 3.0+` is installed (via `dotnet --info`).

I managed to find a workaround to open the solution by `Visual Studio 2017` but it requires small changes. See [the pull request](https://github.com/gaevoy/Gaev.BlazorOnAspNet/pull/2/files). The source code is in [vs2017-adaptation](https://github.com/gaevoy/Gaev.BlazorOnAspNet/tree/vs2017-adaptation) branch of `Gaev.BlazorOnAspNet` project.


text:
var u = require("uru"),
    types = u.types;


text:
package gigasecond

import "time"

// Constant declaration.
const testVersion = 4

// Represents a gigasecond. For performance boost, precalculate the gigasecond and reuse
const gigaSecondForDuration = time.Duration(1000000000) * time.Second

// AddGigasecond adds a gigasecond (10^9) to the given time.
func AddGigasecond(in time.Time) time.Time {
	return in.Add(gigaSecondForDuration)
}