text:
package org.apache.batik.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.apache.batik.util.io.NormalizingReader;
import org.apache.batik.util.io.StreamNormalizingReader;
import org.apache.batik.util.io.StringNormalizingReader;

/**
 * An abstract scanner class to be extended.
 *
 * @author Stephane Hillion
 * @author Cameron McCormack
 * @version $Id$
 */
public abstract class AbstractScanner {

    /**
     * The reader.
     */
    protected NormalizingReader reader;

    /**
     * The current char.
     */
    protected int current;

    /**
     * The recording buffer.
     */
    protected char[] buffer = new char[128];

    /**
     * The current position in the buffer.
     */
    protected int position;

    /**
     * The type of the current lexical unit.
     */
    protected int type;

    /**
     * The previous lexical unit type that was scanned.
     */
    protected int previousType;

    /**
     * The start offset of the last lexical unit.
     */
    protected int start;

    /**
     * The end offset of the last lexical unit.
     */
    protected int end;

    /**
     * The characters to skip to create the string which represents the
     * current token.
     */
    protected int blankCharacters;

    /**
     * Creates a new AbstractScanner object.
     * @param r The reader to scan.
     */
    public AbstractScanner(Reader r) throws ParseException {
        try {
            reader = new StreamNormalizingReader(r);
            current = nextChar();
        } catch (IOException e) {
            throw new ParseException(e);
        }
    }

    /**
     * Creates a new AbstractScanner object.
     * @param is The input stream to scan.
     * @param enc The encoding to use to decode the input stream, or null.
     */
    public AbstractScanner(InputStream is, String enc) throws ParseException {
        try {
            reader = new StreamNormalizingReader(is, enc);
            current = nextChar();
        } catch (IOException e) {
            throw new ParseException(e);
        }
    }

    /**
     * Creates a new AbstractScanner object.
     * @param s The string to scan.
     */
    public AbstractScanner(String s) throws ParseException {
        try {
            reader = new StringNormalizingReader(s);
            current = nextChar();
        } catch (IOException e) {
            throw new ParseException(e);
        }
    }

    /**
     * Returns the current line.
     */
    public int getLine() {
        return reader.getLine();
    }

    /**
     * Returns the current column.
     */
    public int getColumn() {
        return reader.getColumn();
    }

    /**
     * Returns the buffer used to store the chars.
     */
    public char[] getBuffer() {
        return buffer;
    }

    /**
     * Returns the start offset of the last lexical unit.
     */
    public int getStart() {
        return start;
    }

    /**
     * Returns the end offset of the last lexical unit.
     */
    public int getEnd() {
        return end;
    }

    /**
     * Clears the buffer.
     */
    public void clearBuffer() {
        if (position <= 0) {
            position = 0;
        } else {
            buffer[0] = buffer[position-1];
            position = 1;
        }
    }

    /**
     * The current lexical unit type like defined in LexicalUnits.
     */
    public int getType() {
        return type;
    }

    /**
     * Returns the string representation of the current lexical unit.
     */
    public String getStringValue() {
        return new String(buffer, start, end - start);
    }

    /**
     * Returns the next token.
     */
    public int next() throws ParseException {
        blankCharacters = 0;
        start = position - 1;
        previousType = type;
        nextToken();
        end = position - endGap();
        return type;
    }

    /**
     * Returns the end gap of the current lexical unit.
     */
    protected abstract int endGap();

    /**
     * Returns the next token.
     */
    protected abstract void nextToken() throws ParseException;

    /**
     * Compares the given int with the given character, ignoring case.
     */
    protected static boolean isEqualIgnoreCase(int i, char c) {
        return (i == -1) ? false : Character.toLowerCase((char)i) == c;
    }

    /**
     * Sets the value of the current char to the next character or -1 if the
     * end of stream has been reached.
     */
    protected int nextChar() throws IOException {
        current = reader.read();

        if (current == -1) {
            return current;
        }

        if (position == buffer.length) {
            char[] t = new char[position * 3 / 2];
            for (int i = 0; i < position; i++) {
                t[i] = buffer[i];
            }
            buffer = t;
        }

        return buffer[position++] = (char)current;
    }
}


text:
package io.corbel.oauth.api;

import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import io.corbel.lib.token.reader.TokenReader;
import io.corbel.oauth.session.SessionCookieFactory;

/**
 * @author Alexander De Leon
 *
 */
@Path(ApiVersion.CURRENT + "/oauth/signout") public class SignoutResource {

    private final SessionCookieFactory sessionCookieFactory;

    public SignoutResource(SessionCookieFactory sessionCookieFactory) {
        this.sessionCookieFactory = sessionCookieFactory;
    }

    @GET
    public Response signout(@CookieParam(SessionCookieFactory.COOKIE_NAME) TokenReader session) {
        ResponseBuilder responseBuilder = Response.noContent();
        if (null != session) {
            String token = session.getToken();
            NewCookie cookie = sessionCookieFactory.destroyCookie(token);
            responseBuilder.cookie(cookie);
        }
        return responseBuilder.build();
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const _ = require('lodash')

exports.get_env = function (project_dir, NODE_ENV) {
    const cfg = {
        NOCACHE: process.env.NOCACHE,
        static_base: process.env.STATIC_BASE || 'http://rawgit.com',
        public_static_base: process.env.PUBLIC_STATIC_BASE || process.env.STATIC_BASE || 'http://rawgit.com',
        version: require("../package.json").version,
        PORT: process.env.PORT || 8000,
        NODE_ENV: process.env.NODE_ENV || NODE_ENV || 'development'
    }
    if (process.env.GH_REPO || process.env.MODE === 'github' || project_dir === 'github') {
        _.extend(cfg, {
            github: true,
            local: false,
            base_user: process.env.GH_USER_BASE || 'cacahootie',
            base_repo_name: process.env.GH_REPO_BASE || 'motly-base',
            whitelist_gh_user: process.env.GH_USER || 'cacahootie',
            whitelist_gh_repo: process.env.GH_REPO || 'motly-test'
        })
    } else {
        _.extend(cfg, {
            local: true,
            NOCACHE: true,
            project_dir: process.env.PROJECT_DIR || project_dir || './',
            base_dir: process.env.BASE_DIR || './test/test_data/motly-base'
        })
    }
    return cfg
}


text:
<?php

namespace Application\Sonata\UserBundle\Admin\Model;

use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\UserBundle\Admin\Model\UserAdmin as BaseType;

class UserAdmin extends BaseType {

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper) {
        $listMapper
                ->addIdentifier('username')
                ->add('groups')
                ->add('enabled')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper) {
        $formMapper
                ->with('General')
                ->add('username')
                ->add('email')
                ->add('plainPassword', 'text', array('required' => false))
                ->end()
                ->with('Groups')
                ->add('groups', 'sonata_type_model', array('required' => false))
                ->end()
                ->with('Profile')
                ->add('firstname', null, array('required' => false))
                ->add('lastname', null, array('required' => false))
                ->end()
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function preUpdate($user) {
        $this->getUserManager()->updateCanonicalFields($user);
        $this->getUserManager()->updatePassword($user);
    }

    /**
     * @return UserManagerInterface
     */
    public function getUserManager() {
        return $this->userManager;
    }

}


text:
from amdevice import *
import os.path
import os
from plistservice import *

class ImageMounter(object):
	def __init__(self, amdevice):
		self.dev = amdevice

	def disconnect(self):
		pass

	def mount(self, image_path=None, progress=None):
		u'''Mounts a disk image on the device.

		Arguments:
		image -- the path to the image to load; the .signature file must be
		         beside the image (default None - we select the best debug
		         disk image)
		progress -- an optional callback (default None)

		Error:
		Raises RuntimeError on mounting error, or a file exception from reading
		the signature file
		'''
		def callback(cfdict, arg):
			pass #print CFTypeTo(cfdict)

		if image_path is None:
			image_path = self.dev.find_developer_disk_image_path()

		sigpath = image_path + u'.signature'
		f = open(sigpath, u'rb')
		sig = f.read()
		f.close()

		cfpath = CFTypeFrom(image_path)
		cfoptions = CFTypeFrom({
			u'ImageType': u'Developer', # XXX add support for other image types
			u'ImageSignature': sig
		})
		cb = AMDeviceProgressCallback(callback)
		if progress is not None:
			cb = AMDeviceProgressCallback(progress)
		# XXX so the code for mount image checks if its mounted and only bothers
		# to resend the image if it isn't; for some reason I dont understand its
		# not doing this on my version - its always sending it; then the mount
		# fails (with lots of syslog output on the device)
		# -- this may be due to the image I'm loading not being a perfect match
		#AMDSetLogLevel(0xff)
		err = AMDeviceMountImage(self.dev.dev, cfpath, cfoptions, cb, None)
		#AMDSetLogLevel(0x00)
		CFRelease(cfpath)
		CFRelease(cfoptions)
		if err != MDERR_OK and (err & 0xFFFFFFFF) != 0xe8000076: # already mounted
			raise RuntimeError(u'Unable to mount disk image', err)

def register_argparse_mount(cmdargs):
	import argparse
	import pprint
	import sys

	def cmd_mountdev(args, dev):
		im = ImageMounter(dev)
		im.mount()
		im.disconnect()

	def cmd_mountcustom(args, dev):
		im = ImageMounter(dev)
		im.mount(args.path.decode(u'utf-8'))
		im.disconnect()

	mountparser = cmdargs.add_parser(
		u'mount',
		help=u'mounts a disk image'
	)
	mountcmds = mountparser.add_subparsers()

	# mount developer disk image
	devcmd = mountcmds.add_parser(
		u'dev',
		help=u'mounts the best developer disk image avaliable for the device'
	)
	devcmd.set_defaults(func=cmd_mountdev)

	# mount custom disk image
	cuscmd = mountcmds.add_parser(
		u'custom',
		help=u'mounts the supplied disk image; .signature file must be alongside'
	)
	cuscmd.add_argument(
		u'path',
		help=u'the path to the .dmg; we expect a .signature alongside'
	)
	cuscmd.set_defaults(func=cmd_mountcustom)

#'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/6.0 (10A403)/DeveloperDiskImage.dmg'


text:
"""Test for document_reader.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from language.question_answering.decatt_docreader.layers import document_reader
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import estimator as tf_estimator

class DocumentReaderTest(tf.test.TestCase):

  def test_document_reader(self):
    with tf.Graph().as_default():
      start_score, end_score = document_reader.score_endpoints(
          question_emb=tf.random_uniform([3, 5, 7]),
          question_len=tf.constant([5, 2, 0]),
          context_emb=tf.random_uniform([3, 8, 7]),
          context_len=tf.constant([8, 6, 1]),
          hidden_size=9,
          num_layers=2,
          dropout_ratio=0.1,
          mode=tf_estimator.ModeKeys.TRAIN)
      with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        actual_start_score, actual_end_score = sess.run(
            [start_score, end_score])
      self.assertAllEqual(actual_start_score.shape, [3, 8])
      self.assertAllEqual(actual_end_score.shape, [3, 8])

if __name__ == "__main__":
  tf.test.main()


text:
package com.example.rx;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * Created by alanchen on 15/9/11.
 */
public class RxBase {

    static Observable<String> mStringObservable = Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("Hello Rxjava");
            //Notice 如果onCompleted 先调用了,那么后面的onNext onError则会被无视掉,但是不是等同于return,后面其他的代码还是会执行
            subscriber.onCompleted();
//            System.out.println("看看onCompleted调用了还会不会有输出");
            subscriber.onError(new Throwable("hehehe"));
        }
    });

    static Subscriber<String> mStringSubscriber = new Subscriber<String>() {
        @Override
        public void onCompleted() {
            System.out.println("onCompleted");

        }

        @Override
        public void onError(Throwable e) {
            System.out.println("onError:" + e.getMessage());
        }

        @Override
        public void onNext(String s) {
            System.out.println(s);
        }
    };

    /**
     * Observable.just就是用来创建只发出一个事件就结束的Observable对象
     * 它在call里自动调用了 onNext 和 onCompleted
     */
    static Observable<String> simpleObservable = Observable.just("Hell,simple observable");

    /**
     * 如果不关心OnComplete和OnError,我们只需要在onNext的时候做一些处理,这时候就可以使用Action1类。
     */
    static Action1<String> onNextAction = new Action1<String>() {
        @Override
        public void call(String s) {
            System.out.println("Action1<String> onNextAction:" + s);
        }
    };

    static Action1<Throwable> onErrorAction = new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            System.out.println("Action1<Throwable> onErrorAction:");
        }
    };

    static Action0 onCompleteAction = new Action0() {
        @Override
        public void call() {
            System.out.println("Action0 onCompleteAction:");
        }
    };

    public static void main(String[] args) {

//        mStringObservable.subscribe(mStringSubscriber);//执行后 输出 Hello Rxjava   onCompleted
//
//        simpleObservable.subscribe(mStringSubscriber);//执行后 输出 Hell,simple observable  onCompleted
//
//        //Notice  如果调用onError 这个单个的onNextAction 会报错
        mStringObservable.subscribe(onNextAction);
        mStringObservable.subscribe(onNextAction, onErrorAction);
        mStringObservable.subscribe(onNextAction, onErrorAction, onCompleteAction);
//
//
        Observable.just("Hello simple onaction1").subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                System.out.println(s);
            }
        });

    }
}


text:
/* automaton
 * (c) 2013 Justin Gottula
 * The source code of this project is distributed under the terms of the
 * simplified BSD license. See the LICENSE file for details.
 */

#ifndef AUTOMATON_ALGO_CRC7_H
#define AUTOMATON_ALGO_CRC7_H

#include "std.h"

uint8_t crc7_byte(uint8_t crc, uint8_t datum);
uint8_t crc7_arr(uint8_t crc, uint8_t len, const uint8_t data[static len]);

#endif


text:
.class final Lcom/android/settings/applications/ManageApplications$2;
.super Ljava/lang/Object;
.source "ManageApplications.java"

# interfaces
.implements Lcom/android/settings/dashboard/SummaryLoader$SummaryProviderFactory;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settings/applications/ManageApplications;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createSummaryProvider(Landroid/app/Activity;Lcom/android/settings/dashboard/SummaryLoader;)Lcom/android/settings/dashboard/SummaryLoader$SummaryProvider;
    .locals 2

    new-instance v0, Lcom/android/settings/applications/ManageApplications$SummaryProvider;

    const/4 v1, 0x0

    invoke-direct {v0, p1, p2, v1}, Lcom/android/settings/applications/ManageApplications$SummaryProvider;-><init>(Landroid/content/Context;Lcom/android/settings/dashboard/SummaryLoader;Lcom/android/settings/applications/ManageApplications$SummaryProvider;)V

    return-object v0
.end method


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>Booky management system</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    You need to enable JavaScript to run this app.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_alignParentLeft="true"
        android:background="@color/material_blue_grey_800"
        />

    <TextView
        android:id="@+id/tvEUI"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:textAppearance="?attr/textAppearanceListItem"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/tvStatus"
        tools:text="some EUI"
        />

    <TextView
        android:id="@+id/tvLastSeen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:textAppearance="?attr/textAppearanceListItem"
        android:layout_below="@+id/tvEUI"
        android:layout_toRightOf="@+id/tvStatus"
        tools:text="2015-5-6-12.3.04."

        />
</RelativeLayout>


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | uni button', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    assert.expect(1);

    this.set('label', 'This is a label');

    await render(hbs`{{uni-button label=label}}`);

    assert.dom('.uni-button').hasText('This is a label');
  });

  test('it renders yield content', async function(assert) {
    assert.expect(4);

    this.set('label', 'This label should not show');

    await render(hbs`
      {{#uni-button label=label}}

Click on me!

      {{/uni-button}}
    `);

    assert.dom('.uni-button').exists();
    assert.dom('.uni-button').doesNotIncludeText('This label should not show');
    assert.dom('h1').exists();
    assert.dom('h1').hasText('Click on me!');
  });
});


text:
<?php

namespace App\Service;

use App\Entity\Scenario;
use Doctrine\ORM\EntityManagerInterface;
use DomainException;
use Ds\Component\Api\Api\Api;
use Ds\Component\Camunda\Query\ProcessDefinitionParameters;
use Ds\Component\Entity\Service\EntityService;
use Ds\Component\Form\Service\FormService;

/**
 * Class ScenarioService
 */
final class ScenarioService extends EntityService
{
    /**
     * @var \Ds\Component\Api\Api\Api
     */
    private $api;

    /**
     * @var \Ds\Component\Form\Service\FormService
     */
    private $formService;

    /**
     * Constructor
     *
     * @param \Doctrine\ORM\EntityManagerInterface $manager
     * @param \Ds\Component\Api\Api\Api $api
     * @param \Ds\Component\Form\Service\FormService $formService
     * @param string $entity
     */
    public function __construct(EntityManagerInterface $manager, Api $api, FormService $formService, string $entity = Scenario::class)
    {
        parent::__construct($manager, $entity);
        $this->api = $api;
        $this->formService = $formService;
    }

    /**
     * Get form
     *
     * @param \App\Entity\Scenario $scenario
     * @return \Ds\Component\Form\Model\Form
     * @throws \DomainException
     */
    public function getForm(Scenario $scenario)
    {
        $forms = $this->getForms($scenario);

        foreach ($forms as $form) {
            if ($form->getPrimary()) {
                return $form;
            }
        }
    }

    /**
     * Get forms
     *
     * @param \App\Entity\Scenario $scenario
     * @return array
     * @throws \DomainException
     */
    public function getForms(Scenario $scenario)
    {
        switch ($scenario->getType()) {
            case Scenario::TYPE_BPM:
                $config = $scenario->getConfig();

                if (array_key_exists('form_key', $config)) {
                    $id = $config['form_key'];
                } else {
                    $parameters = new ProcessDefinitionParameters;
                    $parameters
                        ->setKey($scenario->getConfig()['process_definition_key'])
                        ->setTenantId($scenario->getTenant());
                    $id = $this->api->get('workflow.process_definition')->getStartForm(null, $parameters);
                }

                if (null === $id) {
                    return [];
                }

                break;

            default:
                throw new DomainException('Scenario type does not exist.');
        }

        $forms = $this->formService->getForms($id);

        foreach ($forms as $key => $form) {
            $form = $this->formService->resolve($form);

            if ($form->getPrimary()) {
                // @todo Perhaps use the route generator.
                $form->setAction('/scenarios/'.$scenario->getUuid().'/submissions');
            }

            $forms[$key] = $form;
        }

        return $forms;
    }
}


text:
var extend = require('extend');
var pty = require('../build/Release/pty.node');
var net = require('net');
var tty = require('tty');

var version = process.versions.node.split('.').map(function(n) {
  return +(n + '').split('-')[0];
});

var DEFAULT_COLS = 80;
var DEFAULT_ROWS = 24;

/**
 * Terminal
 */

// Example:
//  var term = new Terminal('bash', [], {
//    name: 'xterm-color',
//    cols: 80,
//    rows: 24,
//    cwd: process.env.HOME,
//    env: process.env
//  });

function Terminal(file, args, opts) {
  if (!(this instanceof Terminal)) {
    return new Terminal(file, args, opts);
  }

  var env, cwd, name, cols, rows, currentCols, currentRows, term,
      self = this;

  // backward compatibility
  if (typeof args === 'string') {
    opts = {
      name: arguments[1],
      cols: arguments[2],
      rows: arguments[3],
      cwd:  process.env.HOME
    };
    args = [];
  }

  // arguments
  args = args || [];
  file = file || 'sh';
  opts = opts || {};

  if (opts.snap === true && process.stdout.isTTY === true) {

    // Establish the default columns and rows based on the TTY dimensions
    // of `process.stdout`
    if (isValidPositiveInteger(process.stdout.columns)) {
      currentCols = process.stdout.columns;
    }
    if (isValidPositiveInteger(process.stdout.rows)) {
      currentRows = process.stdout.rows;
    }

  }

  cols = isValidPositiveInteger(opts.cols) ? opts.cols : (currentCols || DEFAULT_COLS);
  rows = isValidPositiveInteger(opts.rows) ? opts.rows : (currentRows || DEFAULT_ROWS);

  opts.env = opts.env || process.env || {};
  env = extend({}, opts.env);

  if (opts.env === process.env) {
    // Make sure we didn't start our server from inside tmux.
    delete env.TMUX;
    delete env.TMUX_PANE;

    // Make sure we didn't start our server from inside screen.
    // http://web.mit.edu/gnu/doc/html/screen_20.html
    delete env.STY;
    delete env.WINDOW;

    // Delete some variables that might confuse our terminal.
    delete env.WINDOWID;
    delete env.TERMCAP;
    delete env.COLUMNS;
    delete env.LINES;
  }

  // We could set some basic env vars here, if they do not exist:
  // USER, SHELL, HOME, LOGNAME, WINDOWID

  cwd = opts.cwd || process.cwd();
  name = opts.name || env.TERM || 'xterm';
  env.TERM = name;
  env.LINES = rows + '';
  env.COLUMNS = cols + '';

  env = environ(env);

  // fork
  term = opts.uid && opts.gid ?
    pty.fork(file, args, env, cwd, cols, rows, opts.uid, opts.gid) :
    pty.fork(file, args, env, cwd, cols, rows);

  this.socket = new TTYStream(term.fd);
  this.socket.setEncoding('utf8');
  this.socket.resume();

  // Configure "snap" currying, if enabled
  if (opts.snap === true && process.stdout.isTTY === true) {

    if (
      (currentCols && currentRows && cols === currentCols && rows === currentRows === rows) ||
      (cols === DEFAULT_COLS && rows === DEFAULT_ROWS)
    ) {
      // Delay for 1 cycle just to ensure that the "resize" event doesn't
      // trigger when the terminal is first opened
      process.nextTick(function() {
        // Automatically resize to match the TTY dimensions of `process.stdout`
        process.stdout.on('resize', function() {
          self.resize(process.stdout.columns, process.stdout.rows);
        });
      });
    }

    // Curry all data received from the pseudo terminal to `process.stdout`
    self.pipe(process.stdout);

    // Curry all data received from `process.stdin` to the pseudo terminal
    process.stdin.setEncoding('utf8');
    process.stdin.resume();
    process.stdin.pipe(self);

  }

  // setup
  this.socket.on('error', function(err) {
    // NOTE: fs.ReadStream gets EAGAIN twice at first:
    if (err.code) {
      if (err.code.indexOf('EAGAIN') > -1) {
        return;
      }
    }

    // close
    self._close();
    // EIO on exit from fs.ReadStream:
    if (!self._emittedExit) {
      self._emittedExit = true;
      Terminal.total--;
      self.emit('exit', null);
    }

    // EIO, happens when someone closes our child process: the only process in the terminal.
    // node  < 0.6.14: errno 5
    // node >= 0.6.14: read EIO
    if (err.code) {
      if (err.code.indexOf('errno 5') > -1 || err.code.indexOf('EIO') > -1) {
        return;
      }
    }

    // throw anything else
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  this.pid = term.pid;
  this.fd  = term.fd;
  this.pty = term.pty;

  this.file = file;
  this.name = name;
  this.cols = cols;
  this.rows = rows;

  this.readable = true;
  this.writable = true;

  Terminal.total++;

  // XXX This never gets emitted with v0.12.0
  this.socket.on('close', function() {
    if (self._emittedExit) {
      return;
    }
    self._emittedExit = true;
    Terminal.total--;
    self._close();
    self.emit('exit', null);
  });

  env = null;
}

Terminal.fork =
Terminal.spawn =
Terminal.createTerminal = function(file, args, opts) {
  return new Terminal(file, args, opts);
};

/**
 * openpty
 */

Terminal.open = function(opts) {
  opts = opts || {};

  if (arguments.length > 1) {
    opts = {
      cols: arguments[1],
      rows: arguments[2]
    };
  }

  var self = Object.create(Terminal.prototype),
      cols = isValidPositiveInteger(opts.cols) ? opts.cols : DEFAULT_COLS,
      rows = isValidPositiveInteger(opts.rows) ? opts.rows : DEFAULT_ROWS,
      term;

  // open
  term = pty.open(cols, rows);

  self.master = new TTYStream(term.master);
  self.master.setEncoding('utf8');
  self.master.resume();

  self.slave = new TTYStream(term.slave);
  self.slave.setEncoding('utf8');
  self.slave.resume();

  self.socket = self.master;
  self.pid = null;
  self.fd  = term.master;
  self.pty = term.pty;

  self.file = process.argv[0] || 'node';
  self.name = process.env.TERM || '';
  self.cols = cols;
  self.rows = rows;

  self.readable = true;
  self.writable = true;

  self.socket.on('error', function(err) {
    Terminal.total--;
    self._close();
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  Terminal.total++;
  self.socket.on('close', function() {
    Terminal.total--;
    self._close();
  });

  return self;
};

/**
 * Total
 */

// Keep track of the total number of terminals for the process.
Terminal.total = 0;

/**
 * Events
 */

Terminal.prototype.write = function(data) {
  return this.socket.write(data);
};

Terminal.prototype.end = function(data) {
  return this.socket.end(data);
};

Terminal.prototype.pipe = function(dest, options) {
  return this.socket.pipe(dest, options);
};

Terminal.prototype.pause = function() {
  return this.socket.pause();
};

Terminal.prototype.resume = function() {
  return this.socket.resume();
};

Terminal.prototype.setEncoding = function(enc) {
  if (this.socket._decoder) {
    delete this.socket._decoder;
  }
  if (enc) {
    this.socket.setEncoding(enc);
  }
};

Terminal.prototype.addListener =
Terminal.prototype.on = function(type, func) {
  this.socket.on(type, func);
  return this;
};

Terminal.prototype.emit = function() {
  return this.socket.emit.apply(this.socket, arguments);
};

Terminal.prototype.listeners = function(type) {
  return this.socket.listeners(type);
};

Terminal.prototype.removeListener = function(type, func) {
  this.socket.removeListener(type, func);
  return this;
};

Terminal.prototype.removeAllListeners = function(type) {
  this.socket.removeAllListeners(type);
  return this;
};

Terminal.prototype.once = function(type, func) {
  this.socket.once(type, func);
  return this;
};

Object.defineProperty(
  Terminal.prototype,
  'stdin',
  {
    get: function() {
      return this;
    }
  }
);

Object.defineProperty(
  Terminal.prototype,
  'stdout',
  {
    get: function() {
      return this;
    }
  }
);

Object.defineProperty(
  Terminal.prototype,
  'stderr',
  {
    get: function() {
      throw new Error('No stderr.');
    }
  }
);

/**
 * TTY
 */

Terminal.prototype.resize = function(cols, rows) {
  cols = isValidPositiveInteger(cols) ? cols : (isValidPositiveInteger(this.cols) ? this.cols : DEFAULT_COLS);
  rows = isValidPositiveInteger(rows) ? rows : (isValidPositiveInteger(this.rows) ? this.rows : DEFAULT_ROWS);

  this.cols = cols;
  this.rows = rows;

  //
  // TODO: Figure out if there is any way to update the environment of an existing pseudo terminal...?
  //
  //env.LINES = rows + '';
  //env.COLUMNS = cols + '';
  //env = environ(env);

  pty.resize(this.fd, cols, rows);
};

Terminal.prototype.destroy = function() {
  var self = this;

  // Unconfigure "snap" currying, if enabled
  if (opts.snap === true && process.stdout.isTTY === true) {

    // Stop currying all data received from the pseudo terminal to `process.stdout`
    self.unpipe(process.stdout);

    // Stop currying all data received from `process.stdin` to the pseudo terminal
    process.stdin.pause();
    process.stdin.unpipe(self);
  }

  // close
  this._close();

  // Need to close the read stream so
  // node stops reading a dead file descriptor.
  // Then we can safely SIGHUP the shell.
  this.socket.once('close', function() {
    self.kill('SIGHUP');
  });

  this.socket.destroy();
};

Terminal.prototype.kill = function(sig) {
  try {
    process.kill(this.pid, sig || 'SIGHUP');
  }
  catch(e) {
    // Do nothing...
  }
};

Terminal.prototype.redraw = function() {
  var self = this,
      cols = this.cols,
      rows = this.rows;

  // We could just send SIGWINCH, but most programs will
  // ignore it if the size hasn't actually changed.

  this.resize(cols + 1, rows + 1);

  setTimeout(function() {
    self.resize(cols, rows);
  }, 30);
};

Object.defineProperty(
  Terminal.prototype,
  'process',
  {
    get: function() {
      return pty.process(this.fd, this.pty) || this.file;
    }
  }
);

Terminal.prototype._close = function() {
  this.socket.writable = false;
  this.socket.readable = false;
  this.write = function() {};
  this.end = function() {};
  this.writable = false;
  this.readable = false;
};

/**
 * TTY Stream
 */

function TTYStream(fd) {
  // Could use: if (!require('tty').ReadStream)
  if (version[0] === 0 && version[1] < 7) {
    return new net.Socket(fd);
  }

  if (version[0] === 0 && version[1] < 12) {
    return new tty.ReadStream(fd);
  }

  return new Socket(fd);
}

/**
 * Wrap net.Socket for a workaround
 */

function Socket(options) {
  if (!(this instanceof Socket)) {
    return new Socket(options);
  }
  var tty = process.binding('tty_wrap');
  var guessHandleType = tty.guessHandleType;
  tty.guessHandleType = function() {
    return 'PIPE';
  };
  net.Socket.call(this, options);
  tty.guessHandleType = guessHandleType;
}

if (Object.setPrototypeOf) {
  Object.setPrototypeOf(
    Socket.prototype,
    net.Socket.prototype
  );
}
else {
  Socket.prototype._proto_ = net.Socket.prototype;
}

/**
 * Helpers
 */

function environ(env) {
  var keys = Object.keys(env || {}),
      l = keys.length,
      i = 0,
      pairs = [];

  for (; i < l; i++) {
    pairs.push(keys[i] + '=' + env[keys[i]]);
  }

  return pairs;
}

function isValidPositiveInteger(num) {
  return (
    typeof num === 'number' &&
    !isNaN(num) &&
    num > 0 &&
    num !== Infinity &&
    parseInt(num, 10) === num
  );
}

/**
 * Expose
 */

module.exports = exports = Terminal;
exports.Terminal = Terminal;
exports['native'] = pty;


text:
namespace g{namespace Uno{namespace Runtime{namespace Implementation{namespace Internal{struct FormatStringLiteral;}}}}}

namespace g{
namespace Uno{
namespace Runtime{
namespace Implementation{
namespace Internal{

// public sealed class FormatStringLiteral :987
// {
::g::Uno::Runtime::Implementation::Internal::FormatStringToken_type* FormatStringLiteral_typeof();
void FormatStringLiteral__ctor_1_fn(FormatStringLiteral* __this, uString* lexeme);
void FormatStringLiteral__Equals_fn(FormatStringLiteral* __this, uObject* obj, bool* __retval);
void FormatStringLiteral__GetHashCode_fn(FormatStringLiteral* __this, int* __retval);
void FormatStringLiteral__New1_fn(uString* lexeme, FormatStringLiteral** __retval);
void FormatStringLiteral__ToString1_fn(FormatStringLiteral* __this, uArray* objs, uString** __retval);

struct FormatStringLiteral : ::g::Uno::Runtime::Implementation::Internal::FormatStringToken
{
    void ctor_1(uString* lexeme);
    static FormatStringLiteral* New1(uString* lexeme);
};
// }

}}}}} // ::g::Uno::Runtime::Implementation::Internal


text:
'use babel';

import {EOL, DELIMITER} from './message-utils';

function createMessage(msg) {
  return msg + EOL;
}

function positionToString(position) {
  return position.getLine() + DELIMITER + position.getColumn();
}

export function createAddBreakpointMessage(position) {
  return createMessage(`ADDBREAKPOINT${DELIMITER}${positionToString(position)}`);
}

export function createRemoveBreakpointMessage(position) {
  return createMessage(`REMOVEBREAKPOINT${DELIMITER}${positionToString(position)}`);
}

export function createRunToNextBreakpointMessage() {
  return createMessage('RUNTONEXTBREAKPOINT');
}

export function createRunToEndOfMethodMessage() {
  return createMessage('RUNTOENDOFMETHOD');
}

export function createEnableAllBreakpointsMessage() {
  return createMessage('ENABLEALLBREAKPOINTS');
}

export function createDisableAllBreakpointsMessage() {
  return createMessage('DISABLEALLBREAKPOINTS');
}

export function createStartReplayMessage(callId) {
  return createMessage(`STARTREPLAY${DELIMITER}${callId}`);
}

export function createStepMessage() {
  return createMessage('STEP');
}

export function createStepOverMessage() {
  return createMessage('STEPOVER');
}

export function createStopReplayMessage() {
  return createMessage('STOPREPLAY');
}

export function createRemoveAllBreakpointsMessage() {
  return createMessage('REMOVEALLBREAKPOINTS');
}


text:
set -e

export RELEASE_APP_EXE=Release/shared.exe
export RELEASE_UPX_EXE=Release/upxed/shared.exe
export APP_EXE="*.lib"

make clean
make all
cp -p /bin/bash.exe $RELEASE_APP_EXE
#make upx
cp -p $RELEASE_APP_EXE $RELEASE_UPX_EXE
#make sign
cp -p $RELEASE_UPX_EXE $(basename $RELEASE_UPX_EXE)
make hashes
make zip
make tag
make release
make sig
make sum
make upload


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="theme" content="hugo-academic">
  <meta name="generator" content="Hugo 0.31.1" />
  <meta name="author" content="Philippe Grosjean">
  <meta name="description" content="Professor of Marine Ecology and Data Sciences">

  <link rel="alternate" hreflang="en-us" href="/tags/coral-reef/">

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha512-6MXa8B6uaO18Hid6blRMetEIoPqHf7Ux1tnyIQdpt9qI5OACx7C+O3IVTr98vwGnlcg0LOLa02i9Y1HpVhlfiw==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.1/css/academicons.min.css" integrity="sha512-NThgw3XKQ1absAahW6to7Ey42uycrVvfNfyjqcFNgCmOCQ5AR4AO0SiXrN+8ZtYeappp56lk1WtvjVmEa+VR6A==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous">

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700%7cRoboto:400,400italic,700%7cRoboto+Mono">

  <link rel="stylesheet" href="/styles.css">

  <link rel="alternate" href="/index.xml" type="application/rss+xml" title="Philippe Grosjean">
  <link rel="feed" href="/index.xml" type="application/rss+xml" title="Philippe Grosjean">

  <link rel="manifest" href="/site.webmanifest">
  <link rel="icon" type="image/png" href="/img/icon.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png">

  <link rel="canonical" href="/tags/coral-reef/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="twitter:site" content="@PhilGrosjean">
  <meta property="twitter:creator" content="@PhilGrosjean">

  <meta property="og:site_name" content="Philippe Grosjean">
  <meta property="og:url" content="/tags/coral-reef/">
  <meta property="og:title" content="Coral reef | Philippe Grosjean">
  <meta property="og:description" content="Professor of Marine Ecology and Data Sciences">
  <meta property="og:locale" content="en-us">

  <meta property="og:updated_time" content="2014-03-12T00:00:00+00:00">

  <title>Coral reef | Philippe Grosjean</title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
              data-target=".navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>

            Home

            Publications

            Posts

            Projects

            Teaching

            Tags

            Contact

Coral reef

Coral reef ecology in acidified mesocosms

      Studying changes induced by ocean acidification in coral reef ecosystems in artificial mesocosms, focusing on long-term effects to take acclimation into account.

      © 2017-2018 Philippe Grosjean (license CC BY-NC-SA 4.0) ·

      Powered by the
      Academic theme for
      Hugo.

        <button type="button" class="close btn-large" data-dismiss="modal">×</button>

Cite

           Copy

           Download


text:
'use strict';

angular.module('housrApp')
  .config(function($stateProvider) {
    $stateProvider
      .state('logout', {
        url: '/logout',
        templateUrl: 'app/account/logout/logout.html',
        controller: 'LogoutCtrl'
      });
  });


text:
@interface PodsDummy_Pods_GNGradientView_Example : NSObject
@end
@implementation PodsDummy_Pods_GNGradientView_Example
@end


text:
package gatech.mmpm.sensor;

import gatech.mmpm.ActionParameterType;

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

public class SensorLibrary {
	static ArrayList<Sensor> m_sensors = new ArrayList<Sensor>();
	static ArrayList<Sensor> m_conditions = new ArrayList<Sensor>();
	static ArrayList<Sensor> m_goals = new ArrayList<Sensor>();

	public SensorLibrary()
	{

	}
	public static void registerSensor(Sensor s) {
		m_sensors.add(s);
	}

	public static Sensor getSensor(int index) {
		return m_sensors.get(index);
	}

	public static void registerCondition(Sensor c) {
		m_conditions.add(c);
	}

	public static Sensor getCondition(int index) {
		return m_conditions.get(index);
	}

	public static void registerGoal(Sensor c) {
		m_goals.add(c);
	}

	public static Sensor getGoal(int index) {
		return m_goals.get(index);
	}

	public static int getSensorCount() {
		return m_sensors.size();
	}

	public static int getConditionCount() {
		return m_conditions.size();
	}

	public static int getGoalCount() {
		return m_goals.size();
	}

	public static List<Sensor> getSensors() {
		return m_sensors;
	}

	public static List<Sensor> getSensorsByType(ActionParameterType ... types) {
		List<Sensor> sensorsByType = new ArrayList<Sensor>();
		for(Sensor s: m_sensors) {
			for(ActionParameterType type: types)
				if(s.getType() == type)
					sensorsByType.add(s);
		}
		return sensorsByType;
	}

	public static List<Sensor> getConditions() {
		return m_conditions;
	}

	public static List<Sensor> getGoals() {
		return m_goals;
	}

}


text:
/*
 * These authors would like to acknowledge the Spanish Ministry of Industry,
 * Tourism and Trade, for the support in the project TSI020301-2008-2
 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled
 * Mobile Dynamic Environments", led by Treelogic
 * ( http://www.treelogic.com/ ):
 *
 *   http://www.piramidepse.com/
 */

using System;

namespace ZXing.OneD.RSS.Expanded
{
   /// <summary>
   /// <author>Pablo Orduña, University of Deusto (pablo.orduna@deusto.es)</author>
   /// </summary>
   internal sealed class ExpandedPair
   {
      internal bool MayBeLast { get; private set; }
      internal DataCharacter LeftChar { get; private set; }
      internal DataCharacter RightChar { get; private set; }
      internal FinderPattern FinderPattern { get; private set; }

      internal ExpandedPair(DataCharacter leftChar,
                   DataCharacter rightChar,
                   FinderPattern finderPattern,
                   bool mayBeLast)
      {
         LeftChar = leftChar;
         RightChar = rightChar;
         FinderPattern = finderPattern;
         MayBeLast = mayBeLast;
      }

      public bool MustBeLast
      {
         get { return RightChar == null; }
      }

      override public String ToString()
      {
         return
             "[ " + LeftChar + " , " + RightChar + " : " +
             (FinderPattern == null ? "null" : FinderPattern.Value.ToString()) + " ]";
      }

      override public bool Equals(Object o)
      {
         if (!(o is ExpandedPair))
         {
            return false;
         }
         ExpandedPair that = (ExpandedPair)o;
         return
             EqualsOrNull(LeftChar, that.LeftChar) &&
             EqualsOrNull(RightChar, that.RightChar) &&
             EqualsOrNull(FinderPattern, that.FinderPattern);
      }

      private static bool EqualsOrNull(Object o1, Object o2)
      {
         return o1 == null ? o2 == null : o1.Equals(o2);
      }

      override public int GetHashCode()
      {
         return hashNotNull(LeftChar) ^ hashNotNull(RightChar) ^ hashNotNull(FinderPattern);
      }

      private static int hashNotNull(Object o)
      {
         return o == null ? 0 : o.GetHashCode();
      }
   }
}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008-2009 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_SPARSEVECTOR_H
#define EIGEN_SPARSEVECTOR_H

/** \class SparseVector
  *
  * \brief a sparse vector class
  *
  * \param _Scalar the scalar type, i.e. the type of the coefficients
  *
  * See http://www.netlib.org/linalg/html_templates/node91.html for details on the storage scheme.
  *
  */
template<typename _Scalar, int _Flags>
struct ei_traits<SparseVector<_Scalar, _Flags> >
{
  typedef _Scalar Scalar;
  enum {
    IsColVector = _Flags & RowMajorBit ? 0 : 1,

    RowsAtCompileTime = IsColVector ? Dynamic : 1,
    ColsAtCompileTime = IsColVector ? 1 : Dynamic,
    MaxRowsAtCompileTime = RowsAtCompileTime,
    MaxColsAtCompileTime = ColsAtCompileTime,
    Flags = SparseBit | _Flags,
    CoeffReadCost = NumTraits<Scalar>::ReadCost,
    SupportedAccessPatterns = InnerRandomAccessPattern
  };
};

template<typename _Scalar, int _Flags>
class SparseVector
  : public SparseMatrixBase<SparseVector<_Scalar, _Flags> >
{
  public:
    EIGEN_SPARSE_GENERIC_PUBLIC_INTERFACE(SparseVector)
    EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, +=)
    EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, -=)
//     EIGEN_SPARSE_INHERIT_ASSIGNMENT_OPERATOR(SparseVector, =)

  protected:
  public:

    typedef SparseMatrixBase<SparseVector> SparseBase;
    enum { IsColVector = ei_traits<SparseVector>::IsColVector };

    CompressedStorage<Scalar> m_data;
    int m_size;

    CompressedStorage<Scalar>& _data() { return m_data; }
    CompressedStorage<Scalar>& _data() const { return m_data; }

  public:

    EIGEN_STRONG_INLINE int rows() const { return IsColVector ? m_size : 1; }
    EIGEN_STRONG_INLINE int cols() const { return IsColVector ? 1 : m_size; }
    EIGEN_STRONG_INLINE int innerSize() const { return m_size; }
    EIGEN_STRONG_INLINE int outerSize() const { return 1; }
    EIGEN_STRONG_INLINE int innerNonZeros(int j) const { ei_assert(j==0); return m_size; }

    EIGEN_STRONG_INLINE const Scalar* _valuePtr() const { return &m_data.value(0); }
    EIGEN_STRONG_INLINE Scalar* _valuePtr() { return &m_data.value(0); }

    EIGEN_STRONG_INLINE const int* _innerIndexPtr() const { return &m_data.index(0); }
    EIGEN_STRONG_INLINE int* _innerIndexPtr() { return &m_data.index(0); }

    inline Scalar coeff(int row, int col) const
    {
      ei_assert((IsColVector ? col : row)==0);
      return coeff(IsColVector ? row : col);
    }
    inline Scalar coeff(int i) const { return m_data.at(i); }

    inline Scalar& coeffRef(int row, int col)
    {
      ei_assert((IsColVector ? col : row)==0);
      return coeff(IsColVector ? row : col);
    }

    /** \returns a reference to the coefficient value at given index \a i
      * This operation involes a log(rho*size) binary search. If the coefficient does not
      * exist yet, then a sorted insertion into a sequential buffer is performed.
      *
      * This insertion might be very costly if the number of nonzeros above \a i is large.
      */
    inline Scalar& coeffRef(int i)
    {
      return m_data.atWithInsertion(i);
    }

  public:

    class InnerIterator;

    inline void setZero() { m_data.clear(); }

    /** \returns the number of non zero coefficients */
    inline int nonZeros() const  { return m_data.size(); }

    /**
      */
    inline void reserve(int reserveSize) { m_data.reserve(reserveSize); }

    inline void startFill(int reserve)
    {
      setZero();
      m_data.reserve(reserve);
    }

    /**
      */
    inline Scalar& fill(int r, int c)
    {
      ei_assert(r==0 || c==0);
      return fill(IsColVector ? r : c);
    }

    inline Scalar& fill(int i)
    {
      m_data.append(0, i);
      return m_data.value(m_data.size()-1);
    }

    inline Scalar& fillrand(int r, int c)
    {
      ei_assert(r==0 || c==0);
      return fillrand(IsColVector ? r : c);
    }

    /** Like fill() but with random coordinates.
      */
    inline Scalar& fillrand(int i)
    {
      int startId = 0;
      int id = m_data.size() - 1;
      m_data.resize(id+2,1);

      while ( (id >= startId) && (m_data.index(id) > i) )
      {
        m_data.index(id+1) = m_data.index(id);
        m_data.value(id+1) = m_data.value(id);
        --id;
      }
      m_data.index(id+1) = i;
      m_data.value(id+1) = 0;
      return m_data.value(id+1);
    }

    inline void endFill() {}

    void prune(Scalar reference, RealScalar epsilon = precision<RealScalar>())
    {
      m_data.prune(reference,epsilon);
    }

    void resize(int rows, int cols)
    {
      ei_assert(rows==1 || cols==1);
      resize(IsColVector ? rows : cols);
    }

    void resize(int newSize)
    {
      m_size = newSize;
      m_data.clear();
    }

    void resizeNonZeros(int size) { m_data.resize(size); }

    inline SparseVector() : m_size(0) { resize(0); }

    inline SparseVector(int size) : m_size(0) { resize(size); }

    inline SparseVector(int rows, int cols) : m_size(0) { resize(rows,cols); }

    template<typename OtherDerived>
    inline SparseVector(const MatrixBase<OtherDerived>& other)
      : m_size(0)
    {
      *this = other.derived();
    }

    template<typename OtherDerived>
    inline SparseVector(const SparseMatrixBase<OtherDerived>& other)
      : m_size(0)
    {
      *this = other.derived();
    }

    inline SparseVector(const SparseVector& other)
      : m_size(0)
    {
      *this = other.derived();
    }

    inline void swap(SparseVector& other)
    {
      std::swap(m_size, other.m_size);
      m_data.swap(other.m_data);
    }

    inline SparseVector& operator=(const SparseVector& other)
    {
      if (other.isRValue())
      {
        swap(other.const_cast_derived());
      }
      else
      {
        resize(other.size());
        m_data = other.m_data;
      }
      return *this;
    }

    template<typename OtherDerived>
    inline SparseVector& operator=(const SparseMatrixBase<OtherDerived>& other)
    {
      return Base::operator=(other);
    }

//       const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
//       if (needToTranspose)
//       {
//         // two passes algorithm:
//         //  1 - compute the number of coeffs per dest inner vector
//         //  2 - do the actual copy/eval
//         // Since each coeff of the rhs has to be evaluated twice, let's evauluate it if needed
//         typedef typename ei_nested<OtherDerived,2>::type OtherCopy;
//         OtherCopy otherCopy(other.derived());
//         typedef typename ei_cleantype<OtherCopy>::type _OtherCopy;
//
//         resize(other.rows(), other.cols());
//         Eigen::Map<VectorXi>(m_outerIndex,outerSize()).setZero();
//         // pass 1
//         // FIXME the above copy could be merged with that pass
//         for (int j=0; j<otherCopy.outerSize(); ++j)
//           for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
//             ++m_outerIndex[it.index()];
//
//         // prefix sum
//         int count = 0;
//         VectorXi positions(outerSize());
//         for (int j=0; j<outerSize(); ++j)
//         {
//           int tmp = m_outerIndex[j];
//           m_outerIndex[j] = count;
//           positions[j] = count;
//           count += tmp;
//         }
//         m_outerIndex[outerSize()] = count;
//         // alloc
//         m_data.resize(count);
//         // pass 2
//         for (int j=0; j<otherCopy.outerSize(); ++j)
//           for (typename _OtherCopy::InnerIterator it(otherCopy, j); it; ++it)
//           {
//             int pos = positions[it.index()]++;
//             m_data.index(pos) = j;
//             m_data.value(pos) = it.value();
//           }
//
//         return *this;
//       }
//       else
//       {
//         // there is no special optimization
//         return SparseMatrixBase<SparseMatrix>::operator=(other.derived());
//       }
//     }

    friend std::ostream & operator << (std::ostream & s, const SparseVector& m)
    {
      for (unsigned int i=0; i<m.nonZeros(); ++i)
        s << "(" << m.m_data.value(i) << "," << m.m_data.index(i) << ") ";
      s << std::endl;
      return s;
    }

    // this specialized version does not seems to be faster
//     Scalar dot(const SparseVector& other) const
//     {
//       int i=0, j=0;
//       Scalar res = 0;
//       asm("#begindot");
//       while (i<nonZeros() && j<other.nonZeros())
//       {
//         if (m_data.index(i)==other.m_data.index(j))
//         {
//           res += m_data.value(i) * ei_conj(other.m_data.value(j));
//           ++i; ++j;
//         }
//         else if (m_data.index(i)<other.m_data.index(j))
//           ++i;
//         else
//           ++j;
//       }
//       asm("#enddot");
//       return res;
//     }

    /** Destructor */
    inline ~SparseVector() {}
};

template<typename Scalar, int _Flags>
class SparseVector<Scalar,_Flags>::InnerIterator
{
  public:
    InnerIterator(const SparseVector& vec, int outer=0)
      : m_data(vec.m_data), m_id(0), m_end(m_data.size())
    {
      ei_assert(outer==0);
    }

    InnerIterator(const CompressedStorage<Scalar>& data)
      : m_data(data), m_id(0), m_end(m_data.size())
    {}

    template<unsigned int Added, unsigned int Removed>
    InnerIterator(const Flagged<SparseVector,Added,Removed>& vec, int outer)
      : m_data(vec._expression().m_data), m_id(0), m_end(m_data.size())
    {}

    inline InnerIterator& operator++() { m_id++; return *this; }

    inline Scalar value() const { return m_data.value(m_id); }
    inline Scalar& valueRef() { return const_cast<Scalar&>(m_data.value(m_id)); }

    inline int index() const { return m_data.index(m_id); }
    inline int row() const { return IsColVector ? index() : 0; }
    inline int col() const { return IsColVector ? 0 : index(); }

    inline operator bool() const { return (m_id < m_end); }

  protected:
    const CompressedStorage<Scalar>& m_data;
    int m_id;
    const int m_end;

  private:
    InnerIterator& operator=(const InnerIterator&);
};

#endif // EIGEN_SPARSEVECTOR_H


text:
package org.gradle.nativeplatform.toolchain.internal.gcc;

import org.gradle.nativeplatform.toolchain.internal.ArgsTransformer;
import org.gradle.nativeplatform.toolchain.internal.MacroArgsConverter;
import org.gradle.nativeplatform.toolchain.internal.NativeCompileSpec;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Maps common options for C/C++ compiling with GCC
 */
abstract class GccCompilerArgsTransformer<T extends NativeCompileSpec> implements ArgsTransformer<T> {
    public List<String> transform(T spec) {
        List<String> args = new ArrayList<String>();
        Collections.addAll(args, "-x", getLanguage());

        for (String macroArg : new MacroArgsConverter().transform(spec.getMacros())) {
            args.add("-D" + macroArg);
        }

        args.addAll(spec.getAllArgs());
        args.add("-c");
        if (spec.isPositionIndependentCode()) {
            if (!spec.getTargetPlatform().getOperatingSystem().isWindows()) {
                args.add("-fPIC");
            }
        }

        for (File file : spec.getIncludeRoots()) {
            args.add("-I");
            args.add(file.getAbsolutePath());
        }
        return args;
    }

    protected abstract String getLanguage();

}


text:
/*
 * $Id$
 */

#ifndef OFTPD_H
#define OFTPD_H

/* address to listen on (use NULL to listen on all addresses) */
#define FTP_ADDRESS NULL

/* default port FTP server listens on (use 0 to listen on default port) */
#define FTP_PORT 0

/* ranges possible for command-line specified port numbers */
#define MIN_PORT 0
#define MAX_PORT 65535

/* default maximum number of clients */
#define MAX_CLIENTS 250

/* bounds on command-line specified number of clients */
#define MIN_NUM_CLIENTS 1
#define MAX_NUM_CLIENTS 300

/* timeout (in seconds) before dropping inactive clients */
#define INACTIVITY_TIMEOUT (15 * 60)

/* README file name (sent automatically as a response to users) */
#define README_FILE_NAME "README"

/* The debug flags control the amount of logging.  */
extern int debug_flags;
#define DEBUG_NONE	0
#define DEBUG_XFER	(1 << 0)
#define DEBUG_CMDS	(1 << 1)

#endif /* OFTPD_H */


text:
package io.rong.app.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import io.rong.app.R;
import io.rong.app.activity.MyAccountActivity;

import com.example.testpic.AlbumHelper;
import com.example.testpic.Bimp;
import com.example.testpic.ImageGridAdapter;
import com.example.testpic.ImageGridAdapter.TextCallback;
import com.example.testpic.ImageItem;
import com.example.testpic.PublishedActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class SelectPictureGridActivity extends Activity
{
	public static final String EXTRA_IMAGE_LIST = "imagelist";

	// ArrayList<Entity> dataList;//鐢ㄦ潵瑁呰浇鏁版嵁婧愮殑鍒楄〃
	List<ImageItem> dataList;
	GridView gridView;
	ImageGridAdapter adapter;// 鑷畾涔夌殑閫傞厤鍣�
	AlbumHelper helper;
	Button bt;

	Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case 0:
				Toast.makeText(SelectPictureGridActivity.this, "最多选择9张图片", 400).show();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_image_grid);

		helper = AlbumHelper.getHelper();
		helper.init(getApplicationContext());

		dataList = (List<ImageItem>) getIntent().getSerializableExtra(
				EXTRA_IMAGE_LIST);

		initView();
		bt = (Button) findViewById(R.id.bt);
		bt.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{

			}

		});
	}

	private void initView()
	{
		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new ImageGridAdapter(SelectPictureGridActivity.this, dataList,
				mHandler);
		gridView.setAdapter(adapter);
		adapter.setTextCallback(new TextCallback()
		{
			public void onListen(int count)
			{
				bt.setText("完成" + "(" + count + ")");
				Log.i("select picture","222222222222");
				Log.i("select picture","count->"+count);
				ArrayList<String> list = new ArrayList<String>();
				Collection<String> c = adapter.map.values();
				Iterator<String> it = c.iterator();
				adapter.map.values().iterator().next();
				Log.i("select picture"," list.size()"+ list.size());
				for (; it.hasNext();)
				{
					list.add(it.next());
				}
				Log.i("select picture"," list.size()"+ list.size());
//				if (Bimp.act_bool)
//				{
//					setResult(Activity.RESULT_OK);
//					Bimp.act_bool = false;
//				}
//				for (int i = 0; i < list.size(); i++)
//				{
//					if (Bimp.drr.size() < 9)
//					{
						Bimp.drr.clear();
						Bimp.drr.add(list.get(0));
						String path = Bimp.drr.get(Bimp.max);
						System.out.println(path);
						Log.i("picture address","path->"+path);
//					}
//				}
				Intent intent=new Intent();
				intent.putExtra("path", path);
				Log.i("SelectPictureGridActivity"," path="+ path);
				setResult(Activity.RESULT_OK,intent);
				Log.i("SelectPictureGridActivity"," list.size()"+ list.size());
				finish();

			}
		});

		gridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				adapter.notifyDataSetChanged();
			}

		});

	}
}


text:
import random

class Enemy:

    def __init__(self, hp):

        self.hp = hp

class Weapon:

    def __init__(self, name, damage, durability, weight, cost, accuracy):

        self.name = name
        self.damage = damage
        self.max_durability = durability
        self.durability = durability
        self.weight = weight
        self.cost = cost
        self.accuracy = accuracy

    def attack(self, enemy):

        hit_chance = random.randint(1,100)
        if hit_chance <= self.accuracy:
            enemy.hp -= self.damage
            self.durability -= 1
        else:
            print 'You missed!'

    def repair(self):
        self.durability = self.max_durability

    def __str__(self):
        return '''Name: {}
Damage: {}
Durability: {}
Weight: {}
Cost: {}
Accuracy: {}'''.format(self.name, self.damage, self.durability, self.weight, self.cost, self.accuracy)

class MasterSword(Weapon):

    def __init__(self, name, damage, weight, cost, accuracy):

        Weapon.__init__(self, name, damage, 'Infinite', weight, cost, accuracy)

    def attack(self, enemy):

        hit_chance = random.randint(1,100)
        if hit_chance <= self.accuracy:
            enemy.hp -= self.damage
        else:
            print 'You missed!'


text:
package cn.xishan.oftenporter.servlet.render.mapping;

import cn.xishan.oftenporter.porter.core.annotation.AspectOperationOfPortIn;
import cn.xishan.oftenporter.porter.core.annotation.PortIn;
import cn.xishan.oftenporter.porter.core.base.PortMethod;

import java.lang.annotation.*;

/**
 * 注解在{@linkplain PortIn}接口函数上,用于直接绑定servlet-path,需要自行处理响应。
 *

 *

 *         注解的函数返回false,表示放弃自行处理,接着会进行后续处理。
 *

 *

 *
 * @author Created by https://github.com/CLovinr on 2020/5/16.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@AspectOperationOfPortIn(handle = PathMappingHandle.class)
public @interface PathMapping
{
    /**
     * 实际访问的页面路径(规则同servlet)。
     *
     * @return
     */
    String[] path();

    PortMethod[] method() default {PortMethod.GET};

    /**
     * 对于同一个请求被多次匹配的情况,数值更小的会被执行。
     *
     * @return
     */
    int order() default 0;

    boolean enable() default true;
}


text:
Shopping Cart

                Your shopping cart is empty

Name:{{item.product.name}}

Product:{{item.product.productId}}

Unit Price:{{item.product.unitPrice |
                        currency}}

                        <form ng-submit="updateCart()" ng-controller="UpdateCartCtrl">

<input type="text" ng-model="item.quantity" placeholder="QTY"
                                                               class="form-control qty-text">

                                <input type="hidden" ng-model="item.productId" value="{{item.productId}}"/>
                                <input type="hidden" ng-model="originalQuantity" value="{{item.quantity}}"/>
                                <button class="btn btn-primary" id="updateCart-{{item.productId}}" type="submit">
                                    Update
                                </button>

Cart updated!

                        </form>

 0">

Items: {{cart.totalItems}}

Sub-total: {{cart.total | currency}}

                        <form ng-submit="checkout()" ng-controller="CheckoutCtrl">
                            <button class="btn btn-primary" id="" type="submit">
                                Checkout
                            </button>
                        </form>


text:
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$email = ($this->session->userdata['logged_in']['email']);
$tipouser = ($this->session->userdata['logged_in']['tipo_usuario']);
} else {
redirect(base_url());
}
?>

<?php if ($tipouser == 'Administrador' || $tipouser == 'OPERADOR'){

 } else {
    redirect(base_url());
 }?>

           Tipos de Monedas

<a href="<?php echo base_url(); ?>index.php"  style="color:#3C8DBC"> Inicio

Configuraciones

Tipos de Monedas

Listado de Tipos de Monedas

                <button role="button" class="btn btn-primary" style="font-weight: bold;font-size: 13px; color: white " id="enviar"  >

                      Agregar Tipo de Moneda
                </button>

                        Item
                        Tipo Moneda
                        Símbolo
                        Activar/Desactivar
                        Editar
                        Borrar

                            <?php $i = 1; ?>

                            <?php foreach ($listar as $bancos) { ?>

                                        <?php echo $i; ?>

                                        <?php echo $bancos->descripcion; ?>

                                        <?php echo $bancos->abreviatura; ?>

				      <?php if ($bancos->activo == 't') {?>
				      <input class='activar_desactivar' id='<?php echo $bancos->id; ?>' type="checkbox" title='Desactivar el usuario <?php echo $bancos->id;?>' checked="checked"/>
				      <?php }else if ($bancos->activo == 'f'){ ?>
				      <input class='activar_desactivar' id='<?php echo $bancos->id; ?>' type="checkbox" title='Activar el usuario <?php echo $bancos->id;?>'/>
				      <?php } ?>

				       <a title="Editar" href="<?php echo base_url() ?>index.php/configuracion/CTiposMonedas/editar/<?= $bancos->id; ?>">

				       <a data-toggle="modal" data-target="#myModal" class='levantar' id='<?php echo $bancos->id; ?>' title="Borrar" >

                                <?php $i++ ?>
                            <?php } ?>

            Version 1.0

        Network C. A.

Eliminar Registro

¿Está seguro que desea eliminar este registro?, si quiere eliminarlo haga click en el botón
                Procesar, de lo contrario si desea cancelar esta acción click en
                 Descartar.

                <button type="button" class="btn btn-warning" class="close" data-dismiss="modal" style="font-weight: bold" >Descartar</button>
                <button type="button" class="btn btn-danger " id="procesar" style="font-weight: bold">Procesar</button>


text:
# Common Causes For Redesign

1. **Creating an object by specifying a class explicitly:**  Abstract Factory (87), Factory Method (107), Prototype (117)
2. **Dependence on specific operations**: Chain of Responsibility (223), Command (233).
3. **Dependence on hardware and software platform**: Abstract Factory (87), Bridge (151)
4. **Dependence on object representations or implementations**: Abstract Factory (87), Bridge (151), Memento (283), Proxy (207)
5. **Algorithmic dependencies**:  Builder (97), Iterator (257), Strategy (315), Template Method (325), Visitor (331)
6. **Tight coupling**:  Abstract Factory (87), Bridge (151), Chain of Responsibility (223), Command (233),
Facade (185), Mediator (273), Observer (293)
7. **Extending functionality by subclassing**: Bridge (151), Chain of Responsibility (223), Composite (163), Decorator (175), Observer (293), Strategy (315)
8. **Inability to alter classes conveniently**:  Adapter (139), Decorator (175), Visitor (331)

# Variable in the design
See GoF 38

# **Creational Patterns**

## Abstract Factory
> Provide an interface for creating families of related or dependent objects without specifying their
concrete classes.

```java
public interface Button {
    void click();
}

// LinuxButton, OsxButton implement it

public interface Window {
    void show();
}

// LinuxWindow, OsxWindow implement it

public interface AbstractFactory {
    Button createButton();
    Window createWindow();
}

public class LinuxFactory implements AbstractFactory {
    @Override
    Button createButton() {
        return new LinuxButton();
    }
    @Override
    Window createWindow() {
        return new LinuxWindow();
    }
}

//Similarly for OsxFactory
```

## Builder

> Separate the construction of a complex object from its representation so that the same construction process can create different representations.

**The telescoping constructor anti-pattern** occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

## Factory Method
> Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

```java
public abstract class BaseHandler {
    public void handle() {
        newProduct.doAction();
    }

    public abstract Product newProduct();
}

public class ConcreteHandler extends BaseHandler {
    @Override
    public Product newProduct() {
        return new ConcreteProductA();
    }
}
```

## Prototype
> Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

The prototype and the factory are one and the same.

## Singleton
> Ensure a class only has one instance, and provide a global point of access to it.

```java
public class Singleton {
	private static Singleton instance = null;
	private Singleton() {
	}
	public synchronized Singleton getInstance() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}
```

## Differences between Creational Patterns

There are 2 ways to parameterize a system by the classes of objects it creates.

1. Subclass the class that creates the objects (**Factory Method**)
2. Define an object that is responsible for knowing the class of the product objects and make it a parameter of the system (**Abstract Factory**, **Builder** and **Prototype**)
* **Abstract Factory** has the factory object producing objects of several classes
* **Builder** has the factory object create a complex product incrementally using a complex protocol
* **Prototype** is when the factory object and the product are one and the product creates new objects by cloning itself.

# **Structural Patterns**

## Adapter

> Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

```java
public interface Adaptee {
    void specificRequest();
}

public interface Target {
    void request();
}

public class Adapter implements Target {
    private final Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}
```

```cpp
class Adaptee {
    public:
        void specificRequest();
}

class Target {
    public:
        virtual void request() = 0;
}

class Adapter : public Target, private Adaptee {
    public:
        virtual void request() override {
            specificRequest();
        }
}
```

## Bridge

> Decouple an abstraction from its implementation so that the two can vary independently.

```java
public interface Database {
    Object[] runQuery(String query);
}

public class MySql implements Database {
    Object[] runQuery(String query) {
        //...
    }
}

public class JsonStore implements Database {
    Object[] runQuery(String query) {
        //...
    }
}

public abstract class Settings {
    private final Database database;

    public Settings(Database database) {
        this.database = database;
    }

    public String get(String key) {
        Object[] results = database.runQuery(key);
        //...
    }
}

/*
 * The abstraction evolves separately from the implementor
 */
public class ApplicationSettigns {
    private final String name;

    public ApplicationSettings(String name, Database database) {
        super(database);
        this.name = name;
    }

    public void save(String key) {
        //...
    }

}
```

## Composite

> Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

```java
public abstract class Component {
    public void add(Component component) {
        throw new UnsupportedOperationException();
    }
    public void remove(Component component) {
        throw new UnsupportedOperationException();
    }

    public abstract void operationA();

}

public class Item extends Component {
    @Override
    void operationA() {
        //...
    }
}

public class Composite extends Component {

    private final List<Component> components = new ArrayList<>();

    @Override
    public void add(Component component) {
        //...
    }

    @Override
    public void remove(Component component) {
        //...
    }

    @Override
    public void operationA() {
        for (Component component : components) {
            component.operationA();
        }
    }
}
```

## Decorator

> Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

```java
public interface Component {
    void operationA();
}

/**
 * Base decorator class just delegates to the encapsulated component
 */
public abstract class Decorator implements Component {
    private final Component component;

    public Decorator(final Component component) {
        this.component = component;
    }

    @Override
    public void operationA() {
        component.operationA();
    }
}

public class RepeatingDecorator extends Decorator {
    public RepeatingDecorator(final Component component) {
        super(component);
    }

    @Override
    public void operationA() {
        for (int i = 0; i < 100; i++) {
            super.operationA();
        }
    }
}

public class LoggingDecorator extends Decorator {
    public RepeatingDecorator(final Component component) {
        super(component);
    }

    @Override
    public void operationA() {
        System.out.println("OperationA START");
        super.operationA()
        System.out.println("OperationA END");
    }
}

```

## Facade

> Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

## Flyweight
> Use sharing to support large numbers of fine-grained objects efficiently.

Usually along with maps to check for its existence.

## Proxy
> Provide a surrogate or placeholder for another object to control access to it.

Types:

* Remote Proxy for remote objects
* Virtual Proxy for creating expensive objects on demand
* Protection Proxy to control access
* Smart reference proxy like smart_ptr in C++

## Differences between Structural Patterns

## Adapter/Bridge/Facade
* The key difference lies in the intents of the two patterns.
* The **adapter** focuses on resolving an incombatibility between two **existing** interfaces. It does not focus on how those interfaces are implemented nor does it consider how they might evolve independently.
* **Bridge** on the other hand bridges an **abstraction** and its - possibly numerous - implementations. It provides a **stable interface for clients** and at the same time accomodates new implementations as the system evolves.
* **Bridge** is frequently used during the design phase of a system whereas the **adapter** is used after a system has been designed.
* Finally, although a **Facade** seems like an adapter for a set of objects, it is important to note that it **defines a new interface** while an adapter implements an existing one.

## Composite/Decorator/Proxy
* **Composite** and **decorator** have similar class diagrams as they both rely on recursive composition.
* **Decorator** is used to **add responsibilities to objects without subclassing**, thus avoiding an explosion of subclasses when trying to generate all possible combinations.
* On the other hand, **Composite** focuses on structuring classes so that **many similar objects can be treated uniformly**.
* Similarly to the **Decorator**, a **Proxy** describes how to provide a level of indirection to an objects and it also forwards requests to an encapsulated object. It also provides an interface identical to this object.
* However, the **Proxy** is **not** concerned with attaching or detaching properties dynamically. Its intent is to **provide a stand-in for an object when it's inconvenient or undesirable to access the object directly**.
* In the **Proxy** pattern, the subject defines the key functionality, and the proxy **provides (or refuses) access to it**. In **Decorator**, the component provides **only part of the functionality**, and one or more decorators furnish the rest.

# **Behavioral Patterns**

## Chain of Responsibility

> Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

```java
public abstract class Logger {
    private final Logger next;

    public Logger(Logger next) {
        this.next = next;
    }

    public void log(String message, MessageType type) {
        if (canHandle(type)) {
            //...
        }
        else {
            if (next != null) {
                next.log(message, type);
            }
        }
    }

    public abstract boolean canHandle(MessageType type);
}

// ...
```
## Command

> Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

1. Command decouples the object that invokes the operation from the one that knows how to perform it.
2. You can assemble commands into a composite command. An example is the MacroCommand class described earlier.
3. Commands are first-class objects. They can be manipulated and extended like any other object.
4. It's easy to add new Commands, because you don't have to change existing classes.

```java
public interface Command {
    void execute();
    void undo();
}

public class Light {
    public void turnOn() {
        //...
    }
    public void turnOff() {
        //...
    }
}

public class TurnOnCommand implements Command {

    private final Light receiver;

    public TurnOnCommand(Light receiver) {
        this.receiver = receiver;
    }

    public void execute() {
        //...
    }

    public void undo() {
        //...
    }
}
```

## Interpreter

> Given a language, define a represention for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Can be used alogn with a **Visitor** if you want to keep creating new ways of interpreting an expression.

## Iterator
> Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

1. Usually generated by the container by a **Factory Method**.
2. Can either be **external** or **internal** (which is used in map/filter operations).

## Mediator

> Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

## Memento

> Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

## Observer

> Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

```java
public interface Observer {
    void update(Observable o); // The parameter is optional
}

public interface Observable { //Also known as Subject
    void add(Observer o);
    void remove(Observer o);
    void notify() {
        //Sample impl
        for (Observer o : observers) {
            o.update(this);
        }
    }
}
```

## State

> Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

TCP Connection example. All states have the same functions but some functions also change the current state of the context.

Differences from Strategy:

* States store a reference to the context object that contains them. Strategies do not.
* States are allowed to replace themselves (IE: to change the state of the context object to something else), while Strategies are not.
* Strategies are passed to the context object as parameters, while States are created by the context object itself.
* Strategies only handle a single, specific task, while States provide the underlying implementation for everything (or most everything) the context object does.

## Strategy
> Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

1. Provides an alternative to subclassing.
2. Eliminates conditional statements

## Template Method

> Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Holywood principle

```java
public abstract class Algorithm {
    public void compute() {
        doA();
        doB();
        System.out.println("Doing C...");
        doC();
    }

    public void doA() {
        //...
    }

    public abstract void doB();
    public abstract void doC();
}
//...
```

## Visitor

> Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

```java
public class A {
    void accept(Visitor v) {
        v.visitA(this);
    }
}

public class B {
    void accept(Visitor v) {
        v.visitB(this);
    }
}

// Difificult to add new visitable classes, have to change all Visitor implementations
// But easy to add new operations, just implement a visitor that performs them
public iterface Visitor {
    void visitA(A obj);
    void visitB(B obj);
}

Visitor visitor = new ComplexVisitor();
for (Object o : objects) {
    o.accept(visitor)
}
```

## Encapsulation
* a **Strategy** object encapsulates an algorithm
* a **State** object encapsulates a state-dependent behavior
* a **Mediator** object encapsulates the protocol between objects, and
* an **Iterator** object encapsulates the way you access and traverse the components of an aggregate object

**Chain of Responsibility** illustrates another difference in behavioral patterns: Not all define static
communication relationships between classes. Chain of Responsibility prescribes communication
between an open-ended number of objects.

## Objects as arguments

* A **Visitor** object is the argument to a polymorphic Accept operation on the objects it visits
* Other patterns define objects that act as magic tokens to be passed around and invoked at a later time.
Both **Command** and **Memento** fall into this category

## Encapsulated vs Distributed Communication
**Mediator** and **Observer** are competing patterns. The difference between them is that Observer
distributes communication by introducing Observer and Subject objects, whereas a Mediator object encapsulates the communication between other objects

In the Observer pattern, there is no single object that encapsulates a constraint. Instead, the Observer and the Subject must cooperate to maintain the constraint. Communication patterns are determined by the way observers and subjects are interconnected: a single subject usually has many observers, and sometimes the observer of one subject is a subject of another observer. The Mediator pattern centralizes rather than distributes. It places the responsibility for maintaining a constraint squarely in the mediator.

## Decoupling Senders and Receivers
When collaborating objects refer to each other directly, they become dependent on each other, and that can have an adverse impact on the layering and reusability of a system. **Command, Observer, Mediator, and Chain of Responsibility** address how you can decouple senders and receivers, but with different tradeoffs.

See GoF - Page 291 for diagrams


text:
class ProjectRolesController < ApplicationController

  # #####################################################
  # GET /project_roles
  # GET /project_roles.xml
  # #####################################################
  def index
    @project_roles = ProjectRole.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @project_roles }
    end
  end

  # #####################################################
  # GET /project_roles/1
  # GET /project_roles/1.xml
  # #####################################################
  def show
    @project_role = ProjectRole.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @project_role }
    end
  end

  # #####################################################
  # GET /project_roles/new
  # GET /project_roles/new.xml
  # #####################################################
  def new
    @project_role = ProjectRole.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @project_role }
    end
  end

  # #####################################################
  # GET /project_roles/1/edit
  # #####################################################
  def edit
    @project_role = ProjectRole.find(params[:id])
  end

  # #####################################################
  # POST /project_roles
  # POST /project_roles.xml
  # #####################################################
  def create
    @project_role = ProjectRole.new(params[:project_role])

    respond_to do |format|
      if @project_role.save
        format.html { redirect_to(@project_role, :notice => 'ProjectRole was successfully created.') }
        format.xml  { render :xml => @project_role, :status => :created, :location => @project_role }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @project_role.errors, :status => :unprocessable_entity }
      end
    end
  end

  # #####################################################
  # PUT /project_roles/1
  # PUT /project_roles/1.xml
  # #####################################################
  def update
#    @project_role = ProjectRole.find(params[:id])
#
#    respond_to do |format|
#      if @project_role.update_attributes(params[:project_role])
#        format.html { redirect_to(@project_role, :notice => 'ProjectRole was successfully updated.') }
#        format.xml  { head :ok }
#      else
#        format.html { render :action => "edit" }
#        format.xml  { render :xml => @project_role.errors, :status => :unprocessable_entity }
#      end
#    end
  end

  # #####################################################
  # DELETE /project_roles/1
  # DELETE /project_roles/1.xml
  # #####################################################
  def destroy
#    @project_role = ProjectRole.find(params[:id])
#    @project_role.destroy
#
#    respond_to do |format|
#      format.html { redirect_to(project_roles_url) }
#      format.xml  { head :ok }
#    end
  end
end


text:
<Record>
<Term>Visceral Prolapse</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Gastrointestinal Diseases</ParentTerm>
<ParentTerm>Pelvic Organ Prolapse</ParentTerm>
<ClassificationPath>Pathological Conditions, Signs and Symptoms/Pathological Conditions, Anatomical/Prolapse/Pelvic Organ Prolapse/Visceral Prolapse</ClassificationPath>
<ClassificationPath>Digestive System Diseases/Gastrointestinal Diseases/Visceral Prolapse</ClassificationPath>
<BroaderTerm>Pathological Conditions, Signs and Symptoms</BroaderTerm>
<BroaderTerm>Pathological Conditions, Anatomical</BroaderTerm>
<BroaderTerm>Gastrointestinal Diseases</BroaderTerm>
<BroaderTerm>Digestive System Diseases</BroaderTerm>
<BroaderTerm>Visceral Prolapse</BroaderTerm>
<BroaderTerm>Pelvic Organ Prolapse</BroaderTerm>
<BroaderTerm>Prolapse</BroaderTerm>
<Synonym>Visceral Prolapse</Synonym>
<Synonym>Splanchnoptosis</Synonym>
<Synonym>Visceroptosis</Synonym>
<Description>The prolapse or downward displacement of the VISCERA.</Description>
<Source>MeSH</Source>
</Record>


text:
using std::vector;

#include <fst/extensions/far/far.h>

namespace fst {

template<class Arc>
inline void FarWriteFst(const Fst<Arc>* fst, string key,
                        string* okey, int* nrep,
                        const int32 &generate_filenames, int i,
                        const string &filename_prefix,
                        const string &filename_suffix) {
  if (key == *okey)
    ++*nrep;
  else
    *nrep = 0;

  *okey = key;

  string ofilename;
  if (generate_filenames) {
    ostringstream tmp;
    tmp.width(generate_filenames);
    tmp.fill('0');
    tmp << i;
    ofilename = tmp.str();
  } else {
    if (*nrep > 0) {
      ostringstream tmp;
      tmp << '.' << nrep;
      key.append(tmp.str().data(), tmp.str().size());
    }
    ofilename = key;
  }
  fst->Write(filename_prefix + ofilename + filename_suffix);
}

template<class Arc>
void FarExtract(const vector<string> &ifilenames,
                const int32 &generate_filenames,
                const string &keys,
                const string &key_separator,
                const string &range_delimiter,
                const string &filename_prefix,
                const string &filename_suffix) {
  FarReader<Arc> *far_reader = FarReader<Arc>::Open(ifilenames);
  if (!far_reader) return;

  string okey;
  int nrep = 0;

  vector<char *> key_vector;
  // User has specified a set of fsts to extract, where some of the "fsts" could
  // be ranges.
  if (!keys.empty()) {
    char *keys_cstr = new char[keys.size()+1];
    strcpy(keys_cstr, keys.c_str());
    SplitToVector(keys_cstr, key_separator.c_str(), &key_vector, true);
    int i = 0;
    for (int k = 0; k < key_vector.size(); ++k, ++i) {
      string key = string(key_vector[k]);
      char *key_cstr = new char[key.size()+1];
      strcpy(key_cstr, key.c_str());
      vector<char *> range_vector;
      SplitToVector(key_cstr, range_delimiter.c_str(), &range_vector, false);
      if (range_vector.size() == 1) {  // Not a range
        if (!far_reader->Find(key)) {
          LOG(ERROR) << "FarExtract: Cannot find key: " << key;
          return;
        }
        const Fst<Arc> &fst = far_reader->GetFst();
        FarWriteFst(&fst, key, &okey, &nrep, generate_filenames, i,
                    filename_prefix, filename_suffix);
      } else if (range_vector.size() == 2) {  // A legal range
        string begin_key = string(range_vector[0]);
        string end_key = string(range_vector[1]);
        if (begin_key.empty() || end_key.empty()) {
          LOG(ERROR) << "FarExtract: Illegal range specification: " << key;
          return;
        }
        if (!far_reader->Find(begin_key)) {
          LOG(ERROR) << "FarExtract: Cannot find key: " << begin_key;
          return;
        }
        for ( ; !far_reader->Done(); far_reader->Next(), ++i) {
          string ikey = far_reader->GetKey();
          if (end_key < ikey) break;
          const Fst<Arc> &fst = far_reader->GetFst();
          FarWriteFst(&fst, ikey, &okey, &nrep, generate_filenames, i,
                      filename_prefix, filename_suffix);
        }
      } else {
        LOG(ERROR) << "FarExtract: Illegal range specification: " << key;
        return;
      }
      delete key_cstr;
    }
    delete keys_cstr;
    return;
  }
  // Nothing specified: extract everything.
  for (int i = 1; !far_reader->Done(); far_reader->Next(), ++i) {
    string key = far_reader->GetKey();
    const Fst<Arc> &fst = far_reader->GetFst();
    FarWriteFst(&fst, key, &okey, &nrep, generate_filenames, i,
                filename_prefix, filename_suffix);
  }
  return;
}

}  // namespace fst

#endif  // FST_EXTENSIONS_FAR_EXTRACT_H__