text:
"""
    pygments.formatters.irc
    ~~~~~~~~~~~~~~~~~~~~~~~

    Formatter for IRC output

    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
    Number, Operator, Generic, Token, Whitespace
from pip._vendor.pygments.util import get_choice_opt

__all__ = ['IRCFormatter']

#: Map token types to a tuple of color values for light and dark
#: backgrounds.
IRC_COLORS = {
    Token:              ('',            ''),

    Whitespace:         ('gray',   'brightblack'),
    Comment:            ('gray',   'brightblack'),
    Comment.Preproc:    ('cyan',        'brightcyan'),
    Keyword:            ('blue',    'brightblue'),
    Keyword.Type:       ('cyan',        'brightcyan'),
    Operator.Word:      ('magenta',      'brightcyan'),
    Name.Builtin:       ('cyan',        'brightcyan'),
    Name.Function:      ('green',   'brightgreen'),
    Name.Namespace:     ('_cyan_',      '_brightcyan_'),
    Name.Class:         ('_green_', '_brightgreen_'),
    Name.Exception:     ('cyan',        'brightcyan'),
    Name.Decorator:     ('brightblack',    'gray'),
    Name.Variable:      ('red',     'brightred'),
    Name.Constant:      ('red',     'brightred'),
    Name.Attribute:     ('cyan',        'brightcyan'),
    Name.Tag:           ('brightblue',        'brightblue'),
    String:             ('yellow',       'yellow'),
    Number:             ('blue',    'brightblue'),

    Generic.Deleted:    ('brightred',        'brightred'),
    Generic.Inserted:   ('green',  'brightgreen'),
    Generic.Heading:    ('**',         '**'),
    Generic.Subheading: ('*magenta*',   '*brightmagenta*'),
    Generic.Error:      ('brightred',        'brightred'),

    Error:              ('_brightred_',      '_brightred_'),
}

IRC_COLOR_MAP = {
    'white': 0,
    'black': 1,
    'blue': 2,
    'brightgreen': 3,
    'brightred': 4,
    'yellow': 5,
    'magenta': 6,
    'orange': 7,
    'green': 7, #compat w/ ansi
    'brightyellow': 8,
    'lightgreen': 9,
    'brightcyan': 9, # compat w/ ansi
    'cyan': 10,
    'lightblue': 11,
    'red': 11, # compat w/ ansi
    'brightblue': 12,
    'brightmagenta': 13,
    'brightblack': 14,
    'gray': 15,
}

def ircformat(color, text):
    if len(color) < 1:
        return text
    add = sub = ''
    if '_' in color: # italic
        add += '\x1D'
        sub = '\x1D' + sub
        color = color.strip('_')
    if '*' in color: # bold
        add += '\x02'
        sub = '\x02' + sub
        color = color.strip('*')
    # underline (\x1F) not supported
    # backgrounds (\x03FF,BB) not supported
    if len(color) > 0: # actual color - may have issues with ircformat("red", "blah")+"10" type stuff
        add += '\x03' + str(IRC_COLOR_MAP[color]).zfill(2)
        sub = '\x03' + sub
    return add + text + sub
    return '<'+add+'>'+text+'</'+sub+'>'

class IRCFormatter(Formatter):
    r"""
    Format tokens with IRC color sequences

    The `get_style_defs()` method doesn't do anything special since there is
    no support for common styles.

    Options accepted:

    `bg`
        Set to ``"light"`` or ``"dark"`` depending on the terminal's background
        (default: ``"light"``).

    `colorscheme`
        A dictionary mapping token types to (lightbg, darkbg) color names or
        ``None`` (default: ``None`` = use builtin colorscheme).

    `linenos`
        Set to ``True`` to have line numbers in the output as well
        (default: ``False`` = no line numbers).
    """
    name = 'IRC'
    aliases = ['irc', 'IRC']
    filenames = []

    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.darkbg = get_choice_opt(options, 'bg',
                                     ['light', 'dark'], 'light') == 'dark'
        self.colorscheme = options.get('colorscheme', None) or IRC_COLORS
        self.linenos = options.get('linenos', False)
        self._lineno = 0

    def _write_lineno(self, outfile):
        self._lineno += 1
        outfile.write("\n%04d: " % self._lineno)

    def _format_unencoded_with_lineno(self, tokensource, outfile):
        self._write_lineno(outfile)

        for ttype, value in tokensource:
            if value.endswith("\n"):
                self._write_lineno(outfile)
                value = value[:-1]
            color = self.colorscheme.get(ttype)
            while color is None:
                ttype = ttype.parent
                color = self.colorscheme.get(ttype)
            if color:
                color = color[self.darkbg]
                spl = value.split('\n')
                for line in spl[:-1]:
                    self._write_lineno(outfile)
                    if line:
                        outfile.write(ircformat(color, line[:-1]))
                if spl[-1]:
                    outfile.write(ircformat(color, spl[-1]))
            else:
                outfile.write(value)

        outfile.write("\n")

    def format_unencoded(self, tokensource, outfile):
        if self.linenos:
            self._format_unencoded_with_lineno(tokensource, outfile)
            return

        for ttype, value in tokensource:
            color = self.colorscheme.get(ttype)
            while color is None:
                ttype = ttype[:-1]
                color = self.colorscheme.get(ttype)
            if color:
                color = color[self.darkbg]
                spl = value.split('\n')
                for line in spl[:-1]:
                    if line:
                        outfile.write(ircformat(color, line))
                    outfile.write('\n')
                if spl[-1]:
                    outfile.write(ircformat(color, spl[-1]))
            else:
                outfile.write(value)


text:
#ifndef IKOS_DOMAIN_CONSTRAINTS_HPP
#define IKOS_DOMAIN_CONSTRAINTS_HPP

#include <ikos/common.hpp>
#include <ikos/bignums.hpp>
#include <ikos/linear_constraints.hpp>
#include <api/extended_constraints.hpp>

/* domains */
#include <ikos/constants.hpp>
#include <ikos/octagons.hpp>

namespace ikos {

  template< typename Number, typename VariableName >
  class domain_constraints {

  public:
    typedef variable< Number, VariableName > variable_t;
    typedef linear_expression< Number, VariableName > linear_expression_t;
    typedef extended_constraint< Number, VariableName > extended_constraint_t;
    typedef extended_constraint_system< Number, VariableName > extended_constraint_system_t;

    typedef constant_domain< Number, VariableName > constant_domain_t;
    typedef interval_domain< Number, VariableName > interval_domain_t;
    typedef octagon< Number, VariableName > octagon_t;

  private:
    extended_constraint_system_t _get_constraints(constant_domain_t& domain) {
      extended_constraint_system_t csts;

      for(typename constant_domain_t::iterator it = domain.begin(); it != domain.end(); ++it) {
        if(it->second.is_number()) {
          csts += extended_constraint_t(variable_t(it->first) - it->second.number().get(), extended_constraint_t::EQ);
        }
      }

      return csts;
    }

    extended_constraint_system_t _get_constraints(interval_domain_t& domain) {
      extended_constraint_system_t csts;

      for(typename interval_domain_t::iterator it = domain.begin(); it != domain.end(); ++it) {
        if(it->second.singleton()) {
          csts += extended_constraint_t(variable_t(it->first) - it->second.singleton().get(), extended_constraint_t::EQ);
        }
        else {
          if(!it->second.lb().is_minus_infinity()) {
            csts += extended_constraint_t(variable_t(it->first) - it->second.lb().number().get(), extended_constraint_t::SUP_EQ);
          }

          if(!it->second.ub().is_plus_infinity()) {
            csts += extended_constraint_t(variable_t(it->first) - it->second.ub().number().get(), extended_constraint_t::INF_EQ);
          }
        }
      }

      return csts;
    }

    extended_constraint_system_t _get_constraints(octagon_t& domain) {
      extended_constraint_system_t csts;
      csts += domain.constraints();
      return csts;
    }

  public:
    template< typename AbstractDomain >
    extended_constraint_system_t get_constraints(AbstractDomain& domain) {
      if(domain.is_bottom()) {
        extended_constraint_system_t csts;

        // constraint (0 != 0)
        csts += extended_constraint_t(linear_expression_t(), extended_constraint_t::NOT_EQ);

        return csts;
      }
      else if(domain.is_top()) {
        return extended_constraint_system_t();
      }
      else {
        return this->_get_constraints(domain);
      }
    }

  };

}

#endif // IKOS_DOMAIN_CONSTRAINTS_HPP

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Doctrine\DBAL\Schema\Synchronizer;

use Doctrine\DBAL\Schema\Schema;

/**
 * The synchronizer knows how to synchronize a schema with the configured
 * database.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
interface SchemaSynchronizer
{
    /**
     * Get the SQL statements that can be executed to create the schema.
     *
     * @param  Schema $createSchema
     * @return array
     */
    public function getCreateSchema(Schema $createSchema);

    /**
     * Get the SQL Statements to update given schema with the underlying db.
     *
     * @param  Schema $toSchema
     * @param  bool   $noDrops
     * @return array
     */
    public function getUpdateSchema(Schema $toSchema, $noDrops = false);

    /**
     * Get the SQL Statements to drop the given schema from underlying db.
     *
     * @param  Schema $dropSchema
     * @return array
     */
    public function getDropSchema(Schema $dropSchema);

    /**
     * Get the SQL statements to drop all schema assets from underlying db.
     *
     * @return array
     */
    public function getDropAllSchema();

    /**
     * Create the Schema
     *
     * @param  Schema $createSchema
     * @return void
     */
    public function createSchema(Schema $createSchema);

    /**
     * Update the Schema to new schema version.
     *
     * @param  Schema $toSchema
     * @param  bool   $noDrops
     * @return void
     */
    public function updateSchema(Schema $toSchema, $noDrops = false);

    /**
     * Drop the given database schema from the underlying db.
     *
     * @param  Schema $dropSchema
     * @return void
     */
    public function dropSchema(Schema $dropSchema);

    /**
     * Drop all assets from the underyling db.
     *
     * @return void
     */
    public function dropAllSchema();
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lab4;

/**
 *
 * @author HP
 */
public abstract class persona {

    protected String nombre;
    protected int ID;
    protected int edad;
    protected int altura;
    protected int peso;
    protected String residencia;

    public persona(String nombre, int ID, int edad, int alura, int peso, String residencia) {
        this.nombre = nombre;
        this.ID = ID;
        this.edad = edad;
        this.altura = alura;
        this.peso = peso;
        this.residencia = residencia;
    }

    public abstract void modificar();

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public int getEdad() {
        return edad;
    }

    public void setEdad(int edad) {
        this.edad = edad;
    }

    public int getAltura() {
        return altura;
    }

    public void setAltura(int altura) {
        this.altura = altura;
    }

    public int getPeso() {
        return peso;
    }

    public void setPeso(int peso) {
        this.peso = peso;
    }

    public String getResidencia() {
        return residencia;
    }

    public void setResidencia(String residencia) {
        this.residencia = residencia;
    }

    @Override
    public String toString() {
        return "persona{" + "nombre=" + nombre + ", ID=" + ID + ", edad=" + edad + ", alura=" + altura + ", peso=" + peso + ", residencia=" + residencia + '}';
    }

}


text:
/**
 *
 */
package com.titanium.assessment.mapper;

import java.sql.Timestamp;
import  com.titanium.assessment.mapper.base.AssessmentUserSearchTermsBase;

/**
 * @author JinMa
 *
 */

public class AssessmentUserSearchTerms extends  AssessmentUserSearchTermsBase{

}


text:
class DeletedDomain < ActiveRecord::Base
  belongs_to :product
  belongs_to :partner

  belongs_to :registrant,       class_name: Contact,  foreign_key: :registrant_handle
  belongs_to :admin_contact,    class_name: Contact,  foreign_key: :admin_handle
  belongs_to :billing_contact,  class_name: Contact,  foreign_key: :billing_handle
  belongs_to :tech_contact,     class_name: Contact,  foreign_key: :tech_handle

  def restore!
    Domain.create product:                    self.product,
                  partner:                    self.partner,
                  name:                       self.name,
                  authcode:                   self.authcode,
                  registrant_handle:          self.registrant_handle,
                  admin_handle:               self.admin_handle,
                  billing_handle:             self.billing_handle,
                  tech_handle:                self.tech_handle,
                  registered_at:              self.registered_at,
                  expires_at:                 self.expires_at,
                  ok:                         self.ok,
                  inactive:                   self.inactive,
                  client_renew_prohibited:    self.client_renew_prohibited,
                  client_delete_prohibited:   self.client_delete_prohibited,
                  client_transfer_prohibited: self.client_transfer_prohibited,
                  client_update_prohibited:   self.client_update_prohibited

    self.delete
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright (C) FuseSource, Inc.
  http://fusesource.com

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:bridge="http://fusesource.org/fabric/bridge" xmlns:zkbridge="http://fusesource.org/fabric/bridge/zookeeper"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://fusesource.org/fabric/bridge http://fusesource.org/fabric/bridge/fabric-bridge.xsd
        http://fusesource.org/fabric/bridge/zookeeper http://fusesource.org/fabric/bridge/zookeeper/fabric-bridge-zookeeper.xsd">

    <bean id="curator" class="io.fabric8.zookeeper.spring.CuratorFactoryBean">
        <property name="timeout" value="30000"/>
        <property name="connectString" value="localhost:2181"/>
    </bean>

  <bean id="fabricservice" class="io.fabric8.service.FabricServiceImpl">
    <property name="curator" ref="curator"/>
  </bean>

  <!-- destinations configured using Fabric -->
  <zkbridge:zkbridge-destinations id="upstream" fabricServiceRef="fabricservice"/>

  <zkbridge:zkbridge-destinations id="downstream" fabricServiceRef="fabricservice"/>

  <!-- Fabric configured bridge, uses Fabric to discover destinations -->
  <zkbridge:zkbridge-connector id="myzkbridge" inboundDestinationsRef="downstream"
                               outboundDestinationsRef="upstream" fabricServiceRef="fabricservice"
                               zooKeeperRef="curator" gatewayProfileName="test-gateway">
    <bridge:local-broker
        brokerUrl="vm://local?broker.persistent=false&broker.brokerName=local&jms.prefetchPolicy.queuePrefetch=10"/>
  </zkbridge:zkbridge-connector>

</beans>


text:
<resources>

    <!--
         Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
    -->
    <dimen name="activity_horizontal_margin">64dp</dimen>
    <style name="CustomActionBarTheme"
        parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="windowActionBarOverlay">true</item>
        <item name="actionBarStyle">@style/MyActionBar</item>
		<item name="android:windowContentOverlay">@null</item>
		<item name="android:windowBackground">@android:color/black</item>
    </style>

    <style name="MyActionBar"
        parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:background">@android:color/transparent</item>
        <item name="background">@android:color/transparent</item>
    </style>
</resources>


text:
package funcmap

import (
	"html/template"
)

func rawHTML(text string) template.HTML {
	return template.HTML(text)
}

func rawHTMLAttr(text string) template.HTMLAttr {
	return template.HTMLAttr(text)
}

func rawCSS(text string) template.CSS {
	return template.CSS(text)
}

func rawJS(text string) template.JS {
	return template.JS(text)
}

func rawJSStr(text string) template.JSStr {
	return template.JSStr(text)
}

func rawURL(text string) template.URL {
	return template.URL(text)
}

// 提供常用的 html/template 函数
// RawFuncMap 为 html/template.FuncMap 类型
// 里面提供了 rawHTML, rawHTMLAttr, rawCSS, rawJS, rawJSStr, rawURL 函数,
// 这些函数可以在模板中应用, 如 {{rawHTML `<br>`}}
var RawFuncMap = template.FuncMap{
	"rawHTML":     rawHTML,
	"rawHTMLAttr": rawHTMLAttr,
	"rawCSS":      rawCSS,
	"rawJS":       rawJS,
	"rawJSStr":    rawJSStr,
	"rawURL":      rawURL,
}


text:
class RanksController < ApplicationController

  before_filter :redirect_home, :only => [:show]
  before_filter :require_admin, :except => [:index]

  def index
    @ranks = Rank.find(:all, :order => 'min_posts asc')
  end

  def new
  end

  def create
    @rank = Rank.new(params[:rank])
    if @rank.save
      redirect_to ranks_path
    else
      render :action => 'new'
    end
  end

  def edit
    @rank = Rank.find(params[:id])
  end

  def update
    @rank = Rank.find(params[:id])
    if @rank.update_attributes(params[:rank])
      redirect_to ranks_path
    else
      render :action => "edit"
    end
  end

  def destroy
    @rank = Rank.find(params[:id])
    @rank.destroy
    redirect_to ranks_path
  end
end


text:
function buffer_SubRule (buf, str) {
	// Common properties
	this.idx = -1
	this.length = 1
	this.next = lastSubRule
	this.prev = null
	// Specific properties
	this.buf = buf
	this.str = str
}

buffer_SubRule.prototype.test = function (buf, offset) {
	var isString = typeof buf === 'string'
	var n = isString ? this.str.length : this.buf.length

	if (buf.length < offset + n) return -1

	var i = buf.indexOf( isString ? this.str : this.buf, offset)

	if (this.length > 0) this.length = n

	return i < 0 ? -1 : this.next.test(buf, i + n)
}


text:
package org.devgateway.ocds.web.rest.controller.request;

import org.devgateway.ocds.web.annotate.LanguageValidation;

/**
 * Created by mpostelnicu on 2/17/17.
 * A paging request that also holds the language param
 */
public class LangYearFilterPagingRequest extends YearFilterPagingRequest {

    @LanguageValidation
    protected String language;

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}


text:
package org.jchlabs.gharonda.guice;

import org.jchlabs.gharonda.domain.pom.dao.ServiceproviderdetailsDAO;

import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class ServiceproviderdetailsDAOProvider implements
		Provider<org.jchlabs.gharonda.domain.pom.dao.iface.ServiceproviderdetailsDAO> {

	public org.jchlabs.gharonda.domain.pom.dao.iface.ServiceproviderdetailsDAO get() {
		return ServiceproviderdetailsDAO.getInstance();
	}

}


text:
'use strict'

/* application modules */
const ImmutableCoreModel = require('../lib/immutable-core-model')
const initTestEnv = require('./helpers/init-test-env')

describe('immutable-core-model - via relation to account table', function () {

    var mysql, redis, reset, session

    // models to create
    var accountModelGlobal, accountModel, roleModelGlobal, roleModel, roleAccountModelGlobal, roleAccountModel

    before(async function () {
        [mysql, redis, reset, session] = await initTestEnv()
        await reset(mysql, redis)
        // create account model
        accountModelGlobal = new ImmutableCoreModel({
            // disable default columns
            columns: {
                accountAccountId: false,
                d: false,
                data: false,
                originalId: false,
                parentId: false,
                sessionId: false,
            },
            mysql: mysql,
            name: 'account',
            redis: redis,
            relations: {
                role: {via: 'roleAccount'},
            },
        })
        // create role model
        roleModelGlobal = new ImmutableCoreModel({
            columns: {
                roleName: {
                    immutable: true,
                    type: 'string',
                    unique: true,
                },
            },
            mysql: mysql,
            name: 'role',
            redis: redis,
        })
        // create role account model
        roleAccountModelGlobal = new ImmutableCoreModel({
            columns: {
                accountId: {
                    index: true,
                    null: false,
                    type: 'id',
                },
                d: false,
                data: false,
                originalId: false,
                parentId: false,
                roleId: {
                    index: true,
                    null: false,
                    type: 'id',
                }
            },
            mysql: mysql,
            name: 'roleAccount',
            redis: redis,
            relations: {
                role: {},
            }
        })
        // sync with mysql
        await accountModelGlobal.sync()
        await roleModelGlobal.sync()
        await roleAccountModelGlobal.sync()
        // get local instances
        accountModel = accountModelGlobal.session(session)
        roleModel = roleModelGlobal.session(session)
        roleAccountModel = roleAccountModelGlobal.session(session)
    })

    after(async function () {
        await mysql.close()
    })

    it('should query models related to account model', async function () {
        // create account
        var account = await accountModel.create({})
        // create related record
        var role = await account.create('role', {foo: 'bar'})
        // query related
        var result = await account.select('role')
        // fetch records
        var records = await result.fetch(1)
        // test related
        assert.isArray(records)
        assert.strictEqual(records.length, 1)
        assert.strictEqual(records[0].id, role.id)
    })

    it('should query models related to account model inverse', async function () {
        // create account
        var account = await accountModel.create({})
        // create related record
        var role = await account.create('role', {foo: 'bar'})
        // query related
        var result = await role.select('account')
        // fetch records
        var records = await result.fetch(1)
        // test related
        assert.isArray(records)
        assert.strictEqual(records.length, 1)
        assert.strictEqual(records[0].id, account.id)
    })

    it('should query account with related model', async function () {
        // create account
        var account = await accountModel.create({})
        // create related record
        var role = await account.create('role', {foo: 'bar'})
        // query related
        var accountWithRole = await accountModel.query({
            limit: 1,
            where: { id: account.id },
            with: { role: true },
        })
        // test related
        assert.isObject(accountWithRole.related)
        assert.isArray(accountWithRole.related.role)
        assert.strictEqual(accountWithRole.related.role.length, 1)
        assert.strictEqual(accountWithRole.related.role[0].id, role.id)
    })

})


text:
/*	$NetBSD: ieee8023ad_impl.h,v 1.2 2005/12/10 23:21:39 elad Exp $	*/

/*-
 * Copyright (c)2005 YAMAMOTO Takashi,
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: soc2013/dpl/head/sys/net/ieee8023ad_lacp.h 177332 2008-03-17 01:26:44Z thompsa $
 */

/*
 * IEEE802.3ad LACP
 *
 * implementation details.
 */

#define	LACP_TIMER_CURRENT_WHILE	0
#define	LACP_TIMER_PERIODIC		1
#define	LACP_TIMER_WAIT_WHILE		2
#define	LACP_NTIMER			3

#define	LACP_TIMER_ARM(port, timer, val) \
	(port)->lp_timer[(timer)] = (val)
#define	LACP_TIMER_DISARM(port, timer) \
	(port)->lp_timer[(timer)] = 0
#define	LACP_TIMER_ISARMED(port, timer) \
	((port)->lp_timer[(timer)] > 0)

/*
 * IEEE802.3ad LACP
 *
 * protocol definitions.
 */

#define	LACP_STATE_ACTIVITY	(1<<0)
#define	LACP_STATE_TIMEOUT	(1<<1)
#define	LACP_STATE_AGGREGATION	(1<<2)
#define	LACP_STATE_SYNC		(1<<3)
#define	LACP_STATE_COLLECTING	(1<<4)
#define	LACP_STATE_DISTRIBUTING	(1<<5)
#define	LACP_STATE_DEFAULTED	(1<<6)
#define	LACP_STATE_EXPIRED	(1<<7)

#define	LACP_PORT_NTT		0x00000001
#define	LACP_PORT_MARK		0x00000002

#define	LACP_STATE_BITS		\
	"\020"			\
	"\001ACTIVITY"		\
	"\002TIMEOUT"		\
	"\003AGGREGATION"	\
	"\004SYNC"		\
	"\005COLLECTING"	\
	"\006DISTRIBUTING"	\
	"\007DEFAULTED"		\
	"\010EXPIRED"

/*
 * IEEE802.3 slow protocols
 *
 * protocol (on-wire) definitions.
 *
 * XXX should be elsewhere.
 */

#define	SLOWPROTOCOLS_SUBTYPE_LACP	1
#define	SLOWPROTOCOLS_SUBTYPE_MARKER	2

struct slowprothdr {
	uint8_t		sph_subtype;
	uint8_t		sph_version;
} __packed;

/*
 * TLV on-wire structure.
 */

struct tlvhdr {
	uint8_t		tlv_type;
	uint8_t		tlv_length;
	/* uint8_t tlv_value[]; */
} __packed;

/*
 * ... and our implementation.
 */

#define	TLV_SET(tlv, type, length) \
	do { \
		(tlv)->tlv_type = (type); \
		(tlv)->tlv_length = sizeof(*tlv) + (length); \
	} while (/*CONSTCOND*/0)

struct tlv_template {
	uint8_t			tmpl_type;
	uint8_t			tmpl_length;
};

struct lacp_systemid {
	uint16_t		lsi_prio;
	uint8_t			lsi_mac[6];
} __packed;

struct lacp_portid {
	uint16_t		lpi_prio;
	uint16_t		lpi_portno;
} __packed;

struct lacp_peerinfo {
	struct lacp_systemid	lip_systemid;
	uint16_t		lip_key;
	struct lacp_portid	lip_portid;
	uint8_t			lip_state;
	uint8_t			lip_resv[3];
} __packed;

struct lacp_collectorinfo {
	uint16_t		lci_maxdelay;
	uint8_t			lci_resv[12];
} __packed;

struct lacpdu {
	struct ether_header	ldu_eh;
	struct slowprothdr	ldu_sph;

	struct tlvhdr		ldu_tlv_actor;
	struct lacp_peerinfo	ldu_actor;
	struct tlvhdr		ldu_tlv_partner;
	struct lacp_peerinfo	ldu_partner;
	struct tlvhdr		ldu_tlv_collector;
	struct lacp_collectorinfo ldu_collector;
	struct tlvhdr		ldu_tlv_term;
	uint8_t			ldu_resv[50];
} __packed;

/*
 * IEEE802.3ad marker protocol
 *
 * protocol (on-wire) definitions.
 */
struct lacp_markerinfo {
	uint16_t		mi_rq_port;
	uint8_t			mi_rq_system[ETHER_ADDR_LEN];
	uint32_t		mi_rq_xid;
	uint8_t			mi_pad[2];
} __packed;

struct markerdu {
	struct ether_header	mdu_eh;
	struct slowprothdr	mdu_sph;

	struct tlvhdr		mdu_tlv;
	struct lacp_markerinfo	mdu_info;
	struct tlvhdr		mdu_tlv_term;
	uint8_t			mdu_resv[90];
} __packed;

#define	MARKER_TYPE_INFO	0x01
#define	MARKER_TYPE_RESPONSE	0x02

enum lacp_selected {
	LACP_UNSELECTED,
	LACP_STANDBY,	/* not used in this implementation */
	LACP_SELECTED,
};

enum lacp_mux_state {
	LACP_MUX_DETACHED,
	LACP_MUX_WAITING,
	LACP_MUX_ATTACHED,
	LACP_MUX_COLLECTING,
	LACP_MUX_DISTRIBUTING,
};

#define	LACP_MAX_PORTS		32

struct lacp_portmap {
	int			pm_count;
	struct lacp_port	*pm_map[LACP_MAX_PORTS];
};

struct lacp_port {
	TAILQ_ENTRY(lacp_port)	lp_dist_q;
	LIST_ENTRY(lacp_port)	lp_next;
	struct lacp_softc	*lp_lsc;
	struct lagg_port	*lp_lagg;
	struct ifnet		*lp_ifp;
	struct lacp_peerinfo	lp_partner;
	struct lacp_peerinfo	lp_actor;
	struct lacp_markerinfo	lp_marker;
#define	lp_state	lp_actor.lip_state
#define	lp_key		lp_actor.lip_key
#define	lp_systemid	lp_actor.lip_systemid
	struct timeval		lp_last_lacpdu;
	int			lp_lacpdu_sent;
	enum lacp_mux_state	lp_mux_state;
	enum lacp_selected	lp_selected;
	int			lp_flags;
	u_int			lp_media; /* XXX redundant */
	int			lp_timer[LACP_NTIMER];
	struct ifmultiaddr	*lp_ifma;

	struct lacp_aggregator	*lp_aggregator;
};

struct lacp_aggregator {
	TAILQ_ENTRY(lacp_aggregator)	la_q;
	int			la_refcnt; /* num of ports which selected us */
	int			la_nports; /* num of distributing ports  */
	TAILQ_HEAD(, lacp_port)	la_ports; /* distributing ports */
	struct lacp_peerinfo	la_partner;
	struct lacp_peerinfo	la_actor;
	int			la_pending; /* number of ports in wait_while */
};

struct lacp_softc {
	struct lagg_softc	*lsc_softc;
	struct mtx		lsc_mtx;
	struct lacp_aggregator	*lsc_active_aggregator;
	TAILQ_HEAD(, lacp_aggregator) lsc_aggregators;
	boolean_t		lsc_suppress_distributing;
	struct callout		lsc_transit_callout;
	struct callout		lsc_callout;
	LIST_HEAD(, lacp_port)	lsc_ports;
	struct lacp_portmap	lsc_pmap[2];
	volatile u_int		lsc_activemap;
	u_int32_t		lsc_hashkey;
};

#define	LACP_TYPE_ACTORINFO	1
#define	LACP_TYPE_PARTNERINFO	2
#define	LACP_TYPE_COLLECTORINFO	3

/* timeout values (in sec) */
#define	LACP_FAST_PERIODIC_TIME		(1)
#define	LACP_SLOW_PERIODIC_TIME		(30)
#define	LACP_SHORT_TIMEOUT_TIME		(3 * LACP_FAST_PERIODIC_TIME)
#define	LACP_LONG_TIMEOUT_TIME		(3 * LACP_SLOW_PERIODIC_TIME)
#define	LACP_CHURN_DETECTION_TIME	(60)
#define	LACP_AGGREGATE_WAIT_TIME	(2)
#define	LACP_TRANSIT_DELAY		3000	/* in msec */

#define	LACP_STATE_EQ(s1, s2, mask)	\
	((((s1) ^ (s2)) & (mask)) == 0)

#define	LACP_SYS_PRI(peer)	(peer).lip_systemid.lsi_prio

#define	LACP_PORT(_lp)	((struct lacp_port *)(_lp)->lp_psc)
#define	LACP_SOFTC(_sc)	((struct lacp_softc *)(_sc)->sc_psc)

#define LACP_LOCK_INIT(_lsc)		mtx_init(&(_lsc)->lsc_mtx, \
					    "lacp mtx", NULL, MTX_DEF)
#define LACP_LOCK_DESTROY(_lsc)		mtx_destroy(&(_lsc)->lsc_mtx)
#define LACP_LOCK(_lsc)			mtx_lock(&(_lsc)->lsc_mtx)
#define LACP_UNLOCK(_lsc)		mtx_unlock(&(_lsc)->lsc_mtx)
#define LACP_LOCK_ASSERT(_lsc)		mtx_assert(&(_lsc)->lsc_mtx, MA_OWNED)

struct mbuf	*lacp_input(struct lagg_port *, struct mbuf *);
struct lagg_port *lacp_select_tx_port(struct lagg_softc *, struct mbuf *);
int		lacp_attach(struct lagg_softc *);
int		lacp_detach(struct lagg_softc *);
void		lacp_init(struct lagg_softc *);
void		lacp_stop(struct lagg_softc *);
int		lacp_port_create(struct lagg_port *);
void		lacp_port_destroy(struct lagg_port *);
void		lacp_linkstate(struct lagg_port *);
void		lacp_req(struct lagg_softc *, caddr_t);
void		lacp_portreq(struct lagg_port *, caddr_t);

static __inline int
lacp_isactive(struct lagg_port *lgp)
{
	struct lacp_port *lp = LACP_PORT(lgp);
	struct lacp_softc *lsc = lp->lp_lsc;
	struct lacp_aggregator *la = lp->lp_aggregator;

	/* This port is joined to the active aggregator */
	if (la != NULL && la == lsc->lsc_active_aggregator)
		return (1);

	return (0);
}

static __inline int
lacp_iscollecting(struct lagg_port *lgp)
{
	struct lacp_port *lp = LACP_PORT(lgp);

	return ((lp->lp_state & LACP_STATE_COLLECTING) != 0);
}

static __inline int
lacp_isdistributing(struct lagg_port *lgp)
{
	struct lacp_port *lp = LACP_PORT(lgp);

	return ((lp->lp_state & LACP_STATE_DISTRIBUTING) != 0);
}

/* following constants don't include terminating NUL */
#define	LACP_MACSTR_MAX		(2*6 + 5)
#define	LACP_SYSTEMPRIOSTR_MAX	(4)
#define	LACP_SYSTEMIDSTR_MAX	(LACP_SYSTEMPRIOSTR_MAX + 1 + LACP_MACSTR_MAX)
#define	LACP_PORTPRIOSTR_MAX	(4)
#define	LACP_PORTNOSTR_MAX	(4)
#define	LACP_PORTIDSTR_MAX	(LACP_PORTPRIOSTR_MAX + 1 + LACP_PORTNOSTR_MAX)
#define	LACP_KEYSTR_MAX		(4)
#define	LACP_PARTNERSTR_MAX	\
	(1 + LACP_SYSTEMIDSTR_MAX + 1 + LACP_KEYSTR_MAX + 1 \
	+ LACP_PORTIDSTR_MAX + 1)
#define	LACP_LAGIDSTR_MAX	\
	(1 + LACP_PARTNERSTR_MAX + 1 + LACP_PARTNERSTR_MAX + 1)
#define	LACP_STATESTR_MAX	(255) /* XXX */


text:
1. Clone this repository (or download the zip code)

1. Install LSL driver for your headset. This will depend on your hardware. Sometimes the manufacturer will provide you with a program. Sometimes you have to check out the code base and recompile from https://github.com/sccn/labstreaminglayer/tree/master/Apps. Then check if you can connect to the stream with LabRecorder (see the troubleshooting section below).

2. Then install the LSL Matlab interface library using the released code from https://github.com/labstreaminglayer/liblsl-Matlab/releases (install the zip release, which contains binary for your Platform). Unzip the file in the **src** folder of the current repository. Make sure the folder is named **liblsl-Matlab** or Neurofeedbacklab will not be able to find it (the path is defined at the end of the nfblab_setfields.m function).

2. Clone EEGLAB with submodules from https://github.com/sccn/eeglab or install the released version

3. Make sure you have the latest version (2.5 or later) of the *clean_rawdata* plugin (use the EEGLAB plugin manager -- menu item *File > Manage extensions*)

4. Install the *Picard* plugin using the EEGLAB plugin manager if you want to perform real-time independent component rejections

5. Install the *ROIconnect* plugin (beta) from https://github.com/arnodelorme/roiconnect if you want to do real-time eLoreta and connectivity analysis.

5. Start Matlab

6. Stats EEGLAB by going to the EEGLAB folder and typing "eeglab"

7. Use *nfblab_check_computation.m* to check Neurofeedbacklab real-time computation against a standard EEGLAB pipeline.

8. Adapt *nfblab_muse.m* for your headset

9. Type *nfblab_process('help', true)* to see Neurofeedbacklab parameters.

The default LSL stream type is set to "EEG" ("lsltype" variable in nfblab_options.m file), and the default LSL name is set to empty ("lslname" variable in nfblab_options.m file), which should work in most case to connect to a LSL EEG stream if it is available on your platform. However, in some cases, you might want to change these variables and also check that the stream is visible on your system.

To identify the name of the LSL stream for your EEG headset using the LabRecorded program (https://github.com/labstreaminglayer/App-LabRecorder/releases). This is the most stable LSL program, and if this program cannot see the LSL stream, there is a problem with the LSL driver you are using. Once you have the stream's name, you can copy it to the nfblab_options.m file (and leave the "lsltype" variable empty).

# Troubleshooting Matlab LSL interface

Note that LSL libraries Neurofeedbacklab uses are from BCILAB, which are themselves compiled from the Lab Streaming Layer repository https://github.com/sccn/labstreaminglayer (and BCILAB versions might have been compiled with earlier versions of the LSL code). If you encounter a problem with connecting Matlab and LSL, you could try the following.

# Connecting to a headset (Mac, PC, or Ubuntu)

1. This example uses the Muse headset, but the process is similar for other headsets. Power on your Muse. This assumes you have a Muse 1 headset (not Muse 2). Use the muse-io command line interface to stream data to lsl (available at https://sites.google.com/a/interaxon.ca/muse-developer-site/download). The command is as follows (with XXXX being the name of your Muse as visible on the Bluetooth preference). For some early Muse 1 you first need to pair by hand using the Bluetooth Mac menu. For late Muse 1 headsets, you do not need to. We tried this under Windows, Mac, and Ubuntu.

muse-io --device Muse-XXXX --lsl-eeg EEG

2. Use LabRecorder to check that you can see the EEG stream (https://github.com/labstreaminglayer/App-LabRecorder) and stream from it. This app is very stable, as mentioned earlier. This will allow you to make sure the LSL steam is visible and functional.

3. Start Matlab and run *nfblab_process('help', true)* to add the LSL paths. Now try to connect using Matlab. Note that the code below will work for any headset and is not limited to the Muse. Type the commands

```Matlab
lib = lsl_loadlib();
result = nfblab_findlslstream(lib,'EEG','')
inlet = lsl_inlet(result{1});
pause(1);
[chunk,stamps] = inlet.pull_chunk();
pause(1);
[chunk,stamps] = inlet.pull_chunk();
figure; plot(chunk');
```

If successful, the variable <i>chunk</i> should contain a chunk of data, and it should show on the command line. Otherwise, it will show [] (which means empty in Matlab) or generate an error. You can also use the function lsl_resolve_byprop to find streams (lsl_resolve_byprop(lib, 'type', 'EEG', 'name', '')).

# Getting started with running Neurofeedback experiments

Run and modify the file [nfblab_run_template.m](https://github.com/arnodelorme/neurofeedbacklab/blob/master/src/nfblab_run_template.m) to get started. Change the number of channels and sampling rate to match your system. Neurofeedbacklab should be able to pick up the LSL stream of type EEG. If it does not, troubleshoot LSL as explained in the previous sections. Change the options as needed to match your Neurofeedback protocol.


text:
class AddDeltaToArticles < ActiveRecord::Migration
  def self.up
    add_column :articles, :delta, :boolean
  end

  def self.down
    remove_column :articles, :delta
  end
end


text:
'use strict';

var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var should = require('should');
var gutil = require('gulp-util');

module.exports = function(git, util){

  it('should add files to the git repo', function(done) {
    var fakeFile = new gutil.File(util.testFiles[0]);
    var gitS = git.add();
    gitS.on('data', function(newFile){
      should.exist(newFile);
      should.exist('test/.git/objects/');
      done();
    });
    gitS.write(fakeFile);
    gitS.end();
  });

  it('should add multiple files to the git repo', function(done) {
    var fakeFiles = [];
    util.testFiles.forEach(function(name){
      fakeFiles.push( new gutil.File(name) );
    });
    var gitS = git.add();
    gitS.on('data', function(newFile){
      should.exist(newFile);
      should.exist('test/.git/objects/');
    });
    fakeFiles.forEach(function(file){
      gitS.write(file);
    });
    gitS.end(done);
  });

  it('should fire an end event', function(done) {
    var fakeFile = new gutil.File(util.testFiles[0]);
    var gitS = git.add();

    gitS.on('end', function() {
      done();
    });

    gitS.write(fakeFile);
    gitS.end();
  });

};


text:
package com.wehelp.wehelp.adapters;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wehelp.wehelp.EventDetailActivity;
import com.wehelp.wehelp.HelpEventActivity;
import com.wehelp.wehelp.R;
import com.wehelp.wehelp.classes.Category;
import com.wehelp.wehelp.classes.Event;
import com.wehelp.wehelp.classes.EventRequirement;
import com.wehelp.wehelp.classes.UserRequirement;
import com.wehelp.wehelp.classes.WeHelpApp;
import com.wehelp.wehelp.controllers.EventController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Created by temp on 9/15/16.
 */
public class TimelineEventAdapter extends ArrayAdapter<Event>{

    private Context context;
    private List<Event> eventList;

    @Inject
    EventController eventController;
    int userId;

    @Inject
    Application application;

    public TimelineEventAdapter(Context context, List<Event> list) {
        super(context, R.layout.row_timeline, list);
        this.context = context;
        this.eventList= list;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        final Event timelineEvent = eventList.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row_timeline, null);
            System.out.println("timeline event: convertView was NULL");
        }

        TextView eventAddress = (TextView)convertView.findViewById(R.id.event_timeline_date);
        TextView eventHour = (TextView)convertView.findViewById(R.id.event_timeline_hour);
        TextView eventCreator = (TextView)convertView.findViewById(R.id.event_timeline_creator);
        TextView eventCategory = (TextView)convertView.findViewById(R.id.event_timeline_category);
        TextView eventTitle = (TextView)convertView.findViewById(R.id.event_timeline_title);
        TextView eventDescription = (TextView)convertView.findViewById(R.id.event_timeline_description);
        TextView eventParticipants = (TextView)convertView.findViewById(R.id.event_timeline_participating);
        Button btnHelp = (Button)convertView.findViewById(R.id.btn_abandon);
        LinearLayout requirementsLayout = (LinearLayout)convertView.findViewById(R.id.event_requirement_layout);
        LinearLayout userRequirementsLayout = (LinearLayout)convertView.findViewById(R.id.event_user_requirements_layout);
        TextView tvHelpWith = (TextView)convertView.findViewById(R.id.tv_helpwith);
        tvHelpWith.setVisibility(View.GONE);
        userRequirementsLayout.setVisibility(View.GONE);

        String address = "Endereço: "+timelineEvent.getCidade()+" / "+timelineEvent.getRua()+" - "+timelineEvent.getNumero()+", "+timelineEvent.getComplemento();
        String hour = "Data: "+new SimpleDateFormat("dd/MM/yyyy / HH:mm").format(timelineEvent.getDataInicio());

        Category category = timelineEvent.getCategoria();

        String categoria = category.getDescricao();
        String title = timelineEvent.getNome();
        String descricao = timelineEvent.getDescricao();
        ArrayList requisitos = timelineEvent.getRequisitos();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_list_item_1, android.R.id.text1);

        requirementsLayout.removeAllViews();
        userRequirementsLayout.removeAllViews();

        TextView tvNeed = (TextView)convertView.findViewById(R.id.txt_need);
        tvNeed.setVisibility(View.GONE);

        if(requisitos.size() > 0) {
            tvNeed.setVisibility(View.VISIBLE);
            for(int i = 0; i< requisitos.size() ; i++) {
                Object objRequisito = requisitos.get(i);
                EventRequirement requisito = (EventRequirement) objRequisito;

                double quantidadeRequisito = requisito.getQuant();

                for(int j = 0; j < requisito.getUsuariosRequisito().size(); j++) {

                    UserRequirement userRequirement = requisito.getUsuariosRequisito().get(j);
                    int userId = ((WeHelpApp)getContext().getApplicationContext()).getUser().getId();
                    int userIdRequisito = userRequirement.getId();
                    if(userId == userIdRequisito){
                        tvHelpWith.setVisibility(View.VISIBLE);
                        userRequirementsLayout.setVisibility(View.VISIBLE);
                        String requisitoUserString;
                        if(userRequirement.getUn().equalsIgnoreCase("")) {
                            requisitoUserString = userRequirement.getQuant()+" "+requisito.getDescricao();
                        } else {
                            requisitoUserString = userRequirement.getQuant()+" "+userRequirement.getUn()+" de "+requisito.getDescricao();
                        }

                        TextView requirementUserTxt = new TextView(getContext());
                        requirementUserTxt.setTextColor(context.getResources().getColor(R.color.colorAccent));
                        requirementUserTxt.setTextSize(14);
                        requirementUserTxt.setPadding(5, 0, 0 ,0);
                        requirementUserTxt.setText(requisitoUserString);
                        userRequirementsLayout.addView(requirementUserTxt);
                    }
                    System.out.println("USER ID: "+((WeHelpApp)getContext().getApplicationContext()).getUser().getId());

                    quantidadeRequisito -= userRequirement.getQuant();
                }

                String requisitoString;

                if(requisito.getUn().equalsIgnoreCase("")) {
                    requisitoString = requisito.getQuant()+" "+requisito.getDescricao();
                } else {
                    requisitoString = requisito.getQuant()+" "+requisito.getUn()+" de "+requisito.getDescricao();
                }

                TextView requirementTxt = new TextView(getContext());

                if(quantidadeRequisito <= 0) {
                    requirementTxt.setText(requisitoString +" - Quantidade atingida!");
                    requirementTxt.setTextColor(context.getResources().getColor(R.color.checkedRequirement));
                } else {
                    requirementTxt.setText(requisitoString +" (ainda faltam "+quantidadeRequisito+")");
                    requirementTxt.setTextColor(context.getResources().getColor(R.color.colorAccent));
                }

                requirementTxt.setTextSize(14);
                requirementTxt.setPadding(0, 0, 0 ,0);
                requirementsLayout.addView(requirementTxt);
            }

        } else {
            tvNeed.setVisibility(View.GONE);
            tvHelpWith.setVisibility(View.GONE);
            userRequirementsLayout.setVisibility(View.GONE);
            requirementsLayout.setVisibility(View.GONE);
        }

        btnHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentHelp = new Intent(getContext(), HelpEventActivity.class);

                Bundle mBundle = new Bundle();
                mBundle.putSerializable("event", timelineEvent);
                intentHelp.putExtras(mBundle);

                context.startActivity(intentHelp);
            }
        });

        eventTitle.setText(title);
        eventCategory.setText(categoria);
        eventAddress.setText(address);
        eventHour.setText(hour);
        eventCreator.setText("CRIADOR");
        eventDescription.setText(timelineEvent.getDescricao());
        if(timelineEvent.getNumeroParticipantes() > 0) {
            eventParticipants.setText(timelineEvent.getNumeroParticipantes()+" pessoas irão participar deste evento.");
        }
        if(timelineEvent.getNumeroParticipantes() == 1) {
            eventParticipants.setText(timelineEvent.getNumeroParticipantes()+" pessoa irá participar deste evento.");
        }
        if(timelineEvent.getNumeroParticipantes() == 0){
            eventParticipants.setText("Não há nenhuma pessoa participando no momento. Seja a primeira!");
        }

        return convertView;
    }
}


text:
If you're used to writing server side scripts, and have little experience writing mobile HTML apps, then this guide is absolutely for you. And if you think you're an expert on node.js or mobile HTML apps, you should also read this guide carefully, too many 'experts' were restricted to their old experiences and failed to be aware of new possibilities.

## Express?

If you searched `write desktop apps in node.js` and found node-webkit, the first thing you may do is trying to figure out how to make `Express` or other node web frameworks work, and I've get questions like this far too many times.

The answer is, you can still use `Express` in the same way you use with Node.js (create a HTTP server, etc), but that's not the way in which you can fully unleash the power of node-webkit.

### Router

People who want `Express` are indeed finding two things: `router` and `template engine`.

As for `router`, it is used for showing different pages for different urls, like `/user/zcbenz` and `/article/901127`. You don't need a `router` in node-webkit, because you already have a better one: the `file:` protocol. For example, if you have an app like this:

```
app
├── index.html
└── views
    ├── user.html
    └── article.html
```

Then you you can navigate to a page by using `window.location = 'views/user.html#zcbenz'` and handle logics in `views/user.html` file.

However the recommended way is not opening a new window or changing the `window.location`, you should just replace part of your page with ajax, like `$('#main').load('views/user.html#zcbenz');`. Doing it this way users won't have bad experience of having the page refresh/flicker, and the current javascript context is also kept.

### Template Engine

For template engine, node.js developers have always been comfortable with rendering at server side and then sending the result to clients. In node-webkit everything is client side, you don't need to render the template and then feed it to node-webkit, you could just render everything after the page is loaded.

The basic idea is: use the template engine to generate contents on the fly, and then append dynamic contents into the DOM. like this:

```html
<script>
var jade = require('jade');
var gen_files_view = jade.compile([
    '- each file in files',
    '  .file(data-path="#{file.path}")',
    '    .icon',
    '      img(src="icons/#{file.type}.png")',
    '    .name #{file.name}',
].join('\n'));

$(document).ready(function() {
  // read sth to files
  // blabla...
  $('#content').html(gen_files_view({ files: files }));
});
</script>
```

Another example is how I refresh the address bar and folder view in [zcbenz/nw-file-explorer](https://github.com/zcbenz/nw-sample-apps/tree/master/file-explorer), see [node_modules/folder_view.js](https://github.com/zcbenz/nw-sample-apps/blob/master/file-explorer/node_modules/folder_view.js) and [node_modules/address_bar.js](https://github.com/zcbenz/nw-sample-apps/blob/master/file-explorer/node_modules/address_bar.js).

### Why not the router way?

One of the founding nature of node-webkit is that you can call any Node modules you want from DOM **directly**. 'directly' means the Javascript objects of Node and DOM reside in the same V8 heap. So variables references are made directly like a pointer, and function calls don't need to come across any kind of JSON marshalling/unmarshalling bridge between processes, or even threads.

Some may find their code in B/S architecture can be easily reused by launching a http server in node-webkit, but refactoring your code a little bit and making DOM calls to Node directly would give you a brand new way of writing applications, with benefits to both performance and architecture.

## CoffeeScript, LESS and more

Developers who code in node.js would also want languages that compile into javascript and CSS, the most famous ones are `CoffeeScript` and `LESS`. Usually people would compile the code on the server side and then send results to clients' browsers, but instead you can use them directly on the browser side, by installing the compiler first and then evaluate the code on the fly.

For `CoffeScript`, you should first tag your coffeescript with the type `text/coffeescript`, and then include [coffee-script.js](http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js) after all coffeescript is available on the page (this is the compiler that will evaluate and compile all coffeescript in order). Here is an example:

```html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/coffeescript">
 $ -> $('#header').css 'background-color', 'green'
</script>
<script type="text/javascript" src="http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js"></script>
</head>
<body>
<h1 id="header" style="color:white">CoffeeScript is alive!</h1>
</body>
</html>
```

You can also load `CoffeeScript` files using the `require` function from Node. In order to do so, you must first locally install the `coffee-script` module in your project directory (`npm install coffee-script`). After that, all you need to do is just require the `coffee-script/register` module, which registers `.coffee` extension. Example:

index.html
```html
<!DOCTYPE html>
<html>
 <head>
  <script>
   require('coffee-script/register');  // for versions < 1.7.0, use: require('coffee-script');
   require('./app.coffee');
  </script>
 </head>
 <body>
 </body>
</html>
```

app.coffee
```coffeescript
window.alert 'Hello!'
```

For `LESS`, it also has an online compiler that translates your `.less` file into `.css` file in browser, to use it, just add following lines in `<head>` tag:

```html
<link rel="stylesheet/less" href="/link/to/your.less" type="text/css" />
<script src="http://lesscss.googlecode.com/files/less-1.3.0.min.js"></script>
```

And of course you can always choose to compile the code before packing your app, and only deliver the complied files to end users.

## Page navigation and multiple windows

If you have written server side scripts, you would be familiar with navigating user to different pages when they click a link, and save users' session information in `cookies` or in server.

In node-webkit, you can basically do the same thing by using `window.location`, you can install it in the `onclick` event of a link and node-webkit will navigate to a new page when user clicks it. But by doing this you would lose everything in `window` context, you can save everything in cookies like old web pages, or you can save things in the `global` variable, which resides in Node.js's context and will live through your app.

But a better way is just refreshing part of your pages, not navigating to a new one, you can search for `ajax` to get basic ideas.

The `global` variable is also useful for apps that have multiple windows. Every opened window will share a same `global`, so you can use it to transfer messages across different windows. And the normal HTML way of using the return value of `window.open` is also available, for more you can have a look at [[Play with window]].


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2016 ResiliNets, ITTC, University of Kansas
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Truc Anh N. Nguyen <annguyen@ittc.ku.edu>
 *          Keerthi Ganta <keerthig@ittc.ku.edu>
 *          Md Moshfequr Rahman <moshfequr@ittc.ku.edu>
 *          Amir Modarresi <amodarresi@ittc.ku.edu>
 *
 * James P.G. Sterbenz <jpgs@ittc.ku.edu>, director
 * ResiliNets Research Group  http://wiki.ittc.ku.edu/resilinets
 * Information and Telecommunication Technology Center (ITTC)
 * and Department of Electrical Engineering and Computer Science
 * The University of Kansas Lawrence, KS USA.
 */

#ifndef TCPSCALABLE_H
#define TCPSCALABLE_H

#include "ns3/tcp-congestion-ops.h"

namespace ns3 {

/**
 * \ingroup congestionOps
 *
 * \brief An implementation of TCP Scalable
 *
 * Scalable improves TCP performance to better utilize the available bandwidth
 * of a highspeed wide area network by altering NewReno congestion window
 * adjustment algorithm.
 *
 * When congestion has not been detected, for each ACK received in an RTT,
 * Scalable increases its cwnd per:
 *
 *         cwnd = cwnd + 0.01                  (1)
 *
 * Following Linux implementation of Scalable, we use 50 instead of 100 to
 * account for delayed ACK.
 *
 * On the first detection of congestion in a given RTT, cwnd is reduced based
 * on the following equation:
 *
 *         cwnd = cwnd - ceil(0.125 * cwnd)       (2)
 *
 * More information: http://doi.acm.org/10.1145/956981.956989
 */

class TcpScalable : public TcpNewReno
{
public:
  /**
   * \brief Get the type ID.
   * \return the object TypeId
   */
  static TypeId GetTypeId (void);

  /**
   * Create an unbound tcp socket.
   */
  TcpScalable (void);

  /**
   * \brief Copy constructor
   * \param sock the object to copy
   */
  TcpScalable (const TcpScalable& sock);
  virtual ~TcpScalable (void);

  virtual std::string GetName () const;

  /**
   * \brief Get slow start threshold following Scalable principle (Equation 2)
   *
   * \param tcb internal congestion state
   * \param bytesInFlight bytes in flight
   *
   * \return the slow start threshold value
   */
  virtual uint32_t GetSsThresh (Ptr<const TcpSocketState> tcb,
                                uint32_t bytesInFlight);

  virtual Ptr<TcpCongestionOps> Fork ();

protected:
  /**
   * \brief Congestion avoidance of TcpScalable (Equation 1)
   *
   * \param tcb internal congestion state
   * \param segmentsAcked count of segments acked
   */
  virtual void CongestionAvoidance (Ptr<TcpSocketState> tcb,
                                    uint32_t segmentsAcked);

private:
  uint32_t m_ackCnt;               //!< Number of received ACK
  uint32_t m_aiFactor;             //!< Additive increase factor
  double m_mdFactor;               //!< Multiplicative decrease factor
};

} // namespace ns3

#endif // TCPSCALABLE_H


text:
import GraphicObject from './GraphicObject.js';

/* *********************************************************************************************** *
 * Circle
 * =============================================================================================== *
 * REQUIRE: GraphicObject
 * *********************************************************************************************** */
export default Circle;

function Circle(settings) {
	settings = settings || {};
	this.radius = settings.radius || 10;

	GraphicObject.call(this, settings);
}

//--------------------------------------------------------------------------------------------------

Circle.prototype = Object.create(GraphicObject.prototype);

//--------------------------------------------------------------------------------------------------

Circle.prototype.constructor = Circle;

//--------------------------------------------------------------------------------------------------

Circle.prototype.shaped = function(sprite) {
	this.sprite = sprite || this.sprite;
	this.sprite.beginPath();
	this.sprite.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
	this.sprite.closePath();
};


text:
import React from 'react';
import { View } from 'react-native';

import CardImageHeader from '../../common/card-image-header/cardImageHeader';
import SimpleCardBody from '../../common/simple-card-body/simpleCardBody';
import { imageProp } from '../../../resources/propTypes';

const PreviewHeaderView = ({ title, cover, icon, subtitle }) =>
  <View>
    <CardImageHeader
      cover={cover}
      icon={icon}
    />
    <SimpleCardBody
      title={title}
      subtitle={subtitle}
    />
  </View>;

PreviewHeaderView.propTypes = {
  title: React.PropTypes.string.isRequired,
  cover: imageProp.isRequired,
  icon: imageProp.isRequired,
  subtitle: React.PropTypes.string.isRequired,
};

export default PreviewHeaderView;


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Sticks</title>
  <link href='http://fonts.googleapis.com/css?family=Raleway:400,300,600' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.1/skeleton.min.css">

200 DOM elements


text: View on jsbin.com


text:
echo $<ref>VAR

. "included.bash"


text:
using Glav.CognitiveServices.FluentApi.ComputerVision.Domain;
using Glav.CognitiveServices.FluentApi.Core.Configuration;

namespace Glav.CognitiveServices.FluentApi.ComputerVision.Configuration
{
    public class ReadImageAnalysisServiceConfig : ApiServiceUriFragment
    {
        public ReadImageAnalysisServiceConfig(string apiVersionIdentifier) : base(apiVersionIdentifier) { }
        public override string Template => "vision/{0}/read/analyze";

        public override ApiActionDefinition ApiAction => ComputerVisionApiOperations.ReadImage;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap Template</title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">

    <form class="form-horizontal" role="form">

            聚焦

                <input class="form-control" id="focusedInput" type="text" value="该输入框获得焦点...">

                禁用

                <input class="form-control" id="disabledInput" type="text" placeholder="该输入框禁止输入..." disabled>

        <fieldset disabled>

                    禁用输入(Fieldset disabled)

                    <input type="text" id="disabledTextInput" class="form-control" placeholder="禁止输入">

                    禁用选择菜单(Fieldset disabled)

                    <select id="disabledSelect" class="form-control">
                        <option>禁止选择</option>
                    </select>

        </fieldset>

                输入成功

                <input type="text" class="form-control" id="inputSuccess">

                输入警告

                <input type="text" class="form-control" id="inputWarning">

                输入错误

                <input type="text" class="form-control" id="inputError">

    </form>


text:
package uk.ac.ebi.eva.commons.core.models;

/**
 * Base implementation of {@link IFeatureCoordinates}
 */
public class FeatureCoordinates implements IFeatureCoordinates {

    private String id;

    private String name;

    private String feature;

    private String chromosome;

    private int start;

    private int end;

    FeatureCoordinates() {
        this(null,null,null,null,-1,-1);
    }

    public FeatureCoordinates(IFeatureCoordinates featureCoordinates) {
        this(
                featureCoordinates.getId(),
                featureCoordinates.getName(),
                featureCoordinates.getFeature(),
                featureCoordinates.getChromosome(),
                featureCoordinates.getStart(),
                featureCoordinates.getEnd()
        );
    }

    public FeatureCoordinates(String id, String name, String feature, String chromosome, int start, int end) {
        this.id = id;
        this.name = name;
        this.feature = feature;
        this.chromosome = chromosome;
        this.start = start;
        this.end = end;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getFeature() {
        return feature;
    }

    @Override
    public String getChromosome() {
        return chromosome;
    }

    @Override
    public int getStart() {
        return start;
    }

    @Override
    public int getEnd() {
        return end;
    }
}


text:
  <pnc-header>
    <pnc-header-title>{{ detailCtrl.product.name || 'Empty' }}</pnc-header-title>
    <pnc-header-buttons>

      <button type="button" class="btn btn-lg btn-default" data-toggle="tooltip" title="Edit Product" ng-click="productForm.$show()" ng-class="{ 'active': productForm.$visible }"> Edit
      </button>
      <button ng-hide="true" type="button" class="btn btn-lg btn-danger disabled" data-toggle="tooltip" title="Delete Product">
         Delete
      </button>
    </pnc-header-buttons>
  </pnc-header>

  <form editable-form class="form-horizontal" name="productForm" onbeforesave="detailCtrl.update()" novalidate>

      Name

{{ detailCtrl.product.name || 'Empty' }}

        Required field.

      Description

{{ detailCtrl.product.description }}

      Short Name

{{ detailCtrl.product.abbreviation }}

      Product Code

{{ detailCtrl.product.productCode }}

      System Code

{{ detailCtrl.product.pgmSystemName }}

        <button type="submit" class="btn btn-primary" ng-disabled="productForm.$waiting || productForm.name.$invalid">
          Save
        </button>
        <button type="button" class="btn btn-default" ng-disabled="productForm.$waiting" ng-click="productForm.$cancel()">
          Cancel
        </button>

  </form>

  <pnc-header>
    <pnc-header-title>Product Versions</pnc-header-title>
    <pnc-header-buttons>
      <button type="button" class="btn btn-lg btn-default" data-toggle="tooltip" title="Create Product Version" ui-sref="product.detail.createVersion({ productId: detailCtrl.product.id })">
           Create
      </button>
    </pnc-header-buttons>
  </pnc-header>

  <pnc-product-versions product-id="detailCtrl.product.id"></pnc-product-versions>


text:
release_file="/etc/*-release"
pip_install_script_url="https://bootstrap.pypa.io/get-pip.py"
pip_install_script="get-pip.py"
is_redhat=0
is_amazon=0

grep "Red Hat" $release_file
if [[ "$?" -eq 0 ]]; then
  is_redhat=1
fi

if [[ "$is_redhat" -eq 0 ]]; then
  grep "Amazon Linux" $release_file
  if [[ "$?" -eq 0 ]]; then
    is_amazon=1
  fi
fi

if [[ "$is_redhat" -eq "1" ]]; then
  curl -O $pip_install_script_url
  sudo python $pip_install_script
  sudo pip install awscli
  curl -O http://s3.amazonaws.com/ec2metadata/ec2-metadata
  chmod u+x ec2-metadata
  sudo mkdir -p /opt/aws/bin/
  sudo mv ec2-metadata /opt/aws/bin/
elif [[ "$is_amazon" -eq "1" ]]; then
  sudo pip install --upgrade pip
  sudo yum -y install python-pip
else
  echo "Only tested with Amazon Linux and RHEL... exiting..."
  exit -1
fi

fields=2
SPACE=" "

#get the instance ID
instance_id=$(/opt/aws/bin/ec2-metadata --instance-id | cut --fields=$fields -d "$SPACE")

metadata_url="http://169.254.169.254/latest/dynamic/instance-identity/document"
delimeter="\""

#get the region
region=$(curl -s $metadata_url | grep region | awk -F$delimeter '{print $4}')

# get the tags
tag_value=$(aws --region $region ec2 describe-tags --filters "Name=resource-id,Values=$instance_id" --output=text)

# get the Name: value
if [[ "$is_redhat" -eq "1" ]]; then
  fields=5
  tag_value=$(echo $tag_value | cut --fields=$fields -d "$SPACE")
else
  tag_value=$(grep -Po 'Name \K\S+' <<< $tag_value)
fi


text:
package com.amazonaws.services.networkmanager.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.networkmanager.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * PeeringMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class PeeringMarshaller {

    private static final MarshallingInfo<String> CORENETWORKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CoreNetworkId").build();
    private static final MarshallingInfo<String> CORENETWORKARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CoreNetworkArn").build();
    private static final MarshallingInfo<String> PEERINGID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("PeeringId").build();
    private static final MarshallingInfo<String> OWNERACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OwnerAccountId").build();
    private static final MarshallingInfo<String> PEERINGTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PeeringType").build();
    private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("State").build();
    private static final MarshallingInfo<String> EDGELOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EdgeLocation").build();
    private static final MarshallingInfo<String> RESOURCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceArn").build();
    private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Tags").build();
    private static final MarshallingInfo<java.util.Date> CREATEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreatedAt").timestampFormat("unixTimestamp").build();

    private static final PeeringMarshaller instance = new PeeringMarshaller();

    public static PeeringMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Peering peering, ProtocolMarshaller protocolMarshaller) {

        if (peering == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(peering.getCoreNetworkId(), CORENETWORKID_BINDING);
            protocolMarshaller.marshall(peering.getCoreNetworkArn(), CORENETWORKARN_BINDING);
            protocolMarshaller.marshall(peering.getPeeringId(), PEERINGID_BINDING);
            protocolMarshaller.marshall(peering.getOwnerAccountId(), OWNERACCOUNTID_BINDING);
            protocolMarshaller.marshall(peering.getPeeringType(), PEERINGTYPE_BINDING);
            protocolMarshaller.marshall(peering.getState(), STATE_BINDING);
            protocolMarshaller.marshall(peering.getEdgeLocation(), EDGELOCATION_BINDING);
            protocolMarshaller.marshall(peering.getResourceArn(), RESOURCEARN_BINDING);
            protocolMarshaller.marshall(peering.getTags(), TAGS_BINDING);
            protocolMarshaller.marshall(peering.getCreatedAt(), CREATEDAT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
#ifndef USER_MODULE_H
#define USER_MODULE_H

#include "Module.h"

class Queue;
/**
 *  The UserModule
 *
 */
class UserModule: public Module
{
   public:

      /**
        *  Initializes the Module
        *  @param argc  Number of command line arguments
        *  @param argv  Array with the command line arguments
        *  @param noUserCache If not to use user caching.
        *  @param noSqlUpdate If not to update sql tables.
        */
      UserModule( int argc, char* argv[] );

      /**
        *  Cleans up
        */
      virtual ~UserModule();

      /**
        *  The module's initialization function
        */
      virtual void init();

      /**
        *  Handle a command from the user
        *  @param cmd Pointer to string with the command
        *  @return Integer reporting what happened; 0: error ocurred
        *          1: everything ok, -1: quit now
        */
      int handleCommand(const char* input);

   private:

      bool addUsers(const char* fileName, Queue *queue, bool allok);

      /// User add filename
      char m_userAddFilename[4096];

      /// flag to add users only if all users OK to add
      bool m_onlyUsersAllOK;

      /// If not to use user cache.
      bool m_noUserCache;

      /// If not to update sql tables.
      bool m_noSqlUpdate;
};

#endif // USER_MODULE_H


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tap_1 = require("./tap");
var EmptyError_1 = require("../util/EmptyError");
/**
 * If the source observable completes without emitting a value, it will emit
 * an error. The error will be created at that time by the optional
 * `errorFactory` argument, otherwise, the error will be {@link ErrorEmpty}.
 *
 * @example
 *
 * const click$ = fromEvent(button, 'click');
 *
 * clicks$.pipe(
 *   takeUntil(timer(1000)),
 *   throwIfEmpty(
 *     () => new Error('the button was not clicked within 1 second')
 *   ),
 * )
 * .subscribe({
 *   next() { console.log('The button was clicked'); },
 *   error(err) { console.error(err); },
 * });
 * @param {Function} [errorFactory] A factory function called to produce the
 * error to be thrown when the source observable completes without emitting a
 * value.
 */
exports.throwIfEmpty = function (errorFactory) {
    if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
    return tap_1.tap({
        hasValue: false,
        next: function () { this.hasValue = true; },
        complete: function () {
            if (!this.hasValue) {
                throw errorFactory();
            }
        }
    });
};
function defaultErrorFactory() {
    return new EmptyError_1.EmptyError();
}
//# sourceMappingURL=throwIfEmpty.js.map


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using System;

namespace SchoolBusClient.Handlers
{
    public static class ProxyServerOptionsExtensions
    {
        public static Uri ToUri(this ProxyServerOptions options)
        {
            int portNumber = 80;
            int.TryParse(options.Port, out portNumber);
            UriBuilder uriBuilder = new UriBuilder(options.Scheme, options.Host, portNumber);
            return uriBuilder.Uri;
        }

        public static IOptions<ProxyOptions> ToProxyOptions(this ProxyServerOptions options)
        {
            ProxyOptions proxyOptions = new ProxyOptions()
            {
                Host = options.Host,
                Port = options.Port,
                Scheme = options.Scheme
            };

            return Options.Create(proxyOptions);
        }
    }
}


text:
title: Cheating and Codecademy 2
layout: post
author: harry.keyland
permalink: /cheating-and-codecademy-/
source-id: 1C1hEci9whFjXhPjh6hRuYoJMO41v2sLlDO0Ohv7nWnM
published: true
---
**Cheating and Codecademy 2**

In the lesson we carried on with codecademy and we carried going through the lessons on codecademy and someone in our class got caught telling a friend the correct bit of code. We got taught a lesson about this which was that you should never tell people the answer. This is because is doesn't help them learn because the point of learning is not to get the answer right but the process of getting to the answer. So if you tell someone the answer then they don't have to work it out themselves which means they miss out on a piece of learning. This is a bad thing because if they have a test on it they won't know how to do it.


text:
package org.opensingular.form.validation.validator;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opensingular.form.SDictionary;
import org.opensingular.form.SInstance;
import org.opensingular.form.type.core.SIString;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.validation.InstanceValidatable;
import org.opensingular.form.validation.ValidationError;
import org.opensingular.form.validation.ValidationErrorLevel;

public class StringValidatorsTest {

    InstanceValidatableMock<SIString> instanceValidatableMock;
    SIString siString;

    @Before
    public void setUp() throws Exception {
        siString = SDictionary.create().newInstance(STypeString.class);
        instanceValidatableMock = new InstanceValidatableMock<>(siString);
    }

    @Test
    public void matches() throws Exception {
        siString.setValue("danilo");
        StringValidators.matches("[a-z]+", "").validate(instanceValidatableMock);
        Assert.assertFalse(instanceValidatableMock.containsErrors);
    }

    @Test
    public void doestNotMatches() throws Exception {
        siString.setValue("danilo");
        StringValidators.matches("\\d", "").validate(instanceValidatableMock);
        Assert.assertTrue(instanceValidatableMock.containsErrors);
    }

    @Test
    public void endsWith() throws Exception {
        siString.setValue("danilo");
        StringValidators.endsWith("ilo", "").validate(instanceValidatableMock);
        Assert.assertFalse(instanceValidatableMock.containsErrors);
    }

    @Test
    public void doestNotEndsWith() throws Exception {
        siString.setValue("danilo");
        StringValidators.endsWith("bajara", "").validate(instanceValidatableMock);
        Assert.assertTrue(instanceValidatableMock.containsErrors);
    }

    @Test
    public void isNotBlank() throws Exception {
        siString.setValue("danilo");
        StringValidators.isNotBlank("").validate(instanceValidatableMock);
        Assert.assertFalse(instanceValidatableMock.containsErrors);
    }

    @Test
    public void isBlank() throws Exception {
        siString.setValue("    ");
        StringValidators.isNotBlank("").validate(instanceValidatableMock);
        Assert.assertTrue(instanceValidatableMock.containsErrors);
    }

    static class InstanceValidatableMock<I extends SInstance> implements InstanceValidatable<I> {

        final I instance;
        boolean containsErrors = false;

        InstanceValidatableMock(I instance) {
            this.instance = instance;
        }

        @Override
        public I getInstance() {
            return instance;
        }

        @Override
        public InstanceValidatable<I> setDefaultLevel(ValidationErrorLevel level) {
            return this;
        }

        @Override
        public ValidationErrorLevel getDefaultLevel() {
            return null;
        }

        @Override
        public ValidationError error(ValidationError error) {
            containsErrors = true;
            return null;
        }

        @Override
        public ValidationError error(String msg) {
            containsErrors = true;
            return null;
        }

        @Override
        public ValidationError error(ValidationErrorLevel level, ValidationError error) {
            containsErrors = true;
            return null;
        }

        @Override
        public ValidationError error(ValidationErrorLevel level, String msg) {
            containsErrors = true;
            return null;
        }
    }

}


text:
package nut

import "github.com/gin-gonic/gin"

func (p *AdminPlugin) indexLeaveWords(l string, c *gin.Context) (interface{}, error) {
	var items []LeaveWord
	err := p.DB.Model(&items).
		Order("created_at DESC").Select()
	return items, err
}
func (p *AdminPlugin) destroyLeaveWord(l string, c *gin.Context) (interface{}, error) {
	_, err := p.DB.Model(&LeaveWord{}).Where("id = ?", c.Param("id")).Delete()
	return gin.H{}, err
}


text:
var map;

// Create object to define tile provider settings and transformations. Supports
// all Leaflet TileLayer options.
var projectedTiles = {
  "EPSG:3571 Bering Sea": L.PolarMap.layer3571,
  "EPSG:3572 Alaska"    : L.PolarMap.layer3572,
  "EPSG:3573 Canada"    : L.PolarMap.layer3573,
  "EPSG:3574 Atlantic"  : L.PolarMap.layer3574,
  "EPSG:3575 Europe"    : L.PolarMap.layer3575,
  "EPSG:3576 Russia"    : L.PolarMap.layer3576
};

// Set up next/prev linked list
$.each(projectedTiles, function (layerName, layer) {
  var keys = Object.keys(projectedTiles);
  var index = keys.indexOf(layerName);
  var prev = (index === 0) ? keys.length - 1 : index - 1;
  var next = (index === keys.length - 1) ? 0 : index + 1;

  layer.prev = projectedTiles[keys[prev]];
  layer.next = projectedTiles[keys[next]];
});

// Initialization
$(document).ready(function() {
  Autosize.enable();

  // Load PolarMap
  var defaultLayer = projectedTiles["EPSG:3571 Bering Sea"];
  map = L.PolarMap.map('xmap', {
    baseLayer: defaultLayer,
    center: defaultLayer.options.center,
    zoom: defaultLayer.options.zoom
  });

  // Add a Leaflet layer group. Assumed to be EPSG:3857.
  L.layerGroup([
    L.marker([51.080126, -114.13380900]).bindPopup("University of Calgary"),
    L.marker([90, 100]).bindPopup("North Pole")
  ]).addTo(map);

  var layersControl = L.control.layers(projectedTiles, null);
  layersControl.addTo(map);

  // Wire up rotation controls
  var getBaseLayer = function() {
    var foundLayer = null;
    $.each(projectedTiles, function (layerName, layer) {
      if (map.hasLayer(layer)) {
        foundLayer = layer;
      }
    });
    return foundLayer;
  };

  var rotationControls = L.PolarMap.Control.rotation({
    onRotateCW: function() {
      map.loadTileProjection(getBaseLayer().next);
    },

    onRotateCCW: function() {
      map.loadTileProjection(getBaseLayer().prev);
    }
  });
  rotationControls.addTo(map);
});


text:
#ifndef _MOVE_H
#define _MOVE_H

#include "global.h"

/**********************************************************/

/* Struct to store Move and color of the player */
typedef struct
{
	char tile[ 2 ][ MAXIMUM_MOVE_SIZE ];	// ( BOARD_SIZE - 1 ) / 2 is the maximum number of jumps of a BOARD_SIZE * BOARD_SIZE board
	char color;
} Move;
/**********************************************************/

/*
Caution!

tile[0][0] and tile[1][0] holds the row and col of the piece we want to move!
All the other coordinates are the tiles that this piece will go to.

for a move to be valid the tile[0][i+1] (where tile[0][i] holds the row of the last tile of our move) must be -1.
Only exception to this is when we have to use all (( BOARD_SIZE - 1 ) / 2 + 1) tiles.

A Null move (the only legal move when we cannot move) has tile[0][0] = -1.

Server can ask for a move even we have none available.

*/

#endif


text:
    <title>Range Filter with datepicker (jQuery UI)</title>

 To). It is not required to specify the two values." data-step="6">
                    _#= Srch.U.collapsibleRefinerTitle(ctx.RefinementControl.propertyName, ctx.ClientControl.get_id(), refinerCatTitle, iconClass) =#_

                        From
                        <input type='text' id='_#= fromInput =#_' name='from' value='_#= from =#_' />
                        To
                        <input type='text' id='_#= toInput =#_' name='to' value='_#= to =#_' />
                        Refine
                        Clear


text:
package org.apache.activemq.artemis.tests.integration.stomp.util;

public class ClientStompFrameV12 extends ClientStompFrameV11 {

   public ClientStompFrameV12(String command) {
      this(command, true, true);
   }

   public ClientStompFrameV12(String command, boolean newEol, boolean validate) {
      super(command, validate);
      /**
       * Stomp 1.2 frames allow a carriage return (octet 13) to optionally
       * precedes the required line feed (octet 10) as their internal line breaks.
       * Stomp 1.0 and 1.1 only allow line feeds.
       */
      if (newEol) {
         EOL = "\r\n";
      }
   }

   @Override
   public String toString() {
      return "[1.2]" + super.toString();
   }

}


text:
package jira

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/jws"
)

func TestJWTFetch_JSONResponse(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{
			"access_token": "90d64460d14870c08c81352a05dedd3465940a7c",
			"token_type": "Bearer",
			"expires_in": 3600
		}`))
	}))
	defer ts.Close()

	conf := &Config{
		BaseURL: "https://my.app.com",
		Subject: "userkey",
		Config: oauth2.Config{
			ClientID:     "super_secret_client_id",
			ClientSecret: "super_shared_secret",
			Scopes:       []string{"read", "write"},
			Endpoint: oauth2.Endpoint{
				AuthURL:  "https://example.com",
				TokenURL: ts.URL,
			},
		},
	}

	tok, err := conf.TokenSource(context.Background()).Token()
	if err != nil {
		t.Fatal(err)
	}
	if !tok.Valid() {
		t.Errorf("got invalid token: %v", tok)
	}
	if got, want := tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c"; got != want {
		t.Errorf("access token = %q; want %q", got, want)
	}
	if got, want := tok.TokenType, "Bearer"; got != want {
		t.Errorf("token type = %q; want %q", got, want)
	}
	if got := tok.Expiry.IsZero(); got {
		t.Errorf("token expiry = %v, want none", got)
	}
}

func TestJWTFetch_BadResponse(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"token_type": "Bearer"}`))
	}))
	defer ts.Close()

	conf := &Config{
		BaseURL: "https://my.app.com",
		Subject: "userkey",
		Config: oauth2.Config{
			ClientID:     "super_secret_client_id",
			ClientSecret: "super_shared_secret",
			Scopes:       []string{"read", "write"},
			Endpoint: oauth2.Endpoint{
				AuthURL:  "https://example.com",
				TokenURL: ts.URL,
			},
		},
	}

	tok, err := conf.TokenSource(context.Background()).Token()
	if err != nil {
		t.Fatal(err)
	}
	if tok == nil {
		t.Fatalf("got nil token; want token")
	}
	if tok.Valid() {
		t.Errorf("got invalid token: %v", tok)
	}
	if got, want := tok.AccessToken, ""; got != want {
		t.Errorf("access token = %q; want %q", got, want)
	}
	if got, want := tok.TokenType, "Bearer"; got != want {
		t.Errorf("token type = %q; want %q", got, want)
	}
}

func TestJWTFetch_BadResponseType(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"access_token":123, "token_type": "Bearer"}`))
	}))
	defer ts.Close()

	conf := &Config{
		BaseURL: "https://my.app.com",
		Subject: "userkey",
		Config: oauth2.Config{
			ClientID:     "super_secret_client_id",
			ClientSecret: "super_shared_secret",
			Endpoint: oauth2.Endpoint{
				AuthURL:  "https://example.com",
				TokenURL: ts.URL,
			},
		},
	}

	tok, err := conf.TokenSource(context.Background()).Token()
	if err == nil {
		t.Error("got a token; expected error")
		if got, want := tok.AccessToken, ""; got != want {
			t.Errorf("access token = %q; want %q", got, want)
		}
	}
}

func TestJWTFetch_Assertion(t *testing.T) {
	var assertion string
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		assertion = r.Form.Get("assertion")

		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{
			"access_token": "90d64460d14870c08c81352a05dedd3465940a7c",
			"token_type": "Bearer",
			"expires_in": 3600
		}`))
	}))
	defer ts.Close()

	conf := &Config{
		BaseURL: "https://my.app.com",
		Subject: "userkey",
		Config: oauth2.Config{
			ClientID:     "super_secret_client_id",
			ClientSecret: "super_shared_secret",
			Endpoint: oauth2.Endpoint{
				AuthURL:  "https://example.com",
				TokenURL: ts.URL,
			},
		},
	}

	_, err := conf.TokenSource(context.Background()).Token()
	if err != nil {
		t.Fatalf("Failed to fetch token: %v", err)
	}

	parts := strings.Split(assertion, ".")
	if len(parts) != 3 {
		t.Fatalf("assertion = %q; want 3 parts", assertion)
	}
	gotjson, err := base64.RawURLEncoding.DecodeString(parts[0])
	if err != nil {
		t.Fatalf("invalid token header; err = %v", err)
	}

	got := jws.Header{}
	if err := json.Unmarshal(gotjson, &got); err != nil {
		t.Errorf("failed to unmarshal json token header = %q; err = %v", gotjson, err)
	}

	want := jws.Header{
		Algorithm: "HS256",
		Typ:       "JWT",
	}
	if got != want {
		t.Errorf("access token header = %q; want %q", got, want)
	}
}


text:
This file documents all notable changes to Sysdig Falco Helm Chart. The release
numbering uses [semantic versioning](http://semver.org).

## v0.2.0

### Major Changes

* Add NATS Output integration

### Minor Changes

* Fix value mismatch between code and documentation

## v0.1.1

### Minor Changes

* Fix several typos

## v0.1.0

### Major Changes

* Initial release of Sysdig Falco Helm Chart


text:
Section 4 of the [Sam Format
Specification](http://samtools.github.io/hts-specs/SAMv1.pdf) has details about
the BGZF format.

Peter Cock also has a [terrific
post](http://blastedbio.blogspot.com/2011/11/bgzf-blocked-bigger-better-gzip.html)
about this format on his blog [Blasted
Bioinformatics](http://blastedbio.blogspot.com/).

## Creating SQLite Databases

### GWAS Catalog Data

I've created a toy SQLite database from the NHGRI GWAS catalog. There are two
versions: an unnormalized table, and a more-normalized set of two tables.

The NHGRI [catalog of published GWA studies](http://www.genome.gov/gwastudies/)
can be downloaded from here: http://www.genome.gov/admin/gwascatalog.txt. This
file was downloaded 2014-09-07. Unfortunately, this file is quite messy so I've
taken a cleaner subset of entries. A big problem is that this data is
distributed as one (unnormalized) table, when it should be at least two tables
(studies and risk alleles associated with studies). To simplify examples, I've
used removed 542 rows (from 17,833) that don't have clean, single RS IDs for
the strongest risk SNP:

    $ gawk -F"\t" '$21 ~ /^rs[0-9]+-.? *$/' gwascatalog.txt > filtered_gwascatalog.txt

We use the risk allele column, since (unfortunately), the `SNPs` column has
some combined entries like: `rs11209002,rs2064689,rs1004819,rs2902440`.
Overall, we lose information but this makes the SQLite examples much simpler.
If you actually needed to process these data (not for a toy example), you could
write a script that parses and cleans the joined RS IDs. Ideally, the data
should be provided in a cleaner format that is more conducive to parsing.

For the first simple examples we use a quick script I wrote,
`gwascat2sqlite.py`, to create a table `gwascat` in a SQLite database
`gwascat.db` from the filtered GWAS catalog file.

    $ python gwascat2sqlite.py gwascat.db gwascat filtered_gwascatalog.txt

For other examples, we use GWAS Catalog split into two tables, so these tables
are normalized ([2NF](http://en.wikipedia.org/wiki/Second_normal_form)). These
two tables are `loci` and `schema`. We use Pubmed IDs as unique IDs, which they
are, according to:

    $ cat filtered_gwascatalog.txt | cut -f2 | uniq | sort | uniq -d

Note that there's a character encoding problem in the original
`gwascatalog.txt` -- this sort of stuff happens all the time. Using `cut` may
give you a warning and *incorrect results*. The issue here is that one or more
characters are UTF-8, which is not a single-byte encoding scheme. Setting your
shell to force C-style single byte support solves this:

    $ export LC_CTYPE=C
    $ export LANG=C

We can see these with the trick we learned in chapter 7:

    $ nonascii filtered_gwascatalog.txt

The two table database was generated with (this creates two tables, `loci`, and
`study`):

    $ gwascat2sqlite2table.py hs_variants.db filtered_gwascatalog.txt

#### Notes about these data

As one example to demonstrate grouping data and using SQLite functions, I look
at the maximum -log10 p-values per year. A clear (somewhat unsurprising) trend
emerges: -log10 p-values roughly increase over time. This is due to larger
study sample sizes. It'd be nice to get at the actual raw sample size
information. Unfortunately, while the `initial_samplesize` and
`replication_samplesize` columns include descriptive information about the
populations included in the study, the actual are not easily extractable
without loss of information.

### The Toy Joining Data

Teaching joins with real data is tricky, as there are far too many rows to show
full cross joins, add in complexities like NULLs, etc. I have created small toy
data sets `assocs.txt` and `studies.txt` in the directory `toy-joins/`. The
database `joins.db` is included in the main directory for easy access, but the
Makefile and `joins.sql` file used to create it are in `toy-joins/`.

### 1000 Genome Data

I've downloaded the file with:

    $ wget http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr19.phase3_shapeit2_mvncall_integrated_v5.20130502.genotypes.vcf.gz

and created a table `freqs_1kg` in `hs_variants.db`:

    $ vcf2sqlite.py hs_variants.db freqs_1kg \
       ALL.chr19.phase3_shapeit2_mvncall_integrated_v5.20130502.genotypes.vcf.gz

## More on SQLite Types

I've simplified some of my discussion of SQLite types, though paying careful
attention to not take it too far. The best, most definitive source is this page
of the SQLite documentation: http://www.sqlite.org/datatype3.html

So while I gloss over the finer details of SQLite storage classes and data
types, this isn't far enough from the truth that it's incorrect.

## Binning to improve overlap query performance in relational databases

The classic reference for this is [Kent et al.
(2002)](http://genome.cshlp.org/content/12/6/996.full) *The Human Genome
Browser at UCSC*. See Figure 7 and the surrounding discussion for more details.
There's also much more information and code examples at:
http://genomewiki.ucsc.edu/index.php/Bin_indexing_system.

Jim Kent's code uses very clever bit shift schemes that are (relatively) easily
implemented in other languages.

## Data for the SQLite +.import+ example

Given this is a chapter on databases, I couldn't resist using a database (UCSC
Genome Browser's MySQL database) to generate some data for an example on how to
import data into a database. See the SQL file `ucsc_example_vars.sql`, which
contains:

    SELECT chrom, chromStart, chromEnd, strand, name
    FROM snp137Common
    WHERE name IN("rs12255372", "rs333", "rs1333049", "rs4988235");

These are some popular RS ID's from the great site
[SNPedia](http://www.snpedia.com/index.php/SNPedia). This SQL grabs their
positions from the dbSNP track in UCSC. It can be executed using:

    $ mysql --user=genome --host=genome-mysql.cse.ucsc.edu -A hg19 \
      < ucsc_example_vars.sql | sed 1d > variants.txt

## Database Normalization Resources

[E.F. Codd](http://en.wikipedia.org/wiki/Edgar_F._Codd) was the inventor of the
relational model and the normal forms. His [The relational model for database
management](http://dl.acm.org/citation.cfm?id=77708&CFID=560187979&CFTOKEN=80219131)
is available online for free, but is very technical. Jay Kreibich's [Using
SQLite](http://shop.oreilly.com/product/9780596521196.do) has a good short
treatment.

Date's writings ([Date on Database: Writings
2000-2006](http://www.amazon.com/Date-Database-Writings-2000-2006-C/dp/159059746X))
are interesting and show some of the disagreement with, and extensions of
Codd's definitions.

## In-memory Databases

SQLite also supports in-memory databases (which are faster than on-disk
databases, since memory IO is faster than disk IO). You can create these by
opening a connection to `:memory:` (rather than your normal SQLite3 file). For example, in Python, this would look like:

    con = sqlite3.connect(":memory:")

See [SQLite's documentation](https://www.sqlite.org/inmemorydb.html) for more
information. [Python's sqlite3 module documentation](https://docs.python.org/2/library/sqlite3.html) also covers an example.

## Python and SQLite3

I mention that you should always use
[placeholders](https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute)
in SQL statements. Although the focus of this chapter is not creating and
working with databases open to the public, it's worth noting that not handling
query building correctly can lead to disastrous results. There's a classic
[xkcd](http://xkcd.com/327/) on this:

![](http://imgs.xkcd.com/comics/exploits_of_a_mom.png)


text:
NumPy is a dependency for Matplotlib.
Matplotlib isn't supported on Python 3.

## Example 1

A simple Matplotlib example (using IPython):

	In [1]: import matplotlib.pyplot as plt
	In [2]: x = range(5)
	In [3]: plt.plot(x, [xi**2 for xi in x]) # using list comprehension
	In [4]: plt.show(block=False)  	     	 # experimental block keyword

To overplot, call `plt.plot` multiple times before calling `plt.show`.

## Example 2

Numpy is better:

	In [27]: import numpy as np
	In [28]: x = np.arange(0, 5, 0.5) # start, stop, interval
	In [29]: plt.plot(x, x*2)
	In [30]: plt.plot(x, x*3)
	In [31]: plt.plot(x, x*4)
	In [32]: plt.show()

## Blocking figure window

Toggle figure window blocking the command line with:

	In [36]: plt.ion()
	In [37]: plt.ioff()

Or start with:

	$ ipython - pylab

## Pylab

Should I skip pyplot and go right to pylab, which combines pyplot and
numpy? Maybe not:

> "We and the authors of Matplotlib discourage the use of pylab,
> other than for proof-of-concept snippets. While being rather
> simple to use, it teaches developers the wrong way to use
> Matplotlib, so we intentionally do not present it in this book."

## Initial imports

In the preferred style, initial imports are:

	>>> import matplotlib.pyplot as plt
	>>> import numpy as np
	>>> from mpl_toolkits.basemap import Basemap