text:
package com.opengamma.engine.calcnode;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;

import java.util.Set;

import org.testng.annotations.Test;

import com.google.common.collect.Iterables;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.cache.ViewComputationCache;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.test.CalculationNodeUtils;
import com.opengamma.engine.test.MockFunction;
import com.opengamma.engine.test.TestCalculationNode;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.ExecutionLog;
import com.opengamma.engine.view.ExecutionLogMode;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.log.LogBridge;
import com.opengamma.util.log.LogEvent;
import com.opengamma.util.log.LogLevel;
import com.opengamma.util.log.SimpleLogEvent;
import com.opengamma.util.log.ThreadLocalLogEventListener;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.test.TestLifecycle;

/**
 * Tests the {@link SimpleCalculationNode} class. Note the name so that Clover doesn't ignore it.
 */
@Test(groups = TestGroup.UNIT)
public class CalculationNodeTest {

  public void mockFunctionInvocationOneInputMissing() throws Exception {
    TestLifecycle.begin();
    try {
      final MockFunction mockFunction = CalculationNodeUtils.getMockFunction();
      final TestCalculationNode calcNode = CalculationNodeUtils.getTestCalcNode(mockFunction);
      TestLifecycle.register(calcNode);
      final CalculationJob calcJob = CalculationNodeUtils.getCalculationJob(mockFunction);

      final long startTime = System.nanoTime();
      final CalculationJobResult jobResult = calcNode.executeJob(calcJob);
      final long endTime = System.nanoTime();
      assertNotNull(jobResult);
      assertTrue(jobResult.getDuration() >= 0);
      assertTrue(endTime - startTime >= jobResult.getDuration());
      assertEquals(1, jobResult.getResultItems().size());
      final CalculationJobResultItem resultItem = jobResult.getResultItems().get(0);
      assertEquals(InvocationResult.MISSING_INPUTS, resultItem.getResult());

      final ExecutionLog executionLog = resultItem.getExecutionLog();
      assertNotNull(executionLog);
      assertEquals(MissingInputException.class.getName(), executionLog.getExceptionClass());
      assertEquals("Unable to execute because of 1 missing input(s)", executionLog.getExceptionMessage());
      assertNull(executionLog.getExceptionStackTrace());
    } finally {
      TestLifecycle.end();
    }
  }

  public void mockFunctionInvocationOneInputOneOutput() throws Exception {
    TestLifecycle.begin();
    try {
      final MockFunction mockFunction = CalculationNodeUtils.getMockFunction();
      final TestCalculationNode calcNode = CalculationNodeUtils.getTestCalcNode(mockFunction);
      TestLifecycle.register(calcNode);
      final CalculationJob calcJob = CalculationNodeUtils.getCalculationJob(mockFunction);
      final ValueSpecification inputSpec = CalculationNodeUtils.getMockFunctionInputs(mockFunction).iterator().next();
      final ComputedValue inputValue = new ComputedValue(inputSpec, "Just an input object");

      final ViewComputationCache cache = calcNode.getCache(calcJob.getSpecification());
      cache.putSharedValue(inputValue);

      final CalculationJobResult jobResult = calcNode.executeJob(calcJob);
      assertNotNull(jobResult);
      assertEquals(1, jobResult.getResultItems().size());
      final CalculationJobResultItem resultItem = jobResult.getResultItems().get(0);
      assertEquals(InvocationResult.SUCCESS, resultItem.getResult());
      assertEquals("Nothing we care about", cache.getValue(mockFunction.getResultSpec()));
    } finally {
      TestLifecycle.end();
    }
  }

  //-------------------------------------------------------------------------
  public void testLogIndicators() throws Exception {
    TestLifecycle.begin();
    try {
      final MockFunction mockFunction = getMockLoggingFunction();
      final ThreadLocalLogEventListener logEventListener = new ThreadLocalLogEventListener();
      final TestCalculationNode calcNode = new TestCalculationNode(logEventListener);
      TestLifecycle.register(calcNode);
      CalculationNodeUtils.configureTestCalcNode(calcNode, mockFunction);
      final CalculationJob calcJob = CalculationNodeUtils.getCalculationJob(mockFunction, ExecutionLogMode.INDICATORS);
      final CalculationJobResultItem resultItemLogIndicators = getResultWithLogging(mockFunction, logEventListener, calcNode, calcJob);

      final ExecutionLog executionLog = resultItemLogIndicators.getExecutionLog();
      assertNotNull(executionLog);
      assertTrue(executionLog.getLogLevels().contains(LogLevel.WARN));
      assertFalse(executionLog.getLogLevels().contains(LogLevel.ERROR));
      assertFalse(executionLog.getLogLevels().contains(LogLevel.INFO));

      assertNull(executionLog.getEvents());

      assertNull(executionLog.getExceptionClass());
      assertNull(executionLog.getExceptionMessage());
      assertNull(executionLog.getExceptionStackTrace());
    } finally {
      TestLifecycle.end();
    }
  }

  public void testLogFull() throws Exception {
    TestLifecycle.begin();
    try {
      final MockFunction mockFunction = getMockLoggingFunction();
      final ThreadLocalLogEventListener logEventListener = new ThreadLocalLogEventListener();
      final TestCalculationNode calcNode = new TestCalculationNode(logEventListener);
      TestLifecycle.register(calcNode);
      CalculationNodeUtils.configureTestCalcNode(calcNode, mockFunction);
      final CalculationJob calcJob = CalculationNodeUtils.getCalculationJob(mockFunction, ExecutionLogMode.FULL);
      final CalculationJobResultItem resultItemLogIndicators = getResultWithLogging(mockFunction, logEventListener, calcNode, calcJob);

      final ExecutionLog executionLog = resultItemLogIndicators.getExecutionLog();
      assertNotNull(executionLog);
      assertTrue(executionLog.getLogLevels().contains(LogLevel.WARN));
      assertFalse(executionLog.getLogLevels().contains(LogLevel.ERROR));
      assertFalse(executionLog.getLogLevels().contains(LogLevel.INFO));

      assertNotNull(executionLog.getEvents());
      assertEquals(1, executionLog.getEvents().size());
      final LogEvent event = Iterables.getOnlyElement(executionLog.getEvents());
      assertNotNull(event);
      assertEquals(LogLevel.WARN, event.getLevel());
      assertEquals("Warning during execution", event.getMessage());

      assertNull(executionLog.getExceptionClass());
      assertNull(executionLog.getExceptionMessage());
      assertNull(executionLog.getExceptionStackTrace());
    } finally {
      TestLifecycle.end();
    }
  }

  private CalculationJobResultItem getResultWithLogging(final MockFunction mockFunction, final ThreadLocalLogEventListener logEventListener, final TestCalculationNode calcNode,
      final CalculationJob calcJob) throws AsynchronousExecution {
    LogBridge.getInstance().addListener(logEventListener);
    CalculationJobResult jobResult;
    try {
      jobResult = calcNode.executeJob(calcJob);
    } finally {
      LogBridge.getInstance().removeListener(logEventListener);
    }

    assertNotNull(jobResult);
    assertEquals(1, jobResult.getResultItems().size());
    final CalculationJobResultItem resultItem = jobResult.getResultItems().get(0);
    assertEquals(InvocationResult.SUCCESS, resultItem.getResult());
    final ViewComputationCache cache = calcNode.getCache(calcJob.getSpecification());
    assertEquals("Result", cache.getValue(mockFunction.getResultSpec()));
    return resultItem;
  }

  private MockFunction getMockLoggingFunction() {
    final MockFunction fn = new MockLoggingFunction(MockFunction.UNIQUE_ID, ComputationTarget.NULL);
    fn.addResult(new ValueSpecification("OUTPUT", ComputationTargetSpecification.NULL, ValueProperties.with(ValuePropertyNames.FUNCTION, MockFunction.UNIQUE_ID).get()), "Result");
    return fn;
  }

  private class MockLoggingFunction extends MockFunction {

    public MockLoggingFunction(final String uniqueId, final ComputationTarget target) {
      super(uniqueId, target);
    }

    @Override
    public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
      final LogEvent logEvent = new SimpleLogEvent(LogLevel.WARN, "Warning during execution");
      LogBridge.getInstance().log(logEvent);
      return super.execute(executionContext, inputs, target, desiredValues);
    }

  }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>AWSEC2DetachVolumeRequest Class Reference</title>

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

				AWS Mobile SDK for iOS v2.4.1

				Amazon Web Services, Inc.

Index

Hierarchy

							On This Page

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

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

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

	<optgroup label="Properties">

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

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

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

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

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

	</optgroup>

</select>

AWSEC2DetachVolumeRequest Class Reference

	Inherits from
	AWSRequest : AWSModel : AWSMTLModel

	Declared in
	AWSEC2Model.h
AWSEC2Model.m

  device

The device name.

@property (nonatomic, strong) NSString *device

Declared In

AWSEC2Model.h

  dryRun

@property (nonatomic, strong) NSNumber *dryRun

Declared In

AWSEC2Model.h

  force

Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures.

@property (nonatomic, strong) NSNumber *force

Declared In

AWSEC2Model.h

  instanceId

The ID of the instance.

@property (nonatomic, strong) NSString *instanceId

Declared In

AWSEC2Model.h

  volumeId

The ID of the volume.

@property (nonatomic, strong) NSString *volumeId

Declared In

AWSEC2Model.h

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

Generated by appledoc 2.2.1 (build 1333).

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <vector>
#include "paddle/fluid/framework/lod_tensor.h"

namespace paddle {
namespace framework {

using LoDTensorArray = std::vector<LoDTensor>;

}  // namespace framework
}  // namespace paddle


text:
class Timer
{
public:
	Timer() : m_StartTime(0), m_StopTime(0), m_PausedTime(0), m_Running(0), m_Paused(0) { }

	void Start();
	void Stop();
	void Restart();

	void Pause();
	void Unpause();

	bool IsRunning() { return this->m_Running; }
	bool IsPaused() { return this->m_Paused; }

	uint32_t GetDeltaTime();
	uint32_t GetDeltaTime_MS() { return this->GetDeltaTime() % 1000; }
	uint32_t GetDeltaTime_S() { return this->GetDeltaTime() / 1000; }
	uint32_t GetTime() { return (Time::GetTime() - this->m_StartTime); }

private:
	uint32_t m_StartTime;
	uint32_t m_StopTime;
	uint32_t m_PausedTime;

	bool m_Running;
	bool m_Paused;
};

#endif


text:
import {Utils} from "../../Utils.class";
import {ComponentTransform} from "../../ComponentTransform.class";
import {Component_GPU} from "../../Component_GPU.class";
import {Mesh} from "../../Mesh.class";
import {Constants} from "../../Constants";
/**
* @class
*/
export class Grid {
    constructor(sce) {
        this._sce = sce;
        this._project = this._sce.getLoadedProject();
        this._gl = this._project.getActiveStage().getWebGLContext();
        this._utils = new Utils();

        this.node = new Node();
        this.node.setName("grid");
        this._project.getActiveStage().addNode(this.node);

        this.mesh = new Mesh().loadBox();

        // ComponentTransform
        this.comp_transform = new ComponentTransform();
        this.node.addComponent(this.comp_transform);

        // Component_GPU
        this.comp_renderer = new Component_GPU();
        this.node.addComponent(this.comp_renderer);

        this.gridColor = $V3([0.3,0.3,0.3]);
    }

	/**
	* Show the grid
     * @param {number} gridsize
	* @param {number} [separation=1.0] separation of the grid
	*/
	generate(gridsize, separation) {
		this.gridEnabled = true;

		this.size = (gridsize !== undefined && gridsize !== null) ? gridsize : this.size;
		this.separation = (separation !== undefined && separation !== null) ? separation : this.separation;

		this.countLines = (this.size/this.separation)+1;
		this.countLines *= 2;

		let startX = -(this.size/2);
		let endX = (this.size/2);

		let startZ = -(this.size/2);
		let endZ = (this.size/2);

		let currentX = startX;
		let currentZ = startZ;

		// generate lines for the grid
		let linesVertexArray = [];
		let linesVertexLocArray = [];
		let linesIndexArray = [];
		this.id = 0;
		for(let n = 0, f = this.countLines; n < f; n++) {

			if(currentZ <= endZ) {
				// generate lines in Z
				linesVertexArray.push(	startX, 0.0, currentZ, 1.0,
										endX, 0.0, currentZ, 1.0);

				currentZ += this.separation;
			} else {
				// generate lines in X
				linesVertexArray.push(	currentX, 0.0, startZ, 1.0,
										currentX, 0.0, endZ, 1.0);

				currentX += this.separation;
			}

			linesVertexLocArray.push(this.gridColor.e[0], this.gridColor.e[1], this.gridColor.e[2], 1.0,
									this.gridColor.e[0], this.gridColor.e[1], this.gridColor.e[2], 1.0);
			linesIndexArray.push(this.id, this.id+1);

			this.id += 2;
		}

		// generate lines for axis
		// X
		linesVertexArray.push(	0.0, 0.0, 0.0, 1.0,
								10.0, 0.0, 0.0, 1.0);
		linesVertexLocArray.push(1.0, 0.0, 0.0, 1.0,
								1.0, 0.0, 0.0, 1.0);
		linesIndexArray.push(this.id, this.id+1);
		this.id += 2;

		// Y
		linesVertexArray.push(	0.0, 0.0, 0.0, 1.0,
								0.0, 10.0, 0.0, 1.0);
		linesVertexLocArray.push(0.0, 1.0, 0.0, 1.0,
								0.0, 1.0, 0.0, 1.0);
		linesIndexArray.push(this.id, this.id+1);
		this.id += 2;

		// Z
		linesVertexArray.push(	0.0, 0.0, 0.0, 1.0,
								0.0, 0.0, 10.0, 1.0);
		linesVertexLocArray.push(0.0, 0.0, 1.0, 1.0,
								0.0, 0.0, 1.0, 1.0);
		linesIndexArray.push(this.id, this.id+1);

        this.comp_renderer.setGPUFor( this.comp_renderer.gl,
                                {   "float4*attr vertexPos": (function(){return linesVertexArray;}).bind(this),
                                    "float4*attr vertexColor": (function(){return linesVertexLocArray;}).bind(this),
                                    "indices": (function(){return linesIndexArray;}).bind(this),

                                    "mat4 PMatrix": (function(){return this._project.getActiveStage().getActiveCamera().getComponent(Constants.COMPONENT_TYPES.PROJECTION).getMatrix().transpose().e;}).bind(this),
                                    "mat4 cameraWMatrix": (function(){return this._project.getActiveStage().getActiveCamera().getComponent(Constants.COMPONENT_TYPES.TRANSFORM_TARGET).getMatrix().transpose().e;}).bind(this),
                                    "mat4 nodeWMatrix": (function(){return this.node.getComponent(Constants.COMPONENT_TYPES.TRANSFORM).getMatrixPosition().transpose().e;}).bind(this)
                                },

                                // GRAPHIC PROGRAM
                                {"type": "GRAPHIC",
                                "name": "VFP_GRID",
                                "config": [["RGB"],
                                    // vertex head
                                    'out vec4 vVC;\n',

                                    // vertex source
                                    'vec4 vp = vertexPos[];\n'+
                                    'vec4 vc = vertexColor[];\n'+

                                    'vVC = vc;'+

                                    'gl_Position = PMatrix * cameraWMatrix * nodeWMatrix * vp;\n',

                                    // fragment head
                                    'in vec4 vVC;\n',

                                    // fragment source
                                    'return [vVC];\n'
                                ],
                                "drawMode": 1,
                                "depthTest": true,
                                "blend": true,
                                "blendEquation": Constants.BLENDING_EQUATION_TYPES.FUNC_ADD,
                                "blendSrcMode": Constants.BLENDING_MODES.SRC_ALPHA,
                                "blendDstMode": Constants.BLENDING_MODES.ONE_MINUS_SRC_ALPHA}, (function() {
                this.comp_renderer.setArgUpdatable("PMatrix", true);
                this.comp_renderer.setArgUpdatable("cameraWMatrix", true);
                this.comp_renderer.setArgUpdatable("nodeWMatrix", true);
                this.comp_renderer.getComponentBufferArg("RGB", this._project.getActiveStage().getActiveCamera().getComponent(Constants.COMPONENT_TYPES.GPU));
			}).bind(this));
	};
}
global.Grid = Grid;
module.exports.Grid = Grid;


text:
Gitian building
================

This file was moved to [the UltimateOnlineCash Core documentation repository](https://github.com/bitcoin-core/docs/blob/master/gitian-building.md) at [https://github.com/bitcoin-core/docs](https://github.com/bitcoin-core/docs).


text:
package org.jbpm.dashboard.renderer.service;

/**
 * This class builds the URL to navigate to a dashbuilder application.
 * Basically, adds the locale support,
 * so the locale of the gwt application and the locale for the dashbuilder app will be the same.
 */
public class DashboardURLBuilder {

    final static private String GWT_DEFAULT_LOCALE  = "default";
    final static private String DASHBUILDER_DEFAULT_LOCALE  = "en";
    final static private String SLASH  = "/";

    /**
     *
Returns the url for jBPM dashboard using the current locale.

     *
As GWT does not emulate JRE String#format (https://code.google.com/p/google-web-toolkit/issues/detail?id=3945),
     * the URL is splitted in:a preffix and a suffix.

     * @param preffix The URL value before the language parameter
     * @param suffix The URL value after the language parameter
     * @param localeName The GWT locale name.
     * @return The url for the jBPM dashboard.
     */
    public static String getDashboardURL(String preffix, String suffix, String localeName) {
        if (preffix == null && suffix == null) return null;

        StringBuilder result = new StringBuilder();

        if (preffix != null) result.append(preffix);

        if (localeName != null) {
            if (!preffix.endsWith(SLASH)) result.append(SLASH);
            if (GWT_DEFAULT_LOCALE.equals(localeName)) localeName = DASHBUILDER_DEFAULT_LOCALE;
            result.append(localeName);
        }

        if (suffix != null) {
            if (!result.toString().endsWith(SLASH) && !suffix.startsWith(SLASH)) {
                result.append(SLASH);
            }
            result.append(suffix);
        }

        return result.toString();
    }

}


text:
package obcpbft

import (
	"encoding/base64"
	"fmt"

	"github.com/openblockchain/obc-peer/openchain/consensus"
	"github.com/openblockchain/obc-peer/openchain/util"
	pb "github.com/openblockchain/obc-peer/protos"

	"github.com/golang/protobuf/proto"
	"github.com/spf13/viper"
)

type obcClassic struct {
	cpi  consensus.CPI
	pbft *pbftCore
}

func newObcClassic(id uint64, config *viper.Viper, cpi consensus.CPI) *obcClassic {
	op := &obcClassic{cpi: cpi}
	op.pbft = newPbftCore(id, config, op, cpi)
	return op
}

// RecvMsg receives both CHAIN_TRANSACTION and CONSENSUS messages from
// the stack. New transaction requests are broadcast to all replicas,
// so that the current primary will receive the request.
func (op *obcClassic) RecvMsg(ocMsg *pb.OpenchainMessage) error {
	if ocMsg.Type == pb.OpenchainMessage_CHAIN_TRANSACTION {
		logger.Info("New consensus request received")

		if err := op.validate(ocMsg.Payload); err != nil {
			logger.Warning("Request did not verify: %s", err)
			return err
		}

		op.pbft.request(ocMsg.Payload)

		req := &Request{Payload: ocMsg.Payload}
		msg := &Message{&Message_Request{req}}
		msgRaw, _ := proto.Marshal(msg)
		op.broadcast(msgRaw)

		return nil
	}

	if ocMsg.Type != pb.OpenchainMessage_CONSENSUS {
		return fmt.Errorf("Unexpected message type: %s", ocMsg.Type)
	}

	pbftMsg := &Message{}
	err := proto.Unmarshal(ocMsg.Payload, pbftMsg)
	if err != nil {
		return err
	}
	if req := pbftMsg.GetRequest(); req != nil {
		op.pbft.request(req.Payload)
	} else {
		op.pbft.receive(ocMsg.Payload)
	}

	return nil
}

// Close tells us to release resources we are holding
func (op *obcClassic) Close() {
	op.pbft.close()
}

// =============================================================================
// innerCPI interface (functions called by pbft-core)
// =============================================================================

// multicast a message to all replicas
func (op *obcClassic) broadcast(msgPayload []byte) {
	ocMsg := &pb.OpenchainMessage{
		Type:    pb.OpenchainMessage_CONSENSUS,
		Payload: msgPayload,
	}
	op.cpi.Broadcast(ocMsg)
}

// send a message to a specific replica
func (op *obcClassic) unicast(msgPayload []byte, receiverID uint64) (err error) {
	ocMsg := &pb.OpenchainMessage{
		Type:    pb.OpenchainMessage_CONSENSUS,
		Payload: msgPayload,
	}
	receiverHandle, err := getValidatorHandle(receiverID)
	if err != nil {
		return
	}
	return op.cpi.Unicast(ocMsg, receiverHandle)
}

func (op *obcClassic) sign(msg []byte) ([]byte, error) {
	return op.cpi.Sign(msg)
}

func (op *obcClassic) verify(senderID uint64, signature []byte, message []byte) error {
	senderHandle, err := getValidatorHandle(senderID)
	if err != nil {
		return fmt.Errorf("Could not verify message from %v: %v", senderHandle.Name, err)
	}
	return op.cpi.Verify(senderHandle, signature, message)
}

// validate checks whether the request is valid syntactically.
// For now, we only need this for the obc-sieve verify/verify-set and flush messages.
// Thus, for obc-classic, this is a no-op.
func (op *obcClassic) validate(txRaw []byte) error {
	return nil
}

// execute an opaque request which corresponds to an OBC Transaction
func (op *obcClassic) execute(txRaw []byte) {
	if err := op.validate(txRaw); err != nil {
		logger.Error("Request in transaction did not verify: %s", err)
		return
	}

	tx := &pb.Transaction{}
	err := proto.Unmarshal(txRaw, tx)
	if err != nil {
		logger.Error("Unable to unmarshal transaction: %v", err)
		return
	}

	txs := []*pb.Transaction{tx}
	txBatchID := base64.StdEncoding.EncodeToString(util.ComputeCryptoHash(txRaw))

	if err := op.cpi.BeginTxBatch(txBatchID); err != nil {
		logger.Error("Failed to begin transaction %s: %v", txBatchID, err)
		return
	}

	_, errs := op.cpi.ExecTXs(txs)
	if errs[len(txs)] != nil {
		logger.Error("Failed to execute transaction %s: %v", txBatchID, errs)
		if err = op.cpi.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}

	if err = op.cpi.CommitTxBatch(txBatchID, txs, nil, nil); err != nil {
		logger.Error("Failed to commit transaction %s to the ledger: %v", txBatchID, err)
		if err = op.cpi.RollbackTxBatch(txBatchID); err != nil {
			panic(fmt.Errorf("Unable to rollback transaction %s: %v", txBatchID, err))
		}
		return
	}
}

// called when a view-change happened in the underlying PBFT
// classic mode pbft does not use this information
func (op *obcClassic) viewChange(curView uint64) {
}


text:
/*
This file is licensed under the Apache License v2.0 with LLVM Exceptions.
See https://llvm.org/LICENSE.txt for license information.
SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/

extern int setupterm(char *term, int filedes, int *errret);
extern struct term *set_curterm(struct term *termp);
extern int del_curterm(struct term *termp);
extern int tigetnum(char *capname);

int main() {
  setupterm(0, 0, 0);
  set_curterm(0);
  del_curterm(0);
  tigetnum(0);
}


text:
published: true
title: Thinking Neumannically? Think again ...
layout: post
author: Shivam Agarwal
category: Computer articles
tags:
- John von Neumann
- von Neumann Architecture
- Universal Turing Machine

---

i7 processors having 2.7 GHz clock speed, boosted to 3.3 GHz. Means in one second 3300000000 clock cycles are executed, capable of executing 92 billion instructions per second.

It certainly leaves you with a chill feeling. Isn't it?

Do we ever imagine that so much is going on when we simply do a "quick" check of our facebook account and that too several times a day?

This article is going to be about the most basic element which started the revolution of Digital Computers...

<!-- more -->

**Question**- Have you ever wondered that in the name **John von Neumann**, von starts with a small case v?

One of my great teachers always says – "Tum dekhta hai par dekhta nai", means we see but we don't observe. The question above stands a testimony of the quote.

While building EDVAC (Electronic Discrete Variable Automatic Computer, a computer weighing 7850 kg.), an architecture was proposed as von Neumann Architecture.

Now why are we discussing an architecture that was introduced over 60 years ago? Because, even today you pick any desktop computer and it still uses the same architecture.

John von Neumann was a great mathematician. As the greatest inventions have simplest underlying principle, von Neumann architecture is no exception.

It says that program and data reside in same memory. There is a connection between CPU and memory (RAM), called bus. At a time CPU can either be fetching/writing data or fetching an instruction from memory. It's simple right?

If you're an Undergraduate in Computer Science, I bet some bells must be ringing in your mind. I'll give you a hint, it's called – **"Universal Turing Machine"**, which reads data from memory (through a memory tape) executed it and again writes back the result in memory. It's not just a coincidence for two concepts so similar to emerge in near about the same time. Many of us don't know but Alan Turing and John von Neumann worked together to shape the computers as we see them today.

Coming back to the von Neumann architecture, we still use it with some modifications. Like cache has been inserted to get better speed. But that too is only a modification since at a time processor can either fetch an instruction or fetch/write data. So what's so great about it that we still use it (no offense to sir Neumann). It's simplicity of performing either of the tasks is the main reason why it's still used.

Imagine a computer where Instructions reside in different memory and data in a different one (this is Harvard architecture). The problem will be when to select what has to be done and then the selection would itself require some computation to be done which would again be performed by the same CPU. This complexity has forced processor makers to think in terms of Neumann architecture.

The obvious question would be that if there is only a single bus, wouldn't it be a drawback in terms of speed? Definitely yes!!

**The term "von Neumann bottleneck" was coined by John Backus in his 1977 ACM Turing Award lecture.** According to Backus:
<cite>
"Surely there must be a less primitive way of making big changes in the store than by pushing vast numbers of words back and forth through the von Neumann bottleneck. Not only is this tube a literal bottleneck for the data traffic of a problem, but, more importantly, it is an intellectual bottleneck that has kept us tied to word-at-a-time thinking instead of encouraging us to think in terms of the larger conceptual units of the task at hand. Thus programming is basically planning and detailing the enormous traffic of words through the von Neumann bottleneck, and much of that traffic concerns not significant data itself, but where to find it."</cite>

To make it simpler, we all know about instruction set and simple C.

Suppose we want to add two numbers. The c statement will be:

c = a + b;

Where a, b, c are variables.
Finally it will be converted into a sequence of instructions such as:

LDA  a

ADD b

STA  c

Further will be converted to:

DR -> M[a]   //DR- data register M[a]- stands for memory reference at address a.

AC -> DR         // AC – accumulator register

DR -> M[b]

AC -> AC + DR

M[c] -> AC

We observe that at one time either the data or an instruction (such as addition) is fetched from memory (and hence the Neumann architecture).

That means computer has to perform tasks serially? Yes, it performs tasks serially at this level. But today parallelism is achieved today using computers based on von Neumann architectures in a different way through threads and employing multiple processors in a system. You can find a great practical article here.

But from our previous program we can see how von Neumann architecture forces high level language developers to think in Neumann way. Read ["this"](http://www.cs.cmu.edu/~crary/819-f09/Backus78.pdf) article and you will be amazed.

There are systems build on Harvard architecture. But due to the concept of Cache memory we use today (which is modified Harvard architecture), the Harvard architecture is of little practical use.

In my opinion John von Neumann was a great administrator too, coz he employed the greatest administration rule, which was **Keep It Short and Simple**, unlike this article. :P

Oh I almost forgot to answer: **why v is in small case in the name John von Neumann?**

The answer is- **go GOOGLE it!!**  Self learning is the best.

**Be force with you.**

Further Read ["The First Draft Report on the EDVAC"](http://qss.stanford.edu/~godfrey/vonNeumann/vnedvac.pdf).


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Office2019.Drawing.SVG;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using Svg;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

using BlipFill = DocumentFormat.OpenXml.Drawing.BlipFill;
using Extension = DocumentFormat.OpenXml.Drawing.Extension;
using Picture = DocumentFormat.OpenXml.Drawing.Picture;

namespace SVGExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Common.ExampleUtilities.ShowHelp(new string[]
                {
                    "SVGExample: ",
                    "Usage: SVGExample <filename> <svg>",
                    "Where: <filename> is the path to the file in which to add the svg.",
                    "Where: <svg> is the path to the svg file to add.",
                });
            }
            else if (Common.ExampleUtilities.CheckIfFilesExist(args))
            {
                AddSvg(args[0], args[1]);
            }
        }

        public static void AddSvg(string docPath, string svgPath)
        {
            if (docPath == null)
            {
                throw new ArgumentNullException(nameof(docPath));
            }

            if (svgPath == null)
            {
                throw new ArgumentNullException(nameof(svgPath));
            }

            using (PresentationDocument presentationDocument = PresentationDocument.Open(docPath, true))
            {
                // Get the relationship ID of the first slide.
                PresentationPart presentationPart = presentationDocument.PresentationPart;

                // Verify that the presentation part and presentation exist.
                if (presentationPart != null && presentationPart.Presentation != null)
                {
                    OpenXmlElementList slideIds = presentationPart.Presentation.SlideIdList.ChildElements;

                    if (slideIds.Count > 0)
                    {
                        string relId = (slideIds[0] as SlideId).RelationshipId;
                        SlidePart slidePart = (SlidePart)presentationPart.GetPartById(relId);

                        // Get count of relationships and increment by one to make next unique id
                        int partsCount = slidePart.Parts.Count();
                        string pngId = $"rId{++partsCount}";
                        string svgId = $"rId{++partsCount}";

                        var creationId = new DocumentFormat.OpenXml.Office2016.Drawing.CreationId();
                        creationId.AddNamespaceDeclaration("a16", "http://schemas.microsoft.com/office/drawing/2014/main");
                        creationId.Id = "{E36DC281-2F17-44E3-80EA-AB5BFA90E4D7}";

                        var picture = new DocumentFormat.OpenXml.Presentation.Picture();

                        // add non visual properties to picture
                        picture.NonVisualPictureProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureProperties();
                        picture.NonVisualPictureProperties.NonVisualDrawingProperties = new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() { Id = new UInt32Value((uint)++partsCount), Name = "Picture 1" };
                        picture.NonVisualPictureProperties.NonVisualDrawingProperties.AppendChild(new DocumentFormat.OpenXml.Drawing.ExtensionList(
                                    new Extension(
                                        creationId)
                                    { Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}" }));
                        picture.NonVisualPictureProperties.NonVisualPictureDrawingProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties();
                        picture.NonVisualPictureProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
                        picture.NonVisualPictureProperties.NonVisualPictureDrawingProperties.PictureLocks = new PictureLocks() { NoChangeAspect = true };

                        // add blipfill
                        picture.BlipFill = new DocumentFormat.OpenXml.Presentation.BlipFill();
                        picture.BlipFill.Blip = new Blip() { Embed = svgId };
                        picture.BlipFill.AppendChild(new Stretch(
                                new FillRectangle()));
                        BlipExtensionList blipExtensionList = new BlipExtensionList();
                        Extension ext = blipExtensionList.AppendChild(new Extension());
                        ext.Uri = string.Empty;
                        ext.AppendChild(new SVGBlip());
                        picture.BlipFill.Blip.AppendChild(blipExtensionList);
                        picture.ShapeProperties = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
                        picture.ShapeProperties.Transform2D = new Transform2D();
                        picture.ShapeProperties.Transform2D.Offset = new Offset();
                        picture.ShapeProperties.Transform2D.Offset.X = new Int64Value(5638800L);
                        picture.ShapeProperties.Transform2D.Offset.Y = new Int64Value(2971800L);
                        picture.ShapeProperties.Transform2D.Extents = new Extents();
                        picture.ShapeProperties.Transform2D.Extents.Cx = new Int64Value(914400L);
                        picture.ShapeProperties.Transform2D.Extents.Cy = new Int64Value(914400L);
                        picture.ShapeProperties.AppendChild(new PresetGeometry(
                            new AdjustValueList())
                        { Preset = ShapeTypeValues.Rectangle });

                        // Create a temporary in memory png file from the svg (inserting svg requires a png copy to be visible)
                        // Using https://www.nuget.org/packages/Svg/ to convert svg to png
                        SvgDocument svgDocument = SvgDocument.Open(svgPath);
                        using System.Drawing.Bitmap bitmap = svgDocument.Draw();
                        string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";
                        bitmap.Save(fileName, ImageFormat.Png);

                        // Add png to slidePart
                        using FileStream pngFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        pngFileStream.Seek(0, SeekOrigin.Begin);
                        ImagePart pngImagePart = slidePart.AddImagePart(ImagePartType.Png, pngId);
                        pngImagePart.FeedData(pngFileStream);
                        picture.BlipFill.Blip.Embed = pngId;

                        // Add image part with new svg id
                        using FileStream svgFileStream = new FileStream(svgPath, FileMode.Open, FileAccess.Read);
                        svgFileStream.Seek(0, SeekOrigin.Begin);
                        ImagePart svgImgPart = slidePart.AddImagePart(ImagePartType.Svg, svgId);
                        svgImgPart.FeedData(svgFileStream);
                        IEnumerable<SVGBlip> sVGBlips = blipExtensionList.Descendants<SVGBlip>();
                        sVGBlips.First().Embed = svgId;
                        slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(picture);
                    }
                }
            }
        }
    }
}


text:
const { USER_ID } = process.env;

const debug = require('debug')('feedparser');
const batch = require('through2-batch');

const { Newsfeed, Article } = require('./resources');

const feedParser = require('./feedparser');
const converter = require('./converter');

const context = {
  userId: USER_ID,
  godMode: true,
  applicationId: 'governorhub'
};

module.exports = {
  parseFeeds
};

function pipeAndIgnoreErrors(...streams) {
  return streams.reduce((from, to) => {
    from.pipe(to);

    let ended = false;
    from.on('end', () => {
      ended = true;
    });

    to.on('error', err => {
      console.error(err);
      // Need to repipe as (unexpectedly to me) node will have
      // unpiped us from the original stream.
      //
      // See https://nodejs.org/api/stream.html#stream_event_unpipe

      if (ended) {
        to.end();
      } else {
        from.pipe(to);
      }
    });

    return to;
  });
}

function parseFeeds() {
  const newsfeedsStream = Newsfeed.streamQuery({
    context,
    query: { find: { source: { $ne: null } } }
    // query: {
    //   find: {
    //     source: {
    //       $in: [
    //         'http://www.4children.org.uk/News/RSS',
    //         'http://feeds.bbci.co.uk/news/education/rss.xml'
    //       ]
    //     }
    //   }
    // }
  });

  const outStream = pipeAndIgnoreErrors(
    newsfeedsStream,
    feedParser(),
    converter(),
    createArticle()
  );

  outStream.on('finish', function() {
    console.log('done');
  });
}

function createArticle() {
  return batch.obj({ batchSize: 200 }, async (articles, enc, callback) => {
    try {
      console.log(`Creating ${articles.length} articles`);
      const guids = articles.map(article => article.guid);
      debug('Creating articles', articles);
      await Article.bulkUpdateOrCreate({ context, articles });
      debug('Created article', guids);
      callback();
    } catch (err) {
      callback(err);
    }
  });
}


text:
<?php

class AdminController extends BController
{
	public $defaultAction = 'admin';
	public $layout = '//layouts/main';

	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','create','update','view','testNewView','ajaxEdit'),
				'users'=>UserModule::getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['User']))
            $model->attributes=$_GET['User'];

        $this->render('index',array(
            'model'=>$model,
        ));
		/*$dataProvider=new CActiveDataProvider('User', array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->controller->module->user_page_size,
			),
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));//*/
	}

	public function actionTestNewView()
	{
		$model = $this->loadModel();
		$this->render('test',array(
			'model'=>$model,
		));
	}

	public function actionAjaxEdit()
	{
		$es = new EditableSaver('User');
		$es->update();/*
		$model = User::model()->findByPk($_POST['pk']);
		$model->username = $_POST['value'];
		$model->save();*/
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$model = $this->loadModel();
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;
		//$profile=new Profile;
		$this->performAjaxValidation(array($model));
		if(isset($_POST['User']))
		{

			$model->attributes=$_POST['User'];
			$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
			//$profile->attributes=$_POST['Profile'];
			//$profile->user_id=0;

			if($model->validate()) {
                $model->password=Yii::app()->controller->module->encrypting($model->password);
				if($model->save(false)) {

				}else{
                    $errores = $model->getErrors();
                    dump($errores);exit;
                }
				$this->redirect(array('view','id'=>$model->id));
			} else {

			}
		}

		$this->render('create',array(
			'model'=>$model,
			//'profile'=>$profile,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();
		//$profile=$model->profile;
		$this->performAjaxValidation(array($model));
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];

			if($model->validate()) {
				$old_password = User::model()->notsafe()->findByPk($model->id);
				if ($old_password->password!=$model->password) {
					$model->password=Yii::app()->controller->module->encrypting($model->password);
					$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
				}
				//Why save false --> just encrypting password
				$model->save(false);
				//$profile->save();
				$this->redirect(array('view','id'=>$model->id));
			} else {
				//$profile->validate();
			}
		}

		$this->render('update',array(
			'model'=>$model,
			//'profile'=>$profile,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{

		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel();

			//$profile = Profile::model()->findByPk($model->id);
			//$profile->delete();
			$model->delete();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax']))
				$this->redirect(array('/user/admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($validate)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
        {
            echo CActiveForm::validate($validate);
            Yii::app()->end();
        }
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=User::model()->notsafe()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

}


text:
declare module '@ember-decorators/runloop';

declare module 'ember-modal-dialog/components/modal-dialog';

declare module 'ember-radio-button/components/radio-button';

declare module 'ember-simple-auth/mixins/authenticated-route-mixin' {
  import Mixin from '@ember/object/mixin';
  export default Mixin;
}

declare module 'wherehows-web/initializers/ember-cli-mirage' {
  import { IMirageServer } from 'wherehows-web/typings/ember-cli-mirage';

  const startMirage: (env?: string) => IMirageServer;

  export { startMirage };
}

declare module 'ivy-tabs/components/ivy-tabs-tablist' {
  import Component from '@ember/component';
  export default class IvyTabsTablistComponent extends Component {
    focusSelectedTab: () => void;
    selectPreviousTab: () => void;
    selectNextTab: () => void;
  }
}

declare module 'ember-simple-auth/authenticators/base' {
  import EmberObject from '@ember/object';
  export default EmberObject;
}

/**
 * Augments the Transition interface in the Ember namespace
 */
declare module 'ember' {
  export namespace Ember {
    // eslint-disable-next-line typescript/interface-name-prefix
    interface Transition {
      params: Record<string, any>;
      // temporary typedef till resolution of https://github.com/tildeio/router.js/issues/250
      promise?: Promise<any> & { finally: (callback: Function, label?: string) => Promise<any> };
    }
  }
}

declare module 'ember-simple-auth/services/session' {
  import Ember from 'ember';
  import Service from '@ember/service';

  export default class Session extends Service {
    authenticate(authenticator: string, ...args: Array<any>): Promise<void>;
    authorize(authorizer: string, block: Function): void;
    invalidate(...args: Array<any>): Promise<void>;
    attemptedTransition: Ember.Transition | null;
    data: Readonly<object | { authenticated: {} }>;
    isAuthenticated: boolean;
  }
}

declare module 'ember-inflector' {
  const singularize: (arg: string) => string;
  function pluralize(arg: string): string;
  function pluralize(count: number, arg: string, options?: { withoutCount: number }): string;
  export { singularize, pluralize };
}

declare module 'ember-cli-mirage';

// https://github.com/ember-cli/ember-fetch/issues/72
// TS assumes the mapping btw ES modules and CJS modules is 1:1
// However, `ember-fetch` is the module name, but it's imported with `fetch`
declare module 'fetch' {
  export default function fetch(
    input: RequestInfo,
    options?: { method?: string; body?: any; headers?: object | Headers; credentials?: RequestCredentials }
  ): Promise<Response>;
}

declare module 'scrollmonitor';

/**
 * Merges global type defs for global modules on the window namespace.
 * These should be refactored into imported modules if available or shimmed as such
 */
// eslint-disable-next-line typescript/interface-name-prefix
interface Window {
  marked(param: string): { htmlSafe: () => string };

  JsonHuman: {
    format(
      data: any,
      options?: {
        showArrayIndex: void | boolean;
        hyperlinks: { enable: boolean; keys: null | Array<string>; target: string };
        bool: {
          //https://github.com/prettier/prettier/issues/3102
          text: object; //{ 'true': string; 'false': string };
          image: object; //{ 'true': string; 'false': string };
          showImage: boolean;
          showText: boolean;
        };
      }
    ): Element;
  };

  // global array for piwik tracking
  _paq: Array<any>;
}

/**
 * Merges the JSONView plugin into the jquery interface
 */
// eslint-disable-next-line typescript/interface-name-prefix
interface JQuery {
  JSONView(json: object): this;
  treegrid(): this;
}


text:
This software is no longer maintained or deployed.  It is preserved here
for historical interest.


text:
var express = require('express');
var config = require('./server/config/environment')(); // because config is a function
var configureExpress = require('./server/config/express');
var http = require('http');
var routes = require('./server/routes');

// declaring environment
var app = express();

// configuring express
configureExpress(app);

// configuring routes
routes.configure(app);

// app.listen(config.port);

var server = http.createServer(app);
server.listen(config.port);

console.log('magic is happening on port %d', config.port);


text:
namespace llvm {

/// This class maintains the abbreviations read from a block info block.
class BitstreamBlockInfo {
public:
  /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
  /// describe abbreviations that all blocks of the specified ID inherit.
  struct BlockInfo {
    unsigned BlockID = 0;
    std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
    std::string Name;
    std::vector<std::pair<unsigned, std::string>> RecordNames;
  };

private:
  std::vector<BlockInfo> BlockInfoRecords;

public:
  /// If there is block info for the specified ID, return it, otherwise return
  /// null.
  const BlockInfo *getBlockInfo(unsigned BlockID) const {
    // Common case, the most recent entry matches BlockID.
    if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
      return &BlockInfoRecords.back();

    for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
         i != e; ++i)
      if (BlockInfoRecords[i].BlockID == BlockID)
        return &BlockInfoRecords[i];
    return nullptr;
  }

  BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
    if (const BlockInfo *BI = getBlockInfo(BlockID))
      return *const_cast<BlockInfo*>(BI);

    // Otherwise, add a new record.
    BlockInfoRecords.emplace_back();
    BlockInfoRecords.back().BlockID = BlockID;
    return BlockInfoRecords.back();
  }
};

/// This represents a position within a bitstream. There may be multiple
/// independent cursors reading within one bitstream, each maintaining their
/// own local state.
class SimpleBitstreamCursor {
  ArrayRef<uint8_t> BitcodeBytes;
  size_t NextChar = 0;

public:
  /// This is the current data we have pulled from the stream but have not
  /// returned to the client. This is specifically and intentionally defined to
  /// follow the word size of the host machine for efficiency. We use word_t in
  /// places that are aware of this to make it perfectly explicit what is going
  /// on.
  using word_t = size_t;

private:
  word_t CurWord = 0;

  /// This is the number of bits in CurWord that are valid. This is always from
  /// [0...bits_of(size_t)-1] inclusive.
  unsigned BitsInCurWord = 0;

public:
  static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;

  SimpleBitstreamCursor() = default;
  explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
      : BitcodeBytes(BitcodeBytes) {}
  explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
      : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
  explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
      : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}

  bool canSkipToPos(size_t pos) const {
    // pos can be skipped to if it is a valid address or one byte past the end.
    return pos <= BitcodeBytes.size();
  }

  bool AtEndOfStream() {
    return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
  }

  /// Return the bit # of the bit we are reading.
  uint64_t GetCurrentBitNo() const {
    return NextChar*CHAR_BIT - BitsInCurWord;
  }

  // Return the byte # of the current bit.
  uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }

  ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }

  /// Reset the stream to the specified bit number.
  Error JumpToBit(uint64_t BitNo) {
    size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
    unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
    assert(canSkipToPos(ByteNo) && "Invalid location");

    // Move the cursor to the right word.
    NextChar = ByteNo;
    BitsInCurWord = 0;

    // Skip over any bits that are already consumed.
    if (WordBitNo) {
      if (Expected<word_t> Res = Read(WordBitNo))
        return Error::success();
      else
        return Res.takeError();
    }

    return Error::success();
  }

  /// Get a pointer into the bitstream at the specified byte offset.
  const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
    return BitcodeBytes.data() + ByteNo;
  }

  /// Get a pointer into the bitstream at the specified bit offset.
  ///
  /// The bit offset must be on a byte boundary.
  const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
    assert(!(BitNo % 8) && "Expected bit on byte boundary");
    return getPointerToByte(BitNo / 8, NumBytes);
  }

  Error fillCurWord() {
    if (NextChar >= BitcodeBytes.size())
      return createStringError(std::errc::io_error,
                               "Unexpected end of file reading %u of %u bytes",
                               NextChar, BitcodeBytes.size());

    // Read the next word from the stream.
    const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
    unsigned BytesRead;
    if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
      BytesRead = sizeof(word_t);
      CurWord =
          support::endian::read<word_t, support::little, support::unaligned>(
              NextCharPtr);
    } else {
      // Short read.
      BytesRead = BitcodeBytes.size() - NextChar;
      CurWord = 0;
      for (unsigned B = 0; B != BytesRead; ++B)
        CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
    }
    NextChar += BytesRead;
    BitsInCurWord = BytesRead * 8;
    return Error::success();
  }

  Expected<word_t> Read(unsigned NumBits) {
    static const unsigned BitsInWord = MaxChunkSize;

    assert(NumBits && NumBits <= BitsInWord &&
           "Cannot return zero or more than BitsInWord bits!");

    static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;

    // If the field is fully contained by CurWord, return it quickly.
    if (BitsInCurWord >= NumBits) {
      word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));

      // Use a mask to avoid undefined behavior.
      CurWord >>= (NumBits & Mask);

      BitsInCurWord -= NumBits;
      return R;
    }

    word_t R = BitsInCurWord ? CurWord : 0;
    unsigned BitsLeft = NumBits - BitsInCurWord;

    if (Error fillResult = fillCurWord())
      return std::move(fillResult);

    // If we run out of data, abort.
    if (BitsLeft > BitsInCurWord)
      return createStringError(std::errc::io_error,
                               "Unexpected end of file reading %u of %u bits",
                               BitsInCurWord, BitsLeft);

    word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));

    // Use a mask to avoid undefined behavior.
    CurWord >>= (BitsLeft & Mask);

    BitsInCurWord -= BitsLeft;

    R |= R2 << (NumBits - BitsLeft);

    return R;
  }

  Expected<uint32_t> ReadVBR(unsigned NumBits) {
    Expected<unsigned> MaybeRead = Read(NumBits);
    if (!MaybeRead)
      return MaybeRead;
    uint32_t Piece = MaybeRead.get();

    if ((Piece & (1U << (NumBits-1))) == 0)
      return Piece;

    uint32_t Result = 0;
    unsigned NextBit = 0;
    while (true) {
      Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;

      if ((Piece & (1U << (NumBits-1))) == 0)
        return Result;

      NextBit += NumBits-1;
      MaybeRead = Read(NumBits);
      if (!MaybeRead)
        return MaybeRead;
      Piece = MaybeRead.get();
    }
  }

  // Read a VBR that may have a value up to 64-bits in size. The chunk size of
  // the VBR must still be <= 32 bits though.
  Expected<uint64_t> ReadVBR64(unsigned NumBits) {
    Expected<uint64_t> MaybeRead = Read(NumBits);
    if (!MaybeRead)
      return MaybeRead;
    uint32_t Piece = MaybeRead.get();

    if ((Piece & (1U << (NumBits-1))) == 0)
      return uint64_t(Piece);

    uint64_t Result = 0;
    unsigned NextBit = 0;
    while (true) {
      Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;

      if ((Piece & (1U << (NumBits-1))) == 0)
        return Result;

      NextBit += NumBits-1;
      MaybeRead = Read(NumBits);
      if (!MaybeRead)
        return MaybeRead;
      Piece = MaybeRead.get();
    }
  }

  void SkipToFourByteBoundary() {
    // If word_t is 64-bits and if we've read less than 32 bits, just dump
    // the bits we have up to the next 32-bit boundary.
    if (sizeof(word_t) > 4 &&
        BitsInCurWord >= 32) {
      CurWord >>= BitsInCurWord-32;
      BitsInCurWord = 32;
      return;
    }

    BitsInCurWord = 0;
  }

  /// Return the size of the stream in bytes.
  size_t SizeInBytes() const { return BitcodeBytes.size(); }

  /// Skip to the end of the file.
  void skipToEnd() { NextChar = BitcodeBytes.size(); }
};

/// When advancing through a bitstream cursor, each advance can discover a few
/// different kinds of entries:
struct BitstreamEntry {
  enum {
    Error,    // Malformed bitcode was found.
    EndBlock, // We've reached the end of the current block, (or the end of the
              // file, which is treated like a series of EndBlock records.
    SubBlock, // This is the start of a new subblock of a specific ID.
    Record    // This is a record with a specific AbbrevID.
  } Kind;

  unsigned ID;

  static BitstreamEntry getError() {
    BitstreamEntry E; E.Kind = Error; return E;
  }

  static BitstreamEntry getEndBlock() {
    BitstreamEntry E; E.Kind = EndBlock; return E;
  }

  static BitstreamEntry getSubBlock(unsigned ID) {
    BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
  }

  static BitstreamEntry getRecord(unsigned AbbrevID) {
    BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
  }
};

/// This represents a position within a bitcode file, implemented on top of a
/// SimpleBitstreamCursor.
///
/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
/// be passed by value.
class BitstreamCursor : SimpleBitstreamCursor {
  // This is the declared size of code values used for the current block, in
  // bits.
  unsigned CurCodeSize = 2;

  /// Abbrevs installed at in this block.
  std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;

  struct Block {
    unsigned PrevCodeSize;
    std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;

    explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
  };

  /// This tracks the codesize of parent blocks.
  SmallVector<Block, 8> BlockScope;

  BitstreamBlockInfo *BlockInfo = nullptr;

public:
  static const size_t MaxChunkSize = sizeof(word_t) * 8;

  BitstreamCursor() = default;
  explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
      : SimpleBitstreamCursor(BitcodeBytes) {}
  explicit BitstreamCursor(StringRef BitcodeBytes)
      : SimpleBitstreamCursor(BitcodeBytes) {}
  explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
      : SimpleBitstreamCursor(BitcodeBytes) {}

  using SimpleBitstreamCursor::AtEndOfStream;
  using SimpleBitstreamCursor::canSkipToPos;
  using SimpleBitstreamCursor::fillCurWord;
  using SimpleBitstreamCursor::getBitcodeBytes;
  using SimpleBitstreamCursor::GetCurrentBitNo;
  using SimpleBitstreamCursor::getCurrentByteNo;
  using SimpleBitstreamCursor::getPointerToByte;
  using SimpleBitstreamCursor::JumpToBit;
  using SimpleBitstreamCursor::Read;
  using SimpleBitstreamCursor::ReadVBR;
  using SimpleBitstreamCursor::ReadVBR64;
  using SimpleBitstreamCursor::SizeInBytes;
  using SimpleBitstreamCursor::skipToEnd;

  /// Return the number of bits used to encode an abbrev #.
  unsigned getAbbrevIDWidth() const { return CurCodeSize; }

  /// Flags that modify the behavior of advance().
  enum {
    /// If this flag is used, the advance() method does not automatically pop
    /// the block scope when the end of a block is reached.
    AF_DontPopBlockAtEnd = 1,

    /// If this flag is used, abbrev entries are returned just like normal
    /// records.
    AF_DontAutoprocessAbbrevs = 2
  };

  /// Advance the current bitstream, returning the next entry in the stream.
  Expected<BitstreamEntry> advance(unsigned Flags = 0) {
    while (true) {
      if (AtEndOfStream())
        return BitstreamEntry::getError();

      Expected<unsigned> MaybeCode = ReadCode();
      if (!MaybeCode)
        return MaybeCode.takeError();
      unsigned Code = MaybeCode.get();

      if (Code == bitc::END_BLOCK) {
        // Pop the end of the block unless Flags tells us not to.
        if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
          return BitstreamEntry::getError();
        return BitstreamEntry::getEndBlock();
      }

      if (Code == bitc::ENTER_SUBBLOCK) {
        if (Expected<unsigned> MaybeSubBlock = ReadSubBlockID())
          return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
        else
          return MaybeSubBlock.takeError();
      }

      if (Code == bitc::DEFINE_ABBREV &&
          !(Flags & AF_DontAutoprocessAbbrevs)) {
        // We read and accumulate abbrev's, the client can't do anything with
        // them anyway.
        if (Error Err = ReadAbbrevRecord())
          return std::move(Err);
        continue;
      }

      return BitstreamEntry::getRecord(Code);
    }
  }

  /// This is a convenience function for clients that don't expect any
  /// subblocks. This just skips over them automatically.
  Expected<BitstreamEntry> advanceSkippingSubblocks(unsigned Flags = 0) {
    while (true) {
      // If we found a normal entry, return it.
      Expected<BitstreamEntry> MaybeEntry = advance(Flags);
      if (!MaybeEntry)
        return MaybeEntry;
      BitstreamEntry Entry = MaybeEntry.get();

      if (Entry.Kind != BitstreamEntry::SubBlock)
        return Entry;

      // If we found a sub-block, just skip over it and check the next entry.
      if (Error Err = SkipBlock())
        return std::move(Err);
    }
  }

  Expected<unsigned> ReadCode() { return Read(CurCodeSize); }

  // Block header:
  //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]

  /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
  Expected<unsigned> ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }

  /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
  /// of this block.
  Error SkipBlock() {
    // Read and ignore the codelen value.
    if (Expected<uint32_t> Res = ReadVBR(bitc::CodeLenWidth))
      ; // Since we are skipping this block, we don't care what code widths are
        // used inside of it.
    else
      return Res.takeError();

    SkipToFourByteBoundary();
    Expected<unsigned> MaybeNum = Read(bitc::BlockSizeWidth);
    if (!MaybeNum)
      return MaybeNum.takeError();
    size_t NumFourBytes = MaybeNum.get();

    // Check that the block wasn't partially defined, and that the offset isn't
    // bogus.
    size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
    if (AtEndOfStream())
      return createStringError(std::errc::illegal_byte_sequence,
                               "can't skip block: already at end of stream");
    if (!canSkipToPos(SkipTo / 8))
      return createStringError(std::errc::illegal_byte_sequence,
                               "can't skip to bit %zu from %" PRIu64, SkipTo,
                               GetCurrentBitNo());

    if (Error Res = JumpToBit(SkipTo))
      return Res;

    return Error::success();
  }

  /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
  Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);

  bool ReadBlockEnd() {
    if (BlockScope.empty()) return true;

    // Block tail:
    //    [END_BLOCK, <align4bytes>]
    SkipToFourByteBoundary();

    popBlockScope();
    return false;
  }

private:
  void popBlockScope() {
    CurCodeSize = BlockScope.back().PrevCodeSize;

    CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
    BlockScope.pop_back();
  }

  //===--------------------------------------------------------------------===//
  // Record Processing
  //===--------------------------------------------------------------------===//

public:
  /// Return the abbreviation for the specified AbbrevId.
  const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
    unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
    if (AbbrevNo >= CurAbbrevs.size())
      report_fatal_error("Invalid abbrev number");
    return CurAbbrevs[AbbrevNo].get();
  }

  /// Read the current record and discard it, returning the code for the record.
  Expected<unsigned> skipRecord(unsigned AbbrevID);

  Expected<unsigned> readRecord(unsigned AbbrevID,
                                SmallVectorImpl<uint64_t> &Vals,
                                StringRef *Blob = nullptr);

  //===--------------------------------------------------------------------===//
  // Abbrev Processing
  //===--------------------------------------------------------------------===//
  Error ReadAbbrevRecord();

  /// Read and return a block info block from the bitstream. If an error was
  /// encountered, return None.
  ///
  /// \param ReadBlockInfoNames Whether to read block/record name information in
  /// the BlockInfo block. Only llvm-bcanalyzer uses this.
  Expected<Optional<BitstreamBlockInfo>>
  ReadBlockInfoBlock(bool ReadBlockInfoNames = false);

  /// Set the block info to be used by this BitstreamCursor to interpret
  /// abbreviated records.
  void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
};

} // end llvm namespace

#endif // LLVM_BITSTREAM_BITSTREAMREADER_H


text:
package kr.debop4j.core.io;

import kr.debop4j.core.Guard;
import kr.debop4j.core.ISerializer;
import kr.debop4j.core.cryptography.symmetric.ISymmetricByteEncryptor;
import kr.debop4j.core.cryptography.symmetric.RC2ByteEncryptor;

/**
 * 객체 직렬화를 수행한 후, 암호화를 수행합니다.
 *
 * @author 배성혁 ( sunghyouk.bae@gmail.com )
 * @since 12. 12. 17
 */
public class EncryptableSerializer extends SerializerDecorator {

    private final ISymmetricByteEncryptor encryptor;

    /**
     * Instantiates a new Encryptable serializer.
     *
     * @param serializer the serializer
     */
    public EncryptableSerializer(ISerializer serializer) {
        this(serializer, new RC2ByteEncryptor());
    }

    /**
     * Instantiates a new Encryptable serializer.
     *
     * @param serializer the serializer
     * @param encryptor  the encryptor
     */
    public EncryptableSerializer(ISerializer serializer, ISymmetricByteEncryptor encryptor) {
        super(serializer);

        Guard.shouldNotBeNull(encryptor, "encryptor");
        this.encryptor = encryptor;
    }

    @Override
    public byte[] serialize(Object graph) {
        return encryptor.encrypt(super.serialize(graph));
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        return super.deserialize(encryptor.decrypt(bytes), clazz);
    }
}


text:
// Copyright 2014-2015 Boundary, Inc.
//
// 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.
package com.boundary.sdk.event.esper;

import static org.apache.camel.LoggingLevel.DEBUG;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boundary.sdk.event.BoundaryRouteBuilder;
import com.espertech.esper.client.EventBean;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Implementation of a Esper streaming route
 */
public class EsperRouteBuilder extends BoundaryRouteBuilder {

	private static Logger LOG = LoggerFactory.getLogger(EsperRouteBuilder.class);

	private String configuration;
	private String instance;
	private QueryList queryList;

	public EsperRouteBuilder() {
	}

	public String getConfiguration() {
		return configuration;
	}

	public void setConfiguration(String configuration) {
		this.configuration = configuration;
	}

	public String getInstance() {
		return instance;
	}

	public void setInstance(String instance) {
		this.instance = instance;
	}

	protected QueryList getQueryList() {
		return this.queryList;
	}

	private QueryList load(URI uri) {
		ObjectMapper mapper = new ObjectMapper();
		QueryList queryList = null;
		LOG.info("Loading queries from {}",uri);
		File file = new File(uri);

		try {
			queryList = mapper.readValue(file,QueryList.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return queryList;
	}

	/**
	 * TODO: Proper handling of exception
	 * @throws URISyntaxException {@link URISyntaxException}
	 */
	protected void loadConfiguration() throws URISyntaxException {
		ClassLoader classLoader = this.getClass().getClassLoader();
		URL url = classLoader.getResource(this.configuration);
		this.queryList = load(url.toURI());
	}

	public void configure() throws Exception {
		String inputUri = String.format("esper://%s?configured=true",this.getInstance());

        from(this.getFromUri())
		.startupOrder(this.getStartUpOrder())
		.routeId(this.getRouteId() + "-INPUT")
		.unmarshal().serialization()
		.log(DEBUG,"headers: ${headers} body; ${body}, class: ${body.getClass.toString}")
        .to(inputUri);

        addQueriesToRoute();
    }

	private void addQueriesToRoute() throws URISyntaxException {
		loadConfiguration();
		QueryList list = this.getQueryList();

		for (Query query : list.getQueries()) {
			if (query.isEnabled()) {
				addQuery(query.getName(),query.getQuery());
			}
		}
	}

    private void addQuery(String name,String query) {
		String queryUri = String.format("esper://%s?configured=true&eql=%s",
				this.getInstance(),query);
		this.startUpOrder++;

		LOG.info("Adding query \"{}\": \"{}\"",name,query);

        from(queryUri)
        .startupOrder(this.getStartUpOrder())
        .routeId(String.format("%s-QUERY: %s",this.getRouteId(),name))
        .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                    	Message in = exchange.getIn();
                        EventBean event = in.getBody(EventBean.class);
                        Object e = event.getUnderlying();
                        in.setBody(e);
                    }
                })
        .log(DEBUG,"headers: ${headers} body; ${body}, class: ${body.getClass.toString}")
        .marshal().serialization()
        .to(this.toUri);
    }
}


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:text="Text View" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:text="Button" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:hint="Edit Text"
            android:text="Edit Text" />

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:src="@drawable/picture" />

        <ImageButton
            android:id="@+id/image_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/picture"
            android:scaleType="fitXY" />

        <AutoCompleteTextView
            android:id="@+id/auto"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:text="AutoCompleteTextView" />

        <MultiAutoCompleteTextView
            android:id="@+id/multi_auto"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:text="MultiAutoCompleteTextView" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:orientation="horizontal">

            <CheckBox
                android:layout_width="?attr/actionBarSize"
                android:layout_height="?attr/actionBarSize" />

            <RadioGroup
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RadioButton
                    android:layout_width="?attr/actionBarSize"
                    android:layout_height="?attr/actionBarSize" />

                <RadioButton
                    android:layout_width="?attr/actionBarSize"
                    android:layout_height="?attr/actionBarSize" />

                <RadioButton
                    android:layout_width="?attr/actionBarSize"
                    android:layout_height="?attr/actionBarSize" />
            </RadioGroup>
        </LinearLayout>

        <CheckedTextView
            android:id="@+id/checked_text_view"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:filterTouchesWhenObscured="true"
            android:focusableInTouchMode="true"
            android:gravity="center_vertical"
            android:text="CheckedTextView" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ProgressBar
                android:layout_width="?attr/actionBarSize"
                android:layout_height="?attr/actionBarSize" />
        </LinearLayout>

        <ProgressBar
            android:id="@+id/progress_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:progress="15" />

        <SeekBar
            android:id="@+id/seekbar_self"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:max="100"
            android:progress="20" />

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            android:rating="3"
            android:stepSize="0.5" />
    </LinearLayout>

</ScrollView>


text:
require File.expand_path '../../../lib/sok', File.dirname(__FILE__)
include Kabu

dir = File.expand_path '../../../data/strategy1-4/', File.dirname(__FILE__)
exam = Examination.new
exam.mfe(CbPbHigh.new, dir)


text:
<?php

namespace Doctrine\Common\Cache;

/**
 * Interface for cache drivers.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision: 3938 $
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
interface Cache
{
    /**
     * Fetches an entry from the cache.
     *
     * @param string $id cache id The id of the cache entry to fetch.
     * @return string The cached data or FALSE, if no cache entry exists for the given id.
     */
    function fetch($id);

    /**
     * Test if an entry exists in the cache.
     *
     * @param string $id cache id The cache id of the entry to check for.
     * @return boolean TRUE if a cache entry exists for the given cache id, FALSE otherwise.
     */
    function contains($id);

    /**
     * Puts data into the cache.
     *
     * @param string $id The cache id.
     * @param string $data The cache entry/data.
     * @param int $lifeTime The lifetime. If != 0, sets a specific lifetime for this cache entry (0 => infinite lifeTime).
     * @return boolean TRUE if the entry was successfully stored in the cache, FALSE otherwise.
     */
    function save($id, $data, $lifeTime = 0);

    /**
     * Deletes a cache entry.
     *
     * @param string $id cache id
     * @return boolean TRUE if the cache entry was successfully deleted, FALSE otherwise.
     */
    function delete($id);
}


text:
import React from 'react';
export interface RadioButtonProps {
    value: string | number;
    style?: React.CSSProperties;
}
export default class RadioButton extends React.Component<RadioButtonProps, any> {
    static defaultProps: {
        prefixCls: string;
    };
    render(): JSX.Element;
}


text:
// SPDX-License-Identifier: Unlicense OR MIT

// Package cocoainit initializes support for multithreaded
// programs in Cocoa.
package cocoainit

/*
#cgo CFLAGS: -xobjective-c -fmodules -fobjc-arc
#import <Foundation/Foundation.h>

static inline void activate_cocoa_multithreading() {
    [[NSThread new] start];
}
#pragma GCC visibility push(hidden)
*/
import "C"

func init() {
	C.activate_cocoa_multithreading()
}


text:
namespace zdb
{
	class DataField;

	class DataRow
	{
	public:
		DataRow();
		virtual ~DataRow();

		void Clear();
		inline void AddField(DataField *field);
		inline size_t GetFieldCount() const;
		inline const DataField* GetField(int index) const;
		const DataField* GetField(const char *name) const;
		std::string ToString() const;

	protected:
		DataRow(const DataRow &other) {}
		DataRow& operator = (const DataRow &other) { return *this; }

	private:
		typedef std::vector<DataField*> FieldVector;
		FieldVector m_fields;
	}; // class DataRow

	void DataRow::AddField(DataField *field)
	{
		m_fields.push_back(field);
	}

	size_t DataRow::GetFieldCount() const
	{
		return m_fields.size();
	}

	const DataField* DataRow::GetField(int index) const
	{
		return (index < 0 || index >= m_fields.size() ? NULL : m_fields[index]);
	}
} // namespace zdb
#endif


text:
from nova import flags
from nova import log as logging
from nova import utils
from nova.network import linux_net
from nova.openstack.common import cfg
from ryu.app.client import OFPClient

LOG = logging.getLogger(__name__)

ryu_linux_net_opt = cfg.StrOpt('linuxnet_ovs_ryu_api_host',
                               default='127.0.0.1:8080',
                               help='Openflow Ryu REST API host:port')

FLAGS = flags.FLAGS
FLAGS.register_opt(ryu_linux_net_opt)

def _get_datapath_id(bridge_name):
    out, _err = utils.execute('ovs-vsctl', 'get', 'Bridge',
                              bridge_name, 'datapath_id', run_as_root=True)
    return out.strip().strip('"')

def _get_port_no(dev):
    out, _err = utils.execute('ovs-vsctl', 'get', 'Interface', dev,
                              'ofport', run_as_root=True)
    return int(out.strip())

class LinuxOVSRyuInterfaceDriver(linux_net.LinuxOVSInterfaceDriver):
    def __init__(self):
        super(LinuxOVSRyuInterfaceDriver, self).__init__()

        LOG.debug('ryu rest host %s', FLAGS.linuxnet_ovs_ryu_api_host)
        self.ryu_client = OFPClient(FLAGS.linuxnet_ovs_ryu_api_host)
        self.datapath_id = _get_datapath_id(
            FLAGS.linuxnet_ovs_integration_bridge)

        if linux_net.binary_name == 'nova-network':
            for tables in [linux_net.iptables_manager.ipv4,
                           linux_net.iptables_manager.ipv6]:
                tables['filter'].add_rule('FORWARD',
                        '--in-interface gw-+ --out-interface gw-+ -j DROP')
            linux_net.iptables_manager.apply()

    def plug(self, network, mac_address, gateway=True):
        LOG.debug("network %s mac_adress %s gateway %s",
                  network, mac_address, gateway)
        ret = super(LinuxOVSRyuInterfaceDriver, self).plug(
            network, mac_address, gateway)

        port_no = _get_port_no(self.get_dev(network))
        self.ryu_client.create_port(network['uuid'], self.datapath_id, port_no)
        return ret


text:
import sys
import re
from optparse import OptionParser

from skype_api import *

appname = 'chat_finder'

class SkypeChat:
	def __init__(self, _chunk_size = 5, debug = False):
		self.ids = None
		self.chunk = 0
		self.chunk_size = _chunk_size
		self.topics = {}
		self.members = {}
		self.friendlyname = {}
		self.api = SkypeAPI(appname, debug)

	def init_chat_ids(self):
		ret = self.api.send_and_block('SEARCH CHATS')
		r = re.search (r'CHATS (.*)', ret)
		if r:
			self.ids = r.group(1).strip().split(', ')
		# convert percentage to actual value
		self.chunk_size = len(self.ids) * self.chunk_size / 100

	# Gets chat info by chunks
	def get_all_chats(self):
		if not self.ids:
			self.init_chat_ids()

		lo = self.chunk
		self.hi = min([self.chunk + self.chunk_size - 1, len(self.ids) - 1])

		for i in self.ids[lo:self.hi]:
			self.api.send('GET CHAT ' + i + ' TOPIC')
			self.api.send('GET CHAT ' + i + ' MEMBERS')
			self.api.send('GET CHAT ' + i + ' FRIENDLYNAME')

		while True:
			msgs = self.api.response_wait(1)
			if not msgs: break
			for reply in msgs:
				r = re.search (r'CHAT (\S+) TOPIC (.+)', reply)
				if r: self.topics[r.group(1).strip()] = r.group(2).strip()
				r = re.search (r'CHAT (\S+) MEMBERS (.+)', reply)
				if r: self.members[r.group(1).strip()] = r.group(2).strip()
				r = re.search (r'CHAT (\S+) FRIENDLYNAME (.+)', reply)
				if r: self.friendlyname[r.group(1).strip()] = r.group(2).strip()

		self.chunk = min([self.chunk + self.chunk_size, len(self.ids) - 1])

	def open_chat(self, name):
		self.api.send('OPEN CHAT ' + name)

	def open_chat_by_index(self, index):
		self.open_chat(self.ids[index])

	def print_chat_list(self, filter):
		for i in self.ids[:self.hi]:
			# display only multi-chats
			if not self.members.has_key(i) or len(self.members[i].split()) < 3:
				continue
			# string we filter on
			search_str = ''
			if self.topics.has_key(i):
				search_str = search_str + self.topics[i]
			elif self.friendlyname.has_key(i):
				search_str = search_str + self.friendlyname[i]
			if self.members.has_key(i):
				search_str = search_str + self.members[i]
			search_str = search_str.lower()

			if not filter or search_str.find(filter) >= 0:
				t = ''
				if self.topics.has_key(i):           t = '**' + self.topics[i] + '**'
				elif self.friendlyname.has_key(i):   t = '"' + self.friendlyname[i] + '"'
				if self.members.has_key(i):          t = t + ' ' + self.members[i]
				if t:
					print str(self.ids.index(i)) + ': ' + t

	def perc_loaded(self):
		return str( int(float(self.chunk) / len(self.ids) * 100) )

if __name__ == "__main__":
	parser = OptionParser('%prog [options]')

	parser.add_option('-c', '--chunk', dest='chunk',
		default = 5, help='Percentage of total number of chats to load each time (100 for all)')
	parser.add_option('-d', '--debug', action='store_true', dest='debug',
		default = False, help='Print debug messages')

	options, args = parser.parse_args()
	if len(args):
		parser.print_help()
		sys.exit(0)

	try:
		api = SkypeChat(int(options.chunk), options.debug)
	except StandardError:
		print 'Could not connect to Skype. Check if "' + appname + '" is authorized to connect to Skype (Options - Public API)'
		sys.exit(0)

	print 'Please patient while chats are being loaded...'
	api.get_all_chats()

	filter = None
	refresh = True
	while True:
		if refresh:
			print ''
			api.print_chat_list(filter)
		refresh = False

		print 'Loaded: ' + api.perc_loaded() + ' %'
		print 'Quick help: "/word" filter by word; "/" clean filter; "m" load more chats; number to open a chat; "q" to quit'
		print '> ',
		sys.stdout.flush()
		result = sys.stdin.readline().strip().lower()

		if not result: continue

		elif result == '/':
			filter = None
			refresh = True
		elif result[0] == '/':
			filter = result[1:]
			refresh = True
		elif result.isdigit():
			api.open_chat_by_index(int(result))
		elif result[0] == '#':
			api.open_chat(result)
		elif result == 'm':
			print 'Loading more chats...'
			api.get_all_chats()
			refresh = True
		elif result == 'h':
			print 'Skype Chat Finder: Finds old multi-chats and allows to open them'
			print 'Commands:'
			print '    /word         Filters chat topic and member list with "word"'
			print '    /             Show all chats (reset filter)'
			print '    m             Loads more chats'
			print '    Chat number   Opens the chat window in Skype'
			print '    q             Quits'
		elif result == 'q':
			break


text:
package com.twelvemonkeys.imageio.plugins.pict;

import com.twelvemonkeys.imageio.plugins.pict.QuickTime.ImageDesc;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * QTBMPDecompressorTest.
 *
 * @author Harald Kuhr
 * @author last modified by $Author: haraldk$
 * @version $Id: QTBMPDecompressorTest.java,v 1.0 24/03/2021 haraldk Exp$
 */
public class QTGenericDecompressorTest {
    private ImageDesc createDescription(final String identifer, final String name, final int depth) {
        ImageDesc description = new ImageDesc();
        description.compressorVendor = QuickTime.VENDOR_APPLE;
        description.compressorIdentifer = identifer;
        description.compressorName = name;
        description.depth = (short) depth;

        return description;
    }

    @Test
    public void canDecompressJPEG() {
        QTDecompressor decompressor = new QTGenericDecompressor();

        assertTrue(decompressor.canDecompress(createDescription("jpeg", "Photo - JPEG", 8)));
        assertTrue(decompressor.canDecompress(createDescription("jpeg", "Photo - JPEG", 24)));
    }

    @Test
    public void canDecompressPNG() {
        QTDecompressor decompressor = new QTGenericDecompressor();

        assertTrue(decompressor.canDecompress(createDescription("png ", "PNG", 8)));
        assertTrue(decompressor.canDecompress(createDescription("png ", "PNG", 24)));
        assertTrue(decompressor.canDecompress(createDescription("png ", "PNG", 32)));
    }

    @Test
    public void canDecompressTIFF() {
        QTDecompressor decompressor = new QTGenericDecompressor();

        assertTrue(decompressor.canDecompress(createDescription("tiff", "TIFF", 8)));
        assertTrue(decompressor.canDecompress(createDescription("tiff", "TIFF", 24)));
        assertTrue(decompressor.canDecompress(createDescription("tiff", "TIFF", 32)));
    }
}


text:
namespace SE3D
{
	class ParamVector4D : public ShaderParameter
	{
	private:
		Vector4D m_Value;
	public:
		ParamVector4D(Vector4D value, uint32 nameID, int32 location)
			: ShaderParameter(nameID, VECTOR4D, location), m_Value(value)
		{
		}

		void Bind() override
		{
			glUniform4f(m_Location, m_Value.x, m_Value.y, m_Value.z, m_Value.w);
		}

		inline void SetValue(Vector4D value) { m_Value = value; }
		inline Vector4D GetValue() const { return m_Value; }
	};
}


text:
<resources>

	<!-- Base application theme. -->
	<style name="AppTheme" parent="Theme.AppCompat.Light">
		<!-- Customize your theme here. -->
		<item name="colorPrimary">@color/colorPrimary</item>
		<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
		<item name="colorAccent">@color/colorAccent</item>
		<item name="android:textColor">#FF808080</item>
	</style>

	<style name="AppTheme.NoActionBar" parent="AppTheme">
		<item name="windowActionBar">false</item>
		<item name="windowNoTitle">true</item>
		<item name="android:textColor">#FF808080</item>
	</style>

	<style name="TextInputError" parent="TextAppearance.AppCompat.Small">
		<item name="android:textStyle">bold</item>
		<item name="android:textColor">#ff0000</item>
	</style>

	<style name="BlueButton" parent="Widget.AppCompat.Button.Colored">
		<item name="android:textColor">@color/white</item>
		<item name="colorButtonNormal">@color/blue_500</item>
	</style>

	<style name="RedButton" parent="Widget.AppCompat.Button.Colored">
		<item name="android:textColor">@color/white</item>
		<item name="colorButtonNormal">@color/red_500</item>
	</style>

	<style name="GreyButton" parent="@style/Base.Widget.AppCompat.Button.Borderless">
		<item name="android:textColor">@color/gray</item>
		<item name="colorButtonNormal">@color/grey_300</item>
	</style>

	<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>

	<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>

	<style name="loading_dialog" parent="Base.Animation.AppCompat.Dialog">
		<item name="android:windowFrame">@null</item>       <!-- Dialog的windowFrame框为无 -->
		<item name="android:windowBackground">@drawable/bg_black_transparent
		</item> <!-- 设置dialog的背景 -->
		<item name="android:windowNoTitle">true</item>      <!-- 是否显示title -->
		<item name="android:windowIsTranslucent">false</item>    <!-- 是否半透明 -->
		<item name="android:windowIsFloating">true</item>       <!-- 是否浮现在activity之上 -->
		<item name="android:windowContentOverlay">@android:color/transparent
		</item>  <!-- 也是个drawable,定义contentoverlay的背景 -->
		<item name="android:backgroundDimEnabled">false</item>  <!-- 背景是否模糊显示 -->
	</style>

	<style name="ToolbarColoredBackArrow" parent="AppTheme">
		<item name="android:textColorSecondary">@color/colorImAccent</item>
	</style>

</resources>


text:
using System.Collections;
using UnityEngine;

namespace MultiPacMan.Player.Input {
    public abstract class InputInterpreter : MonoBehaviour {
        public abstract bool IsTurboOn ();
        public abstract Vector2 GetMovementDirection ();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Open SCAP Library: oval_varModel.c File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Open SCAP Library

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

src

OVAL

Data Structures |
Macros |
Typedefs |
Functions

oval_varModel.c File Reference

Open Vulnerability and Assessment Language.
More...

#include <string.h>

#include <time.h>

#include "oval_definitions_impl.h"

#include "oval_agent_api_impl.h"

#include "oval_parser_impl.h"

#include "adt/oval_string_map_impl.h"

#include "oval_system_characteristics_impl.h"

#include "common/util.h"

#include "common/debug_priv.h"

#include "common/_error.h"

#include "common/elements.h"

#include "oscap_source.h"

#include "source/oscap_source_priv.h"

Data Structures

struct  	_oval_variable_model_frame

struct  	oval_variable_model

 	The OVAL variable model facilitates access to external variable value bindings used to to constrain the evaluation of OVAL objects.  More...

Macros

#define 	NAMESPACE_VARIABLES   "http://oval.mitre.org/XMLSchema/oval-variables-5"

Typedefs

typedef struct

_oval_variable_model_frame 	_oval_variable_model_frame_t

typedef struct oval_variable_model 	oval_variable_model_t

Functions

bool 	oval_variable_model_iterator_has_more (struct oval_variable_model_iterator *itr)

struct oval_variable_model * 	oval_variable_model_iterator_next (struct oval_variable_model_iterator *itr)

void 	oval_variable_model_iterator_free (struct oval_variable_model_iterator *itr)

struct oval_variable_model * 	oval_variable_model_new ()

struct oval_variable_model * 	oval_variable_model_clone (struct oval_variable_model *old_model)

void 	oval_variable_model_free (struct oval_variable_model *model)

struct oval_generator * 	oval_variable_model_get_generator (struct oval_variable_model *model)

void 	oval_variable_model_set_generator (struct oval_variable_model *model, struct oval_generator *generator)

void 	oval_variable_model_add (struct oval_variable_model *model, char *varid, const char *comm, oval_datatype_t datatype, char *value)

struct oval_variable_model * 	oval_variable_model_import_source (struct oscap_source *source)

struct oval_variable_model * 	oval_variable_model_import (const char *file)

int 	oval_variable_model_export (struct oval_variable_model *model, const char *file)

bool 	oval_variable_model_has_variable (struct oval_variable_model *model, const char *id)

struct oval_string_iterator * 	oval_variable_model_get_variable_ids (struct oval_variable_model *model)

oval_datatype_t 	oval_variable_model_get_datatype (struct oval_variable_model *model, char *varid)

const char * 	oval_variable_model_get_comment (struct oval_variable_model *model, char *varid)

struct oval_value_iterator * 	oval_variable_model_get_values (struct oval_variable_model *model, char *varid)

struct oval_collection * 	oval_variable_model_get_values_ref (struct oval_variable_model *model, char *varid)

Detailed Description

Open Vulnerability and Assessment Language.

See more details at http://oval.mitre.org/

<address class="footer">
Generated by

 1.8.6
</address>


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const identity_1 = require("@azure/identity");
const cosmos_1 = require("@azure/cosmos");
const retry_1 = require("./retry");
function getEnv(name) {
    const result = process.env[name];
    if (typeof result === 'undefined') {
        throw new Error('Missing env: ' + name);
    }
    return result;
}
function createDefaultConfig(quality) {
    return {
        id: quality,
        frozen: false
    };
}
async function getConfig(client, quality) {
    const query = `SELECT TOP 1 * FROM c WHERE c.id = "${quality}"`;
    const res = await client.database('builds').container('config').items.query(query).fetchAll();
    if (res.resources.length === 0) {
        return createDefaultConfig(quality);
    }
    return res.resources[0];
}
async function main() {
    const commit = process.env['VSCODE_DISTRO_COMMIT'] || getEnv('BUILD_SOURCEVERSION');
    const quality = getEnv('VSCODE_QUALITY');
    const aadCredentials = new identity_1.ClientSecretCredential(process.env['AZURE_TENANT_ID'], process.env['AZURE_CLIENT_ID'], process.env['AZURE_CLIENT_SECRET']);
    const client = new cosmos_1.CosmosClient({ endpoint: process.env['AZURE_DOCUMENTDB_ENDPOINT'], aadCredentials });
    const config = await getConfig(client, quality);
    console.log('Quality config:', config);
    if (config.frozen) {
        console.log(`Skipping release because quality ${quality} is frozen.`);
        return;
    }
    console.log(`Releasing build ${commit}...`);
    const scripts = client.database('builds').container(quality).scripts;
    await (0, retry_1.retry)(() => scripts.storedProcedure('releaseBuild').execute('', [commit]));
}
main().then(() => {
    console.log('Build successfully released');
    process.exit(0);
}, err => {
    console.error(err);
    process.exit(1);
});


text:
package com.danisola.restify.servlet;

import com.danisola.restify.url.RestUrl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public interface Head {

    void head(HttpServletRequest req, HttpServletResponse res, RestUrl url) throws ServletException, IOException;
}