text:
package wordprocessor;

/**
 * Text formatting information.
 *
 * Currently this is only bold and italic.
 *
 * @author  <insert your name here>
 * @version  1.2
 */
class Style {
	/** True if the text is formatted in bold, false otherwise. */
	private boolean bold;

	/** True if the text is formatted in italic, false otherwise. */
	private boolean italic;

	/**
	 * Creates a new Style object.
	 *
	 * @param bold True iff the Style shall be bold.
	 * @param italic True iff the Style shall be italic.
	 */
	public Style(boolean bold, boolean italic) {
	}

	/**
	 * Sets the bold and italic attributes according to the given style-change command.
	 *
	 * @param change The style-change command
	 */
	public void apply(StyleChange change) {
	}

	/**
	 * Returns true iff text of this Style is bold.
	 *
	 * @return True iff text of this Style is bold.
	 */
	public boolean isBold() {
	}

	/**
	 * Returns true iff text of this Style is italic.
	 *
	 * @return True iff text of this Style is italic.
	 */
	public boolean isItalic() {
	}

	/**
	 * Compares Styles for equality with other objects.
	 *
	 * Styles are equal, when they format text in the same way, e.g.
	 * both are non-bold and non-italic,
	 * both are bold but non-italic,
	 * both are non-bold but italic, or
	 * both are bold and italic.
	 *
	 * @param other The object to compare to.
	 * @return True iff the Styles are equal.
	 */
	public boolean equals(Object other) {
	}

	/**
	 * Returns a String containing HTML opening tags for the Style.
	 *
	 * The String must only contain <b>, <i>, where the former is
	 * used for all bold Styles and the later is used for all italic Styles.
	 *
	 * For testability of the method's output the bold tag must come before
	 * italic one.
	 *
	 * @return String containing HTML start tags for the Style
	 */
	public String getHTMLStartTags() {
	}

	/**
	 * Returns a String containing HTML end tags for the Style.
	 *
	 * The String contains any combination of </b> for bold and
	 * </i> for italic text, and no other characters.
	 *
	 * Ordering of the tags must be consistent with getHTMLStartTags(), so that
	 * an HTML document generated with these methods has correctly nested tags.
	 *
	 * @return String containing HTML end tags for the Style
	 */
	public String getHTMLEndTags() {
	}
}


text:
using System;
using System.Collections.Generic;
using Tup.Cobar4Net.Parser.Visitor;

namespace Tup.Cobar4Net.Parser.Ast.Expression.Primary.Function.Cast
{
    /// <author>
    ///     QIU Shuo
    /// </author>
    public class Convert : FunctionExpression
    {
        public Convert(IExpression arg, string transcodeName)
            : base("CONVERT", WrapList(arg))
        {
            if (null == transcodeName)
            {
                throw new ArgumentException("transcodeName is null");
            }
            TranscodeName = transcodeName;
        }

        public virtual string TranscodeName { get; }

        public override FunctionExpression ConstructFunction(IList<IExpression> arguments)
        {
            throw new NotSupportedException("function of char has special arguments");
        }

        public override void Accept(ISqlAstVisitor visitor)
        {
            visitor.Visit(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class ImageUploader < BaseUploader
  def allowed_types
    @allowed_types ||= %w[image/jpeg image/jpg image/png image/svg+xml image/gif].freeze
  end
end


text:
package at.ac.univie.isc.asio.security;

import at.ac.univie.isc.asio.InvalidUsage;
import com.google.common.base.Converter;
import com.google.common.base.Objects;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.BadCredentialsException;

import javax.servlet.http.HttpServletRequest;

/**
 * Extract delegated credentials from the {@code 'Delegate-Authorization'} http header. Expects the
 * credentials to be given as defined in the {@code Basic Authentication} scheme.
 */
public final class DelegationDetailsSource
    implements AuthenticationDetailsSource<HttpServletRequest, DelegatedCredentialsDetails> {

  /**
   * Create a source, which reads the delegated credentials request header with the given name.
   */
  public static DelegationDetailsSource usingHeader(final String headerName) {
    return new DelegationDetailsSource(headerName, BasicAuthConverter.fromString());
  }

  private final Converter<String, Identity> parser;
  private final String delegatedCredentialsHeader;

  private DelegationDetailsSource(final String delegateAuthorizationHeader, final Converter<String, Identity> parser) {
    this.parser = parser;
    delegatedCredentialsHeader = delegateAuthorizationHeader;
  }

  public DelegatedCredentialsDetails buildDetails(final HttpServletRequest request) {
    final Identity credentials = findDelegatedCredentials(request);
    return new DelegatedCredentialsDetails(credentials);
  }

  private Identity findDelegatedCredentials(final HttpServletRequest request) {
    try {
      final String header = request.getHeader(delegatedCredentialsHeader);
      return Objects.firstNonNull(parser.convert(header), Identity.undefined());
    } catch (final InvalidUsage malformedCredentials) {
      throw new BadCredentialsException("illegal delegated credentials in '" + delegatedCredentialsHeader + "' header", malformedCredentials);
    }
  }
}


text:
constexpr const char *VignetteEffect::Name;

const char *VignetteEffect::getName() const { return Name; }
const char *VignetteEffect::getDescriptiveName() const {
  return "Vignette";
}
const char *VignetteEffect::getDescription() const {
  return "Applies a vignette effect to the overall particle image";
}

void VignetteEffect::loadConfig(const json &json) {
  loadEaseInOutConfig(json);
}
void VignetteEffect::saveConfig(json &json) const {
  saveEaseInOutConfig(json);
}

void VignetteEffect::randomizeConfig(std::default_random_engine &random) {
}

void VignetteEffect::registerEffect(EffectRegistrationData &data) const {
  data.vertexShader.appendMainBody(
      TEMPLATE(R"glsl(
  {
    vec2 screenCoord = texcoord * 2.0 - 1.0;

    float a = atan(screenCoord.y, screenCoord.x);

    // https://en.wikipedia.org/wiki/Squircle
    // https://thatsmaths.com/2016/07/14/squircles/  (Eq. 3)
    float s = sin(2 * a);
    float x = length(screenCoord) - s * s * mix(1.0, 0.1, ${factor});

    const float blendStart = 0.8;
    const float blendEnd = 1.0;

    // linear ramp from blend start to blend end
    float l = clamp((x - blendStart) * (1.0 / (blendEnd - blendStart)), 0.0, 1.0);

    visibility *= mix(1.0, 1.0 - l*l, ${factor});
  }
  )glsl")
          .compile({
              UNIFORM(data.uniforms, "factor", GLSLType::Float,
                      [this](const RenderProps &props) {
                        auto result = getEase(props);
                        return UniformValue(result);
                      }),
          })
          .c_str());
}

void VignetteEffect::registerEffectSound(EffectSoundRegistrationData &data) const {
}


text:
DEFINE_LOG_SENDER(World);

using namespace ve;

World::World(Engine* engine) :
	m_engine(engine)
{

}

bool World::init()
{
	return allocateStorageForCoreComponentTypes();
}

void World::flushAttachings()
{
	for(auto& componentAttacher : m_componentAttachers)
	{
		componentAttacher();
	}

	m_componentAttachers.clear();
}

void World::flushDetachings()
{
	for(auto& componentDetacher : m_componentDetachers)
	{
		componentDetacher();
	}

	m_componentDetachers.clear();
}

std::shared_ptr<EntityFunctionality> World::createEntityFunctionality()
{
	EntityId entityId;
	std::shared_ptr<EntityFunctionality> entityFunctionality;

	if(m_availableEntityIds.empty())
	{
		entityId.m_index = m_validEntitySerials.size();
		entityId.m_serial = EntityId::invalidSerial + 1;

		m_validEntitySerials.push_back(entityId.m_serial);
		m_entityFunctionalities.push_back(entityFunctionality);
	}
	else
	{
		entityId = m_availableEntityIds.back();
		m_availableEntityIds.pop_back();
	}

	m_entityComponentDatabase.initComponentsIndexMapping(entityId.m_index);

	entityFunctionality = std::make_shared<EntityFunctionality>(entityId, this);
	m_entityFunctionalities[entityId.m_index] = entityFunctionality;
	return entityFunctionality;
}

void World::removeEntityFunctionality(const EntityId& entityId)
{
	if(!isEntityIdValid(entityId))
	{
		ENGINE_LOG(World, LogLevel::NOTE_WARNING,
		           "cannot remove an EntityFunctionality with an invalid ID");
		return;
	}

	// generate a new EntityId and store it for later use
	EntityId newEntityId(entityId);
	newEntityId.m_serial++;
	m_availableEntityIds.push_back(newEntityId);
	m_validEntitySerials[newEntityId.m_index] = newEntityId.m_serial;

	m_entityFunctionalities[entityId.m_index] = nullptr;
}

std::shared_ptr<EntityFunctionality> World::getEntityFunctionality(const EntityId& entityId) const
{
	if(!isEntityIdValid(entityId))
	{
		ENGINE_LOG(World, LogLevel::NOTE_WARNING,
		           "cannot get an EntityFunctionality with an invalid ID");
		return nullptr;
	}

	return m_entityFunctionalities[entityId.m_index];
}

bool World::isEntityIdValid(const EntityId& entityId) const
{
	if(entityId.m_index < m_validEntitySerials.size())
	{
		if(m_validEntitySerials[entityId.m_index] != entityId.m_serial)
		{
			ENGINE_LOG(World, LogLevel::NOTE_WARNING,
			           "invalid entity detected - entity serial is invalid");
			return false;
		}
	}
	else
	{
		ENGINE_LOG(World, LogLevel::NOTE_WARNING,
		           "invalid entity detected - entity index is invalid");
		return false;
	}

	return true;
}

EntityId::IndexType World::getEntityIndex(const Entity& entity) const
{
	return entity->getEntityId().m_index;
}

EntityComponentDatabase* World::getEntityComponentDatabase()
{
	return &m_entityComponentDatabase;
}

bool World::allocateStorageForCoreComponentTypes()
{
	bool isAllocationSuccess = false;

	isAllocationSuccess |= m_entityComponentDatabase.allocateComponentStorage<CCamera>();
	isAllocationSuccess |= m_entityComponentDatabase.allocateComponentStorage<CStaticModelGroup>();
	isAllocationSuccess |= m_entityComponentDatabase.allocateComponentStorage<CTransform>();
	isAllocationSuccess |= m_entityComponentDatabase.allocateComponentStorage<CGameLogicGroup>();
	isAllocationSuccess |= m_entityComponentDatabase.allocateComponentStorage<CTestComponent>();

	return isAllocationSuccess;
}


text:
<?php

namespace SocialiteProviders\Procore;

use GuzzleHttp\RequestOptions;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

class Provider extends AbstractProvider
{
    public const IDENTIFIER = 'PROCORE';

    /**
     * {@inheritdoc}
     */
    protected $scopeSeparator = ' ';

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase(
            'https://login.procore.com/oauth/authorize',
            $state
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://login.procore.com/oauth/token';
    }

    public function getRefreshTokenResponse($refreshToken)
    {
        $response = $this->getHttpClient()->post($this->getTokenUrl(), [
            RequestOptions::HEADERS     => ['Accept' => 'application/json'],
            RequestOptions::FORM_PARAMS => $this->getRefreshTokenFields($refreshToken),
        ]);

        return json_decode((string) $response->getBody(), true);
    }

    public function getRefreshTokenFields($refreshToken)
    {
        return [
            'client_id'     => $this->clientId,
            'client_secret' => $this->clientSecret,
            'grant_type'    => 'refresh_token',
            'refresh_token' => $refreshToken,
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get(
            'https://api.procore.com/vapid/me',
            [
                RequestOptions::HEADERS => [
                    'Accept'        => 'application/json',
                    'Authorization' => 'Bearer '.$token,
                ],
            ]
        );

        return json_decode((string) $response->getBody(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user)->map([
            'id'       => $user['id'],
            'name'     => $user['name'],
            'email'    => $user['login'],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenFields($code)
    {
        return array_merge(parent::getTokenFields($code), [
            'grant_type' => 'authorization_code',
        ]);
    }
}


text:
.. Dataverse API Documentation master file, created by
   sphinx-quickstart on Wed Aug 28 17:54:16 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

API Guide
=========

**Contents:**

.. toctree::

   intro
   sword
   search
   dataaccess
   native-api
   metrics
   client-libraries
   apps


text:
namespace blink {

CSSInvalidVariableValue* CSSInvalidVariableValue::Create() {
  return CssValuePool().InvalidVariableValue();
}

String CSSInvalidVariableValue::CustomCSSText() const {
  return "";
}

}  // namespace blink


text:
layout: post
title: The Proposal
description:
image:
  feature: row_of_lights.jpg
---

We want to know your thoughts. How does this document 'feel' to you? Does it describe what we are and what we need to be?

-  The latest draft as of June 12 2014.

-  The "Special Character Guidelines" document as it is now, from 2008.

- Click here for a comparison of the two.

###How to provide feedback

If you have any feedback to offer there are three ways we invite you to do that. Please choose the method that feels most comfortble for you

- Discussion in person. Please feel free to approach any of the people listed on the front page of this site to discuss this proposal.
- By sending email to scd@groups.tera.school.nz.
- By joining our online and email discussion group at http://groups.tera.school.nz/groups/scd/


text:
struct destination {
  unsigned id;
  explicit destination(unsigned des_id = 0) : id(des_id) {}
};  // resource

struct connection {
  destination *dest;
};

connection connect(destination *dest) {
  connection new_conn;
  new_conn.dest = dest;
  std::cout << "Setup connection to " << new_conn.dest->id << std::endl;
  return new_conn;
}

void disconnect(connection conn) {
  std::cout << "Stop connection to " << conn.dest->id << std::endl;
  //conn.dest = nullptr;
}

void end_connection(connection *p) {
  disconnect(*p);
}

void f(destination &d) {
  connection c = connect(&d);
  std::shared_ptr<connection> p(&c, end_connection);
  // use connection
  std::cout << "Using connection " << c.dest->id << std::endl;
}

int main() {
  destination d(5);
  f(d);

  return 0;
}


text:
<?php

namespace Genj\FaqBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Class QuestionRepository
 *
 * @package Genj\FaqBundle\Entity
 */
class QuestionRepository extends EntityRepository
{
    /**
     * @param string $categorySlug
     *
     * @return Question|null
     */
    public function retrieveFirstByCategorySlug($categorySlug)
    {
        $query = $this->createQueryBuilder('q')
            ->join('q.category', 'c')
            ->where('c.slug = :categorySlug')
            ->orderBy('q.rank', 'ASC')
            ->setMaxResults(1)
            ->getQuery();

        $query->setParameter('categorySlug', $categorySlug);

        return $query->getOneOrNullResult();
    }
}


text:
Modular JS

AMD & CommonJS modules

Hi, I’m Brian, and I

love Javascript

founded Hovercraft Studios so I could write more JS

have some stuff on github

made a clock, one that explodes, and this purely css analog version

wrote some things about JS and OOCSS

Hi, I’m Brian

My internet career started in 1993, when I helped WVU make a Gopher repository for some documents.

I know what you’re thinking …

Awesome

Gopher is the bees knees!

No

The web

I made my first, personal web page in 1994, and took a job in Wexford, PA as the “computer guy” for a non-profit.

The web

Shortly after that, in 1995, an amazing technology came along that changed the web forever.  It allowed changing parts of a page without reloading the whole thing.

I know what you’re thinking …

Frames

No

It was something much more awesome, something that made the browser programmable.

Ok, ok, now I know what you’re thinking …

Java Applets

No

Javascript

Javascript

and it was awesome because we could do awesome stuff like this:

<a href="javascript:
    alert('All ur link r belong to us'); return false">

Evolution

Later we realized that was bad, and we started to understand the true power of this new technology.  We started doing awesome stuff like this:

<script>
    function globalFunctionValidateDate() {
        // Awesome circa-1996 date validation
        // codez here
        document.forms[0].birthDate ...
    }

    // More global vars and functions here
</script>

Evolution

Later we realized that was bad, and we started to understand the true power of this new technology.  We started doing awesome stuff like this:

<script src="lotsOfGlobals1.js">
<script src="lotsOfGlobals2.js">
<script src="lotsOfGlobals3.js">

Profit!

And we basked in our global name collision and manual dependency management glory

Ajax

Fast-forward to 1999/2000, and along came AJAX, or Ajax, aka Asychronous Javascript And XML, aka “everything awesome we can do on the web”

Ajax

We started creating larger, more complex apps, and saw the need for better organization and architecture.

Evolution

Unfortunately, better meant:

<script src="lotsOfGlobals1.js">
<script src="lotsOfGlobals2.js">
<script src="lotsOfGlobals3.js">
<script src="lotsOfGlobals4.js">
<script src="lotsOfGlobals5.js">
<script src="lotsOfGlobals6.js">
<script src="lotsOfGlobals7.js">
<script src="lotsOfGlobals8.js">
<script src="lotsOfGlobals9.js">
...
...
<script src="OMG-WhyDoesMyPageLoadTimeSuck.js">

Modules

Along came the Module Pattern and all its variants, to help us namespace our code, encapsulate data, and expose more carefully crafted APIs.

Finally!

<script src="Module1.js">
<script src="Module2.js">
<script src="Module3.js">
<script src="Module4.js">
<script src="Module5.js">
<script src="Module6.js">
<script src="Module7.js">
<script src="Module8.js">
<script src="Module9.js">
...
...
<script src="OMG-WhyDoesMyPageLoadTime-STILL-Suck.js">

Modules

The various module patterns solved some key problems, but

They provide a pattern for dependency declaration, but don’t provide any real help with dependency organization or automatic dependency loading

Some frameworks like Dojo and MooTools have their own proprietery module formats that solve the organization and loading problems

But you have to buy into them wholesale to get the advantages

Still had to choose between a built version with 1 <script> or non-built version with lots of <script>

<script>

What’s the problem?

Synchronous loading? … who cares, if you’re doing a JS build (you are, aren’t you?)

<script>

What’s the problem?

But, if you’re doing a build, do you have to build every time you make even the smallest change to your code?

AMD. Because the web already has a build step: F5

— James Burke (@jburke)

HTML5

the new aka “everything awesome on the web”

We want to build even bigger, more interactive applications in the browser.

Node

aka “everything awesome on the server”

Javascript is everywhere, and we want to share the same code in the browser and on the server.

Current project stats

Approx 207 Modules

Approx 110 View modules each of which has its own: HTML template(s), CSS file, i18n Language file, Unit test file

Only 6 Pages

Not including 3rd party: Dojo, curl.js AMD loader, wire.js IOC container, cujo data binding

Current project stats

Using <script> would be impossible

Dependency management would be a nightmare

Could we even figure it out manually?!?

One small dependency change could wreck the app

With 1 <script>, doing a build would kill productivity

With multiple <script>s, pageload time would be well beyond unacceptable

Help

Larger, more complex apps require more carefully crafted, rigorous architecture, patterns, and code organization.

Want

Things we want to keep

Avoid global namespace problems in your own code and with 3rd party code

Promote modular code from the ground up … i.e. make it easy enough to write modular code, so we don’t choose not to just based on friction

Promotes thinking about the API your module will expose by making you return it or decorate module.exports with it

Want

Things we’d like to have

Encapsulation that is automatic and “free”.

Automatic dependency management

Ability to run the exact same code built for production, and non-built for fast development (read: browser reload)

Code that can be shared between servers and clients

AMD & CommonJS

Real modules for Javascript

Three main parts

Module format

Loader

Build tools (aka optimizer)

Module format

AMD uses define()

CommonJS’s “define” is implicit, file contents are the module

AMD

Asynchronous

Module

Definition

AMD

Designed with browser environment in mind

Designed to allow/promote asynchronous loading

Plugins for loading other resource types

James Burke @jburke, Kris Zyp @kriszyp, John Hann @unscriptable

Read the spec

Who’s using it?

Dojo 1.7

MooTools 2

Firebug 1.8

jQuery 1.7 … no, really

define()

define(moduleId, dependencies, definitionFunc);

define()

define(dependencies, definitionFunc);

Using a moduleId can make it harder to relocate your module during refactoring.  Use anonymous modules where possible.

Module format

define(

    ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'],

    function (modA, modB, modC) {

        var myModule = {
			doStuff: function() { ... }
		}

        return myModule;
    }
);

define(

    ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'],

    function (modA, modB, modC) {

        var myModule = {
			doStuff: function() { ... }
		}

        return myModule;
    }
);

define(

    // dependency list
    ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'],

    function (modA, modB, modC) {

        var myModule = {
			doStuff: function() { ... }
		}

        return myModule;
    }
);

define(

    ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'],

    // module definition function
    // deps mapped to function params
    function (modA, modB, modC) {

        // create your module here
        var myModule = {
			doStuff: function() { ... }
		}

        return myModule;
    }
);

define(

    ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'],

    function (modA, modB, modC) {

        var myModule = {
			doStuff: function() { ... }
		}

        // return your module
        return myModule;
    }
);

Using it

<html class="loading">
 <head>
  <script src="curl.js"></script>
  <script>
   curl(['MyApp/MyModule'],
    function(MyModule) {
    // Startup main module, which probably
    // loads and starts up other modules
	var m = new MyModule();
    m.doStuff();
    document.getElementsByTagName('html')
      .className = '';
   });
  </script>
...

Plugins

AMD plugins can load other types of resources, such as images, html templates, css, localized language/strings files, etc.

Plugins

define([
    'renderer',
    'text!modA-template.html',
    'i18n!modA-strings',
    'css!modA'
    ],
    function(renderer, template, strings) {
        function ModAWidget(node) {
            this.node = node;
        }

        ModAWidget.prototype = {
            render: function() {
                renderer.render(template, strings, this.node);
            }
        }

        return ModAWidget;
    }
)

Plugins

define([
    'renderer',
    'text!modA-template.html',
    'i18n!modA-strings',
    'css!modA'
    ],
    function(renderer, template, strings) {
        function ModAWidget(node) {
            this.node = node;
        }

        ModAWidget.prototype = {
            render: function() {
                renderer.render(template, strings, this.node);
            }
        }

        return ModAWidget;
    }
)

Plugins

Can do even more powerful things

wire! plugin - wire.js IOC container integration

has! has.js feature detection and conditional module loading

cs! plugin that loads and compiles Coffeescript

CommonJS

A community driven set of proposed best practices, specs, and APIs, with a goal of compatibility across JS environments.

One of those specs is the CommonJS Module Spec

Plenty more info at the CommonJS wiki

Module format

No define()

require, module, and exports “free variables”, i.e. they're implicit

Node !== CommonJS

exports === this

exports === module.exports

extra module.exports property is not CommonJS

Using exports is more ES harmony-like

Module format

var modA, modB, modC;

modA = require('pkgA/modA');
modB = require('pkgA/modB');
modC = require('pkgZ/modC');

function doStuff() { ... }

exports.doStuff = doStuff;

// No define()

var modA, modB, modC;

modA = require('pkgA/modA');
modB = require('pkgA/modB');
modC = require('pkgZ/modC');

function doStuff() { ... }

exports.doStuff = doStuff;

// No define()

// Load dependencies using require
var modA, modB, modC;

modA = require('pkgA/modA');
modB = require('pkgA/modB');
modC = require('pkgZ/modC');

function doStuff() { ... }

exports.doStuff = doStuff;

// No define()

// Load dependencies using require
var modA, modB, modC;

modA = require('pkgA/modA');
modB = require('pkgA/modB');
modC = require('pkgZ/modC');

function doStuff() { ... }

exports.doStuff = doStuff;

// Load dependencies using require
var modA, modB, modC;

modA = require('pkgA/modA');
modB = require('pkgA/modB');
modC = require('pkgZ/modC');

function doStuff() { ... }

// OK in Node
// NOT OK in CommonJS (yet)
module.exports = doStuff;

Examples

define(
/* 'MyLib/dateFormat', */ // AMD
['MyLib/stringFormat'],
function (stringFormat) {

	return {
		short: function(date) {
			var y, m, d;
			// ...
			return stringFormat.format("%d/%d/%d",
				y, m, d);
		},
		long: function(date) {
			var y, m, d, h, mi, s;
			// ...
			return stringFormat.format("%d/%d/%d %d:%d:%d",
				y, m, d, h, mi, s);
		}
	};
});

Using the module

define(
/* 'MyApp/DateView', */
['MyLib/dateFormat'],
function(dateFormat) {
	function DateView(domNode) {
		this.dateNode = domNode
	}

	DateView.prototype = {
		setDate: function(date) {
			this.date = date;
		},
		renderDate: function() {
			this.dateNode.innerHTML =
				dateFormat.short(this.date);
		}
	};

	return DateView;
});

// CommonJS

var stringFormat = require('MyLib/stringFormat');

exports.short = function(date) {
	var y, m, d;
	// ...
	return stringFormat.format("%d/%d/%d",
		y, m, d);
};

exports.long = function(date) {
	var y, m, d, h, mi, s;
	// ...
	return stringFormat.format("%d/%d/%d %d:%d:%d",
		y, m, d, h, mi, s);
};

// CommonJS

var stringFormat = require('MyLib/stringFormat');

exports.short = function(date) {
	var y, m, d;
	// ...
	return stringFormat.format("%d/%d/%d",
		y, m, d);
};

exports.long = function(date) {
	var y, m, d, h, mi, s;
	// ...
	return stringFormat.format("%d/%d/%d %d:%d:%d",
		y, m, d, h, mi, s);
};

Using the module

var dateFormat = require('MyLib/dateFormat');

var date = ...

console.log(dateFormat.short(date));

Using the module

var shortDate = require('MyLib/dateFormat').short;

var date = ...

console.log(shortDate(date));

WTF

I know what you’re thinking

Which one?!?

Why are there 2 (3 if you include the Node variant) module formats, and how am I supposed to know which one to pick?!?!!1

Differences

Scope

Distance

John Hann — AMD versus CJS. What’s the best format?

Scope

Browser environments allow direct access to global namespace from anywhere, and AMD can’t prevent that.

CJS server environments don’t have browser baggage, so were designed to prevent global access.

John Hann — AMD versus CJS. What’s the best format?

Distance

Browsers have to load resources from the network, which is unpredictable and unreliable.  Synchronous, blocking operations don’t make sense here.

Servers can load from local disk in effectively-zero time, so synchronous is ok … but Node is an async badass, so ...

Hey Node, why u no load modules async?!?

Probably: simpler programming model

But still, grrrr

Relax

These module formats are a good thing

AMD(’s) greatest benefit isn't being able to load scripts on-demand, as some people may think, the greatest benefit is the increase of the code organization/modularity and also the reduced need for globals/namespacing.

Miller Medeiros — Amd Is Better for the Web Than Commonjs Modules

Relax

AMD and CommonJS are a clear upgrade path to ES.Next Harmony modules.

Which one?

write modules that could execute in a server environment in CJS format

write modules that could benefit from AMD's browser-friendly features in AMD format

Consider AMD plugins as well, they can be a huge advantage

John Hann — AMD versus CJS. What’s the best format?

Loader

You need a Loader if you use AMD modules, or CommonJS modules in an environment that doesn't have an integrated loader

AMD Loaders

RequireJS

curl.js

bdLoad

lsjs

Node

RequireJS can be used to load AMD in Node

AMD Integrated Loaders

dojo 1.7

MooTools 2 (see 2.0wip branch as of this writing)

CommonJS Loaders

RequireJS

curl.js

PINF

CommonJS Integrated Loaders

Node

Narwhal

Persevere

RingoJS

SproutCore 1.1

JFDI

Read a bit more

Pick a module format

write modules that could execute in a server environment in CJS format

write modules that could benefit from AMD's browser-friendly features (and plugins) in AMD format

Pick a loader

Go

Read moar nao

Tagneto: On inventing JS module formats and script loaders

Using AMD loaders to write and manage modular javascript

AMD Module Patterns

AMD versus CJS. What’s the best format? | Unscriptable.com

AMD is better for the web than CommonJS modules |  Blog | Miller Medeiros

Read moar nao

AMD

AMD Spec on github

RequireJS Google Group

AMD Implementors Google Group

CommonJS

CommonJS

CommonJS Modules wiki

CommonJS Google Group

HOVERCRAFT

brian@hovercraftstudios.com

@briancavalier

briancavalier@github


text:
{% extends "wagtailadmin/base.html" %}
{% load i18n wagtailadmin_tags %}
{% block titletag %}{% blocktrans trimmed with form_title=form_page.title|capfirst %}Submissions of {{ form_title }}{% endblocktrans %}{% endblock %}
{% block extra_js %}
    {{ block.super }}

{% endblock %}
{% block content %}
    {% fragment as form_actions %}

                {% icon name="download" wrapped=1 %}{% trans 'Download XLSX' %}

{% icon name="arrow-down" %}

                        {% icon name="download" wrapped=1 %}{% trans 'Download CSV' %}

    {% endfragment %}

    {% include "wagtailadmin/shared/header.html" with classname="w-header--no-border" title=page_title subtitle=form_page.title|capfirst icon="form" merged=1 extra_actions=form_actions %}

            {% if submissions %}
                <form action="{% url 'wagtailforms:delete_submissions' form_page.id %}" method="get">
                    {% include "wagtailforms/list_submissions.html" %}
                    {% include "wagtailadmin/shared/pagination_nav.html" with items=page_obj %}
                </form>
            {% else %}

{% blocktrans trimmed with title=form_page.title %}There have been no submissions of the '{{ title }}' form.{% endblocktrans %}

            {% endif %}

{% trans 'Filter' %}

            <form action="" method="get" novalidate>
                <button class="button button-longrunning" type="submit">{% icon name="spinner" %}{% trans 'Apply filters' %}</button>
                {% for field in select_date_form %}
                    {% include "wagtailadmin/shared/field_as_li.html" with field=field %}
                {% endfor %}
            </form>

{% endblock %}


text:
import collections

from supriya import CalculationRate
from supriya.ugens.PureUGen import PureUGen

class AllpassN(PureUGen):
    """
    A non-interpolating allpass delay line unit generator.

    ::

        >>> source = supriya.ugens.In.ar(bus=0)
        >>> allpass_n = supriya.ugens.AllpassN.ar(source=source)
        >>> allpass_n
        AllpassN.ar()

    """

    ### CLASS VARIABLES ###

    __documentation_section__ = "Delay UGens"

    _ordered_input_names = collections.OrderedDict(
        [
            ("source", None),
            ("maximum_delay_time", 0.2),
            ("delay_time", 0.2),
            ("decay_time", 1.0),
        ]
    )

    _valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)


text:
namespace nekit {
namespace utils {

SystemResolver::SystemResolver(Runloop* runloop, size_t thread_count)
    : runloop_{runloop}, thread_count_{thread_count} {
  work_guard_ = std::make_unique<
      boost::asio::executor_work_guard<boost::asio::io_context::executor_type>>(
      boost::asio::make_work_guard(*resolve_runloop_.BoostIoContext()));

  for (size_t i = 0; i < thread_count_; i++) {
    thread_group_.create_thread(boost::bind(&boost::asio::io_context::run,
                                            resolve_runloop_.BoostIoContext()));
  }
}

Cancelable SystemResolver::Resolve(std::string domain,
                                   AddressPreference preference,
                                   EventHandler handler) {
  // Preference is ignored. Let the OS do the choice as of now.
  (void)preference;

  NETRACE << "Start resolving " << domain << ".";

  Cancelable cancelable{};

  resolve_runloop_.Post([this, domain, handler, cancelable,
                         lifetime{lifetime_}]() mutable {
    // Note it will be guaranteed that the `runloop_` will never be
    // released before all the instances implementing `AsyncInterface`
    // which will return that `runloop_` are released. This resolver will
    // never be released before `runloop_` is released. In the destructor
    // this thread is guaranteed to exit before resolver is released, so
    // there is no need to worry about any thread issues here. Resolver and
    // `runloop_` will exist when this thread is running.

    if (cancelable.canceled() || lifetime.canceled()) {
      return;
    }

    auto resolver =
        boost::asio::ip::tcp::resolver(*resolve_runloop_.BoostIoContext());

    NEDEBUG << "Trying to resolve " << domain << ".";

    boost::system::error_code ec;
    auto result = resolver.resolve(domain, "", ec);

    if (ec) {
      auto error = BoostErrorCategory::FromBoostError(ec);
      NEERROR << "Failed to resolve " << domain << " due to " << error << ".";

      runloop_->Post([handler, error{std::move(error)}, cancelable,
                      life_time{lifetime_}]() mutable {
        if (cancelable.canceled() || life_time.canceled()) {
          return;
        }

        handler(utils::MakeErrorResult(std::move(error)));
      });
      return;
    }

    auto addresses = std::make_shared<std::vector<boost::asio::ip::address>>();

    for (auto iter = result.begin(); iter != result.end(); iter++) {
      addresses->emplace_back(iter->endpoint().address());
    }

    NEINFO << "Successfully resolved domain " << domain << ".";

    runloop_->Post([handler, addresses, cancelable, life_time{lifetime_}]() {
      if (cancelable.canceled() || life_time.canceled()) {
        return;
      }

      handler(addresses);
    });
  });

  return cancelable;
}

void SystemResolver::Stop() {
  work_guard_.reset();
  thread_group_.join_all();
}

SystemResolver::~SystemResolver() {
  Stop();
  lifetime_.Cancel();
}

utils::Runloop* SystemResolver::GetRunloop() { return runloop_; }
}  // namespace utils
}  // namespace nekit


text:
package com.ericsson.otp.erlang;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *

 * Represents an OTP node.
 *

 *
 *

 * About nodenames: Erlang nodenames consist of two components, an alivename and
 * a hostname separated by '@'. Additionally, there are two nodename formats:
 * short and long. Short names are of the form "alive@hostname", while long
 * names are of the form "alive@host.fully.qualified.domainname". Erlang has
 * special requirements regarding the use of the short and long formats, in
 * particular they cannot be mixed freely in a network of communicating nodes,
 * however Jinterface makes no distinction. See the Erlang documentation for
 * more information about nodenames.
 *

 *
 *

 * The constructors for the AbstractNode classes will create names exactly as
 * you provide them as long as the name contains '@'. If the string you provide
 * contains no '@', it will be treated as an alivename and the name of the local
 * host will be appended, resulting in a shortname. Nodenames longer than 255
 * characters will be truncated without warning.
 *

 *
 *

 * Upon initialization, this class attempts to read the file .erlang.cookie in
 * the user's home directory, and uses the trimmed first line of the file as the
 * default cookie by those constructors lacking a cookie argument. If for any
 * reason the file cannot be found or read, the default cookie will be set to
 * the empty string (""). The location of a user's home directory is determined
 * using the system property "user.home", which may not be automatically set on
 * all platforms.
 *

 *
 *

 * Instances of this class cannot be created directly, use one of the subclasses
 * instead.
 *

 */
public class AbstractNode implements OtpTransportFactory {
    static String localHost = null;
    String node;
    String host;
    String alive;
    String cookie;
    static String defaultCookie = null;
    final OtpTransportFactory transportFactory;

    // Node types
    static final int NTYPE_R6 = 110; // 'n' post-r5, all nodes
    static final int NTYPE_R4_ERLANG = 109; // 'm' Only for source compatibility
    static final int NTYPE_R4_HIDDEN = 104; // 'h' Only for source compatibility

    // Node capability flags
    static final int dFlagPublished = 1;
    static final int dFlagAtomCache = 2;
    static final int dFlagExtendedReferences = 4;
    static final int dFlagDistMonitor = 8;
    static final int dFlagFunTags = 0x10;
    static final int dFlagDistMonitorName = 0x20; // NOT USED
    static final int dFlagHiddenAtomCache = 0x40; // NOT SUPPORTED
    static final int dflagNewFunTags = 0x80;
    static final int dFlagExtendedPidsPorts = 0x100;
    static final int dFlagExportPtrTag = 0x200; // NOT SUPPORTED
    static final int dFlagBitBinaries = 0x400;
    static final int dFlagNewFloats = 0x800;
    static final int dFlagUnicodeIo = 0x1000;
    static final int dFlagUtf8Atoms = 0x10000;
    static final int dFlagMapTag = 0x20000;

    int ntype = NTYPE_R6;
    int proto = 0; // tcp/ip
    int distHigh = 5; // Cannot talk to nodes before R6
    int distLow = 5; // Cannot talk to nodes before R6
    int creation = 0;
    int flags = dFlagExtendedReferences | dFlagExtendedPidsPorts
            | dFlagBitBinaries | dFlagNewFloats | dFlagFunTags
            | dflagNewFunTags | dFlagUtf8Atoms | dFlagMapTag;

    /* initialize hostname and default cookie */
    static {
        try {
            localHost = InetAddress.getLocalHost().getHostName();
            /*
             * Make sure it's a short name, i.e. strip of everything after first
             * '.'
             */
            final int dot = localHost.indexOf(".");
            if (dot != -1) {
                localHost = localHost.substring(0, dot);
            }
        } catch (final UnknownHostException e) {
            localHost = "localhost";
        }

        final String homeDir = getHomeDir();
        final String dotCookieFilename = homeDir + File.separator
                + ".erlang.cookie";
        BufferedReader br = null;

        try {
            final File dotCookieFile = new File(dotCookieFilename);

            br = new BufferedReader(new FileReader(dotCookieFile));
            final String line = br.readLine();
            if (line == null) {
                defaultCookie = "";
            } else {
                defaultCookie = line.trim();
            }
        } catch (final IOException e) {
            defaultCookie = "";
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (final IOException e) {
            }
        }
    }

    protected AbstractNode(final OtpTransportFactory transportFactory) {
        this.transportFactory = transportFactory;
    }

    /**
     * Create a node with the given name and default cookie and transport
     * factory.
     */
    protected AbstractNode(final String node) {
        this(node, defaultCookie, new OtpSocketTransportFactory());
    }

    /**
     * Create a node with the given name, transport factory and the default
     * cookie.
     */
    protected AbstractNode(final String node,
            final OtpTransportFactory transportFactory) {
        this(node, defaultCookie, transportFactory);
    }

    /**
     * Create a node with the given name, cookie and default transport factory.
     */
    protected AbstractNode(final String name, final String cookie) {
        this(name, cookie, new OtpSocketTransportFactory());
    }

    /**
     * Create a node with the given name, cookie and transport factory.
     */
    protected AbstractNode(final String name, final String cookie,
            final OtpTransportFactory transportFactory) {
        this.cookie = cookie;
        this.transportFactory = transportFactory;

        final int i = name.indexOf('@', 0);
        if (i < 0) {
            alive = name;
            host = localHost;
        } else {
            alive = name.substring(0, i);
            host = name.substring(i + 1, name.length());
        }

        if (alive.length() > 0xff) {
            alive = alive.substring(0, 0xff);
        }

        node = alive + "@" + host;
    }

    /**
     * Get the name of this node.
     *
     * @return the name of the node represented by this object.
     */
    public String node() {
        return node;
    }

    /**
     * Get the hostname part of the nodename. Nodenames are composed of two
     * parts, an alivename and a hostname, separated by '@'. This method returns
     * the part of the nodename following the '@'.
     *
     * @return the hostname component of the nodename.
     */
    public String host() {
        return host;
    }

    /**
     * Get the alivename part of the hostname. Nodenames are composed of two
     * parts, an alivename and a hostname, separated by '@'. This method returns
     * the part of the nodename preceding the '@'.
     *
     * @return the alivename component of the nodename.
     */
    public String alive() {
        return alive;
    }

    /**
     * Get the authorization cookie used by this node.
     *
     * @return the authorization cookie used by this node.
     */
    public String cookie() {
        return cookie;
    }

    // package scope
    int type() {
        return ntype;
    }

    // package scope
    int distHigh() {
        return distHigh;
    }

    // package scope
    int distLow() {
        return distLow;
    }

    // package scope: useless information?
    int proto() {
        return proto;
    }

    // package scope
    int creation() {
        return creation;
    }

    /**
     * Set the authorization cookie used by this node.
     *
     * @return the previous authorization cookie used by this node.
     */
    public String setCookie(final String cookie) {
        final String prev = this.cookie;
        this.cookie = cookie;
        return prev;
    }

    @Override
    public String toString() {
        return node();
    }

    private static String getHomeDir() {
        final String home = System.getProperty("user.home");
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            final String drive = System.getenv("HOMEDRIVE");
            final String path = System.getenv("HOMEPATH");
            return drive != null && path != null ? drive + path : home;
        }
        return home;
    }

    public OtpTransport createTransport(final String addr, final int port)
            throws IOException {
        return transportFactory.createTransport(addr, port);
    }

    public OtpTransport createTransport(final InetAddress addr, final int port)
            throws IOException {
        return transportFactory.createTransport(addr, port);
    }

    public OtpServerTransport createServerTransport(final int port)
            throws IOException {
        return transportFactory.createServerTransport(port);
    }
}


text:
class FeedbackMessage < ActiveRecord::Base
  belongs_to :user
  has_many :comments, as: :commentable, dependent: :destroy

  validates_presence_of :user_id
  validates_presence_of :message

  before_save :set_defaults
  after_create :send_email

  private

  def set_defaults
    self.details ||= {}
  end

  def send_email
    UserMailer.feedback_email(self).deliver!
  end
end


text:
from __future__ import unicode_literals

import os

from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
from django.utils._os import upath
from django.utils.encoding import force_text
from django.utils.translation import activate, get_language, trans_real

from .test_extraction import ExtractorTests

SAMPLEPROJECT_DIR = os.path.join(os.path.dirname(os.path.abspath(upath(__file__))), 'sampleproject')
SAMPLEPROJECT_LOCALE = os.path.join(SAMPLEPROJECT_DIR, 'locale')

@override_settings(LOCALE_PATHS=[SAMPLEPROJECT_LOCALE])
class FrenchTestCase(SimpleTestCase):
    """Tests using the French translations of the sampleproject."""

    PO_FILE = os.path.join(SAMPLEPROJECT_LOCALE, 'fr', 'LC_MESSAGES', 'django.po')

    def setUp(self):
        self._language = get_language()
        self._translations = trans_real._translations
        activate('fr')

    def tearDown(self):
        trans_real._translations = self._translations
        activate(self._language)

class ExtractingStringsWithPercentSigns(FrenchTestCase, ExtractorTests):
    """
    Tests the extracted string found in the gettext catalog.

    Ensures that percent signs are python formatted.

    These tests should all have an analogous translation tests below, ensuring
    the python formatting does not persist through to a rendered template.
    """

    def setUp(self):
        super(ExtractingStringsWithPercentSigns, self).setUp()
        with open(self.PO_FILE, 'r') as fp:
            self.po_contents = force_text(fp.read())

    def test_trans_tag_with_percent_symbol_at_the_end(self):
        self.assertMsgId('Literal with a percent symbol at the end %%', self.po_contents)

    def test_trans_tag_with_percent_symbol_in_the_middle(self):
        self.assertMsgId('Literal with a percent %% symbol in the middle', self.po_contents)
        self.assertMsgId('It is 100%%', self.po_contents)

    def test_trans_tag_with_string_that_look_like_fmt_spec(self):
        self.assertMsgId('Looks like a str fmt spec %%s but should not be interpreted as such', self.po_contents)
        self.assertMsgId('Looks like a str fmt spec %% o but should not be interpreted as such', self.po_contents)

    def test_adds_python_format_to_all_percent_signs(self):
        self.assertMsgId('1 percent sign %%, 2 percent signs %%%%, 3 percent signs %%%%%%', self.po_contents)
        self.assertMsgId('%(name)s says: 1 percent sign %%, 2 percent signs %%%%', self.po_contents)

class RenderingTemplatesWithPercentSigns(FrenchTestCase):
    """
    Test rendering of templates that use percent signs.

    Ensures both trans and blocktrans tags behave consistently.

    Refs #11240, #11966, #24257
    """

    def test_translates_with_a_percent_symbol_at_the_end(self):
        expected = 'Littérale avec un symbole de pour cent à la fin %'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent symbol at the end %" %}')
        self.assertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent symbol at '
            'the end %{% endblocktrans %}'
        )
        self.assertEqual(block_tpl.render(Context({})), expected)

    def test_translates_with_percent_symbol_in_the_middle(self):
        expected = 'Pour cent littérale % avec un symbole au milieu'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent % symbol in the middle" %}')
        self.assertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent % symbol '
            'in the middle{% endblocktrans %}'
        )
        self.assertEqual(block_tpl.render(Context({})), expected)

    def test_translates_with_percent_symbol_using_context(self):
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" %}')
        self.assertEqual(trans_tpl.render(Context({})), 'Il est de 100%')
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" context "female" %}')
        self.assertEqual(trans_tpl.render(Context({})), 'Elle est de 100%')

        block_tpl = Template('{% load i18n %}{% blocktrans %}It is 100%{% endblocktrans %}')
        self.assertEqual(block_tpl.render(Context({})), 'Il est de 100%')
        block_tpl = Template('{% load i18n %}{% blocktrans context "female" %}It is 100%{% endblocktrans %}')
        self.assertEqual(block_tpl.render(Context({})), 'Elle est de 100%')

    def test_translates_with_string_that_look_like_fmt_spec_with_trans(self):
        # tests "%s"
        expected = ('On dirait un spec str fmt %s mais ne devrait pas être interprété comme plus disponible')
        trans_tpl = Template(
            '{% load i18n %}{% trans "Looks like a str fmt spec %s but '
            'should not be interpreted as such" %}'
        )
        self.assertEqual(trans_tpl.render(Context({})), expected)
        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Looks like a str fmt spec %s but '
            'should not be interpreted as such{% endblocktrans %}'
        )
        self.assertEqual(block_tpl.render(Context({})), expected)

        # tests "% o"
        expected = ('On dirait un spec str fmt % o mais ne devrait pas être interprété comme plus disponible')
        trans_tpl = Template(
            '{% load i18n %}{% trans "Looks like a str fmt spec % o but should not be '
            'interpreted as such" %}'
        )
        self.assertEqual(trans_tpl.render(Context({})), expected)
        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Looks like a str fmt spec % o but should not be '
            'interpreted as such{% endblocktrans %}'
        )
        self.assertEqual(block_tpl.render(Context({})), expected)

    def test_translates_multiple_percent_signs(self):
        expected = ('1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage %%%')

        trans_tpl = Template(
            '{% load i18n %}{% trans "1 percent sign %, 2 percent signs %%, '
            '3 percent signs %%%" %}'
        )
        self.assertEqual(trans_tpl.render(Context({})), expected)
        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}1 percent sign %, 2 percent signs '
            '%%, 3 percent signs %%%{% endblocktrans %}'
        )
        self.assertEqual(block_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}{{name}} says: 1 percent sign %, '
            '2 percent signs %%{% endblocktrans %}'
        )
        self.assertEqual(
            block_tpl.render(Context({"name": "Django"})),
            'Django dit: 1 pour cent signe %, deux signes de pourcentage %%'
        )


text:
package org.chromium.chrome.browser.omnibox;

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.graphics.Rect;
import android.view.View;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLooper;

import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.chrome.browser.WindowDelegate;

import java.util.concurrent.atomic.AtomicInteger;

@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class KeyboardHideHelperUnitTest {
    @Mock
    private Runnable mKeyboardHiddenCallback;
    @Mock
    private View mRootView;
    @Mock
    private WindowDelegate mWindowDelegate;

    @Spy
    private View mView;

    private KeyboardHideHelper mKeyboardHideHelper;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        mView = spy(new View(RuntimeEnvironment.application));
        mKeyboardHideHelper = new KeyboardHideHelper(mView, mKeyboardHiddenCallback);
    }

    @Test
    public void testHideNotifiedOnSizeDecrease_WithoutWindowDelegate() {
        doReturn(mRootView).when(mView).getRootView();
        doReturn(300).when(mRootView).getHeight();
        mKeyboardHideHelper.monitorForKeyboardHidden();
        Assert.assertTrue(mKeyboardHideHelper.isMonitoringForLayoutChanges());

        doReturn(500).when(mRootView).getHeight();
        mKeyboardHideHelper.onGlobalLayout();

        verify(mKeyboardHiddenCallback, times(1)).run();
        Assert.assertFalse(mKeyboardHideHelper.isMonitoringForLayoutChanges());
    }

    @Test
    public void testHideNotifiedOnSizeDecrease_WithWindowDelegate() {
        mKeyboardHideHelper.setWindowDelegate(mWindowDelegate);
        final AtomicInteger height = new AtomicInteger(300);
        Answer<Void> windowVisibleDisplayFrameAnswer = new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) {
                ((Rect) invocation.getArgument(0)).set(0, 0, 100, height.get());
                return null;
            }
        };
        Mockito.doAnswer(windowVisibleDisplayFrameAnswer)
                .when(mWindowDelegate)
                .getWindowVisibleDisplayFrame(Mockito.any(Rect.class));
        doReturn(500).when(mWindowDelegate).getDecorViewHeight();

        mKeyboardHideHelper.monitorForKeyboardHidden();
        Assert.assertTrue(mKeyboardHideHelper.isMonitoringForLayoutChanges());

        height.set(500);
        mKeyboardHideHelper.onGlobalLayout();

        verify(mKeyboardHiddenCallback, times(1)).run();
        Assert.assertFalse(mKeyboardHideHelper.isMonitoringForLayoutChanges());
    }

    @Test
    public void testMonitorTimeElapsed() {
        mKeyboardHideHelper.monitorForKeyboardHidden();
        Assert.assertTrue(mKeyboardHideHelper.isMonitoringForLayoutChanges());
        ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
        Assert.assertFalse(mKeyboardHideHelper.isMonitoringForLayoutChanges());
    }
}


text:
package cn.gov.jscd.experts.dao;

public interface MailService {

}


text:
\begin{tikzpicture}[node distance = 1cm, auto, align=center]
% Узлы
\node [input]                                               (init)              {Начало итерации};
\node [block, below of=init]                                (TLEReader)         {TLEReader};
\node [block, below of=TLEReader]                           (AstroUtils)        {AstroUtils};
\node [block, below of=AstroUtils]                          (OrbitCalculator)   {OrbitCalculator};
\node [block, right of=TLEReader, node distance = 6cm]      (NeQuick)           {NeQuick};
\node [block, right of=AstroUtils, node distance = 6cm]     (RadarStation)      {RadarStation};
\node [block, right of=OrbitCalculator, node distance = 6cm](out)               {Выход};
\node [input, below of=out, node distance=2.5cm]              (end)               {Конец итерации};

% Рёбра
\path [line, dotted] (init)         -- node {} (TLEReader);
\path [line] (TLEReader)            -- node {} (AstroUtils);
\path [line] (AstroUtils)           -- node {} (OrbitCalculator);
\draw [line] (OrbitCalculator.east) -- ++(0.5,0)
                                    -- ++(0,6)
                                    -- ++(0,0) --
node  {} node {} (NeQuick.west);
\path [line] (NeQuick)              -- node {} (RadarStation);
\path [line] (RadarStation)         -- node {} (out);
\path [line, dotted] (out)          -- node {} (end);

%\path [line] (view) -- node {} (read);
\end{tikzpicture}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Enumeratio Critica Lichenum Europaeorum quos et Nova Methodo Digerit. Accedunt Tabulae Decem, quibus Cuncta Lichenum Europaeorum Genera et Subgenera in Lapidem Delineata et per Partes Colorata Illustrantur 207 (1850)

#### Original name
Segestria umbonata Schaer.

### Remarks
null


text:
namespace PARSER
{

    /// The class provides means to create XML real signal objects.

    /// The XML real signal creator class.
    class XmlFSignalCreator : public XmlSignalCreator
    {
        public:

            /// The XML real signal creator constructor.
            ///
            /// @param rRegEx The regular expression matching the log line.
            /// @param rTimestamp The expression to create the timestamp of the signal.
            /// @param rName The expression to create the name of the signal.
            /// @param rValue The expression to create the value of the signal.
            XmlFSignalCreator(const std::string &rRegEx,
                              const std::string &rTimestamp,
                              const std::string &rName,
                              const std::string &rValue) :
                XmlSignalCreator(rRegEx, rTimestamp, rName, rValue, "")
            {
                m_FloatEvaluator.ParseFloatString(rValue);
            }

            /// @copydoc SignalCreator::Create()
            virtual SIGNAL::Signal *Create(const std::string &rLogLine,
                                           INSTRUMENT::Instrument::LineNumberT lineNumber,
                                           SIGNAL::SourceRegistry::HandleT sourceHandle) const;

    };

}


text:
let mut squares = (0..10).map(|i| i*i);

// What if we have ?Sized
// We need to strictly separate mutable and immutable iterators
assert_eq!(squares.nth(4), Some(16));
assert_eq!(squares.nth(0), Some(25));
assert_eq!(squares.nth(6), None);


text:
"""
Implemetation of eiffel like methods (methods with preconditions and postconditions).

eiffelmethod is a new descriptor that implements eiffel like methods. It accepts a method and
optional pre and post conditions. fI the pre or post conditions are not given it searchs methodName_pre
and methodName_post.
"""

import types

class eiffelmethod(object):
    def __init__(self, method, pre=None, post = None):
        self._method = method
        self._pre = pre
        self._post = post
    def __get__(self, inst, type=None):
    	result = EiffelMethodWraper(inst,self._method,self._pre, self._post)
    	setattr(inst, self._method.__name__,result)
        return result

class EiffelMethodWraper:
    def __init__(self, inst, method, pre, post):
        self._inst = inst
        self._method = method
        if not pre:
        	pre = getattr(inst,method.__name__+"_pre",None)
        	if pre: pre = pre.im_func
        self._pre = pre
        if not post:
        	post = getattr(inst,method.__name__+"_post",None)
        	if post: post = post.im_func
        self._post = post

    def __call__(self, *args, **kargs):
        if self._pre:
        	apply(self._pre,(self._inst,)+args, kargs)
        result = apply(self._method,(self._inst,)+args, kargs)
        if self._post:
			apply(self._post,(self._inst,result)+args, kargs)
        return result

def _test():
    class C:
        def f(self, arg):
            return arg+1
        def f_pre(self, arg):
            assert arg>0
        def f_post(self, result, arg):
            assert result>arg
        f = eiffelmethod(f,f_pre,f_post)
    c = C()
    c.f(1)
    try:
    	c.f(-1)
    except AssertionError:
    	pass
    else:
    	raise "c.f(-1) bad implemented"
    print "OK"

if __name__=='__main__':
    _test()


text:
from __future__ import absolute_import, division, print_function

from .form import Form, TornadoInputWrapper

__author__ = 'ipfans <ipfanscn@gmail.com>'
__since__ = '2015-08-28'
__version__ = '1.0.0'

__all__ = ['Form', 'TornadoInputWrapper']


text:
@implementation UIView (MJ)

- (void)setX:(CGFloat)x{

    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)x{
    return self.frame.origin.x;
}

- (void)setY:(CGFloat)y{

    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)y{
    return self.frame.origin.y;
}

- (void)setWidth:(CGFloat)width{

    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)width{
    return self.frame.size.width;
}

- (void)setHeight:(CGFloat)height{

    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGFloat)height{
    return self.frame.size.height;
}

- (void)setSize:(CGSize)size{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)size{
    return self.frame.size;
}

- (void)setOrigin:(CGPoint)origin{
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGPoint)origin{
    return self.frame.origin;
}

-(void)drawCorners:(UIRectCorner)roundedCorners rect:(CGRect)rect radius:(CGFloat)radius borderLineWidth:(CGFloat)lineWidth color:(UIColor *)color{

    // 单独设置每个矩形的圆角 ///////////////////////////////////////////////////////
    CGRect frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
    CGSize radiusSize = CGSizeMake(radius,radius);

    UIRectCorner corners = roundedCorners;

    //create path
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:corners cornerRadii:radiusSize];

    path.lineWidth = lineWidth * 2; /// 乘2是因为边线有一半的宽度会被剪掉

    //设置线条的颜色
    [color set];

    // 将path绘制出来
    [path stroke];

    // 裁剪圆角外的部分
    [self corners:roundedCorners rect:rect radius:radius];

}

-(void)corners:(UIRectCorner)roundedCorners rect:(CGRect)rect radius:(CGFloat)radius{

    CGRect frame = rect;
    CGSize radiusSize = CGSizeMake(radius,radius);

    UIRectCorner corners = roundedCorners;

    //create path
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:corners cornerRadii:radiusSize];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = frame;
    maskLayer.path = path.CGPath;
    self.layer.mask = maskLayer;

}

@end


text:
package br.senac.tads4.piiv.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import br.senac.tads4.piiv.model.enumerated.FormaPagamento;
import br.senac.tads4.piiv.model.enumerated.StatusPedido;
import br.senac.tads4.piiv.model.enumerated.TipoPagamento;

@Entity
@Table(name = "pedido")
public class Pedido implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(name = "data_pedido")
	private LocalDate dataPedido;

	@NotNull(message = "O campo cliente é obrigatório")
	@ManyToOne
	@JoinColumn(name = "id_cliente")
	private Cliente cliente;

	@OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
	private Set<ItemPedido> itensPedido;

	@NotNull(message = "O campo tipo de pagamento é obrigatório")
	@Column(name = "tipo_pagamento")
	@Enumerated(EnumType.STRING)
	private TipoPagamento tipoPagamento;

	@Column(name = "forma_pagamento")
	@Enumerated(EnumType.STRING)
	private FormaPagamento formaPagamento;

	private Integer parcelas = 1;

	@Column(name = "data_pagamento")
	private LocalDate dataPagamento;

	@NotNull(message = "O campo valor subtotal é obrigatório")
	@Column(name = "valor_subtotal")
	private BigDecimal valorSubTotal;

	@NotNull(message = "O campo valor do frete é obrigatório")
	@Column(name = "valor_frete")
	private BigDecimal valorFrete;

	@NotNull(message = "O campo valor total é obrigatório")
	@Column(name = "valor_total")
	private BigDecimal valorTotal;

	@NotNull(message = "O campo data da entrega é obrigatório")
	@Column(name = "dias_entrega")
	private Integer diasEntrega;

	@Column(name = "data_separacao")
	private LocalDate dataSeparacao;

	@Column(name = "data_transporte")
	private LocalDate dataTransporte;

	@Column(name = "data_entrega")
	private LocalDate dataEntrega;

	@Enumerated(EnumType.STRING)
	private StatusPedido status;

	@Transient
	private DadosPagamento dadosPagamento;

	@Embedded
	private EnderecoEntrega enderecoEntrega;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public LocalDate getDataPedido() {
		return dataPedido;
	}

	public void setDataPedido(LocalDate dataPedido) {
		this.dataPedido = dataPedido;
	}

	public Cliente getCliente() {
		return cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	public Set<ItemPedido> getItensPedido() {
		return itensPedido;
	}

	public void setItensPedido(Set<ItemPedido> itensPedido) {
		this.itensPedido = itensPedido;
	}

	public Integer getQuantidadeItensPedido() {
		Integer quantidade = 0;

		for (ItemPedido itemPedido : itensPedido) {
			quantidade += itemPedido.getQuantidade();
		}

		return quantidade;
	}

	public TipoPagamento getTipoPagamento() {
		return tipoPagamento;
	}

	public void setTipoPagamento(TipoPagamento tipoPagamento) {
		this.tipoPagamento = tipoPagamento;
	}

	public FormaPagamento getFormaPagamento() {
		return formaPagamento;
	}

	public void setFormaPagamento(FormaPagamento formaPagamento) {
		this.formaPagamento = formaPagamento;
	}

	public Integer getParcelas() {
		return parcelas;
	}

	public void setParcelas(Integer parcelas) {
		this.parcelas = parcelas;
	}

	public LocalDate getDataPagamento() {
		return dataPagamento;
	}

	public void setDataPagamento(LocalDate dataPagamento) {
		this.dataPagamento = dataPagamento;
	}

	public BigDecimal getValorSubTotal() {
		return valorSubTotal;
	}

	public void setValorSubTotal(BigDecimal valorSubTotal) {
		this.valorSubTotal = valorSubTotal;
	}

	public BigDecimal getValorFrete() {
		return valorFrete;
	}

	public void setValorFrete(BigDecimal valorFrete) {
		this.valorFrete = valorFrete;
	}

	public BigDecimal getValorTotal() {
		return valorTotal;
	}

	public void setValorTotal(BigDecimal valorTotal) {
		this.valorTotal = valorTotal;
	}

	public Integer getDiasEntrega() {
		return diasEntrega;
	}

	public void setDiasEntrega(Integer diasEntrega) {
		this.diasEntrega = diasEntrega;
	}

	public LocalDate getDataSeparacao() {
		return dataSeparacao;
	}

	public void setDataSeparacao(LocalDate dataSeparacao) {
		this.dataSeparacao = dataSeparacao;
	}

	public LocalDate getDataTransporte() {
		return dataTransporte;
	}

	public void setDataTransporte(LocalDate dataTransporte) {
		this.dataTransporte = dataTransporte;
	}

	public LocalDate getDataEntrega() {
		return dataEntrega;
	}

	public void setDataEntrega(LocalDate dataEntrega) {
		this.dataEntrega = dataEntrega;
	}

	public StatusPedido getStatus() {
		return status;
	}

	public void setStatus(StatusPedido status) {
		this.status = status;
	}

	public EnderecoEntrega getEnderecoEntrega() {
		return enderecoEntrega;
	}

	public void setEnderecoEntrega(EnderecoEntrega enderecoEntrega) {
		this.enderecoEntrega = enderecoEntrega;
	}

	public DadosPagamento getDadosPagamento() {
		return dadosPagamento;
	}

	public void setDadosPagamento(DadosPagamento dadosPagamento) {
		this.dadosPagamento = dadosPagamento;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Pedido other = (Pedido) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}


text:
Logs for container: {{ container.Name }}

            <button class="btn btn-info" ng-click="scrollTo('stdout')">stdout</button>
            <button class="btn btn-warning" ng-click="scrollTo('stderr')">stderr</button>

                Reload logs
                <input id="tailLines" type="number" ng-style="{width: '45px'}"
                       ng-model="tailLines" ng-keypress="($event.which === 13)? toggleTail() : 0"/>
                lines

                <input id="timestampToggle" type="checkbox" ng-model="showTimestamps"
                       ng-change="toggleTimestamps()"/> Timestamps

STDOUT

{{stdout}}

STDERR

{{stderr}}


text:
describe('Chapter 5', function() {
  require('should');
  const Redis = require('ioredis');
  const ch05 = require('../src/ch05/main');
  const Utils = require('../src/utils');
  const { Config } = require('../src/config');

  let redis;
  before(async () => {
    redis = new Redis({
      db: 15,
    });
    await redis.flushdb();
    redis.on('error', error => {
      debug('Redis connection error', error);
    });
  });

  after(function() {
    redis.quit();
  });

  describe('test_log_recent', async () => {
    it(`Let's write a few logs to the recent log: five logs`, async () => {
      for (let msg in [0, 1, 2, 3, 4]) {
        await ch05.logRecent(redis, 'test', `this is message ${msg}`);
      }
      const recent = await redis.lrange(
        `recent:test:${ch05.LOG_SEVERITY.INFO}`,
        0,
        -1,
      );

      recent.length.should.be.aboveOrEqual(5);
    });
  });

  describe('test_log_common', async () => {
    it(`Let's write some items to the common log`, async () => {
      let count = 1;
      while (count < 6) {
        let i = 0;
        while (i < count) {
          await ch05.logCommon(redis, 'test', `message-${count}`);
          i++;
        }
        count++;
      }
      const res = await redis.zrevrange(
        `common:test:${ch05.LOG_SEVERITY.INFO}`,
        0,
        -1,
        'withscores',
      );

      res.length.should.equal(10);
      res[0].should.equal('message-5');
      parseInt(res[1], 10).should.equal(5);
    });
  });

  describe('test_counters', async () => {
    it(`Let's update some counters for now and a little in the future`, async () => {
      const now = Utils.currentTimestamp();
      let count = 0;
      while (count < 10) {
        await ch05.updateCounter(
          redis,
          'test',
          Math.ceil(Math.random() * 5),
          now + count,
        );
        count++;
      }
    });

    it(`We have some per-second counters:`, async () => {
      const res = await ch05.getCounter(redis, 'test', 1);
      res.length.should.be.aboveOrEqual(10);
    });

    it(`We have some per-5-second counters:`, async () => {
      const res = await ch05.getCounter(redis, 'test', 5);
      res.length.should.be.aboveOrEqual(2);
    });

    it(`Let's clean out some counters by setting our sample count to 0`, async () => {
      const sourceCurrentTimestamp = Utils.currentTimestamp;
      function newCurrentTimestamp() {
        return sourceCurrentTimestamp() + 2 * 86400;
      }
      Utils.currentTimestamp = newCurrentTimestamp;
      Config.SAMPLE_COUNT = 0;
      await ch05.cleanCounters(redis);
      Utils.currentTimestamp = sourceCurrentTimestamp;
      Config.SAMPLE_COUNT = 100;
    });

    it(`Did we clean out all of the counters?`, async () => {
      const res = await ch05.getCounter(redis, 'test', 86400);
      res.length.should.equal(0);
    });
  });
});


text:
package org.compass.spring.aop;

import org.compass.core.CompassException;
import org.compass.core.Resource;

/**
 * A simple base class for CompassSession#create operation.
 *
 * @author kimchy
 */
public class AbstractCompassCreateInterceptor extends AbstractCompassInterceptor {

    protected void create(Object value) throws CompassException {
        if (value instanceof Resource) {
            compassTemplate.create((Resource) value);
        } else {
            compassTemplate.create(value);
        }
    }
}


text:
Version: **v21.1.0**

This is my personal web site, made with love without frameworks, huge libraries but a bit of JavaScript's voodoo glue.

This is pure HTML/JS/CSS for the following reason: is will be faster to understand and to update for people who want to fork this project. No technical debt, vanilla web.

Moreover this missing of such tools avoids the risks of failures, exploits or planned obsolescence.

Simple project, simple web site, simple tools, with self hosted contents ;-)

It's under MIT license, so feel free to fork this project and use it as a base for your own web site!

## Pro tip

Before deploying the web site on production, you should minify the CSS and JS sources, and compute the JS and CSS files' SRI values (and update the references in the HTML pages inside 'integrity' attributes):

```shell
cd .dev
bash minify-css.sh
node minify-js.js
```

Then

```shell
cd .dev
node compute-sri.js
```

## Note

Heavy files are not versionned (like podcasts and videos)


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE pise SYSTEM "PARSER/pise.dtd">

<pise>

    <title>CDS</title>
    <description>Search Coding Regions</description>
    <authors>F. Chauveau</authors>
    <category>nucleic:translation</category>
    <category>gene finding</category>

<command>cds</command>

<parameters>

<parameter iscommand="1" ishidden="1" issimple="1" type="String">
<name>cds</name>
<attributes>

	<format>
		<language>seqlab</language>
		cds
		<language>perl</language>
		"cds"
	</format>
	<group>0</group>

</attributes>
</parameter>

<parameter ismandatory="1" issimple="1" type="Sequence">
<name>seq</name>
<attributes>

	<prompt>Sequence File</prompt>
	<format>
		<language>perl</language>
		" $value"
	</format>
	<group>10</group>

</attributes>
</parameter>

<parameter type="Paragraph">
<paragraph>
<name>search</name>
<prompt>Search parameters</prompt>
<parameters>

	<parameter type="Integer">
	<name>minaa</name>
	<attributes>

		<prompt>Minimum number of amino acids in CDS</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -l $value" : ""
		</format>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Excl">
	<name>frame</name>
	<attributes>

		<prompt>Frame</prompt>
		<format>
			<language>perl</language>
			($value)? " -f $value" : ""
		</format>
		<group>1</group>
		<vlist>
			<value>1</value>
			1
			<value>2</value>
			2
			<value>3</value>
			3
			<value>-1</value>
			1 (opposite strand)
			<value>-2</value>
			2 (opposite strand)
			<value>-3</value>
			3 (opposite strand)
		</vlist>

	</attributes>
	</parameter>

	<parameter type="String">
	<name>starts</name>
	<attributes>

		<prompt>START codons (separated by commas)</prompt>
		<format>
			<language>perl</language>
			($value && ($value !~ /,/ || $value =~ s/,/ /g) )? " -c \\"$value\\" " : ""
		</format>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>maxf</name>
	<attributes>

		<prompt>longest CDS in each frame</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -m":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>max</name>
	<attributes>

		<prompt>longest CDS</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -M":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>all</name>
	<attributes>

		<prompt>all CDS, including CDS inside CDS</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -a":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

</parameters>
</paragraph>

</parameter>

<parameter type="Paragraph">
<paragraph>
<name>output</name>
<prompt>Output parameters</prompt>
<parameters>

	<parameter type="Switch">
	<name>nucl</name>
	<attributes>

		<prompt>nucleotids output</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -n":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>print_adn</name>
	<attributes>

		<prompt>Print ADN as well as Amino-acids</prompt>
		<format>
			<language>perl</language>
			($print_adn || defined $left_adn)? " -v $left_adn" : ""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Integer">
	<name>left_adn</name>
	<attributes>

		<prompt>How many base pairs on the left (if print ADN)</prompt>
		<format>
			<language>perl</language>
			""
		</format>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>print_frame</name>
	<attributes>

		<prompt>print frame before search</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -s":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>print_pos</name>
	<attributes>

		<prompt>print only position(s)</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -p":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Switch">
	<name>xml</name>
	<attributes>

		<prompt>XML output (-x)</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -x":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

</parameters>
</paragraph>

</parameter>

<parameter ishidden="1" type="String">
<name>xmldtdcopy</name>
<attributes>

	<format>
		<language>perl</language>
		"; cp /local/gensoft/lib/pasteur/cds.dtd ."
	</format>
	<group>100</group>
<precond>
	<language>perl</language>
	$xml
</precond>

</attributes>
</parameter>

<parameter type="Results">
<name>xmldtd</name>
<attributes>

<precond>
	<language>perl</language>
	$xml
</precond>
	<filenames>cds.dtd</filenames>

</attributes>
</parameter>

<parameter type="Paragraph">
<paragraph>
<name>others</name>
<prompt>Other parameters</prompt>
<parameters>

	<parameter type="Switch">
	<name>end_stop</name>
	<attributes>

		<prompt>CDS ends at STOP</prompt>
		<format>
			<language>perl</language>
			 ($value)? " -e":""
		</format>
		<vdef><value>0</value></vdef>
		<group>1</group>

	</attributes>
	</parameter>

	<parameter type="Excl">
	<name>genetic</name>
	<attributes>

		<prompt>Genetic Code</prompt>
		<format>
			<language>perl</language>
			 ($value && $value ne $vdef)? " -g $value" : ""
		</format>
		<vdef><value>1</value></vdef>
		<group>1</group>
		<vlist>
			<value>1</value>
			Standard
			<value>2</value>
			Vertebrate Mitochondrial
			<value>3</value>
			Yeast Mitochondrial
			<value>4</value>
			Mold, Protozoan, Coelenterate Mitochondrial and Mycoplasma/Spiroplasma
			<value>5</value>
			Invertebrate Mitochondrial
			<value>6</value>
			Ciliate Macronuclear and Dasycladacean
			<value>9</value>
			Echinoderm Mitochondrial
			<value>10</value>
			Euplotid Nuclear
			<value>11</value>
			Bacterial
			<value>12</value>
			Alternative Yeast Nuclear
			<value>13</value>
			Ascidian Mitochondrial
			<value>14</value>
			Flatworm Mitochondrial
			<value>15</value>
			Blepharisma Macronuclear
		</vlist>

	</attributes>
	</parameter>

</parameters>
</paragraph>

</parameter>

</parameters>
</pise>


text:
/* input/output format */
#ifndef __INPDEF_H__
#define __INPDEF_H__

/* BILLY 8/6/04 */
#ifndef COMPILE_ALL_CPP
#ifdef __cplusplus
extern "C" {
#endif
#endif

int e_MolfileToInchi_Input( FILE *inp_molfile, inchi_Input *orig_at_data, int bMergeAllInputStructures,
                       int bDoNotAddH, int bAllowEmptyStructure,
                       const char *pSdfLabel, char *pSdfValue, long *lSdfId,
                       long *lMolfileNumber, INCHI_MODE *pInpAtomFlags, int *err, char *pStrErr );
int e_INChIToInchi_Input( INCHI_IOSTREAM *inp_molfile, inchi_Input *orig_at_data, int bMergeAllInputStructures,
                       int bDoNotAddH, int vABParityUnknown, INPUT_TYPE nInputType,
                       char *pSdfLabel, char *pSdfValue, long *lSdfId, INCHI_MODE *pInpAtomFlags,
                       int *err, char *pStrErr );

int e_CopyMOLfile(FILE *inp_file, long fPtrStart, long fPtrEnd, FILE *prb_file, long nNumb);

/* BILLY 8/6/04 */
#ifndef COMPILE_ALL_CPP
#ifdef __cplusplus
}
#endif
#endif

#endif  /* __INPDEF_H__ */


text:
Things are a mite awkward with this right now. I'm storing the datascript
connection in the app-db, which among other things breaks the re-frisk
display. I'm using the re-frame effect stuff from 0.8, but a lot of the effect
handlers just transact a change into datascript and I'm relying on posh to
pull them out for UI changes.

This actually doesn't seem as bad as I expected it to be, but maybe I
should keep datascript around as a coeffect, inject it into a bunch of
my handlers, and then use dynamic subscriptions for the front-end.

## UI

- Play button for songs

## Playlist generation

- Re-roll seeds when no search results are found
- Keep track of what's been searched
- Generate and save an actual playlist
- Maybe try soundcloud instead of spotify, less walled-gardeny
  and you can stream music from the actual page
- Or youtube? Seems like a swamp, though

## Persistence

- Save checkin results to localstorage, only fetch new ones
- Same for spotify searches
- Look into persisting the whole datascript db - maybe via
  [datascript-transit](https://github.com/tonsky/datascript-transit)?

## Checkins

- Support Facebook checkins
- Maybe instagram or something?
- Add UI to select window of time to use for checkins

## Mobile

- Make it prettier
- Mobile interface via swipes / taps, shake.js

## Etc

- Scrub PII out of test-checkin file


text:
VFL to CCSS Compiler [![Build Status](https://travis-ci.org/gss/vfl-compiler.png?branch=master)](https://travis-ci.org/gss/vfl-compiler)
=============

This library compiles [GSS-flavored VFL](http://gridstylesheets.org/guides/vfl/) statements into [GSS-flavored CCSS](http://gridstylesheets.org/guides/ccss/) statements.

## Background

Language specs inspired by Apple's [Visual Format Language](https://developer.apple.com/library/ios/documentation/userexperience/conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html) (VFL) and Greg Badros's [Constraint CSS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.4819) (CCSS).

## Documentation

Please refer to <http://gridstylesheets.org/guides/vfl/>.