text:
title: "Community Round-up #18"
author: [jgebhardt]
---

In this Round-up, we are taking a few closer looks at React's interplay with different frameworks and architectures.

## "Little framework BIG splash"

Let's start with yet another refreshing introduction to React: Craig Savolainen ([@maedhr](https://twitter.com/maedhr)) walks through some first steps, demonstrating [how to build a Google Maps component](http://infinitemonkeys.influitive.com/little-framework-big-splash) using React.

## Architecting your app with react

Brandon Konkle ([@bkonkle](https://twitter.com/bkonkle))
[Architecting your app with react](http://lincolnloop.com/blog/architecting-your-app-react-part-1/)
We're looking forward to part 2!

> React is not a full MVC framework, and this is actually one of its strengths. Many who adopt React choose to do so alongside their favorite MVC framework, like Backbone. React has no opinions about routing or syncing data, so you can easily use your favorite tools to handle those aspects of your frontend application. You'll often see React used to manage specific parts of an application's UI and not others. React really shines, however, when you fully embrace its strategies and make it the core of your application's interface.
>
> [Read the full article...](http://lincolnloop.com/blog/architecting-your-app-react-part-1/)

## React vs. async DOM manipulation

Eliseu Monar ([@eliseumds](https://twitter.com/eliseumds))'s post "[ReactJS vs async concurrent rendering](http://eliseumds.tumblr.com/post/77843550010/vitalbox-pchr-reactjs-vs-async-concurrent-rendering)" is a great example of how React quite literally renders a whole array of common web development work(arounds) obsolete.

## React, Scala and the Play Framework
[Matthias Nehlsen](http://matthiasnehlsen.com/) wrote a detailed introductory piece on [React and the Play Framework](http://matthiasnehlsen.com/blog/2014/01/05/play-framework-and-facebooks-react-library/), including a helpful architectural diagram of a typical React app.

Nehlsen's React frontend is the second implementation of his chat application's frontend, following an AngularJS version. Both implementations are functionally equivalent and offer some perspective on differences between the two frameworks.

In [another article](http://matthiasnehlsen.com/blog/2014/01/24/scala-dot-js-and-reactjs/), he walks us through the process of using React with scala.js to implement app-wide undo functionality.

Also check out his [talk](http://m.ustream.tv/recorded/42780242) at Ping Conference 2014, in which he walks through a lot of the previously content in great detail.

## React and Backbone

The folks over at [Venmo](https://venmo.com/) are using React in conjunction with Backbone.
Thomas Boyt ([@thomasaboyt](https://twitter.com/thomasaboyt)) wrote [this detailed piece](http://www.thomasboyt.com/2013/12/17/using-reactjs-as-a-backbone-view.html) about why React and Backbone are "a fantastic pairing".

## React vs. Ember

Eric Berry ([@coderberry](https://twitter.com/coderberry)) developed Ember equivalents for some of the official React examples. Read his post for a side-by-side comparison of the respective implementations: ["Facebook React vs. Ember"](https://instructure.github.io/blog/2013/12/17/facebook-react-vs-ember/).

## React and plain old HTML

Daniel Lo Nigro ([@Daniel15](https://twitter.com/Daniel15)) created [React-Magic](https://github.com/reactjs/react-magic), which leverages React to ajaxify plain old html pages and even [allows CSS transitions between pageloads](http://stuff.dan.cx/facebook/react-hacks/magic/red.php).

> React-Magic intercepts all navigation (link clicks and form posts) and loads the requested page via an AJAX request. React is then used to "diff" the old HTML with the new HTML, and only update the parts of the DOM that have been changed.
>
> [Check out the project on GitHub...](https://github.com/reactjs/react-magic)

On a related note, [Reactize](https://turbo-react.herokuapp.com/) by Ross Allen ([@ssorallen](https://twitter.com/ssorallen)) is a similarly awesome project: A wrapper for Rails' [Turbolinks](https://github.com/rails/turbolinks/), which seems to have inspired John Lynch ([@johnrlynch](https://twitter.com/johnrlynch)) to then create [a server-rendered version using the JSX transformer in Rails middleware](http://www.rigelgroupllc.com/blog/2014/01/12/react-jsx-transformer-in-rails-middleware/).

## React and Object.observe
Check out [François de Campredon](https://github.com/fdecampredon)'s implementation of [TodoMVC based on React and ES6's Object.observe](https://github.com/fdecampredon/react-observe-todomvc/).

## React and Angular

Ian Bicking ([@ianbicking](https://twitter.com/ianbicking)) of Mozilla Labs [explains why he "decided to go with React instead of Angular.js"](https://plus.google.com/+IanBicking/posts/Qj8R5SWAsfE).

### ng-React Update

[David Chang](https://github.com/davidchang) works through some performance improvements of his [ngReact](https://github.com/davidchang/ngReact) project. His post ["ng-React Update - React 0.9 and Angular Track By"](http://davidandsuzi.com/ngreact-update/) includes some helpful advice on boosting render performance for Angular components.

> Angular gives you a ton of functionality out of the box - a full MV* framework - and I am a big fan, but I'll admit that you need to know how to twist the right knobs to get performance.
>
> That said, React gives you a very strong view component out of the box with the performance baked right in. Try as I did, I couldn't actually get it any faster. So pretty impressive stuff.
>
>[Read the full post...](http://davidandsuzi.com/ngreact-update/)

React was also recently mentioned at ng-conf, where the Angular team commented on React's concept of the virtual DOM:

## React and Web Components

Jonathan Krause ([@jonykrause](https://twitter.com/jonykrause)) offers his thoughts regarding [parallels between React and Web Components](http://jonykrau.se/posts/the-value-of-react), highlighting the value of React's ability to render pages on the server practically for free.

## Immutable React

[Peter Hausel](http://pk11.kinja.com/) shows how to build a Wikipedia auto-complete demo based on immutable data structures (similar to [mori](https://npmjs.org/package/mori)), really taking advantage of the framework's one-way reactive data binding:

> Its truly reactive design makes DOM updates finally sane and when combined with persistent data structures one can experience JavaScript development like it was never done before.

> [Read the full post](http://tech.kinja.com/immutable-react-1495205675)

## D3 and React

[Ben Smith](http://10consulting.com/) built some great SVG-based charting components using a little less of D3 and a little more of React: [D3 and React - the future of charting components?](http://10consulting.com/2014/02/19/d3-plus-reactjs-for-charting/)

## Om and React
Josh Haberman ([@joshhaberman](https://twitter.com/JoshHaberman)) discusses performance differences between React, Om and traditional MVC frameworks in "[A closer look at OM vs React performance](http://blog.reverberate.org/2014/02/on-future-of-javascript-mvc-frameworks.html)".

Speaking of Om: [Omchaya](https://github.com/sgrove/omchaya) by Sean Grove ([@sgrove](https://twitter.com/sgrove)) is a neat Cljs/Om example project.

## Random Tweets

Worked for 2 hours on a [@react_js](https://twitter.com/react_js) app sans internet. Love that I could get stuff done with it without googling every question.
— John Shimek (@varikin) February 20, 2014


text:
/*
 * CSCE 4444
 *
 *
 */
package Panels;

import Listeners.Navigator;
import java.util.Stack;

public class Icons extends javax.swing.JPanel {

    private Navigator navigator;

    /**
     * Creates new form Icons
     */
    public Icons() {
        initComponents();
    }

    public void setNavigator(Navigator navigator)
    {
        this.navigator = navigator;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setOpaque(false);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/home-icon-48x48.png"))); // NOI18N
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jLabel1MouseClicked(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/back-icon-48x48.png"))); // NOI18N
        jLabel2.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jLabel2MouseClicked(evt);
            }
        });

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/refill-icon-48x48.png"))); // NOI18N
        jLabel3.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/waiter-icon-48x48.png"))); // NOI18N

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/tutorial-icon-48x48.png"))); // NOI18N

        jLabel6.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel6.setText("BACK");

        jLabel7.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel7.setText("HOME");

        jLabel8.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel8.setText("REFILL");

        jLabel9.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel9.setText("WAITER");

        jLabel10.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabel10.setText("INFO");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel8)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel5)
                    .addComponent(jLabel10))
                .addGap(6, 6, 6))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel6))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel8))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel9))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel10)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
        // TODO add your handling code here:
        navigator.goToHomeScreen();
    }//GEN-LAST:event_jLabel1MouseClicked

    private void jLabel2MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jLabel2MouseClicked
    {//GEN-HEADEREND:event_jLabel2MouseClicked
        // TODO add your handling code here:

    }//GEN-LAST:event_jLabel2MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    // End of variables declaration//GEN-END:variables
}

redpajama_set_name: RedPajamaGithub


text:
using System.Linq;
using Nimrod.Events.DataAccess.EF;
using Nimrod.Events.DomainModel;
using Nimrod.Events.Services.Queries.Base;

namespace Nimrod.Events.Services.Queries
{
    public class SessionQueries : EventQueries, ISessionQueries
    {
        public SessionQueries(EventsDb db) : base(db)
        {
        }

        public IQueryable<Session> GetAll()
        {
            return _db.Sessions;
        }

        public Session Single(int id)
        {
            return _db.Sessions.Find(id);
        }
    }
}


text:
<?php

spl_autoload_register(function ($class) {
    // the package namespace
    $ns = 'Firebase';

    $base_dir = __DIR__ . '/src';

    $prefix_len = strlen($ns);
    if (substr($class, 0, $prefix_len) !== $ns) {
        return;
    }

    // strip the prefix off the class
    $class = substr($class, $prefix_len);

    // a partial filename
    $file = $base_dir .str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

    if (is_readable($file)) {
        require $file;
    }

});


text:
package application;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Сервлет добавления пользователя.
 */
public class CreateUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("roles", DbManager.INSTANCE.getRoles());
        req.setAttribute("countries", DbManager.INSTANCE.getCountries());
        req.setAttribute("cities", DbManager.INSTANCE.getCities());
        req.getRequestDispatcher("WEB-INF/views/create.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String login = req.getParameter("login");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String country = req.getParameter("country");
        String city = req.getParameter("city");
        String role = req.getParameter("role");

        if (login.trim().equals("") | password.trim().equals("")) {
            req.setAttribute("error", "Login and password could not be blank.");
            doGet(req, resp);
        } else if (!DbManager.INSTANCE.loginIsFree(-1, login)) {
            req.setAttribute("error", "Login is already in use. Please choose another one.");
            doGet(req, resp);
        } else {
            DbManager.INSTANCE.addUser(name, login, password, email, country, city, role);
        }
        resp.sendRedirect(String.format("%s/", req.getContextPath()));
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>TheFeed - Search</title>

Search Results

You searched for : {{ search }}

	{% for post in posts %}

{{ post.username }}

{{ post.post_content }}

       {{ post.tags_string }}

      {{ post.post_time }}

    {% endfor %}

	{% block content %}{% endblock %}


text:
@interface EmoticonboardPageOffset : NSObject
{
    unsigned long long _totalValue;
    double _curValue;
}

@property(nonatomic) double curValue; // @synthesize curValue=_curValue;
@property(nonatomic) unsigned long long totalValue; // @synthesize totalValue=_totalValue;

@end


text:
// Copyright (c) Edgardo Zoppi.  All Rights Reserved.  Licensed under the MIT License.  See License.txt in the project root for license information.

using System.Linq;
using CCIProvider;
using Model;
using Model.Types;
using Model.ThreeAddressCode.Instructions;
using Backend.Serialization;
using Backend.Analyses;
using Backend.Model;
using Backend.Transformations;
using Backend.Utils;

namespace Console
{
    class Program
	{
		private Host host;

		public Program(Host host)
		{
			this.host = host;
		}

		public void VisitMethods()
		{
			var allDefinedMethods = from a in host.Assemblies
									from t in a.RootNamespace.GetAllTypes()
									from m in t.Members.OfType<MethodDefinition>()
									where m.Body != null
									select m;

			foreach (var method in allDefinedMethods)
			{
				VisitMethod(method);
			}
		}

		private void VisitMethod(MethodDefinition method)
		{
			System.Console.WriteLine(method.Name);

			var methodBodyBytecode = method.Body;
			var disassembler = new Disassembler(method);
			var methodBody = disassembler.Execute();
			method.Body = methodBody;

			var cfAnalysis = new ControlFlowAnalysis(method.Body);
			//var cfg = cfAnalysis.GenerateNormalControlFlow();
			var cfg = cfAnalysis.GenerateExceptionalControlFlow();

			var dgml = DGMLSerializer.Serialize(cfg);

			if (method.Name == "ExampleTryCatchFinally")
				;

			var domAnalysis = new DominanceAnalysis(cfg);
			domAnalysis.Analyze();
			domAnalysis.GenerateDominanceTree();

			var loopAnalysis = new NaturalLoopAnalysis(cfg);
			loopAnalysis.Analyze();

			var domFrontierAnalysis = new DominanceFrontierAnalysis(cfg);
			domFrontierAnalysis.Analyze();

			var splitter = new WebAnalysis(cfg);
			splitter.Analyze();
			splitter.Transform();

			methodBody.UpdateVariables();

			var typeAnalysis = new TypeInferenceAnalysis(cfg);
			typeAnalysis.Analyze();

			var forwardCopyAnalysis = new ForwardCopyPropagationAnalysis(cfg);
			forwardCopyAnalysis.Analyze();
			forwardCopyAnalysis.Transform(methodBody);

			var backwardCopyAnalysis = new BackwardCopyPropagationAnalysis(cfg);
			backwardCopyAnalysis.Analyze();
			backwardCopyAnalysis.Transform(methodBody);

			//var pointsTo = new PointsToAnalysis(cfg);
			//var result = pointsTo.Analyze();

			var liveVariables = new LiveVariablesAnalysis(cfg);
			liveVariables.Analyze();

			var ssa = new StaticSingleAssignment(methodBody, cfg);
			ssa.Transform();
			ssa.Prune(liveVariables);

			methodBody.UpdateVariables();

            var pta = new PointsToAnalysis(cfg, method);
            var results = pta.Analyze();
            var ptgDGML = DGMLSerializer.Serialize(results[cfg.Exit.Id].Output);

            //var dot = DOTSerializer.Serialize(cfg);
            //var dgml = DGMLSerializer.Serialize(cfg);

            //dgml = DGMLSerializer.Serialize(host, typeDefinition);
        }

        static void Main(string[] args)
		{
			const string root = @"..\..\..";
			//const string root = @"C:"; // casa
			//const string root = @"C:\Users\Edgar\Projects"; // facu

			const string input = root + @"\Test\bin\Debug\Test.dll";

			//using (var host = new PeReader.DefaultHost())
			//using (var assembly = new Assembly(host))
			//{
			//	assembly.Load(input);

			//	Types.Initialize(host);

			//	//var extractor = new TypesExtractor(host);
			//	//extractor.Extract(assembly.Module);

			//	var visitor = new MethodVisitor(host, assembly.PdbReader);
			//	visitor.Rewrite(assembly.Module);
			//}

			var host = new Host();
			//host.Assemblies.Add(assembly);

			PlatformTypes.Resolve(host);

			var loader = new Loader(host);
			loader.LoadAssembly(input);
            //loader.LoadCoreAssembly();

            var type = new BasicType("ExamplesPointsTo")
            {
                ContainingAssembly = new AssemblyReference("Test"),
                ContainingNamespace = "Test",
                ContainingTypes = null
			};

			var typeDefinition = host.ResolveReference(type);

			var method = new MethodReference("Example1", PlatformTypes.Void)
			{
				ContainingType = type,
			};

			//var methodDefinition = host.ResolveReference(method) as MethodDefinition;

			var program = new Program(host);
			//program.VisitMethods();

			// Testing method calls inlining
			var methodDefinition = host.ResolveReference(method) as MethodDefinition;
			var methodCalls = methodDefinition.Body.Instructions.OfType<MethodCallInstruction>().ToList();

			//foreach (var methodCall in methodCalls)
			//{
			//	var callee = host.ResolveReference(methodCall.Method) as MethodDefinition;
			//	methodDefinition.Body.Inline(methodCall, callee.Body);
			//}

			methodDefinition.Body.UpdateVariables();

			type = new BasicType("ExamplesPointsTo")
			{
				ContainingAssembly = new AssemblyReference("Test"),
				ContainingNamespace = "Test"
			};

			method = new MethodReference("Example1", PlatformTypes.Void)
			{
				ContainingType = type,
			};

			methodDefinition = host.ResolveReference(method) as MethodDefinition;

            //var ch = new ClassHierarchyAnalysis(host);
            //ch.Analyze();

            //var dgml = DGMLSerializer.Serialize(ch);

            //var chcga = new ClassHierarchyCallGraphAnalysis(host, ch);
            //var cg = chcga.Analyze(methodDefinition.ToEnumerable());

            //dgml = DGMLSerializer.Serialize(cg);

            program.VisitMethod(methodDefinition);

			System.Console.WriteLine("Done!");
			System.Console.ReadKey();
		}
	}
}


text:
package com.myrunning.leaderboard.db.dao.sqlmapdao;

/**
 *  File: CompetitorSqlMapClientDao.java
 *  Author: Joshua Forester
 *  Date: 2009/08/21
 *  Description: SqlMapDao for Competitor.
 **/

import java.util.List;
import java.util.ListIterator;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.util.StringUtils;
import com.myrunning.leaderboard.model.Competitor;
import com.myrunning.leaderboard.db.dao.ifacedao.CompetitorDao;
import com.myrunning.leaderboard.db.dao.query.PersonIdAndCourseIdQuery;

public class CompetitorSqlMapClientDao extends PersonSqlMapClientDao implements CompetitorDao {

    static Logger logger = Logger.getLogger(CompetitorSqlMapClientDao.class);

    public CompetitorSqlMapClientDao() {
	// empty
    }

    public Competitor getCompetitorById(String id) {
	return decorate((Competitor) getSqlMapClientTemplate().queryForObject("getCompetitorById", id));
    }

    public Competitor getCompetitorById(long id) {
	return getCompetitorById(String.valueOf(id));
    }

    public Competitor getCompetitorByEmail(String email) {
	return decorate((Competitor) getSqlMapClientTemplate().queryForObject("getCompetitorByEmail", email));
    }

    public Competitor getCompetitorByPersonIdAndCourseId(String personId, String courseId) {
	PersonIdAndCourseIdQuery query = new PersonIdAndCourseIdQuery();
	query.setPersonId(Long.parseLong(personId));
	query.setCourseId(Long.parseLong(courseId));
	return decorate((Competitor) getSqlMapClientTemplate().queryForObject("getCompetitorByPersonIdAndCourseId", query));
    }

    public Competitor getCompetitorByPersonIdAndCourseId(long personId, String courseId) {
	return getCompetitorByPersonIdAndCourseId(String.valueOf(personId), courseId);
    }

    public Competitor getCompetitorByPersonIdAndCourseId(String personId, long courseId) {
	return getCompetitorByPersonIdAndCourseId(personId, String.valueOf(courseId));
    }

    public Competitor getCompetitorByPersonIdAndCourseId(long personId, long courseId) {
	return getCompetitorByPersonIdAndCourseId(String.valueOf(personId), String.valueOf(courseId));
    }

    public Competitor getCompetitorByTraits(Competitor competitor) {
	if ((competitor.getFirstName() == null) ||
	    (! StringUtils.hasText(competitor.getFirstName())) ||
	    (competitor.getLastName() == null) ||
	    (! StringUtils.hasText(competitor.getLastName())) ||
	    (competitor.getCity() == null) ||
	    (! StringUtils.hasText(competitor.getCity())) ||
	    (competitor.getRegion() == null) ||
	    (! StringUtils.hasText(competitor.getRegion())) ||
	    (competitor.getCountry() == null) ||
	    (! StringUtils.hasText(competitor.getCountry())) ||
	    (competitor.getZip() == 0) ||
	    (! StringUtils.hasText(String.valueOf(competitor.getZip()))) ||
	    (competitor.getGender() == null) ||
	    (! StringUtils.hasText(competitor.getGender())) ||
	    (competitor.getBirthday() == null) ||
	    (! StringUtils.hasText(competitor.getBirthday().toString()))) {
	    throw new IllegalArgumentException();
	} else {
	    return decorate((Competitor) getSqlMapClientTemplate().queryForObject("getCompetitorByTraits", competitor));
	}
    }

    public List getCompetitorsByPersonId(String personId, boolean decorate) {
	if (decorate) {
	    return decorate(getSqlMapClientTemplate().queryForList("getCompetitorsByPersonId", personId));
	} else {
	    return getSqlMapClientTemplate().queryForList("getCompetitorsByPersonId", personId);
	}
    }

    public List getCompetitorsByPersonId(long personId, boolean decorate) {
	return getCompetitorsByPersonId(String.valueOf(personId), decorate);
    }

    public List getAll(boolean decorate) {
	if (decorate) {
	    return decorate(getSqlMapClientTemplate().queryForList("getAllCompetitors"));
	} else {
	    return getSqlMapClientTemplate().queryForList("getAllCompetitors");
	}
    }

    public List getCompetitorsByTeamId(String id, boolean decorate) {
	if (decorate) {
	    return decorate(getSqlMapClientTemplate().queryForList("getCompetitorsByTeamId", id));
	} else {
	    return getSqlMapClientTemplate().queryForList("getCompetitorsByTeamId", id);
	}
    }

    public List getCompetitorsByTeamId(long id, boolean decorate) {
	return getCompetitorsByTeamId(String.valueOf(id), decorate);
    }

    public void insertCompetitor(Competitor competitor) {
	competitor.setDefaults();
	insertPerson(competitor);
	competitor.setPersonId(getLastInsertId());
	getSqlMapClientTemplate().update("insertCompetitor", competitor);
    }

    public void attachCompetitor(Competitor competitor) {
	getSqlMapClientTemplate().update("insertCompetitor", competitor);
    }

    public void updateCompetitor(Competitor competitor) {
	// should this exist?  permissions issues may mean that a person object
	// is updated by a race director?
	competitor.setDefaults();

	// since we are updating, we don't want to update the person
	// with the competitor's id.  so save state and restore after
	// person update for competitor update
	long competitorId = competitor.getId();
	competitor.setId(competitor.getPersonId());
	updatePerson(competitor);
	competitor.setId(competitorId);

	getSqlMapClientTemplate().update("updateCompetitor", competitor);
    }

    public void updateAttachedCompetitor(Competitor competitor) {
	getSqlMapClientTemplate().update("updateCompetitor", competitor);
    }

    public void deleteCompetitorById(String id) {
	// delete only the competitor here, not the associated PERSON object also
	getSqlMapClientTemplate().update("deleteCompetitorById", id);
    }

    public void deleteCompetitorById(long id) {
	deleteCompetitorById(String.valueOf(id));
    }

    public static List decorate(List list) {

	ListIterator<Competitor> li = list.listIterator();
	Competitor competitor = null;
	while (li.hasNext()) {
	    competitor = li.next();
	    competitor = decorate(competitor);
	}

	return list;
    }

    public static Competitor decorate(Competitor competitor) {

	if (competitor == null) {
	    return competitor;
	}

	long id = competitor.getId();
	competitor.setId(competitor.getPersonId());
	competitor = (Competitor) PersonSqlMapClientDao.decorate(competitor);
	competitor.setId(id);

	return competitor;
    }

}// END OF CLASS CompetitorSqlMapClientDao


text:
/**
 */
package edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.provider;

import edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.InterfaceDrawing;
import edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.KAMP4aPSFieldofactivityannotationsPackage;

import java.util.Collection;
import java.util.List;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;

/**
 * This is the item provider adapter for a {@link edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.InterfaceDrawing} object.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class InterfaceDrawingItemProvider extends DrawingItemProvider {
	/**
	 * This constructs an instance from a factory and a notifier.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public InterfaceDrawingItemProvider(AdapterFactory adapterFactory) {
		super(adapterFactory);
	}

	/**
	 * This returns the property descriptors for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
		if (itemPropertyDescriptors == null) {
			super.getPropertyDescriptors(object);

			addDrawn_interfacePropertyDescriptor(object);
		}
		return itemPropertyDescriptors;
	}

	/**
	 * This adds a property descriptor for the Drawn interface feature.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected void addDrawn_interfacePropertyDescriptor(Object object) {
		itemPropertyDescriptors.add
			(createItemPropertyDescriptor
				(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
				 getResourceLocator(),
				 getString("_UI_InterfaceDrawing_drawn_interface_feature"),
				 getString("_UI_PropertyDescriptor_description", "_UI_InterfaceDrawing_drawn_interface_feature", "_UI_InterfaceDrawing_type"),
				 KAMP4aPSFieldofactivityannotationsPackage.Literals.INTERFACE_DRAWING__DRAWN_INTERFACE,
				 true,
				 false,
				 true,
				 null,
				 null,
				 null));
	}

	/**
	 * This returns InterfaceDrawing.gif.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object getImage(Object object) {
		return overlayImage(object, getResourceLocator().getImage("full/obj16/InterfaceDrawing"));
	}

	/**
	 * This returns the label text for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public String getText(Object object) {
		String label = ((InterfaceDrawing)object).getFilename();
		return label == null || label.length() == 0 ?
			getString("_UI_InterfaceDrawing_type") :
			getString("_UI_InterfaceDrawing_type") + " " + label;
	}

	/**
	 * This handles model notifications by calling {@link #updateChildren} to update any cached
	 * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void notifyChanged(Notification notification) {
		updateChildren(notification);
		super.notifyChanged(notification);
	}

	/**
	 * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
	 * that can be created under this object.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
		super.collectNewChildDescriptors(newChildDescriptors, object);
	}

}


text:
package io.crate.license;

import org.elasticsearch.action.support.master.MasterNodeRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

public class SetLicenseRequest extends MasterNodeRequest<SetLicenseRequest> {

    private final LicenseKey licenseKey;

    SetLicenseRequest(LicenseKey licenseKey) {
        this.licenseKey = licenseKey;
    }

    LicenseKey licenseMetadata() {
        return licenseKey;
    }

    public SetLicenseRequest(StreamInput in) throws IOException {
        super(in);
        licenseKey = new LicenseKey(in);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        licenseKey.writeTo(out);
    }
}


text:
.. _clients-all-examples:

Code Examples for |ak-tm|
=========================

There are many programming languages that provide |ak| client libraries.
The following "Hello, World!" examples are written in various languages to demonstrate how to produce to and consume from an |ak-tm| cluster, which can be in `Confluent Cloud <https://www.confluent.io/confluent-cloud/?utm_source=github&utm_medium=demo&utm_campaign=ch.examples_type.community_content.clients-ccloud>`__, on your local host, or any other |ak| cluster.
For the subset of languages that support it, the code examples also demonstrate how to use Avro and |sr-long|.

* :ref:`C (librdkafka) <client-examples-c>`
* :ref:`Clojure <client-examples-clojure>`
* :ref:`C-sharp/.Net <client-examples-csharp>`
* :ref:`Go <client-examples-go>`
* :ref:`Groovy <client-examples-groovy>`
* :ref:`Java <client-examples-java>`
* :ref:`Java Spring Boot <client-examples-java-springboot>`
* :ref:`Kotlin <client-examples-kotlin>`
* `Node.js <https://developer.confluent.io/get-started/nodejs/>`__
* :ref:`Python <client-examples-python>`
* :ref:`Ruby <client-examples-ruby>`
* :ref:`Rust <client-examples-rust>`
* :ref:`Scala <client-examples-scala>`

There are additional examples for |ak| and |cp| command line tools and components:

* :ref:`Apache Kafka commands <client-examples-kafka-commands>`
* :ref:`Confluent CLI <client-examples-confluent-cli>`
* :ref:`Confluent CLI (Cloud) <client-examples-ccloud>`
* :ref:`Kafka Connect Datagen <client-examples-kafka-connect-datagen>`
* :ref:`kcat <client-examples-kcat>`
* :ref:`KSQL Datagen <client-examples-ksql-datagen>`
* :ref:`REST Proxy <client-examples-rest-proxy>`

.. figure:: ../cloud/images/clients-all.png
   :width: 600px

.. toctree::
      :maxdepth: 1
      :hidden:

      Apache Kafka commands <kafka-commands>
      C (librdkafka) <c>
      Clojure <clojure>
      Confluent CLI <confluent-cli>
      Confluent CLI (Cloud) <ccloud>
      .NET <csharp>
      Go <go>
      Groovy <groovy>
      Java <java>
      Java Spring Boot <java-springboot>
      Kafka Connect Datagen <kafka-connect-datagen>
      kcat <kcat>
      Kotlin <kotlin>
      KSQL Datagen <ksql-datagen>
      Node.js <https://developer.confluent.io/get-started/nodejs/>
      Python <python>
      REST Proxy <rest-proxy>
      Ruby <ruby>
      Rust <rust>
      Scala <scala>


text:
author: generalchoa
comments: true
date: 2011-12-13 15:50:06+00:00
layout: post
slug: week-29-day-79a
title: Week 29 - Day 79A
wordpress_id: 536
categories:
- A
- Personal Records
- StrongLifts
tags:
- 1x5
- bench
- dips
- PR
- reverse crunches
- rows
- squat
- stall
- technique
---

**Squat:**

5 x Bar
5 x 145
3 x 175
2 x 205
1 x 235
**5 x 265 PR !!!**

Got another PR.  I'm not sure if I went low enough on the 4th rep.  My camera ran out of memory when trying to film just the first warm-up weight.  Going for 1.5xBW next workout and hopefully I can sort out the camera issue by then.

**Bench:**

****2 x 5 x Bar
5 x 75
3 x 95
2 x 115
1 x 135
3 x 160

Stalled hard on the bench.  Didn't feel confident with the lift.  Should definitely get a spotter next time to improve confidence and give the lift all I've got.

**Rows:**

****5 x 95
3 x 115
5 x 135

People using the rack, so I couldn't get my cleans in.  Decided to do some rows, felt a bit heavy for the weight.  **Squeeze the bar hard before lifting**.  This causes the lats to contract.  Promotes less jerking by using controlled lift as opposed to using jerk momentum to get the weight up.  Makes the muscles work harder.

**Accessories:**

10/5/3 x BW + 15 lbs Dips - Pretty hard, going to go up to 17.5 next A session.

3 x 12 x 7.5 lbs Reverse crunches - Tried doing dragon flags before this.  The negative wasn't too bad, but the positive was impossible to do.  I think I might start doing some additional core exercises to get me to dragon flagging.


text:
    <form class="form-signin form-horizontal centered" name="signinForm" role="form">

Introduce tu código de acceso:

        <input type="text" class="form-control"
               name="group"  required autofocus ng-model="groupId"
               ng-minlength="8"
               ng-maxlength="8"
               ng-pattern="/\w{4}\d{4}/"
               ng-change="access()"
               >

        	Valor invalido
        	Cargando...

Acceder sin código

    </form>


text:
<?xml version="1.0" encoding="UTF-8"?>
<gsmlb:MappedFeature xmlns:xlink="http://www.w3.org/1999/xlink"
 xmlns:gml="http://www.opengis.net/gml/3.2"
 xmlns:gsmlb="http://www.opengis.net/gsml/4.1/GeoSciML-Basic"
 xmlns:swe="http://www.opengis.net/swe/2.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.opengis.net/gsml/4.1/GeoSciML-Basic http://schemas.opengis.net/gsml/4.1/geoSciMLBasic.xsd"
 gml:id="mf.16">
 <gsmlb:mappingFrame
  xlink:href="http://inspire.ec.europa.eu/codelist/MappingFrameValue/topOfBedrock"
  xlink:title="top of bedrock"/>
 <gsmlb:specification>
  <gsmlb:Fold gml:id="FOLD_ID_1">
   <gml:identifier codeSpace="http://data.bgs.ac.uk/">http://data.bgs.ac.uk/ref/625KGeologyMap/Fold/bgsn_digmap20111213000010000_625k</gml:identifier>
   <gml:name>UNNAMED FOLD</gml:name>
   <!--  -->
   <!-- The GeologicAge is provided by a relationship to a GeologicEvent -->
   <!--  -->
   <gsmlb:geologicHistory>
    <gsmlb:GeologicEvent gml:id="EVENT_3">
     <gml:name>HERCYNIAN OROGENY</gml:name>
     <gsmlb:eventProcess
      xlink:href="http://inspire.ec.europa.eu/codelist/EventProcessValue/folding"
      xlink:title="folding"/>
     <gsmlb:olderNamedAge
      xlink:href="http://inspire.ec.europa.eu/codelist/GeochronologicEraValue/tournaisian"
      xlink:title="Tournaisian"/>
     <gsmlb:youngerNamedAge
      xlink:href="http://inspire.ec.europa.eu/codelist/GeochronologicEraValue/tournaisian"
      xlink:title="Tournaisian"/>
     <gsmlb:eventEnvironment>
      <swe:Category
       definition="http://inspire.ec.europa.eu/codelist/EventEnvironmentValue">
       <swe:extension>
        <swe:Category
         definition="http://resource.geosciml.org/classifierscheme/cgi/201211/valuequalifier">
         <swe:identifier>http://resource.geosciml.org/classifier/cgi/valuequalifier/always</swe:identifier>
         <swe:label>always</swe:label>
         <swe:codeSpace
          xlink:href="http://resource.geosciml.org/classifierscheme/cgi/201211/valuequalifier"
         />
        </swe:Category>
       </swe:extension>
       <swe:identifier>http://inspire.ec.europa.eu/codelist/EventEnvironmentValue/crustalSetting</swe:identifier>
       <swe:label>crustal setting</swe:label>
       <swe:codeSpace
        xlink:href="http://inspire.ec.europa.eu/codelist/EventEnvironmentValue"
       />
      </swe:Category>
     </gsmlb:eventEnvironment>
    </gsmlb:GeologicEvent>
   </gsmlb:geologicHistory>
   <gsmlb:profileType
    xlink:href="http://inspire.ec.europa.eu/codelist/FoldProfileTypeValue/anticline"
    xlink:title="anticline"/>
  </gsmlb:Fold>
 </gsmlb:specification>
 <gsmlb:shape>
  <gml:Polygon srsName="urn:ogc:def:crs:EPSG::4326" gml:id="LOCAL_ID_0">
   <gml:exterior>
    <gml:LinearRing>
     <gml:posList srsDimension="2" count="8">55.0760921318516 -3.31719604609088
      55.0833753209835 -3.31853455922777 55.0825574334633 -3.31921378657955
      55.0801997429522 -3.31978309699423 55.0768616358466 -3.3194575613054
      55.0741365291192 -3.31966903508197 55.0756843873373 -3.31747948721346
      55.0760921318516 -3.31719604609088</gml:posList>
    </gml:LinearRing>
   </gml:exterior>
  </gml:Polygon>
 </gsmlb:shape>
</gsmlb:MappedFeature>


text:
/*
Double Tap to Go
Author: Graffino (http://www.graffino.com)
Version: 0.3
Originally by Osvaldas Valutis, www.osvaldas.info
Available for use under the MIT License
*/

;(function($, window, document, undefined) {
	$.fn.doubleTapToGo = function(action) {

		if (!('ontouchstart' in window) &&
			!navigator.msMaxTouchPoints &&
			!navigator.userAgent.toLowerCase().match( /windows phone os 7/i )) return false;

		if (action === 'unbind') {
			this.each(function() {
				$(this).off();
				$(document).off('click touchstart MSPointerDown', handleTouch);
			});

		} else {
			this.each(function() {
				var curItem = false;

				$(this).on('click', function(e) {
					var item = $(this);
					if (item[0] != curItem[0]) {
						e.preventDefault();
						curItem = item;
					}
				});

				$(document).on('click touchstart MSPointerDown', handleTouch);

				function handleTouch(e) {
					var resetItem = true,
						parents = $(e.target).parents();

					for (var i = 0; i < parents.length; i++)
						if (parents[i] == curItem[0])
							resetItem = false;

					if(resetItem)
						curItem = false;
				}
			});
		}
		return this;
	};
})(jQuery, window, document);


text:
module Data.HashTable.MArray (
        HashTable, ArrayElement,
        new, insert, delete, lookup, update,
        fromList, toList,
        longestChain
    ) where

import Data.Hashable
import Control.Monad.Ref

import Data.Array.MArray

-- For specialisation purposes:
import Data.Array.IO ( IOArray )
import Data.Array.ST ( STArray )

import Data.Bits ( (.&.) )
import Data.Int  ( Int32 )
import Data.List ( maximumBy, partition )

import Control.Monad
import Control.Monad.ST ( ST )

import Prelude hiding ( lookup )

-- | The type of elements the HashTable needs to instantiate the MArray at.
-- Somewhat unfortunately we cannot make this abstract since the calling code
-- needs to instantiate it, so we comprimise by at least giving it a name.
type ArrayElement key val = [(key, val)]

data HashTable (arr :: * -> * -> *) m key val = HashTable !(Ref m (HT arr m key val))
  -- TODO: should the IORef really be an MVar?

data HT (arr :: * -> * -> *) m key val = HT {
        kcount  :: !Int32, -- ^ Total number of keys
        bmask   :: !Int32, -- ^ Mask to clip hashes to the number of buckets
        buckets :: !(arr Int32 (ArrayElement key val))
    }

-- -----------------------------------------------------------------------------
-- Parameters

-- | Maximum size, in keys, of the hash table
tABLE_MAX :: Int32
tABLE_MAX  = 32 * 1024 * 1024

tABLE_MIN :: Int32
tABLE_MIN  = 8

-- | Maximum average load of a single hash bucket
hLOAD :: Int32
hLOAD = 7

-- | Entries to ignore in load computation. Hysteresis favors long
-- association-list-like behavior for small tables.
hYSTERESIS :: Int32
hYSTERESIS = 64

-- -----------------------------------------------------------------------------
-- Creating a new hash table

-- | Creates a new, empty, hash table
new :: (MonadRef m, MArray arr (ArrayElement key val) m)
    => m (HashTable arr m key val)
{-# SPECIALIZE new :: IO (HashTable IOArray IO key val) #-}
{-# SPECIALIZE new :: ST s (HashTable (STArray s) (ST s) key val) #-}
new = do
    -- Make a new hash table with a single, empty, segment
    let mask = tABLE_MIN - 1
    bkts <- newArray (0, mask) []

    -- Create a reference to the hash table and return it as a HashTable instance
    liftM HashTable $ newRef $ HT { buckets = bkts, kcount = 0, bmask = mask }

-- -----------------------------------------------------------------------------
-- Inserting a key\/value pair into the hash table

-- | Inserts a key\/value mapping into the hash table.
--
-- Note that 'insert' doesn't remove the old entry from the table -
-- the behaviour is like an association list, where 'lookup' returns
-- the most-recently-inserted mapping for a key in the table.  The
-- reason for this is to keep 'insert' as efficient as possible.  If
-- you need to update a mapping, then we provide 'update'.
insert :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
       => HashTable arr m key val -> key -> val -> m ()
{-# SPECIALIZE insert :: Hashable key => HashTable IOArray IO key val -> key -> val -> IO () #-}
{-# SPECIALIZE insert :: Hashable key => HashTable (STArray s) (ST s) key val -> key -> val -> ST s () #-}
{-# SPECIALIZE insert :: HashTable IOArray IO Int val -> Int -> val -> IO () #-}
{-# SPECIALIZE insert :: HashTable (STArray s) (ST s) Int val -> Int -> val -> ST s () #-}
{-# SPECIALIZE insert :: Hashable key => HashTable IOArray IO [key] val -> [key] -> val -> IO () #-}
{-# SPECIALIZE insert :: Hashable key => HashTable (STArray s) (ST s) [key] val -> [key] -> val -> ST s () #-}
insert ht key val = updatingBucket CanInsert bucket_fn ht key
  where bucket_fn bucket = ((key,val):bucket, 1, ())

-- ------------------------------------------------------------
-- The core of the implementation is lurking down here, in findBucket,
-- updatingBucket, and expandHashTable.

-- | Given a number of keys and a number of buckets, ask whether the hashtable is too big
tooBig :: Int32 -> Int32 -> Bool
tooBig k b = k-hYSTERESIS > hLOAD * b

-- | Find the index of a bucket within table given a mask and hash
bucketIndex :: Int32 -> Int32 -> Int32
bucketIndex mask h = h .&. mask

-- | Find the bucket in which the key belongs.
-- Returns (key equality, bucket index, bucket)
--
-- This rather grab-bag approach gives enough power to do pretty much
-- any bucket-finding thing you might want to do.  We rely on inlining
-- to throw away the stuff we don't want.  I'm proud to say that this
-- plus updatingBucket below reduce most of the other definitions to a
-- few lines of code, while actually speeding up the hashtable
-- implementation when compared with a version which does everything
-- from scratch.
findBucket :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
           => HashTable arr m key val -> key -> m (HT arr m key val, Int32, [(key, val)])
{-# INLINE findBucket #-}
findBucket (HashTable table_ref) key = do
  table@HT{ buckets=bkts, bmask=b } <- readRef table_ref
  let indx = bucketIndex b (int32Hash key)
  bucket <- readArray bkts indx
  return (table, indx, bucket)

-- | Data structure used to indicate to 'updatingBucket' whether the current
-- update is able to insert into the table. If it can't insert, no hashtable
-- enlargement will be required.
data Inserts = CanInsert   -- Used by update and insert
             | CantInsert -- Used by delete
             deriving (Eq)

-- | 'updatingBucket' is the real workhorse of all single-element table
-- updates.  It takes a hashtable and a key, along with a function
-- describing what to do with the bucket in which that key belongs.  A
-- flag indicates whether this function may perform table insertions.
-- The function returns the new contents of the bucket, the number of
-- bucket entries inserted (negative if entries were deleted), and a
-- value which becomes the return value for the function as a whole.
-- The table sizing is enforced here, calling out to expandSubTable as
-- necessary.
--
-- This function is intended to be inlined and specialized for every
-- calling context (eg every provided bucket_fn).
updatingBucket :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
               => Inserts                                  -- ^ Whether the bucket function can insert
               -> ([(key,val)] -> ([(key,val)], Int32, a)) -- ^ Bucket modification function
               -> HashTable arr m key val                  -- ^ Hashtable to change
               -> key                                      -- ^ Key of the bucket to mess with
               -> m a                                      -- ^ Value from the bucket function
{-# INLINE updatingBucket #-}
updatingBucket can_enlarge bucket_fn ht@(HashTable tab_ref) key = do
  -- Obtain the bucket to be modified and run the supplied function on it
  (table@HT{ kcount=k, buckets=bkts, bmask=b }, indx, bckt) <- findBucket ht key
  (bckt', inserts, result) <- return $ bucket_fn bckt

  -- Update the bucket using the value return by the function
  let k' = k + inserts
      table' = table { kcount=k' }
  writeArray bkts indx bckt'

  -- Check if we need to expand the hash table due to a new insertion
  table'' <- if can_enlarge == CanInsert && inserts > 0 && tooBig k' b
             then expandHashTable table'
             else return table'

  -- Update the mutable reference to a hashtable
  writeRef tab_ref table''
  return result

-- | Rehashes the hashtable into a new one to reduce the load factor
expandHashTable :: (Hashable key, MArray arr (ArrayElement key val) m)
                => HT arr m key val -> m (HT arr m key val)
{-# INLINE expandHashTable #-} -- INLINE into updatingBucket use site to benefit from specialisation there
expandHashTable table@(HT{ buckets=bkts, bmask=mask })
  | newmask > tABLE_MAX-1 = return table -- We don't allow the number of buckets to expand beyond a certain size
  | otherwise = do
    -- Create the new buckets array
    newbkts <- newArray (0, newmask) []

    -- Bucket splitting: rehash all the elements in each bucket and put them into one of two
    -- new buckets corresponding to one old bucket depending on the value of the topmost bit
    -- under the expanded mask 'newmask'
    let splitBucket oldindex = do
          bucket <- readArray bkts oldindex
          let (oldb,newb) = partition ((oldindex==) . bucketIndex newmask . int32Hash . fst) bucket
          writeArray newbkts oldindex oldb
          writeArray newbkts (oldindex + oldsize) newb

    -- Split every bucket in the old hashtable and return the modified table
    mapM_ splitBucket [0..mask]
    return $ table { buckets=newbkts, bmask=newmask }
  where
   oldsize = mask + 1
   newmask = mask + mask + 1

-- -----------------------------------------------------------------------------
-- Deleting a mapping from the hash table

-- | Remove a key from a bucket
deleteBucket :: (key -> Bool) -> [(key,val)] -> ([(key, val)], Int32, ())
deleteBucket _   [] = ([], 0, ())
deleteBucket del (pair@(k,_):bucket) =
  case deleteBucket del bucket of
    (bucket', dels, _) | del k     -> dels' `seq` (bucket', dels', ())
                       | otherwise -> (pair:bucket', dels, ())
      where dels' = dels - 1

-- | Remove an entry from the hash table
delete :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
       => HashTable arr m key val -> key -> m ()
{-# SPECIALIZE delete :: Hashable key => HashTable IOArray IO key val -> key -> IO () #-}
{-# SPECIALIZE delete :: Hashable key => HashTable (STArray s) (ST s) key val -> key -> ST s () #-}
{-# SPECIALIZE delete :: HashTable IOArray IO Int val -> Int -> IO () #-}
{-# SPECIALIZE delete :: HashTable (STArray s) (ST s) Int val -> Int -> ST s () #-}
{-# SPECIALIZE delete :: Hashable key => HashTable IOArray IO [key] val -> [key] -> IO () #-}
{-# SPECIALIZE delete :: Hashable key => HashTable (STArray s) (ST s) [key] val -> [key] -> ST s () #-}
delete ht key = updatingBucket CantInsert (deleteBucket (key ==)) ht key

-- -----------------------------------------------------------------------------
-- Updating a mapping in the hash table

-- | Updates an entry in the hash table, returning 'True' if there was
-- already an entry for this key, or 'False' otherwise.  After 'update'
-- there will always be exactly one entry for the given key in the table.
--
-- 'insert' is more efficient than 'update' if you don't care about
-- multiple entries, or you know for sure that multiple entries can't
-- occur.  However, 'update' is more efficient than 'delete' followed
-- by 'insert'.
update :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
       => HashTable arr m key val -> key -> val -> m Bool
{-# SPECIALIZE update :: Hashable key => HashTable IOArray IO key val -> key -> val -> IO Bool #-}
{-# SPECIALIZE update :: Hashable key => HashTable (STArray s) (ST s) key val -> key -> val -> ST s Bool #-}
{-# SPECIALIZE update :: HashTable IOArray IO Int val -> Int -> val -> IO Bool #-}
{-# SPECIALIZE update :: HashTable (STArray s) (ST s) Int val -> Int -> val -> ST s Bool #-}
{-# SPECIALIZE update :: Hashable key => HashTable IOArray IO [key] val -> [key] -> val -> IO Bool #-}
{-# SPECIALIZE update :: Hashable key => HashTable (STArray s) (ST s) [key] val -> [key] -> val -> ST s Bool #-}
update ht key val = updatingBucket CanInsert bucket_fn ht key
  where bucket_fn bucket = let (bucket', dels, _) = deleteBucket (key ==) bucket
                           in  ((key, val):bucket', 1 + dels, dels /= 0)

-- -----------------------------------------------------------------------------
-- Looking up an entry in the hash table

-- | Looks up the value of a key in the hash table.
lookup :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
       => HashTable arr m key val -> key -> m (Maybe val)
{-# SPECIALIZE lookup :: Hashable key => HashTable IOArray IO key val -> key -> IO (Maybe val) #-}
{-# SPECIALIZE lookup :: Hashable key => HashTable (STArray s) (ST s) key val -> key -> ST s (Maybe val) #-}
{-# SPECIALIZE lookup :: HashTable IOArray IO Int val -> Int -> IO (Maybe val) #-}
{-# SPECIALIZE lookup :: HashTable (STArray s) (ST s) Int val -> Int -> ST s (Maybe val) #-}
{-# SPECIALIZE lookup :: Hashable key => HashTable IOArray IO [key] val -> [key] -> IO (Maybe val) #-}
{-# SPECIALIZE lookup :: Hashable key => HashTable (STArray s) (ST s) [key] val -> [key] -> ST s (Maybe val) #-}
lookup ht key = do
  (_, _, bucket) <- findBucket ht key
  let firstHit (k,v) r | key == k  = Just v
                       | otherwise = r
  return (foldr firstHit Nothing bucket)

-- -----------------------------------------------------------------------------
-- Converting to/from lists

-- | Convert a list of key\/value pairs into a hash table
fromList :: (Hashable key, MonadRef m, MArray arr (ArrayElement key val) m)
         => [(key, val)] -> m (HashTable arr m key val)
{-# SPECIALIZE fromList :: Hashable key => [(key, val)] -> IO (HashTable IOArray IO key val) #-}
{-# SPECIALIZE fromList :: Hashable key => [(key, val)] -> ST s (HashTable (STArray s) (ST s) key val) #-}
{-# SPECIALIZE fromList :: [(Int, val)] -> IO (HashTable IOArray IO Int val) #-}
{-# SPECIALIZE fromList :: [(Int, val)] -> ST s (HashTable (STArray s) (ST s) Int val) #-}
{-# SPECIALIZE fromList :: Hashable key => [([key], val)] -> IO (HashTable IOArray IO [key] val) #-}
{-# SPECIALIZE fromList :: Hashable key => [([key], val)] -> ST s (HashTable (STArray s) (ST s) [key] val) #-}
fromList list = do
  table <- new
  sequence_ [ insert table k v | (k, v) <- list ]
  return table

-- | Converts a hash table to a list of key\/value pairs
toList :: (MonadRef m, MArray arr (ArrayElement key val) m)
       => HashTable arr m key val -> m [(key, val)]
{-# SPECIALIZE toList :: HashTable IOArray IO key val -> IO [(key, val)] #-}
{-# SPECIALIZE toList :: HashTable (STArray s) (ST s) key val -> ST s [(key, val)] #-}
toList = mapReduce id concat

mapReduce :: (MonadRef m, MArray arr (ArrayElement key val) m)
          => ([(key, val)] -> r) -- ^ Mapping function - process bucket
          -> ([r] -> r)          -- ^ Reducing function - combine buckets
          -> HashTable arr m key val
          -> m r
{-# INLINE mapReduce #-}
mapReduce m r (HashTable tab_ref ) = do
  HT { buckets=bckts, bmask=b } <- readRef tab_ref
  liftM r (mapM (liftM m . readArray bckts) [0..b])

-- -----------------------------------------------------------------------------
-- Diagnostics

-- | This function is useful for determining whether your hash
-- function is working well for your data set.  It returns the longest
-- chain of key\/value pairs in the hash table for which all the keys
-- hash to the same bucket.
--
-- If this chain is particularly long (say, longer than 14 elements or
-- so), then it might be a good idea to try a different hash function.
longestChain :: (MonadRef m, MArray arr (ArrayElement key val) m)
             => HashTable arr m key val -> m [(key,val)]
longestChain = mapReduce id (maximumBy lengthCmp)
  where lengthCmp (_:x)(_:y) = lengthCmp x y
        lengthCmp []   []    = EQ
        lengthCmp []   _     = LT
        lengthCmp _    []    = GT


text:
.PHONY: release install files test docs prepare publish

all:
	@echo "make release - prepares a release and publishes it"
	@echo "make dev - prepares a development environment (includes tests)"
	@echo "make instdev - prepares a development environment (no tests)"
	@echo "make install - install on local system"
	@echo "make test - run tox"
	@echo "make docs - build docs"
	@echo "prepare - prepare module for release (CURRENTLY IRRELEVANT)"
	@echo "make publish - upload to pypi"

release: docs publish

dev: instdev test

instdev:
	pip install -rdev-requirements.txt
	python setup.py develop

install:
	python setup.py install

test:
	pip install tox
	tox

docs:
	pandoc README.md -f markdown -t rst -s -o README.rst

prepare:
	python scripts/make-release.py

publish:
	python setup.py sdist upload


text:
package org.gradoop.flink.model.impl.operators.matching.common.functions;

import org.apache.flink.api.java.functions.FunctionAnnotation;
import org.apache.flink.configuration.Configuration;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.flink.model.impl.operators.matching.common.matching.ElementMatcher;
import org.gradoop.flink.model.impl.operators.matching.common.tuples.IdWithCandidates;
import org.gradoop.common.model.impl.pojo.Vertex;

import java.util.Collection;

import static org.gradoop.common.util.GradoopConstants.DEFAULT_VERTEX_LABEL;

/**
 * Converts an EPGM vertex to a {@link IdWithCandidates} tuple.
 *
 * vertex -> (vertexId, vertexCandidates)
 *
 * Forwarded Fields:
 *
 * id->f0: vertex id
 *
 * @param <V> EPGM vertex type
 */
@FunctionAnnotation.ForwardedFields("id->f0")
public class BuildIdWithCandidates<V extends Vertex>
  extends AbstractBuilder<V, IdWithCandidates<GradoopId>> {
  /**
   * serial version uid
   */
  private static final long serialVersionUID = 42L;
  /**
   * Query vertices to match against.
   */
  private transient Collection<org.s1ck.gdl.model.Vertex> queryVertices;
  /**
   * Number of vertices in the query graph
   */
  private int vertexCount;
  /**
   * Reduce instantiations
   */
  private final IdWithCandidates<GradoopId> reuseTuple;

  /**
   * Constructor
   *
   * @param query GDL query
   */
  public BuildIdWithCandidates(String query) {
    super(query);
    reuseTuple = new IdWithCandidates<>();
  }

  @Override
  public void open(Configuration parameters) throws Exception {
    super.open(parameters);
    queryVertices = getQueryHandler().getVertices();
    vertexCount   = queryVertices.size();
  }

  @Override
  public IdWithCandidates<GradoopId> map(V v) throws Exception {
    reuseTuple.setId(v.getId());
    reuseTuple.setCandidates(getCandidates(vertexCount,
      ElementMatcher.getMatches(v, queryVertices, DEFAULT_VERTEX_LABEL)));
    return reuseTuple;
  }
}


text:
package executor_test

import (
	"fmt"
	"os"
	"strings"

	. "github.com/pingcap/check"
	"github.com/pingcap/failpoint"
	"github.com/pingcap/tidb/config"
	"github.com/pingcap/tidb/util"
	"github.com/pingcap/tidb/util/testkit"
)

func (s *testSerialSuite1) TestSortInDisk(c *C) {
	s.testSortInDisk(c, false)
	s.testSortInDisk(c, true)
}

func (s *testSerialSuite1) testSortInDisk(c *C, removeDir bool) {
	defer config.RestoreFunc()()
	config.UpdateGlobal(func(conf *config.Config) {
		conf.OOMUseTmpStorage = true
	})
	c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill", "return(true)"), IsNil)
	defer func() {
		c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill"), IsNil)
	}()

	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("use test")

	sm := &mockSessionManager1{
		PS: make([]*util.ProcessInfo, 0),
	}
	tk.Se.SetSessionManager(sm)
	s.domain.ExpensiveQueryHandle().SetSessionManager(sm)

	if removeDir {
		c.Assert(os.RemoveAll(config.GetGlobalConfig().TempStoragePath), IsNil)
		defer func() {
			_, err := os.Stat(config.GetGlobalConfig().TempStoragePath)
			if err != nil {
				c.Assert(os.IsExist(err), IsTrue)
			}
		}()
	}

	tk.MustExec("set @@tidb_mem_quota_query=1;")
	tk.MustExec("set @@tidb_max_chunk_size=32;")
	tk.MustExec("drop table if exists t")
	tk.MustExec("create table t(c1 int, c2 int, c3 int)")
	for i := 0; i < 5; i++ {
		for j := i; j < 1024; j += 5 {
			tk.MustExec(fmt.Sprintf("insert into t values(%v, %v, %v)", j, j, j))
		}
	}
	result := tk.MustQuery("select * from t order by c1")
	for i := 0; i < 1024; i++ {
		c.Assert(result.Rows()[i][0].(string), Equals, fmt.Sprint(i))
		c.Assert(result.Rows()[i][1].(string), Equals, fmt.Sprint(i))
		c.Assert(result.Rows()[i][2].(string), Equals, fmt.Sprint(i))
	}
	c.Assert(tk.Se.GetSessionVars().StmtCtx.MemTracker.BytesConsumed(), Equals, int64(0))
	c.Assert(tk.Se.GetSessionVars().StmtCtx.MemTracker.MaxConsumed(), Greater, int64(0))
	c.Assert(tk.Se.GetSessionVars().StmtCtx.DiskTracker.BytesConsumed(), Equals, int64(0))
	c.Assert(tk.Se.GetSessionVars().StmtCtx.DiskTracker.MaxConsumed(), Greater, int64(0))
}

func (s *testSerialSuite1) TestIssue16696(c *C) {
	defer config.RestoreFunc()()
	config.UpdateGlobal(func(conf *config.Config) {
		conf.OOMUseTmpStorage = true
	})
	c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill", "return(true)"), IsNil)
	defer func() {
		c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/testSortedRowContainerSpill"), IsNil)
	}()
	c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/testRowContainerSpill", "return(true)"), IsNil)
	defer func() { c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/testRowContainerSpill"), IsNil) }()
	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("use test")
	tk.MustExec("drop table if exists t")
	tk.MustExec("CREATE TABLE `t` (`a` int(11) DEFAULT NULL,`b` int(11) DEFAULT NULL)")
	tk.MustExec("insert into t values (1, 1)")
	for i := 0; i < 6; i++ {
		tk.MustExec("insert into t select * from t")
	}
	tk.MustExec("set tidb_mem_quota_query = 1;")
	rows := tk.MustQuery("explain analyze  select t1.a, t1.a +1 from t t1 join t t2 join t t3 order by t1.a").Rows()
	for _, row := range rows {
		length := len(row)
		line := fmt.Sprintf("%v", row)
		disk := fmt.Sprintf("%v", row[length-1])
		if strings.Contains(line, "Sort") || strings.Contains(line, "HashJoin") {
			c.Assert(strings.Contains(disk, "0 Bytes"), IsFalse)
			c.Assert(strings.Contains(disk, "MB") ||
				strings.Contains(disk, "KB") ||
				strings.Contains(disk, "Bytes"), IsTrue)
		}
	}
}


text:
<?php

namespace console\models;

use Yii;

/**
 * This is the model class for table "field_data_field_news_tags".
 *
 * @property string $entity_type
 * @property string $bundle
 * @property integer $deleted
 * @property string $entity_id
 * @property string $revision_id
 * @property string $language
 * @property string $delta
 * @property string $field_news_tags_tid
 */
class FieldDataFieldNewsTags extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'field_data_field_news_tags';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db_tvod1');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['entity_type', 'deleted', 'entity_id', 'language', 'delta'], 'required'],
            [['deleted', 'entity_id', 'revision_id', 'delta', 'field_news_tags_tid'], 'integer'],
            [['entity_type', 'bundle'], 'string', 'max' => 128],
            [['language'], 'string', 'max' => 32]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'entity_type' => 'Entity Type',
            'bundle' => 'Bundle',
            'deleted' => 'Deleted',
            'entity_id' => 'Entity ID',
            'revision_id' => 'Revision ID',
            'language' => 'Language',
            'delta' => 'Delta',
            'field_news_tags_tid' => 'Field News Tags Tid',
        ];
    }
}


text:
var getMapData = require('./_getMapData');

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

module.exports = mapCacheGet;


text:
%Notes by Harsh Mistry
%Stat231
%based on Template from : https://www.cs.cmu.edu/~ggordon/10725-F12/template.tex

\documentclass{article}
\setlength{\oddsidemargin}{0.25 in}
\setlength{\evensidemargin}{-0.25 in}
\setlength{\topmargin}{-0.6 in}
\setlength{\textwidth}{6.5 in}
\setlength{\textheight}{8.5 in}
\setlength{\headsep}{0.75 in}
\setlength{\parindent}{0 in}
\setlength{\parskip}{0.1 in}
\usepackage{amsfonts,graphicx, amssymb}
\usepackage[fleqn]{amsmath}
\usepackage{fixltx2e}
\usepackage{tikz}
\usepackage{color}
\usepackage{tcolorbox}
\usepackage{lipsum}
\usepackage{listings}
\usepackage{scrextend}
\tcbuselibrary{skins,breakable}
\usetikzlibrary{shadings,shadows}
\newcounter{lecnum}
\renewcommand{\thepage}{\thelecnum-\arabic{page}}
\renewcommand{\thesection}{\thelecnum.\arabic{section}}
\renewcommand{\theequation}{\thelecnum.\arabic{equation}}
\renewcommand{\thefigure}{\thelecnum.\arabic{figure}}
\renewcommand{\thetable}{\thelecnum.\arabic{table}}
\newcommand{\lecture}[4]{
   \pagestyle{myheadings}
   \thispagestyle{plain}
   \newpage
   \setcounter{lecnum}{#1}
   \setcounter{page}{1}

%Info Box
   \begin{center}
   \framebox{
      \vbox{\vspace{2mm}
    \hbox to 6.28in { {\bf Stat 231 - Statistics
	\hfill Spring 2017} }
       \vspace{4mm}
       \hbox to 6.28in { {\Large \hfill Lecture #1: #2  \hfill} }
       \vspace{2mm}
       \hbox to 6.28in { {\it Lecturer: #3 \hfill Notes By: #4} }
      \vspace{2mm}}
   }
   \end{center}

   \markboth{Lecture #1: #2}{Lecture #1: #2}

}

\renewcommand{\cite}[1]{[#1]}
\def\beginrefs{\begin{list}%
        {[\arabic{equation}]}{\usecounter{equation}
         \setlength{\leftmargin}{2.0truecm}\setlength{\labelsep}{0.4truecm}%
         \setlength{\labelwidth}{1.6truecm}}}
\def\endrefs{\end{list}}
\def\bibentry#1{\item[\hbox{[#1]}]}

\newcommand{\fig}[3]{
			\vspace{#2}
			\begin{center}
			Figure \thelecnum.#1:~#3
			\end{center}
	}

\newcommand{\pipe}{\(\mid\)}
\newcommand{\ctr}{\(\wedge\)}

\newtheorem{theorem}{Theorem}[lecnum]
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{ex}[theorem]{Example}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{definition}[theorem]{Definition}
\newenvironment{proof}{{\bf Proof:}}{\hfill\rule{2mm}{2mm}}
\newcommand\E{\mathbb{E}}

%color definitions :
\definecolor{darkred}{rgb}{0.55, 0.0, 0.0}
\definecolor{lightcoral}{rgb}{0.94, 0.5, 0.5}
\definecolor{tomato}{rgb}{1.0, 0.39, 0.28}
\definecolor{lightgray}{rgb}{.9,.9,.9}
\definecolor{darkgray}{rgb}{.4,.4,.4}
\definecolor{purple}{rgb}{0.65, 0.12, 0.82}
\definecolor{lightgreen}{rgb}{0.56, 0.93, 0.56}
\definecolor{darkgreen}{rgb}{0.0, 0.2, 0.13}
\definecolor{limegreen}{rgb}{0.2, 0.8, 0.2}
\definecolor{lightblue}{rgb}{0.68, 0.85, 0.9}
\definecolor{darkblue}{rgb}{0.0, 0.0, 0.55}

%Environments
\newenvironment{exblock}[1]{%
    \tcolorbox[beamer,%
    noparskip,breakable,
    colback=lightgreen,colframe=darkgreen,%
    colbacklower=limegreen!75!lightgreen,%
    title=#1]}%
    {\endtcolorbox}

\newenvironment{ablock}[1]{%
    \tcolorbox[beamer,%
    noparskip,breakable,
    colback=lightcoral,colframe=darkred,%
    colbacklower=tomato!75!lightcoral,%
    title=#1]}%
    {\endtcolorbox}

\newenvironment{cblock}[1]{%
    \tcolorbox[beamer,%
    noparskip,breakable,
    colback=lightblue,colframe=darkblue,%
    colbacklower=darkblue!75!lightblue,%
    title=#1]}%
    {\endtcolorbox}

%Languages
\lstdefinelanguage{JavaScript}{
  keywords={typeof, new, true, false, catch, function, return, null, catch, switch, var, if, in, while, do, else, case, break},
  keywordstyle=\color{blue}\bfseries,
  ndkeywords={class, export, boolean, throw, implements, import, this},
  ndkeywordstyle=\color{darkgray}\bfseries,
  identifierstyle=\color{black},
  sensitive=false,
  comment=[l]{//},
  morecomment=[s]{/*}{*/},
  commentstyle=\color{purple}\ttfamily,
  stringstyle=\color{red}\ttfamily,
  morestring=[b]',
  morestring=[b]"
}

%Listings
\lstset{
   language=JavaScript,
   backgroundcolor=\color{lightgray},
   extendedchars=true,
   basicstyle=\footnotesize\ttfamily,
   showstringspaces=false,
   showspaces=false,
   numbers=left,
   numberstyle=\footnotesize,
   numbersep=9pt,
   tabsize=2,
   breaklines=true,
   showtabs=false,
   captionpos=b
}

%Start
\begin{document}

\lecture{19, 20, 21, 22, 23, 24}{June 12th - June 23nd, 2017}{Suryapratim Banerjee}{Harsh Mistry}

\section{T-Distribution Recap}
\(T_n\) is a continuous random variable in \((- \infty, \infty)\) that is said to follow a student's T distribution with n degrees of freedom if T is a ratio of two independent random variables.
$$ T = \frac{Z}{W} $$
Where \(Z \sim G(0,1)\) and \(W = \sqrt{x^2(n) / n} \)

\subsection*{Properties}
\begin{itemize}
\item \(T_n\) is symmetric around zero for all n
\item \(T_n\) looks like the Z-distribution but with a higher kurtosis.
\item n = parameter of the T-distribution
\item As  ns approach infinity and \(T \rightarrow Z\), The T looks like the z
\end{itemize}

\section{T Table}

\begin{theorem}
Let \(y_1 \ldots y_n\) be independent Gaussian random variables with mean \(\mu \text{ and }  \sigma^2\)
Define
$$ \bar{Y} = \frac{1}{n} \sum Y_i \text{ (estimator)} $$
$$  S^2 = \frac{1}{n-1} \sum (Y_i - \bar{Y})^2  \text{ (estimator corresponding to its sample variance)}$$
Then
$$
\frac{\bar{Y} -  \mu}{S / \sqrt{n}} \sim T_{n-1}$$
$$ \frac{(n-1)S^2}{\sigma^2} \sim X^2_{n-1}$$
\end{theorem}

\textbf{Confidence Interval for \(\mu\)}
\begin{enumerate}
\item \(Y_1 \sim G(\mu, r)\)
\item \(\hat{\mu} = \bar{y} \rightarrow \) Estimate
\item \(\bar{Y} \rightarrow\) estimator
\item Construct the pivotal distribution
$$ \frac{\bar{y} - \mu }{S / \sqrt{n}} \sim T_{n-1}$$
\item Find the end points of the pivot (Look in row (n-1) column = percentage)
\item Construct the coverage Interval
$$ P( -c < \frac{\bar{Y} - mu}{\frac{S}{\sqrt{n}}} < c ) = percentage $$
$$ P( \bar{Y} - c \frac{S}{\sqrt{n}} \leq \mu \leq \bar{Y} + c \frac{S}{\sqrt{n}}) = percentage$$
\item Replace \(\bar{Y}\) with \(\bar{y}\)
\end{enumerate}
\textbf{Confidence Interval for \(\sigma^2\) }
\begin{enumerate}
\item Find \(s^2\)
\item Estimator = \(S^2\)
\item Pivotal
$$\frac{(n-1)S^2}{\sigma^2} \sim X^2_{n-1}$$
\item Find Coverage interval from \(x^2\) table
\item Find Confidence Interval
\end{enumerate}

\section{Other Distributions}
\subsection*{Poison Problem}
\begin{itemize}
\item Find Estimate for \(\theta\)
\[\hat{\theta} = \bar{y}\]
\item Estimator of \(\bar{y} \rightarrow \bar{Y}\)
\item By the CLT
\[\frac{\bar{Y} - \theta}{\sqrt{\bar{Y} / n}} \sim G(0,1) \]
\item Construct the coverage Interval
$$ P( -c < \frac{\bar{Y} - \theta}{\sqrt{\bar{Y} / n}} < c ) = percentage $$
$$  \bar{Y} \pm c \sqrt{\bar{Y} / n} $$
\subsection*{Exponential Problem}
Mean = \(\theta\); Variance \(\theta^2\)
$$ \bar{Y} \sim G(\theta , \theta/ \sqrt{n}) $$
$$ \frac{\bar{Y} - \theta}{\theta / \sqrt{n}} = z $$
\end{itemize}

\subsection*{Exact Interval for the Exponential Problem}
If \(Y_i \sim Exp(\theta) \) then
$$ \frac{2 Y_i}{\theta} \sim Exp(2) \sim X^2(2) $$

\section{Relationship between Likelihood Intervals and Confidence Intervals}

Assume N is large

\begin{theorem}
If \(\theta\) is the true value of the parameter; \(\hat{\theta}\) is the MLE; Then
$$ \delta (\theta) = - 2 log \frac{L(\theta)}{L(\tilde{\theta})} \sim X^2 (1)	$$
\(\delta\) = Likelihood Ratio Test Statistic
\end{theorem}

\section{Hypothesis Testing}
\begin{definition}
A hypothesis is a statement made about some attribute of the population
$$ H_ 0 : \theta = \theta_0 $$
\end{definition}

Two claims are tested against each other
\begin{itemize}
\item \(H_0\) : Null Hypothesis = Current conventional wisdom
\item \(H_1\) : Alternate Hypothesis = Challenging view
\end{itemize}

\begin{definition}
a \textbf{p-value} is the probability of observing your evidence (or worse) given that the null hypothesis is true.
\end{definition}

\begin{ablock}{Notes}
\(H_0\) and \(H_1\) are not treated symmetrically unless we have "overwhelming evidence against \(H_0\), we do not reject it. The burden of proof is on \(H_1\)
\end{ablock}

\begin{itemize}
\item \(p > 0.1 \implies\) No evidence against \(H_0\)
\item \(0. 05 < p \leq 0.1 \implies \) Weak evidence against \(H_0\)
\item \(0.01 <  p \leq 0.05 \implies \) Strong evidence against \(H_0\)
\item \(p \leq 0.01 \implies\) Very string evidence against \(H_0\)
\end{itemize}

"Statistically significant" \(\rightarrow\) p-value of the test \(\leq\) 0.05

\begin{itemize}
\item If \(p < 0.05 \implies\) Reject \(H_0\) at \(5\%\) level of significance
\item If \(p > 0.05 \implies\) Do not reject \(H_0\)
\end{itemize}

\subsection*{Type Errors}
\begin{itemize}
\item Type I error : Rejecting \(H_0\) when its actually true
\item Type II error : Do not reject \(H_0\) when it is actually false
\end{itemize}
These Two errors may conflict with each other.

\subsection*{Statistical Tests}
\begin{itemize}
\item Discrepancy measure : A random variable that measures the level of disagreement of the data with the null hypothesis.
\begin{itemize}
\item The distribution of D is known
\item \(D \geq 0\) and \(D = 0\), is the best evidence for the \(H_0\)
\item p-value : \(P(D \geq d; H_0 \text{ is true } )\) where d - value of D in your sample

\end{itemize}
\end{itemize}

\end{document}


text:
<!DOCTYPE html>

  This test is verifying that when the outline is added to an element
  that we correctly invalidate any continuations.

  If this test passes, you should see a green border around the text contents.

CONTENTS


text:
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Globalization;
using System.Reflection;

using Rhino.Mocks.Impl;
using Rhino.Mocks.Interfaces;

namespace Rhino.Mocks.MethodRecorders
{
	/// <summary>
	/// Hold an expectation for a method call on an object
	/// </summary>
	public class ProxyMethodExpectationTriplet
	{
		private object proxy;
		private MethodInfo method;
		private IExpectation expectation;

		/// <summary>
		/// Creates a new <see cref="ProxyMethodExpectationTriplet"/> instance.
		/// </summary>
		/// <param name="proxy">Proxy.</param>
		/// <param name="method">Method.</param>
		/// <param name="expectation">Expectation.</param>
		public ProxyMethodExpectationTriplet(object proxy, MethodInfo method, IExpectation expectation)
		{
			Validate.IsNotNull(proxy, "proxy");
			Validate.IsNotNull(method, "method");
			Validate.IsNotNull(expectation, "expectation");
			this.proxy = proxy;
			this.method = method;
			this.expectation = expectation;
		}

		/// <summary>
		/// Gets the proxy.
		/// </summary>
		/// <value></value>
		public object Proxy
		{
			get { return proxy; }
		}

		/// <summary>
		/// Gets the method.
		/// </summary>
		/// <value></value>
		public MethodInfo Method
		{
			get { return method; }
		}

		/// <summary>
		/// Gets the expectation.
		/// </summary>
		/// <value></value>
		public IExpectation Expectation
		{
			get { return expectation; }
			set { expectation = value; }
		}

		/// <summary>
		/// Determines if the object equal to this instance
		/// </summary>
		/// <param name="obj">Obj.</param>
		/// <returns></returns>
		public override bool Equals(object obj)
		{
			ProxyMethodExpectationTriplet other = obj as ProxyMethodExpectationTriplet;
			if (other == null)
				return false;
			return method == other.method &&
                MockedObjectsEquality.Instance.Compare(proxy, other.proxy) == 0 &&
				expectation == other.expectation;
		}

		/// <summary>
		/// Gets the hash code.
		/// </summary>
		/// <returns></returns>
		public override int GetHashCode()
		{
			return method.GetHashCode() + MockedObjectsEquality.Instance.GetHashCode(proxy) + expectation.GetHashCode();
		}
	}
}


text:
/**
 *
 */
/**
 * @author WFF This package contains the classes related to cloning.
 *
 */
package com.webfirmframework.wffweb.clone;


text:
![Try it now in CWS](https://raw.github.com/GoogleChrome/chrome-app-samples/master/tryitnowbutton.png "Click here to install this sample from the Chrome Web Store")

# Analytics

This example demonstrates how to include support for Google Analytics in your
packaged application. It uses the
[chrome-platform-analytics](https://github.com/GoogleChrome/chrome-platform-analytics) library,
which allows tracking app views or any arbitrary event to Google Analytics.
See more at the [project wiki](https://github.com/GoogleChrome/chrome-platform-analytics/wiki)

*Please note: You will need to modify main.js to include real Google Analytics credentials.*

## Resources

* [Runtime](http://developer.chrome.com/apps/app.runtime.html)
* [Window](http://developer.chrome.com/apps/app.window.html)
* [chrome-platform-analytics](https://github.com/GoogleChrome/chrome-platform-analytics/wiki)

## Screenshot
![screenshot](/samples/analytics/assets/screenshot_1280_800.png)


text:
package com.netflix.servo.publish.atlas;

/**
 * A simple implementation of {@link ServoAtlasConfig} that uses system properties to get
 * values.
 */
public class BasicAtlasConfig implements ServoAtlasConfig {
  @Override
  public String getAtlasUri() {
    return System.getProperty("servo.atlas.uri");
  }

  @Override
  public int getPushQueueSize() {
    String pushQueueSize = System.getProperty("servo.atlas.queueSize", "1000");
    return Integer.parseInt(pushQueueSize);
  }

  @Override
  public boolean shouldSendMetrics() {
    String enabled = System.getProperty("servo.atlas.enabled", "true");
    return Boolean.parseBoolean(enabled);
  }

  @Override
  public int batchSize() {
    String batch = System.getProperty("servo.atlas.batchSize", "10000");
    return Integer.parseInt(batch);
  }
}


text:
layout: page
title: Projects
---

This page lists the various open source projects I'm working on or have published.

## My Projects

 * **[Dat Webext](https://github.com/cliqz-oss/dat-webext)** - A webextension allowing [`dat://` protocol](//dat.foundation) URLs
 to be loaded in Firefox. Currently shipped in the beta version of the [Cliqz Browser](https://cliqz.com/en/latest). _Typescript_.
 * **[Autoconsent](https://github.com/cliqz-oss/autoconsent)** - Library for automated navigation of cookie
 consent notices across the web. _Javascript_.
 * **[URL Parser](https://github.com/cliqz/url-parser)** - A fast typescript implementation of the `window.URL`
 class and spec. Up to 10x faster than other standard implementations. _Typescript_.
 * **[libdwebify](https://github.com/sammacbeth/libdwebify)** - [Browserify](https://github.com/browserify/browserify) transform for polyfilling node networking libraries with [libdweb](https://github.com/mozilla/libdweb) replacements. _Javascript_.
 * **[dat-fox](https://github.com/sammacbeth/dat-fox)** and **[dat-fox helper](https://github.com/sammacbeth/dat-fox-helper)** - A webextension to add `dat://` support to Firefox, using only existing APIs. Superceded by Dat webext. _Javascript_.
 * **[@sammacbeth/types](https://github.com/sammacbeth/types)** - Typescript annotations for node modules,
 including the Dat datastructures, `hyperdrive` and `hypercore`. _Typescript_.

## Projects I contribute to

 * **[Cliqz Concept Browser](https://github.com/cliqz/cliqz-concept-browser)** - A Geckoview browser, forked from the [reference browser](https://github.com/mozilla-mobile/reference-browser) that supports loading `dat://` urls and includes [Cliqz](https://cliqz.com) quick-search. _Kotlin_.
 * **[Re:Consent](https://github.com/cliqz-oss/re-consent)** - A [webextension](https://cliqz.com/en/magazine/re-consent) giving you control over your consent settings on various websites. _Javascript_.
 * **[WhoTracks.Me](https://github.com/cliqz-oss/whotracks.me)** - Website providing transparency about online
 tracking, based on Cliqz and Ghostery data. _Python_.
 * **[Ghostery Extension](https://github.com/ghostery/ghostery-extension)** - Ghostery's browser extension. _Javascript_.
 * **[Browser-core](https://github.com/cliqz-oss/browser-core)** - Core Cliqz browser features. _Javascript_.
 * **[dgram-adaptor](https://github.com/libdweb/dgram-adapter)** - Polyfill of the node `dgram` API for
 webextensions using libdweb. _Javascript_.
 * **[libdweb](https://github.com/mozilla/libdweb)** - Special webextension APIs for Firefox to enable
 dweb applications. _Javascript._


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/io/p10_io_init_done.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_io_init_done.H
/// @brief Wait for dccal done and power-up all configured links/lanes
///-----------------------------------------------------------------------------
/// *HW HW Maintainer: Chris Steffen <cwsteffen@us.ibm.com>
/// *HW FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HW Consumed by  : HB
///-----------------------------------------------------------------------------

#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
typedef fapi2::ReturnCode (*p10_io_init_done_FP_t)(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

extern "C"
{

///
/// @brief Wait for dccal done and power-up all configured links/lanes
///
/// @param[in] i_target Chip target to start
///
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
    fapi2::ReturnCode p10_io_init_done(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern "C"


text:
using namespace std;
using namespace ev3dev;

void delta_hand::init() {
  // Run the base configuration in a separate thread.
  thread base([=]() {
    delta_robot::init();
  });

  const auto stall_time = chrono::milliseconds(100);

  // Start running the grabber motor indefinitely.
  hand.reset();
  hand.set_stop_command(motor::stop_command_coast);
  hand.set_duty_cycle_sp(-80);
  grab_close = hand.position();
  hand.run_forever();

  // Wait until all the motors hit the zero position.
  while (hand.state().count("running")) {
    this_thread::sleep_for(stall_time);
    int pos = hand.position();
    if (pos >= grab_close)
      hand.stop();
    else
      grab_close = pos;
  }
  grab_open = grab_close;

  hand.set_duty_cycle_sp(80);
  hand.run_forever();

  while (hand.state().count("running")) {
    this_thread::sleep_for(stall_time);
    int pos = hand.position();
    if (pos <= grab_open)
      hand.stop();
    else
      grab_open = pos;
  }

  // We always want the hand to move as quickly as possible.
  hand.set_duty_cycle_sp(100);

  // Wait for the base's init.
  base.join();
}


text:
layout: post
title: "Is consistency a bad thing?"
description: "Is consistency always something to aim for in a codebase?"
tags: [Code smells, Clean code]
---

Like most developers I've met, I've always believed consistency in code to be a good thing.

Recently though I've been starting to question if consistency is always a good thing.

## What do I mean by consistency?

Consistency can be applied to many areas within a codebase. You can have consistent naming strategies, formatting rules, and code design patterns to name just a few.

When it comes to formatting, people can often have very strongly held views. Tabs Vs spaces, do braces for a function start with a new line, should you end a line with a semicolon, and so on.

If you are spending time thinking about formatting consistencies you are a very lucky developer. If those are your biggest issues, you've done a great job, go ahead and take the rest of the day off. Unless these formatting inconsistencies are stopping the code from compiling or causing massive readability issues, I wouldn't really worry about them. Or better yet, have the conversation once and stick a linter in your project.

The other main area I've seen discussed when it comes to consistency is the patterns within the application logic. For example, how the data access objects are structured or how a request is parsed into the application domain.

## Good points for consistency

Now don't get me wrong, consistency can be very helpful.

One of the main aims I hear for consistency is making it easier for other developers to understand how the code works across the application. This is a strong point for consistency. It's rare a single developer will be working on an application, so making things easy for your teammates is pretty important.

"Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. ...[Therefore,] making it easy to read makes it easier to write" (Robert c Martin, Clean Code)

Keeping a codebase readable should be one of the main aims of a developer. One of the worst things a developer can do is to reduce the readability of code. By giving patterns to recognise, code readability can be another benefit of sticking to consistent patterns.

## Bad points for consistency

It's clear that consistency can be very helpful, but recently I've been thinking it might be a bit of a code smell. So rather than just sticking with consistency for consistency's sake, maybe think about some of the following points as well.

#### Inertia

I've seen consistency become a real blocker when it comes to refactoring. When you have the same pattern in many places throughout a codebase, when you see a refactoring you want to implement, having to do that refactoring in many places can be time consuming. Sometimes to the point where the benefits of the refactoring are outweighed by the time to implement it.

Communication can help here. Maybe you don't need to refactor every single instance of a pattern. Try refactoring the one instance you originally wanted to, but make sure you communicate with the team that you have done this.

Big refactorings scare me. It's too easy for them to turn in to a thread that just won't stop unraveling. I think the boy scout role is much more effective. Every time you touch code, leave it in a better state than you found it. Even if that's just renaming one variable, the codebase will quickly start to look great. But I find the need for consistency at odds with this approach. It's easy to feel, "I can't just update this, it won't be consistent with the rest of the application". This can lead to just keeping the status quo.

The inertia of trying to make big changes is much greater than if you are making many small ones.

#### Highlighting duplication

If the consistency you are trying to protect is something like a design pattern, then maybe this is a sign of duplication of logic. The fact that there are multiple things done in a consistent way may mean there is a possibility for a cleaner more general implementation that you could be using.

#### Unit testing

If your unit tests are a mirror of your code then consistency can mean you have to update all your tests every time you refactor your code. However, your tests shouldn't be a mirror of your code. The test suite should be a collection of the units of work. If you have to update all your tests every time you refactor, these are likely to be implementation tests rather than unit tests.

#### Making it easier for others

I've seen "making it easier for new team members to navigate around the codebase" be a reason why consistency is important. However, if consistency is the enabling factor for navigation, perhaps that is a signal that the code could be cleaner anyway.

By following Uncle Bob's techniques for clean code, such as naming things clearly and many small functions that do one thing, the code could be easier to navigate. I would rather find my way around a code base that "reads like well written prose" (Grady Booch) rather than relying on spotting a duplicated pattern.

## Conclusion

I'm not saying consistency is a bad thing or that it should be avoided. But if you are ever tempted not to refactor code to preserve consistency, I would be on the lookout for other code smells such as duplication, code that could be cleaner, or unit tests that are too closely coupled to the implementation.


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:angle="270.0" android:endColor="@color/background"
        android:startColor="@color/background" />
</shape>