text:
package uk.ac.imperial.doc.jexpressions.expressions;

/**
 * An expression for a ratio of two expressions.
 *
 * @author Anton Stefanek
 *
 */

public class DivExpression extends AbstractExpression {

	/**
	 * Creates and possibly simplifies a DivExpression with the given numerator
	 * and denominators.
	 *
	 * @param numerator
	 * @param denominator
	 * @return
	 */
	public static AbstractExpression create(AbstractExpression numerator,
			AbstractExpression denominator) {
		if (denominator.equals(DoubleExpression.ONE)) {
			return numerator;
		}
		if (numerator.equals(denominator)) {
			return DoubleExpression.ONE;
		}
		if (numerator.equals(DoubleExpression.ZERO)) {
			return DoubleExpression.ZERO;
		}
		if (numerator instanceof DoubleExpression
				&& denominator instanceof DoubleExpression) {
			double value = ((DoubleExpression) numerator).getValue()
					/ ((DoubleExpression) denominator).getValue();
			return new DoubleExpression(value);
		}
		return new DivExpression(numerator, denominator);
	}

	private AbstractExpression denominator;

	private AbstractExpression numerator;

	protected DivExpression(AbstractExpression numerator,
			AbstractExpression denominator) {
		super();
		this.numerator = numerator;
		this.denominator = denominator;
	}

	@Override
	public void accept(IExpressionVisitor v) {
		v.visit(this);
	}

	@Override
	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (!(o instanceof DivExpression))
			return false;
		DivExpression asDiv = (DivExpression) o;
		return this.numerator.equals(asDiv.getNumerator())
				&& this.denominator.equals(asDiv.getDenominator());
	}

	public AbstractExpression getDenominator() {
		return denominator;
	}

	public AbstractExpression getNumerator() {
		return numerator;
	}

	@Override
	public int hashCode() {
		return numerator.hashCode() * 23 + denominator.hashCode();
	}

	@Override
	public String toString() {
		return numerator.toString() + "/" + denominator.toString();
	}

}

redpajama_set_name: RedPajamaGithub


text:
FROM "elixir:1.11.2-alpine"

ARG MIX_ENV=dev
ENV MIX_ENV=$MIX_ENV

WORKDIR /code/

RUN echo "y" | mix local.hex --if-missing && echo "y" | mix local.rebar --if-missing

ADD ["mix.lock", "mix.exs", "/code/"]

RUN mix deps.get && MIX_ENV=test mix deps.compile && \
  MIX_ENV=$MIX_ENV mix deps.compile

ADD ["config", "lib", "priv", "/code/"]

RUN MIX_ENV=$MIX_ENV mix compile

ADD ["test", "/code/"]

RUN MIX_ENV=test mix compile && MIX_ENV=$MIX_ENV mix compile

ADD . /code/

RUN MIX_ENV=test mix compile && MIX_ENV=$MIX_ENV mix compile

CMD ["/bin/sh"]

# mix ecto.create
# mix ecto.migrate


text:
import vtk.vtkNativeLibrary;
import vtk.vtkRenderWindow;
import vtk.vtkRenderWindowInteractor;
import vtk.vtkRenderer;
import vtk.vtkImageSinusoidSource;
import vtk.vtkNamedColors;
import vtk.vtkImageNormalize;
import vtk.vtkImageCast;
import vtk.vtkImageActor;

public class ImageNormalize
{
  // -----------------------------------------------------------------
  // Load VTK library and print which library was not properly loaded
  static
  {
    if (!vtkNativeLibrary.LoadAllNativeLibraries())
    {
      for (vtkNativeLibrary lib : vtkNativeLibrary.values())
      {
        if (!lib.IsLoaded())
        {
          System.out.println(lib.GetLibraryName() + " not loaded");
        }
      }
    }
    vtkNativeLibrary.DisableOutputWindow(null);
  }
  // -----------------------------------------------------------------

  public static void main(String args[])
  {

    vtkNamedColors colors = new vtkNamedColors();

    double left_bkg[] = new double[]{0.6, 0.5, 0.4, 1.0};
    double right_bkg[] = new double[]{0.4, 0.5, 0.6, 1.0};

    colors.SetColor("bkgColor", left_bkg);
    colors.SetColor("boxColor", right_bkg);

    //  Create an image
    vtkImageSinusoidSource source = new vtkImageSinusoidSource();
    source.Update();

    vtkImageNormalize normalizeFilter = new vtkImageNormalize();

    normalizeFilter.SetInputConnection(source.GetOutputPort());
    normalizeFilter.Update();

    vtkImageCast inputCastFilter = new vtkImageCast();
    inputCastFilter.SetInputConnection(source.GetOutputPort());
    inputCastFilter.SetOutputScalarTypeToUnsignedChar();
    inputCastFilter.Update();

    vtkImageCast normalizeCastFilter = new vtkImageCast();
    normalizeCastFilter.SetInputConnection(normalizeFilter.GetOutputPort());
    normalizeCastFilter.SetOutputScalarTypeToUnsignedChar();
    normalizeCastFilter.Update();

    //  Create actors
    vtkImageActor inputActor = new vtkImageActor();
    inputActor.GetMapper().SetInputConnection(inputCastFilter.GetOutputPort());

    vtkImageActor normalizedActor = new vtkImageActor();
    normalizedActor.GetMapper().SetInputConnection(normalizeCastFilter.GetOutputPort());

    //  Create the render window and interactor.

    vtkRenderWindow renWin = new vtkRenderWindow();
    vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor();
    iren.SetRenderWindow(renWin);

    //  Define viewport ranges
    // (xmin, ymin, xmax, ymax)
    double leftViewport[] = new double[] {0.0, 0.0, 0.5, 1.0};
    double rightViewport[] = new double[] {0.5, 0.0, 1.0, 1.0};

    //  Setup both renderers
    vtkRenderer leftRenderer = new vtkRenderer();
    renWin.AddRenderer(leftRenderer);
    leftRenderer.SetViewport(leftViewport);
    leftRenderer.SetBackground(left_bkg);

    vtkRenderer rightRenderer = new vtkRenderer();
    renWin.AddRenderer(rightRenderer);
    rightRenderer.SetViewport(rightViewport);
    rightRenderer.SetBackground(right_bkg);

    leftRenderer.AddActor(inputActor);
    rightRenderer.AddActor(normalizedActor);

    leftRenderer.ResetCamera();
    rightRenderer.ResetCamera();

    renWin.SetSize(600,300);
    renWin.Render();

    iren.Initialize();
    iren.Start();
  }
}


text:
import * as bcrypt from 'bcryptjs';
import * as sequelize from 'sequelize';

export interface IUser {
  id?: number;
  email?: string;
  password?: string;
  confirmed?: boolean;
}

export interface IUserInstance extends sequelize.Instance<IUser>, IUser {
}

export function model(_sequelize: sequelize.Sequelize): sequelize.Model<IUserInstance, IUser> {
  const model = _sequelize.define<IUserInstance, IUser>(
    'user',
    {
      email: {
        type: sequelize.TEXT,
        unique: true,
        allowNull: false,
        validate: {
          isEmail: true
        }
      },
      password: {
        type: sequelize.TEXT,
        allowNull: false,
        validate: {
          minLen: (value: string) => {
            const minLen = 8;

            if (!(value.length >= minLen)) {
              throw new Error('Password must have length greater or equal to 8 characters');
            }
          }
        }
      },
      confirmed: {
        type: sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false
      }
    },
    {
      instanceMethods: {
        toJSON: function (): IUser {
          const obj = Object.assign({}, this.get());
          delete obj.password;
          return obj;
        },
        comparePassword: function (password: string): Promise<boolean> {
          return new Promise((resolve, reject) => {
            bcrypt.compare(password, this.password, (err, isMatch) => {
              if (err) {
                return reject(err);
              }
              resolve(isMatch);
            });
          });
        }
      }
    }
  );

  model.beforeCreate((instance, options, callback) => {
    hashPassword(instance, options, callback);
  });

  model.beforeUpdate((instance, options, callback) => {
    hashPassword(instance, options, callback);
  });

  return model;
}

function hashPassword(user: IUserInstance, options: Object, cb: Function): void {
  (async () => {
    const salt = await new Promise<string>((resolve, reject) => {
      bcrypt.genSalt(10, (err, result) => {
        if (err) {
          return reject(err);
        }
        resolve(result);
      });
    });

    const hash = await new Promise<string>((resolve, reject) => {
      bcrypt.hash(user.password, salt, (err, result) => {
        if (err) {
          return reject(err);
        }
        resolve(result);
      });
    });

    user.password = hash;
    cb(null, options);
  })()
    .catch((err) => {
      cb(err);
    });
}


text:
<?php

namespace Soda\Cms\InterfaceBuilder\Menu;

class MenuRegistrar
{
    protected $registered_menus = [];

    /**
     * Registers a new CMS form field.
     *
     * @param $name
     * @param $callback
     *
     * @return $this
     */
    public function register($name, $callback)
    {
        if (! isset($this->registered_menus[$name])) {
            $this->registered_menus[$name] = [];
        }

        $this->registered_menus[$name][] = $callback;

        return $this;
    }

    /**
     * Returns a menu by its name.
     *
     * @return Menu|null
     */
    public function resolve($name)
    {
        return $this->isRegistered($name) ? $this->boot($name) : null;
    }

    /**
     * Checks if a menu is registered.
     *
     * @param $name
     *
     * @return bool
     */
    public function isRegistered($name)
    {
        return isset($this->registered_menus[$name]);
    }

    protected function boot($name)
    {
        $callables = $this->registered_menus[$name];

        if ($callables instanceof Menu) {
            return $callables;
        }

        $menu = new Menu($name);

        foreach ($callables as $callable) {
            $callable($menu);
        }

        $this->registered_menus[$name] = $menu;

        return $menu;
    }
}


text:
#ifndef __PHRENDETARGET_H__
#define __PHRENDETARGET_H__

#include <boost/unordered_map.hpp>
#include "config.h"
#include "View.h"
#include "Resource.h"
#include "Texture.h"

namespace phoenix
{

	//! Render Target view management
	enum E_TARGET_VIEW_BEHAVIOR {
		TVB_NOTHING, //!< Do nothing, don't modify the view at all.
		TVB_RESIZE_VIEWPORT, //!< Default behavior, resizes the viewport to match the first texture size.
		TVB_RESIZE_PROJECTION, //!< Resizes just the projection matrix.
		TVB_RESIZE_BOTH, //!< Resizes both the viewport and the projection matrix.
	};

    //! Render Target
    /*!
        This class provides the ability to bind textures as the current render target.
    */
    class RenderTarget
                : public Resource
    {

    public:

		//! Default Constructor
        /*!
			Create a framebuffer object, but does not create a texture. A texture must be attached before this can be used.
		*/
        RenderTarget( ResourceManager& r )
                : Resource(r), FBO_id(0), textures(32), view_behavior(TVB_RESIZE_VIEWPORT), old_view(Vector2d(0.0f,0.0f), Vector2d(0.0f,0.0f))
        {
            setName( "RenderTarget" );
			generateFramebufferObject();
        }

		//! Quick Constructor
        /*!
			Create a framebuffer object and a texture with the given size, and attaches the texture.
		*/
        RenderTarget( ResourceManager& r, Vector2d size )
                : Resource(r), FBO_id(0), textures(32), view_behavior(TVB_RESIZE_VIEWPORT), old_view(Vector2d(0.0f,0.0f), Vector2d(0.0f,0.0f))
        {
            setName( "RenderTarget" );
			generateFramebufferObject();

			TexturePtr t = new Texture( r, size );
			attach( t );
        }

        virtual ~RenderTarget()
        {
			if( GLEW_VERSION_2_0 && FBO_id){
				glDeleteFramebuffersEXT( 1, &FBO_id );
			}
        }

		//! Attaches a texture to the FBO.
		inline void attach( TexturePtr t, const GLuint _where = GL_COLOR_ATTACHMENT0_EXT ){

			textures[_where] = t;

			if( GLEW_VERSION_2_0  && FBO_id ){
				bind();
					glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
								  (GLuint) _where,
								  GL_TEXTURE_2D,
								  t->getTextureId(),
								  0);
				unbind();
			}
		}

		//! Gets the currently attached texture
		inline TexturePtr getTexture( const GLuint _where = GL_COLOR_ATTACHMENT0_EXT ) { return textures[_where]; }

		//! Sets which buffers to draw to, this is analogous to glDrawBuffers/glDrawBuffer
		inline void setDrawBuffers( GLsizei count, const GLenum * bufs ){
			if( GLEW_VERSION_2_0  && FBO_id ){
				bind();

				glDrawBuffers( count,  bufs );

				unbind();
			}
		}

		inline void setDrawBuffer( const GLenum buf ){
			if( GLEW_VERSION_2_0  && FBO_id ){
				bind();

				glDrawBuffer( buf );

				unbind();
			}
		}

		//! Binds the FBO
		inline void bind(){ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FBO_id); }

		//! Unbinds the FBO
		inline void unbind(){ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); }

        //! Binds the FBO and prepares to render, returns false if anything went wrong.
        inline bool start()
		{

			if( GLEW_VERSION_2_0  && FBO_id ){
				bind();

				if( glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ) != GL_FRAMEBUFFER_COMPLETE_EXT ) return false;

				return true;
			}

			return false;

		}

        //! Unbinds the FBO
        inline void end()
		{
			if( GLEW_VERSION_2_0){
				unbind();

			}
		}

		//! Set the view resize behavior, only used when attached to a batch renderer.
		inline void setViewResizeBehavior( E_TARGET_VIEW_BEHAVIOR _b ) { view_behavior = _b; }

		//! Get the view resize behavior.
		inline E_TARGET_VIEW_BEHAVIOR getViewResizeBehavior() { return view_behavior; }

		//! Modifies the view, if needed
		/*!
			Automatically called by BatchRenderer if this is attached.
			Must be called manually for unattached targets.
		*/
		inline void modifyView(View& _view){
			old_view = _view;
			TexturePtr t = getTexture();

			if( view_behavior == TVB_RESIZE_VIEWPORT || view_behavior == TVB_RESIZE_BOTH){
				if( t ){
					_view.setSize( t->getSize() );
				}
			}

			if( view_behavior == TVB_RESIZE_PROJECTION || view_behavior == TVB_RESIZE_BOTH){
				if( t ){
					glMatrixMode(GL_PROJECTION);
					glPushMatrix();
					glLoadIdentity();
					glOrtho(0.0f, t->getSize().getX(), t->getSize().getY(), 0.0f, 1000.0f, -1000.0f);
					glMatrixMode(GL_MODELVIEW);
				}
			}
		}

		//! Restores the view to the last one that was passed to modifyView, also restore the projection matrix if it was modified.
		/*!
			Automatically called by BatchRenderer if this is attached.
		*/
		inline void restoreView(View& _view){
			if( view_behavior != TVB_NOTHING ){
				_view = old_view;

				if( view_behavior == TVB_RESIZE_PROJECTION || view_behavior == TVB_RESIZE_BOTH ){
					glMatrixMode(GL_PROJECTION);
					glPopMatrix();
					glMatrixMode(GL_MODELVIEW);
				}
			}
		}

	protected:

		//! Generate Framebuffer Object Id, returns true if everything was okay, or false if it was unable to do so.
		bool generateFramebufferObject(){
			if( GLEW_VERSION_2_0 ){
				glGenFramebuffersEXT( 1, &FBO_id );
				return FBO_id ? true : false;
			}
			return true;
		}

		GLuint FBO_id;
		boost::unordered_map<GLuint, TexturePtr> textures;
		E_TARGET_VIEW_BEHAVIOR view_behavior;
		View old_view;
    };

    typedef boost::intrusive_ptr<RenderTarget> RenderTargetPtr;
} //namespace phoenix

#endif // __PHRENDETARGET_H__


text:
_[www.codever.land/bookmarks/t/code-quality](https://www.codever.land/bookmarks/t/code-quality)_
---
#### [Codacy](https://www.codacy.com/)
_https://www.codacy.com/_

Automated Code Review to ship better code, faster.
* **tags**: [python](../tagged/python.md), [code-quality](../tagged/code-quality.md)
---
#### [Codecov](https://codecov.io/)
_https://codecov.io/_

Code coverage dashboard.
* **tags**: [python](../tagged/python.md), [code-quality](../tagged/code-quality.md)
---
#### [CodeFactor](https://www.codefactor.io/)
_https://www.codefactor.io/_

Automated Code Review for Git.
* **tags**: [python](../tagged/python.md), [code-quality](../tagged/code-quality.md)
---
#### [Landscape](https://landscape.io/)
_https://landscape.io/_

Hosted continuous Python code metrics.
* **tags**: [python](../tagged/python.md), [code-quality](../tagged/code-quality.md)
---


text:
"""
PlexAPI Play PlayQueues
"""
import plexapi, requests
from plexapi import video
from plexapi import utils

class PlayQueue(object):

    def __init__(self, server, data, initpath):
        self.server = server
        self.initpath = initpath
        self.identifier = data.attrib.get('identifier')
        self.mediaTagPrefix = data.attrib.get('mediaTagPrefix')
        self.mediaTagVersion = data.attrib.get('mediaTagVersion')
        self.playQueueID = data.attrib.get('playQueueID')
        self.playQueueSelectedItemID = data.attrib.get('playQueueSelectedItemID')
        self.playQueueSelectedItemOffset = data.attrib.get('playQueueSelectedItemOffset')
        self.playQueueTotalCount = data.attrib.get('playQueueTotalCount')
        self.playQueueVersion = data.attrib.get('playQueueVersion')
        self.items = [video.build_item(server, elem, initpath) for elem in data]

    @classmethod
    def create(cls, server, video, shuffle=0, continuous=0):
        # NOTE: I have not yet figured out what __GID__ is below or where the proper value
        # can be obtained. However, the good news is passing anything in seems to work.
        path = 'playQueues%s' % utils.joinArgs({
            'uri': 'library://__GID__/item/%s' % video.key,
            'key': video.key,
            'type': 'video',
            'shuffle': shuffle,
            'continuous': continuous,
            'X-Plex-Client-Identifier': plexapi.X_PLEX_IDENTIFIER,
        })
        data = server.query(path, method=requests.post)
        return cls(server, data, initpath=path)


text:
<!DOCTYPE html>
<html class='reftest-wait'>
  <link rel='stylesheet' type='text/css' href='style.css'>
  <script>
    function loadHandler()
    {
      document.getElementById('t').focus();
    }
    function focusHandler()
    {
      document.documentElement.className = '';
    }
  </script>
  <body onload='loadHandler();'>
    <textarea id='t' placeholder='foo' onfocus='focusHandler();'></textarea>
  </body>
</html>


text:
====
Please refer to [ros wiki] (http://wiki.ros.org/reuleaux) for more detailed instruction

#1. RViz and RQT User Interface:

There are two types of interactive markers:
  - The red arrow acts as a pointer which the user can move around the RViz enviroment. Fruthermore by clicking on the arrow another magenta arrow is added to the RViz enviroment. This arrow acts as task poses for base placement planner.
  - The magenta arrow is the task poses for the base placement planner. The orientation of the arrow can be changed by holding the CTRL key and moving it with the mouse.
  - Each arrow has a menu where the user can either delete the selected arrow or it can change its position and orientation by using the 6DOF marker control.
  - The RQT UI communicates simultaniously with the RViz enviroment and the User can change the state of a marker either through RViz or the RQT UI
  - TreeView displays all the added waypoints. The user can manipulate them directly in the TreeView and see their position and orientation of each waypoint.
  - The user can add new point or delete it through the RQT UI.
  - New tool component has been added for adding Arrows by using a mouse click

#2. How to run the code
  Just run rosrun rviz rviz

  - From the panel window select base placement planner
  - Add a reachability map display and set the topic to /reachability_map
  - Add an Interactive Marker display and set the topic to /base_placement_plugin/update
  - Add a markerArray display. Set the topic to /visualization_marker_array

There is a preconfigured rviz config file in the rviz folder

After deciding the task poses load an inverse reachability map previously created. If you have not done it yet, run

rosrun map_creator create_inverse_reachability_map <name of the reachability map>

rosrun map_creator create_inverse_reachability_map /home/abhi/Desktop/motomap_mh5_r0.08_reachability.h5

it will save an invese reachability map in the map_creator/Inv_map folder

After loading the inverse reachability map set the desired parameters. There are two parameters. Number of desired base locations and number of high scoring spheres from where the poses will be collected.

Set the desired output visualization method.(The robot model visualization is still in development. Coming Soon)
```
When everything is set up, press the Find Base button. It will show the base locations.

If you want to see the union map, press the show union map button.


text:
//  Copyright © 2021 650 Industries. All rights reserved.

#import <EXManifests/EXManifestsManifest.h>
#import <EXManifests/EXManifestsBaseManifest.h>

NS_ASSUME_NONNULL_BEGIN

@interface EXManifestsNewManifest : EXManifestsBaseManifest<EXManifestsManifestBehavior>

/**
 * An ID representing this manifest, not the ID for the experience.
 */
- (NSString *)rawId;

/**
 * Incorrect for now until we figure out how to get this in the new manifest format.
 */
- (NSString *)stableLegacyId DEPRECATED_MSG_ATTRIBUTE("Modern manifests don't support stable legacy IDs");

- (NSString *)scopeKey;
- (nullable NSString *)easProjectId;

- (NSString *)createdAt;
- (NSString *)runtimeVersion;
- (NSDictionary *)launchAsset;
- (nullable NSArray *)assets;

- (nullable NSDictionary *)expoGoConfigRootObject;
- (nullable NSDictionary *)expoClientConfigRootObject;

@end

NS_ASSUME_NONNULL_END


text:
package com.leohacker.leetcode.Archived.SymmetricTree;

import com.leohacker.leetcode.utils.TreeNode;

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

/**
 * 非递归的方式判断这棵树是否是对称的。广度遍历,一层层判断是否对称。如果都是空指针,遍历结束。
 * 考虑判断对称的需求,保存每层数据的队列要保存所有的空指针,也就是完全二叉树。
 */
public class IterativePrototypeSolution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }

        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);

        boolean empty = isEmpty(list);
        boolean symmetric = isSymmetricList(list);

        while (!empty && symmetric) {
            List<TreeNode> newlist = new ArrayList<TreeNode>();
            for (TreeNode node : list) {
                if ( node == null ) {
                    newlist.add(null);
                    newlist.add(null);
                } else {
                    newlist.add(node.left);
                    newlist.add(node.right);
                }
            }
            empty = isEmpty(newlist);
            symmetric = isSymmetricList(newlist);
            list = newlist;
        }
        return empty ? true : false;
    }

    private boolean isEmpty(List<TreeNode> list) {
        int index = list.size();
        index--;
        while ( (index >= 0) && list.get(index) == null ) {
            index--;
        }
        return (index < 0) ? true : false;
    }

    private boolean isSymmetricList(List<TreeNode> list) {
        int left = 0;
        int right = list.size() - 1;
        boolean symmetic = true;
        while(left < right && symmetic) {
            TreeNode leftNode = list.get(left);
            TreeNode rightNode = list.get(right);

            if ( leftNode == rightNode ) {
                symmetic = true;
            } else if ( leftNode == null || rightNode == null) {
                symmetic = false;
            } else {
                symmetic = (leftNode.val == rightNode.val) ? true : false;
            }
            left++;
            right--;
        }
        return symmetic;
    }
}


text:
title: "Scrum introduction"
layout: post
---

### Context

At 1001pharmacies, technical projects are developed using Agile method, more specifically Scrum method.

I was "only" a developer in the scrum team but recently I became the Scrum Master for all those projects.

Here are my work cases...

### What is Scrum

Scrum is a subset of Agile. It is a lightweight process framework for agile development, and the most widely-used one.
- A "process framework" is a particular set of practices that must be followed in order for a process to be consistent with the framework. (For example, the Scrum process framework requires the use of development cycles called Sprints, the XP framework requires pair programming, and so forth.)
- "Lightweight" means that the overhead of the process is kept as small as possible, to maximize the amount of productive time available for getting useful work done.

### Scrum master

The Scrum Master is a facilitator, a person dedicated to the well development of team and product delivery.

### Retrospective

One of the major work for a Scrum master is to make great retrospective to keep a good dynamic and make the team growing and being better !

Here are some formats I used for retrospective:

- [Pig or chicken](retrospective/pig-or-chicken.html)
- [Love retro](retrospective/love-retro.html)


text:
var Promise = require('bluebird'),
    Handlebars = require('handlebars'),
    _ = require('lodash'),
    fs = Promise.promisifyAll(require('fs')),
    join = require('path').join,
    knex = require('knex')({
        client: 'sqlite3',
        connection: {
            filename: "./mydb.sqlite"
        },
        pool: {
            min: 0,
            max: 1
        }
    });

const output_dir = 'output';
fs.mkdirAsync(output_dir)
    .catch(err => {
        if (err.code !== 'EEXIST') {
            console.error(err);
        }
    });

var source = fs.readFileSync('classTemplate.handlebars', 'utf8');
var template = Handlebars.compile(source);

knex.select('*')
    .from('sqlite_master')
    .where('type', 'table')
    .map(function (row) {
        console.log(row.name);
        return knex.raw(`pragma table_info(${row.name})`)
            .then(columns => writeTableColumns(row.name, columns));
    })
    .then(() => console.log('Finished generating classes'))
    .then(knex.destroy);

function writeTableColumns(table, columns) {
    var generated = template({
        className: table,
        properties: _.pluck(columns, 'name')
    });

    fs.writeFileAsync(join(output_dir, `${table}.js`), generated);
}


text:
#include "ShadowNodeTraits.h"

namespace facebook::react {} // namespace facebook::react


text:
PONY_EXTERN_C_BEGIN

typedef struct actorref_t
{
  pony_actor_t* actor;
  size_t rc;
  uint32_t mark;
  objectmap_t map;
} actorref_t;

object_t* ponyint_actorref_getobject(actorref_t* aref, void* address);

object_t* ponyint_actorref_getorput(actorref_t* aref, void* address,
  uint32_t mark);

void ponyint_actorref_free(actorref_t* aref);

DECLARE_HASHMAP(ponyint_actormap, actormap_t, actorref_t);

actorref_t* ponyint_actormap_getactor(actormap_t* map, pony_actor_t* actor, size_t* index);

actorref_t* ponyint_actormap_getorput(actormap_t* map, pony_actor_t* actor,
  uint32_t mark);

deltamap_t* ponyint_actormap_sweep(pony_ctx_t* ctx, actormap_t* map,
  uint32_t mark, deltamap_t* delta);

PONY_EXTERN_C_END

#endif


text:
import * as cp from 'child_process';
import { FileChangeType } from 'vs/platform/files/common/files';
import * as decoder from 'vs/base/node/decoder';
import * as glob from 'vs/base/common/glob';
import { IDiskFileChange, ILogMessage } from 'vs/platform/files/node/watcher/watcher';
import { FileAccess } from 'vs/base/common/network';

export class OutOfProcessWin32FolderWatcher {

	private static readonly MAX_RESTARTS = 5;

	private static changeTypeMap: FileChangeType[] = [FileChangeType.UPDATED, FileChangeType.ADDED, FileChangeType.DELETED];

	private ignored: glob.ParsedPattern[];

	private handle: cp.ChildProcess | undefined;
	private restartCounter: number;

	constructor(
		private watchedFolder: string,
		ignored: string[],
		private eventCallback: (events: IDiskFileChange[]) => void,
		private logCallback: (message: ILogMessage) => void,
		private verboseLogging: boolean
	) {
		this.restartCounter = 0;

		if (Array.isArray(ignored)) {
			this.ignored = ignored.map(i => glob.parse(i));
		} else {
			this.ignored = [];
		}

		// Logging
		if (this.verboseLogging) {
			this.log(`Start watching: ${watchedFolder}`);
		}

		this.startWatcher();
	}

	private startWatcher(): void {
		const args = [this.watchedFolder];
		if (this.verboseLogging) {
			args.push('-verbose');
		}

		this.handle = cp.spawn(FileAccess.asFileUri('vs/platform/files/node/watcher/win32/CodeHelper.exe', require).fsPath, args);

		const stdoutLineDecoder = new decoder.LineDecoder();

		// Events over stdout
		this.handle.stdout!.on('data', (data: Buffer) => {

			// Collect raw events from output
			const rawEvents: IDiskFileChange[] = [];
			stdoutLineDecoder.write(data).forEach((line) => {
				const eventParts = line.split('|');
				if (eventParts.length === 2) {
					const changeType = Number(eventParts[0]);
					const absolutePath = eventParts[1];

					// File Change Event (0 Changed, 1 Created, 2 Deleted)
					if (changeType >= 0 && changeType < 3) {

						// Support ignores
						if (this.ignored && this.ignored.some(ignore => ignore(absolutePath))) {
							if (this.verboseLogging) {
								this.log(absolutePath);
							}

							return;
						}

						// Otherwise record as event
						rawEvents.push({
							type: OutOfProcessWin32FolderWatcher.changeTypeMap[changeType],
							path: absolutePath
						});
					}

					// 3 Logging
					else {
						this.log(eventParts[1]);
					}
				}
			});

			// Trigger processing of events through the delayer to batch them up properly
			if (rawEvents.length > 0) {
				this.eventCallback(rawEvents);
			}
		});

		// Errors
		this.handle.on('error', (error: Error) => this.onError(error));
		this.handle.stderr!.on('data', (data: Buffer) => this.onError(data));

		// Exit
		this.handle.on('exit', (code: number, signal: string) => this.onExit(code, signal));
	}

	private onError(error: Error | Buffer): void {
		this.error('process error: ' + error.toString());
	}

	private onExit(code: number, signal: string): void {
		if (this.handle) { // exit while not yet being disposed is unexpected!
			this.error(`terminated unexpectedly (code: ${code}, signal: ${signal})`);

			if (this.restartCounter <= OutOfProcessWin32FolderWatcher.MAX_RESTARTS) {
				this.error('is restarted again...');
				this.restartCounter++;
				this.startWatcher(); // restart
			} else {
				this.error('Watcher failed to start after retrying for some time, giving up. Please report this as a bug report!');
			}
		}
	}

	private error(message: string) {
		this.logCallback({ type: 'error', message: `[File Watcher (C#)] ${message}` });
	}

	private log(message: string) {
		this.logCallback({ type: 'trace', message: `[File Watcher (C#)] ${message}` });
	}

	dispose(): void {
		if (this.handle) {
			this.handle.kill();
			this.handle = undefined;
		}
	}
}


text:
module Multidb
  class Candidate
    def initialize(name, target)
      @name = name

      case target
      when Hash
        @connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
        @connection_handler.establish_connection(target.merge(name: 'primary'))
      when ActiveRecord::ConnectionAdapters::ConnectionHandler
        @connection_handler = target
      else
        raise ArgumentError, 'Connection handler not passed to target'
      end
    end

    def connection(&block)
      if block_given?
        @connection_handler.retrieve_connection_pool('primary').with_connection(&block)
      else
        @connection_handler.retrieve_connection('primary')
      end
    end

    def disconnect!
      @connection_handler.clear_all_connections!
    end

    attr_reader :name
  end
end


text:
package com.github.ssindelar.ps2parser.data.character.friends;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Generated;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({ "last_login_time", "character_id", "online" })
public class ApiFriend {

	@JsonProperty("last_login_time")
	private String lastLoginTime;
	@JsonProperty("character_id")
	private String characterId;
	@JsonProperty("online")
	private String online;
	private Map<String, Object> additionalProperties = new HashMap<String, Object>();

	@JsonProperty("last_login_time")
	public String getLastLoginTime() {
		return this.lastLoginTime;
	}

	@JsonProperty("last_login_time")
	public void setLastLoginTime(String lastLoginTime) {
		this.lastLoginTime = lastLoginTime;
	}

	@JsonProperty("character_id")
	public String getCharacterId() {
		return this.characterId;
	}

	@JsonProperty("character_id")
	public void setCharacterId(String characterId) {
		this.characterId = characterId;
	}

	@JsonProperty("online")
	public String getOnline() {
		return this.online;
	}

	@JsonProperty("online")
	public void setOnline(String online) {
		this.online = online;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public boolean equals(Object other) {
		return EqualsBuilder.reflectionEquals(this, other);
	}

	@JsonAnyGetter
	public Map<String, Object> getAdditionalProperties() {
		return this.additionalProperties;
	}

	@JsonAnySetter
	public void setAdditionalProperties(String name, Object value) {
		this.additionalProperties.put(name, value);
	}

}


text:
package at.renehollander.advancedmanager.scripting.eventloop.defaultmodules;

import at.renehollander.advancedmanager.scripting.eventloop.module.Module;
import at.renehollander.advancedmanager.scripting.eventloop.module.NamedModule;
import at.renehollander.advancedmanager.scripting.eventloop.util.Function;

public class Require extends Module {

    public Require() {
    }

    public void load() {
        super.load();
        getEnviroment().getBindings().put("require", (Function.OneArg.WithReturn<Object, String>) this::require);
    }

    public Object require(String name) {
        NamedModule module = getEnviroment().getModuleNameMapping().get(name);
        if (module == null) {
            throw new RuntimeException("module \"" + name + "\" not found");
        }
        return module.getExports();
    }

}


text:
const authMiddleware = require('../helpers/authMiddleware.js')
const requestTable = require('../database/tables/requests.js')
const errorMessages = require('../constants/errorMessages.js');

module.exports = {
  method: 'GET',
  path:'/assign',
  config: {
    auth: {
      strategy: 'base'
    },
    pre: [
        { method: authMiddleware, assign: 'user' }
    ],
    handler: (req, reply) => {
      let request = {
        id: req.query.id,
        admin: req.query.admin
      };
      requestTable.updateAssigned(request, function (err, data) {
        if (err) {
          return reply.view('error', {
            error: errorMessages.databaseError
          });
        }
        reply.redirect('/dashboard');
      });
    }
  }
};


text:
**Back /Symfony2**

Download composer

    curl -s http://getcomposer.org/installer | php

Install dependencies

    php composer.phar install

Install Angular & dependencies

	php app/console sp:bower:install


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

<TITLE>
Cursor
</TITLE>

<META NAME="date" CONTENT="2011-05-13">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.appengine.api.datastore

Class Cursor

java.lang.Object
  com.google.appengine.api.datastore.Cursor

All Implemented Interfaces:
java.io.Serializable

public final class Cursor
extends java.lang.Object
implements java.io.Serializable

A cursor that represents a position in a query.

 To resume a Query at the position defined by a Cursor, the
 Cursor must be present in the FetchOptions passed to a PreparedQuery identical to the one it was created from.

 Cursors can be retrieved from PreparedQuery.asQueryResult* functions.
 A typical use case would be:

 Cursor originalCursor = preparedQuery.asQueryResultList(withLimit(20)).getCursor();
 String encodedCursor = original.toWebSafeString();

 The encoded cursor can then be passed safely in a get or post arg of a web
 request and on another request the next batch of results can be retrieved with:

 Cursor decodedCursor = Cursor.fromWebSafeString(encodedCursor);
 List<Entity> nextBatch = preparedQuery.asQueryResultList(withLimit(20).cursor(decoded));

See Also:
Serialized Form

Method Summary

 boolean
equals(java.lang.Object obj)

static Cursor
fromWebSafeString(java.lang.String encodedCursor)

          Decodes the given encoded cursor

 int
hashCode()

 java.lang.String
toString()

 java.lang.String
toWebSafeString()

          Encodes the current cursor as a web safe string that can later be decoded
 by fromWebSafeString(String)

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Method Detail

toWebSafeString

public java.lang.String toWebSafeString()

Encodes the current cursor as a web safe string that can later be decoded
 by fromWebSafeString(String)

fromWebSafeString

public static Cursor fromWebSafeString(java.lang.String encodedCursor)

Decodes the given encoded cursor

Parameters:
encodedCursor -

Returns:
the decoded cursor

Throws:

java.lang.IllegalArgumentException - if the provided string is not a valid encoded cursor

equals

public boolean equals(java.lang.Object obj)

Overrides:
equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
module Grape
  module Validations
    module Types
      # Implementation for parameters that are multipart file objects.
      # Actual handling of these objects is provided by +Rack::Request+;
      # this class is here only to assert that rack's handling has succeeded.
      class File
        class << self
          def parse(input)
            return if input.nil?
            return InvalidValue.new unless parsed?(input)

            # Processing of multipart file objects
            # is already taken care of by Rack::Request.
            # Nothing to do here.
            input
          end

          def parsed?(value)
            # Rack::Request creates a Hash with filename,
            # content type and an IO object. Do a bit of basic
            # duck-typing.
            value.is_a?(::Hash) && value.key?(:tempfile) && value[:tempfile].is_a?(Tempfile)
          end
        end
      end
    end
  end
end


text:
import React from 'react'
import {
  AsyncStorage,
  View,
  FlatList,
  Image,
  WebView,
} from 'react-native'
import Instagram from '@uppy/instagram'

function getQueryParamValueFromUrl (name, url) {
  // eslint-disable-next-line no-param-reassign
  name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]')
  const regexS = `[\\?&]${name}=([^&#]*)`
  const regex = new RegExp(regexS)
  const results = regex.exec(url)
  return results == null ? null : results[1]
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    flex: 1,
    paddingTop: 30,
  },
  item: {
    justifyContent: 'center',
    alignItems: 'center',
    height: 100,
  },
})

// how instagram provider can be render, not ready
export default class UppyRNInstagram extends React.Component {
  constructor () {
    super()

    this.state = {
      instagram: {
        user: 'bla@gmail.com',
        items: [
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/cats/1' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/cats/2' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/cats/3' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/cats/4' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/cats/5' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/' },
          { caption: Date.now(), url: 'http://lorempixel.com/200/200/' },
        ],
      },
    }
  }

  componentDidMount () {
    const { uppy } = this.props
    const options = {
      id: 'uppyRN:Instagram',
      ...this.props,
      storage: AsyncStorage,
    }
    delete options.uppy
    uppy.use(Instagram, options)
    this.plugin = uppy.getPlugin(options.id)

    this.setState({
      authUrl: this.plugin.provider.authUrl(),
    })
  }

  componentWillUnmount () {
    const { uppy } = this.props
    uppy.removePlugin(this.plugin)
  }

  // eslint-disable-next-line class-methods-use-this
  renderGrid (items) {
    return (
      <View style={styles.container}>
        <FlatList
          data={items}
          renderItem={({ item }) => (
            <View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
              <Image style={styles.item} source={{ uri: item.url }} />
            </View>
          )}
          keyExtractor={(item, index) => index.toString()}
          numColumns={3}
        />
      </View>
    )
  }

  renderInstagram () {
    return (
      <WebView
        source={{ uri: this.state.authUrl }}
        style={{ marginTop: 20 }}
        onNavigationStateChange={(ev) => {
          const { url } = ev
          const token = getQueryParamValueFromUrl('uppyAuthToken', url)
          this.plugin.provider.setAuthToken(token)
          // return this.renderGrid(this.state.instagram.items)
        }}
      />
    )
  }

  render () {
    return this.renderInstagram()
  }
}


text:
const _       = require('lodash');
const Stocks  = require('../stocks/model.js');

const growthRate = require('../../../lib/modules/timeseries/growthRate.js');

const getMetrics = (options) => {
  const instructions = {
    pipeline: [],
  };

  if(options.tickers) {
    const tickers = _.isArray(options.tickers) ? options.tickers : [options.tickers];

    instructions.pipeline.push({
      "$match": {
        "ticker": {
          "$in": tickers
        }
      }
    });
  }

  const projection = {
    "$project": {
      "ticker": 1,
    }
  };

  _.forEach(options.metrics, (path) => {
    projection['$project'][path] = 1;
  });

  instructions.pipeline.push(projection);

  return Stocks.aggregate(instructions);
};

const getEarnings = (tickers) => {
  const metrics = [
    "summary.annual.EarningsPerShareDiluted",
    "summary.annual.EarningsPerShareBasicAndDiluted",
  ];

  return getMetrics({ tickers, metrics })
    .then(data => _.map(data, prepareEarnings(metrics)))
};

const prepareEarnings = _.curry((metrics, data) => {
  const earnings = compromiseMetric(metrics, data);

  _.forEach(earnings, (earning, index) => {
    if(index === 0) {
      earning.growth = 0;
    } else {
      const previous = earnings[index-1].value;
      const current = earning.value;

      if(previous) {
        earning.growth = current/previous - 1;
      } else {
        earning.growth = 0;
      }
    }
  });

  return {
    ticker: _.get(data, 'ticker'),
    earnings,
    averages: calculateGrowthRatesByYear(earnings),
  };
});

const compromiseMetric = _.curry((metrics, content) => {
  return _
    .chain(metrics)
    .map((metric) => {
      const value = _.get(content, metric);

      if(_.isArray(value) && value.length > 0) {
        return value;
      }
    })
    .sortBy('length')
    .first()
    .value();
});

const calculateGrowthRatesByYear = (earnings) => {
  const rates = _.map(earnings, 'growth');

  return {
    'count': earnings.length,
    '1y': calculateAverageGrowthRate(rates, -1),
    '3y': calculateAverageGrowthRate(rates, -3),
    '5y': calculateAverageGrowthRate(rates, -5),
    '10y': calculateAverageGrowthRate(rates, -10),
    'all': calculateAverageGrowthRate(rates),
  };
};

const calculateAverageGrowthRate = (rates, position) => {
  return _.mean(position ? _.slice(rates, position) : rates);
};

module.exports = {
  getMetrics,

  getEarnings,
};


text:
describe WorldFlags do
	describe '.'

end


text:
package org.hisp.dhis.feedback;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.base.MoreObjects;
import org.hisp.dhis.common.DxfNamespaces;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@JacksonXmlRootElement( localName = "errorReport", namespace = DxfNamespaces.DXF_2_0 )
public class ErrorReport
{
    protected final ErrorMessage message;

    protected final Class<?> mainKlass;

    protected Class<?> errorKlass;

    protected Object value;

    public ErrorReport( Class<?> mainKlass, ErrorCode errorCode, Object... args )
    {
        this.mainKlass = mainKlass;
        this.message = new ErrorMessage( errorCode, args );
    }

    public ErrorReport( Class<?> mainKlass, ErrorMessage message )
    {
        this.mainKlass = mainKlass;
        this.message = message;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public ErrorCode getErrorCode()
    {
        return message.getErrorCode();
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getMessage()
    {
        return message.getMessage();
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Class<?> getMainKlass()
    {
        return mainKlass;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Class<?> getErrorKlass()
    {
        return errorKlass;
    }

    public ErrorReport setErrorKlass( Class<?> errorKlass )
    {
        this.errorKlass = errorKlass;
        return this;
    }

    @JsonProperty
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Object getValue()
    {
        return value;
    }

    public ErrorReport setValue( Object value )
    {
        this.value = value;
        return this;
    }

    @Override
    public String toString()
    {
        return MoreObjects.toStringHelper( this )
            .add( "message", getMessage() )
            .add( "errorCode", message.getErrorCode() )
            .add( "mainKlass", mainKlass )
            .add( "errorKlass", errorKlass )
            .add( "value", value )
            .toString();
    }
}


text:
function [ f ] = func_measure( f, i, meas_vec, sel_meas )
%FUNC_MEASURE Measurement update for linear measurement function.
% sel_meas corresponds to the selected measurement (core temperature vs.
% surface left/middle/right)

f.P = f.A_d*f.P*f.A_d' + f.Q;           	 % prediction update covariance
K = (f.C(sel_meas,:)*f.P*f.C(sel_meas,:)'+f.R)...             % Kalman gain
    \(f.P*f.C(sel_meas,:)');
f.x(i+1,:) = f.x(i+1,:)' ...                     % Measurement update state
    + K*(meas_vec(sel_meas) - f.y(i,sel_meas)');
f.P = f.P - K*f.C(sel_meas,:)*f.P;          % Measurement update covariance

end


text:
import {A4AVariableSource} from '../a4a-variable-source';
import {createIframePromise} from '../../../../testing/iframe';
import {installDocumentInfoServiceForDoc} from
  '../../../../src/service/document-info-impl';

describe('A4AVariableSource', () => {

  let varSource;

  beforeEach(() => {
    return createIframePromise().then(iframe => {
      iframe.doc.title = 'Pixel Test';
      const link = iframe.doc.createElement('link');
      link.setAttribute('href', 'https://pinterest.com:8080/pin1');
      link.setAttribute('rel', 'canonical');
      iframe.doc.head.appendChild(link);
      installDocumentInfoServiceForDoc(iframe.ampdoc);
      varSource = new A4AVariableSource(iframe.ampdoc, iframe.win);
    });
  });

  function expandAsync(varName, opt_params) {
    return varSource.get(varName).async.apply(null, opt_params);
  }

  function expandSync(varName, opt_params) {
    return varSource.get(varName).sync.apply(null, opt_params);
  }

  it('should replace RANDOM', () => {
    expect(expandSync('RANDOM')).to.match(/(\d+(\.\d+)?)$/);
  });

  it('should replace CANONICAL_URL', () => {
    expect(expandSync('CANONICAL_URL'))
        .to.equal('https://pinterest.com:8080/pin1');
  });

  it('should replace AD_NAV_TIMING', () => {
    expect(expandSync('AD_NAV_TIMING', ['navigationStart'])).to.match(/\d+/);
    return expandAsync('AD_NAV_TIMING', ['navigationStart']).then(val =>
      expect(val).to.match(/\d+/)
    );
  });

  it('should replace AD_NAV_TYPE', () => {
    expect(expandSync('AD_NAV_TYPE')).to.match(/\d/);
  });

  it('should replace AD_NAV_REDIRECT_COUNT', () => {
    expect(expandSync('AD_NAV_REDIRECT_COUNT')).to.match(/\d/);
  });

  it('should replace HTML_ATTR', () => {
    expect(expandSync('HTML_ATTR', ['div', 'id'])).to.equal(
        '[{\"id\":\"parent\"}]');
  });

  it('should replace CLIENT_ID with null', () => {
    return expect(expandSync('CLIENT_ID', ['a'])).to.be.null;
  });

  function undefinedVariable(varName) {
    it('should not replace ' + varName, () => {
      expect(varSource.get(varName)).to.be.undefined;
    });
  }

  // Performance timing info.
  undefinedVariable('NAV_TIMING');
  undefinedVariable('NAV_TYPE');
  undefinedVariable('NAV_REDIRECT_COUNT');
  undefinedVariable('PAGE_LOAD_TIME');
  undefinedVariable('DOMAIN_LOOKUP_TIME');
  undefinedVariable('TCP_CONNECT_TIME');
  undefinedVariable('SERVER_RESPONSE_TIME');
  undefinedVariable('PAGE_DOWNLOAD_TIME');
  undefinedVariable('REDIRECT_TIME');
  undefinedVariable('DOM_INTERACTIVE_TIME');
  undefinedVariable('CONTENT_LOAD_TIME');

  // Access data.
  undefinedVariable('ACCESS_READER_ID');
  undefinedVariable('AUTHDATA');

  // amp-bind state.
  // AMP_STATE() is not scoped to the FIE so this cannot be safely removed
  // without refactoring the implementation in url-replacements-impl.js.
  undefinedVariable('AMP_STATE');
});


text:
/*
 | This file is part of the DITA Open Toolkit project hosted on
 | Sourceforge.net. See the accompanying license.txt file for
 | applicable licenses.
*/

/*
 | (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved.
 */

/*
 * The Oxygen WebHelp Plugin redistributes this file under the terms of the
 * Apache Software Foundation License v2.0:
 *
 * http://opensource.org/licenses/apache2.0.php
 */

.unresolved { background-color: skyblue; }
.noTemplate { background-color: yellow; }

.base { background-color: #ffffff; }

/* Default of italics to set apart figure captions */
.figcap { font-style: italic }
.figdesc { font-style: normal }

/* Use @frame to create frames on figures */
.figborder { border-style: solid; padding-left : 3px; border-width : 2px; padding-right : 3px; margin-top: 1em; border-color : Silver;}
.figsides { border-left : 2px solid; padding-left : 3px; border-right : 2px solid; padding-right : 3px; margin-top: 1em; border-color : Silver;}
.figtop { border-top : 2px solid; margin-top: 1em; border-color : Silver;}
.figbottom { border-bottom : 2px solid; border-color : Silver;}
.figtopbot { border-top : 2px solid; border-bottom : 2px solid; margin-top: 1em; border-color : Silver;}

/* Most link groups are created with <div>. Ensure they have space before and after. */
.ullinks { list-style-type: none }
.ulchildlink { margin-top: 1em; margin-bottom: 1em }
.olchildlink { margin-top: 1em; margin-bottom: 1em }
.linklist { margin-bottom: 1em }
.linklistwithchild { margin-bottom: 1em  }
.sublinklist { margin-bottom: 1em  }
.relconcepts { margin-top: 1em; margin-bottom: 1em }
.reltasks { margin-top: 1em; margin-bottom: 1em }
.relref { margin-top: 1em; margin-bottom: 1em }
.relinfo { margin-top: 1em; margin-bottom: 1em }
.breadcrumb { font-size : smaller; margin-bottom: 1em }
dt.prereq { margin-left : 20px;}

/* Set heading sizes, getting smaller for deeper nesting */
.topictitle1 { margin-top: 0; margin-bottom: .1em; font-size: 1.34em; }
.topictitle2 { margin-top: 1pc; margin-bottom: .45em; font-size: 1.17em; }
.topictitle3 { margin-top: 1pc; margin-bottom: .17em; font-size: 1.17em; font-weight: bold; }
.topictitle4 { margin-top: .83em; font-size: 1.17em; font-weight: bold; }
.topictitle5 { font-size: 1.17em; font-weight: bold; }
.topictitle6 { font-size: 1.17em; font-style: italic; }
.sectiontitle { margin-top: 1em; margin-bottom: 0; color: black; font-size: 1.17em; font-weight: bold;}
.section { margin-top: 1em; margin-bottom: 1em }
.example { margin-top: 1em; margin-bottom: 1em }
div.tasklabel { margin-top: 1em; margin-bottom: 1em; }
h2.tasklabel, h3.tasklabel, h4.tasklabel, h5.tasklabel, h6.tasklabel { font-size: 100%; }

/* All note formats have the same default presentation */
.note { margin-top: 1em; margin-bottom : 1em;}
.notetitle { font-weight: bold }
.notelisttitle { font-weight: bold }
.tip { margin-top: 1em; margin-bottom : 1em;}
.tiptitle { font-weight: bold }
.fastpath { margin-top: 1em; margin-bottom : 1em;}
.fastpathtitle { font-weight: bold }
.important { margin-top: 1em; margin-bottom : 1em;}
.importanttitle { font-weight: bold }
.remember { margin-top: 1em; margin-bottom : 1em;}
.remembertitle { font-weight: bold }
.restriction { margin-top: 1em; margin-bottom : 1em;}
.restrictiontitle { font-weight: bold }
.attention { margin-top: 1em; margin-bottom : 1em;}
.attentiontitle { font-weight: bold }
.dangertitle { font-weight: bold }
.danger { margin-top: 1em; margin-bottom : 1em;}
.cautiontitle { font-weight: bold }
.caution { font-weight: bold; margin-bottom : 1em; }
.warningtitle { font-weight: bold }
.warning { margin-top: 1em; margin-bottom : 1em;}

/* Simple lists do not get a bullet */
ul.simple { list-style-type: none }

/* Used on the first column of a table, when rowheader="firstcol" is used */
.firstcol { font-weight : bold;}

/* Various basic phrase styles */
.bold { font-weight: bold; }
.boldItalic { font-weight: bold; font-style: italic; }
.italic { font-style: italic; }
.underlined { text-decoration: underline; }
.uicontrol, .wintitle { font-weight: bold; }
.parmname { font-weight: bold; }
.kwd { font-weight: bold; }
.defkwd { font-weight: bold; text-decoration: underline; }
.var { font-style : italic;}
.shortcut { text-decoration: underline; }

/* Default of bold for definition list terms */
.dlterm { font-weight: bold; }

/* Use CSS to expand lists with @compact="no" */
.dltermexpand { font-weight: bold; margin-top: 1em; }
*[compact="yes"]>li { margin-top: 0;}
*[compact="no"]>li { margin-top: .53em;}
.liexpand { margin-top: 1em; margin-bottom: 1em }
.sliexpand { margin-top: 1em; margin-bottom: 1em }
.dlexpand { margin-top: 1em; margin-bottom: 1em }
.ddexpand { margin-top: 1em; margin-bottom: 1em }
.stepexpand { margin-top: 1em; margin-bottom: 1em }
.substepexpand { margin-top: 1em; margin-bottom: 1em }

/* Align images based on @align on topic/image */
div.imageleft { text-align: left }
div.imagecenter { text-align: center }
div.imageright { text-align: right }
div.imagejustify { text-align: justify }

pre.screen { padding:5px; border: 1px solid #ccc; background-color: #ddd; margin: 2px 0 2px 0; white-space: pre}

span.filepath { font-family:monospace }

/* The cell border can be turned on with
   {border-right:solid}
   This value creates a very thick border in Firefox (does not match other tables)

   Firefox works with
   {border-right:solid 1pt}
   but this causes a barely visible line in IE */

.cellrowborder { border-top:none; border-bottom:solid 1px }

.cellrowborder,
*[dir] *[dir='ltr'] .cellrowborder,
*[dir] *[dir] *[dir='ltr'] .cellrowborder,
*[dir] *[dir] *[dir] *[dir='ltr'] .cellrowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .cellrowborder{
	border-top:none;
	border-bottom:solid 1px;
	border-right:solid 1px;
	border-left:none;
}
*[dir='rtl'] .cellrowborder,
*[dir] *[dir='rtl'] .cellrowborder,
*[dir] *[dir] *[dir='rtl'] .cellrowborder,
*[dir] *[dir] *[dir] *[dir='rtl'] .cellrowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .cellrowborder{
	border-top:none;
	border-bottom:solid 1px;
	border-right:none;
	border-left:solid 1px;
}

.cell-norowborder { border-top:none; border-bottom:none; border-bottom: hidden; }

.cell-norowborder,
*[dir] *[dir='ltr'] .cell-norowborder,
*[dir] *[dir] *[dir='ltr'] .cell-norowborder,
*[dir] *[dir] *[dir] *[dir='ltr'] .cell-norowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .cell-norowborder{
     border-top:none; border-bottom:none; border-bottom: hidden;
	 border-right:solid 1px;
	 border-left:none;
}
*[dir='rtl'] .cell-norowborder,
*[dir] *[dir='rtl'] .cell-norowborder,
*[dir] *[dir] *[dir='rtl'] .cell-norowborder,
*[dir] *[dir] *[dir] *[dir='rtl'] .cell-norowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .cell-norowborder{
	 border-top:none; border-bottom:none; border-bottom: hidden;
	 border-right:none;
	 border-left:solid 1px;
}

.nocellnorowborder { border:none; border-bottom: hidden }

.nocellnorowborder,
*[dir] *[dir='ltr'] .nocellnorowborder,
*[dir] *[dir] *[dir='ltr'] .nocellnorowborder,
*[dir] *[dir] *[dir] *[dir='ltr'] .nocellnorowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .nocellnorowborder{
	border:none; border-bottom: hidden;
	border-right:hidden;
	border-left:none;
}
*[dir='rtl'] .nocellnorowborder,
*[dir] *[dir='rtl'] .nocellnorowborder,
*[dir] *[dir] *[dir='rtl'] .nocellnorowborder,
*[dir] *[dir] *[dir] *[dir='rtl'] .nocellnorowborder,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .nocellnorowborder{
	border:none; border-bottom: hidden;
	border-left:hidden;
	border-right:none;
}

.row-nocellborder {  border-top:none; border-bottom:solid 1px}

.row-nocellborder,
*[dir] *[dir='ltr'] .row-nocellborder,
*[dir] *[dir] *[dir='ltr'] .row-nocellborder,
*[dir] *[dir] *[dir] *[dir='ltr'] .row-nocellborder,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .row-nocellborder{
	border-top:none; border-bottom:solid 1px;
	border-left:none;
	border-right:hidden;
}
*[dir='rtl'] .row-nocellborder,
*[dir] *[dir='rtl'] .row-nocellborder,
*[dir] *[dir] *[dir='rtl'] .row-nocellborder,
*[dir] *[dir] *[dir] *[dir='rtl'] .row-nocellborder,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .row-nocellborder{
	border-top:none; border-bottom:solid 1px;
	border-left: hidden;
	border-right:none;
}

/*

 The right and left margins, padding, borders depend on the direction.

 */
pre.screen,
*[dir] *[dir='ltr'] pre.screen,
*[dir] *[dir] *[dir='ltr'] pre.screen,
*[dir] *[dir] *[dir] *[dir='ltr'] pre.screen,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] pre.screen{
	margin-right:0;
	margin-left:7px;
}

*[dir='rtl'] pre.screen,
*[dir] *[dir='rtl'] pre.screen,
*[dir] *[dir] *[dir='rtl'] pre.screen,
*[dir] *[dir] *[dir] *[dir='rtl'] pre.screen,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] pre.screen{
	margin-right:7px;
	margin-left:0;
}

dt.prereq,
*[dir] *[dir='ltr'] dt.prereq,
*[dir] *[dir] *[dir='ltr'] dt.prereq,
*[dir] *[dir] *[dir] *[dir='ltr'] dt.prereq,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] dt.prereq{

	margin-left:20px;
	margin-right:0;
}
*[dir='rtl'] dt.prereq,
*[dir] *[dir='rtl'] dt.prereq,
*[dir] *[dir] *[dir='rtl'] dt.prereq,
*[dir] *[dir] *[dir] *[dir='rtl'] dt.prereq,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] dt.prereq{
	margin-left:0;
	margin-right:20px;
}

.linklistwithchild,
*[dir] *[dir='ltr'] .linklistwithchild,
*[dir] *[dir] *[dir='ltr'] .linklistwithchild,
*[dir] *[dir] *[dir] *[dir='ltr'] .linklistwithchild,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .linklistwithchild{
	margin-left:1.5em;
	margin-right: 0;
}
*[dir='rtl'] .linklistwithchild,
*[dir] *[dir='rtl'] .linklistwithchild,
*[dir] *[dir] *[dir='rtl'] .linklistwithchild,
*[dir] *[dir] *[dir] *[dir='rtl'] .linklistwithchild,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .linklistwithchild{
	margin-left:0;
	margin-right: 1.5em;
}

.sublinklist,
*[dir] *[dir='ltr'] .sublinklist,
*[dir] *[dir] *[dir='ltr'] .sublinklist,
*[dir] *[dir] *[dir] *[dir='ltr'] .sublinklist,
*[dir] *[dir] *[dir] *[dir] *[dir='ltr'] .sublinklist{
	margin-left:1.5em;
	margin-right:0;
}
*[dir='rtl'] .sublinklist,
*[dir] *[dir='rtl'] .sublinklist,
*[dir] *[dir] *[dir='rtl'] .sublinklist,
*[dir] *[dir] *[dir] *[dir='rtl'] .sublinklist,
*[dir] *[dir] *[dir] *[dir] *[dir='rtl'] .sublinklist{
	margin-left:0;
	margin-right: 1.5em;
}


text:
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);
var webpackHotMiddleware = require("webpack-hot-middleware");

 //cors and preflight filtering
 /*app.all('*', function(req, res, next){.. //preflight needs to return exact request-header
 res.set('Access-Control-Allow-Headers',
 req.headers['access-control-request-headers']);
 if ('OPTIONS' == req.method) return res.send(204);next(); });
 */
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  hot: true,
  historyApiFallback: true,
  filename: 'bundle.js',
  stats: {
    colors: true,
  },
  publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000,
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(7770, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:7770');
});


text:
import {Directive, ElementRef, Renderer} from 'angular2/core'

@Directive({
    selector: '[autoGrow]',
    host: {
        '(focus)': 'onFocus()',
        '(blur)':'onBlur()'
    }
})
export class AutoGrowDirective {

    constructor(private ele:ElementRef, private renderer: Renderer){

    }

    onFocus(){
        this.renderer.setElementStyle(this.ele.nativeElement, 'width','200');
    }

    onBlur(){
        this.renderer.setElementStyle(this.ele.nativeElement, 'width','120');
    }
}


text:
'use strict';

var IngestSDK = require('../../src/index');
var mock = require('xhr-mock');

var api = new IngestSDK();
var profilesResource;

describe('Ingest API : Resource : Profiles', function () {

  beforeEach(function () {
    profilesResource = new api.profilesResource({
      host: api.config.host,
      resource: 'encoding/profiles',
      tokenSource: api.getToken.bind(api)
    });
  });

  describe('update', function () {

    it('Should fail if no resource are passed in.', function (done) {

      var request = profilesResource.update().then(function (response) {

        expect(response).toBeUndefined();

        done();

      }, function (error) {

        expect(error).toBeDefined();

        done();

      });

      // Ensure a promise was returned.
      expect(request.then).toBeDefined();

    });

    it('Should update a profile record.', function (done) {

      var profile = {
        id: 'test-profile'
      };

      // Mock the XHR object
      mock.setup();

      mock.mock('PUT', api.config.host + '/encoding/profiles/test-profile',
        function (request, response) {

          var _profile = JSON.stringify(profile);

          // Restore the XHR Object
          mock.teardown();

          expect(_profile).toEqual(request._body);

          return response.status(200)
            .header('Content-Type', 'application/json')
            .header('Content-Length', 1)
            .body(_profile);

        });

      var request = profilesResource.update(profile).then(function (response) {

        expect(response).toBeDefined();
        expect(response.data.id).toEqual('test-profile');
        done();

      }, function (error) {

        expect(error).toBeUndefined();
        done();

      });

      // Ensure a promise was returned.
      expect(request.then).toBeDefined();

    });

    it('Should fail to update a profile if something other than an object is passed',
      function (done) {

        var request = profilesResource.update('profile').then(function (response) {

          expect(response).toBeUndefined();
          done();

        }, function (error) {

          expect(error).toBeDefined();
          done();

        });

        // Ensure a promise was returned.
        expect(request.then).toBeDefined();

      });
  });
});


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function calling itself recursively
 *
 * @path ch13/13.0/S13_A3_T3.js
 * @description Creating simple recursive function that calculates factorial
 */

function __func(arg){
    if (arg === 1) {
    	return arg;
    } else {
    	return __func(arg-1)*arg;
    }
};

var fact_of_3 =  __func(3);

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (fact_of_3 !== 6) {
	$ERROR("#1: fact_of_3 === 6. Actual: fact_of_3 ==="+fact_of_3);
}
//
//////////////////////////////////////////////////////////////////////////////


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<title>Sign in</title>
	<link href="css/login.css" rel="stylesheet" type="text/css">

	<form method="post" action="login.php">

Sign in

		<input type="text" name="username" placeholder="username" autofocus required="required">
		<input type="password" name="password" placeholder="password" required="required">
		<button type="submit">Login</button>
	</form>


text:
This addon that adds `ic-ajax` to the generated Ember CLI output (in `vendor.js`).

## Deprecation

This addon is deprecated in favor of `ember-ajax`. You can can read more about
the reasons for this deprecation and how to migrate at the
[`ember-ajax` README](https://github.com/ember-cli/ember-ajax#upgrade-from-ic-ajax).

### Installation / Usage

From within your Ember CLI application (must be > 0.0.34), run the following:

```bash
npm install --save-dev ember-cli-ic-ajax
```

### References

* [ic-ajax](https://github.com/instructure/ic-ajax)


text:
package org.cleartk.ml.feature.transform.extractor;

import static org.cleartk.ml.ClassifierTestUtil.assertFeature;
import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.apache.uima.jcas.tcas.DocumentAnnotation;
import org.cleartk.ml.Feature;
import org.cleartk.ml.Instance;
import org.cleartk.ml.feature.extractor.CleartkExtractor;
import org.cleartk.ml.feature.extractor.CoveredTextExtractor;
import org.cleartk.ml.feature.transform.TransformableFeature;
import org.cleartk.test.util.DefaultTestBase;
import org.cleartk.test.util.type.Token;
import org.junit.Test;

/**
 * Copyright (c) 2014, Regents of the University of Colorado <br>
 * All rights reserved.
 *
 * @author Philip Ogren
 *
 */

public class ZeroMeanUnitStddevExtractorTest extends DefaultTestBase {

  @Test
  public void testBasic() throws Exception {
    CleartkExtractor<DocumentAnnotation, Token> countsExtractor = new CleartkExtractor<DocumentAnnotation, Token>(
        Token.class,
        new CoveredTextExtractor<Token>(),
        new CleartkExtractor.Count(new CleartkExtractor.Covered()));

    ZeroMeanUnitStddevExtractor<String, DocumentAnnotation> zmusExtractor = new ZeroMeanUnitStddevExtractor<String, DocumentAnnotation>(
        "MinMax",
        countsExtractor);

    this.tokenBuilder.buildTokens(this.jCas, "a b b c c c d d d d e e e e e");

    DocumentAnnotation doc = (DocumentAnnotation) jCas.getDocumentAnnotationFs();
    List<Feature> features = zmusExtractor.extract(jCas, doc);
    Instance<String> instance1 = new Instance<String>(features);
    assertEquals(1, features.size());
    assertEquals(TransformableFeature.class.getName(), features.get(0).getClass().getName());
    assertEquals("MinMax", features.get(0).getName());

    features = ((TransformableFeature) (features.get(0))).getFeatures();
    assertFeature("Count_Covered_a", 1, features.get(0));
    assertFeature("Count_Covered_b", 2, features.get(1));
    assertFeature("Count_Covered_c", 3, features.get(2));
    assertFeature("Count_Covered_d", 4, features.get(3));
    assertFeature("Count_Covered_e", 5, features.get(4));

    jCas.reset();
    this.tokenBuilder.buildTokens(this.jCas, "a a a a a a a a b c c c d d e e");
    doc = (DocumentAnnotation) jCas.getDocumentAnnotationFs();
    features = zmusExtractor.extract(jCas, doc);
    Instance<String> instance2 = new Instance<String>(features);
    assertEquals(1, features.size());
    assertEquals(TransformableFeature.class.getName(), features.get(0).getClass().getName());
    assertEquals("MinMax", features.get(0).getName());

    features = ((TransformableFeature) (features.get(0))).getFeatures();
    assertFeature("Count_Covered_a", 8, features.get(0));
    assertFeature("Count_Covered_b", 1, features.get(1));
    assertFeature("Count_Covered_c", 3, features.get(2));
    assertFeature("Count_Covered_d", 2, features.get(3));
    assertFeature("Count_Covered_e", 2, features.get(4));

    // train on two instances
    Iterable<Instance<String>> instances = Arrays.asList(instance1, instance2);
    zmusExtractor.train(instances);

    jCas.reset();
    this.tokenBuilder.buildTokens(this.jCas, "a a b b b c c c d d d e f f f f");
    doc = (DocumentAnnotation) jCas.getDocumentAnnotationFs();
    features = zmusExtractor.extract(jCas, doc);
    features = zmusExtractor.extract(jCas, doc);
    assertEquals(4, features.size());
    // zmus = (value - stats.mean) / stats.stddev;
    // mean(a) = 4.5, stddev(a) = 3.5
    // (2 - 4.5) / 3.5
    assertFeature("ZMUS_Count_Covered_a", -0.7142857142857143d, features.get(0));
    // mean(b) = 1.5, stddev(b) = .5
    // (3 - 1.5) / .5
    assertFeature("ZMUS_Count_Covered_b", 3.0d, features.get(1));
    // zmus(c) = undefined because stddev == 0 - so no feature for that one
    // mean(d) = 3, stddev(d) = 1
    // (3 - 3) / 1
    assertFeature("ZMUS_Count_Covered_d", 0.0d, features.get(2));
    // mean(e) = 3.5, stddev(e) = 1.5
    // (1 - 3.5) / 1.5
    assertFeature("ZMUS_Count_Covered_e", -1.6666667d, features.get(3));
    // mmn(f) = undefined - so no feature for that one
  }

}


text:
// Header for CPrefsDisplayStyles class

#ifndef __CPREFSDISPLAYSTYLES__MULBERRY__
#define __CPREFSDISPLAYSTYLES__MULBERRY__

#include "CPrefsDisplayPanel.h"

// Constants

// Panes
const	PaneIDT		paneid_PrefsDisplayStyles = 5044;
const	PaneIDT		paneid_DSURLColor = 'UCOL';
const	PaneIDT		paneid_DSURLBold = 'UBLD';
const	PaneIDT		paneid_DSURLItalic = 'UITL';
const	PaneIDT		paneid_DSURLUnderline = 'UUND';
const	PaneIDT		paneid_DSURLSeenColor = 'VCOL';
const	PaneIDT		paneid_DSURLSeenBold = 'VBLD';
const	PaneIDT		paneid_DSURLSeenItalic = 'VITL';
const	PaneIDT		paneid_DSURLSeenUnderline = 'VUND';
const	PaneIDT		paneid_DSHeaderColor = 'HCOL';
const	PaneIDT		paneid_DSHeaderBold = 'HBLD';
const	PaneIDT		paneid_DSHeaderItalic = 'HITL';
const	PaneIDT		paneid_DSHeaderUnderline = 'HUND';
const	PaneIDT		paneid_DSTagColor = 'TCOL';
const	PaneIDT		paneid_DSTagBold = 'TBLD';
const	PaneIDT		paneid_DSTagItalic = 'TITL';
const	PaneIDT		paneid_DSTagUnderline = 'TUND';
const	PaneIDT		paneid_DSURLs = 'URLs';

// Mesages

// Resources

// Classes
class CTextDisplay;

struct SStyleTraits;

class	CPrefsDisplayStyles : public CPrefsDisplayPanel
{
private:
	SStyleItems		mURL;
	SStyleItems		mURLSeen;
	SStyleItems		mHeader;
	SStyleItems		mTag;
	CTextDisplay*	mURLs;

public:
	enum { class_ID = 'Dsty' };

					CPrefsDisplayStyles();
					CPrefsDisplayStyles(LStream *inStream);
	virtual 		~CPrefsDisplayStyles();

protected:
	virtual void	FinishCreateSelf(void);					// Do odds & ends

public:
	virtual void	SetData(void* data);			// Set data
	virtual void	UpdateData(void* data);			// Force update of data
};

#endif


text:
import React from 'react';
import 'styles/core.scss';

export default class CoreLayout extends React.Component {
  static propTypes = {
    children : React.PropTypes.element
  }

  constructor () {
    super();
  }

  render () {
    return (
      <div className="container">
        {this.props.children}
      </div>
    );
  }
}


text:
package main

func Main() { main() }


text:
package org.wso2.xml;

import javax.xml.stream.XMLStreamException;

public interface AsyncReaderWrapper {
    String currentText() throws XMLStreamException;

    int currentToken() throws XMLStreamException;

    int nextToken() throws XMLStreamException;
}


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCollectionDelegate = createCollectionDelegate;

var _bind2 = require('fast.js/function/bind');

var _bind3 = _interopRequireDefault(_bind2);

var _forEach = require('fast.js/forEach');

var _forEach2 = _interopRequireDefault(_forEach);

var _map2 = require('fast.js/map');

var _map3 = _interopRequireDefault(_map2);

var _keys2 = require('fast.js/object/keys');

var _keys3 = _interopRequireDefault(_keys2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Collection = typeof window !== 'undefined' && window.Mars ? window.Mars.Collection : require('marsdb').Collection;

function createCollectionDelegate(connection) {
  var _currentDelegateClass = Collection.defaultDelegate();

  /**
   * Collection manager is a factory for Mars.Collection
   * objects (one object by collection name).
   * It also syncing client/server changes.
   */

  var CollectionManager = function (_currentDelegateClass2) {
    _inherits(CollectionManager, _currentDelegateClass2);

    function CollectionManager() {
      var _Object$getPrototypeO;

      _classCallCheck(this, CollectionManager);

      for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var _this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(CollectionManager)).call.apply(_Object$getPrototypeO, [this].concat(args)));

      connection.on('status:connected', (0, _bind3.default)(_this._handleConnected, _this));
      connection.on('message:added', (0, _bind3.default)(_this._handleRemoteAdded, _this));
      connection.on('message:changed', (0, _bind3.default)(_this._handleRemoteChanged, _this));
      connection.on('message:removed', (0, _bind3.default)(_this._handleRemoteRemoved, _this));

      // For ensure that collection is initialized
      process.nextTick(function () {
        if (connection.isConnected) {
          _this._handleConnected(false);
        }
      });
      return _this;
    }

    /**
     * Calls remote method `/_collection_name_/insert`. It reverts back
     * optimistic update on server fail. It also have some options
     * to customize working approach:
     * `retryOnDisconnect` option retry method call if it was failed
     * 										 because dicsonnection. Default is true.
     * `waitResult` option disable optimistic update of the collection.
     * 							Returned Promise will be resolved when server returns
     * 							the result.
     * @param  {Object}  doc
     * @param  {Boolean} options.retryOnDisconnect
     * @param  {Boolean} options.waitResult
     * @param  {Object}  randomId
     * @return {Promise}
     */

    _createClass(CollectionManager, [{
      key: 'insert',
      value: function insert(doc) {
        var _this2 = this;

        var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
        var randomId = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

        var localInsert = _get(Object.getPrototypeOf(CollectionManager.prototype), 'insert', this).call(this, doc, options, randomId);
        var quiet = options.quiet;
        var _options$retryOnDisco = options.retryOnDisconnect;
        var retryOnDisconnect = _options$retryOnDisco === undefined ? true : _options$retryOnDisco;
        var waitResult = options.waitResult;

        if (!quiet) {
          var methodName = '/' + this.db.modelName + '/insert';
          var applyOpts = {
            retryOnDisconnect: !!retryOnDisconnect,
            randomSeed: randomId.seed
          };
          var result = connection.methodManager.apply(methodName, [doc], applyOpts).then(null, function (e) {
            return localInsert.then(function () {
              return _this2.db.remove(doc._id, { quiet: true });
            }).then(function () {
              throw e;
            });
          });

          if (waitResult) {
            return result.then(function () {
              return localInsert;
            });
          }
        }

        return localInsert;
      }

      /**
       * Calls remote method `/_collection_name_/remove`. It reverts back
       * optimistic update on server fail. It also have some options
       * to customize working approach:
       * `retryOnDisconnect` option retry method call if it was failed
       * 										 because dicsonnection. Default is true.
       * `waitResult` option disable optimistic update of the collection.
       * 							Returned Promise will be resolved when server returns
       * 							the result.
       * @param  {Object}  doc
       * @param  {Boolean} options.retryOnDisconnect
       * @param  {Boolean} options.waitResult
       * @param  {Object}  randomId
       * @return {Promise}
       */

    }, {
      key: 'remove',
      value: function remove(query) {
        var _this3 = this;

        var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

        var localRemove = _get(Object.getPrototypeOf(CollectionManager.prototype), 'remove', this).call(this, query, options);
        var quiet = options.quiet;
        var _options$retryOnDisco2 = options.retryOnDisconnect;
        var retryOnDisconnect = _options$retryOnDisco2 === undefined ? true : _options$retryOnDisco2;
        var waitResult = options.waitResult;

        if (!quiet) {
          var methodName = '/' + this.db.modelName + '/remove';
          var applyOpts = { retryOnDisconnect: !!retryOnDisconnect };
          var result = connection.methodManager.apply(methodName, [query], applyOpts).then(null, function (e) {
            return localRemove.then(function (remDocs) {
              return _this3.db.insertAll(remDocs, { quiet: true });
            }).then(function () {
              throw e;
            });
          });

          if (waitResult) {
            return result.then(function () {
              return localRemove;
            });
          }
        }

        return localRemove;
      }

      /**
       * Calls remote method `/_collection_name_/update`. It reverts back
       * optimistic update on server fail. It also have some options
       * to customize working approach:
       * `retryOnDisconnect` option retry method call if it was failed
       * 										 because dicsonnection. Default is true.
       * `waitResult` option disable optimistic update of the collection.
       * 							Returned Promise will be resolved when server returns
       * 							the result.
       * @param  {Object}  doc
       * @param  {Boolean} options.retryOnDisconnect
       * @param  {Boolean} options.waitResult
       * @param  {Object}  randomId
       * @return {Promise}
       */

    }, {
      key: 'update',
      value: function update(query, modifier) {
        var _this4 = this;

        var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];

        var localUpdate = _get(Object.getPrototypeOf(CollectionManager.prototype), 'update', this).call(this, query, modifier, options);
        var quiet = options.quiet;
        var _options$retryOnDisco3 = options.retryOnDisconnect;
        var retryOnDisconnect = _options$retryOnDisco3 === undefined ? true : _options$retryOnDisco3;
        var waitResult = options.waitResult;

        var otherOpts = _objectWithoutProperties(options, ['quiet', 'retryOnDisconnect', 'waitResult']);

        if (!quiet) {
          var methodName = '/' + this.db.modelName + '/update';
          var applyOpts = { retryOnDisconnect: !!retryOnDisconnect };
          var result = connection.methodManager.apply(methodName, [query, modifier, otherOpts], applyOpts).then(null, function (e) {
            return localUpdate.then(function (res) {
              return (0, _map3.default)(res.updated, function (d, i) {
                if (!res.original[i]) {
                  return _this4.db.remove(d._id, { quiet: true });
                } else {
                  var docId = res.original[i]._id;
                  delete res.original[i]._id;
                  return _this4.db.update({ _id: docId }, res.original[i], { quiet: true, upsert: true });
                }
              });
            }).then(function () {
              throw e;
            });
          });

          if (waitResult) {
            return result.then(function () {
              return localUpdate;
            });
          }
        }

        return localUpdate;
      }
    }, {
      key: '_handleConnected',
      value: function _handleConnected(reconnected) {
        var _this5 = this;

        var methodName = '/' + this.db.modelName + '/sync';
        return this.db.ids().then(function (ids) {
          return connection.methodManager.apply(methodName, [ids]).result();
        }).then(function (removedIds) {
          return _this5.db.remove({ _id: { $in: removedIds } }, { quiet: true, multi: true });
        });
      }
    }, {
      key: '_handleRemoteAdded',
      value: function _handleRemoteAdded(msg) {
        if (msg.collection === this.db.modelName) {
          delete msg.fields._id;
          return this.db.update({ _id: msg.id }, msg.fields, { quiet: true, upsert: true });
        } else {
          return Promise.resolve();
        }
      }
    }, {
      key: '_handleRemoteChanged',
      value: function _handleRemoteChanged(msg) {
        var _this6 = this;

        if (msg.collection === this.db.modelName) {
          var _ret = function () {
            var modifier = {};
            if (Array.isArray(msg.cleared) && msg.cleared.length > 0) {
              modifier.$unset = {};
              var _iteratorNormalCompletion = true;
              var _didIteratorError = false;
              var _iteratorError = undefined;

              try {
                for (var _iterator = msg.cleared[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                  var f = _step.value;

                  modifier.$unset[f] = 1;
                }
              } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion && _iterator.return) {
                    _iterator.return();
                  }
                } finally {
                  if (_didIteratorError) {
                    throw _iteratorError;
                  }
                }
              }
            }
            if (msg.fields) {
              delete msg.fields._id;
              modifier.$set = {};
              (0, _forEach2.default)(msg.fields, function (v, k) {
                modifier.$set[k] = v;
              });
            }

            if ((0, _keys3.default)(modifier).length > 0) {
              return {
                v: _this6.db.update(msg.id, modifier, { quiet: true })
              };
            }
          }();

          if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
        } else {
          return Promise.resolve();
        }
      }
    }, {
      key: '_handleRemoteRemoved',
      value: function _handleRemoteRemoved(msg) {
        if (msg.collection === this.db.modelName) {
          return this.db.remove(msg.id, { quiet: true });
        } else {
          return Promise.resolve();
        }
      }
    }]);

    return CollectionManager;
  }(_currentDelegateClass);

  return CollectionManager;
}


text:
package com.vladsch.flexmark.ext.toc;

import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.ast.BlockContent;
import com.vladsch.flexmark.util.ast.DoNotDecorate;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * A sim toc contents node containing all text that came after the sim toc node
 */
public class SimTocContent extends Block implements DoNotDecorate {
    @NotNull
    @Override
    public BasedSequence[] getSegments() {
        //return EMPTY_SEGMENTS;
        return EMPTY_SEGMENTS;
    }

    @Override
    public void getAstExtra(@NotNull StringBuilder out) {
    }

    public SimTocContent() {
    }

    public SimTocContent(BasedSequence chars) {
        super(chars);
    }

    public SimTocContent(BasedSequence chars, List<BasedSequence> lineSegments) {
        super(chars, lineSegments);
    }

    public SimTocContent(List<BasedSequence> lineSegments) {
        super(lineSegments);
    }

    public SimTocContent(BlockContent blockContent) {
        super(blockContent);
    }
}


text: var designApp = angular.module("designApp", ["ui.bootstrap", "dndLists", "uniprotApp"]);


text:
using System.Linq;
using SFA.DAS.EmployerAccounts.Models.Account;

namespace SFA.DAS.EmployerAccounts.Data
{
    public static class AccountLegalEntityExtensions
    {
        /// <summary>
        ///     Query extension that selects only legal entities for an account that have either an active signed or active pending agreement).
        /// </summary>
        public static IQueryable<AccountLegalEntity> WithSignedOrPendingAgreementsForAccount(this IQueryable<AccountLegalEntity> query, long accountId)
        {
            return query.Where(ale =>
                ale.AccountId == accountId && ale.Deleted == null && (ale.PendingAgreementId != null || ale.SignedAgreementId != null));
        }
    }
}


text:
import {
  SAVE_CAMPAIGN_REQUEST,
  SAVE_CAMPAIGN_SUCCESS,
  SAVE_CAMPAIGN_FAILURE,
  SAVE_CAMPAIGN_RESET,
} from '../actions/campaign';

const INITIAL_STATE = {
  isSaving: false,
  isSaved: false,
  error: null,
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case SAVE_CAMPAIGN_REQUEST:
      return {
        ...state,
        isSaving: true,
        error: null,
      };
    case SAVE_CAMPAIGN_SUCCESS:
      return {
        ...state,
        isSaving: false,
        isSaved: true,
      };
    case SAVE_CAMPAIGN_FAILURE:
      return {
        ...state,
        isSaving: false,
        error: action.error,
      };
    case SAVE_CAMPAIGN_RESET:
      return { ...INITIAL_STATE };
    default:
      return state;
  }
};


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<hibernate-mapping>
    <class name="ru.job4j.carMarket.model.entity.Car" table="car">
        <id name="id" column="id">
            <generator class="identity"/>
        </id>
        <property name="mark" column="mark"/>
        <property name="model" column="model"/>
        <property name="transmission" column="transmission"/>
        <property name="bodyType" column="body_type"/>
        <property name="yearIssue" column="year_issue"/>
        <property name="price" column="price"/>
        <property name="pathImage" column="path_image"/>
        <property name="isSold" column="sold"/>
        <many-to-one name="user"
                     column="user_id"
                     class="ru.job4j.carMarket.model.entity.User"
                     not-null="false"
                     cascade="all"/>
                     <!--lazy="proxy"-->

    </class>
</hibernate-mapping>


text:
@interface PSUManager : NSObject

+ (instancetype)sharedManager;

- (void)requestAlbums:(PSUSourceType)type completion:(void(^)(NSArray<PSUAlbum *> *albums))block;
- (void)requestPhotosForAlbum:(PSUAlbum *)album completion:(void(^)(NSArray<PSUPhoto *> *photos))block;
- (NSUInteger)numberOfAlbums:(PSUSourceType)type;
- (NSUInteger)numberOfPhotosForAlbum:(PSUAlbum *)album;

@end


text:
package com.arrow.acn.client.cloud.aws.shadow;

import java.io.Serializable;

public class ShadowDocument implements Serializable {
	private static final long serialVersionUID = 6461967977077487220L;

	private long messageNumber;
	private ShadowRequest payload;
	private int qos;
	private long timestamp;
	private String topic;

	public long getMessageNumber() {
		return messageNumber;
	}

	public void setMessageNumber(long messageNumber) {
		this.messageNumber = messageNumber;
	}

	public ShadowRequest getPayload() {
		return payload;
	}

	public void setPayload(ShadowRequest payload) {
		this.payload = payload;
	}

	public int getQos() {
		return qos;
	}

	public void setQos(int qos) {
		this.qos = qos;
	}

	public long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}

	public String getTopic() {
		return topic;
	}

	public void setTopic(String topic) {
		this.topic = topic;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (messageNumber ^ (messageNumber >>> 32));
		result = prime * result + ((payload == null) ? 0 : payload.hashCode());
		result = prime * result + qos;
		result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
		result = prime * result + ((topic == null) ? 0 : topic.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;
		ShadowDocument other = (ShadowDocument) obj;
		if (messageNumber != other.messageNumber)
			return false;
		if (payload == null) {
			if (other.payload != null)
				return false;
		} else if (!payload.equals(other.payload))
			return false;
		if (qos != other.qos)
			return false;
		if (timestamp != other.timestamp)
			return false;
		if (topic == null) {
			if (other.topic != null)
				return false;
		} else if (!topic.equals(other.topic))
			return false;
		return true;
	}
}