text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="shortcut icon" href="assets/images/fav_icons/sd_favicon_purple.png" type="image/x-icon" />
	<title>JavaScript Templating</title>
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/custom.css" rel="stylesheet">

Home

							Chapters

02 - jQuery Template

03 - Mustache.js

04 - Handlebars.js

05 - Dust

JavaScript Templating

04 - Handlebars.js

Simple Templates with HandlebarsJS

This example embeds the template and data directly in the source HTML.

Helpers with HandlebarsJS

This example embeds the template and data directly in the source HTML.

Precompiled Templates with HandlebarsJS

Precompiled Template Example

Conditionals and Loops with HandlebarsJS

This example embeds the template and data directly in the source HTML.


text: console.log("some code after init");

redpajama_set_name: RedPajamaGithub


text:
require "bundler/setup"
require "kindle_manager"

Dir[File.join(File.dirname(__FILE__), "..", "spec", "support", "**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = ".rspec_status"

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end

  config.filter_run_excluding browser: true

  config.before do
    allow(Capybara).to receive(:save_path).and_return('spec/fixtures/tmp')

    # Mock credentials
    %w[AMAZON_USERNAME_CODE AMAZON_PASSWORD_CODE AMAZON_CODE_SALT].each do |key|
      ENV[key] = 'test'
    end
  end
end


text:
<?php

/** @phpstub */
class MongoInt64
{
    /** @var string */
    public $value;

    /**
     * Creates a new 64-bit integer.
     *
     * @param string $value
     */
    public function __construct($value)
    {
    }

    /**
     * Returns the string representation of this 64-bit integer.
     *
     * @return string Returns the string representation of this integer.
     */
    public function __toString()
    {
    }
}


text:
package org.apache.camel.spring;

import org.apache.camel.model.ModelHelper;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 */
public class DumpModelAsXmlPlaceholdersTest extends SpringTestSupport {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/spring/DumpModelAsXmlPlaceholdersTest.xml");
    }

    public void testDumpModelAsXml() throws Exception {
        assertEquals("Gouda", context.getRoutes().get(0).getId());
        String xml = ModelHelper.dumpModelAsXml(context, context.getRouteDefinition("Gouda"));
        assertNotNull(xml);
        log.info(xml);

        assertTrue(xml.contains("<route xmlns=\"http://camel.apache.org/schema/spring\" customId=\"true\" id=\"Gouda\">"));
        assertTrue(xml.contains("<from uri=\"direct:start-{{cheese.type}}\"/>"));
        assertTrue(xml.contains("<to customId=\"true\" id=\"log\" uri=\"direct:end-{{cheese.type}}\"/>"));
    }

}


text:
<load target="js/widget.js" />
<load target="css/widget.css" />
<form action="./" method="get" onsubmit="return addContentWidget(this); return false;" id="content_fo">
	<input type="hidden" name="content" value="{$oDocument->getContentText()}" />
	<input type="hidden" name="mid" value="{$module_info->mid}" />
	<input type="hidden" name="module_srl" value="{$module_srl}" />
	<input type="hidden" name="document_srl" value="{$document_srl}" />
	<input type="hidden" name="style" value="float:left;padding:none;margin:none;width:100%;" />
	<input type="hidden" name="widget_padding_left" value="" />
	<input type="hidden" name="widget_padding_right" value="" />
	<input type="hidden" name="widget_padding_top" value="" />
	<input type="hidden" name="widget_padding_bottom" value="" />

{$lang->cmd_content_insert}

{$editor}

		<input type="submit" value="{$lang->cmd_save}" class="x_btn x_btn-inverse" />

</form>


text:
import os.path
import json

def get_config_file():
    vl_dir = os.path.join(os.path.expanduser('~'), '.vl/')
    if not os.path.exists(vl_dir):
        os.makedirs(vl_dir, mode=0700)
    config_file = os.path.join(vl_dir, 'config')
    return config_file

def read_config():
    try:
        with open(get_config_file()) as config_file:
            return json.load(config_file)
    except IOError:
        return {}

def write_config(config):
    with open(get_config_file(), 'w') as config_file:
        json.dump(config, config_file, indent=4)

def get_auth():
    config = read_config()
    auth = None
    if 'auth_token' in config:
        auth = config['auth_token']
    return auth

def set_auth(token):
    config = read_config()
    config.update(token)
    write_config(config)

def delete_auth():
    config = read_config()
    if 'auth_token' in config:
        del config['auth_token']
    write_config(config)


text:
(function() {
  /**
  The HackMyResume date representation.
  @license MIT. See LICENSE.md for details.
  @module core/fluent-date
  */
  var FluentDate, abbr, moment, months;

  moment = require('moment');

  require('../utils/string');

  /**
  Create a FluentDate from a string or Moment date object. There are a few date
  formats to be aware of here.
  1. The words "Present" and "Now", referring to the current date
  2. The default "YYYY-MM-DD" format used in JSON Resume ("2015-02-10")
  3. Year-and-month only ("2015-04")
  4. Year-only "YYYY" ("2015")
  5. The friendly HackMyResume "mmm YYYY" format ("Mar 2015" or "Dec 2008")
  6. Empty dates ("", " ")
  7. Any other date format that Moment.js can parse from
  Note: Moment can transparently parse all or most of these, without requiring us
  to specify a date format...but for maximum parsing safety and to avoid Moment
  deprecation warnings, it's recommended to either a) explicitly specify the date
  format or b) use an ISO format. For clarity, we handle these cases explicitly.
  @class FluentDate
  */
  FluentDate = class FluentDate {
    constructor(dt) {
      this.rep = this.fmt(dt);
    }

    static isCurrent(dt) {
      return !dt || (String.is(dt) && /^(present|now|current)$/.test(dt));
    }

  };

  months = {};

  abbr = {};

  moment.months().forEach(function(m, idx) {
    return months[m.toLowerCase()] = idx + 1;
  });

  moment.monthsShort().forEach(function(m, idx) {
    return abbr[m.toLowerCase()] = idx + 1;
  });

  abbr.sept = 9;

  module.exports = FluentDate;

  FluentDate.fmt = function(dt, throws) {
    var month, mt, parts, ref, temp;
    throws = (throws === void 0 || throws === null) || throws;
    if (typeof dt === 'string' || dt instanceof String) {
      dt = dt.toLowerCase().trim();
      if (/^(present|now|current)$/.test(dt)) { // "Present", "Now"
        return moment();
      } else if (/^\D+\s+\d{4}$/.test(dt)) { // "Mar 2015"
        parts = dt.split(' ');
        month = months[parts[0]] || abbr[parts[0]];
        temp = parts[1] + '-' + ((ref = month < 10) != null ? ref : '0' + {
          month: month.toString()
        });
        return moment(temp, 'YYYY-MM');
      } else if (/^\d{4}-\d{1,2}$/.test(dt)) { // "2015-03", "1998-4"
        return moment(dt, 'YYYY-MM');
      } else if (/^\s*\d{4}\s*$/.test(dt)) { // "2015"
        return moment(dt, 'YYYY');
      } else if (/^\s*$/.test(dt)) { // "", " "
        return moment();
      } else {
        mt = moment(dt);
        if (mt.isValid()) {
          return mt;
        }
        if (throws) {
          throw 'Invalid date format encountered.';
        }
        return null;
      }
    } else {
      if (!dt) {
        return moment();
      } else if (dt.isValid && dt.isValid()) {
        return dt;
      }
      if (throws) {
        throw 'Unknown date object encountered.';
      }
      return null;
    }
  };

}).call(this);

//# sourceMappingURL=fluent-date.js.map


text:
package com.anupam.annotations;

import java.util.Set;
import java.util.logging.Logger;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import com.google.common.collect.Sets;

public class RetryMethodInterceptor implements MethodInterceptor {

  private static final Logger logger = Logger.getLogger(RetryMethodInterceptor.class.getName());

  @Override
  public Object invoke(MethodInvocation methodInvocator) throws Throwable {
    Retry retryAnnotation = methodInvocator.getMethod().getAnnotation(Retry.class);
    Set<Class<? extends Throwable>> retriableExceptions =
        Sets.newHashSet(retryAnnotation.retryOnExceptions());

    String className = methodInvocator.getThis().getClass().getCanonicalName();
    String methodName = methodInvocator.getMethod().getName();

    int tryCount = 0;
    while (true) {
      try {
        return methodInvocator.proceed();
      } catch (Throwable ex) {
        tryCount++;
        boolean isExceptionInAllowedList = isRetriableException(retriableExceptions, ex.getClass());
        if (!isExceptionInAllowedList) {
          System.out.println(String.format(
              "Exception not in retry list for class: %s - method: %s - retry count: %s",
              className, methodName, tryCount));
          throw ex;
        } else if (isExceptionInAllowedList && tryCount > retryAnnotation.maxTries()) {
          System.out.println(String
                  .format(
                      "Exhausted retries, rethrowing exception for class: %s - method: %s - retry count: %s",
                      className, methodName, tryCount));
          throw ex;
        }
        System.out.println(String.format("Retrying for class: %s - method: %s - retry count: %s",
            className, methodName, tryCount));
      }
    }
  }

  private boolean isRetriableException(Set<Class<? extends Throwable>> allowedExceptions,
      Class<? extends Throwable> caughtException) {
    for (Class<? extends Throwable> look : allowedExceptions) {
      // Only compare the class names we do not want to compare superclass so Class#isAssignableFrom
      // can't be used.
      if (caughtException.getCanonicalName().equalsIgnoreCase(look.getCanonicalName())) {
        return true;
      }
    }
    return false;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>CxImage: Encode</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Classes

Files

Encode

Functions

bool 	CxImage::Save (const TCHAR *filename, DWORD imagetype)

bool 	CxImage::Encode (FILE *hFile, DWORD imagetype)

bool 	CxImage::Encode (CxFile *hFile, DWORD imagetype)

bool 	CxImage::Encode (CxFile *hFile, CxImage **pImages, int pagecount, DWORD imagetype)

bool 	CxImage::Encode (FILE *hFile, CxImage **pImages, int pagecount, DWORD imagetype)

bool 	CxImage::Encode (BYTE *&buffer, long &size, DWORD imagetype)

bool 	CxImage::Encode2RGBA (CxFile *hFile, bool bFlipY=false)

bool 	CxImage::Encode2RGBA (BYTE *&buffer, long &size, bool bFlipY=false)

Detailed Description

Function Documentation

          bool CxImage::Encode
          (
          BYTE *&
           buffer,

          long &
           size,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to memory buffer the image in a specific format.

Parameters:

	buffer,: 	output memory buffer pointer. Must be NULL, the function allocates and fill the memory, the application must free the buffer, see also FreeMemory().

	size,: 	output memory buffer size.

	imagetype,: 	file format, see ENUM_CXIMAGE_FORMATS

Returns:

true if everything is ok

          bool CxImage::Encode
          (
          FILE *
           hFile,

          CxImage **
           pImages,

          int
           pagecount,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to disk or memory pagecount images, referenced by an array of CxImage pointers.

Parameters:

	hFile,: 	file handle.

	pImages,: 	array of CxImage pointers.

	pagecount,: 	number of images.

	imagetype,: 	can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF.

Returns:

true if everything is ok

          bool CxImage::Encode
          (
          CxFile *
           hFile,

          CxImage **
           pImages,

          int
           pagecount,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to disk or memory pagecount images, referenced by an array of CxImage pointers.

Parameters:

	hFile,: 	file handle (CxMemFile or CxIOFile), with write access.

	pImages,: 	array of CxImage pointers.

	pagecount,: 	number of images.

	imagetype,: 	can be CXIMAGE_FORMAT_TIF, CXIMAGE_FORMAT_GIF or CXIMAGE_FORMAT_ICO.

Returns:

true if everything is ok

          bool CxImage::Encode
          (
          CxFile *
           hFile,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to disk the image in a specific format.

Parameters:

	hFile,: 	file handle (CxMemFile or CxIOFile), with write access.

	imagetype,: 	file format, see ENUM_CXIMAGE_FORMATS

Returns:

true if everything is ok

See also:

ENUM_CXIMAGE_FORMATS

          bool CxImage::Encode
          (
          FILE *
           hFile,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to disk the image in a specific format.

Parameters:

	hFile,: 	file handle, open and enabled for writing.

	imagetype,: 	file format, see ENUM_CXIMAGE_FORMATS

Returns:

true if everything is ok

          bool CxImage::Encode2RGBA
          (
          BYTE *&
           buffer,

          long &
           size,

          bool
           bFlipY = false

          )
          		 [inherited]

exports the image into a RGBA buffer, Useful for OpenGL applications.

Parameters:

	buffer,: 	output memory buffer pointer. Must be NULL, the function allocates and fill the memory, the application must free the buffer, see also FreeMemory().

	size,: 	output memory buffer size.

	bFlipY,: 	direction of Y axis. default = false.

Returns:

true if everything is ok

          bool CxImage::Encode2RGBA
          (
          CxFile *
           hFile,

          bool
           bFlipY = false

          )
          		 [inherited]

exports the image into a RGBA buffer, Useful for OpenGL applications.

Parameters:

	hFile,: 	file handle (CxMemFile or CxIOFile), with write access.

	bFlipY,: 	direction of Y axis. default = false.

Returns:

true if everything is ok

          bool CxImage::Save
          (
          const TCHAR *
           filename,

          DWORD
           imagetype

          )
          		 [inherited]

Saves to disk the image in a specific format.

Parameters:

	filename,: 	file name

	imagetype,: 	file format, see ENUM_CXIMAGE_FORMATS

Returns:

true if everything is ok

<address style="text-align: right;">Generated on Thu Jan 31 20:11:32 2008 for CxImage by

 1.5.4 </address>


text:
<?php

namespace Magento\Theme\Test\Unit\Block\Html;

class HeaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Theme\Block\Html\Header
     */
    protected $unit;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $scopeConfig;

    protected function setUp()
    {
        $context = $this->getMockBuilder('Magento\Framework\View\Element\Template\Context')
            ->setMethods(['getScopeConfig'])
            ->disableOriginalConstructor()
            ->getMock();
        $this->scopeConfig = $this->getMockBuilder('\Magento\Framework\App\Config')
            ->setMethods(['getValue'])
            ->disableOriginalConstructor()->getMock();
        $context->expects($this->once())->method('getScopeConfig')->will($this->returnValue($this->scopeConfig));

        $this->unit = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject(
            'Magento\Theme\Block\Html\Header',
            ['context' => $context]
        );
    }

    public function testGetWelcomeDefault()
    {
        $this->scopeConfig->expects($this->once())->method('getValue')
            ->with('design/header/welcome', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)
            ->willReturn('Welcome Message');

        $this->assertEquals('Welcome Message', $this->unit->getWelcome());
    }
}


text:
package org.scalautils

import org.scalatest._
import scala.collection.GenSeq
import scala.collection.GenMap
import scala.collection.GenSet
import scala.collection.GenIterable
import scala.collection.GenTraversable
import scala.collection.GenTraversableOnce
import scala.collection.{mutable,immutable}

class ConversionCheckedSetEqualityConstraintsSpec extends Spec with NonImplicitAssertions with ConversionCheckedTripleEquals with SetEqualityConstraints {

  case class Super(size: Int)
  class Sub(sz: Int) extends Super(sz)

  val super1: Super = new Super(1)
  val sub1: Sub = new Sub(1)
  val super2: Super = new Super(2)
  val sub2: Sub = new Sub(2)
  val nullSuper: Super = null

  case class Fruit(name: String)
  class Apple extends Fruit("apple")
  class Orange extends Fruit("orange")

  object `the SetEqualityConstraints trait` {

    def `should allow any Set to be compared with any other Set, so long as the element types of the two Sets adhere to the equality constraint in force for those types` {
      assert(mutable.HashSet(1, 2, 3) === immutable.HashSet(1, 2, 3))
      assert(mutable.HashSet(1, 2, 3) === immutable.HashSet(1L, 2L, 3L))
      assert(mutable.HashSet(1L, 2L, 3L) === immutable.HashSet(1, 2, 3))
      assert(immutable.HashSet(1, 2, 3) === mutable.HashSet(1L, 2L, 3L))
      assert(immutable.HashSet(1L, 2L, 3L) === mutable.HashSet(1, 2, 3))
      assert(mutable.HashSet(new Apple, new Apple) === immutable.HashSet(new Fruit("apple"), new Fruit("apple")))
      assert(immutable.HashSet(new Fruit("apple"), new Fruit("apple")) === mutable.HashSet(new Apple, new Apple))
      // assert(mutable.HashSet(new Apple, new Apple) === immutable.HashSet(new Orange, new Orange)) // does not compile last time I checked
      // assert(immutable.HashSet(new Apple, new Apple) === mutable.HashSet(new Orange, new Orange)) // does not compile last time I checked
      // assert(immutable.HashSet(new Orange, new Orange) === mutable.HashSet(new Apple, new Apple)) // does not compile last time I checked
      // assert(mutable.HashSet(new Orange, new Orange) === immutable.HashSet(new Apple, new Apple)) // does not compile last time I checked
    }
  }
}


text:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;

namespace RestSamples.Service
{
    public class ApiServiceWithHttpClient : IApiService
    {
        private HttpMessageHandler _messageHandler;

        public ApiServiceWithHttpClient(HttpMessageHandler handler)
        {
            _messageHandler = handler;
        }

        public async Task<IEnumerable<string>> GetAllValues()
        {
            using (var httpClient = new HttpClient(_messageHandler))
            {
                var httpMessage = new HttpRequestMessage(new HttpMethod("GET"), "http://localhost:59642/api/values");
                var response = await httpClient.SendAsync(httpMessage);
                return await response.Content.ReadAsAsync<IEnumerable<string>>();
            }
        }

        public async Task<bool> SaveValue(string value)
        {
            using (var httpClient = new HttpClient(_messageHandler))
            {
                var httpMessage = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:59642/api/values");
                httpMessage.Content = new ObjectContent(typeof(string), value, new JsonMediaTypeFormatter());
                var response = await httpClient.SendAsync(httpMessage);
                return response.StatusCode == HttpStatusCode.Created;
            }
        }
    }
}


text:
class AddUserIdToEmailSuppressions < ActiveRecord::Migration[6.1]
  def change
    add_column :email_suppressions, :user_id, :integer
    add_index :email_suppressions, :user_id
  end
end


text:
package org.merlin.config.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.merlin.config.type.TypeStringify;

/**
 * Annotation that identifies how to convert a type to a string. This can be specified with either an instance method that converts an object to its primitive
 * (ultimately string) representation, or else a TypeStringify class that performs this operation. Only one value should be specified. When applied to a class,
 * applies to the class itself; when applied to a method, applies to the method's return type.
 *
 * @author Merlin Hughes
 * @version 0.1, 2007/04/15
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface Stringify {

    /**
     * The name of a method that can convert an object to its primitive (ultimately string) form.
     */
    public String method() default "";

    /**
     * A class that can convert an object to its string form.
     */
    public Class<? extends TypeStringify> stringify() default TypeStringify.class;
}


text:
// MESSAGE MEMORY_VECT PACKING

#define MAVLINK_MSG_ID_MEMORY_VECT 249

MAVPACKED(
typedef struct __mavlink_memory_vect_t {
 uint16_t address; /*< Starting address of the debug variables*/
 uint8_t ver; /*< Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below*/
 uint8_t type; /*< Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14*/
 int8_t value[32]; /*< Memory contents at specified address*/
}) mavlink_memory_vect_t;

#define MAVLINK_MSG_ID_MEMORY_VECT_LEN 36
#define MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN 36
#define MAVLINK_MSG_ID_249_LEN 36
#define MAVLINK_MSG_ID_249_MIN_LEN 36

#define MAVLINK_MSG_ID_MEMORY_VECT_CRC 204
#define MAVLINK_MSG_ID_249_CRC 204

#define MAVLINK_MSG_MEMORY_VECT_FIELD_VALUE_LEN 32

#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_MEMORY_VECT { \
	249, \
	"MEMORY_VECT", \
	4, \
	{  { "address", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_memory_vect_t, address) }, \
         { "ver", NULL, MAVLINK_TYPE_UINT8_T, 0, 2, offsetof(mavlink_memory_vect_t, ver) }, \
         { "type", NULL, MAVLINK_TYPE_UINT8_T, 0, 3, offsetof(mavlink_memory_vect_t, type) }, \
         { "value", NULL, MAVLINK_TYPE_INT8_T, 32, 4, offsetof(mavlink_memory_vect_t, value) }, \
         } \
}
#else
#define MAVLINK_MESSAGE_INFO_MEMORY_VECT { \
	"MEMORY_VECT", \
	4, \
	{  { "address", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_memory_vect_t, address) }, \
         { "ver", NULL, MAVLINK_TYPE_UINT8_T, 0, 2, offsetof(mavlink_memory_vect_t, ver) }, \
         { "type", NULL, MAVLINK_TYPE_UINT8_T, 0, 3, offsetof(mavlink_memory_vect_t, type) }, \
         { "value", NULL, MAVLINK_TYPE_INT8_T, 32, 4, offsetof(mavlink_memory_vect_t, value) }, \
         } \
}
#endif

/**
 * @brief Pack a memory_vect message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 *
 * @param address Starting address of the debug variables
 * @param ver Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below
 * @param type Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14
 * @param value Memory contents at specified address
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_memory_vect_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
						       uint16_t address, uint8_t ver, uint8_t type, const int8_t *value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_MEMORY_VECT_LEN];
	_mav_put_uint16_t(buf, 0, address);
	_mav_put_uint8_t(buf, 2, ver);
	_mav_put_uint8_t(buf, 3, type);
	_mav_put_int8_t_array(buf, 4, value, 32);
        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_MEMORY_VECT_LEN);
#else
	mavlink_memory_vect_t packet;
	packet.address = address;
	packet.ver = ver;
	packet.type = type;
	mav_array_memcpy(packet.value, value, sizeof(int8_t)*32);
        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_MEMORY_VECT_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_MEMORY_VECT;
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
}

/**
 * @brief Pack a memory_vect message on a channel
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param address Starting address of the debug variables
 * @param ver Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below
 * @param type Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14
 * @param value Memory contents at specified address
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_memory_vect_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
							   mavlink_message_t* msg,
						           uint16_t address,uint8_t ver,uint8_t type,const int8_t *value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_MEMORY_VECT_LEN];
	_mav_put_uint16_t(buf, 0, address);
	_mav_put_uint8_t(buf, 2, ver);
	_mav_put_uint8_t(buf, 3, type);
	_mav_put_int8_t_array(buf, 4, value, 32);
        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_MEMORY_VECT_LEN);
#else
	mavlink_memory_vect_t packet;
	packet.address = address;
	packet.ver = ver;
	packet.type = type;
	mav_array_memcpy(packet.value, value, sizeof(int8_t)*32);
        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_MEMORY_VECT_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_MEMORY_VECT;
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
}

/**
 * @brief Encode a memory_vect struct
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 * @param memory_vect C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_memory_vect_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_memory_vect_t* memory_vect)
{
	return mavlink_msg_memory_vect_pack(system_id, component_id, msg, memory_vect->address, memory_vect->ver, memory_vect->type, memory_vect->value);
}

/**
 * @brief Encode a memory_vect struct on a channel
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param memory_vect C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_memory_vect_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_memory_vect_t* memory_vect)
{
	return mavlink_msg_memory_vect_pack_chan(system_id, component_id, chan, msg, memory_vect->address, memory_vect->ver, memory_vect->type, memory_vect->value);
}

/**
 * @brief Send a memory_vect message
 * @param chan MAVLink channel to send the message
 *
 * @param address Starting address of the debug variables
 * @param ver Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below
 * @param type Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14
 * @param value Memory contents at specified address
 */
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS

static inline void mavlink_msg_memory_vect_send(mavlink_channel_t chan, uint16_t address, uint8_t ver, uint8_t type, const int8_t *value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_MEMORY_VECT_LEN];
	_mav_put_uint16_t(buf, 0, address);
	_mav_put_uint8_t(buf, 2, ver);
	_mav_put_uint8_t(buf, 3, type);
	_mav_put_int8_t_array(buf, 4, value, 32);
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MEMORY_VECT, buf, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
#else
	mavlink_memory_vect_t packet;
	packet.address = address;
	packet.ver = ver;
	packet.type = type;
	mav_array_memcpy(packet.value, value, sizeof(int8_t)*32);
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MEMORY_VECT, (const char *)&packet, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
#endif
}

/**
 * @brief Send a memory_vect message
 * @param chan MAVLink channel to send the message
 * @param struct The MAVLink struct to serialize
 */
static inline void mavlink_msg_memory_vect_send_struct(mavlink_channel_t chan, const mavlink_memory_vect_t* memory_vect)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
    mavlink_msg_memory_vect_send(chan, memory_vect->address, memory_vect->ver, memory_vect->type, memory_vect->value);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MEMORY_VECT, (const char *)memory_vect, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
#endif
}

#if MAVLINK_MSG_ID_MEMORY_VECT_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
  This varient of _send() can be used to save stack space by re-using
  memory from the receive buffer.  The caller provides a
  mavlink_message_t which is the size of a full mavlink message. This
  is usually the receive buffer for the channel, and allows a reply to an
  incoming message with minimum stack space usage.
 */
static inline void mavlink_msg_memory_vect_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan,  uint16_t address, uint8_t ver, uint8_t type, const int8_t *value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char *buf = (char *)msgbuf;
	_mav_put_uint16_t(buf, 0, address);
	_mav_put_uint8_t(buf, 2, ver);
	_mav_put_uint8_t(buf, 3, type);
	_mav_put_int8_t_array(buf, 4, value, 32);
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MEMORY_VECT, buf, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
#else
	mavlink_memory_vect_t *packet = (mavlink_memory_vect_t *)msgbuf;
	packet->address = address;
	packet->ver = ver;
	packet->type = type;
	mav_array_memcpy(packet->value, value, sizeof(int8_t)*32);
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MEMORY_VECT, (const char *)packet, MAVLINK_MSG_ID_MEMORY_VECT_MIN_LEN, MAVLINK_MSG_ID_MEMORY_VECT_LEN, MAVLINK_MSG_ID_MEMORY_VECT_CRC);
#endif
}
#endif

#endif

// MESSAGE MEMORY_VECT UNPACKING

/**
 * @brief Get field address from memory_vect message
 *
 * @return Starting address of the debug variables
 */
static inline uint16_t mavlink_msg_memory_vect_get_address(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  0);
}

/**
 * @brief Get field ver from memory_vect message
 *
 * @return Version code of the type variable. 0=unknown, type ignored and assumed int16_t. 1=as below
 */
static inline uint8_t mavlink_msg_memory_vect_get_ver(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  2);
}

/**
 * @brief Get field type from memory_vect message
 *
 * @return Type code of the memory variables. for ver = 1: 0=16 x int16_t, 1=16 x uint16_t, 2=16 x Q15, 3=16 x 1Q14
 */
static inline uint8_t mavlink_msg_memory_vect_get_type(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  3);
}

/**
 * @brief Get field value from memory_vect message
 *
 * @return Memory contents at specified address
 */
static inline uint16_t mavlink_msg_memory_vect_get_value(const mavlink_message_t* msg, int8_t *value)
{
	return _MAV_RETURN_int8_t_array(msg, value, 32,  4);
}

/**
 * @brief Decode a memory_vect message into a struct
 *
 * @param msg The message to decode
 * @param memory_vect C-struct to decode the message contents into
 */
static inline void mavlink_msg_memory_vect_decode(const mavlink_message_t* msg, mavlink_memory_vect_t* memory_vect)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	memory_vect->address = mavlink_msg_memory_vect_get_address(msg);
	memory_vect->ver = mavlink_msg_memory_vect_get_ver(msg);
	memory_vect->type = mavlink_msg_memory_vect_get_type(msg);
	mavlink_msg_memory_vect_get_value(msg, memory_vect->value);
#else
        uint8_t len = msg->len < MAVLINK_MSG_ID_MEMORY_VECT_LEN? msg->len : MAVLINK_MSG_ID_MEMORY_VECT_LEN;
        memset(memory_vect, 0, MAVLINK_MSG_ID_MEMORY_VECT_LEN);
	memcpy(memory_vect, _MAV_PAYLOAD(msg), len);
#endif
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Torrey bot. Club 24(10): 466 (1897)

#### Original name
Crandallia juncicola Ellis & Sacc., 1897

### Remarks
null


text:
package org.pentaho.di.trans.steps.dbproc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.loadsave.LoadSaveTester;
import org.pentaho.di.trans.steps.loadsave.initializer.InitializerInterface;
import org.pentaho.di.trans.steps.loadsave.validator.ArrayLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.DatabaseMetaLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.FieldLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.IntLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.PrimitiveIntArrayLoadSaveValidator;
import org.pentaho.di.trans.steps.loadsave.validator.StringLoadSaveValidator;

public class DBProcMetaTest implements InitializerInterface<StepMetaInterface> {
  LoadSaveTester loadSaveTester;
  Class<DBProcMeta> testMetaClass = DBProcMeta.class;

  @Before
  public void setUpLoadSave() throws Exception {
    KettleEnvironment.init();
    PluginRegistry.init( true );
    List<String> attributes =
        Arrays.asList( "procedure", "resultName", "resultType", "autoCommit", "argumentType", "argument", "argumentDirection", "database" );

    Map<String, String> getterMap = new HashMap<String, String>();
    Map<String, String> setterMap = new HashMap<String, String>();

    FieldLoadSaveValidator<String[]> stringArrayLoadSaveValidator =
        new ArrayLoadSaveValidator<String>( new StringLoadSaveValidator(), 5 );

    Map<String, FieldLoadSaveValidator<?>> attrValidatorMap = new HashMap<String, FieldLoadSaveValidator<?>>();
    attrValidatorMap.put( "argument", stringArrayLoadSaveValidator );
    attrValidatorMap.put( "argumentDirection", stringArrayLoadSaveValidator );
    attrValidatorMap.put( "argumentType",
        new PrimitiveIntArrayLoadSaveValidator( new IntLoadSaveValidator( 7 ), 5 ) );
    attrValidatorMap.put( "database", new DatabaseMetaLoadSaveValidator() );
    attrValidatorMap.put( "resultType", new IntLoadSaveValidator( 7 ) );

    Map<String, FieldLoadSaveValidator<?>> typeValidatorMap = new HashMap<String, FieldLoadSaveValidator<?>>();

    loadSaveTester =
        new LoadSaveTester( testMetaClass, attributes, new ArrayList<String>(), new ArrayList<String>(),
            getterMap, setterMap, attrValidatorMap, typeValidatorMap, this );
  }

  // Call the allocate method on the LoadSaveTester meta class
  @Override
  public void modify( StepMetaInterface someMeta ) {
    if ( someMeta instanceof DBProcMeta ) {
      ( (DBProcMeta) someMeta ).allocate( 5 );
    }
  }

  @Test
  public void testSerialization() throws KettleException {
    loadSaveTester.testSerialization();
  }
}


text:
#include <err.h>
#include <bits.h>
#include <list.h>
#include <debug.h>
#include <trace.h>
#include <string.h>
#include <printf.h>
#include <malloc.h>
#include <lk/init.h>
#include <dev/keys.h>
#include <kernel/event.h>
#include <kernel/mutex.h>
#include <lib/console.h>

#define LOCAL_TRACE 0

static unsigned long key_bitmap[BITMAP_NUM_WORDS(MAX_KEYS)];

typedef struct {
	struct list_node node;
	uint16_t code;
	uint16_t value;
} key_event_t;

static struct list_node event_queue;
static event_t key_posted;
static mutex_t queue_mutex, bitmap_mutex;

static struct list_node event_sources;
static mutex_t source_mutex;

static int key_poll_thread(void *arg)
{
	for(;;) {
		mutex_acquire(&source_mutex);
		key_event_source_t *source;
		list_for_every_entry(&event_sources, source, key_event_source_t, node) {
			// update time
			lk_time_t current = current_time();
			source->delta = current-source->last;
			source->last = current;

			source->poll(source);
		}
		mutex_release(&source_mutex);

		thread_yield();
	}
	return 0;
}

static void keys_init_threading(uint level)
{
	thread_detach_and_resume(thread_create("key poll thread", &key_poll_thread, NULL, DEFAULT_PRIORITY, DEFAULT_STACK_SIZE));
}

static void keys_init_heap(uint level)
{
	memset(key_bitmap, 0, sizeof(key_bitmap));
	mutex_init(&bitmap_mutex);

	list_initialize(&event_queue);
	event_init(&key_posted, 0, EVENT_FLAG_AUTOUNSIGNAL);
	mutex_init(&queue_mutex);

	list_initialize(&event_sources);
	mutex_init(&source_mutex);
}

void keys_add_source(key_event_source_t* source) {
	source->last = INFINITE_TIME;

	mutex_acquire(&source_mutex);
	list_add_tail(&event_sources, &source->node);
	mutex_release(&source_mutex);
}

int keys_post_event(uint16_t code, int16_t value)
{
	if (code >= MAX_KEYS) {
		LTRACEF("Invalid keycode posted: %d\n", code);
		return ERR_INVALID_ARGS;
	}

	mutex_acquire(&bitmap_mutex);
	if (value)
		bitmap_set(key_bitmap, code);
	else
		bitmap_clear(key_bitmap, code);
	mutex_release(&bitmap_mutex);

	// I guess we shouldn't ignore these
	if(!value) return NO_ERROR;

	// create event
	key_event_t* event = malloc(sizeof(key_event_t));
	event->code = code;
	event->value = value;

	// add event
	mutex_acquire(&queue_mutex);
	list_add_tail(&event_queue, &event->node);
	mutex_init(&queue_mutex);

	// signal
	LTRACEF("key state change: %d %d\n", code, value);
	event_signal(&key_posted, 0);

	return NO_ERROR;
}

int keys_get_state(uint16_t code)
{
	if (code >= MAX_KEYS) {
		LTRACEF("Invalid keycode requested: %d\n", code);
		return ERR_INVALID_ARGS;
	}

	return bitmap_test(key_bitmap, code);
}

void keys_clear_all(void)
{
	mutex_acquire(&bitmap_mutex);
	memset(key_bitmap, 0, sizeof(key_bitmap));
	mutex_release(&bitmap_mutex);

	mutex_acquire(&queue_mutex);
	while(keys_has_next()) {
		key_event_t* event = list_remove_tail_type(&event_queue, key_event_t, node);
		free(event);
	}
	mutex_release(&queue_mutex);
}

int keys_get_next(uint16_t* code, uint16_t* value, bool wait)
{
	// wait for next event
	if(!keys_has_next())
		event_wait(&key_posted);

	// get event
	mutex_acquire(&queue_mutex);
	key_event_t* event = list_remove_tail_type(&event_queue, key_event_t, node);
	mutex_release(&queue_mutex);

	// set result code
	*code = event->code;
	*value = event->value;

	// free event
	free(event);

	return NO_ERROR;
}

int keys_has_next(void)
{
	return !list_is_empty(&event_queue);
}

static int cmd_keys(int argc, const cmd_args *argv)
{
	if (argc < 2) {
	notenoughargs:
		printf("not enough arguments\n");
	usage:
		printf("usage:\n");
		printf("%s post <code> <value>\n", argv[0].str);
		return ERR_GENERIC;
	}

	if (!strcmp(argv[1].str, "post")) {
		if (argc < 4) goto notenoughargs;
		keys_post_event(argv[2].u, argv[3].u);
	} else {
		printf("unknown command\n");
		goto usage;
	}

	return NO_ERROR;
}

STATIC_COMMAND_START
#if LK_DEBUGLEVEL > 0
STATIC_COMMAND("keys", "key commands", &cmd_keys)
#endif
STATIC_COMMAND_END(keys);

LK_INIT_HOOK(keys_threading, &keys_init_threading, LK_INIT_LEVEL_THREADING);
LK_INIT_HOOK(keys_heap, &keys_init_heap, LK_INIT_LEVEL_HEAP);


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package edu.wpi.first.wpilibj.hal;

import java.util.Map;

import com.snobot.simulator.SensorActuatorRegistry;
import com.snobot.simulator.module_wrapper.RelayWrapper;

public class RelayJNI extends DIOJNI
{
    private static RelayWrapper getWrapperFromBuffer(long digital_port_pointer)
    {
        int port = (int) digital_port_pointer;

        Map<Integer, RelayWrapper> relays = SensorActuatorRegistry.get().getRelays();

        if (!relays.containsKey(port))
        {
            relays.put(port, new RelayWrapper(port));
        }

        return relays.get(port);
    }

    public static void setRelayForward(long digital_port_pointer, boolean on)
    {
        getWrapperFromBuffer(digital_port_pointer).setRelayForwards(on);
    }

    public static void setRelayReverse(long digital_port_pointer, boolean on)
    {
        getWrapperFromBuffer(digital_port_pointer).setRelayReverse(on);
    }

    public static boolean getRelayForward(long digital_port_pointer)
    {
        return getWrapperFromBuffer(digital_port_pointer).getRelayForwards();
    }

    public static boolean getRelayReverse(long digital_port_pointer)
    {
        return getWrapperFromBuffer(digital_port_pointer).getRelayReverse();
    }
}


text:
@implementation Endereco
#pragma mark Métodos Públicos

#pragma mark Métodos Privados

@end


text:
/*

twitchClient is a simple CLI app for testing twitchgo API calls.

*/
package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"

	"golang.org/x/oauth2"

	"github.com/ddrboxman/twitchgo"
	"github.com/k0kubun/pp"

	"github.com/motemen/go-loghttp"
	"github.com/urfave/cli"
)

func main() {
	app := cli.NewApp()
	app.EnableBashCompletion = true

	var clientID string
	var accessToken string
	var verbosity int

	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:        "verbose",
			Value:       0,
			Usage:       "verbosity level - 0, 1, 2",
			Destination: &verbosity,
		},

		cli.StringFlag{
			Name:        "client_id",
			Usage:       "Twitch client ID to authorize requests",
			EnvVar:      "TWITCH_CLIENT_ID",
			Destination: &clientID,
		},

		cli.StringFlag{
			Name:        "access_token",
			Usage:       "OAuth access token to authorize certain requests",
			EnvVar:      "TWITCH_ACCESS_TOKEN",
			Destination: &accessToken,
		},
	}

	app.Before = func(c *cli.Context) error {
		if clientID == "" {
			return cli.NewExitError("Twitch client ID was not specified", 1)
		}

		if accessToken == "" {
			twitchClient = twitch.NewTwitchClient(clientID)
		} else {
			token := &oauth2.Token{AccessToken: accessToken}
			client := (&oauth2.Config{}).Client(oauth2.NoContext, token)
			twitchClient = twitch.NewTwitchClientWithHTTPClient(clientID, client)
		}

		if verbosity > 0 {
			// Print HTTP requests and possibly bodies
			http.DefaultTransport = &loghttp.Transport{
				Transport: http.DefaultTransport,
				LogRequest: func(req *http.Request) {
					dump, _ := httputil.DumpRequest(req, verbosity > 1)
					fmt.Printf("--> <%s>: \n%s\n", req.URL, string(dump))
				},
				LogResponse: func(resp *http.Response) {
					dump, _ := httputil.DumpResponse(resp, verbosity > 1)
					fmt.Printf("<-- [%d] <%s>:\n%s\n", resp.StatusCode, resp.Request.URL, string(dump))
				},
			}
		}

		if verbosity > 1 {
			fmt.Printf("Client ID: %s\nAccess Token: %s\n", clientID, accessToken)
		}

		return nil
	}

	app.Commands = appCommands

	err := app.Run(os.Args)
	if err != nil {
		panic(err)
	}
}

var twitchClient twitch.TwitchClient
var appCommands = []cli.Command{
	{
		Name:  "channel",
		Usage: "print a channel's information",
		Action: func(c *cli.Context) error {
			if c.NArg() < 1 {
				return cli.NewExitError("must supply channel name/ID", 126)
			}

			channel, _ := twitchClient.GetChannel(c.Args().Get(0))

			pp.Println(channel)

			return nil
		},
	},

	{
		Name:  "followers",
		Usage: "print two pages of a channel's followers",
		Action: func(c *cli.Context) error {
			if c.NArg() < 1 {
				return cli.NewExitError("must supply channel ID", 126)
			}

			// Get first page
			followers, err := twitchClient.GetFollowersForID(c.Args().Get(0), nil)
			if err != nil {
				return err
			}

			pp.Println(followers)

			// Get second page
			options := twitch.RequestOptions{
				Extra: &url.Values{},
			}
			options.Extra.Add("after", followers.Pagination["cursor"])

			followers, err = twitchClient.GetFollowersForID(c.Args().Get(0), &options)
			if err != nil {
				return err
			}

			pp.Println(followers)

			return nil
		},
	},

	{
		Name:  "subscribers",
		Usage: "print a channel's subscribers",
		Action: func(c *cli.Context) error {
			if c.NArg() < 1 {
				return cli.NewExitError("must supply channel ID", 126)
			}

			var subs []interface{}
			var requestOptions *twitch.RequestOptions
			for {
				// Paginate subscriber data to get all subs
				resp, err := twitchClient.GetSubscribersForID(c.Args().Get(0), requestOptions)
				if err != nil {
					return err
				}

				subs = append(subs, resp.Subscriptions)

				if len(resp.Subscriptions) > 0 {
					requestOptions = &twitch.RequestOptions{}
					requestOptions.Extra = &url.Values{}
					requestOptions.Extra.Add("after", resp.Pagination["cursor"])
				} else {
					break
				}
			}

			pp.Println(subs)

			return nil
		},
	},

	{
		Name:  "streams",
		Usage: "print one or more channel's active streams",
		Action: func(c *cli.Context) error {
			if c.NArg() < 1 {
				return cli.NewExitError("must supply at least one channel ID", 126)
			}

			streams, err := twitchClient.GetStreamsForIDs(nil, append([]string{c.Args().First()}, c.Args().Tail()...)...)
			if err != nil {
				return err
			}

			pp.Println(streams)

			return nil
		},
	},

	{
		Name:  "videos",
		Usage: "print a channel's video info",
		Action: func(c *cli.Context) error {
			if c.NArg() < 1 {
				return cli.NewExitError("must supply a channel ID", 126)
			}

			videos, err := twitchClient.GetVideosForID(c.Args().First(), nil)
			if err != nil {
				return err
			}

			pp.Println(videos)

			return nil
		},
	},
}


text:
package cmd

import (
	"fmt"
	"github.com/jquag/kempt/conf"
	"github.com/jquag/kempt/util"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

func runArchive(cfg *conf.Config, dirStr string) error {
	rootStat, err := os.Stat(dirStr)
	if err != nil {
		return err
	}

	count, err := archiveFiles(cfg, dirStr, rootStat)
	if err != nil {
		return err
	}

	fmt.Printf("Archived %d file(s)\n", count)

	if cfg.ZipAgeDays > 0 {
		return zipArchives(cfg, dirStr)
	}
	return nil
}

func zipArchives(cfg *conf.Config, dirStr string) error {
	//subtract a month so we don't zip the month represented by current date - ZipAgeDays
	maxTime := cfg.ZipTime().AddDate(0, -1, 0)
	count, err := cfg.EachMonth(dirStr, maxTime, zipArchive)
	if err == nil {
		fmt.Printf("Zipped %d folder(s)\n", count)
	}
	return err
}

func zipArchive(monthPath string, maxDate time.Time) (int, error) {
    if !strings.HasSuffix(monthPath, ".zip") {
        err := util.ZipFolder(monthPath)
        if err != nil {
            return 0, fmt.Errorf("Error! Failed to zip %s - %s\n", monthPath, err)
        }
        err = os.RemoveAll(monthPath)
        if err != nil {
            fmt.Printf("Warning. Failed to remove month (%s) folder after zipping - %s\n", monthPath, err)
        } else {
            util.Verbosef("Zipped %s\n", monthPath)
        }
        return 1, nil
    } else {
        return 0, nil
    }
}

func archiveFiles(cfg *conf.Config, dirStr string, rootStat os.FileInfo) (int, error) {
	count := 0
	fileList, err := filepath.Glob(filepath.Join(dirStr, cfg.Pattern))
	if err != nil {
		return 0, err
	}
	archiveTime := cfg.ArchiveTime()
	for _, fname := range fileList {
		fs, e := os.Stat(fname)
		if e != nil {
			fmt.Printf("Error! Failed to consider %s for archiving: %s\n", fname, e)
			continue
		}

        if fs.Name() == conf.ConfName || fs.IsDir() {
            continue
        }

		if fs.ModTime().Before(archiveTime) {
			if newname, e := archiveFile(fname, cfg, rootStat, fs); e != nil {
				fmt.Printf("Error! Failed to archive %s - %s\n", fname, e)
			} else {
				util.Verbosef("Moved %s --> %s\n", fname, newname)
				count += 1
			}
		}
	}
	return count, nil
}

func archiveFile(fname string, cfg *conf.Config, rootStat os.FileInfo, fs os.FileInfo) (newname string, err error) {
	year := strconv.Itoa(fs.ModTime().Year())
	month := fs.ModTime().Month().String()

	archivePath := filepath.Join(cfg.ArchivePath(rootStat.Name()), year, month)
	err = os.MkdirAll(archivePath, rootStat.Mode())
	if err != nil && !os.IsExist(err) {
		return
	}

	zipPath := archivePath + ".zip"
	if util.FileExists(zipPath) {
		//unzip so we can archive the new file ... it will be rezipped later
		if err = util.Unzip(zipPath, archivePath); err != nil {
			return
		}
	}

	newname = filepath.Join(archivePath, fs.Name())
	if _, err = os.Stat(newname); err == nil {
		err = fmt.Errorf("A file of the same name already exists in the archive")
		return
	}
	err = os.Rename(fname, newname)

	return
}


text:
require "notiffany/notifier/base"

module Notiffany
  class Notifier
    # System notifications using the
    # [libnotify](https://github.com/splattael/libnotify) gem.
    #
    # This gem is available for Linux, FreeBSD, OpenBSD and Solaris and sends
    # system notifications to
    # Gnome [libnotify](http://developer.gnome.org/libnotify):
    #
    class Libnotify < Base
      DEFAULTS = {
        transient: false,
        append:    true,
        timeout:   3
      }

      private

      def _supported_hosts
        %w(linux linux-gnu freebsd openbsd sunos solaris)
      end

      def _check_available(_opts = {})
      end

      # Shows a system notification.
      #
      # @param [String] message the notification message body
      # @param [Hash] opts additional notification library options
      # @option opts [String] type the notification type. Either 'success',
      #   'pending', 'failed' or 'notify'
      # @option opts [String] title the notification title
      # @option opts [String] image the path to the notification image
      # @option opts [Boolean] transient keep the notifications around after
      #   display
      # @option opts [Boolean] append append onto existing notification
      # @option opts [Number, Boolean] timeout the number of seconds to display
      #   (1.5 (s), 1000 (ms), false)
      #
      def _perform_notify(message, opts = {})
        opts = opts.merge(
          summary: opts[:title],
          icon_path: opts[:image],
          body: message,
          urgency: opts[:urgency] || (opts[:type] == "failed" ? :normal : :low)
        )

        ::Libnotify.show(opts)
      end
    end
  end
end


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Document</title>

a

b

c

d

  <button onclick="inspector.toggleActive();">toggleActive</button>


text:
package test.xml.data;

import gov.nih.nci.cacoresdk.domain.other.levelassociation.Card;
import gov.nih.nci.cacoresdk.domain.other.levelassociation.Deck;
import gov.nih.nci.cacoresdk.domain.other.levelassociation.Hand;
import gov.nih.nci.cacoresdk.domain.other.levelassociation.Suit;
import gov.nih.nci.iso21090.Ii;

import java.util.Collection;
import java.util.Iterator;

public class LevelAssociationXMLDataTest extends SDKXMLDataTestBase
{
	public static String getTestCaseName()
	{
		return "Level association XML Data Test Case";
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch1() throws Exception
	{
		Hand searchObject = new Hand();
		Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.other.levelassociation.Hand",searchObject );

		assertNotNull(results);
		assertEquals(5,results.size());

		for(Iterator i = results.iterator();i.hasNext();)
		{
			Hand result = (Hand)i.next();
			toXML(result);

			validateClassElements(result);
			validateIso90210Element(result, "id", "extension", result.getId().getExtension());

			assertTrue(validateXMLData(result, searchObject.getClass()));

			Hand result2 = (Hand)fromXML(result);

			assertNotNull(result2);
			assertNotNull(result2.getId().getExtension());
			assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
		}
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch2() throws Exception
	{
		Card searchObject = new Card();
		Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.other.levelassociation.Card",searchObject );

		assertNotNull(results);
		assertEquals(53,results.size());

		for(Iterator i = results.iterator();i.hasNext();)
		{
			Card result = (Card)i.next();
			toXML(result);

			validateClassElements(result);
			validateIso90210Element(result, "id", "extension", result.getId().getExtension());
			if (result.getId().getExtension().equals("1")) {// Only row with id=1 has an image
				validateIso90210Element(result, "image", "value", result.getImage().getValue());
			}
			validateIso90210Element(result, "name", "value", result.getName().getValue());

			assertTrue(validateXMLData(result, searchObject.getClass()));

			Card result2 = (Card)fromXML(result);

			assertNotNull(result2);
			assertNotNull(result2.getId().getExtension());   assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
			if (new Integer(result2.getId().getExtension()) == 1)
				assertNotNull(result2.getImage());// Only row with id=1 has an image
			assertNotNull(result2.getName());
		}
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch3() throws Exception
	{
		Suit searchObject = new Suit();
		Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.other.levelassociation.Suit",searchObject );

		assertNotNull(results);
		assertEquals(4,results.size());

		for(Iterator i = results.iterator();i.hasNext();)
		{
			Suit result = (Suit)i.next();
			toXML(result);

			validateClassElements(result);
			validateIso90210Element(result, "id", "extension", result.getId().getExtension());
			validateIso90210Element(result, "name", "value", result.getName().getValue());

			assertTrue(validateXMLData(result, searchObject.getClass()));

			Suit result2 = (Suit)fromXML(result);

			assertNotNull(result2);
			assertNotNull(result2.getId().getExtension());   assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
			assertNotNull(result2.getName());
		}
	}

	/**
	 * Uses Nested Search Criteria for search
	 * Verifies that the results are returned
	 * Verifies size of the result set
	 * Verifies that none of the attribute is null
	 *
	 * @throws Exception
	 */
	public void testEntireObjectNestedSearch4() throws Exception
	{
		Deck searchObject = new Deck();
		Collection results = getApplicationService().search("gov.nih.nci.cacoresdk.domain.other.levelassociation.Deck",searchObject );

		assertNotNull(results);
		assertEquals(1,results.size());

		for(Iterator i = results.iterator();i.hasNext();)
		{
			Deck result = (Deck)i.next();
			toXML(result);

			validateClassElements(result);
			validateIso90210Element(result, "id", "extension", result.getId().getExtension());
			validateIso90210Element(result, "name", "value", result.getName().getValue());

			assertTrue(validateXMLData(result, searchObject.getClass()));

			Deck result2 = (Deck)fromXML(result);

			assertNotNull(result2);
			assertNotNull(result2.getId().getExtension());   assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());
			assertNotNull(result2.getName());
		}
	}

	/**
	 * Verifies all the associations in the object graph
	 *
	 * @throws Exception
	 */
	public void testAssociationsInBeans() throws Exception {
		Hand searchObject = new Hand();
		Ii ii = new Ii();
		ii.setExtension("1");
		searchObject.setId(ii);
		Collection results = getApplicationService().search(
				"gov.nih.nci.cacoresdk.domain.other.levelassociation.Card",searchObject);

		assertNotNull(results);
		assertEquals(3, results.size());

		Iterator i = results.iterator();
		Card card = (Card) i.next();
		toXML(card);
		Card result2 = (Card) fromXML(card);

		assertNotNull(result2);
		assertNotNull(result2.getId().getExtension());
		assertEquals(II_ROOT_GLOBAL_CONSTANT_VALUE,result2.getId().getRoot());

		validateAssociation(card, "Suit", "suit", false);

		Suit suit = result2.getSuit();
		assertNotNull(suit);
		assertNull(suit.getCardCollection());
	}
}


text:
if (typeof global != 'undefined') require('./load.test').load(global);
if (node) junjo_test();

// test start
function junjo_test() {

  var $j = new Junjo();
  $j(function() {
    this.cb;
    this.terminate();
  })
  .timeout(100);

  $j.run();
}