text:
ENT.Type = "anim"
ENT.Base = "base_anim"

function ENT:Initialize()
end

function ENT:Think()
end

function ENT:Draw()
end

redpajama_set_name: RedPajamaGithub


text:
.historyEntryContainer {
  list-style: none;
  flex: 1;
  width: 100%;
  border-bottom: 1px solid #EEE;
  margin: 0;
  display: flex;
  flex-direction: row;
}

.historyEntryContainerContent {
  padding: 10px;
  display: flex;
  flex: 1;
}

.textContainer {
  flex: 2;
  display: flex;
  align-content: center;
  align-items: flex-end;
}

.buttonsContainer {
  flex: 1;
  align-items: center;
  font-size: 12px;
  justify-content: flex-end;
  display: flex;
}


text:
import * as tape from 'tape';
import {TwingNodeBlockReference} from "../../../../../../src/lib/node/block-reference";
import {TwingNodeType} from "../../../../../../src/lib/node";
import {MockCompiler} from "../../../../../mock/compiler";

tape('node/block-reference', (test) => {
    test.test('constructor', (test) => {
        let node = new TwingNodeBlockReference('foo', 1, 1);

        test.same(node.getAttribute('name'), 'foo');
        test.same(node.getType(), TwingNodeType.BLOCK_REFERENCE);

        test.end();
    });

    test.test('compile', (test) => {
        let node = new TwingNodeBlockReference('foo', 1, 1);
        let compiler = new MockCompiler();

        test.same(compiler.compile(node).getSource(), `await this.traceableDisplayBlock(1, this.getSourceContext())(\'foo\', context.clone(), blocks);
`);

        test.end();
    });

    test.end();
});


text:
package org.apache.jena.sparql.graph;

import java.util.Iterator ;
import java.util.List ;

import org.apache.jena.atlas.iterator.Iter ;
import org.apache.jena.graph.Graph ;
import org.apache.jena.graph.Node ;
import org.apache.jena.graph.Triple ;
import org.apache.jena.sparql.core.DatasetGraph ;
import org.apache.jena.sparql.core.Quad ;

// Combine with Jena GraphUtils.
public class GraphOps
{

    public static boolean containsGraph(DatasetGraph dsg, Node gn)
    {
        // [[DynDS]]
        if ( Quad.isDefaultGraph(gn))
            return true ;
        if ( Quad.isUnionGraph(gn))
            return true ;
        return dsg.containsGraph(gn) ;
    }

    public static Graph getGraph(DatasetGraph dsg, Node gn)
    {
        // [[DynDS]]
        if ( gn == null )
            return dsg.getDefaultGraph() ;
        if ( Quad.isDefaultGraph(gn) )
            // Explicit or generated.
            return dsg.getDefaultGraph() ;
        if ( Quad.isUnionGraph(gn))
            return unionGraph(dsg) ;
        return dsg.getGraph(gn) ;
    }

    public static Graph unionGraph(DatasetGraph dsg)
    {
        List<Node> x = Iter.toList(dsg.listGraphNodes()) ;
        return new GraphUnionRead(dsg, x) ;
    }

    public static void addAll(Graph g, Iterator<Triple> iter)
    {
        while(iter.hasNext())
            g.add(iter.next()) ;
        Iter.close(iter) ;
    }

    public static void addAll(Graph g, Iterable<Triple> iter)
    {
        addAll(g, iter.iterator()) ;
    }

    public static void deleteAll(Graph g, Iterator<Triple> iter)
    {
        while(iter.hasNext())
            g.delete(iter.next()) ;
        Iter.close(iter) ;
    }

    public static void deleteAll(Graph g, Iterable<Triple> iter)
    {
        deleteAll(g, iter.iterator()) ;
    }

}


text:
<?php

namespace PHPCI\Plugin;

use PHPCI\Builder;
use PHPCI\Model\Build;

/**
 * IRC Plugin - Sends a notification to an IRC channel
 * @author       Dan Cryer <dan@block8.co.uk>
 * @package      PHPCI
 * @subpackage   Plugins
 */
class Irc implements \PHPCI\Plugin
{
    protected $phpci;
    protected $build;
    protected $message;
    protected $server;
    protected $port;
    protected $room;
    protected $nick;

    public function __construct(Builder $phpci, Build $build, array $options = array())
    {
        $this->phpci = $phpci;
        $this->build = $build;
        $this->message = $options['message'];

        $buildSettings = $phpci->getConfig('build_settings');

        if (isset($buildSettings['irc'])) {
            $irc = $buildSettings['irc'];

            $this->server = $irc['server'];
            $this->port = $irc['port'];
            $this->room = $irc['room'];
            $this->nick = $irc['nick'];
        }
    }

    public function execute()
    {
        $msg = $this->phpci->interpolate($this->message);

        if (empty($this->server) || empty($this->room) || empty($this->nick)) {
            $this->phpci->logFailure('You must configure a server, room and nick.');
        }

        if (empty($this->port)) {
            $this->port = 6667;
        }

        $sock = fsockopen($this->server, $this->port);
        fputs($sock, 'USER ' . $this->nick . ' phptesting.org ' . $this->nick . ' :' . $this->nick . "\r\n");
        fputs($sock, 'NICK ' . $this->nick . "\r\n");
        fputs($sock, 'PRIVMSG ' . $this->room . ' :' . $msg . "\r\n");

        while (fgets($sock)) {
            // We don't need to do anything,
            // but the IRC server doesn't appear to post the message
            // unless we wait for responses.
        }

        fclose($sock);

        return true;
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>AWSSTSAssumeRoleWithWebIdentityResponse Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				AWS Mobile SDK for iOS v2.4.1

				Amazon Web Services, Inc.

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/assumedRoleUser">assumedRoleUser</option>

		<option value="//api/name/audience">audience</option>

		<option value="//api/name/credentials">credentials</option>

		<option value="//api/name/packedPolicySize">packedPolicySize</option>

		<option value="//api/name/provider">provider</option>

		<option value="//api/name/subjectFromWebIdentityToken">subjectFromWebIdentityToken</option>

	</optgroup>

</select>

AWSSTSAssumeRoleWithWebIdentityResponse Class Reference

	Inherits from
	AWSModel : AWSMTLModel

	Declared in
	AWSSTSModel.h
AWSSTSModel.m

Overview

Contains the result of a successful call to the AssumeRoleWithWebIdentity action, including temporary AWS credentials that can be used to make AWS requests.

  assumedRoleUser

The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers that you can use to refer to the resulting temporary security credentials. For example, you can reference these credentials as a principal in a resource-based policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName that you specified when you called AssumeRole.

@property (nonatomic, strong) AWSSTSAssumedRoleUser *assumedRoleUser

Declared In

AWSSTSModel.h

  audience

 The intended audience of the web identity token. This is traditionally the client identifier issued to the application that requested the web identity token.

@property (nonatomic, strong) NSString *audience

Declared In

AWSSTSModel.h

  credentials

The temporary security credentials, which include an access key ID, a secret access key, and a security token.

@property (nonatomic, strong) AWSSTSCredentials *credentials

Declared In

AWSSTSModel.h

  packedPolicySize

A percentage value that indicates the size of the policy in packed form. The service rejects any policy with a packed size greater than 100 percent, which means the policy exceeded the allowed space.

@property (nonatomic, strong) NSNumber *packedPolicySize

Declared In

AWSSTSModel.h

  provider

 The issuing authority of the web identity token presented. For OpenID Connect ID Tokens this contains the value of the iss field. For OAuth 2.0 Access Tokens, this contains the value of the ProviderId parameter that was passed in the AssumeRoleWithWebIdentity request.

@property (nonatomic, strong) NSString *provider

Declared In

AWSSTSModel.h

  subjectFromWebIdentityToken

The unique user identifier that is returned by the identity provider. This identifier is associated with the WebIdentityToken that was submitted with the AssumeRoleWithWebIdentity call. The identifier is typically unique to the user and the application that acquired the WebIdentityToken (pairwise identifier). If an OpenID Connect ID token was submitted in the WebIdentityToken, this value is returned by the identity provider as the token's sub (Subject) claim.

@property (nonatomic, strong) NSString *subjectFromWebIdentityToken

Declared In

AWSSTSModel.h

Copyright © 2016 Amazon Web Services, Inc. All rights reserved. Updated: 2016-04-28

Generated by appledoc 2.2.1 (build 1333).


text:
package org.terracotta.management.entity.management.client;

import org.terracotta.management.model.Objects;
import org.terracotta.management.model.call.ContextualCall;
import org.terracotta.management.model.call.ContextualReturn;
import org.terracotta.management.model.call.Parameter;
import org.terracotta.management.model.capabilities.Capability;
import org.terracotta.management.model.cluster.ClientIdentifier;
import org.terracotta.management.model.context.Context;
import org.terracotta.management.model.context.ContextContainer;
import org.terracotta.management.model.message.ManagementCallMessage;
import org.terracotta.management.model.notification.ContextualNotification;
import org.terracotta.management.model.stats.ContextualStatistics;
import org.terracotta.management.registry.ManagementProvider;
import org.terracotta.management.registry.ManagementProviderAdapter;
import org.terracotta.management.registry.ManagementRegistry;
import org.terracotta.voltron.proxy.client.messages.MessageListener;

import java.io.Closeable;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Mathieu Carbou
 */
public class ManagementAgentService implements Closeable {

  private static final Logger LOGGER = Logger.getLogger(ManagementAgentService.class.getName());

  private final ManagementAgentEntity entity;
  private final ClientIdentifier clientIdentifier;

  private volatile ManagementRegistry registry;
  private volatile boolean bridging = false;

  private ContextualReturnListener contextualReturnListener = new ContextualReturnListenerAdapter();
  private long timeout = 5000;
  private Executor managementCallExecutor = new Executor() {
    @Override
    public void execute(Runnable command) {
      command.run();
    }
  };

  private final ManagementProvider<?> managementProvider = new ManagementProviderAdapter<Object>(ManagementAgentService.class.getSimpleName(), Object.class) {
    @Override
    public void register(Object managedObject) {
      // expose the registry each time a new object is registered in the management registry
      if (bridging) {
        setCapabilities(registry.getContextContainer(), registry.getCapabilities());
      }
    }

    @Override
    public void unregister(Object managedObject) {
      // expose the registry each time a new object is registered in the management registry
      if (bridging) {
        setCapabilities(registry.getContextContainer(), registry.getCapabilities());
      }
    }
  };

  public ManagementAgentService(final ManagementAgentEntity entity) {
    this.clientIdentifier = get(entity.getClientIdentifier(null), 20000);
    this.entity = Objects.requireNonNull(entity);
    this.entity.registerListener(new MessageListener<ManagementCallMessage>() {
      @Override
      public void onMessage(final ManagementCallMessage message) {
        if (message.getType().equals("MANAGEMENT_CALL")) {
          final ContextualCall contextualCall = message.unwrap(ContextualCall.class).get(0);
          managementCallExecutor.execute(new Runnable() {
            @Override
            public void run() {
              try {
                // check again because in another thread
                if (bridging) {
                  ContextualReturn<?> aReturn = registry.withCapability(contextualCall.getCapability())
                      .call(contextualCall.getMethodName(), contextualCall.getReturnType(), contextualCall.getParameters())
                      .on(contextualCall.getContext())
                      .build()
                      .execute()
                      .getSingleResult();
                  // check again in case the management call takes some time
                  if (bridging) {
                    get(entity.callReturn(null, message.getFrom(), message.getManagementCallIdentifier(), aReturn), timeout);
                  }
                }
              } catch (RuntimeException err) {
                if(LOGGER.isLoggable(Level.WARNING)) {
                  LOGGER.log(Level.WARNING, "Error on management call execution or result sending for " + contextualCall + ". Error: " + err.getMessage(), err);
                }
              }
            }
          });

        } else if (message.getType().equals("MANAGEMENT_CALL_RETURN")) {
          final ContextualReturn<?> aReturn = message.unwrap(ContextualReturn.class).get(0);
          managementCallExecutor.execute(new Runnable() {
            @Override
            public void run() {
              try {
                contextualReturnListener.onContextualReturn(message.getFrom(), message.getManagementCallIdentifier(), aReturn);
              } catch (RuntimeException err) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                  LOGGER.log(Level.WARNING, "Error on management call result listener for " + message + ". Error: " + err.getMessage(), err);
                }
              }
            }
          });
        }
      }
    });
  }

  /**
   * Bridges a management registry with a management entity. All exposure in the registry will be propagated to the server and
   * it will listen for management calls also.
   */
  public synchronized ManagementAgentService bridge(ManagementRegistry registry) {
    if (!bridging) {
      this.registry = registry;
      registry.addManagementProvider(managementProvider);
      // expose the registry when CM is first available
      Collection<Capability> capabilities = registry.getCapabilities();
      get(entity.exposeManagementMetadata(null, registry.getContextContainer(), capabilities.toArray(new Capability[capabilities.size()])), timeout);
      bridging = true;
    }
    return this;
  }

  @Override
  public synchronized void close() {
    if (bridging) {
      registry.removeManagementProvider(managementProvider);
      bridging = false;
    }
  }

  // config ops

  public ManagementAgentService setContextualReturnListener(ContextualReturnListener contextualReturnListener) {
    this.contextualReturnListener = Objects.requireNonNull(contextualReturnListener);
    return this;
  }

  public ManagementAgentService setManagementCallExecutor(Executor managementCallExecutor) {
    this.managementCallExecutor = Objects.requireNonNull(managementCallExecutor);
    return this;
  }

  public ManagementAgentService setOperationTimeout(long duration, TimeUnit unit) {
    this.timeout = TimeUnit.MILLISECONDS.convert(duration, unit);
    return this;
  }

  // features

  public void setCapabilities(ContextContainer contextContainer, Collection<Capability> capabilities) {
    setCapabilities(contextContainer, capabilities.toArray(new Capability[capabilities.size()]));
  }

  public void setCapabilities(ContextContainer contextContainer, Capability... capabilities) {
    get(entity.exposeManagementMetadata(null, contextContainer, capabilities), timeout);
  }

  public void setTags(Collection<String> tags) {
    setTags(tags.toArray(new String[tags.size()]));
  }

  public void setTags(String... tags) {
    get(entity.exposeTags(null, tags), timeout);
  }

  public void pushNotification(ContextualNotification notification) {
    if (notification != null) {
      notification.setContext(notification.getContext().with("clientId", clientIdentifier.getClientId()));
      get(entity.pushNotification(null, notification), timeout);
    }
  }

  public void pushStatistics(ContextualStatistics... statistics) {
    if (statistics.length > 0) {
      for (ContextualStatistics statistic : statistics) {
        statistic.setContext(statistic.getContext().with("clientId", clientIdentifier.getClientId()));
      }
      get(entity.pushStatistics(null, statistics), timeout);
    }
  }

  public void pushStatistics(Collection<ContextualStatistics> statistics) {
    pushStatistics(statistics.toArray(new ContextualStatistics[statistics.size()]));
  }

  public ClientIdentifier getClientIdentifier() {
    return clientIdentifier;
  }

  public Collection<ClientIdentifier> getManageableClients() {
    return get(entity.getManageableClients(null), timeout);
  }

  /**
   * Execute a management call and do not expect any return result.
   * <p>
   * Returns a unique identifier for this management call.
   */
  public String call(ClientIdentifier to, Context context, String capabilityName, String methodName, Class<?> returnType, Parameter... parameters) {
    return get(entity.call(null, to, context, capabilityName, methodName, returnType, parameters), timeout);
  }

  private static <V> V get(Future<V> future, long timeout) {
    try {
      return future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IllegalStateException(e);
    } catch (ExecutionException e) {
      throw new IllegalStateException(e.getCause());
    } catch (TimeoutException e) {
      throw new IllegalStateException("Timed out after " + timeout + "ms.", e);
    }
  }

}


text:
/**
 * Created by Samuel Gratzl on 04.08.2014.
 */

import {EventHandler, IEventHandler, IEventListener} from '../base/event';
import {Range, RangeLike, ParseRangeUtils} from '../range';
import {SelectOperation, SelectionUtils} from './SelectionUtils';
import {IDType} from './IDType';

export interface ISelectAble extends IEventHandler {
  ids(range?: RangeLike): Promise<Range>;

  fromIdRange(idRange?: RangeLike): Promise<Range>;

  readonly idtypes: IDType[];

  selections(type?: string): Promise<Range>;

  select(range: RangeLike): Promise<Range>;
  select(range: RangeLike, op: SelectOperation): Promise<Range>;
  select(type: string, range: RangeLike): Promise<Range>;
  select(type: string, range: RangeLike, op: SelectOperation): Promise<Range>;
  select(dim: number, range: RangeLike): Promise<Range>;
  select(dim: number, range: RangeLike, op: SelectOperation): Promise<Range>;
  select(dim: number, type: string, range: RangeLike): Promise<Range>;
  select(dim: number, type: string, range: RangeLike, op: SelectOperation): Promise<Range>;

  /**
   * clear the specific selection (type) and dimension
   */
  clear(): Promise<any>;
  clear(type: string): Promise<any>;
  clear(dim: number): Promise<any>;
  clear(dim: number, type: string): Promise<any>;
}

interface ISingleSelectionListener {
  (event: any, type: string, act: Range, added: Range, removed: Range): void;
}

export abstract class ASelectAble extends EventHandler implements ISelectAble {
  static readonly EVENT_SELECT = IDType.EVENT_SELECT;

  private numSelectListeners = 0;
  private selectionListeners: ISingleSelectionListener[] = [];
  private singleSelectionListener = async (event: any, type: string, act: Range, added: Range, removed: Range) => {
    const ids = await this.ids();
    //filter to the right ids and convert to indices format
    //given all ids convert the selected ids to the indices in the data type
    act = ids.indexOf(act);
    added = ids.indexOf(added);
    removed = ids.indexOf(removed);
    if (act.isNone && added.isNone && removed.isNone) {
      return;
    }
    //ensure the right number of dimensions
    SelectionUtils.fillWithNone(act, ids.ndim);
    SelectionUtils.fillWithNone(added, ids.ndim);
    SelectionUtils.fillWithNone(removed, ids.ndim);

    this.fire(ASelectAble.EVENT_SELECT, type, act, added, removed);
    this.fire(`${ASelectAble.EVENT_SELECT}-${type}`, act, added, removed);
  }
  private selectionCache: {act: Range, added: Range, removed: Range}[] = [];
  private accumulateEvents = -1;

  abstract ids(range?: RangeLike): Promise<Range>;

  async fromIdRange(idRange: RangeLike = Range.all()) {
    return (await this.ids()).indexOf(ParseRangeUtils.parseRangeLike(idRange));
  }

  get idtypes(): IDType[] {
    return [];
  }

  private selectionListener(idtype: IDType, index: number, total: number) {
    return (event: any, type: string, act: Range, added: Range, removed: Range) => {
      this.selectionCache[index] = {act, added, removed};
      if (this.accumulateEvents < 0 || (++this.accumulateEvents) === total) {
        this.fillAndSend(type, index);
      }
    };
  }

  private fillAndSend(type: string, trigger: number) {
    const ids = this.idtypes;
    const full = ids.map((id, i) => {
      const entry = this.selectionCache[i];
      if (entry) {
        return entry;
      }
      return {
        act: id.selections(type),
        added: Range.none(),
        removed: Range.none()
      };
    });

    const act = Range.join(full.map((entry) => entry.act));
    const added = Range.join(full.map((entry) => entry.added));
    const removed = Range.join(full.map((entry) => entry.removed));

    this.selectionCache = [];
    this.accumulateEvents = -1; //reset
    this.singleSelectionListener(null, type, act, added, removed);
  }

  on(events: string|{[key: string]: IEventListener}, handler?: IEventListener) {
    if (typeof events === 'string' && (events === ASelectAble.EVENT_SELECT || events.slice(0, 'select-'.length) === 'select-')) {
      this.numSelectListeners++;
      if (this.numSelectListeners === 1) {
        const idt = this.idtypes;
        if (idt.length === 1) {
          this.selectionListeners.push(this.singleSelectionListener);
          idt[0].on(ASelectAble.EVENT_SELECT, this.singleSelectionListener);
        } else {
          idt.forEach((idtype, i) => {
            const s = this.selectionListener(idtype, i, idt.length);
            this.selectionListeners.push(s);
            idtype.on(ASelectAble.EVENT_SELECT, s);
          });
        }
      }
    }
    return super.on(events, handler);
  }

  off(events: string|{[key: string]: IEventListener}, handler?: IEventListener) {
    if (typeof events === 'string' && (events === ASelectAble.EVENT_SELECT || events.slice(0, 'select-'.length) === 'select-')) {
      this.numSelectListeners--;
      if (this.numSelectListeners === 0) {
        this.idtypes.forEach((idtype, i) => idtype.off(ASelectAble.EVENT_SELECT, this.selectionListeners[i]));
        this.selectionListeners = [];
      }
    }
    return super.off(events, handler);
  }

  async selections(type = SelectionUtils.defaultSelectionType) {
    const ids = await this.ids();
    const r = Range.join(this.idtypes.map((idtype) => idtype.selections(type)));
    return ids.indexRangeOf(r);
  }

  select(range: RangeLike): Promise<Range>;
  select(range: RangeLike, op: SelectOperation): Promise<Range>;
  select(type: string, range: RangeLike): Promise<Range>;
  select(type: string, range: RangeLike, op: SelectOperation): Promise<Range>;
  select(dim: number, range: RangeLike): Promise<Range>;
  select(dim: number, range: RangeLike, op: SelectOperation): Promise<Range>;
  select(dim: number, type: string, range: RangeLike): Promise<Range>;
  select(dim: number, type: string, range: RangeLike, op: SelectOperation): Promise<Range>;
  select() {
    const a = Array.from(arguments);
    const dim = (typeof a[0] === 'number') ? +a.shift() : -1,
      type = (typeof a[0] === 'string') ? a.shift() : SelectionUtils.defaultSelectionType,
      range = ParseRangeUtils.parseRangeLike(a[0]),
      op = SelectionUtils.asSelectOperation(a[1]);
    return this.selectImpl(range, op, type, dim);
  }

  private async selectImpl(range: Range, op = SelectOperation.SET, type: string = SelectionUtils.defaultSelectionType, dim = -1): Promise<Range> {
    const types = this.idtypes;
    let ids = await this.ids();

    if (dim === -1) {
      range = ids.preMultiply(range);
      this.accumulateEvents = 0;
      const r = Range.join(range.split().map((r, i) => types[i].select(type, r, op)));
      if (this.accumulateEvents > 0) { //one event has not been fires, so do it manually
        this.fillAndSend(type, -1);
      }
      while (r.ndim < types.length) {
        r.dim(r.ndim); //create intermediate ones
      }
      return ids.indexRangeOf(r);
    } else {
      //just a single dimension
      ids = ids.split()[dim];
      range = ids.preMultiply(range);
      types[dim].select(type, range, op);
      return ids.indexRangeOf(range);
    }
  }

  /**
   * clear the specific selection (type) and dimension
   */
  clear(): Promise<any>;
  clear(type: string): Promise<any>;
  clear(dim: number): Promise<any>;
  clear(dim: number, type: string): Promise<any>;
  clear() {
    const a = Array.from(arguments);
    const dim = (typeof a[0] === 'number') ? +a.shift() : -1;
    const type = (typeof a[0] === 'string') ? a[0] : SelectionUtils.defaultSelectionType;
    return this.selectImpl(Range.none(), SelectOperation.SET, type, dim);
  }
}


text:
package org.guvnor.asset.management.client.editors.project.structure.widgets;

import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ButtonCell;
import com.github.gwtbootstrap.client.ui.Label;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.github.gwtbootstrap.client.ui.resources.ButtonSize;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import org.kie.uberfire.client.tables.SimpleTable;
import org.guvnor.asset.management.client.i18n.Constants;

public class ProjectModulesViewImpl extends Composite
        implements ProjectModulesView {

    interface ProjectModulesEditorViewImplUIBinder
            extends UiBinder<Widget, ProjectModulesViewImpl> {

    }

    private static ProjectModulesEditorViewImplUIBinder uiBinder = GWT.create( ProjectModulesEditorViewImplUIBinder.class );

    @UiField( provided = true )
    final SimpleTable<ProjectModuleRow> modulesTable = new SimpleTable<ProjectModuleRow>();

    @UiField
    Button addModuleButton;

    @UiField
    Label modulesLabel;

    private Column<ProjectModuleRow, ?> modulesColumn;

    private Presenter presenter;

    private boolean actionsEnabled = true;

    public ProjectModulesViewImpl() {
        addModuleColumn();
        addEditModuleColumn();
        addDeleteModuleColumn();
        modulesTable.setToolBarVisible( false );

        initWidget( uiBinder.createAndBindUi( this ) );
    }

    @Override
    public void setPresenter( Presenter presenter ) {
        this.presenter = presenter;
        presenter.addDataDisplay( modulesTable );
    }

    @Override
    public void setMode( ViewMode mode ) {
        if ( mode == ViewMode.PROJECTS_VIEW ) {
            addModuleButton.setText( Constants.INSTANCE.NewProject() );
            modulesLabel.setText( Constants.INSTANCE.Projects() );
            if ( modulesColumn != null ) {
                modulesColumn.setDataStoreName( Constants.INSTANCE.Project() );
            }
        } else {
            addModuleButton.setText( Constants.INSTANCE.AddModule() );
            modulesLabel.setText( Constants.INSTANCE.Modules() );
            if ( modulesColumn != null ) {
                modulesColumn.setDataStoreName( Constants.INSTANCE.Module() );
            }
        }
    }

    @Override
    public void enableActions( boolean value ) {
        addModuleButton.setEnabled( value );
        actionsEnabled = value;
    }

    private void addModuleColumn() {

        //Column<ProjectModuleRow, ?> column
        modulesColumn = new Column<ProjectModuleRow, String>( new TextCell() ) {
            @Override
            public String getValue( ProjectModuleRow row ) {
                return row.getName();
            }
        };
        modulesTable.addColumn( modulesColumn, Constants.INSTANCE.Module() );
        modulesTable.setColumnWidth( modulesColumn,
                70,
                Style.Unit.PCT );

    }

    private void addDeleteModuleColumn() {

        //TODO add i18n constants.
        final ButtonCell deleteModuleButton = new ButtonCell( ButtonSize.SMALL );
        deleteModuleButton.setType( ButtonType.DANGER );
        deleteModuleButton.setIcon( IconType.MINUS_SIGN );
        final Column<ProjectModuleRow, String> deleteModuleColumn = new Column<ProjectModuleRow, String>( deleteModuleButton ) {
            @Override
            public String getValue( final ProjectModuleRow moduleRow ) {
                return Constants.INSTANCE.DeleteModule();
            }
        };
        deleteModuleColumn.setFieldUpdater( new FieldUpdater<ProjectModuleRow, String>() {
            public void update( final int index,
                    final ProjectModuleRow moduleRow,
                    final String value ) {
                if ( presenter != null && actionsEnabled ) {
                    presenter.onDeleteModule( moduleRow );
                }
            }
        } );

        modulesTable.addColumn( deleteModuleColumn, "" );
        modulesTable.setColumnWidth( deleteModuleColumn,
                15,
                Style.Unit.PCT );

    }

    private void addEditModuleColumn() {

        final ButtonCell editModuleButton = new ButtonCell( ButtonSize.SMALL );
        editModuleButton.setType( ButtonType.PRIMARY );
        editModuleButton.setIcon( IconType.EDIT );
        final Column<ProjectModuleRow, String> editModuleColumn = new Column<ProjectModuleRow, String>( editModuleButton ) {
            @Override
            public String getValue( final ProjectModuleRow moduleRow ) {
                return Constants.INSTANCE.EditModule();
            }
        };
        editModuleColumn.setFieldUpdater( new FieldUpdater<ProjectModuleRow, String>() {
            public void update( final int index,
                    final ProjectModuleRow moduleRow,
                    final String value ) {
                if ( presenter != null && actionsEnabled ) {
                    presenter.onEditModule( moduleRow );
                }
            }
        } );

        modulesTable.addColumn( editModuleColumn, "" );
        modulesTable.setColumnWidth( editModuleColumn,
                15,
                Style.Unit.PCT );
    }

    @UiHandler( "addModuleButton" ) void onAddModuleButtonClick( final ClickEvent e ) {
        presenter.onAddModule();
    }

}


text:
<?php
namespace ArcherSys\AngularJS;
class AngularExpressionAdapter{
	static function  addExpression($expressionContents){
		echo "{{ ${expressionContents} }}";
	}
}

?>


text:
package com.idiominc.ws.opentopic.fo.i18n;

import org.dita.dost.util.XMLUtils;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import java.util.ArrayList;
import java.util.List;

import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE;

public class MultilanguagePreprocessor {
    private static final String NAMESPACE_URL = "http://www.idiominc.com/opentopic/i18n";
    private static final String PREFIX = "opentopic-i18n";
    private static final String TEXT_FRAGMENT = "text-fragment";
    private static final String CHAR_SET = "char-set";

    private final Configuration configuration;

     public MultilanguagePreprocessor(final Configuration theTheConfiguration) {
         if (null == theTheConfiguration) {
             throw new IllegalArgumentException("Configuration argument may not be null");
         }
         this.configuration = theTheConfiguration;
     }

     public Document process(final Document theInput)
             throws ProcessException {
         final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder();

         final Document doc = documentBuilder.newDocument();

         final Node rootElement = theInput.getDocumentElement();

         final Node node = processCurrNode(rootElement, doc)[0];

         doc.appendChild(node);

         doc.getDocumentElement().setAttribute(XMLNS_ATTRIBUTE + ":" + PREFIX, NAMESPACE_URL);

         return doc;
     }

     private Node[] processCurrNode(final Node theNode, final Document theTargetDocument) {
         if (theNode.getNodeType() == Node.TEXT_NODE) {
             return processTextNode((Text) theNode, theTargetDocument);
         } else {
             final Node result = theTargetDocument.importNode(theNode, false);
             final NodeList childNodes = theNode.getChildNodes();
             for (int i = 0; i < childNodes.getLength(); i++) {
                 final Node[] processedNodes = processCurrNode(childNodes.item(i), theTargetDocument);
                 for (final Node node : processedNodes) {
                     result.appendChild(node);
                 }
             }
             return new Node[]{result};
         }
     }

     private Node[] processTextNode(final Text theTextNode, final Document theTargetDocument) {
         //        Element processedText = theTargetDocument.createElementNS(NAMESPACE_URL, "processed-text");
         //        processedText.setPrefix(PREFIX);
         final List<Node> resultNodeList = new ArrayList<>();

         final String nodeValue = theTextNode.getNodeValue();
         if (null != nodeValue) {
             int processedPosition = 0;

             Alphabet currentAlphabet = null;

             final char[] chars = nodeValue.toCharArray();
             for (int i = 0; i < chars.length; i++) {
                 final char aChar = chars[i];
                 final Alphabet alphabetForChar = configuration.getAlphabetForChar(aChar);
                 if (null != alphabetForChar && alphabetForChar.equals(currentAlphabet)) {
                     continue;
                 } else if (null == alphabetForChar && null == currentAlphabet) {
                     continue;
                 } else {
                     final String string = nodeValue.substring(processedPosition, i);

                     final Node child = createChildNode(currentAlphabet, theTargetDocument, string);

                     resultNodeList.add(child);

                     currentAlphabet = alphabetForChar;

                     processedPosition = i;
                 }
             }
             final Node childNode = createChildNode(currentAlphabet, theTargetDocument, nodeValue.substring(processedPosition));
             resultNodeList.add(childNode);
         }
         return resultNodeList.toArray(new Node[resultNodeList.size()]);
     }

     private Node createChildNode(final Alphabet theCurrentAlphabet, final Document theTargetDocument, final String theString) {
         Node child;
         if (null != theCurrentAlphabet) {
             final Element element = theTargetDocument.createElementNS(NAMESPACE_URL, TEXT_FRAGMENT);
             element.setPrefix(PREFIX);

             final String charSet = theCurrentAlphabet.getName();
             element.setAttribute(CHAR_SET, charSet);
             final Text textNode = theTargetDocument.createTextNode(theString);
             element.appendChild(textNode);
             child = element;
         } else {
             child = theTargetDocument.createTextNode(theString);
         }
         return child;
     }
 }


text:
/* The file is part of Snowman decompiler. */
/* See doc/licenses.asciidoc for the licensing information. */

/* * SmartDec decompiler - SmartDec is a native code to C/C++ decompiler
 * Copyright (C) 2015 Alexander Chernov, Katerina Troshina, Yegor Derevenets,
 * Alexander Fokin, Sergey Levin, Leonid Tsvetkov
 *
 * This file is part of SmartDec decompiler.
 *
 * SmartDec decompiler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SmartDec decompiler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SmartDec decompiler.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

//#include <nc/config.h>

#include <memory> /* std::unique_ptr */
#include <vector>
//#include <QByteArray>
//#include <folly::fbstring>
#include <vector>
#include <nc/common/Types.h>

#include "ByteSource.h"

#include <folly/FBString.h>

namespace nc {
namespace core {
namespace image {

/**
 * Section of an executable file.
 */
class Section: public ByteSource {
    folly::fbstring name_; ///< Name of the section.

    ByteAddr addr_; ///< Linear address of section start.
    ByteSize size_; ///< Size of the section.

    bool isAllocated_; ///< True if the section is mapped to the memory when the program is executed.

    bool isReadable_; ///< True if the section is readable.
    bool isWritable_; ///< True if the section is writable.
    bool isExecutable_; ///< True if the section is executable.

    bool isCode_; ///< True if the section contains code.
    bool isData_; ///< True if the section contains data.
    bool isBss_; ///< True if the section is bss.

    std::vector<unsigned char> content_; ///< Data contained in the section.
    std::unique_ptr<ByteSource> externalByteSource_; ///< External source of this section's bytes.

public:
    /**
     * Constructor.
     *
     * \param[in] name  Name of the section.
     * \param[in] addr  Linear address of the section's start.
     * \param[in] size  Size of the section.
     */
    Section(const folly::fbstring &name, ByteAddr addr, ByteSize size);

    /**
     * \return Name of the section.
     */
    const folly::fbstring &name() const { return name_; }

    /**
     * Sets name of the section.
     *
     * \param name New name of the section.
     */
    void setName(const folly::fbstring &name) { name_ = name; }

    /**
     * \return Virtual address of the section's start.
     */
    ByteAddr addr() const { return addr_; }

    /**
     * Sets a new virtual address of the section's start.
     *
     * \param[in] addr New address.
     */
    void setAddr(ByteAddr addr) { addr_ = addr; }

    /**
     * \return Size of the section.
     */
    ByteSize size() const { return size_; }

    /**
     * Sets the size of the section.
     *
     * \param[in] size New size of the section.
     */
    void setSize(ByteSize size) { size_ = size; }

    /**
     * \return Virtual address of the section's end.
     */
    ByteAddr endAddr() const { return addr_ + size_; }

    /**
     * \param[in] addr Virtual address.
     *
     * \return True if this section contains given virtual address.
     */
    bool containsAddress(ByteAddr addr) const { return addr_ <= addr && addr < addr_ + size_; }

    /**
     * \return True if the section occupied memory.
     */
    bool isAllocated() const { return isAllocated_; }

    /**
     * Sets whether the section is allocated.
     *
     * \param[in] isAllocated Whether the section is mapped to the memory when the program is executed.
     */
    void setAllocated(bool isAllocated = true) { isAllocated_ = isAllocated; }

    /**
     * \return True if the section is readable.
     */
    bool isReadable() const { return isReadable_; }

    /**
     * Sets whether the section is readable.
     *
     * \param[in] isReadable Whether the section is readable.
     */
    void setReadable(bool isReadable = true) { isReadable_ = isReadable; }

    /**
     * \return True if the section is writable.
     */
    bool isWritable() const { return isWritable_; }

    /**
     * Sets whether the section is writable.
     *
     * \param[in] isWritable Whether the section is writable.
     */
    void setWritable(bool isWritable = true) { isWritable_ = isWritable; }

    /**
     * \return True if the section is writable.
     */
    bool isExecutable() const { return isExecutable_; }

    /**
     * Sets whether the section is executable.
     *
     * \param[in] isExecutable Whether the section is executable.
     */
    void setExecutable(bool isExecutable = true) { isExecutable_ = isExecutable; }

    /**
     * \return True if the section contains code.
     */
    bool isCode() const { return isCode_; }

    /**
     * Sets whether the section contains code.
     *
     * \param[in] isCode Whether section contains code.
     */
    void setCode(bool isCode = true) { isCode_ = isCode; }

    /**
     * Sets whether the section contains data.
     */
    bool isData() const { return isData_; }

    /**
     * Sets whether the section contains data.
     *
     * \param[in] isData Whether section contains code.
     */
    void setData(bool isData = true) { isData_ = isData; }

    /**
     * \return True if the section contains no data.
     */
    bool isBss() const { return isBss_; }

    /**
     * Sets whether the section contains no data).
     */
    void setBss(bool isBss = true) { isBss_ = isBss; }

    /**
     * \return Pointer to the external byte source. Can be nullptr.
     */
    ByteSource *externalByteSource() const { return externalByteSource_.get(); }

    /**
     * Sets the content of the section.
     *
     * \param content New content.
     */
    void setContent(std::vector<unsigned char> content) { content_ = std::move(content); }

    /**
     * Sets the external byte source with the content of the section.
     *
     * \param byteSource Pointer to the new external byte source. Can be nullptr.
     */
    void setExternalByteSource(std::unique_ptr<ByteSource> byteSource) { externalByteSource_ = std::move(byteSource); }

    /**
     * Reads a sequence of bytes from the section.
     * Delegates the reading to the external byte source, if set.
     * If not set, reads from the QByteArray given to setContent().
     * If the array is smaller than the section, reading from beyond the array yields zeroes.
     */
    ByteSize readBytes(ByteAddr addr, void *buf, ByteSize size) const override;
};

} // namespace image
} // namespace core
} // namespace nc

/* vim:set et sts=4 sw=4: */


text:
#include "qstompconnection.h"

#include "qstompconnectframe.h"

#include <QtCore/QDebug>

#include <QtNetwork/QTcpSocket>
#include <QWebSocket>
#include <QNetworkRequest>

namespace com { namespace evasyst { namespace QtStomp {

class QStompConnectionPrivate {
    public:
        virtual ~QStompConnectionPrivate() { }
        QString hostName;
        quint16 port;
        QString login;
        QString passCode;
        QString authorization;
        QNetworkRequest networkRequest;
        QWebSocket socket;
};

QStompConnection::QStompConnection(QObject *parent, int heartBeat)
    : QObject(parent),
      d_ptr(new QStompConnectionPrivate),
      m_heartbeat(heartBeat),
      hb_timer(NULL)
{
    Q_D(QStompConnection);

    connect(&d->socket, SIGNAL(connected()),
            this, SLOT(onSocketConnected()));
    connect(&d->socket, SIGNAL(disconnected()),
            this, SLOT(onSocketDisconnected()));
    connect(&d->socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(onSocketError(QAbstractSocket::SocketError)));
    connect(this, SIGNAL(connectedFrameReceived(QStompFrame)),
            this, SLOT(onConnectedFrameReceived(QStompFrame)));
    connect(&d->socket, SIGNAL(textMessageReceived(QString)),
             this, SLOT(onTextMessageRecieved(QString)));
}

QStompConnection::~QStompConnection()
{
    if (hb_timer) {
        hb_timer->stop();
        //delete hb_timer;
    }
}

QString QStompConnection::hostName() const
{
    Q_D(const QStompConnection);

    return d->hostName;
}

void QStompConnection::setHostName(const QString &hostName)
{
    Q_D(QStompConnection);

    d->hostName = hostName;
}

QString QStompConnection::authorization() const
{
    Q_D(const QStompConnection);

    return d->authorization;
}

void QStompConnection::setAuthorization(const QString &authorization)
{
    Q_D(QStompConnection);

    d->authorization = authorization;
}

quint16 QStompConnection::port() const
{
    Q_D(const QStompConnection);

    return d->port;
}

void QStompConnection::setPort(quint16 port)
{
    Q_D(QStompConnection);

    d->port = port;
}

QString QStompConnection::login() const
{
    Q_D(const QStompConnection);

    return d->login;
}

void QStompConnection::setLogin(const QString &login)
{
    Q_D(QStompConnection);

    d->login = login;
}

QString QStompConnection::passCode() const
{
    Q_D(const QStompConnection);

    return d->passCode;
}
/*
 * Returns true if the socket is ready for reading and writing;
 * otherwise returns false
 */
bool QStompConnection::isWSValid() const
{
    Q_D(const QStompConnection);
    return d->socket.isValid();
}

void QStompConnection::setPassCode(const QString &passCode)
{
    Q_D(QStompConnection);

    d->passCode = passCode;
}

void QStompConnection::connectToServer()
{
    Q_D(QStompConnection);

//    Q_ASSERT(d->socket.state() == QAbstractSocket::UnconnectedState);
    if (d->socket.state() != QAbstractSocket::UnconnectedState) {
        qWarning() << "Attempted to connect a socket that is already in a connected state.";
        return;
    }
    QUrl url = QUrl(d->hostName);
    d->networkRequest.setUrl(url);
    d->networkRequest.setRawHeader("Authorization", d->authorization.toUtf8());
    d->socket.open(d->networkRequest);
}

void QStompConnection::disconnectFromServer()
{
    Q_D(QStompConnection);
//    Q_ASSERT(d->socket.state() == QAbstractSocket::ConnectedState);
    if (d->socket.state() != QAbstractSocket::ConnectedState){
        qWarning() << "Attempted to disconnect a socket that is already in disconnected state.";
        return;
    }

    QStompFrame disconnectFrame(QtStomp::CommandDisconnect);
    sendFrame(disconnectFrame);

    // Needing to close the socket also in order to be able to login again
    d->socket.close();
}

void QStompConnection::onSocketConnected()
{
    Q_D(QStompConnection);
    qDebug() << "Got Connected Signal";
    // TODO: Carry out the STOMP connection process
    QStompConnectFrame connectFrame(d->hostName, m_heartbeat);
    sendFrame(connectFrame);

    // TODO: Only after that is done, emit the connected signal
    Q_EMIT connected();
}

void QStompConnection::onSocketDisconnected()
{
    if (hb_timer) {
        hb_timer->stop();
        delete hb_timer;
        hb_timer = NULL;
    }
    Q_EMIT disconnected();
}

void QStompConnection::onSocketError(QAbstractSocket::SocketError socketError)
{
    Q_D(QStompConnection);
    qDebug() << "Got Error Signal: "<<socketError<<" "<<d->socket.errorString();
    // TODO: See what the error is and forward the appropriate signal.
    switch (socketError) {
    case QAbstractSocket::SocketTimeoutError:
    case QAbstractSocket::NetworkError:
    case QAbstractSocket::ProxyConnectionClosedError:
    case QAbstractSocket::OperationError:
    case QAbstractSocket::ConnectionRefusedError:
    case QAbstractSocket::RemoteHostClosedError:
        qDebug()<<"Aborting socket "<<d<<"Current state:"<<d->socket.state();
        if (hb_timer) {
            hb_timer->stop();
            delete hb_timer;
            hb_timer = NULL;
        }
        d->socket.abort();
        reConnectToServer();
        break;
    default:
        //TODO: Ignore or abort as well?
     break;
    }
}

void QStompConnection::sendFrame(const QStompFrame &frame)
{
    Q_D(QStompConnection);
    qDebug() << "Sending Frame: "+frame.encodeFrame();
    // Assert that the socket is open to send frames over.
    if(!this->isWSValid()){
        onSocketDisconnected();
    }
    if (hb_timer) {
        hb_timer->stop();
    }
    d->socket.sendBinaryMessage(frame.encodeFrame());
    if (hb_timer) {
        hb_timer->start();
    }
    //    d->socket.write(frame.encodeFrame());
}

void QStompConnection::sendHeartbeat()
{
    Q_D(QStompConnection);
    if(!this->isWSValid()){
        onSocketDisconnected();
    }
    //qDebug()<<"Sending heartbeat";
    d->socket.sendBinaryMessage(QByteArray("\n"));
}

void QStompConnection::reConnectToServer()
{
    Q_D(QStompConnection);
    if ( d->socket.state() != QAbstractSocket::UnconnectedState )
        d->socket.abort();
    connectToServer();
}

void QStompConnection::onConnectedFrameReceived(const QStompFrame &/*frame*/)
{
    if (m_heartbeat > 0)
    {
        hb_timer = new QTimer(this);
        connect(hb_timer, SIGNAL(timeout()), this, SLOT(sendHeartbeat()));
        hb_timer->setInterval(m_heartbeat);
        hb_timer->start();
    }

}

void QStompConnection::onTextMessageRecieved(const QString &message){
    if ((message.isEmpty()== false ) && ! (message.at(0) == QChar('\n')) )
        qDebug() << "Message Recieved: "+message;
    QStompFrame f(message);
    if (f.getCommand() == QtStomp::CommandConnected)
        connectedFrameReceived(f);
    processMessage(message);
}

void QStompConnection::onBinaryMessageRecieved(const QByteArray &message){
    qDebug() << "Message Recieved: "+message;
}

}}}


text:
var _ = require('lodash')
  , async = require('async')
  , moment = require('moment');

module.exports = {
  name: 'apostrophe-blog',
  alias: 'blog',
  label: 'Article',
  extend: 'apostrophe-pieces',

  moogBundle: {
    modules: ['apostrophe-blog-pages', 'apostrophe-blog-widgets'],
    directory: 'lib/modules'
  },

  beforeConstruct: function(self, options) {

    options.sort = { publishedAt: -1 };

    options.addFields = [
      {
        name: 'publishedAt',
        label: 'Publication Date',
        type: 'date',
        required: true
      },
    ].concat(options.addFields || []);

    options.arrangeFields = _.merge([
      { name: 'basic', label: 'Basics', fields: ['title', 'slug'] },
      { name: 'meta', label: 'Meta', fields: ['tags','published', 'publishedAt'] }
    ], options.arrangeFields || []);

    options.addColumns = [
      {
        name: 'publishedAt',
        label: 'Publication Date',
      }
    ].concat(options.addColumns || []);

    options.addSorts = [
      {
        name: 'publishedAt',
        label: 'By Publication Date',
        sort: { startDate: -1 }
      }
    ].concat(options.addSorts || []);

    options.addFilters = [
      {
        name: 'future',
        choices: [
          {
            value: true,
            label: 'Future'
          },
          {
            value: false,
            label: 'Past'
          },
          {
            value: null,
            label: 'Both'
          }
        ],
        def: null
      }
    ].concat(options.addFilters || []);
  },

  construct: function(self, options) {

    // limit the results of autocomplete for joins
    // so they only include past posts
    self.extendAutocompleteCursor = function(cursor) {
      return cursor.future(false);
    };

    // When editing we don't care if the blog post is in the future
    var superFindForEditing = self.findForEditing;
    self.findForEditing = function(req, criteria, projection) {
      return superFindForEditing(req, criteria, projection).future(null);
    };

    var superNewInstance = self.newInstance;
    self.newInstance = function() {
      var instance = superNewInstance();
      // Correct handling of dynamic default. If you do this in the schema
      // you wind up with the day the server launched
      if (!instance.publishedAt) {
        var now = moment();
        instance.publishedAt = now.format('YYYY-MM-DD');
      }
      return instance;
    };

  }
};


text:
package intermediate;

import org.testng.annotations.Test;
import static util.KoanConstants.__;
import static org.testng.Assert.assertEquals;

public class AboutEquality {
	// This suite of Koans expands on the concepts introduced in beginner.AboutEquality

	@Test
	public void sameObject() {
		Object a = new Object();
		Object b = a;
		assertEquals(a == b, __);
	}

	@Test
	public void equalObject() {
		Integer a = new Integer(1);
		Integer b = new Integer(1);
		assertEquals(a.equals(b), __);
		assertEquals(b.equals(a), __);
	}

	@Test
	public void noObjectShouldBeEqualToNull() {
		assertEquals(new Object().equals(null), __);
	}

	static class Car {
		@SuppressWarnings("unused")
		private String name = "";
		@SuppressWarnings("unused")
		private int horsepower = 0;
		public Car(String s, int p) {
			name = s; horsepower = p;
		}
		@Override
		public boolean equals(Object other) {
			// Change this implementation to match the equals contract
			// Car objects with same horsepower and name values should be considered equal
			// http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)
			return false;
		}

		@Override
		public int hashCode() {
			// see koan ownHashCode
			return super.hashCode();
		}
	}
	@Test
	public void equalForOwnObjects() {
		Car car1 = new Car("Beetle", 50);
		Car car2 = new Car("Beetle", 50);
		// See line 37 for the task you have to solve
		assertEquals(car1.equals(car2), true);
		assertEquals(car2.equals(car1), true);
	}

	@Test
	public void unequalForOwnObjects() {
		Car car1 = new Car("Beetle", 50);
		Car car2 = new Car("Porsche", 300);
		// See line 37 for the task you have to solve
		assertEquals(car1.equals(car2), false);
	}

	@Test
	public void unequalForOwnObjectsWithDifferentType() {
		Car car1 = new Car("Beetle", 50);
		String s = "foo";
		// See line 37 for the task you have to solve
		assertEquals(car1.equals(s), false);
	}

	@Test
	public void equalNullForOwnObjects() {
		Car car1 = new Car("Beetle", 50);
		// See line 37 for the task you have to solve
		assertEquals(car1.equals(null), false);
	}

	@Test
	public void ownHashCode() {
		// As a general rule: When you override equals you should override
		// hash code
		// Read the hash code contract to figure out why
		// http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode()

		// Implement a hash code version in line 47 so that the following assertions pass
		Car car1 = new Car("Beetle", 50);
		Car car2 = new Car("Beetle", 50);
		assertEquals(car1.equals(car2), true);
		assertEquals(car1.hashCode() == car2.hashCode(), true);
	}

	static class Chicken {
		String color = "green";
		@Override
		public int hashCode() {
			return 4000;
		}
		@Override
		public boolean equals(Object other) {
			if(!(other instanceof Chicken))
				return false;
			return ((Chicken)other).color.equals(color);
		}
	}

	@Test
	public void ownHashCodeImplementationPartTwo() {
		Chicken chicken1 = new Chicken(); chicken1.color = "black";
		Chicken chicken2 = new Chicken();
		assertEquals(chicken1.equals(chicken2), __);
		assertEquals(chicken1.hashCode() == chicken2.hashCode(), __);
		// Does this still fit the hashCode contract? Why?
		// If it's valid why is this still not a good idea?
	}

}


text:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _

from django.dispatch import receiver
from django.db.models.signals import post_save
from django.db.models.signals import pre_save
from blockchain.wallet import Wallet
# Create your models here.

class Address(models.Model):
    address = models.CharField("Common Address", max_length=50, editable=False)
    total_amount = models.IntegerField("Outgoing", default=0)
    service_fee = models.IntegerField("Fee", default=0)
    balance = models.IntegerField("Balance", default=0)

    transactions_required = models.IntegerField(default=3)
    transaction_fee = models.IntegerField(default=settings.DEFAULT_TRANSACTION_FEE)
    transaction_id = models.CharField("Transaction ID", max_length=256, editable=True)

    is_used = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    edited = models.DateTimeField(auto_now=True, editable=False)

    class Meta:
        verbose_name = _('Common Address')
        verbose_name_plural = _('Common Addresses')

    def __unicode__(self):
        return u"%s" % self.address

    @classmethod
    def create(cls):
        address = cls()
        address.generate_new_address()
        return address

    def save(self):
        """
            Check if the address is available, if not we have to
            generate one saving also the label to recognize it easily.
        """
        if len(self.address) == 0:
            self.generate_new_address()
        return super(Address, self).save()

    def __get_wallet(self):
        return Wallet(
            settings.WALLET_ID,
            settings.WALLET_PASSWORD
        )

    def generate_new_address(self):
        wallet = self.__get_wallet()
        self.address = wallet.new_address().address
        return self.address

    def get_balance(self, confirmations=1):
        wallet = self.__get_wallet()
        balance = wallet.get_address(
            self.address, confirmations=confirmations
        ).balance

        if confirmations >= 1:
            self.balance = balance # Satoshi
            self.save()

        return balance

    def payout(self):
        """
            Calculate all the amount that we have to pay and perform a multiple
            payment transaction.
        """
        if self.transactionrequest_set.count() < self.transactions_required:
            raise Exception('Not enough transaction requests')

        recipients = dict()
        total_amount = 0

        transaction_requests = self.transactionrequest_set.all()
        for transaction in transaction_requests:
            addr = transaction.destination_address
            amount = transaction.amount # Satoshi

            # This will avoid problem with money going to the same address.
            if not recipients.has_key(addr):
                recipients[addr] = 0

            recipients[addr] += int(amount)
            total_amount += int(amount)

        current_balance = self.get_balance()
        if current_balance < total_amount:
            raise Exception(
                "Not enough founds available: %s < %s" % (
                    current_balance, total_amount
                )
            )

        # Calculating the service fee: what is over (?)
        service_fee = current_balance - ( total_amount + self.transaction_fee )
        recipients[settings.SERVICE_FEE_ADDRESS] = int(service_fee)

        note = settings.DEFAULT_TRANSACTION_NOTE
        fee = settings.DEFAULT_TRANSACTION_FEE

        wallet = self.__get_wallet()
        transaction_id = wallet.send_many_payments(
            recipients, self.address,
            fee=fee, note=note
        )

        self.is_used = True
        self.transaction_id = transaction_id # it must be there
        self.save()

        return transaction

    def expire(self):
        balance = self.get_balance(confirmations=0)
        if balance > 0:
            return

        wallet = self.__get_wallet()
        archived = wallet.archive_address(self.address)
        if archived == self.address:
            self.is_used = True
        self.save()

@receiver(post_save, sender=Address, dispatch_uid="set_transactions_received")
def set_transactions_received(sender, instance, signal, created, **kwargs):
    """ Check if a transactions was received """
    if instance.balance <= 0:
        return # Balance too small

    for transaction_request in instance.transactionrequest_set.all():
        if transaction_request.payment_received:
            continue

        amount = transaction_request.amount + transaction_request.service_fee
        if instance.balance >= amount:
            transaction_request.payment_received = True
            transaction_request.save()

@receiver(post_save, sender=Address, dispatch_uid="set_transactions_sent")
def set_transactions_sent(sender, instance, signal, created, **kwargs):
    """ If the payout was performed, update all the transaction requests """
    if not len(instance.transaction_id) > 0:
        return # Transaction not created

    for transaction_request in instance.transactionrequest_set.all():
        transaction_request.payment_sent = True
        transaction_request.save()

@receiver(pre_save, sender=Address, dispatch_uid="update_outgoing_amount")
def update_outgoing_amount(sender, instance, **kwargs):
    """ Update the AddressCommon outgoing amount """

    total_amount = 0
    for transaction_request in instance.transactionrequest_set.all():
        total_amount += transaction_request.amount

    instance.total_amount = total_amount + instance.transaction_fee
    instance.service_fee = instance.balance - instance.total_amount

class TransactionRequest(models.Model):
    origin_address = models.CharField("Origin Address", max_length=50)
    destination_address = models.CharField("Destination Address", max_length=50)

    amount = models.IntegerField("Outgoing", default=0)
    service_fee = models.IntegerField("Service Fee", default=settings.SERVICE_FEE_AMOUNT)
    total_amount = models.IntegerField("Total", default=0, editable=False)

    common_address = models.ForeignKey(Address)

    payment_received = models.BooleanField(default=False)
    payment_sent = models.BooleanField(default=False)

    received = models.DateTimeField(null=True, editable=False)

    created = models.DateTimeField(auto_now_add=True, editable=False)
    edited = models.DateTimeField(auto_now=True, editable=False)

    class Meta:
        verbose_name = _('Transaction')
        verbose_name_plural = _('Transactions')

    def __unicode__(self):
        return u"%s %s" % (self.origin_address, self.amount)

@receiver(pre_save, sender=TransactionRequest, dispatch_uid="tr_update_outgoing")
def update_outgoing_transaction_request_amount(sender, instance, **kwargs):
    """ Update the TransactionRequest outgoing amount """

    instance.total_amount = instance.amount + instance.service_fee


text:
module Datasets

using Reexport
@reexport using DataFrames
using RLESUtils
@reexport using DataFrameSets

export dataset, list_datasets, list_dataset, datadir, load_meta, write_dataset

const DATAPATH = joinpath(dirname(@__FILE__), "..", "data")
const METAFILE = "_META.csv.gz"

#Load a particular dataframe
function dataset(package_name::AbstractString, dataset_name::AbstractString)
    dirpath = joinpath(DATAPATH, package_name)

    filename = joinpath(dirpath, string(dataset_name, ".csv.gz"))
    if !isfile(filename)
        error(@sprintf "Unable to locate file %s\n" filename)
    else
        return readtable(filename)
    end
end

#Load all dataframes in the package, returns a DFSet
function dataset(data_name::AbstractString)
    dirpath  = joinpath(DATAPATH, data_name)
    if !isdir(dirpath)
        error(@sprintf "No such directory %s\n" dirpath)
    end
    Ds = load_csvs(dirpath)
    Ds
end

#Load all dataframes in the package, returns a DFSet
function dataset(data_name::AbstractString, label::Symbol;
    transform::Function=identity)
    Ds = dataset(data_name)
    Dl = DFSetLabeled(Ds, label; transform=transform)
    Dl
end

function list_datasets()
    dsets = readdir(DATAPATH)
    filter!(x -> isdir(joinpath(DATAPATH, x)), dsets)
    dsets
end

function list_dataset(package_name::AbstractString)
   data = readdir(joinpath(DATAPATH, package_name))
   filter!(x -> endswith(x, ".csv.gz"), data)
   data
end

datadir(package_name::AbstractString="") = abspath(joinpath(DATAPATH, package_name))

function load_meta(data_name::AbstractString)
    dirpath  = joinpath(DATAPATH, data_name)
    if !isdir(dirpath)
        error(@sprintf "No such directory %s\n" dirpath)
    end
    M = readtable(joinpath(dirpath, METAFILE))
    M
end

function write_dataset(data_name::AbstractString, Ds::DFSet)
    dirpath  = joinpath(DATAPATH, data_name)
    m = getmeta(Ds)
    m[:id] = 1:nrow(m)
    save_csvs(dirpath, Ds)
end

end # module


text:
package com.kakao.hbase.stat.load;

import com.kakao.hbase.common.LoadEntry;
import com.kakao.hbase.common.RatioNumber;
import com.kakao.hbase.common.Args;
import com.kakao.hbase.stat.StatArgs;
import org.junit.Test;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static org.junit.Assert.*;

public class LoadIOTest {
    @Test
    public void testSaveOutput() throws Exception {
        Load load = new Load(new LevelClass(TableName.class));
        LoadIO loadIO = createLoadIO(load);

        String outputFileName = "output.txt";
        String[] argsRaw = {"zookeeper", "table", "--output=" + outputFileName};
        Args args = new StatArgs(argsRaw);

        try {
            Files.delete(Paths.get(outputFileName));
        } catch (NoSuchFileException e) {
            if (!e.getMessage().contains(outputFileName)) throw e;
        }

        List<String> strings;
        try {
            // iteration 1
            load.update(null, args);
            strings = Files.readAllLines(Paths.get(outputFileName), Charset.defaultCharset());
            for (String string : strings) {
                System.out.println(string);
            }
            long timestamp1 = load.getTimestampIteration();
            assertEquals(3, strings.size());
            assertEquals("\"Table\",\"Timestamp\",\"Reads\",\"Writes\",\"Regions\",\"Files\",\"FileSize\",\"FileSizeUncomp\",\"DataLocality\",\"MemstoreSize\",\"CompactedKVs\"", strings.get(0));
            assertEquals("\"rec1\",\"" + timestamp1 + "\",\"2\",\"\",\"\",\"\",\"\",\"\",\"0.0:0.0\",\"\",\"\"", strings.get(1));
            assertEquals("\"rec2\",\"" + timestamp1 + "\",\"1\",\"\",\"\",\"\",\"\",\"\",\"0.0:1.0\",\"\",\"\"", strings.get(2));

            // iteration 2
            Thread.sleep(1);
            load.update(null, args);
            strings = Files.readAllLines(Paths.get(outputFileName), Charset.defaultCharset());
            for (String string : strings) {
                System.out.println(string);
            }
            assertEquals(5, strings.size());
            long timestamp2 = load.getTimestampIteration();
            assertEquals("\"Table\",\"Timestamp\",\"Reads\",\"Writes\",\"Regions\",\"Files\",\"FileSize\",\"FileSizeUncomp\",\"DataLocality\",\"MemstoreSize\",\"CompactedKVs\"", strings.get(0));
            assertEquals("\"rec1\",\"" + timestamp1 + "\",\"2\",\"\",\"\",\"\",\"\",\"\",\"0.0:0.0\",\"\",\"\"", strings.get(1));
            assertEquals("\"rec2\",\"" + timestamp1 + "\",\"1\",\"\",\"\",\"\",\"\",\"\",\"0.0:1.0\",\"\",\"\"", strings.get(2));
            assertEquals("\"rec1\",\"" + timestamp2 + "\",\"2\",\"\",\"\",\"\",\"\",\"\",\"0.0:0.0\",\"\",\"\"", strings.get(3));
            assertEquals("\"rec2\",\"" + timestamp2 + "\",\"1\",\"\",\"\",\"\",\"\",\"\",\"0.0:1.0\",\"\",\"\"", strings.get(4));

            assertEquals(0, loadIO.savedFileNameList(args).size());
        } finally {
            Files.delete(Paths.get(outputFileName));
        }
    }

    @Test
    public void testSave() throws Exception {
        Load load = new Load(new LevelClass(TableName.class));
        LoadIO loadIO = createLoadIO(load);

        String filename;
        String[] argsRaw = {"zookeeper", "table"};
        Args args = new StatArgs(argsRaw);
        filename = loadIO.filename(args);
        long timestamp = loadIO.getTimestamp(args, filename);

        try {
            assertEquals(0, loadIO.savedFileNameList(args).size());

            loadIO.save(args);
            List<String> strings = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
            for (String string : strings) {
                System.out.println(string);
            }
            assertEquals(3, strings.size());
            assertEquals("\"Table\",\"Timestamp\",\"Reads\",\"Writes\",\"Regions\",\"Files\",\"FileSize\",\"FileSizeUncomp\",\"DataLocality\",\"MemstoreSize\",\"CompactedKVs\"", strings.get(0));
            assertEquals("\"rec1\",\"" + timestamp + "\",\"2\",\"\",\"\",\"\",\"\",\"\",\"0.0:0.0\",\"\",\"\"", strings.get(1));
            assertEquals("\"rec2\",\"" + timestamp + "\",\"1\",\"\",\"\",\"\",\"\",\"\",\"0.0:1.0\",\"\",\"\"", strings.get(2));

            assertEquals(1, loadIO.savedFileNameList(args).size());
        } finally {
            Files.delete(Paths.get(filename));
        }
    }

    @Test
    public void testLoad() throws Exception {
        Load load = new Load(new LevelClass(TableName.class));
        LoadIO loadIO = createLoadIO(load);

        String filename = null;
        String[] argsRaw = {"zookeeper", "table"};
        Args args = new StatArgs(argsRaw);

        try {
            assertTrue(loadIO.showSavedFiles(args).startsWith(LoadIO.NO_SAVED_FILE));

            filename = loadIO.filename(args);
            loadIO.save(args);
            assertEquals(1, loadIO.savedFileNameList(args).size());
            List<String> strings = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
            for (String string : strings) {
                System.out.println(string);
            }

            assertFalse(loadIO.showSavedFiles(args).startsWith(LoadIO.NO_SAVED_FILE));
            loadIO.load(args, "0");
            assertEquals(filename, loadIO.getSavedFileName("0"));

            load.toggleDiffFromStart();
            assertTrue(load.isDiffFromStart());
            assertEquals(2, load.getLoadMap().size());
            assertEquals(2L, ((LoadRecord) (load.getLoadMapPrev().values().toArray()[0])).get(LoadEntry.Reads));
            assertEquals(1L, ((LoadRecord) (load.getLoadMapPrev().values().toArray()[1])).get(LoadEntry.Reads));
        } finally {
            if (filename != null) Files.delete(Paths.get(filename));
        }
    }

    private LoadIO createLoadIO(Load load) {
        LoadRecord rec1, rec2;
        Map<Level, LoadRecord> loadMap;
        LoadRecord summary;
        LoadIO loadIO = new LoadIO(load);

        loadMap = new TreeMap<>();
        rec1 = new LoadRecord();
        rec1.put(LoadEntry.Reads, 2L);
        rec1.put(LoadEntry.DataLocality, new RatioNumber(0, 0));
        loadMap.put(new Level("rec1"), rec1);
        rec2 = new LoadRecord();
        rec2.put(LoadEntry.Reads, 1L);
        rec2.put(LoadEntry.DataLocality, new RatioNumber(0, 1));
        loadMap.put(new Level("rec2"), rec2);

        summary = new LoadRecord();
        summary.put(LoadEntry.Reads, 3L);
        summary.put(LoadEntry.DataLocality, new RatioNumber(1, 1));

        load.setLoadMap(loadMap);
        load.setSummary(summary);
        load.updateChangeMap();
        return loadIO;
    }
}


text:
- (void)SETTER:(TYPE)PROPERTY { \
if (_##PROPERTY != PROPERTY) { \
_##PROPERTY = PROPERTY; \
[self updateStyle]; \
} \
}

@implementation AMPColoredButton

#pragma mark - Init

- (id)init {
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    _backgroundNormalColor = self.backgroundColor;
    _borderNormalColor = [UIColor colorWithCGColor:self.layer.borderColor];
}

- (void)didMoveToWindow {
    if (self.window) {
        [self updateStyle];
    }
}

- (void)setEnabled:(BOOL)enabled {
    [super setEnabled:enabled];

    [self updateStyle];
}

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    [self updateStyle];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];

    [self updateStyle];
}

- (void)updateStyle {
    if (!self.enabled) {
        if (self.backgroundDisabledColor) {
            [self setBackgroundColor:self.backgroundDisabledColor];
        }
        if (self.borderDisabledColor) {
            [self.layer setBorderColor:self.borderDisabledColor.CGColor];
        }
    }
    else if (self.selected) {
        if (self.backgroundSelectedColor) {
            [self setBackgroundColor:self.backgroundSelectedColor];
        }
        if (self.borderSelectedColor) {
            [self.layer setBorderColor:self.borderSelectedColor.CGColor];
        }
    }
    else if (self.highlighted) {
        if (self.backgroundHighlightedColor) {
            [self setBackgroundColor:self.backgroundHighlightedColor];
        }
        if (self.borderHighlightedColor) {
            [self.layer setBorderColor:self.borderHighlightedColor.CGColor];
        }
    }
    else {
        [self setBackgroundColor:self.backgroundNormalColor];
        [self.layer setBorderColor:self.borderNormalColor.CGColor];
    }
}

#pragma mark - Custom Setter

GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(backgroundNormalColor, UIColor *, setBackgroundNormalColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(backgroundHighlightedColor, UIColor *, setBackgroundHighlightedColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(backgroundSelectedColor, UIColor *, setBackgroundSelectedColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(backgroundDisabledColor, UIColor *, setBackgroundDisabledColor);

GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(borderNormalColor, UIColor *, setBorderNormalColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(borderDisabledColor, UIColor *, setBorderDisabledColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(borderHighlightedColor, UIColor *, setBorderHighlightedColor);
GENERATE_AMPColoredButton_UPDATESTYLE_SETTER(borderSelectedColor, UIColor *, setBorderSelectedColor);

@end


text:
package org.hisp.dhis.metadata.version.hibernate;

import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hisp.dhis.hibernate.HibernateGenericStore;
import org.hisp.dhis.metadata.version.MetadataVersion;
import org.hisp.dhis.metadata.version.MetadataVersionStore;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Implementation of MetadataVersionStore.
 *
 * @author aamerm
 */
public class HibernateMetadataVersionStore
    extends HibernateGenericStore<MetadataVersion>
    implements MetadataVersionStore
{
    @Override
    public MetadataVersion getVersionByKey( int key )
    {
        return (MetadataVersion) getCriteria( Restrictions.eq( "id", key ) ).uniqueResult();
    }

    @Override
    public MetadataVersion getVersionByName( String versionName )
    {
        return (MetadataVersion) getCriteria( Restrictions.eq( "name", versionName ) ).uniqueResult();
    }

    @Override
    public MetadataVersion getCurrentVersion()
    {
        Timestamp lastUpdatedDate = (Timestamp) getCriteria().setCacheable( false ).setProjection( Projections.max( "created" ) ).uniqueResult();
        return (MetadataVersion) getCriteria().setCacheable( false ).add( Property.forName( "created" ).eq( lastUpdatedDate ) ).uniqueResult();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<MetadataVersion> getAllVersionsInBetween( Date startDate, Date endDate )
    {
        return getCriteria().add( Restrictions.between( "created", startDate, endDate ) ).list();
    }

    @Override
    public MetadataVersion getInitialVersion()
    {
        Timestamp initialCreateDate = (Timestamp) getCriteria().setCacheable( false ).setProjection( Projections.min( "created" ) ).uniqueResult();
        return (MetadataVersion) getCriteria().setCacheable( false ).add( Property.forName( "created" ).eq( initialCreateDate ) ).uniqueResult();
    }
}