text:
/** @module transition */ /** for typedoc */

import {IPromise} from "angular";
import {IInjectable, extend, tail, isPromise, isArray, assertPredicate, unnestR, flatten, identity} from "../common/common";

import {TransitionOptions, TransitionHookOptions, IHookRegistry, TreeChanges, IEventHook, ITransitionService} from "./interface";

import {Transition, TransitionHook} from "./module";
import {State} from "../state/module";
import {Node} from "../path/module";

interface IToFrom {
  to:   State;
  from: State;
}

let successErrorOptions: TransitionHookOptions = {
  async: false,
  rejectIfSuperseded: false
};

/**
 * This class returns applicable TransitionHooks for a specific Transition instance.
 *
 * Hooks (IEventHook) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g.
 * myTransition.onEnter(...).  The HookBuilder finds matching IEventHooks (where the match criteria is
 * determined by the type of hook)
 *
 * The HookBuilder also converts IEventHooks objects to TransitionHook objects, which are used to run a Transition.
 *
 * The HookBuilder constructor is given the $transitions service and a Transition instance.  Thus, a HookBuilder
 * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private
 * in the Transition class, so we must also provide the Transition's _treeChanges)
 *
 */
export class HookBuilder {

  treeChanges: TreeChanges;
  transitionOptions: TransitionOptions;

  toState: State;
  fromState: State;

  constructor(private $transitions: ITransitionService, private transition: Transition, private baseHookOptions: TransitionHookOptions) {
    this.treeChanges        = transition.treeChanges();
    this.toState            = tail(this.treeChanges.to).state;
    this.fromState          = tail(this.treeChanges.from).state;
    this.transitionOptions  = transition.options();
  }

  // TODO: These get* methods are returning different cardinalities of hooks
  // onBefore/onStart/onFinish/onSuccess/onError returns an array of hooks
  // onExit/onRetain/onEnter returns an array of arrays of hooks

  getOnBeforeHooks  = () => this._buildTransitionHooks("onBefore", {}, { async: false });
  getOnStartHooks   = () => this._buildTransitionHooks("onStart");
  getOnExitHooks    = () => this._buildNodeHooks("onExit",          this.treeChanges.exiting.reverse(), (node) => this._toFrom({ from: node.state }));
  getOnRetainHooks  = () => this._buildNodeHooks("onRetain",        this.treeChanges.retained,          (node) => this._toFrom());
  getOnEnterHooks   = () => this._buildNodeHooks("onEnter",         this.treeChanges.entering,          (node) => this._toFrom({ to: node.state }));
  getOnFinishHooks  = () => this._buildTransitionHooks("onFinish", { $treeChanges$: this.treeChanges });
  getOnSuccessHooks = () => this._buildTransitionHooks("onSuccess", {}, {async: false, rejectIfSuperseded: false});
  getOnErrorHooks   = () => this._buildTransitionHooks("onError", {}, {async: false, rejectIfSuperseded: false});

  asyncHooks() {
    let onStartHooks    = this.getOnStartHooks();
    let onExitHooks     = this.getOnExitHooks();
    let onRetainHooks   = this.getOnRetainHooks();
    let onEnterHooks    = this.getOnEnterHooks();
    let onFinishHooks   = this.getOnFinishHooks();

    return flatten([onStartHooks, onExitHooks, onRetainHooks, onEnterHooks, onFinishHooks]).filter(identity);
  }

  private _toFrom(toFromOverride?): IToFrom {
    return extend({ to: this.toState, from: this.fromState }, toFromOverride);
  }

  /**
   * Returns an array of newly built TransitionHook objects.
   *
   * Builds a TransitionHook which cares about the entire Transition, for instance, onActivate
   * Finds all registered IEventHooks which matched the hookType and toFrom criteria.
   * A TransitionHook is then built from each IEventHook with the context, locals, and options provided.
   */
  private _buildTransitionHooks(hookType: string, locals = {}, options: TransitionHookOptions = {}) {
    let context = this.treeChanges.to, node = tail(context);
    options.traceData = { hookType, context };

    const transitionHook = eventHook => this.buildHook(node, eventHook.callback, locals, options);
    return this._matchingHooks(hookType, this._toFrom()).map(transitionHook);
  }

  /**
   * Returns an 2 dimensional array of newly built TransitionHook objects.
   * Each inner array contains the hooks for a node in the Path.
   *
   * For each Node in the Path:
   * Builds the toFrom criteria
   * Finds all registered IEventHooks which matched the hookType and toFrom criteria.
   * A TransitionHook is then built from each IEventHook with the context, locals, and options provided.
   */
  private _buildNodeHooks(hookType: string, path: Node[], toFromFn: (node: Node) => IToFrom, locals: any = {}, options: TransitionHookOptions = {}) {
    const hooksForNode = (node: Node) => {
      let toFrom = toFromFn(node);
      options.traceData = { hookType, context: node };
      locals.$state$ = node.state;

      const transitionHook = eventHook => this.buildHook(node, eventHook.callback, locals, options);
      return this._matchingHooks(hookType, toFrom).map(transitionHook);
    };

    return path.map(hooksForNode);
  }

  /** Given a node and a callback function, builds a TransitionHook */
  buildHook(node: Node, fn: IInjectable, locals?, options: TransitionHookOptions = {}): TransitionHook {
    let _options = extend({}, this.baseHookOptions, options);
    return new TransitionHook(fn, extend({}, locals), node.resolveContext, _options);
  }

  /**
   * returns an array of the IEventHooks from:
   * - The Transition object instance hook registry
   * - The TransitionService ($transitions) global hook registry
   * which matched:
   * - the eventType
   * - the matchCriteria to state
   * - the matchCriteria from state
   */
  private _matchingHooks(hookName: string, matchCriteria: IToFrom): IEventHook[] {
    const matchFilter   = hook => hook.matches(matchCriteria.to, matchCriteria.from);
    const prioritySort  = (l, r) => r.priority - l.priority;

    return [ this.transition, this.$transitions ]                             // Instance and Global hook registries
        .map((reg: IHookRegistry) => reg.getHooks(hookName))                  // Get named hooks from registries
        .filter(assertPredicate(isArray, `broken event named: ${hookName}`))  // Sanity check
        .reduce(unnestR)                                                      // Un-nest IEventHook[][] to IEventHook[] array
        .filter(matchFilter)                                                  // Only those satisfying matchCriteria
        .sort(prioritySort);                                                  // Order them by .priority field
  }
}


text:
require 'norp/formatters/base'

module Norp
  module Utils
    module Formatters

      class Bare < Norp::Formatters::Base
        def get_output
          messages = []

          @files.each do |file|
            next unless file.messages.any?

            messages << "File: #{file.path}"

            file.messages.each do |msg|
              body = msg.body.split("\n").map{ |l| "    #{ l }" }.join "\n"

              messages << "  #{ msg.level }: Line ##{ msg.line }\n#{ body }"
            end

            messages << ""
          end

          messages.join "\n"
        end
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.evilco.mc.nbt.tag;

import com.evilco.mc.nbt.stream.NbtInputStream;
import com.evilco.mc.nbt.stream.NbtOutputStream;

import javax.annotation.Nonnull;
import java.io.IOException;

public class TagShort extends AbstractTag {

	/**
	 * Stores the tag value.
	 */
	protected short value;

	/**
	 * Constructs a new TagShort.
	 * @param name
	 * @param value
	 */
	public TagShort (@Nonnull String name, short value) {
		super (name);
		this.setValue (value);
	}

	/**
	 * Constructs a new TagShort.
	 * @param inputStream
	 * @param anonymous
	 * @throws IOException
	 */
	public TagShort (@Nonnull NbtInputStream inputStream, boolean anonymous) throws IOException {
		super (inputStream, anonymous);

		// read value
		this.setValue (inputStream.readShort ());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public byte getTagID () {
		return TagType.SHORT.typeID;
	}

	/**
	 * Returns the tag value.
	 * @return
	 */
	public short getValue () {
		return this.value;
	}

	/**
	 * Sets a new tag value.
	 * @param s
	 */
	public void setValue (short s) {
		this.value = s;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void write (NbtOutputStream outputStream, boolean anonymous) throws IOException {
		super.write (outputStream, anonymous);

		// write value
		outputStream.writeShort (this.value);
	}
}


text:
<?php

namespace Grace\ORM\Service\Config;

class ConfigLoadException extends \LogicException
{
}


text:
package org.apache.camel.impl;

import org.apache.camel.impl.engine.MemoryStateRepository;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MemoryStateRepositoryTest {
    @Test
    public void shouldSaveState() throws Exception {
        // Given an empty FileStateRepository
        MemoryStateRepository repository = new MemoryStateRepository();

        // When saving a state
        repository.setState("key", "value");

        // Then it should be retrieved afterwards
        assertEquals("value", repository.getState("key"));
    }

    @Test
    public void shouldUpdateState() throws Exception {
        // Given a FileStateRepository with a state in it
        MemoryStateRepository repository = new MemoryStateRepository();
        repository.setState("key", "value");

        // When updating the state
        repository.setState("key", "value2");

        // Then the new value should be retrieved afterwards
        assertEquals("value2", repository.getState("key"));
    }
}


text:
const express = require("express");
const router = express.Router();
const path = require("path");
const bcrypt = require("./admin").bcrypt;
const pool = require('../index');
const LoginValidator = require("./loginValidator");

const loginForm = path.resolve(__dirname, "../client/admin/login.html");

router.get("/", function (req, resp) {
    resp.sendFile(loginForm);
});

var loginTester = new LoginValidator();

router.post("/", function (req, resp){
    let validLogin = loginTester.testItem(req.body);
    if (validLogin.passing){
        console.log(req.body);
        let dbQuery = "SELECT * FROM user_login WHERE username = $1";
        pool.query(dbQuery, [req.body.username], function (err, result) {
            if (err) {console.log(err)}

            if (result.rows[0] !== undefined) {
                if (result.rows.length > 0) {
                    bcrypt.compare(req.body.password, result.rows[0].password, function (err, isMatch) {
                        if (isMatch) {
                            req.session.user_id = result.rows[0].type_id;
                            req.session.SPK_user = result.rows[0].id;
                            resp.send({
                                status: "success",
                                message: "login successfully",
                                type: req.session.user_id,
                                user: req.session.id
                            });
                        } else {
                            resp.send({status: "failed", message: "incorrect login"});
                        }
                        //resp.send({status:"success"});
                    });

                    //req.session.user = result.rows[0];
                    //console.log(req.session.user.password);
                    //resp.send({status:"success", user:req.session.user});
                } else {
                    resp.send({status: "fail", message: "incorrect login"});
                }
            } else {
                resp.send({status: "fail", message: "incorrect login"});
            }
        });
    } else {
        resp.send({status: "invalid login", message: validLogin.err});
    }
});

module.exports = router;


text:
<?php

class Google_Service_Compute_OperationsScopedList extends Google_Collection
{
  protected $collection_key = 'operations';
  protected $operationsType = 'Google_Service_Compute_Operation';
  protected $operationsDataType = 'array';
  protected $warningType = 'Google_Service_Compute_OperationsScopedListWarning';
  protected $warningDataType = '';

  public function setOperations($operations)
  {
    $this->operations = $operations;
  }
  public function getOperations()
  {
    return $this->operations;
  }
  public function setWarning(Google_Service_Compute_OperationsScopedListWarning $warning)
  {
    $this->warning = $warning;
  }
  public function getWarning()
  {
    return $this->warning;
  }
}


text:
package br.cefetrj.sagitarii.persistence.repository;

import java.util.HashSet;
import java.util.Set;

import br.cefetrj.sagitarii.persistence.entity.Consumption;
import br.cefetrj.sagitarii.persistence.exceptions.DatabaseConnectException;
import br.cefetrj.sagitarii.persistence.exceptions.DeleteException;
import br.cefetrj.sagitarii.persistence.exceptions.InsertException;
import br.cefetrj.sagitarii.persistence.exceptions.NotFoundException;
import br.cefetrj.sagitarii.persistence.infra.DaoFactory;
import br.cefetrj.sagitarii.persistence.infra.IDao;

public class ConsumptionRepository extends BasicRepository {

	public ConsumptionRepository() throws DatabaseConnectException {
		super();
		logger.debug("init");
	}

	public Set<Consumption> getList(int idInstance) throws NotFoundException {
		logger.debug("get list" );
		DaoFactory<Consumption> df = new DaoFactory<Consumption>();
		IDao<Consumption> fm = df.getDao(this.session, Consumption.class);
		Set<Consumption> consumptions = null;
		try {
			consumptions = new HashSet<Consumption>( fm.getList("select * from consumptions where id_instance = " + idInstance) );
		} catch ( Exception e ) {
			closeSession();
			throw e;
		}
		closeSession();
		logger.debug("done: " + consumptions.size() + " consumptions.");
		return consumptions;
	}

	public Consumption insertConsumption(Consumption consumption) throws InsertException {
		logger.debug("insert");
		DaoFactory<Consumption> df = new DaoFactory<Consumption>();
		IDao<Consumption> fm = df.getDao(this.session, Consumption.class);

		try {
			fm.insertDO(consumption);
			commit();
		} catch (InsertException e) {
			rollBack();
			closeSession();
			logger.error( e.getMessage() );
			throw e;
		}
		closeSession();
		logger.debug("done");
		return consumption;
	}

	public Consumption getConsumption(int idConsumption) throws NotFoundException {
		logger.debug("get " + idConsumption + "...");
		DaoFactory<Consumption> df = new DaoFactory<Consumption>();
		IDao<Consumption> fm = df.getDao(this.session, Consumption.class);
		Consumption consumption = null;
		try {
			consumption = fm.getDO(idConsumption);
		} catch ( Exception e ) {
			closeSession();
			throw e;
		}
		closeSession();
		logger.debug("done" );
		return consumption;
	}

	public void deleteConsumption(Consumption consumption) throws DeleteException {
		logger.debug("delete" );
		DaoFactory<Consumption> df = new DaoFactory<Consumption>();
		IDao<Consumption> fm = df.getDao(this.session, Consumption.class);
		try {
			fm.deleteDO(consumption);
			commit();
		} catch (DeleteException e) {
			rollBack();
			closeSession();
			logger.error( e.getMessage() );
			throw e;
		}
		logger.debug("done");
		closeSession();
	}

}


text:
"""Starts a service for running portable beam pipelines.

The basic usage is simply

    python -m apache_beam.runners.portability.local_job_service_main

Many other options are also supported, such as starting in the background or
passing in a lockfile to ensure that only one copy of the service is running
at a time.  Pass --help to see them all.
"""

import argparse
import logging
import os
import pathlib
import signal
import subprocess
import sys
import time

from apache_beam.runners.portability import local_job_service

_LOGGER = logging.getLogger(__name__)

def run(argv):
  if argv[0] == __file__:
    argv = argv[1:]
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '-p',
      '--port',
      '--job_port',
      type=int,
      default=0,
      help='port on which to serve the job api')
  parser.add_argument('--staging_dir')
  parser.add_argument(
      '--pid_file', help='File in which to store the process id of the server.')
  parser.add_argument(
      '--port_file', help='File in which to store the port of the server.')
  parser.add_argument(
      '--background',
      action='store_true',
      help='Start the server up as a background process.'
      ' Will fail if pid_file already exists, unless --stop is also specified.')
  parser.add_argument(
      '--stderr_file',
      help='Where to write stderr (if not specified, merged with stdout).')
  parser.add_argument(
      '--stdout_file', help='Where to write stdout for background job service.')
  parser.add_argument(
      '--stop',
      action='store_true',
      help='Stop the existing process, if any, specified in pid_file.'
      ' Will not start up a new service unless --background is specified.')
  options = parser.parse_args(argv)

  if options.stop:
    if not options.pid_file:
      raise RuntimeError('--pid_file must be specified with --stop')
    if os.path.exists(options.pid_file):
      with open(options.pid_file) as fin:
        pid = int(fin.read())
      print('Killing process at', pid)
      try:
        os.kill(pid, signal.SIGTERM)
      except Exception:
        print('Process', pid, 'already killed.')
      os.unlink(options.pid_file)
    else:
      print('Process id file', options.pid_file, 'already removed.')
    if not options.background:
      return

  if options.background:
    if not options.pid_file:
      raise RuntimeError('--pid_file must be specified with --start')
    if options.stop:
      argv.remove('--stop')
    argv.remove('--background')
    if not options.port_file:
      options.port_file = os.path.splitext(options.pid_file)[0] + '.port'
      argv.append('--port_file')
      argv.append(options.port_file)

    if not options.stdout_file:
      raise RuntimeError('--stdout_file must be specified with --background')
    os.makedirs(pathlib.PurePath(options.stdout_file).parent, exist_ok=True)
    stdout_dest = open(options.stdout_file, mode='w')

    if options.stderr_file:
      os.makedirs(pathlib.PurePath(options.stderr_file).parent, exist_ok=True)
      stderr_dest = open(options.stderr_file, mode='w')
    else:
      stderr_dest = subprocess.STDOUT

    subprocess.Popen([
        sys.executable,
        '-m',
        'apache_beam.runners.portability.local_job_service_main'
    ] + argv,
                     stderr=stderr_dest,
                     stdout=stdout_dest)
    print('Waiting for server to start up...')
    while not os.path.exists(options.port_file):
      time.sleep(.1)
    with open(options.port_file) as fin:
      port = fin.read()
    print('Server started at port', port)
    return

  if options.pid_file:
    print('Writing process id to', options.pid_file)
    os.makedirs(pathlib.PurePath(options.pid_file).parent, exist_ok=True)
    fd = os.open(options.pid_file, os.O_CREAT | os.O_EXCL | os.O_RDWR)
    with os.fdopen(fd, 'w') as fout:
      fout.write(str(os.getpid()))
  try:
    job_servicer = local_job_service.LocalJobServicer(options.staging_dir)
    port = job_servicer.start_grpc_server(options.port)
    try:
      if options.port_file:
        print('Writing port to', options.port_file)
        os.makedirs(pathlib.PurePath(options.port_file).parent, exist_ok=True)
        with open(options.port_file + '.tmp', 'w') as fout:
          fout.write(str(port))
        os.rename(options.port_file + '.tmp', options.port_file)
      serve("Listening for beam jobs on port %d." % port, job_servicer)
    finally:
      job_servicer.stop()
  finally:
    if options.pid_file and os.path.exists(options.pid_file):
      os.unlink(options.pid_file)
    if options.port_file and os.path.exists(options.port_file):
      os.unlink(options.port_file)

def serve(msg, job_servicer):
  logging_delay = 30
  while True:
    _LOGGER.info(msg)
    time.sleep(logging_delay)
    logging_delay *= 1.25

if __name__ == '__main__':
  signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  logging.basicConfig()
  logging.getLogger().setLevel(logging.INFO)
  run(sys.argv)


text:
package edu.avans.hartigehap.service.impl;

import javax.persistence.Entity;

import edu.avans.hartigehap.service.IMessage;
import edu.avans.hartigehap.service.INotifyProvider;

@Entity
public class WhatsappNotifyProvider extends NotifyProvider implements INotifyProvider{

	private static final long serialVersionUID = 1L;

	@Override
	public boolean sendMessage(IMessage message) {
		// TODO Auto-generated method stub
		return false;
	}

}


text:
KnpMenu
=======

The admin comes with `KnpMenu`_ integration.
It integrates a menu with the KnpMenu library. This menu can be a SonataAdmin
service, a menu created with a Knp menu provider or a route of a custom controller.

.. note::
    This article assumes you are using Symfony 4. Using Symfony 2.8 or 3
    will require to slightly modify some namespaces and paths when creating
    entities and admins.

Add a custom controller entry in the menu
-----------------------------------------

To add a custom controller entry in the admin menu:

Create your controller::

    <?php

    class BlogController
    {
        /**
         * @Route("/blog", name="blog_home")
         */
        public function blogAction()
        {
            // ...
        }

        /**
         * @Route("/blog/article/{articleId}", name="blog_article")
         */
        public function ArticleAction($articleId)
        {
            // ...
        }
    }

Add the controller route as an item of the menu:

.. configuration-block::

    .. code-block:: yaml

        # config/packages/sonata_admin.yaml

        sonata_admin:
            dashboard:
                groups:
                    news:
                        label:                ~
                        label_catalogue:      ~
                        items:
                            - sonata.news.admin.post
                            - route:        blog_home
                              label:        Blog
                            - route:        blog_article
                              route_params: { articleId: 3 }
                              label:        Article

If you want to show your route to user with different roles, you can configure this for each route. If this is not set,
group roles will be checked.

.. configuration-block::

    .. code-block:: yaml

        # config/packages/sonata_admin.yaml

        sonata_admin:
            dashboard:
                groups:
                    news:
                        label:                ~
                        label_catalogue:      ~
                        items:
                            - sonata.news.admin.post
                            - route:        blog_home
                              label:        Blog
                              roles:        [ ROLE_FOO, ROLE_BAR ]
                            - route:        blog_article
                              route_params: { articleId: 3 }
                              label:        Article
                        roles: [ ROLE_ADMIN, ROLE_SONATA_ADMIN]

You can also override the template of knp_menu used by sonata. The default
one is `@SonataAdmin/Menu/sonata_menu.html.twig`:

.. configuration-block::

    .. code-block:: yaml

        # config/packages/sonata_admin.yaml

        sonata_admin:
            templates:
                knp_menu_template:           "@ApplicationAdmin/Menu/custom_knp_menu.html.twig"

And voilà, now you have a menu group which contains a link to a sonata admin via its id, to your blog and to a specific article.

Using a menu provider
---------------------

As seen above, the main way to declare your menu is by declaring items
in your sonata admin config file. In some cases you may have to create a
more complex menu depending on your business logic. This is possible by
using a menu provider to populate a whole menu group. This is done with
the ``provider`` config value.

The following configuration uses a menu provider to populate the menu group ``my_group``:

.. configuration-block::

    .. code-block:: yaml

        # config/packages/sonata_admin.yaml

        sonata_admin:
            dashboard:
                groups:
                    my_group:
                        provider:        'MyBundle:MyMenuProvider:getMyMenu'
                        icon:            ''

With KnpMenuBundle you can create a custom menu by using a builder class
or by declaring it as a service. Please see the `Knp documentation`_ for
further information.

In sonata, whatever the implementation you choose, you only have to provide
the menu alias to the provider config key:

* If you are using a builder class, your menu alias should be something like ``MyBundle:MyMenuProvider:getMyMenu``.
* If you are using a service, your menu alias is the alias set in the ``knp_menu.menu`` tag. In the following example this is ``my_menu_alias``:

.. configuration-block::

    .. code-block:: xml

        <service id="my_menu_provider" class="MyBundle/MyDirectory/MyMenuProvider">
            <tag name="knp_menu.menu" alias="my_menu_alias" />
        </service>

Please note that when using the provider option, you can't set the menu
label via the configuration. It is done in your custom menu.

Extending the menu
------------------

You can modify the menu via events easily. You can register as many
listeners as you want for the event with name ``sonata.admin.event.configure.menu.sidebar``::

    <?php
    // src/EventListener/MenuBuilderListener.php

    namespace App\EventListener;

    use Sonata\AdminBundle\Event\ConfigureMenuEvent;

    class MenuBuilderListener
    {
        public function addMenuItems(ConfigureMenuEvent $event)
        {
            $menu = $event->getMenu();

            $child = $menu->addChild('reports', [
                'label' => 'Daily and monthly reports',
                'route' => 'app_reports_index',
            ])->setExtras([
                'icon' => '',
            ]);
        }
    }

.. configuration-block::

    .. code-block:: yaml

        # config/services.yaml

        services:
            app.menu_listener:
                class: App\EventListener\MenuBuilderListener
                tags:
                    - { name: kernel.event_listener, event: sonata.admin.event.configure.menu.sidebar, method: addMenuItems }

Please see the `Using events to allow a menu to be extended`_ for further information.

Hiding menu items
-----------------

You can modify the menu to hide some menu items. You need to add the ``show_in_dashboard`` option in
your admin services or simply remove menu items from the ``sonata_admin`` dashboard group configuration:

.. code-block:: yaml

    sonata_admin.admin.post:
        class: Sonata\AdminBundle\Admin\PostAdmin
        arguments: [~, Sonata\AdminBundle\Entity\Post, SonataAdminBundle:CRUD]
        tags:
            - {name: sonata.admin, manager_type: orm, group: admin, label: Post, show_in_dashboard: false}
        public: true

.. code-block:: yaml

    # config/packages/sonata_admin.yaml

    sonata_admin:
        dashboard:
            groups:
                news:
                    label:                ~
                    label_catalogue:      ~
                    items:
                      # just comment or remove the sonata.news.admin.post declaration to hide it from the menu.
                      #  - sonata.news.admin.post
                        - route:        blog_home
                          label:        Blog
                        - sonata.news.admin.news

Keeping menu group open
-----------------------

You can add the ``keep_open`` option to menu group to keep that group always
open and ignore open/close effects:

.. code-block:: yaml

    # config/packages/sonata_admin.yaml

    sonata_admin:
        dashboard:
            groups:
                sonata.admin.group.content:
                    keep_open:            true
                    label:                sonata_media
                    label_catalogue:      SonataMediaBundle
                    icon:                 ''
                    items:
                        - sonata.media.admin.media
                        - sonata.media.admin.gallery

.. figure:: ../images/keep_open.png
   :align: center
   :alt: The navigation side bar with a group which uses "keep_open" option

Show menu item without treeview
-------------------------------

You can modify the menu to show menu item without treeview. You need to add option ``on_top`` in your admin services
or in sonata_admin dashboard group configuration:

.. code-block:: yaml

    sonata_admin.admin.post:
        class: Sonata\AdminBundle\Admin\PostAdmin
        arguments: [~, Sonata\AdminBundle\Entity\Post, SonataAdminBundle:CRUD]
        tags:
            - {name: sonata.admin, manager_type: orm, group: admin, label: Post, on_top: true}
        public: true

.. code-block:: yaml

    # config/packages/sonata_admin.yaml

    sonata_admin:
        dashboard:
            groups:
                news:
                    on_top:               true
                    label:                ~
                    label_catalogue:      ~
                    items:
                        - sonata.news.admin.post

.. figure:: ../images/demo_on_top.png
   :align: center
   :alt: on_top option
   :width: 500

In this screenshot, we add ``on_top`` option to ``Tag`` and ``Blog Post`` admin services.

Your can't use this option for two or more items in the same time, for example:

.. code-block:: yaml

    # config/packages/sonata_admin.yaml

    sonata_admin:
        dashboard:
            groups:
                news:
                    on_top:               true
                    label:                ~
                    label_catalogue:      ~
                    items:
                        - sonata.news.admin.post
                        - route:        blog_home
                          label:        Blog

In this case you have an exception: "You can't use ``on_top`` option with multiple same name groups".

.. _KnpMenu: https://github.com/KnpLabs/KnpMenu
.. _Knp documentation: http://symfony.com/doc/current/bundles/KnpMenuBundle/index.html#create-your-first-menu
.. _Using events to allow a menu to be extended: http://symfony.com/doc/master/bundles/KnpMenuBundle/events.html


text:
[![Build Status](https://travis-ci.org/kmcclosk/compose-io-tools.svg)](https://travis-ci.org/kmcclosk/compose-io-tools)

Useful functions for interacting with the compose.io REST API.


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Removing unique constraint on 'Thumbnail', fields ['name', 'storage_hash']
        db.delete_unique('easy_thumbnails_thumbnail', ['name', 'storage_hash'])

        # Adding unique constraint on 'Thumbnail', fields ['source', 'name', 'storage_hash']
        db.create_unique('easy_thumbnails_thumbnail', ['source_id', 'name', 'storage_hash'])

    def backwards(self, orm):

        # Removing unique constraint on 'Thumbnail', fields ['source', 'name', 'storage_hash']
        db.delete_unique('easy_thumbnails_thumbnail', ['source_id', 'name', 'storage_hash'])

        # Adding unique constraint on 'Thumbnail', fields ['name', 'storage_hash']
        db.create_unique('easy_thumbnails_thumbnail', ['name', 'storage_hash'])

    models = {
        'easy_thumbnails.source': {
            'Meta': {'unique_together': "(('storage_hash', 'name'),)", 'object_name': 'Source'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 9, 16, 9, 47, 8, 272761)'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'storage_hash': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'})
        },
        'easy_thumbnails.thumbnail': {
            'Meta': {'unique_together': "(('storage_hash', 'name', 'source'),)", 'object_name': 'Thumbnail'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 9, 16, 9, 47, 8, 272761)'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'source': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'thumbnails'", 'to': "orm['easy_thumbnails.Source']"}),
            'storage_hash': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'})
        }
    }

    complete_apps = ['easy_thumbnails']


text:
 # huskeliste

## TODO

- [x] eirik: komponenter, rfudino-kode, gzzl
- [x] torgeir: server, klient, raspberry pi-kode
- [x] torgeir: test router
- [x] torgeir: test pi+buttons
- [ ] Lag turnering-skjema med deltagerene
- [x] router
- [x] Mail angående bord

- [x] lage introduksjon-slides: gå igjennom relevant kode, fortell om oppsett, vis hvordan det funker
- [x] kjøp rackets + baller

## ta med til oslo

- [x] rackets + noen baller
- [x] arduino + shields (torgeir)
- [x] arduino + shields (eirik)
- [x] batteri
- [x] gaffa-teip
- [x] loddebolt, tinn, leds, motstander, ledninger, prototype-board, flere pushbuttons
- [x] amperemeter
- [x] kamera (spør emil)
- [x] verktøy: lita tang, umbracosett, leatherman
- [x] verktøy: shiftnøkkel, skrujern
- [x] mus, tastatur, skjerm
- [x] rfduino fra pi+bord
- [x] ruter + str√∏m fra blikkboksen
- [x] pi + str√∏m + hdmi
- [x] noen ekstra tp-kabler


text:
=====
Tests
=====

Running the tests
-----------------
Run these tests from the project ``dts_test_project``, it comes prepacked with the correct settings file and extra apps to enable tests to ensure different apps can exist in ``SHARED_APPS`` and ``TENANT_APPS``.

.. code-block:: bash

    ./manage.py test tenant_schemas.tests

To run the test suite outsite of your application you can use tox_ to test all supported Django versions.

.. code-block:: bash

    tox

Updating your app's tests to work with tenant-schemas
-----------------------------------------------------
Because django will not create tenants for you during your tests, we have packed some custom test cases and other utilities. If you want a test to happen at any of the tenant's domain, you can use the test case ``TenantTestCase``. It will automatically create a tenant for you, set the connection's schema to tenant's schema and make it available at ``self.tenant``. We have also included a ``TenantRequestFactory`` and a ``TenantClient`` so that your requests will all take place at the tenant's domain automatically. Here's an example

.. code-block:: python

    from tenant_schemas.test.cases import TenantTestCase
    from tenant_schemas.test.client import TenantClient

    class BaseSetup(TenantTestCase):
        def setUp(self):
            self.c = TenantClient(self.tenant)

        def test_user_profile_view(self):
            response = self.c.get(reverse('user_profile'))
            self.assertEqual(response.status_code, 200)

Running tests faster
--------------------
Running tests using ``TenantTestCase`` can start being a bottleneck once the number of tests grow. ``TenantTestCase`` drops, recreates and executes migrations for the test schema every time for every ``TenantTestCase`` you have. If you do not care that the state between tests is kept, an alternative is to use the class ``FastTenantTestCase``. Unlike ``TenantTestCase``, the test schema and its migrations will only be created and ran once. This is a significant improvement in speed coming at the cost of shared state.

.. code-block:: python

    from tenant_schemas.test.cases import FastTenantTestCase

.. _tox: https://tox.readthedocs.io/


text:
Haskell Syntax Highlighting in Jupyterlab

## Prerequisites

* JupyterLab

## Installation

```bash
jupyter labextension install jupyterlab-ihaskell
```

## Development

For a development install (requires npm version 4 or later), do the following in the repository directory:

```bash
npm install
npm run build
jupyter labextension link .
```

To rebuild the package and the JupyterLab app:

```bash
npm run build
jupyter lab build
```

## Prebuilt extension

This is currently built with

```bash
$ nix-shell -p 'python3.withPackages(p: [ p.jupyterlab ])' nodejs
[nix-shell] $ npm install
[nix-shell] $ npm run build
[nix-shell] $ jupyter labextension build
```


text:
package net.grandcentrix.tray.provider;

import net.grandcentrix.tray.TrayPreferences;
import net.grandcentrix.tray.core.AbstractTrayPreference;
import net.grandcentrix.tray.core.TrayException;
import net.grandcentrix.tray.core.TrayItem;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Helper for accessing the {@link TrayContentProvider}
 *

 * Created by pascalwelsch on 11/20/14.
 */
public class TrayProviderHelper {

    private final Context mContext;

    private final TrayUri mTrayUri;

    public TrayProviderHelper(@NonNull final Context context) {
        mContext = context;
        mTrayUri = new TrayUri(context);
    }

    /**
     * clears all Preferences saved. Module independent. Erases all preference data
     *
     * @return true when successful
     */
    public boolean clear() {
        try {
            // result can be 0 for an empty module, don't check if rows > 0
            mContext.getContentResolver().delete(mTrayUri.get(), null, null);
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * clears all {@link TrayPreferences} but the modules stated.
     *
     * @param modules modules excluded when deleting preferences
     * @return true when successful, false otherwise. true doesn't indicate that something got
     * cleared, it just means no error occurred
     */
    public boolean clearBut(AbstractTrayPreference... modules) {
        String selection = null;
        String[] selectionArgs = new String[]{};

        for (final AbstractTrayPreference module : modules) {
            if (module == null) {
                continue;
            }
            String moduleName = module.getName();
            selection = SqliteHelper
                    .extendSelection(selection, TrayContract.Preferences.Columns.MODULE + " != ?");
            selectionArgs = SqliteHelper
                    .extendSelectionArgs(selectionArgs, new String[]{moduleName});
        }

        try {
            // result can be 0 for an empty module, don't check if rows > 0
            mContext.getContentResolver().delete(mTrayUri.get(), selection, selectionArgs);
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Builds a list of all Preferences saved.
     *
     * @return all Preferences as list.
     */
    @NonNull
    public List<TrayItem> getAll() {
        return queryProviderSafe(mTrayUri.get());
    }

    /**
     * saves the value into the database.
     *
     * @param module module name
     * @param key    key for mapping
     * @param value  data to save
     * @return true when successfully written
     */
    public boolean persist(@NonNull final String module, @NonNull final String key,
            @NonNull final String value) {
        return persist(module, key, null, value);
    }

    /**
     * saves the value into the database combined with a previousKey.
     *
     * @param module      module name
     * @param key         key for mapping
     * @param previousKey key used before migration
     * @param value       data to save
     * @return true when successfully written
     */
    public boolean persist(@NonNull final String module, @NonNull final String key,
            @Nullable final String previousKey, @Nullable final String value) {
        final Uri uri = mTrayUri.builder()
                .setModule(module)
                .setKey(key)
                .build();
        return persist(uri, value, previousKey);
    }

    public boolean persist(@NonNull final Uri uri, @Nullable String value) {
        return persist(uri, value, null);
    }

    public boolean persist(@NonNull final Uri uri, @Nullable String value,
            @Nullable final String previousKey) {
        ContentValues values = new ContentValues();
        values.put(TrayContract.Preferences.Columns.VALUE, value);
        values.put(TrayContract.Preferences.Columns.MIGRATED_KEY, previousKey);
        try {
            return mContext.getContentResolver().insert(uri, values) != null;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * sends a query for TrayItems to the provider
     *
     * @param uri path to data
     * @return list of items
     * @throws TrayException when something is wrong with the provider/database
     */
    @NonNull
    public List<TrayItem> queryProvider(@NonNull final Uri uri) throws TrayException {
        final Cursor cursor;
        try {
            cursor = mContext.getContentResolver().query(uri, null, null, null, null);
        } catch (Throwable e) {
            throw new TrayException("Hard error accessing the ContentProvider", e);
        }

        // Return Preference if found
        if (cursor == null) {
            // When running in here, please check if your ContentProvider has the correct authority
            throw new TrayException("could not access stored data with uri " + uri);
        }

        final ArrayList<TrayItem> list = new ArrayList<>();
        for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
            final TrayItem trayItem = cursorToTrayItem(cursor);
            list.add(trayItem);
        }
        cursor.close();
        return list;
    }

    /**
     * sends a query for TrayItems to the provider, doesn't throw when the database access couldn't
     * be established
     *
     * @param uri path to data
     * @return list of items, empty when an error occured
     */
    @NonNull
    public List<TrayItem> queryProviderSafe(@NonNull final Uri uri) {
        try {
            return queryProvider(uri);
        } catch (TrayException e) {
            return new ArrayList<>();
        }
    }

    /**
     * removes items for the given Uri
     *
     * @param uri what to remove, use {@link TrayUri#builder()} to build a valid uri
     * @return true when delete runs without error. doesn't care about the delete result int
     */
    public boolean remove(final Uri uri) {
        try {
            mContext.getContentResolver().delete(uri, null, null);
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * removes items for the given Uri and returns the count of the deleted items
     *
     * @param uri what to remove, use {@link TrayUri#builder()} to build a valid uri
     * @return number of deleted rows
     */
    public int removeAndCount(final Uri uri) {
        try {
            return mContext.getContentResolver().delete(uri, null, null);
        } catch (Throwable e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * wipes all data, including meta data for the preferences like the current version number.
     *
     * @return true for success
     */
    public boolean wipe() {
        if (!clear()) {
            return false;
        }
        try {
            return mContext.getContentResolver().delete(mTrayUri.getInternal(), null, null) > 0;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * converts a {@link Cursor} to a {@link TrayItem}
     *

     * This is not a secondary constructor in {@link TrayItem} because the columns are a
     * implementation detail of the provider package
     *
     * @param cursor (size > 1)
     * @return a {@link TrayItem} filled with data
     */
    @NonNull
    static TrayItem cursorToTrayItem(final Cursor cursor) {
        final String module = cursor.getString(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.MODULE));
        final String key = cursor.getString(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.KEY));
        final String migratedKey = cursor.getString(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.MIGRATED_KEY));
        final String value = cursor.getString(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.VALUE));
        final Date created = new Date(cursor.getLong(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.CREATED)));
        final Date updated = new Date(cursor.getLong(cursor
                .getColumnIndexOrThrow(TrayContract.Preferences.Columns.UPDATED)));
        return new TrayItem(module, key, migratedKey, value, created, updated);
    }
}


text:
function Tc = cct(uvs)
% Calculate  correlated color temperature from CIE uv coordinates
%
%   correlatedColorTemperature = cct(uvArray)
%
% The CIE has defined methods for estimating the relationship between
% chromaticity coordinates (uv, see xyz2uv) and the color temperature of a
% blackbody radiator. This routine accepts 1960 UCS chromaticity
% coordinates, uv, and returns the color temperature in degrees Kelvin of
% the correlated blackbody radiators.
%
% This correlated color temperature is often used to summarize the
% appearance properties of a light source.
%
% This routine requires the information in the file: cct.mat
%
% Reference: Wyszecki & Stiles pgs. 227-228
%
% correlatedColorTemperature
% UV  : [u1,u2,u3 ...; v1, v2, v3 ...] chromaticity coordinates as a column vector.
%
%Example:
%  colorTemp = cct([.31,.32]')
%
%
% See also: spd2cct, xyz2uv
%
% Copyright ImagEval Consultants, LLC, 2003.

% TODO:  Make this work for XYZ.  Make an xyY to uv conversion routine.
% Put the cct.mat file in the proper place and give it some decent
% structure.

if ieNotDefined('uvs'), error('uv coordinates are required');
elseif (size(uvs,1) ~= 2), error('uv must have two rows.');
end

cctData = load('cct.mat');

Nd = size(uvs,2);		% Number of uv coordinates
Nt = size(cctData.table,1);	    % Number of temperatures

T  = repmat(cctData.table(:,1),[1 Nd]);
u  = repmat(cctData.table(:,2),[1 Nd]);
v  = repmat(cctData.table(:,3),[1 Nd]);
t  = repmat(cctData.table(:,4),[1 Nd]);

us = repmat(uvs(1,:),[Nt 1]);
vs = repmat(uvs(2,:),[Nt 1]);

d  = ( (us-u) - t.*(vs-v) ) ./ sqrt( 1+t.^2 );

% Instead of dividing as explained in W&S and
% checking for negative values.  I look at the
% signs and took differences.  This avoids
% divide by zero errors.

% ds is padded by zeros to get the indices
% correct when doing the find operation.

ds = sign(d);
ds = ds.*(ds~=0) + 1.*(ds==0);
ds = [ds; zeros(1,Nd)];

j  = find( abs(diff(ds)) == 2 )';

if (length(j) ~= Nd)
    error(['Check input range. ' ...
        'U [' num2str(u(1,1)) ' ' num2str(u(end,1)) ']. ' ...]
        'V [' num2str(v(1,1)) ' ' num2str(v(end,1)) '].']);
end

Tc = 1 ./ ...
    ( 1./T(j) + d(j)./(d(j)-d(j+1)).*(1./T(j+1) - 1./T(j)) );

return;


text:
package org.ambraproject.wombat.service.remote;

import static org.ambraproject.wombat.service.remote.ArticleSearchQuery.ARTICLE_TYPE_FACET_FIELD;
import static org.ambraproject.wombat.service.remote.ArticleSearchQuery.ARTICLE_TYPE_TAG;
import static org.ambraproject.wombat.service.remote.ArticleSearchQuery.JOURNAL_KEY_FIELD;
import static org.ambraproject.wombat.service.remote.ArticleSearchQuery.JOURNAL_TAG;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import org.ambraproject.wombat.util.UrlParamBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.NameValuePair;

public class SolrQueryBuilder {
  private static final int THREAD_PER_FACET = -1;

  public static List<NameValuePair> buildParameters(ArticleSearchQuery asq) {
    UrlParamBuilder params = UrlParamBuilder.params();

    params.add("wt", "json");

    if (asq.isPartialSearch()) {
      params.add("qf", "doc_partial_body");
      params.add("fl", "*");
      params.add("fq", "doc_type:partial");
    } else {
      params.add("fq", "doc_type:full");
    }

    params.add("fq", "!article_type_facet:\"Issue Image\"");

    if (asq.getStart() > 0) {
      params.add("start", Integer.toString(asq.getStart()));
    }
    params.add("rows", Integer.toString(asq.getRows()));

    params.add("hl", "false");

    String queryString = asq.getQuery();
    params.add("q", queryString);
    if (asq.isSimple()) {
      // Use the dismax query parser, recommended for all user-entered queries.
      // See https://wiki.apache.org/solr/DisMax
      params.add("defType", "dismax");
    }

    if (asq.getFacetFields().size() > 0) {
      params.add("facet", "true");
      for (ArticleSearchQuery.Facet field: asq.getFacetFields()) {
        String query = field.getExcludeKey()
          .map(excludeKey->String.format("{!ex=%s}", excludeKey)).orElse("") +
          field.getField();
        params.add("facet.field", query);
      }
      params.add("facet.mincount", Integer.toString(asq.getFacetMinCount()));
      params.add("facet.limit", Integer.toString(asq.getFacetLimit()));
      params.add("facet.threads", Integer.toString(THREAD_PER_FACET));
      params.add("json.nl", "map");
    } else {
      params.add("facet", "false");
    }

    List<String> fields = asq.getFields().orElse(ArticleSearchQuery.ARTICLE_FIELDS);
    params.add("fl", Joiner.on(",").join(fields));

    asq.getCursor().ifPresent(cursor -> params.add("cursorMark", cursor));

    setQueryFilters(asq, params);

    if (asq.getStatsField().isPresent()) {
      params.add("stats", "true");
      params.add("stats.field", asq.getStatsField().get());
    }

    return params.build();
  }

  public static void setQueryFilters(ArticleSearchQuery asq, UrlParamBuilder params) {
    if (asq.getSortOrder().isPresent()) {
      String sortOrderStr = asq.getSortOrder().get().getValue() + ",id desc";
      params.add("sort", sortOrderStr);
    }

    if (asq.getDateRange().isPresent()) {
      String dateRangeStr = asq.getDateRange().get().getValue();
      if (!Strings.isNullOrEmpty(dateRangeStr)) {
        params.add("fq", "publication_date:" + dateRangeStr);
      }
    }
    if (!CollectionUtils.isEmpty(asq.getJournalKeys())) {
      params.add("fq", buildOrSearchClause(JOURNAL_KEY_FIELD,
                                           asq.getJournalKeys(),
                                           JOURNAL_TAG));
    }

    if (!CollectionUtils.isEmpty(asq.getArticleTypes())) {
      params.add("fq", buildOrSearchClause(ARTICLE_TYPE_FACET_FIELD,
                                           asq.getArticleTypes(),
                                           ARTICLE_TYPE_TAG));
    }

    if (!CollectionUtils.isEmpty(asq.getArticleTypesToExclude())) {
      params.add("fq", buildAndSearchClause("!article_type_facet", asq.getArticleTypesToExclude()));
    }

    if (!CollectionUtils.isEmpty(asq.getSubjects())) {
      params.add("fq", buildAndSearchClause("subject", asq.getSubjects()));
    }

    if (!CollectionUtils.isEmpty(asq.getAuthors())) {
      params.add("fq", buildAndSearchClause("author", asq.getAuthors()));
    }

    if (!CollectionUtils.isEmpty(asq.getSections())) {
      List<String> sectionQueryList = new ArrayList<>();
      for (String section : asq.getSections()) {
        //Convert friendly section name to Solr field name TODO:clean this up
        section = section.equals("References") ? "reference" : section;
        sectionQueryList.add(section.toLowerCase().replace(' ', '_'));
      }
      params.add("qf", Joiner.on(" OR ").join(sectionQueryList));
    }
  }

  private static String buildSearchClause(String field, List<String> clauses, String joiner, Optional<String> rawTag) {
    String tag = rawTag.map(t->String.format("{!tag=%s}", t)).orElse("");
    return tag + clauses.stream().map(
      clause -> field + ":" + (clause.equals("*") ? "*" : ("\"" + clause + "\""))
    ).collect(Collectors.joining(joiner));
  }

  static String buildAndSearchClause(String what, List<String> clauses) {
    return buildSearchClause(what, clauses, " AND ", Optional.empty());
  }

  static String buildOrSearchClause(String what, List<String> clauses) {
    return buildSearchClause(what, clauses, " OR ", Optional.empty());
  }

  static String buildOrSearchClause(String what, List<String> clauses, String tag) {
    return buildSearchClause(what, clauses, " OR ", Optional.of(tag));
  }
}


text:
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Gax;
using Google.Protobuf;
using System;

namespace Google.Cloud.Bigtable.V2
{
    /// <summary>
    /// Static class with convenience methods for creating various kinds of <see cref="RowFilter"/> instances.
    /// </summary>
    public static class RowFilters
    {
        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which does not match any
        /// cells, regardless of input. Useful for temporarily disabling just part of
        /// a filter.
        /// </summary>
        /// <returns>The created row filter.</returns>
        public static RowFilter BlockAllFilter() =>
            new RowFilter { BlockAllFilter = true };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only the most
        /// recent N cells within each column.
        /// </summary>
        /// <remarks>
        /// <para>
        /// For example, if N=2, this filter would match column `foo:bar` at timestamps
        /// 10 and 9, skip all earlier cells in `foo:bar`, and then begin matching again
        /// in column `foo:bar2`.
        /// </para>
        /// <para>
        /// If duplicate cells are present, as is possible when using an Interleave,
        /// each copy of the cell is counted separately.
        /// </para>
        /// </remarks>
        /// <param name="limit">
        /// The maximum number of cells allowed per column.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter CellsPerColumnLimit(int limit) =>
            new RowFilter { CellsPerColumnLimitFilter = limit };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only the first
        /// N cells of each row.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If duplicate cells are present, as is possible when using an Interleave,
        /// each copy of the cell is counted separately.
        /// </para>
        /// </remarks>
        /// <param name="limit">
        /// The maximum number of cells allowed per row.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter CellsPerRowLimit(int limit) =>
            new RowFilter { CellsPerRowLimitFilter = limit };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which skips the first N cells
        /// of each row, matching all subsequent cells.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If duplicate cells are present, as is possible when using an Interleave,
        /// each copy of the cell is counted separately.
        /// </para>
        /// </remarks>
        /// <param name="offset">
        /// The number of cells to skip per row.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter CellsPerRowOffset(int offset) =>
            new RowFilter { CellsPerRowOffsetFilter = offset };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which sends rows through
        /// several RowFilters in sequence.
        /// </summary>
        /// <param name="filters">
        /// The elements of "filters" are chained together to process the input row:
        /// in row -> f(0) -> intermediate row -> f(1) -> ... -> f(N) -> out row
        /// The full chain is executed atomically.  Must not be null, or contain null
        /// elements.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter Chain(params RowFilter[] filters) =>
            new RowFilter
            {
                Chain = new RowFilter.Types.Chain
                {
                    Filters = { Utilities.ValidateCollection(filters, nameof(filters)) }
                }
            };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells from
        /// columns whose qualifiers satisfy the given RE2 regex.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The format of RE2 is documented at https://github.com/google/re2/wiki/Syntax.
        /// </para>
        /// <para>
        /// Note that, since column qualifiers can contain arbitrary bytes, the `\C`
        /// escape sequence must be used if a true wildcard is desired. The `.`
        /// character will not match the new line character `\n`, which may be
        /// present in a binary qualifier.
        /// </para>
        /// </remarks>
        /// <param name="regex">
        /// The RE2 regex used to match column qualifiers.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter ColumnQualifierRegex(string regex) =>
            new RowFilter { ColumnQualifierRegexFilter = ByteString.CopyFromUtf8(regex) };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells from
        /// columns within the given range.
        /// </summary>
        /// <param name="range">
        /// The range of columns from which cells should be matched. Must not be null.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter ColumnRange(ColumnRange range) =>
            new RowFilter { ColumnRangeFilter = GaxPreconditions.CheckNotNull(range, nameof(range)) };

        // TODO: Add additional ColumnRange... methods to take start/end values?

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which applies one of two
        /// possible RowFilters to the data based on the output of a predicate
        /// RowFilter.
        /// </summary>
        /// <param name="predicateFilter">
        /// If <paramref name="predicateFilter"/> outputs any cells, then
        /// <paramref name="trueFilter"/> will be evaluated on the input row.
        /// Otherwise, <paramref name="falseFilter"/> will be evaluated.
        /// Must not be null.
        /// </param>
        /// <param name="trueFilter">
        /// The filter to apply to the input row if <paramref name="predicateFilter"/>
        /// returns any results. If null, no results will be returned in the true case.
        /// </param>
        /// <param name="falseFilter">
        /// The filter to apply to the input row if <paramref name="predicateFilter"/>
        /// does not return any results. If null, no results will be returned in the
        /// false case.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter Condition(
            RowFilter predicateFilter, RowFilter trueFilter, RowFilter falseFilter) =>
            new RowFilter
            {
                Condition = new RowFilter.Types.Condition
                {
                    // TODO: Verify this on server. Might be allowed for (row contains any cells).
                    PredicateFilter = GaxPreconditions.CheckNotNull(predicateFilter, nameof(predicateFilter)),
                    TrueFilter = trueFilter,
                    FalseFilter = falseFilter
                }
            };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// from columns whose families satisfy the given RE2 regex.
        /// </summary>
        /// <remarks>
        /// <para>
        /// For technical reasons, the regex must not contain the `:` character, even
        /// if it is not being used as a literal. Note that, since column families
        /// cannot contain the new line character `\n`, it is sufficient to use `.`
        /// as a full wildcard when matching column family names.
        /// </para>
        /// </remarks>
        /// <param name="regex">
        /// The RE2 regex used to match column families. Must not be null.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter FamilyNameRegex(string regex) =>
            new RowFilter { FamilyNameRegexFilter = GaxPreconditions.CheckNotNull(regex, nameof(regex)) };

        // TODO: Copy docs from Interleave.Filters, but only once the formatting issues are resolved.
        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which applies several
        /// RowFilters to the data in parallel and combines the results.
        /// </summary>
        /// <param name="filters">
        /// The filters to apply in parallel. Must not be null, or contain null elements.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter Interleave(params RowFilter[] filters) =>
            new RowFilter
            {
                Interleave = new RowFilter.Types.Interleave
                {
                    Filters = { Utilities.ValidateCollection(filters, nameof(filters)) }
                }
            };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches all cells,
        /// regardless of input. Functionally equivalent to leaving `filter` unset,
        /// but included for completeness.
        /// </summary>
        /// <returns>The created row filter.</returns>
        public static RowFilter PassAllFilter() =>
            new RowFilter { PassAllFilter = true };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// from rows whose keys satisfy the given RE2 regex. In other words, passes
        /// through the entire row when the key matches, and otherwise produces an
        /// empty row.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The format of RE2 is documented at https://github.com/google/re2/wiki/Syntax.
        /// </para>
        /// <para>
        /// Note that, since row keys can contain arbitrary bytes, the `\C` escape
        /// sequence must be used if a true wildcard is desired. The `.` character
        /// will not match the new line character `\n`, which may be present in a
        /// binary key.
        /// </para>
        /// </remarks>
        /// <param name="regex">
        /// The RE2 regex used to match row keys.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter RowKeyRegex(string regex) =>
            new RowFilter { RowKeyRegexFilter = ByteString.CopyFromUtf8(regex) };

        // TODO: Seems like this is 0-1. Verify and document it. Validate too?
        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches all cells
        /// from a row with probability p, and matches no cells from the row with
        /// probability 1-p.
        /// </summary>
        /// <param name="probability">
        /// The probability with which rows should be matched.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter RowSample(double probability) =>
            new RowFilter { RowSampleFilter = probability };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which replaces each cell's
        /// value with the empty string. This is useful for increasing performance when
        /// only getting cell counts rather than cell values.
        /// </summary>
        /// <returns>The created row filter.</returns>
        public static RowFilter StripValueTransformer() =>
            new RowFilter { StripValueTransformer = true };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// with versions within the given range.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Note: version values are stored on the server as if they are microseconds since the Unix epoch.
        /// However, the server only supports millisecond granularity, so the server only allows microseconds
        /// in multiples of 1,000. <see cref="BigtableVersion"/> attempts to hide this complexity by exposing
        /// its underlying <see cref="BigtableVersion.Value"/> in terms of milliseconds, so if desired, a
        /// custom versioning scheme of 1, 2, ... can be used rather than 1000, 2000, ... However, access to
        /// the underlying microsecond value is still provided via <see cref="BigtableVersion.Micros"/>.
        /// </para>
        /// <para>
        /// Note: when using ReadModifyWriteRow, modified columns automatically use a server version, which
        /// is based on the current timestamp since the Unix epoch. For those columns, other reads and writes
        /// should use <see cref="BigtableVersion"/> values constructed from DateTime values, as opposed to
        /// using a custom versioning scheme with 64-bit values.
        /// </para>
        /// </remarks>
        /// <param name="startTimestamp">
        /// Of the range of versions from which cells should be matched, inclusive lower bound timestamp
        /// whose milliseconds since the Unix epoch should be used as the version value. If null, interpreted
        /// as 0.  It must be specified in UTC.
        /// </param>
        /// <param name="endTimestamp">
        /// Of the range of versions from which cells should be matched, exclusive upper bound timestamp
        /// whose milliseconds since the Unix epoch should be used as the version value. If null, interpreted
        /// as infinity.  It must be specified in UTC.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter TimestampRange(DateTime? startTimestamp, DateTime? endTimestamp) =>
            VersionRange(new BigtableVersionRange(startTimestamp, endTimestamp));

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// with values that fall within the given range.
        /// </summary>
        /// <param name="range">
        /// The range of values to match. Must not be null.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter ValueRange(ValueRange range) =>
            new RowFilter { ValueRangeFilter = GaxPreconditions.CheckNotNull(range, nameof(range)) };

        // TODO: Add additional ValueRange... methods to take start/end values?

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// with values that satisfy the given regular expression.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The format of RE2 is documented at https://github.com/google/re2/wiki/Syntax.
        /// </para>
        /// <para>
        /// Note that, since cell values can contain arbitrary bytes, the `\C` escape
        /// sequence must be used if a true wildcard is desired. The `.` character
        /// will not match the new line character `\n`, which may be present in a
        /// binary value.
        /// </para>
        /// </remarks>
        /// <param name="regex">
        /// The RE2 regex used to match cell values.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter ValueRegex(string regex) =>
            new RowFilter { ValueRegexFilter = ByteString.CopyFromUtf8(regex) };

        /// <summary>
        /// Creates a new <see cref="RowFilter"/> instance which matches only cells
        /// with versions within the given range.
        /// </summary>
        /// <param name="range">
        /// The range of versions from which cells should be matched. Must not be null.
        /// </param>
        /// <returns>The created row filter.</returns>
        public static RowFilter VersionRange(BigtableVersionRange range) =>
            new RowFilter { TimestampRangeFilter = GaxPreconditions.CheckNotNull(range, nameof(range)).ToTimestampRange() };

        // TODO: Add additional VersionRange... methods to take start/end values?
    }
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>helix-front documentation</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/x-icon" href="./images/favicon.ico">
	   <link rel="stylesheet" href="./styles/style.css">
        <link rel="stylesheet" href="./styles/dark.css">

            helix-front documentation
            <button type="button" class="btn btn-default btn-menu ion-ios-menu" id="btn-menu"></button>

<input type="text" placeholder="Type to search">
            <compodoc-menu></compodoc-menu>

                   <compodoc-menu mode="normal"></compodoc-menu>

Modules

AppModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/AppModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

ChooserModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/ChooserModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

ClusterModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/ClusterModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

ConfigurationModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/ConfigurationModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

ControllerModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/ControllerModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

CoreModule

                                    No graph available.

                            Browse

DashboardModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/DashboardModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

HistoryModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/HistoryModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

InstanceModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/InstanceModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

MaterialModule

                                    No graph available.

                            Browse

ResourceModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/ResourceModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

SharedModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/SharedModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

TestingModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/TestingModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

WorkflowModule

                                    <object id="demo-svg" type="image/svg+xml" lazy="./modules/WorkflowModule/dependencies.svg" style="width: 100%; height: 175px;">
                                        Your browser does not support SVG
                                    </object>

                            Browse

 results matching ""

No results matching ""

               <input type="checkbox">

                    <svg class="slider-icon" viewBox="0 0 24 24" fill="none" height="20" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" width="20" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
                    </svg>


text:
/* Interrupt based USART RX driver for STM32 */

#include "usart.h"

#include "atomic.h"
#include "common.h"
#include "queue.h"
#include "registers.h"

static void usart_rx_init(struct usart_config const *config)
{
	intptr_t base = config->hw->base;

	STM32_USART_CR1(base) |= STM32_USART_CR1_RXNEIE;
	STM32_USART_CR1(base) |= STM32_USART_CR1_RE;
}

static void usart_rx_interrupt_handler(struct usart_config const *config)
{
	intptr_t base = config->hw->base;
	uint8_t  byte;

	if (!(STM32_USART_SR(base) & STM32_USART_SR_RXNE))
		return;

	byte = STM32_USART_RDR(base);

	if (!queue_add_unit(config->producer.queue, &byte))
		atomic_add(&config->state->rx_dropped, 1);
}

struct usart_rx const usart_rx_interrupt = {
	.producer_ops = {
		/*
		 * Nothing to do here, we either had enough space in the queue
		 * when a character came in or we dropped it already.
		 */
		.read = NULL,
	},

	.init      = usart_rx_init,
	.interrupt = usart_rx_interrupt_handler,
};


text:
{-# LANGUAGE TemplateHaskell, QuasiQuotes, ScopedTypeVariables #-}
-- | A generator is executed at compile time to load a list of entries
-- to embed into the subsite.  This module contains several basic generators,
-- but the design of generators and entries is such that it is straightforward
-- to make custom generators for your own specific purposes, see <#g:4 this section>.
module Yesod.EmbeddedStatic.Generators (
  -- * Generators
    Location
  , embedFile
  , embedFileAt
  , embedDir
  , embedDirAt
  , concatFiles
  , concatFilesWith

  -- * Compression options for 'concatFilesWith'
  , jasmine
  , uglifyJs
  , yuiJavascript
  , yuiCSS
  , closureJs
  , compressTool
  , tryCompressTools

  -- * Util
  , pathToName

  -- * Custom Generators

  -- $example
) where

import Control.Applicative ((<$>), (<*>))
import Control.Exception (try, SomeException)
import Control.Monad (forM, when)
import Control.Monad.Trans.Resource (runResourceT)
import Data.Char (isDigit, isLower)
import Data.Conduit (($$))
import Data.Default (def)
import Data.Maybe (isNothing)
import Language.Haskell.TH
import Network.Mime (defaultMimeLookup)
import System.Directory (doesDirectoryExist, getDirectoryContents, findExecutable)
import System.FilePath ((</>))
import Text.Jasmine (minifym)
import qualified Data.ByteString.Lazy as BL
import qualified Data.Conduit.List as C
import Data.Conduit.Binary (sourceHandle)
import qualified Data.Text as T
import qualified System.Process as Proc
import System.Exit (ExitCode (ExitSuccess))
import Control.Concurrent.Async (Concurrently (..))
import System.IO (hClose)

import Yesod.EmbeddedStatic.Types

-- | Embed a single file.  Equivalent to passing the same string twice to 'embedFileAt'.
embedFile :: FilePath -> Generator
embedFile f = embedFileAt f f

-- | Embed a single file at a given location within the static subsite and generate a
--   route variable based on the location via 'pathToName'.  The @FilePath@ must be a relative
--   path to the directory in which you run @cabal build@.  During development, the file located
--   at this filepath will be reloaded on every request.  When compiling for production, the contents
--   of the file will be embedded into the executable and so the file does not need to be
--   distributed along with the executable.
embedFileAt :: Location -> FilePath -> Generator
embedFileAt loc f = do
    let mime = defaultMimeLookup $ T.pack f
    let entry = def {
                    ebHaskellName = Just $ pathToName loc
                  , ebLocation = loc
                  , ebMimeType = mime
                  , ebProductionContent = BL.readFile f
                  , ebDevelReload = [| BL.readFile $(litE $ stringL f) |]
                  }
    return [entry]

-- | List all files recursively in a directory
getRecursiveContents :: Location -- ^ The directory to search
                     -> FilePath   -- ^ The prefix to add to the filenames
                     -> IO [(Location,FilePath)]
getRecursiveContents prefix topdir = do
  names <- getDirectoryContents topdir
  let properNames = filter (`notElem` [".", ".."]) names
  paths <- forM properNames $ \name -> do
    let path = topdir </> name
    let loc = if null prefix then name else prefix ++ "/" ++ name
    isDirectory <- doesDirectoryExist path
    if isDirectory
      then getRecursiveContents loc path
      else return [(loc, path)]
  return (concat paths)

-- | Embed all files in a directory into the static subsite.
--
-- Equivalent to passing the empty string as the location to 'embedDirAt',
-- so the directory path itself is not part of the resource locations (and so
-- also not part of the generated route variable names).
embedDir :: FilePath -> Generator
embedDir = embedDirAt ""

-- | Embed all files in a directory to a given location within the static subsite.
--
-- The directory tree rooted at the 'FilePath' (which must be relative to the directory in
-- which you run @cabal build@) is embedded into the static subsite at the given
-- location.  Also, route variables will be created based on the final location
-- of each file.  For example, if a directory \"static\" contains the files
--
-- * css/bootstrap.css
--
-- * js/jquery.js
--
-- * js/bootstrap.js
--
-- then @embedDirAt \"somefolder\" \"static\"@ will
--
-- * Make the file @static\/css\/bootstrap.css@ available at the location
--   @somefolder\/css\/bootstrap.css@ within the static subsite and similarly
--   for the other two files.
--
-- * Create variables @somefolder_css_bootstrap_css@, @somefolder_js_jquery_js@,
--   @somefolder_js_bootstrap_js@ all of type @Route EmbeddedStatic@.
--
-- * During development, the files will be reloaded on every request.  During
--   production, the contents of all files will be embedded into the executable.
--
-- * During development, files that are added to the directory while the server
--   is running will not be detected.  You need to recompile the module which
--   contains the call to @mkEmbeddedStatic@.  This will also generate new route
--   variables for the new files.
embedDirAt :: Location -> FilePath -> Generator
embedDirAt loc dir = do
    files <- runIO $ getRecursiveContents loc dir
    concat <$> mapM (uncurry embedFileAt) files

-- | Concatinate a list of files and embed it at the location.  Equivalent to passing @return@ to
--   'concatFilesWith'.
concatFiles :: Location -> [FilePath] -> Generator
concatFiles loc files = concatFilesWith loc return files

-- | Concatinate a list of files into a single 'BL.ByteString', run the resulting content through the given
--   function, embed it at the given location, and create a haskell variable name for the route based on
--   the location.
--
--   The processing function is only run when compiling for production, and the processing function is
--   executed at compile time.  During development, on every request the files listed are reloaded,
--   concatenated, and served as a single resource at the given location without being processed.
concatFilesWith :: Location -> (BL.ByteString -> IO BL.ByteString) -> [FilePath] -> Generator
concatFilesWith loc process files = do
    let load = do putStrLn $ "Creating " ++ loc
                  BL.concat <$> mapM BL.readFile files >>= process
        expFiles = listE $ map (litE . stringL) files
        expCt = [| BL.concat <$> mapM BL.readFile $expFiles |]
        mime = defaultMimeLookup $ T.pack loc
    return [def { ebHaskellName = Just $ pathToName loc
                , ebLocation = loc
                , ebMimeType = mime
                , ebProductionContent = load
                , ebDevelReload = expCt
                }]

-- | Convienient rexport of 'minifym' with a type signature to work with 'concatFilesWith'.
jasmine :: BL.ByteString -> IO BL.ByteString
jasmine ct = return $ either (const ct) id $ minifym ct

-- | Use <https://github.com/mishoo/UglifyJS2 UglifyJS2> to compress javascript.
-- Assumes @uglifyjs@ is located in the path and uses options @[\"-m\", \"-c\"]@
-- to both mangle and compress and the option \"-\" to cause uglifyjs to read from
-- standard input.
uglifyJs :: BL.ByteString -> IO BL.ByteString
uglifyJs = compressTool "uglifyjs" ["-", "-m", "-c"]

-- | Use <http://yui.github.io/yuicompressor/ YUI Compressor> to compress javascript.
-- Assumes a script @yuicompressor@ is located in the path.  If not, you can still
-- use something like
--
-- > compressTool "java" ["-jar", "/path/to/yuicompressor.jar", "--type", "js"]
yuiJavascript :: BL.ByteString -> IO BL.ByteString
yuiJavascript = compressTool "yuicompressor" ["--type", "js"]

-- | Use <http://yui.github.io/yuicompressor/ YUI Compressor> to compress CSS.
-- Assumes a script @yuicompressor@ is located in the path.
yuiCSS :: BL.ByteString -> IO BL.ByteString
yuiCSS = compressTool "yuicompressor" ["--type", "css"]

-- | Use <https://developers.google.com/closure/compiler/ Closure> to compress
-- javascript using the default options.  Assumes a script @closure@ is located in
-- the path. If not, you can still run using
--
-- > compressTool "java" ["-jar", "/path/to/compiler.jar"]
closureJs :: BL.ByteString -> IO BL.ByteString
closureJs = compressTool "closure" []

-- | Helper to convert a process into a compression function.  The process
-- should be set up to take input from standard input and write to standard output.
compressTool :: FilePath -- ^ program
             -> [String] -- ^ options
             -> BL.ByteString -> IO BL.ByteString
compressTool f opts ct = do
    mpath <- findExecutable f
    when (isNothing mpath) $
        fail $ "Unable to find " ++ f
    let p = (Proc.proc f opts)
                { Proc.std_in = Proc.CreatePipe
                , Proc.std_out = Proc.CreatePipe
                }
    (Just hin, Just hout, _, ph) <- Proc.createProcess p
    (compressed, (), code) <- runConcurrently $ (,,)
        <$> Concurrently (sourceHandle hout $$ C.consume)
        <*> Concurrently (BL.hPut hin ct >> hClose hin)
        <*> Concurrently (Proc.waitForProcess ph)
    if code == ExitSuccess
        then do
            putStrLn $ "Compressed successfully with " ++ f
            return $ BL.fromChunks compressed
        else error $ "compressTool: compression failed with " ++ f

-- | Try a list of processing functions (like the compressions above) one by one until
-- one succeeds (does not raise an exception).  Once a processing function succeeds,
-- none of the remaining functions are used.  If none succeeds, the input is just
-- returned unprocessed.  This is helpful if you are distributing
-- code on hackage and do not know what compressors the user will have installed.  You
-- can list several and they will be tried in order until one succeeds.
tryCompressTools :: [BL.ByteString -> IO BL.ByteString] -> BL.ByteString -> IO BL.ByteString
tryCompressTools [] x = return x
tryCompressTools (p:ps) x = do
    mres <- try $ p x
    case mres of
        Left (err :: SomeException) -> do
            putStrLn $ show err
            tryCompressTools ps x
        Right res -> return res

-- | Clean up a path to make it a valid haskell name by replacing all non-letters
--   and non-numbers by underscores.  In addition, if the path starts with a capital
--   letter or number add an initial underscore.
pathToName :: FilePath -> Name
pathToName f = routeName
    where
      replace c
        | 'A' <= c && c <= 'Z' = c
        | 'a' <= c && c <= 'z' = c
        | '0' <= c && c <= '9' = c
        | otherwise = '_'
      name = map replace f
      routeName = mkName $
            case () of
                ()
                    | null name -> error "null-named file"
                    | isDigit (head name) -> '_' : name
                    | isLower (head name) -> name
                    | otherwise -> '_' : name

-- $example
-- Here is an example of creating your own custom generator.
-- Because of template haskell stage restrictions, you must define generators in a
-- different module from where you use them.  The following generator will embed a
-- JSON document that contains the compile time.
--
-- >{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
-- >module CompileTime where
-- >
-- >import Data.Aeson
-- >import Data.Default
-- >import Data.Time
-- >import Yesod.EmbeddedStatic.Generators
-- >import Yesod.EmbeddedStatic.Types
-- >import qualified Data.ByteString.Lazy as BL
-- >
-- >getTime :: IO BL.ByteString
-- >getTime = do
-- >    t <- getCurrentTime
-- >    return $ encode $
-- >        object [ "compile_time" .= show t ]
-- >
-- >timeGenerator :: Location -> Generator
-- >timeGenerator loc =
-- >    return $ [def
-- >        { ebHaskellName = Just $ pathToName loc
-- >        , ebLocation    = loc
-- >        , ebMimeType    = "application/json"
-- >        , ebProductionContent = getTime
-- >        , ebDevelReload = [| getTime |]
-- >        }]
--
-- Notice how the @getTime@ action is given as both 'ebProductionContent' and
-- 'ebDevelReload'.  The result is that during development, the @getTime@ action
-- will be re-executed on every request so the time returned will be different
-- for each reload.  When compiling for production, the @getTime@ action will
-- be executed once at compile time to produce the content to embed and never
-- called at runtime.
--
-- Here is a small example yesod program using this generator.  Try toggling
-- the development argument to @mkEmbeddedStatic@.
--
-- >{-# LANGUAGE TemplateHaskell, QuasiQuotes, TypeFamilies #-}
-- >module Main where
-- >
-- >import Yesod
-- >import Yesod.EmbeddedStatic
-- >import CompileTime (timeGenerator)
-- >
-- >mkEmbeddedStatic True "eStatic" [timeGenerator "compile-time.json"]
-- >
-- >-- The above will generate variables
-- >-- eStatic :: EmbeddedStatic
-- >-- compile_time_json :: Route EmbeddedStatic
-- >
-- >data MyApp = MyApp { getStatic :: EmbeddedStatic }
-- >
-- >mkYesod "MyApp" [parseRoutes|
-- >/ HomeR GET
-- >/static StaticR EmbeddedStatic getStatic
-- >|]
-- >
-- >instance Yesod MyApp
-- >
-- >getHomeR :: Handler Html
-- >getHomeR = defaultLayout $ [whamlet|
-- >
Hello
-- >
Check the
-- >    compile time
-- >|]
-- >
-- >main :: IO ()
-- >main = warp 3000 $ MyApp eStatic


text:
<?php
namespace Spot;

/**
* Entity object interface
*
* @package Spot
*/
interface EntityInterface
{
    /**
     * Table name getter/setter
     */
    public static function table($tableName = null);

    /**
     * Connection name getter/setter
     */
    public static function connection($connectionName = null);

    /**
     * Datasource options getter/setter
     */
    public static function tableOptions($tableOpts = null);

    /**
     * Mapper name getter
     */
    public static function mapper();

    /**
     * Return defined fields of the entity
     */
    public static function fields();

    /**
     * Add events to this entity
     */
    public static function events(EventEmitter $eventEmitter);

    /**
     * Return defined fields of the entity
     */
    public static function relations(MapperInterface $mapper, EntityInterface $entity);

    /**
     * Return scopes defined by this entity. Scopes are called from the
     * Spot\Query object as a sort of in-context dynamic query method
     */
    public static function scopes();

    /**
     * Gets and sets data on the current entity
     */
    public function data($data = null, $modified = true);

    /**
     * Return array of field data with data from the field names listed removed
     *
     * @param array List of field names to exclude in data list returned
     */
    public function dataExcept(array $except);

    /**
     * Gets data that has been modified since object construct,
     * optionally allowing for selecting a single field
     */
    public function dataModified($field = null);

    /**
     * Gets data that has not been modified since object construct,
     * optionally allowing for selecting a single field
     */
    public function dataUnmodified($field = null);

    /**
     * Is entity new (unsaved)?
     *
     * @return boolean
     */
    public function isNew($new = null);

    /**
     * Returns true if a field has been modified.
     * If no field name is passed in, return whether any fields have been changed
     */
    public function isModified($field = null);

    /**
     * Alias of self::data()
     */
    public function toArray();

    /**
     * Check if any errors exist
     *
     * @param  string  $field OPTIONAL field name
     * @return boolean
     */
    public function hasErrors($field = null);

    /**
     * Error message getter/setter
     *
     * @param $field string|array String return errors with field key, array sets errors
     * @return self|array|boolean Setter return self, getter returns array or boolean if key given and not found
     */
    public function errors($msgs = null, $overwrite = true);

    /**
     * Add an error to error messages array
     *
     * @param string $field Field name that error message relates to
     * @param mixed  $msg   Error message text - String or array of messages
     */
    public function error($field, $msg);

    /**
     * Enable isset() for object properties
     */
    public function __isset($key);

    /**
     * Getter for field properties
     */
    public function &__get($field);
    public function get($field);

    /**
     * Setter for field properties
     */
    public function __set($field, $value);
    public function set($field, $value, $modified = true);

    /**
     * Get/Set relation
     */
    public function relation($relationName, $relationObj = null);

    /**
     * Get primary key field name
     *
     * @return string Primary key field name
     */
    public function primaryKeyField();

    /**
     * Get the value of the primary key field defined on this entity
     *
     * @return mixed Value of the primary key field
     */
    public function primaryKey();

    /**
     * Return array for json_encode()
     */
    public function jsonSerialize();

    /**
     * String representation of the class (JSON)
     */
    public function __toString();
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rounded_custom_border"
    tools:context="io.pslab.fragment.TimebaseTriggerFragment">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginEnd="@dimen/timebase_margin_end"
        android:layout_marginStart="@dimen/timebase_margin_start">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:foregroundGravity="center_vertical">

            <TextView
                android:id="@+id/tv_timebase_label_tt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center_vertical"
                android:gravity="center"
                android:text="@string/timebase"
                android:textSize="14sp"
                android:textStyle="normal|bold"
                app:layout_constraintTop_toTopOf="parent"
                tools:layout_editor_absoluteX="311dp" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="match_parent" />

            <io.pslab.others.FloatSeekBar
                android:id="@+id/seekBar_timebase_tt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/checkbox_trigger_tt"
                android:layout_gravity="center_vertical"
                android:layout_marginEnd="0dp"
                android:layout_marginStart="0dp"
                android:layout_marginTop="0dp"
                android:layout_weight="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tv_timebase_label_tt" />

            <TextView
                android:id="@+id/tv_timebase_values_tt"
                android:layout_width="85dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <CheckBox
                android:id="@+id/checkbox_trigger_tt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/tv_timebase_label_tt"
                android:layout_below="@+id/seekBar2"
                android:layout_gravity="center_vertical|center_horizontal"
                android:paddingEnd="10dp"
                android:paddingStart="0dp"
                android:text="@string/trigger"
                android:textColor="@android:color/background_dark"
                android:textSize="14sp"
                android:textStyle="normal|bold"
                app:layout_constraintTop_toBottomOf="@+id/seekBar_timebase_tt"
                tools:layout_editor_absoluteX="318dp"
                android:layout_alignLeft="@+id/tv_timebase_label_tt"
                android:paddingRight="10dp"
                android:paddingLeft="0dp" />

            <Space
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <Spinner
                android:id="@+id/spinner_trigger_channel_tt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/checkbox_trigger_tt"
                android:layout_gravity="center_vertical"
                android:layout_toEndOf="@+id/tv_timebase_label_tt"
                android:layout_toRightOf="@+id/tv_timebase_label_tt"
                tools:layout_editor_absoluteX="52dp"
                tools:layout_editor_absoluteY="121dp" />

            <io.pslab.others.FloatSeekBar
                android:id="@+id/seekBar_trigger"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/checkbox_trigger_tt"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tv_timebase_label_tt" />

            <TextView
                android:id="@+id/tv_trigger_values_tt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_gravity="center_vertical"
                android:text="@string/text_view" />
        </TableRow>

    </TableLayout>

</RelativeLayout>