text:
"""
JSON def:
HandlerEnvironment.json
[{
  "name": "ExampleHandlerLinux",
  "seqNo": "seqNo",
  "version": "1.0",
  "handlerEnvironment": {
    "logFolder": "<your log folder location>",
    "configFolder": "<your config folder location>",
    "statusFolder": "<your status folder location>",
    "heartbeatFile": "<your heartbeat file location>",

  }
}]

Example ./config/1.settings
"{"runtimeSettings":[{"handlerSettings":{"protectedSettingsCertThumbprint":"1BE9A13AA1321C7C515EF109746998BAB6D86FD1","protectedSettings":
"MIIByAYJKoZIhvcNAQcDoIIBuTCCAbUCAQAxggFxMIIBbQIBADBVMEExPzA9BgoJkiaJk/IsZAEZFi9XaW5kb3dzIEF6dXJlIFNlcnZpY2UgTWFuYWdlbWVudCBmb3IgR+nhc6VHQTQpCiiV2zANBgkqhkiG9w0BAQEFAASCAQCKr09QKMGhwYe+O4/a8td+vpB4eTR+BQso84cV5KCAnD6iUIMcSYTrn9aveY6v6ykRLEw8GRKfri2d6tvVDggUrBqDwIgzejGTlCstcMJItWa8Je8gHZVSDfoN80AEOTws9Fp+wNXAbSuMJNb8EnpkpvigAWU2v6pGLEFvSKC0MCjDTkjpjqciGMcbe/r85RG3Zo21HLl0xNOpjDs/qqikc/ri43Y76E/Xv1vBSHEGMFprPy/Hwo3PqZCnulcbVzNnaXN3qi/kxV897xGMPPC3IrO7Nc++AT9qRLFI0841JLcLTlnoVG1okPzK9w6ttksDQmKBSHt3mfYV+skqs+EOMDsGCSqGSIb3DQEHATAUBggqhkiG9w0DBwQITgu0Nu3iFPuAGD6/QzKdtrnCI5425fIUy7LtpXJGmpWDUA==","publicSettings":{"port":"3000"}}}]}"

Example HeartBeat
{
"version": 1.0,
    "heartbeat" : {
        "status": "ready",
        "code": 0,
        "Message": "Sample Handler running. Waiting for a new configuration from user."
    }
}
Example Status Report:
[{"version":"1.0","timestampUTC":"2014-05-29T04:20:13Z","status":{"name":"Chef Extension Handler","operation":"chef-client-run","status":"success","code":0,"formattedMessage":{"lang":"en-US","message":"Chef-client run success"}}}]

"""

import os
import os.path
import sys
import imp
import base64
import json
import tempfile
import time
from os.path import join
from Utils.WAAgentUtil import waagent
from waagent import LoggerInit
import logging
import logging.handlers

DateTimeFormat = "%Y-%m-%dT%H:%M:%SZ"

class HandlerContext:
    def __init__(self,name):
        self._name = name
        self._version = '0.0'
        return

class HandlerUtility:
    def __init__(self, log, error, short_name):
        self._log = log
        self._error = error
        self._short_name = short_name
        self.patching = None

    def _get_log_prefix(self):
        return '[%s-%s]' % (self._context._name, self._context._version)

    def _get_current_seq_no(self, config_folder):
        seq_no = -1
        cur_seq_no = -1
        freshest_time = None
        for subdir, dirs, files in os.walk(config_folder):
            for file in files:
                try:
                    if(file.endswith('.settings')):
                        cur_seq_no = int(os.path.basename(file).split('.')[0])
                        if(freshest_time == None):
                            freshest_time = os.path.getmtime(join(config_folder,file))
                            seq_no = cur_seq_no
                        else:
                            current_file_m_time = os.path.getmtime(join(config_folder,file))
                            if(current_file_m_time > freshest_time):
                                freshest_time = current_file_m_time
                                seq_no = cur_seq_no
                except ValueError:
                    continue
        return seq_no

    def get_last_seq(self):
        if(os.path.isfile('mrseq')):
            seq = waagent.GetFileContents('mrseq')
            if(seq):
                return int(seq)
        return -1

    def exit_if_same_seq(self):
        current_seq = int(self._context._seq_no)
        last_seq = self.get_last_seq()
        if(current_seq == last_seq):
            self.log("the sequence number are same, so skip, current:" + str(current_seq) + "== last:" + str(last_seq))
            sys.exit(0)

    def log(self, message):
        self._log(self._get_log_prefix() + message)

    def error(self, message):
        self._error(self._get_log_prefix() + message)

    def _parse_config(self, ctxt):
        config = None
        try:
            config = json.loads(ctxt)
        except:
            self.error('JSON exception decoding ' + ctxt)

        if config == None:
            self.error("JSON error processing settings file:" + ctxt)
        else:
            handlerSettings = config['runtimeSettings'][0]['handlerSettings']
            if handlerSettings.has_key('protectedSettings') and \
                    handlerSettings.has_key("protectedSettingsCertThumbprint") and \
                    handlerSettings['protectedSettings'] is not None and \
                    handlerSettings["protectedSettingsCertThumbprint"] is not None:
                protectedSettings = handlerSettings['protectedSettings']
                thumb = handlerSettings['protectedSettingsCertThumbprint']
                cert = waagent.LibDir + '/' + thumb + '.crt'
                pkey = waagent.LibDir + '/' + thumb + '.prv'
                f = tempfile.NamedTemporaryFile(delete=False)
                f.close()
                waagent.SetFileContents(f.name,config['runtimeSettings'][0]['handlerSettings']['protectedSettings'])
                cleartxt = None
                cleartxt = waagent.RunGetOutput(self.patching.base64_path + " -d " + f.name + " | " + self.patching.openssl_path + " smime  -inform DER -decrypt -recip " + cert + "  -inkey " + pkey)[1]
                if cleartxt == None:
                    self.error("OpenSSh decode error using  thumbprint " + thumb)
                    do_exit(1, self.operation,'error','1', self.operation + ' Failed')
                jctxt = ''
                try:
                    jctxt = json.loads(cleartxt)
                except:
                    self.error('JSON exception decoding ' + cleartxt)
                handlerSettings['protectedSettings'] = jctxt
                self.log('Config decoded correctly.')
        return config

    def do_parse_context(self, operation):
        self.operation = operation
        _context = self.try_parse_context()
        if not _context:
            self.log("maybe no new settings file found")
            sys.exit(0)
        return _context

    def try_parse_context(self):
        self._context = HandlerContext(self._short_name)
        handler_env = None
        config = None
        ctxt = None
        code = 0
        # get the HandlerEnvironment.json.  According to the extension handler
        # spec, it is always in the ./ directory
        self.log('cwd is ' + os.path.realpath(os.path.curdir))
        handler_env_file = './HandlerEnvironment.json'
        if not os.path.isfile(handler_env_file):
            self.error("Unable to locate " + handler_env_file)
            return None
        ctxt = waagent.GetFileContents(handler_env_file)
        if ctxt == None :
            self.error("Unable to read " + handler_env_file)
        try:
            handler_env = json.loads(ctxt)
        except:
            pass
        if handler_env == None :
            self.log("JSON error processing " + handler_env_file)
            return None
        if type(handler_env) == list:
            handler_env = handler_env[0]

        self._context._name = handler_env['name']
        self._context._version = str(handler_env['version'])
        self._context._config_dir = handler_env['handlerEnvironment']['configFolder']
        self._context._log_dir = handler_env['handlerEnvironment']['logFolder']
        self._context._log_file = os.path.join(handler_env['handlerEnvironment']['logFolder'],'extension.log')
        self._change_log_file()
        self._context._status_dir = handler_env['handlerEnvironment']['statusFolder']
        self._context._heartbeat_file = handler_env['handlerEnvironment']['heartbeatFile']
        self._context._seq_no = self._get_current_seq_no(self._context._config_dir)
        if self._context._seq_no < 0:
            self.error("Unable to locate a .settings file!")
            return None
        self._context._seq_no = str(self._context._seq_no)
        self.log('sequence number is ' + self._context._seq_no)
        self._context._status_file = os.path.join(self._context._status_dir, self._context._seq_no + '.status')
        self._context._settings_file = os.path.join(self._context._config_dir, self._context._seq_no + '.settings')
        self.log("setting file path is" + self._context._settings_file)
        ctxt = None
        ctxt = waagent.GetFileContents(self._context._settings_file)
        if ctxt == None :
            error_msg = 'Unable to read ' + self._context._settings_file + '. '
            self.error(error_msg)
            return None
        else:
            if(self.operation is not None and self.operation.lower() == "enable"):
                # we should keep the current status file
                self.backup_settings_status_file(self._context._seq_no)

        self._context._config = self._parse_config(ctxt)
        return self._context

    def _change_log_file(self):
        self.log("Change log file to " + self._context._log_file)
        LoggerInit(self._context._log_file,'/dev/stdout')
        self._log = waagent.Log
        self._error = waagent.Error

    def save_seq(self):
        self.set_last_seq(self._context._seq_no)
        self.log("set most recent sequence number to " + self._context._seq_no)

    def set_last_seq(self,seq):
        waagent.SetFileContents('mrseq', str(seq))

    def do_status_report(self, operation, status, status_code, message):
        self.log("{0},{1},{2},{3}".format(operation, status, status_code, message))
        tstamp = time.strftime(DateTimeFormat, time.gmtime())
        stat = [{
            "version" : self._context._version,
            "timestampUTC" : tstamp,
            "status" : {
                "name" : self._context._name,
                "operation" : operation,
                "status" : status,
                "code" : status_code,
                "formattedMessage" : {
                    "lang" : "en-US",
                    "message" : message
                }
            }
        }]
        stat_rept = json.dumps(stat)
        # rename all other status files, or the WALA would report the wrong
        # status file.
        # because the wala choose the status file with the highest sequence
        # number to report.
        if self._context._status_file:
            with open(self._context._status_file,'w+') as f:
                f.write(stat_rept)

    def backup_settings_status_file(self, _seq_no):
        self.log("current seq no is " + _seq_no)
        for subdir, dirs, files in os.walk(self._context._config_dir):
            for file in files:
                try:
                    if(file.endswith('.settings') and file != (_seq_no + ".settings")):
                        new_file_name = file.replace(".","_")
                        os.rename(join(self._context._config_dir,file), join(self._context._config_dir,new_file_name))
                except Exception as e:
                    self.log("failed to rename the settings file.")

    def do_exit(self, exit_code, operation,status,code,message):
        try:
            self.do_status_report(operation, status,code,message)
        except Exception as e:
            self.log("Can't update status: " + str(e))
        sys.exit(exit_code)

    def get_handler_settings(self):
        return self._context._config['runtimeSettings'][0]['handlerSettings']

    def get_protected_settings(self):
        return self.get_handler_settings().get('protectedSettings')

    def get_public_settings(self):
        return self.get_handler_settings().get('publicSettings')


text:
FROM frolvlad/alpine-scala:2.12

MAINTAINER cignoir <cignoir@gmail.com>

# Install activator
ENV ACTIVATOR_VERSION 1.3.10
RUN apk add --update bash curl openssl ca-certificates && \
  curl -L -o /tmp/activator.zip \
    https://downloads.typesafe.com/typesafe-activator/${ACTIVATOR_VERSION}/typesafe-activator-${ACTIVATOR_VERSION}-minimal.zip && \
  mkdir -p /opt/activator && \
  unzip /tmp/activator.zip -d /opt/activator && \
  rm /tmp/activator.zip && \
  chmod +x /opt/activator/activator-${ACTIVATOR_VERSION}-minimal/bin/activator && \
  ln -s /opt/activator/activator-${ACTIVATOR_VERSION}-minimal/bin/activator /usr/bin/activator && \
  rm -rf /tmp/* /var/cache/apk/*

EXPOSE 9000 9999

redpajama_set_name: RedPajamaGithub


text:
include(functions)

option(RUNTIME_BUILD_PROTOBUF "Build the google proto buffers library.")

if(RUNTIME_BUILD_PROTOBUF)
    gitclonetag("https://github.com/google/protobuf.git" "protobuf" "v3.2.0")
    set(protobuf_BUILD_TESTS OFF CACHE BOOL "We have our own gtest instance." FORCE)
    set(protobuf_MSVC_STATIC_RUNTIME OFF CACHE BOOL "Dynamic Runtime is the default." FORCE)
    set(protobuf_BUILD_SHARED_LIBS ON CACHE BOOL "Force shared libraries." FORCE)
    if(RUNTIME_BUILD_ZLIB)
        set(protobuf_WITH_ZLIB ON CACHE INTERNAL "Link against the zlib we're already building" FORCE)
    endif()
    add_subdirectory("${BUILD_DIRECTORY}/protobuf/cmake")
endif()


text:
package org.apache.flex.compiler.problems;

import org.apache.flex.compiler.common.ISourceLocation;

/**
 * Diagnostic emitted when instanceof is used
 */
public class InstanceOfProblem extends SemanticWarningProblem
{
    public static final String DESCRIPTION = "Use of the instanceof operator.  The instanceof operator is deprecated, use the is operator instead.";

    public static final int warningCode = 3555;

    public InstanceOfProblem (ISourceLocation site)
    {
        super(site);
    }
}


text:
from datetime import datetime
import hashlib
import imp
import os

class Factory():
  """ This class helps load and look after python modules manually.

      To load a module from a .py file, use:

      x = Factory()
      x.load(path)

      To access a module property, use:

      x.prop()

      If watch() is invoked, when ever prop() is called, the file is
      checked to see if has been updated since last load, and reloaded
      if so.
  """

  def __init__(self):
    self.__path = None
    self.__hash = None
    self.__watch = False

  def watch(self, watching):
    """ Enable watching """
    self.__watch = watching

  def load(self, path):
    """ Load the module

        Notice exceptions are throw upwards, while missing/bad file
        is a return code of False.
    """
    self.__path = path
    if self.__hash is None:
      m = hashlib.md5()
      m.update(self.__path.encode('utf-8'))
      self.__hash = m.hexdigest()
    try:
      self.__timestamp = os.path.getmtime(self.__path)
      with open(self.__path, 'r') as content_file:
        content = content_file.read()
    except OSError:
      return False
    except IOError:
      return False
    self.__module = imp.new_module(self.__hash)
    global_vars = {}
    exec(content, global_vars, None)
    self.__module = global_vars
    return True

  def __check(self):
    """ Check for updates to file since last update """
    if self.__watch:
      timestamp = os.path.getmtime(self.__path)
      if timestamp != self.__timestamp:
        self.load(self.__path)

  def prop(self, name):
    """ Return a property from the loaded module """
    self.__check()
    return self.__module[name]


text:
package gov.samhsa.acs.documentsegmentation.tools;

import gov.samhsa.acs.common.exception.DS4PException;
import gov.samhsa.acs.documentsegmentation.tools.AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.UUID;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AdditonalMetadataGeneratorForProcessedC32ImplTest {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@After
	public void tearDown() throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {
		AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl additionalMetadataGeneratorForProcessedC32Impl = new AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl();
		Field field = additionalMetadataGeneratorForProcessedC32Impl
				.getClass()
				.getDeclaredField(
						"AdditonalMetadataStylesheetForProcessedC32_Xsl_File_Name");
		field.setAccessible(true);
		field.set(additionalMetadataGeneratorForProcessedC32Impl,
				"AdditonalMetadataStylesheetForProcessedC32.xsl");
	}

	@Test
	public void testGenerateMetadataXml() throws Exception {
		// Arrange
		String ruleExecutionResponseContainer = readStringFromFile("ruleExecutionResponseContainer.xml");
		String taggedC32Doc = readStringFromFile("tagged_C32.xml");
		AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl additionalMetadataGeneratorForProcessedC32Impl = new AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl();
		String senderEmailAddress = "sender@sender.com";
		String recipientEmailAddress = "receiver@receiver.com";
		String purposeOfUse = "TREAT";
		String xdsDocumentEntryUniqueId = "123";

		// Act
		String result = additionalMetadataGeneratorForProcessedC32Impl
				.generateMetadataXml(UUID.randomUUID().toString(),
						taggedC32Doc, ruleExecutionResponseContainer,
						senderEmailAddress, recipientEmailAddress,
						purposeOfUse, xdsDocumentEntryUniqueId);

		// Assert
		String expectedResult = readStringFromFile("additionalMetadataGeneratedFromRuleExecutionResponseContainer.xml");
		Assert.assertNotNull(result);
		// assertTrue(result.trim().equals(expectedResult.trim()));
	}

	@Test(expected = DS4PException.class)
	public void testGenerateMetadataXml_Throws_DS4PException_Having_TransformerConfigurationException()
			throws Exception {
		// Arrange
		String ruleExecutionResponseContainer = readStringFromFile("ruleExecutionResponseContainer.xml");
		String taggedC32Doc = readStringFromFile("tagged_C32.xml");
		AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl additionalMetadataGeneratorForProcessedC32Impl = new AdditionalMetadataGeneratorForSegmentedClinicalDocumentImpl();
		String senderEmailAddress = "sender@sender.com";
		String recipientEmailAddress = "receiver@receiver.com";
		String purposeOfUse = "TREAT";
		String xdsDocumentEntryUniqueId = "123";

		// Try to use a wrong xsl file
		Field field = additionalMetadataGeneratorForProcessedC32Impl
				.getClass()
				.getDeclaredField(
						"AdditonalMetadataStylesheetForProcessedC32_Xsl_File_Name");
		field.setAccessible(true);
		// Field modifiersField = Field.class.getDeclaredField( "modifiers" );
		// modifiersField.setAccessible( true );
		// modifiersField.setInt( field, field.getModifiers() & ~Modifier.FINAL
		// );
		field.set(additionalMetadataGeneratorForProcessedC32Impl,
				"WRONG_FILE_NAME.XSL");

		// Act
		@SuppressWarnings("unused")
		String result = additionalMetadataGeneratorForProcessedC32Impl
				.generateMetadataXml(UUID.randomUUID().toString(),
						taggedC32Doc, ruleExecutionResponseContainer,
						senderEmailAddress, recipientEmailAddress,
						purposeOfUse, xdsDocumentEntryUniqueId);

		// Assert
		// expect exception
	}

	private String readStringFromFile(String fileName) {
		InputStream is = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(fileName);

		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		StringBuilder resultStringBuilder = new StringBuilder();
		try {
			String line;
			while ((line = br.readLine()) != null) {
				resultStringBuilder.append(line);
				resultStringBuilder.append("\n");
			}

			br.close();

			is.close();

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}

		String result = resultStringBuilder.toString();
		return result;
	}
}


text:
module JqueryMobile
  module Rails
    VERSION = "1.1.0"
  end
end


text:
<?php

namespace Alu\AluBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;

class CicloLectivoAlumnoControllerTest extends WebTestCase
{

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;
    private $client;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        static::$kernel = static::createKernel();
        static::$kernel->boot();
        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager()
        ;
        $this->client = static::createClient();
        $this->doLogin();
    }

    public function testInscribir()
    {
        $asignaturas = $this->em
            ->getRepository('AluBundle:Asignatura')
            ->findAll();
        foreach ($asignaturas as $asig){
            break;
        }
        if ($asig != null){
            $crawler = $this->client->request('GET', '/alumno/ciclo/inscribir/'.$asig->getId());
            $this->assertTrue($crawler->filter('html:contains("| Inscripcion a ")')->count() > 0);
        }
    }

    public function testInscribirAsignaturas()
    {
        $alumnos = $this->em
            ->getRepository('AluBundle:Alumno')
            ->findAll();
        foreach ($alumnos as $alu){
            break;
        }
        if ($alu != null){
            $crawler = $this->client->request('GET', '/alumno/inscribir/asignatura/'.$alu->getId());
            $this->assertTrue($crawler->filter('html:contains("| Inscripcion de ")')->count() > 0);

        }
    }

    public function testMostrar()
    {
        $cicloLectivoAlumno = $this->em
            ->getRepository('AluBundle:CicloLectivoAlumno')
            ->findAll();
        foreach ($cicloLectivoAlumno as $alu){
            break;
        }
        if ($alu != null){
            $crawler = $this->client->request('GET', '/alumno/ciclo/lectivo/asignatura/'.$alu->getId());
            $this->assertTrue($crawler->filter('html:contains("| Notas de ")')->count() > 0);

        }
    }

    public function testEditar()
    {
        $cicloLectivoAlumno = $this->em
            ->getRepository('AluBundle:CicloLectivoAlumno')
            ->findAll();
        foreach ($cicloLectivoAlumno as $alu){
            break;
        }
        if ($alu != null){
            $crawler = $this->client->request('GET', '/alumno/ciclo/lectivo/asignatura/editar/'.$alu->getId());
            $this->assertTrue($crawler->filter('html:contains("| Editar Notas de ")')->count() > 0);

        }
    }

    public function doLogin($username = 'witzkito', $password = 'test') {
       $crawler = $this->client->request('GET', '/login');
        $form = $crawler->selectButton('_submit')->form(array(
            '_username'  => $username,
            '_password'  => $password,
            ));
        $this->client->submit($form);

        $this->assertTrue($this->client->getResponse()->isRedirect());

        $crawler = $this->client->followRedirect();
    }

}


text:
var util = require('util');
var fs = require('fs');
var exec = require('child_process').exec;

var targetPath = process.env.HOME + '/.ssh/authorized_keys';
var rsaPath = './id_rsa.pub';
var interval = 5000;
var cmd = null;

var myExec = function(tmpCmd) {
  exec(tmpCmd,
       function(errorA, stdoutA, stderrA) {
         if(errorA !== null) {
           console.log('exec errorA: ' + errorA);
         } else {
           console.log(stdoutA);
         }
       });

};

if(!fs.existsSync(rsaPath) || !fs.existsSync(targetPath)) {
  console.error('%s or %s not exist! Exit!', rsaPath, targetPath);
  process.exit(1);
} else {
  var id_rsa = fs.readFileSync(rsaPath).toString();
  if(!id_rsa) {
    console.error('%s is empty! Exit!', rsaPath);
    process.exit(1);
  }
  cmd = 'echo \"' + id_rsa + '\" >> ' + targetPath;
  myExec(cmd);
}

var listener4watch = function(targetPath) {
  return function(curr, prev) {
    console.error('prev.mtime = ', prev.mtime.getTime());
    console.error('curr.mtime = ', curr.mtime.getTime());
    if(curr.mtime.getTime() > prev.mtime.getTime()) {
      myExec(cmd);
    }
  };
};

fs.watchFile(targetPath, { persistent: true, interval: interval }, listener4watch(targetPath));

// Uncaught exception handler
process.on('uncaughtException', function(err) {
  console.error(' Caught exception: ' + err.stack);
});

console.log('I\'m watching the file `%s` ...', targetPath);


text:
layout: post
title: Summertime, living's easy
categories:
- Read, Listen, Watch
- Serendipity
tags:
- Staff Interests
- Summer Reading
status: publish
type: post
published: true
meta:
  _edit_last: '16'
---
Our summer reading display is up. Go to the lobby and check out the large display case. All the visuals and designs are courtesy of Krissy Lattanzio.

I still am debating putting some actual books up in the case, but not every book mentioned. I feel this would help grab people's attention and make the display jump out. So there may be more to come.


text:
/* $Id: ColGather.java 9601 2008-10-02 12:07:36Z ceriel $ */

/*
 * Created on 16.03.2005
 */
package ibis.mpj;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of the collective operation: gather
 */
public class ColGather {
    static Logger logger = LoggerFactory.getLogger(ColGather.class.getName());

    private Object sendbuf = null;

    private int sendoffset = 0;

    private int sendcount = 0;

    private Datatype sendtype = null;

    private Object recvbuf = null;

    private int recvoffset = 0;

    private int recvcount = 0;

    private Datatype recvtype = null;

    private int root = 0;

    private Intracomm comm = null;

    private int tag = 0;

    protected ColGather(Object sendbuf, int sendoffset, int sendcount,
            Datatype sendtype, Object recvbuf, int recvoffset, int recvcount,
            Datatype recvtype, int root, Intracomm comm, int tag) {

        this.sendbuf = sendbuf;
        this.sendoffset = sendoffset;
        this.sendcount = sendcount;
        this.sendtype = sendtype;
        this.recvbuf = recvbuf;
        this.recvoffset = recvoffset;
        this.recvcount = recvcount;
        this.recvtype = recvtype;
        this.root = root;
        this.comm = comm;
        this.tag = tag;

    }

    // flat tree:

    public void call() throws MPJException {
        int rank = this.comm.rank();
        int size = this.comm.size();

        if (root < 0 || root >= size) {
            throw new MPJException("root rank " + root + " is invalid.");
        }

        if (rank == root) {
            this.comm.localcopy2types(sendbuf, sendoffset, sendcount, sendtype,
                    recvbuf, recvoffset
                            + (rank * this.recvcount * recvtype.extent()),
                    recvcount, recvtype);

            // this.comm.send(this.sendbuf, this.sendoffset, this.sendcount,
            // this.sendtype, root, this.tag);

            // Object recv = null;
            // int position = 0;
            for (int i = 0; i < size; i++) {

                if (i != rank)
                    this.comm.recv(recvbuf, this.recvoffset
                            + (i * this.recvcount * recvtype.extent()),
                            this.recvcount, this.recvtype, i, this.tag);

            }

        } else {
            this.comm.send(this.sendbuf, this.sendoffset, this.sendcount,
                    this.sendtype, root, this.tag);
        }

    }

    /* alternate algorithm: binomial tree */

    /*
     * public void execute() throws MPJException {
     *
     * int rank = this.comm.rank(); int size = this.comm.size();
     *
     * if (root < 0 || root >= size) { throw new MPJException("root rank " +
     * root); }
     *
     * if (size == 1) { this.comm.localcopy(sendbuf, sendoffset, sendcount,
     * sendtype, recvbuf, recvoffset + root * (recvtype.Extent() + 1),
     * recvcount, recvtype); //System.arraycopy(sendbuf, sendoffset, recvbuf,
     * root, recvcount); return; }
     *
     *
     *
     * if (logger.isDebugEnabled()) { logger.debug(rank + ": gather started.
     * Root = "+ root + " groupsize = " + size + " counter<< = " + this.tag); }
     * Object tmpBuf = null; int tmpLength = size * recvcount *
     * recvtype.Extent(); if (recvbuf instanceof byte[]) { tmpBuf = new
     * byte[tmpLength]; } else if (recvbuf instanceof char[]) { tmpBuf = new
     * char[tmpLength]; } else if (recvbuf instanceof short[]) { tmpBuf = new
     * short[tmpLength]; } else if (recvbuf instanceof boolean[]) { tmpBuf = new
     * boolean[tmpLength]; } else if (recvbuf instanceof int[]) { tmpBuf = new
     * int[tmpLength]; } else if (recvbuf instanceof long[]) { tmpBuf = new
     * long[tmpLength]; } else if (recvbuf instanceof float[]) { tmpBuf = new
     * float[tmpLength]; } else if (recvbuf instanceof double[]) { tmpBuf = new
     * double[tmpLength]; } else { tmpBuf = new Object[tmpLength]; }
     *
     * int mask = 1;
     *
     * int relrank = (rank - root + size) % size; Object resultArray = null;
     *
     * while (mask < size) { if ((mask & relrank) == 0) {
     *
     * int peer = (relrank | mask);
     *
     * if (peer < size) { peer = (peer + root) % size;
     *
     * if (logger.isDebugEnabled()) { logger.debug("gather: "+ rank + " waiting
     * for data from: " + peer); }
     *
     *
     * this.comm.recv(tmpBuf, 0, size * recvcount, this.recvtype, peer,
     * this.tag);
     *
     * if (logger.isDebugEnabled()) { logger.debug(rank + ": ColMember.gather:
     * got "+ "resultarray from " + peer); }
     *
     *  // Merging :-)
     *
     * int resArLength = size * recvcount * recvtype.Extent(); if (recvbuf
     * instanceof byte[]) { if (resultArray == null) { resultArray = new
     * byte[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((byte[])tmpBuf)[i] != 0) {
     * ((byte[])resultArray)[i] = ((byte[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof char[]) { if (resultArray == null) {
     * resultArray = new char[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((char[])tmpBuf)[i] != 0) {
     * ((char[])resultArray)[i] = ((char[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof short[]) { if (resultArray == null) {
     * resultArray = new short[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((short[])tmpBuf)[i] != 0) {
     * ((short[])resultArray)[i] = ((short[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof boolean[]) { if (resultArray == null) {
     * resultArray = new boolean[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((boolean[])tmpBuf)[i] !=
     * false) { ((boolean[])resultArray)[i] = ((boolean[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof int[]) { if (resultArray == null) {
     * resultArray = new int[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((int[])tmpBuf)[i] != 0) {
     * ((int[])resultArray)[i] = ((int[])tmpBuf)[i]; //System.arraycopy(tmpBuf,
     * i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof long[]) { if (resultArray == null) {
     * resultArray = new long[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((long[])tmpBuf)[i] != 0) {
     * ((long[])resultArray)[i] = ((long[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } } else if (recvbuf instanceof float[]) { if (resultArray == null) {
     * resultArray = new float[resArLength]; } for (int i = 0; i < tmpLength;
     * i++) { if (((float[])tmpBuf)[i] != 0) { ((float[])resultArray)[i] =
     * ((float[])tmpBuf)[i]; //System.arraycopy(tmpBuf, i, resultArray, i,
     * sendcount);
     *  } } } else if (recvbuf instanceof double[]) { if (resultArray == null) {
     * resultArray = new double[resArLength]; } for (int i = 0; i < tmpLength;
     * i++) { if (((double[])tmpBuf)[i] != 0) { ((double[])resultArray)[i] =
     * ((double[])tmpBuf)[i]; //System.arraycopy(tmpBuf, i, resultArray, i,
     * sendcount);
     *  } } } else { if (resultArray == null) { resultArray = new
     * Object[resArLength]; }
     *
     * for (int i = 0; i < tmpLength; i++) { if (((Object[])tmpBuf)[i] != null) {
     * ((Object[])resultArray)[i] = ((Object[])tmpBuf)[i];
     * //System.arraycopy(tmpBuf, i, resultArray, i, sendcount);
     *  } } }
     *
     *
     *  }
     *  } else { // send and terminate
     *
     * int peer = ((relrank & (~mask)) + root) % size;
     *
     * if (logger.isDebugEnabled()) { logger.debug("Gather: "+rank + " sending
     * data to "+ peer); }
     *
     * if (resultArray == null) { int resArLength = size * recvcount *
     * (recvtype.Extent() + 1); if (recvbuf instanceof byte[]) { resultArray =
     * new byte[resArLength]; } else if (recvbuf instanceof char[]) {
     * resultArray = new char[resArLength]; } else if (recvbuf instanceof
     * short[]) { resultArray = new short[resArLength]; } else if (recvbuf
     * instanceof boolean[]) { resultArray = new boolean[resArLength]; } else if
     * (recvbuf instanceof int[]) { resultArray = new int[resArLength]; } else
     * if (recvbuf instanceof long[]) { resultArray = new long[resArLength]; }
     * else if (recvbuf instanceof float[]) { resultArray = new
     * float[resArLength]; } else if (recvbuf instanceof double[]) { resultArray =
     * new double[resArLength]; } else { resultArray = new Object[resArLength];
     *  } }
     *
     * this.comm.localcopy(sendbuf, sendoffset, sendcount, sendtype,
     * resultArray, rank * recvcount * recvtype.Extent(), recvcount, recvtype);
     * //System.arraycopy(sendbuf, 0, resultArray, rank, sendcount);
     *
     * this.comm.send(resultArray, 0, size*recvcount, this.recvtype, peer,
     * this.tag);
     *
     * break; }
     *
     * mask <<= 1; }
     *
     * if (logger.isDebugEnabled()) { logger.debug(rank + ": gather done."); }
     *
     *
     *
     *
     * if (rank != root) { return; }
     *  // Add object of root to array. //System.arraycopy(sendbuf, sendoffset,
     * resultArray, root, sendcount); this.comm.localcopy(sendbuf, sendoffset,
     * sendcount, sendtype, resultArray, root * recvcount * recvtype.Extent(),
     * recvcount, recvtype);
     *
     *
     * System.arraycopy(resultArray, 0, recvbuf, recvoffset, size * recvcount *
     * recvtype.Extent());
     *
     *  }
     */
}


text:
<?php

namespace Eddmash\PowerOrm\Tests\TestApp\Models;

use Eddmash\PowerOrm\Model\Model;

class MetaTestUser extends Model
{
    public function unboundFields()
    {
        return [
            'name' => Model::CharField(['maxLength' => 200]),
            'email' => Model::EmailField(),
        ];
    }
}


text:
#include "TTSpatAmbipanning.h"

#define thisTTClass			TTSpatAmbipanning
#define thisTTClassName		"spat.ambipanning"
#define thisTTClassTags		"audio, spatialization, processing, dbap"

TTObjectBasePtr TTSpatAmbipanning::instantiate(TTSymbol name, TTValue arguments)
{
	return (TTObjectBasePtr) new thisTTClass(arguments);
}

extern "C" void thisTTClass :: registerClass ()
{
	TTClassRegister( thisTTClassName, thisTTClassTags, thisTTClass :: instantiate );
}

TTSpatAmbipanning::TTSpatAmbipanning(const TTValue& arguments) : TTSpatBase(arguments)
{
	mRenderer = new TTSpatAmbipanningRenderer;

	addAttributeWithGetterAndSetter(DistanceMode, kTypeInt32);
	addAttributeWithGetterAndSetter(DbUnit, kTypeFloat64);
	addAttributeWithGetterAndSetter(DistAtt, kTypeFloat64);
	addAttributeWithGetterAndSetter(XyzScale, kTypeFloat64);
	addAttributeWithGetterAndSetter(AedScale, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterCurve, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterAttDb, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterAtt, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterAtt2, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterSize, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterSize2, kTypeFloat64);
	addAttributeWithGetterAndSetter(CenterSize3, kTypeFloat64);
}

TTSpatAmbipanning::~TTSpatAmbipanning()
{
	delete mRenderer;
}

TTErr TTSpatAmbipanning::getDistanceMode(TTValue& aValue)
{
	aValue = getRenderer()->getDistanceMode();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setDistanceMode(const TTValue& aValue)
{
	TTFloat64 distanceMode = aValue;

	getRenderer()->setDistanceMode(distanceMode);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getDbUnit(TTValue& aValue)
{
	aValue = getRenderer()->getDbUnit();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setDbUnit(const TTValue& aValue)
{
	TTFloat64 mDbUnit = aValue;

	getRenderer()->setDbUnit(mDbUnit);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getDistAtt(TTValue& aValue)
{
	aValue = getRenderer()->getDistAtt();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setDistAtt(const TTValue& aValue)
{
	TTFloat64 distAtt = aValue;

	getRenderer()->setDistAtt(distAtt);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getXyzScale(TTValue& aValue)
{
	aValue = getRenderer()->getXyzScale();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setXyzScale(const TTValue& aValue)
{
	TTFloat64 xyzScale = aValue;

	getRenderer()->setXyzScale(xyzScale);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getAedScale(TTValue& aValue)
{
	aValue = getRenderer()->getAedScale();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setAedScale(const TTValue& aValue)
{
	TTFloat64 aedScale = aValue;

	getRenderer()->setAedScale(aedScale);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterCurve(TTValue& aValue)
{
	aValue = getRenderer()->getCenterCurve();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterCurve(const TTValue& aValue)
{
	TTFloat64 aCenterCurve = aValue;

	getRenderer()->setCenterCurve(aCenterCurve);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterAttDb(const TTValue& aValue)
{
	TTFloat64 aCenterAttDb = aValue;

	getRenderer()->setCenterAttDb(aCenterAttDb);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterAttDb(TTValue& aValue)
{
	aValue = getRenderer()->getCenterAttDb();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterAtt(const TTValue& aValue)
{
	TTFloat64 aCenterAtt = aValue;

	getRenderer()->setCenterAtt(aCenterAtt);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterAtt(TTValue& aValue)
{
	aValue = getRenderer()->getCenterAtt();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterAtt2(const TTValue& aValue)
{
	TTFloat64 aCenterAtt2 = aValue;

	getRenderer()->setCenterAtt2(aCenterAtt2);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterAtt2(TTValue& aValue)
{
	aValue = getRenderer()->getCenterAtt2();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterSize(const TTValue& aValue)
{
	TTFloat64 aCenterSize = aValue;

	getRenderer()->setCenterSize(aCenterSize);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterSize(TTValue& aValue)
{
	aValue = getRenderer()->getCenterSize();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterSize2(const TTValue& aValue)
{
	TTFloat64 aCenterSize2 = aValue;

	getRenderer()->setCenterSize2(aCenterSize2);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterSize2(TTValue& aValue)
{
	aValue = getRenderer()->getCenterSize2();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setCenterSize3(const TTValue& aValue)
{
	TTFloat64 aCenterSize3 = aValue;

	getRenderer()->setCenterSize3(aCenterSize3);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::getCenterSize3(TTValue& aValue)
{
	aValue = getRenderer()->getCenterSize3();
	return kTTErrNone;
}

TTErr TTSpatAmbipanning::setOrder(const TTValue& aValue)
{
	TTFloat64 aOrder = aValue;

	getRenderer()->setOrder(aOrder);
	getRenderer()->recalculateMatrixCoefficients(mSources, mSinks);
	return kTTErrNone;}

TTErr TTSpatAmbipanning::getOrder(TTValue& aValue)
{
	aValue = getRenderer()->getOrder();
	return kTTErrNone;}


text:
package com.creditease.agent.helpers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.creditease.agent.helpers.compress.CustomClassLoaderObjectInputStream;

public class CompressHelper {

    public static String compress(String str) {

        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的 byte 数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默认缓冲区大小创建新的输出流
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            // 将 b.length 个字节写入此输出流
            gzip.write(str.getBytes());
            gzip.close();
            // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
            return out.toString("ISO-8859-1");
        }
        catch (IOException e) {
            // ignore
        }
        return null;

    }

    /**
     * 字符串的解压
     *
     * @param str
     *            对字符串解压
     * @return 返回解压缩后的字符串
     * @throws IOException
     */
    public static String unCompress(String str) {

        try {
            if (null == str || str.length() <= 0) {
                return str;
            }
            // 创建一个新的 byte 数组输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
            ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
            // 使用默认缓冲区大小创建新的输入流
            GZIPInputStream gzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n = 0;
            while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
                // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
                out.write(buffer, 0, n);
            }
            // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
            return out.toString("UTF-8");
        }

        catch (IOException e) {
            // ignore
        }
        return null;
    }

    /**
     * Compress a byte array with GZIP
     *
     * @param byteArr
     *            a byte array
     * @return a compressed byte array
     * @throws IOException
     */
    public static byte[] compressByteArrWithGZIP(byte[] byteArr) throws IOException {

        ByteArrayOutputStream bos = null;
        GZIPOutputStream gos = null;
        try {
            bos = new ByteArrayOutputStream();
            gos = new GZIPOutputStream(bos);
            gos.write(byteArr);
            gos.flush();
        }
        finally {
            closeStream(gos);
            closeStream(bos);
        }

        return bos.toByteArray();
    }

    /**
     * Serialize one object to byte array
     *
     * @param object
     *            an object of a class which should implement Serializable interface
     * @return one byte array
     * @throws IOException
     */
    public static byte[] transObjectToByteArr(Serializable object) throws IOException {

        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
        }
        finally {
            closeStream(oos);
            closeStream(bos);
        }

        return bos.toByteArray();
    }

    /**
     * Uncompress a byte array with GZIP
     *
     * @param byteArr
     *            a compressed byte array
     * @return a uncompressed byte array
     * @throws IOException
     */
    public static byte[] uncompressByteArrWithGZIP(byte[] byteArr) throws IOException {

        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        GZIPInputStream gis = null;

        try {
            bos = new ByteArrayOutputStream();
            bis = new ByteArrayInputStream(byteArr);
            gis = new GZIPInputStream(bis);

            byte[] buffer = new byte[1024];
            int count = 0;

            while ((count = gis.read(buffer)) >= 0) {
                bos.write(buffer, 0, count);
            }
        }
        finally {
            closeStream(bos);
            closeStream(bis);
            closeStream(gis);
        }

        return bos.toByteArray();
    }

    /**
     * Deserialize a byte array to one object
     *
     * @param byteArr
     * @return one object of a class which implements Serializable interface
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Serializable readObjectFromByteArr(byte[] byteArr, ClassLoader classloader)
            throws IOException, ClassNotFoundException {

        ByteArrayInputStream bis = null;

        ObjectInputStream ois = null;

        try {
            bis = new ByteArrayInputStream(byteArr);

            if (classloader != null) {
                ois = new CustomClassLoaderObjectInputStream(bis, classloader);
            }
            else {
                ois = new ObjectInputStream(bis);
            }
        }
        finally {
            closeStream(bis);
            closeStream(ois);
        }

        return (Serializable) ois.readObject();
    }

    /**
     * Check if a byte array is compressed by GZIP
     *
     * @param byteArr
     *            a byte array
     * @return true stands for compressed data; false stands for uncompressed data
     * @throws IOException
     */
    public static boolean isCompressedByGZIP(byte[] byteArr) throws IOException {

        ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
        int b = readUByte(bis);
        int num = readUByte(bis) << 8 | b;
        return num == GZIPInputStream.GZIP_MAGIC;
    }

    /**
     * Read one byte from a InputStream
     *
     * @param in
     *            one InputStream
     * @return The integer value of the byte
     * @throws IOException
     */
    private static int readUByte(InputStream in) throws IOException {

        int b = in.read();
        if (b == -1) {
            throw new EOFException();
        }
        if (b < -1 || b > 255) {
            // Report on this.in, not argument in; see read{Header, Trailer}.
            throw new IOException(in.getClass().getName() + ".read() returned value out of range -1..255: " + b);
        }
        return b;
    }

    /**
     * Close the stream which implements Closeable interface
     *
     * @param stream
     */
    private static void closeStream(Closeable stream) {

        if (null != stream) {
            try {
                stream.close();
            }
            catch (IOException e) {
                stream = null;
                e.printStackTrace();
            }
        }
    }
}


text: package slices


text:
using System;
using System.Collections.Generic;
using ATMobile.Cells;
using ATMobile.Managers;
using ATMobile.Objects;
using Xamarin.Forms;

namespace ATMobile.Controls
{
    public class PracticeEndsListView : AbstractListView
    {
        public List<PracticeEnd> Ends;

        public PracticeEndsListView ()
        {
            ItemTemplate = new DataTemplate (typeof (PracticeEndCell));
            //RowHeight = 30;
            HasUnevenRows = true;
        }

        public void RefreshList (Guid _practiceId)
        {
            ATManager manager = ATManager.GetInstance ();
            Ends = manager.GetPracticeEnds (_practiceId);
            ItemsSource = Ends;
        }

        public void ClearList ()
        {
            ItemsSource = null;
        }
    }
}


text:
/* $Xorg: XimTrX.h,v 1.3 2000/08/17 19:45:05 cpqbld Exp $ */
/******************************************************************

           Copyright 1992 by Sun Microsystems, Inc.
           Copyright 1992, 1993, 1994 by FUJITSU LIMITED

Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation, and that the name of Sun Microsystems, Inc.
and FUJITSU LIMITED not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
Sun Microsystems, Inc. and FUJITSU LIMITED makes no representations about
the suitability of this software for any purpose.
It is provided "as is" without express or implied warranty.

Sun Microsystems Inc. AND FUJITSU LIMITED DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Sun Microsystems, Inc. AND FUJITSU LIMITED
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

  Author: Hideki Hiura (hhiura@Sun.COM) Sun Microsystems, Inc.
          Takashi Fujiwara     FUJITSU LIMITED
                               fujiwara@a80.tech.yk.fujitsu.co.jp

******************************************************************/
/* $XFree86$ */

#ifndef _XIMTRX_H
#define _XIMTRX_H

typedef struct _XIntrCallbackRec	*XIntrCallbackPtr;

typedef struct _XIntrCallbackRec {
    Bool		 (*func)(
				 Xim, INT16, XPointer, XPointer
);
    XPointer		 call_data;
    XIntrCallbackPtr	 next;
} XIntrCallbackRec ;

typedef struct _XSpecRec {
    XIntrCallbackPtr	 intr_cb;
    Atom		 imconnectid;
    Atom		 improtocolid;
    Atom		 immoredataid;
    Window		 lib_connect_wid;
    Window		 ims_connect_wid;
    XPointer		 ev;
    CARD32		 major_code;
    CARD32		 minor_code;
    CARD32		 BoundarySize;
} XSpecRec;

#define _XIM_PROTOCOL		"_XIM_PROTOCOL"
#define _XIM_XCONNECT		"_XIM_XCONNECT"
#define _XIM_MOREDATA		"_XIM_MOREDATA"

#define MAJOR_TRANSPORT_VERSION         0
#define MINOR_TRANSPORT_VERSION         0

#endif /* _XIMTRX_H */


text:
var express = require('express'),
    mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

var app = express(),
    server = require('http').createServer(app),
    io = require('socket.io')(server);

require('./app')(app); //express app
require('./websocket')(io); //websocket

server.listen(3000, function(){
    console.log('listening on port 3000');
});


text:
angular.module( 'ngBoilerplate.events', [
  'ui.router',
  'placeholders',
  'ui.bootstrap',
  'whichmango.services'
])

.config(function config( $stateProvider ) {
  $stateProvider.state( 'events', {
    url: '/events',
    views: {
      "main": {
        controller: 'EventsCtrl',
        templateUrl: 'events/events.tpl.html'
      }
    },
    data:{ pageTitle: 'What is It?' }
  });
})

.controller( 'EventsCtrl', function EventsCtrl( $scope, Events ) {
  // This is simple a demo for UI Boostrap.
  $scope.events = Events.all();
})

;


text:
"use strict";

// Required node modules
var fs = require("fs");

// Required files
var imfParser = require("../src/imf-parser.js");
var testIMFMessage = require("./testIMFMessage.js");

describe("Internet Message Format (IMF) Parser", function () {
  var testFileEncoding = "utf8";
  var testFilePath = __dirname + "/fixtures/testIMF.txt";

  describe("Parse file", function () {
    var testContext = imfParser.parseFile(testFilePath, testFileEncoding);

    testIMFMessage(testContext);
  });

  describe("Parse message", function () {
    var testMessage = fs.readFileSync(testFilePath, testFileEncoding);
    var testContext = imfParser.parseMessage(testMessage);

    testIMFMessage(testContext);
  });
});


text:
package com.navercorp.pinpoint.rpc;

import com.navercorp.pinpoint.rpc.packet.RequestPacket;
import com.navercorp.pinpoint.rpc.packet.SendPacket;

/**
 * @author Taejin Koo
 */
public class UnsupportOperationMessageListener implements MessageListener {

    private static final UnsupportOperationMessageListener INSTANCE = new UnsupportOperationMessageListener();

    @Override
    public void handleSend(SendPacket sendPacket, PinpointSocket pinpointSocket) {
        StringBuilder errorMessage = new StringBuilder(64);
        errorMessage.append("Unsupported handleSend method");
        errorMessage.append("packet:").append(sendPacket);
        errorMessage.append(", remote::").append(pinpointSocket.getRemoteAddress());

        throw new UnsupportedOperationException(errorMessage.toString());
    }

    @Override
    public void handleRequest(RequestPacket requestPacket, PinpointSocket pinpointSocket) {
        StringBuilder errorMessage = new StringBuilder(64);
        errorMessage.append("Unsupported handleRequest method");
        errorMessage.append("packet:").append(requestPacket);
        errorMessage.append(", remote::").append(pinpointSocket.getRemoteAddress());

        throw new UnsupportedOperationException(errorMessage.toString());
    }

    public static UnsupportOperationMessageListener getInstance() {
        return INSTANCE;
    }

}


text:
<?php
namespace AppBundle\Controller\Backend\Plugin\TeamMember;

use AppBundle\Entity\Layout;

use Neutron\Plugin\TeamMemberBundle\Controller\Backend\TeamMemberOverviewController as BaseController;

class TeamMemberOverviewController extends BaseController
{

    protected function getData($id)
    {
        $data = parent::getData($id);

        if (null === $data['content']->getLayout()){
            $data['content']->setLayout(new Layout());
        }

        $layout = $data['content']->getLayout();
        $data['static_widgets'] = $layout;
        $data['banner_text'] = $layout;
        $data['footer_text'] = $layout;
        $data['callout_box'] = $layout;

        return $data;
    }
}


text:
/* globals module */
/**
 * @module notificationsRegistrationsAnonymousRoute
 * @description Baasic Notifications Registrations Anonymous Route Definition provides Baasic route templates which can be expanded to Baasic REST URIs. Various services can use Baasic Notifications Registrations Anonymous Route Definition to obtain needed routes while other routes will be obtained through HAL. By convention, all route services use the same function names as their corresponding services.
 */

import { injectable, inject } from "inversify";
import { BaseRoute } from '../../common';
import { IGetRequestOptions, IOptions } from '../../common/contracts';;
import { IAppOptions, TYPES as coreTypes } from '../../core/contracts';
import { NotificationsRegistrationsAnonymousBatchRoute, TYPES as notificationsTypes } from './';
import { IAnonymousRegistration } from './contracts';

@injectable()
export class NotificationsRegistrationsAnonymousRoute extends BaseRoute {

    public readonly createRoute: string = 'notifications/registrations/anonymous';

    public readonly findRoute: string = 'notifications/registrations/anonymous/{?searchQuery,providers,page,rpp,sort,embed,fields}';

    public readonly getRoute: string = 'notifications/registrations/anonymous/{id}/{?embed}';

    public readonly updateRoute: string = 'notifications/registrations/anonymous/{id}';

    public readonly deleteRoute: string = 'notifications/registrations/anonymous/{id}';

    get batch(): NotificationsRegistrationsAnonymousBatchRoute {
        return this.notificationsRegistrationsAnonymousBatchRoute;
    }

    constructor(
        @inject(coreTypes.IAppOptions) protected appOptions: IAppOptions,
        @inject(notificationsTypes.NotificationsRegistrationsAnonymousBatchRoute) protected notificationsRegistrationsAnonymousBatchRoute: NotificationsRegistrationsAnonymousBatchRoute
    ) { super(appOptions); }

    /**
     * Parses create anonymous registrations route; this route does not expose any additional options
     * @method
     * @example notificationsRegistrationsAnonymousRoute.create();
     */
    create(): any {
        return super.baseCreate(this.createRoute, {});
    }

    /**
     * Parses find anonymous registrations route which can be expanded with additional options. Supported items are:
     * - `searchQuery` - A string referencing user subscription properties using the phrase search.
     * - `providers` - Comma separated list of notification providers.
     * - `page` - A value used to set the page number, i.e. to retrieve certain user subscription subset from the storage.
     * - `rpp` - A value used to limit the size of result set per page.
     * - `sort` - A string used to set the user subscription property to sort the result collection by.
     * - `embed` - Comma separated list of resources to be contained within the current representation.
     * @method
     * @param options Query resource options object.
     * @example notificationsRegistrationsAnonymousRoute.find({
                   searchQuery: '<search-phrase>',
                   providers: '<provider-name>,<provider-name>'
               });
    */
    find(options?: IOptions): any {
        return super.baseFind(this.findRoute, options);
    }

    /**
     * Parses get anonymous registrations route; this route should be expanded with the Id of anonymous registrations resource.
     * @method
     * @param id The registration identifier which uniquely identifies AnonymousRegistration resource that needs to be retrieved.
     * @param options Query resource options object.
     * @example notificationsRegistrationsAnonymousRoute.get({ id: '<registration-id>' });
     */
    get(id: string, options?: IGetRequestOptions): any {
        return super.baseGet(this.getRoute, id, options);
    }

    /**
     * Parses update anonymous registrations route; this route should be expanded with the Id of anonymous registrations resource.
     * @method
     * @param data An object used to update specified AnonymousRegistration resource.
     * @example notificationsRegistrationsAnonymousRoute.update(data);
     */
    update(data: IAnonymousRegistration): any {
        return super.baseUpdate(this.updateRoute, data);
    }

    /**
     * Parses delete anonymous registrations route; this route should be expanded with the Id of anonymous registrations resource.
     * @method
     * @param data An object used to delete specified AnonymousRegistration resource.
     * @example notificationsRegistrationsAnonymousRoute.delete(data);
     */
    delete(data: IAnonymousRegistration): any {
        return super.baseDelete(this.deleteRoute, data);
    }
}

/**
 * @overview
 ***Notes:**
 - Refer to the [REST API documentation](https://github.com/Baasic/baasic-rest-api/wiki) for detailed information about available Baasic REST API end-points.
 - [URI Template](https://github.com/Baasic/uritemplate-js) syntax enables expanding the Baasic route templates to Baasic REST URIs providing it with an object that contains URI parameters.
 - All end-point objects are transformed by the associated route service.
 */


text:
import { AppComponent } from './app.component';

import { TestBed , inject} from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

export function main() {

  describe('AppComponent Test', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        providers: [
          AppComponent
        ]
      });
    });
    it('Test - AppComponent Should Define.', inject([AppComponent], (cmp:any) => {
      expect(cmp).toBeDefined()
    }));

  });
}


text:
#ifndef ROSE_SERIAL_H
#define ROSE_SERIAL_H

void serial_init(void);
int serial_write_char(char c);
int serial_write_string(const char *s);
int serial_write_integer(int radix, int n);
int serial_printf(const char *fmt, ...);

#endif


text:
class Die
  def initialize(sides)
     unless sides > 1
      raise ArgumentError.new("A die can not have less than 1 side")
    end
    @sides=sides
  end

  def sides
    @sides
  end

  def roll
    rand(1..@sides)
  end
end

# 3. Refactored Solution
class Die

  attr_reader :sides

  def initialize(sides)
     unless sides > 1
      raise ArgumentError.new("A die can not have less than 1 side")
    end
    @sides=sides
  end

  def roll
    rand(1..@sides)
  end
end

# # 4. Reflection
# What is an ArgumentError and why would you use one?
# => An ArgumentError is a subclass of the the Error class. The ArgumentError is the error type object that gets raised if an invalid parameter gets passed to a method.
# => It is very possible that someone might want to use your code in their project.
# What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
# => I think the closest thing to a new method, I used was the attr_reader. I also used rand(). They were pretty straight forward to implement.
# What is a Ruby class?
# => A ruby class how you want to describe an object, for example, we created a Die class. From this Die class we can make many different dice, each with their own number of sides
# Why would you use a Ruby class?
# => Its all about keeping things simple and DRY. When creating a class you can add methods that apply to all instances of the class. This is super helpful so you don't end up repeating yourself and do more typing than you have to.
# What is the difference between a local variable and an instance variable?
# => Local variables only exist within the method that which they are used.
# => Instance variables are properties of an instance that are available to that specific instance of the class. For example @sides would be a instance variable.
# Where can an instance variable be used?
# Instance variables and be used from anywhere inside a specific instance of that class.


text:
import {
  layoutRectLtwh,
  layoutRectsOverlap,
  moveLayoutRect,
} from '../layout-rect';
import {dev} from '../log';
import {toggle} from '../style';

const TAG = 'Resource';
const RESOURCE_PROP_ = '__AMP__RESOURCE';
const OWNER_PROP_ = '__AMP__OWNER';

/**
 * Resource state.
 *
 * @enum {number}
 */
export const ResourceState = {
  /**
   * The resource has not been built yet. Measures, layouts, preloads or
   * viewport signals are not allowed.
   */
  NOT_BUILT: 0,

  /**
   * The resource has been built, but not measured yet and not yet ready
   * for layout.
   */
  NOT_LAID_OUT: 1,

  /**
   * The resource has been built and measured and ready for layout.
   */
  READY_FOR_LAYOUT: 2,

  /**
   * The resource is currently scheduled for layout.
   */
  LAYOUT_SCHEDULED: 3,

  /**
   * The resource has been laid out.
   */
  LAYOUT_COMPLETE: 4,

  /**
   * The latest resource's layout failed.
   */
  LAYOUT_FAILED: 5,
};

/**
 * A Resource binding for an AmpElement.
 * @package
 */
export class Resource {

  /**
   * @param {!Element} element
   * @return {!Resource}
   */
  static forElement(element) {
    return /** @type {!Resource} */ (
        dev().assert(Resource.forElementOptional(element),
            'Missing resource prop on %s', element));
  }

  /**
   * @param {!Element} element
   * @return {?Resource}
   */
  static forElementOptional(element) {
    return /** @type {!Resource} */ (element[RESOURCE_PROP_]);
  }

  /**
   * Assigns an owner for the specified element. This means that the resources
   * within this element will be managed by the owner and not Resources manager.
   * @param {!Element} element
   * @param {!AmpElement} owner
   */
  static setOwner(element, owner) {
    dev().assert(owner.contains(element), 'Owner must contain the element');
    if (Resource.forElementOptional(element)) {
      Resource.forElementOptional(element).updateOwner(owner);
    }
    element[OWNER_PROP_] = owner;

    // Need to clear owner cache for all child elements
    const cachedElements = element.getElementsByClassName('-amp-element');
    for (let i = 0; i < cachedElements.length; i++) {
      const ele = cachedElements[i];
      if (Resource.forElementOptional(ele)) {
        Resource.forElementOptional(ele).updateOwner(undefined);
      }
    }
  }

  /**
   * @param {number} id
   * @param {!AmpElement} element
   * @param {!./resources-impl.Resources} resources
   */
  constructor(id, element, resources) {
    element[RESOURCE_PROP_] = this;

    /** @private {number} */
    this.id_ = id;

    /** @export @const {!AmpElement} */
    this.element = element;

    /** @export @const {string} */
    this.debugid = element.tagName.toLowerCase() + '#' + id;

    /** @const {!Window} */
    this.hostWin = element.ownerDocument.defaultView;

    /** @private {!./resources-impl.Resources} */
    this.resources_ = resources;

    /** @private {boolean} */
    this.blacklisted_ = false;

    /** @private {!AmpElement|undefined|null} */
    this.owner_ = undefined;

    /** @private {!ResourceState} */
    this.state_ = element.isBuilt() ? ResourceState.NOT_LAID_OUT :
        ResourceState.NOT_BUILT;

    /** @private {number} */
    this.layoutCount_ = 0;

    /** @private {boolean} */
    this.isFixed_ = false;

    /** @private {!../layout-rect.LayoutRectDef} */
    this.layoutBox_ = layoutRectLtwh(-10000, -10000, 0, 0);

    /** @private {?../layout-rect.LayoutRectDef} */
    this.initialLayoutBox_ = null;

    /** @private {boolean} */
    this.isMeasureRequested_ = false;

    /** @private {boolean} */
    this.isInViewport_ = false;

    /** @private {?Promise<undefined>} */
    this.layoutPromise_ = null;

   /**
    * Pending change size that was requested but could not be satisfied.
    * @private {!./resources-impl.SizeDef|undefined}
    */
    this.pendingChangeSize_ = undefined;

    /** @private {boolean} */
    this.loadedOnce_ = false;

    /** @private {?Function} */
    this.loadPromiseResolve_ = null;

    /** @private @const {!Promise} */
    this.loadPromise_ = new Promise(resolve => {
      this.loadPromiseResolve_ = resolve;
    });

    /** @private {boolean} */
    this.paused_ = false;
  }

  /**
   * Returns resource's ID.
   * @return {number}
   */
  getId() {
    return this.id_;
  }

  /**
   * Update owner element
   * @param {AmpElement|undefined} owner
   */
  updateOwner(owner) {
    this.owner_ = owner;
  }

  /**
   * Returns an owner element or null.
   * @return {?AmpElement}
   */
  getOwner() {
    if (this.owner_ === undefined) {
      for (let n = this.element; n; n = n.parentElement) {
        if (n[OWNER_PROP_]) {
          this.owner_ = n[OWNER_PROP_];
          break;
        }
      }
      if (this.owner_ === undefined) {
        this.owner_ = null;
      }
    }
    return this.owner_;
  }

  /**
   * Whether the resource has an owner.
   * @return {boolean}
   */
  hasOwner() {
    return !!this.getOwner();
  }

  /**
   * Returns the resource's element priority.
   * @return {number}
   */
  getPriority() {
    return this.element.getPriority();
  }

  /**
   * Returns the resource's state. See {@link ResourceState} for details.
   * @return {!ResourceState}
   */
  getState() {
    return this.state_;
  }

  /**
   * Returns whether the resource has been blacklisted.
   * @return {boolean}
   */
  isBlacklisted() {
    return this.blacklisted_;
  }

  /**
   * Requests the resource's element to be built. See {@link AmpElement.build}
   * for details.
   */
  build() {
    if (this.blacklisted_ || !this.element.isUpgraded()) {
      return;
    }
    try {
      this.element.build();
    } catch (e) {
      dev().error(TAG, 'failed to build:', this.debugid, e);
      this.blacklisted_ = true;
      return;
    }

    if (this.hasBeenMeasured()) {
      this.state_ = ResourceState.READY_FOR_LAYOUT;
    } else {
      this.state_ = ResourceState.NOT_LAID_OUT;
    }
    this.element.dispatchCustomEvent('amp:built');
  }

  /**
   * Optionally hides or shows the element depending on the media query.
   */
  applySizesAndMediaQuery() {
    this.element.applySizesAndMediaQuery();
  }

  /**
   * Instructs the element to change its size and transitions to the state
   * awaiting the measure and possibly layout.
   * @param {number|undefined} newHeight
   * @param {number|undefined} newWidth
   */
  changeSize(newHeight, newWidth) {
    this.element./*OK*/changeSize(newHeight, newWidth);
    // Schedule for re-layout.
    if (this.state_ != ResourceState.NOT_BUILT) {
      this.state_ = ResourceState.NOT_LAID_OUT;
    }
  }

  /**
   * Informs the element that it's either overflown or not.
   * @param {boolean} overflown
   * @param {number|undefined} requestedHeight
   * @param {number|undefined} requestedWidth
   */
  overflowCallback(overflown, requestedHeight, requestedWidth) {
    if (overflown) {
      this.pendingChangeSize_ = {
        height: requestedHeight,
        width: requestedWidth,
      };
    }
    this.element.overflowCallback(overflown, requestedHeight, requestedWidth);
  }

  resetPendingChangeSize() {
    this.pendingChangeSize_ = undefined;
  }

  /**
   * @return {!./resources-impl.SizeDef|undefined}
   */
  getPendingChangeSize() {
    return this.pendingChangeSize_;
  }

  /**
   * Measures the resource's boundaries. An upgraded element will be
   * transitioned to the "ready for layout" state.
   */
  measure() {
    this.isMeasureRequested_ = false;

    let box = this.resources_.getViewport().getLayoutRect(this.element);
    const oldBox = this.layoutBox_;
    const viewport = this.resources_.getViewport();
    this.layoutBox_ = box;

    // Calculate whether the element is currently is or in `position:fixed`.
    let isFixed = false;
    if (this.isDisplayed()) {
      const win = this.resources_.win;
      const body = win.document.body;
      for (let n = this.element; n && n != body; n = n./*OK*/offsetParent) {
        if (n.isAlwaysFixed && n.isAlwaysFixed()) {
          isFixed = true;
          break;
        }
        if (viewport.isDeclaredFixed(n) &&
                win./*OK*/getComputedStyle(n).position == 'fixed') {
          isFixed = true;
          break;
        }
      }
    }
    this.isFixed_ = isFixed;

    if (isFixed) {
      // For fixed position elements, we need the relative position to the
      // viewport. When accessing the layoutBox through #getLayoutBox, we'll
      // return the new absolute position.
      box = this.layoutBox_ = moveLayoutRect(box, -viewport.getScrollLeft(),
          -viewport.getScrollTop());
    }

    // Note that "left" doesn't affect readiness for the layout.
    if (this.state_ == ResourceState.NOT_LAID_OUT ||
          oldBox.top != box.top ||
          oldBox.width != box.width ||
          oldBox.height != box.height) {

      if (this.element.isUpgraded() &&
              this.state_ != ResourceState.NOT_BUILT &&
              (this.state_ == ResourceState.NOT_LAID_OUT ||
                  this.element.isRelayoutNeeded())) {
        this.state_ = ResourceState.READY_FOR_LAYOUT;
      }
    }

    if (!this.hasBeenMeasured()) {
      this.initialLayoutBox_ = box;
    }

    this.element.updateLayoutBox(box);
  }

  /**
   * Completes collapse: ensures that the element is `display:none` and
   * updates layout box.
   */
  completeCollapse() {
    toggle(this.element, false);
    this.layoutBox_ = layoutRectLtwh(
        this.layoutBox_.left,
        this.layoutBox_.top,
        0, 0);
    this.isFixed_ = false;
    this.element.updateLayoutBox(this.layoutBox_);
  }

  /**
   * @return {boolean}
   */
  isMeasureRequested() {
    return this.isMeasureRequested_;
  }

  /**
   * Checks if the current resource has been measured.
   * @return {boolean}
   */
  hasBeenMeasured() {
    return !!this.initialLayoutBox_;
  }

  /**
   * Requests the element to be remeasured on the next pass.
   */
  requestMeasure() {
    if (this.state_ == ResourceState.NOT_BUILT) {
      // Can't measure unbuilt element.
      return;
    }
    this.isMeasureRequested_ = true;
  }

  /**
   * Returns a previously measured layout box.
   * @return {!../layout-rect.LayoutRectDef}
   */
  getLayoutBox() {
    if (!this.isFixed_) {
      return this.layoutBox_;
    }
    const viewport = this.resources_.getViewport();
    return moveLayoutRect(this.layoutBox_, viewport.getScrollLeft(),
        viewport.getScrollTop());
  }

  /**
   * Returns the first measured layout box.
   * @return {!../layout-rect.LayoutRectDef}
   */
  getInitialLayoutBox() {
    // Before the first measure, there will be no initial layoutBox.
    // Luckily, layoutBox will be present but essentially useless.
    return this.initialLayoutBox_ || this.layoutBox_;
  }

  /**
   * Whether the resource is displayed, i.e. if it has non-zero width and
   * height.
   * @return {boolean}
   */
  isDisplayed() {
    return this.layoutBox_.height > 0 && this.layoutBox_.width > 0;
  }

  /**
   * Whether the element is fixed according to the latest measurement.
   * @return {boolean}
   */
  isFixed() {
    return this.isFixed_;
  }

  /**
   * Whether the element's layout box overlaps with the specified rect.
   * @param {!../layout-rect.LayoutRectDef} rect
   * @return {boolean}
   */
  overlaps(rect) {
    return layoutRectsOverlap(this.getLayoutBox(), rect);
  }

  /**
   * Whether this element can be pre-rendered.
   * @return {boolean}
   */
  prerenderAllowed() {
    return this.element.prerenderAllowed();
  }

  /**
   * Whether this is allowed to render when not in viewport.
   * @return {boolean}
   */
  renderOutsideViewport() {
    // The exception is for owned resources, since they only attempt to
    // render outside viewport when the owner has explicitly allowed it.
    // TODO(jridgewell, #5803): Resources should be asking owner if it can
    // prerender this resource, so that it can avoid expensive elements wayyy
    // outside of viewport. For now, blindly trust that owner knows what it's
    // doing.
    if (this.hasOwner()) {
      return true;
    }

    const renders = this.element.renderOutsideViewport();
    // Boolean interface, element is either always allowed or never allowed to
    // render outside viewport.
    if (renders === true || renders === false) {
      return renders;
    }
    // Numeric interface, element is allowed to render outside viewport when it
    // is within X times the viewport height of the current viewport.
    const viewportBox = this.resources_.getViewport().getRect();
    const layoutBox = this.getLayoutBox();
    const scrollDirection = this.resources_.getScrollDirection();
    const multipler = Math.max(renders, 0);
    let scrollPenalty = 1;
    let distance;
    if (viewportBox.right < layoutBox.left ||
        viewportBox.left > layoutBox.right) {
      // If outside of viewport's x-axis, element is not in viewport.
      return false;
    }
    if (viewportBox.bottom < layoutBox.top) {
      // Element is below viewport
      distance = layoutBox.top - viewportBox.bottom;

      // If we're scrolling away from the element
      if (scrollDirection == -1) {
        scrollPenalty = 2;
      }
    } else if (viewportBox.top > layoutBox.bottom) {
      // Element is above viewport
      distance = viewportBox.top - layoutBox.bottom;

      // If we're scrolling away from the element
      if (scrollDirection == 1) {
        scrollPenalty = 2;
      }
    } else {
      // Element is in viewport
      return true;
    }
    return distance < viewportBox.height * multipler / scrollPenalty;
  }

  /**
   * Sets the resource's state to LAYOUT_SCHEDULED.
   */
  layoutScheduled() {
    this.state_ = ResourceState.LAYOUT_SCHEDULED;
  }

  /**
   * Starts the layout of the resource. Returns the promise that will yield
   * once layout is complete. Only allowed to be called on a upgraded, built
   * and displayed element.
   * @param {boolean} isDocumentVisible
   * @return {!Promise}
   */
  startLayout(isDocumentVisible) {
    if (this.layoutPromise_) {
      return this.layoutPromise_;
    }
    if (this.state_ == ResourceState.LAYOUT_COMPLETE) {
      return Promise.resolve();
    }
    if (this.state_ == ResourceState.LAYOUT_FAILED) {
      return Promise.reject('already failed');
    }

    dev().assert(this.state_ != ResourceState.NOT_BUILT,
        'Not ready to start layout: %s (%s)', this.debugid, this.state_);

    if (!isDocumentVisible && !this.prerenderAllowed()) {
      dev().fine(TAG, 'layout canceled due to non pre-renderable element:',
          this.debugid, this.state_);
      this.state_ = ResourceState.READY_FOR_LAYOUT;
      return Promise.resolve();
    }

    if (!this.isInViewport() && !this.renderOutsideViewport()) {
      dev().fine(TAG, 'layout canceled due to element not being in viewport:',
          this.debugid, this.state_);
      this.state_ = ResourceState.READY_FOR_LAYOUT;
      return Promise.resolve();
    }

    // Double check that the element has not disappeared since scheduling
    this.measure();
    if (!this.isDisplayed()) {
      dev().fine(TAG, 'layout canceled due to element loosing display:',
          this.debugid, this.state_);
      return Promise.resolve();
    }

    // Not-wanted re-layouts are ignored.
    if (this.layoutCount_ > 0 && !this.element.isRelayoutNeeded()) {
      dev().fine(TAG, 'layout canceled since it wasn\'t requested:',
          this.debugid, this.state_);
      this.state_ = ResourceState.LAYOUT_COMPLETE;
      return Promise.resolve();
    }

    dev().fine(TAG, 'start layout:', this.debugid, 'count:', this.layoutCount_);
    this.layoutCount_++;
    this.state_ = ResourceState.LAYOUT_SCHEDULED;

    let promise;
    try {
      promise = this.element.layoutCallback();
    } catch (e) {
      return Promise.reject(e);
    }

    this.layoutPromise_ = promise.then(() => this.layoutComplete_(true),
        reason => this.layoutComplete_(false, reason));
    return this.layoutPromise_;
  }

  /**
   * @param {boolean} success
   * @param {*=} opt_reason
   * @return {!Promise|undefined}
   */
  layoutComplete_(success, opt_reason) {
    if (this.loadPromiseResolve_) {
      this.loadPromiseResolve_();
      this.loadPromiseResolve_ = null;
    }
    this.layoutPromise_ = null;
    this.loadedOnce_ = true;
    this.state_ = success ? ResourceState.LAYOUT_COMPLETE :
        ResourceState.LAYOUT_FAILED;
    if (success) {
      dev().fine(TAG, 'layout complete:', this.debugid);
    } else {
      dev().fine(TAG, 'loading failed:', this.debugid, opt_reason);
      return Promise.reject(opt_reason);
    }
  }

  /**
   * Returns true if the resource layout has not completed or failed.
   * @return {boolean}
   * */
  isLayoutPending() {
    return this.state_ != ResourceState.LAYOUT_COMPLETE &&
        this.state_ != ResourceState.LAYOUT_FAILED;
  }

  /**
   * Returns a promise that is resolved when this resource is laid out
   * for the first time and the resource was loaded. Note that the resource
   * could be unloaded subsequently. This method returns resolved promise for
   * sunch unloaded elements.
   * @return {!Promise}
   */
  loadedOnce() {
    return this.loadPromise_;
  }

  /**
   * @return {boolean} true if the resource has been loaded at least once.
   */
  hasLoadedOnce() {
    return this.loadedOnce_;
  }

  /**
   * Whether the resource is currently visible in the viewport.
   * @return {boolean}
   */
  isInViewport() {
    return this.isInViewport_;
  }

  /**
   * Updates the inViewport state of the element.
   * @param {boolean} inViewport
   */
  setInViewport(inViewport) {
    if (inViewport == this.isInViewport_) {
      return;
    }
    dev().fine(TAG, 'inViewport:', this.debugid, inViewport);
    this.isInViewport_ = inViewport;
    this.element.viewportCallback(inViewport);
  }

  /**
   * Calls element's unlayoutCallback callback and resets state for
   * relayout in case document becomes active again.
   */
  unlayout() {
    if (this.state_ == ResourceState.NOT_BUILT ||
        this.state_ == ResourceState.NOT_LAID_OUT) {
      return;
    }
    this.setInViewport(false);
    if (this.element.unlayoutCallback()) {
      this.element.togglePlaceholder(true);
      this.state_ = ResourceState.NOT_LAID_OUT;
      this.layoutCount_ = 0;
      this.layoutPromise_ = null;
    }
  }

  /**
   * Returns the task ID for this resource.
   * @param localId
   * @returns {string}
   */
  getTaskId(localId) {
    return this.debugid + '#' + localId;
  }

  /**
   * Calls element's pauseCallback callback.
   */
  pause() {
    if (this.state_ == ResourceState.NOT_BUILT || this.paused_) {
      return;
    }
    this.paused_ = true;
    this.setInViewport(false);
    this.element.pauseCallback();
    if (this.element.unlayoutOnPause()) {
      this.unlayout();
    }
  }

  /**
   * Calls element's pauseCallback callback.
   */
  pauseOnRemove() {
    if (this.state_ == ResourceState.NOT_BUILT) {
      return;
    }
    this.setInViewport(false);
    if (this.paused_) {
      return;
    }
    this.paused_ = true;
    this.element.pauseCallback();
  }

  /**
   * Calls element's resumeCallback callback.
   */
  resume() {
    if (this.state_ == ResourceState.NOT_BUILT || !this.paused_) {
      return;
    }
    this.paused_ = false;
    this.element.resumeCallback();
  }

  /**
   * Called when a previously visible element is no longer displayed.
   */
  unload() {
    this.pause();
    this.unlayout();
  }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LevelRangeFilter Class</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Reference

LevelRangeFilter Class

 This is a simple filter based on Level matching.

For a list of all members of this type, see LevelRangeFilter Members.

        System.Object

   log4net.Filter.FilterSkeleton
      log4net.Filter.LevelRangeFilter

        [Visual Basic]

Public Class LevelRangeFilter
    Inherits FilterSkeleton

        [C#]

public class LevelRangeFilter : FilterSkeleton

Thread Safety

This type is not safe for multithreaded operations.

Remarks

 The filter admits three options LevelMin and LevelMax that determine the range of priorities that are matched, and AcceptOnMatch. If there is a match between the range of priorities and the Level of the LoggingEvent, then the Decide method returns Accept in case the AcceptOnMatch option value is set to true, if it is false then Deny is returned. If there is no match, Deny is returned.

Requirements

Namespace: log4net.Filter

Assembly: log4net (in log4net.dll)

See Also

LevelRangeFilter Members | log4net.Filter Namespace

Copyright 2001-2006 The Apache Software Foundation.

Generated from assembly log4net [1.2.10.0]


text:
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace Burrows.Serialization
{
    using System;
    using System.Reflection;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;

    public class JsonContractResolver :
        CamelCasePropertyNamesContractResolver
    {
        protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);

            // don't camel-case the key names of a dictionary
            contract.PropertyNameResolver = x => x;

            return contract;
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            if (!property.Writable)
            {
                var propertyInfo = member as PropertyInfo;
                if (propertyInfo != null)
                {
                    if (propertyInfo.GetSetMethod(true) != null)
                        property.Writable = true;
                }
            }

            return property;
        }
    }
}


text:
package com.thebluealliance.androidclient.subscribers;

import android.content.res.Resources;

import com.google.gson.Gson;
import com.thebluealliance.androidclient.DefaultTestRunner;
import com.thebluealliance.androidclient.datafeed.APICache;
import com.thebluealliance.androidclient.datafeed.HttpModule;
import com.thebluealliance.androidclient.datafeed.framework.DatafeedTestDriver;
import com.thebluealliance.androidclient.datafeed.framework.ModelMaker;
import com.thebluealliance.androidclient.eventbus.ActionBarTitleEvent;
import com.thebluealliance.androidclient.listitems.ImageListElement;
import com.thebluealliance.androidclient.listitems.ListItem;
import com.thebluealliance.androidclient.listitems.MatchListElement;
import com.thebluealliance.androidclient.models.Event;
import com.thebluealliance.androidclient.models.Match;
import com.thebluealliance.androidclient.models.Media;
import com.thebluealliance.androidclient.renderers.MatchRenderer;
import com.thebluealliance.androidclient.renderers.MediaRenderer;
import com.thebluealliance.androidclient.subscribers.MatchInfoSubscriber.Model;

import org.greenrobot.eventbus.EventBus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

@RunWith(DefaultTestRunner.class)
public class MatchInfoSubscriberTest {

    @Mock EventBus mEventBus;
    @Mock APICache mCache;
    @Mock Resources mResources;

    private MatchInfoSubscriber mSubscriber;
    private Gson mGson;
    private Model mData;
    private MatchRenderer mRenderer;
    private MediaRenderer mMediaRenderer;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mGson = HttpModule.getGson();
        mRenderer = spy(new MatchRenderer(mCache, mResources));
        mMediaRenderer = spy(new MediaRenderer());
        mSubscriber = new MatchInfoSubscriber(mGson, mEventBus, mRenderer, mMediaRenderer, mResources);
        mData = new Model(
          ModelMaker.getModel(Match.class, "2015necmp_f1m1"),
          ModelMaker.getModel(Event.class, "2015necmp"));
    }

    @Test
    public void testParseNullData()  {
        DatafeedTestDriver.parseNullData(mSubscriber);
    }

    @Test
    public void testSimpleParsing()  {
        DatafeedTestDriver.testSimpleParsing(mSubscriber, mData);
        verify(mEventBus).post(any(ActionBarTitleEvent.class));
    }

    @Test
    public void testParsedData()  {
        List<ListItem> data = DatafeedTestDriver.getParsedData(mSubscriber, mData);

        assertEquals(3, data.size());
        assertTrue(data.get(0) instanceof MatchListElement);
        assertTrue(data.get(1) instanceof ImageListElement);

        Media videoItem = ((Match.MatchVideo)mData.match.getVideos().get(0)).asMedia();
        ImageListElement video = (ImageListElement) data.get(1);

        verify(mRenderer).renderFromModel(mData.match, MatchRenderer.RENDER_MATCH_INFO);
        assertTrue(video.equals(mMediaRenderer.renderFromModel(videoItem, null)));
    }
}


text:
class CreateNotes < ActiveRecord::Migration
  def change
    create_table :notes do |t|
      t.integer :user_id
      t.integer :proposal_id
      t.text    :content
      t.timestamps
    end
  end
end


text:
package org.apache.dubbo.remoting.buffer;

import org.junit.Assert;

public class DirectChannelBufferTest extends AbstractChannelBufferTest {

    private ChannelBuffer buffer;

    @Override
    protected ChannelBuffer newBuffer(int capacity) {
        buffer = ChannelBuffers.directBuffer(capacity);
        Assert.assertEquals(0, buffer.writerIndex());
        return buffer;
    }

    @Override
    protected ChannelBuffer[] components() {
        return new ChannelBuffer[]{buffer};
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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"
	xsi:schemaLocation="
		http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">

  <bean id="bridgePropertyPlaceholder" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer">
    <property name="location" value="classpath:org/apache/camel/test/spring/test.properties"/>
  </bean>

  <bean id="testRouteBuilder" class="org.apache.camel.test.spring.TestPropertyInjectRouteBuilder"></bean>

  <camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
      <routeBuilder ref="testRouteBuilder"/>
  </camelContext>

</beans>


text:
package com.balidao.transreport.json;

import java.io.IOException;

import org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class LazyInitializerDeserializer extends JsonDeserializer<JavassistLazyInitializer>{

    public JavassistLazyInitializer deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        return null;
    }

}


text:
#ifndef __G_DBUS_OBJECT_SKELETON_H__
#define __G_DBUS_OBJECT_SKELETON_H__

#include <gio/giotypes.h>

G_BEGIN_DECLS

#define G_TYPE_DBUS_OBJECT_SKELETON         (g_dbus_object_skeleton_get_type ())
#define G_DBUS_OBJECT_SKELETON(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_DBUS_OBJECT_SKELETON, GDBusObjectSkeleton))
#define G_DBUS_OBJECT_SKELETON_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_DBUS_OBJECT_SKELETON, GDBusObjectSkeletonClass))
#define G_DBUS_OBJECT_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_DBUS_OBJECT_SKELETON, GDBusObjectSkeletonClass))
#define G_IS_DBUS_OBJECT_SKELETON(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_DBUS_OBJECT_SKELETON))
#define G_IS_DBUS_OBJECT_SKELETON_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_DBUS_OBJECT_SKELETON))

typedef struct _GDBusObjectSkeletonClass   GDBusObjectSkeletonClass;
typedef struct _GDBusObjectSkeletonPrivate GDBusObjectSkeletonPrivate;

/**
 * GDBusObjectSkeleton:
 *
 * The #GDBusObjectSkeleton structure contains private data and should only be
 * accessed using the provided API.
 *
 * Since: 2.30
 */
struct _GDBusObjectSkeleton
{
  /*< private >*/
  GObject parent_instance;
  GDBusObjectSkeletonPrivate *priv;
};

/**
 * GDBusObjectSkeletonClass:
 * @parent_class: The parent class.
 * @authorize_method: Signal class handler for the #GDBusObjectSkeleton::authorize-method signal.
 *
 * Class structure for #GDBusObjectSkeleton.
 *
 * Since: 2.30
 */
struct _GDBusObjectSkeletonClass
{
  GObjectClass parent_class;

  /* Signals */
  gboolean (*authorize_method) (GDBusObjectSkeleton       *object,
                                GDBusInterfaceSkeleton    *interface_,
                                GDBusMethodInvocation *invocation);

  /*< private >*/
  gpointer padding[8];
};

GLIB_AVAILABLE_IN_ALL
GType                g_dbus_object_skeleton_get_type                  (void) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
GDBusObjectSkeleton *g_dbus_object_skeleton_new                       (const gchar            *object_path);
GLIB_AVAILABLE_IN_ALL
void                 g_dbus_object_skeleton_flush                     (GDBusObjectSkeleton    *object);
GLIB_AVAILABLE_IN_ALL
void                 g_dbus_object_skeleton_add_interface             (GDBusObjectSkeleton    *object,
                                                                       GDBusInterfaceSkeleton *interface_);
GLIB_AVAILABLE_IN_ALL
void                 g_dbus_object_skeleton_remove_interface          (GDBusObjectSkeleton    *object,
                                                                       GDBusInterfaceSkeleton *interface_);
GLIB_AVAILABLE_IN_ALL
void                 g_dbus_object_skeleton_remove_interface_by_name  (GDBusObjectSkeleton    *object,
                                                                       const gchar            *interface_name);
GLIB_AVAILABLE_IN_ALL
void                 g_dbus_object_skeleton_set_object_path           (GDBusObjectSkeleton    *object,
                                                                       const gchar            *object_path);

G_END_DECLS

#endif /* __G_DBUS_OBJECT_SKELETON_H */