text:
@interface FindController ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,ClickImageViewDelegate>

@property (nonatomic, strong) Group *group;
@property (nonatomic, strong) NSIndexPath *indexPath;
@end
static NSString *indent = @"cell1";
@implementation FindController

- (void)viewDidLoad {
    [super viewDidLoad];
   [self.tableView registerNib:[UINib nibWithNibName:@"FindCell" bundle:nil] forCellReuseIdentifier:indent];
    [FindManager sharedFindManager].callBack = ^(){
        [self.tableView reloadData];
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [FindManager sharedFindManager].dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    FindCell *cell = [tableView dequeueReusableCellWithIdentifier:indent forIndexPath:indexPath];
    if (indexPath.row == 3) {
        return cell;
    }else{
    Group *group = [[FindManager sharedFindManager].dataArray objectAtIndex:indexPath.row];
    cell.group = group;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        return 0;
    }else{
        return 200;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableArray *array1 =[NSMutableArray array];
    [manager GET:@"http://api.kuaikanmanhua.com/v1/banners" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
        NSDictionary *dic1 = dic[@"data"];
        NSMutableArray *array = dic1[@"banner_group"];
        for (NSDictionary *dic2 in array) {
            [array1 addObject:dic2[@"pic"]];
        }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error :%@",error);
    }];

    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,self.view.frame.size.width , 200) imageURLStringsGroup:nil]; // 模拟网络延时情景
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView2.delegate = self;
    cycleScrollView2.dotColor = [UIColor yellowColor]; // 自定义分页控件小圆标颜色
    cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
    [self.view addSubview:cycleScrollView2];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScrollView2.imageURLStringsGroup = array1;
    });
    return cycleScrollView2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    self.indexPath = indexPath;
}

-(void)clickImageViewOfCollectionView:(UICollectionView *)collectionView index:(NSIndexPath *)index{

    FindDatailController *findDatailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"finddatail"];

    self.group = [[FindManager sharedFindManager].dataArray objectAtIndex:self.indexPath.row];

    if (self.indexPath.row == 3) {
        Comic *comic = self.group.comicArray[index.row];
    }else{
        Topic *topic = self.group.topicsArray[index.row];
        findDatailVC.datailID = topic.theID;
    }
//    NSLog(@" =============== %ld",self.group.topicsArray.count);

    [self.navigationController pushViewController:findDatailVC animated:YES];
}
@end


text:
require File.expand_path("spec_helper", File.dirname(__FILE__))

def read_all(fh, chunksize, outbuf = nil)
  str = String.new
  outbuf = String.new
  while fh.read(chunksize, outbuf)
    str << outbuf
  end
  str
end

describe Cae::MultipartParser::Part::Body do
  let(:fh_data) { '12345' }
  let(:initial_buffer) { nil }
  let(:size_limit) { 5 }
  let(:expected) { ((initial_buffer || '') + fh_data)[0, size_limit] }
  let(:fh) { StringIO.new fh_data }
  let(:body) do
    Cae::MultipartParser::Part::Body.new(fh, size_limit, initial_buffer)
  end

  (1..15).each do |chunksize|
    it "should work with read chunk size #{chunksize}" do
      read_all(body, chunksize).must_equal expected
    end
  end

  describe "with an initial buffer" do
    let(:initial_buffer) { 'abcde' }
    let(:size_limit) { 10 }

    (1..15).each do |chunksize|
      it "should work with read chunk size #{chunksize}" do
        read_all(body, chunksize).must_equal expected
      end
    end

    it "should not reallocate if passed an outbuf" do
      outbuf = String.new
      refute_changes(->{outbuf.object_id}) do
        while body.read(1, outbuf)
          # no-op
        end
      end
    end

    it "should return nil when empty" do
      read_all(body, size_limit) # empty the "file"
      body.read(1).must_equal nil
    end

    describe "with a shorter size_limit than data available" do
      let(:size_limit) { 5 }
      it "should stop returning data when size_limit is hit" do
        read_all(body, 1).must_equal expected
      end

      it "should return nil when 'empty'" do
        read_all(body, size_limit) # empty the "file"
        body.read(1).must_equal nil
      end
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class renderer.Light</title>
<meta name="date" content="2015-10-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
renderer.Light

Packages that use Light

Package
Description

renderer.geometry

Uses of Light in renderer.geometry

Method parameters in renderer.geometry with type arguments of type Light

Modifier and Type
Method and Description

void
Polygon.draw(int[] viewport,
    float[][] zBuffer,
    int width,
    int height,
    java.awt.Color col,
    java.util.List<Vertex> vertices,
    java.util.List<Light> lights,
    R_Player.Team side,
    R_Player.Team visible,
    int[][] shadowMap,
    int tileSize)

Renders a triangle to a buffer

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

require_once 'ZendL/Tool/Rpc/Loader/IncludePathLoader/RecursiveFilterIterator.php';

class ZendL_Tool_Rpc_Loader_IncludePathLoader extends ZendL_Tool_Rpc_Loader_Abstract
{

    protected $_filterDenyDirectoryPattern = '.*(/|\\\\).svn';
    protected $_filterAcceptFilePattern = '.*(?:Tool|Manifest|Provider)\.php';

    protected function _getFiles()
    {
        $paths = explode(PATH_SEPARATOR, get_include_path());

        $files = array();

        ZendL_Tool_Rpc_Loader_IncludePathLoader_RecursiveFilterIterator::setDenyDirectoryPattern($this->_filterDenyDirectoryPattern);
        ZendL_Tool_Rpc_Loader_IncludePathLoader_RecursiveFilterIterator::setAcceptFilePattern($this->_filterAcceptFilePattern);

        foreach ($paths as $path) {

            if (!file_exists($path) || $path[0] == '.') {
                continue;
            }

            $filter = new ZendL_Tool_Rpc_Loader_IncludePathLoader_RecursiveFilterIterator(new RecursiveDirectoryIterator($path));

            $iterator = new RecursiveIteratorIterator($filter);

            foreach ($iterator as $item) {
                if (!$item->isLink()) {
                    $files[] = $item->getRealPath();
                }
            }
        }

        return $files;
    }

}


text:
int main(int argc, char** argv)
{
    MPI_Init(&argc,&argv);
    int rank = dan_mpi_rank();
    int size = dan_mpi_size();
    int peer = (rank+1)%size;
    int message = 42;
    dan_pmsg m;
    dan_pmsg_init(&m);
    dan_pmsg_start(&m,dan_pmsg_global);
    DAN_PMSG_PACK(&m,peer,message,int);
    dan_pmsg_send(&m);
    while (dan_pmsg_receive(&m))
    {
        assert(dan_pmsg_received_size(&m) == sizeof(message));
        int* unpacked = dan_pmsg_unpack(&m,sizeof(int));
        fprintf(stderr,"%d received %d from %d\n",
                rank,*unpacked,dan_pmsg_received_from(&m));
        assert(dan_pmsg_received_size(&m) == sizeof(message));
    }
    message = 128;
    fprintf(stderr,"%d stage 2\n",rank);
    dan_pmsg_start(&m,dan_pmsg_global);
    DAN_PMSG_PACK(&m,peer,message,int);
    dan_pmsg_send(&m);
    while (dan_pmsg_receive(&m))
    {
        assert(dan_pmsg_received_size(&m) == sizeof(message));
        int* unpacked = dan_pmsg_unpack(&m,sizeof(int));
        fprintf(stderr,"%d received %d from %d\n",
                rank,*unpacked,dan_pmsg_received_from(&m));
        assert(dan_pmsg_received_size(&m) == sizeof(message));
    }
    int peer2 = (rank+size-1)%size;
    fprintf(stderr,"%d stage 3\n",rank);
    message = 3;
    dan_pmsg_start(&m,dan_pmsg_local);
    DAN_PMSG_PACK(&m,peer,message,int);
    DAN_PMSG_PACK(&m,peer2,message,int);
    dan_pmsg_send(&m);
    while (dan_pmsg_receive(&m))
    {
        assert(dan_pmsg_received_size(&m) == sizeof(message));
        int* unpacked = dan_pmsg_unpack(&m,sizeof(int));
        fprintf(stderr,"%d received %d from %d\n",
                rank,*unpacked,dan_pmsg_received_from(&m));
        assert(dan_pmsg_received_size(&m) == sizeof(message));
    }
    dan_pmsg_free(&m);
    MPI_Finalize();
    return 0;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revista Catalana de Micologia 24: 283 (2002)

#### Original name
Clitocybula taniae Vila

### Remarks
null


text:
from .fill_sinks import SinkFiller
from .sink_fill_barnes import SinkFillerBarnes

__all__ = ["SinkFiller", "SinkFillerBarnes"]


text:
package com.diffplug.gradle.spotless;

public final class FormattingOperationSupplier {
	private final FormattingOperation formatter;
	private boolean initialized = false;

	public FormattingOperationSupplier(final FormattingOperation formatter) {
		this.formatter = formatter;
	}

	FormattingOperation get() throws Exception {
		if (!initialized) {
			initialize();
		}
		return formatter;
	}

	private void initialize() throws Exception {
		initialized = true;
		formatter.init();
	}
}


text:
define("lodash/math/add", ["exports"], function (exports) {
  /**
   * Adds two numbers.
   *
   * @static
   * @memberOf _
   * @category Math
   * @param {number} augend The first number to add.
   * @param {number} addend The second number to add.
   * @returns {number} Returns the sum.
   * @example
   *
   * _.add(6, 4);
   * // => 10
   */
  "use strict";

  function add(augend, addend) {
    return (+augend || 0) + (+addend || 0);
  }

  exports["default"] = add;
});


text:
import { rollup } from 'rollup';
import json from 'rollup-plugin-json';
import nodeResolve from 'rollup-plugin-node-resolve';

var pkg = require('../package.json');
var copyright = '';

export default {
  entry: 'src/EsriLeafletWebMap.js',
  moduleName: 'L.esri',
  format: 'umd',
  external: ['leaflet', 'esri-leaflet', 'leaflet-omnivore'],
  plugins: [
    nodeResolve({
      jsnext: true,
      main: false,
      browser: false,
      extensions: [ '.js', '.json' ]
    }),
    json()
  ],
  globals: {
    'leaflet': 'L',
    'esri-leaflet': 'L.esri',
    'leaflet-omnivore': 'omnivore'
  },
  banner: copyright
}


text:
layout: post
title: '2020 All-Stars (s4e10) - This Kershaw guy might be good...'
season: 4
episode: 10
date: '2016-05-30T12:00:00+00:00'
tags:
  - Fantasy Baseball
  - MLB
  - deep league
  - 2020 All-Stars
  - Stephen Strasburg
  - Clayton Kershaw
  - Giolito
  - Jameson Tailon
  - Glasnow
  - Gausman
  - Archey Bradley
  - Nate Eovaldi
  - Matt Bush
  - Aroldis Chapman
  - Yasiel Puig
  - Corey Seager
  - Andre Ethier
  - Trayce Thompson
dogebets:
link: https://2020allstars.pmia.de/2020allstars-s4e10.mp3
length: 20903059
runtime: '43:32'
opus: https://2020allstars.pmia.de/2020allstars-s4e10.opus
---
Kershaw or Strasburg?  I try to make a case for Stephen, but it pretty much all hinges on wins.  It's not really a defensible position, but it's something to chat about.  But speaking of super prospects, JULIO!!!!!  JULIO!!!! JULIO!  Julio Urias made his debut and it was rough.  He got rocked, but this looks like it presents a buying opportunity.  The other super prospect we talk about is Giolito.  We're predicting a September Callup.

From the other side, I have completely given up on Yasiel Puig.  Listen to see how much faith I've lost.

As always, check us out on Twitter [{{ site.twitter.handle }}]({{site.twitter.url}}), Instagram [{{site.instagram.handle}}]({{site.instagram.url}}), and iTunes.

Season {{ page.season }} Episode {{ page.episode }} ({{ page.runtime }})


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>to_i (Rake::PseudoStatus)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

     # File lib/rake.rb, line 316
316:     def to_i
317:       @exitstatus << 8
318:     end


text:
package iscsi

import (
	"path/filepath"
	"strings"

	"github.com/prometheus/procfs/internal/fs"
)

// iscsi target started with /sys/kernel/config/target/iscsi/iqn*
// configfs + target/iscsi/iqn*
// iqnGlob is representing all the possible IQN
const iqnGlob = "target/iscsi/iqn*"

// targetCore static path /sys/kernel/config/target/core for node_exporter
// reading runtime status
const targetCore = "target/core"

// devicePath static path /sys/devices/rbd/[0-9]* for rbd devices to
// read at runtime status
const devicePath = "devices/rbd"

// FS represents the pseudo-filesystem configfs, which provides an interface to
// iscsi kernel data structures in
// sysfs	as /sys
// configfs as /sys/kernel/config
type FS struct {
	sysfs    *fs.FS
	configfs *fs.FS
}

// NewFS returns a new configfs mounted under the given mount point. It will
// error and return empty FS if the mount point can't be read. For the ease of
// use, an empty string parameter configfsMountPoint will call internal fs for
// the default sys path as /sys/kernel/config
func NewFS(sysfsPath string, configfsMountPoint string) (FS, error) {
	if strings.TrimSpace(sysfsPath) == "" {
		sysfsPath = fs.DefaultSysMountPoint
	}
	sysfs, err := fs.NewFS(sysfsPath)
	if err != nil {
		return FS{}, err
	}
	if strings.TrimSpace(configfsMountPoint) == "" {
		configfsMountPoint = fs.DefaultConfigfsMountPoint
	}
	configfs, err := fs.NewFS(configfsMountPoint)
	if err != nil {
		return FS{}, err
	}
	return FS{&sysfs, &configfs}, nil
}

// helper function to get configfs path
func (fs FS) Path(p ...string) string {
	return fs.configfs.Path(p...)
}

// ISCSIStats getting iscsi runtime information
func (fs FS) ISCSIStats() ([]*Stats, error) {
	matches, err := filepath.Glob(fs.configfs.Path(iqnGlob))
	if err != nil {
		return nil, err
	}

	stats := make([]*Stats, 0, len(matches))
	for _, iqnPath := range matches {
		// stats
		s, err := GetStats(iqnPath)
		if err != nil {
			return nil, err
		}
		stats = append(stats, s)
	}

	return stats, nil
}

// TPGT struct for sys target portal group tag info
type TPGT struct {
	Name     string // name of the tpgt group
	TpgtPath string // file path of tpgt
	IsEnable bool   // is the tpgt enable
	Luns     []LUN  // the Luns that tpgt has
}

// LUN struct for sys logical unit number info
type LUN struct {
	Name       string // name of the lun
	LunPath    string // file path of the lun
	Backstore  string // backstore of the lun
	ObjectName string // place holder for object
	TypeNumber string // place holder for number of the device
}

// FILEIO struct for backstore info
type FILEIO struct {
	Name       string // name of the fileio
	Fnumber    string // number related to the backstore
	ObjectName string // place holder for object in iscsi object
	Filename   string // link to the actual file being export
}

// IBLOCK struct for backstore info
type IBLOCK struct {
	Name       string // name of the iblock
	Bnumber    string // number related to the backstore
	ObjectName string // place holder for object in iscsi object
	Iblock     string // link to the actual block being export
}

// RBD struct for backstore info
type RBD struct {
	Name    string // name of the rbd
	Rnumber string // number related to the backstore
	Pool    string // place holder for the rbd pool
	Image   string // place holder for the rbd image
}

// RDMCP struct for backstore info
type RDMCP struct {
	Name       string // name of the rdm_cp
	ObjectName string // place holder for object name
}

// Stats struct for all targets info
type Stats struct {
	Name     string
	Tpgt     []TPGT
	RootPath string
}


text:
require 'rails_helper'

RSpec.describe CheckoutController, type: :controller do

end


text:
Queues in databases are a bad idea for many reasons. See for instance: http://mikehadlow.blogspot.nl/2012/04/database-as-queue-anti-pattern.html.

So don't do it.

Really.

I'm serious.

But...

You may encounter a situation where you
- have no influence on your customers infrastructure
- need to decouple long running processing from an interactive process
- need this decoupling be durable and persist across re-boots
- need a single (physical) queue where multiple producers and multiple consumers can share a topic
- **have a LOW volume of messages**

Then your solution may be the use of this implementation of a Brighter Messaging Gateway using SQL Server.

## Setup

You need SQL Server 2005 or newer (see below as to why).

To setup Brighter with a SQL Server based messaging gateway, some steps are required:

#### Create a table with the schema as shown by the QueueStore.sql example

You can use the following example as a reference for SQL Server:

```sql
        PRINT 'Creating Queue table'
        CREATE TABLE [dbo].[QueueData](
            [Id] [bigint] IDENTITY(1,1) NOT NULL,
            [Topic] [nvarchar](255) NOT NULL,
            [MessageType] [nvarchar](1024) NOT NULL,
            [Payload] [nvarchar](max) NOT NULL,
        CONSTRAINT [PK_QueueData] PRIMARY KEY CLUSTERED
        (
            [Id] ASC
        )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
        ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
        GO

        PRINT 'Creating an index on the Topic column of the Queue table...'
        CREATE NONCLUSTERED INDEX [IX_Topic] ON [dbo].[QueueData]
        (
            [Topic] ASC
        )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
        GO

        Print 'Done'
```

## Configuration

You specify the connection string to the database, and the name of the table that will hold the data.

#### Configure the command processor with a message producer

The following is an example of how to specify the configuration for the SQL Server messaging gateway to the command processor.

```csharp
        var messagingConfiguration = new MsSqlMessagingGatewayConfiguration(@"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
        var producer = new MsSqlMessageProducer(messagingConfiguration);

        var builder = CommandProcessorBuilder.With()
            .Handlers(new HandlerConfiguration())
            .DefaultPolicy()
            .TaskQueues(new MessagingConfiguration(outbox, producer, messageMapperRegistry))
            .RequestContextFactory(new InMemoryRequestContextFactory());

        var commandProcessor = builder.Build();
```

#### Configure the dispatcher with a message consumer factory

The following is an example of how to specify the configuration for the SQL Server messaging gateway to the message dispatcher.

```csharp
        ...

        //create the gateway
        var messagingConfiguration =
            new MsSqlMessagingGatewayConfiguration(
                @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
        var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

        var dispatcher = DispatchBuilder.With()
            .CommandProcessor(CommandProcessorBuilder.With()
                .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                .Policies(policyRegistry)
                .NoTaskQueues()
                .RequestContextFactory(new InMemoryRequestContextFactory())
                .Build())
            .MessageMappers(messageMapperRegistry)
            .DefaultChannelFactory(new MsSqlInputChannelFactory(messageConsumerFactory))
            .Connections(new Connection[]
            {
                new Connection<GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

        dispatcher.Receive();

        ...
```

## Queuing details

#### FIFO

The SQL Server based messaging gateway implements a First In First Out queue.

Therefore, when using a single message consumer, messages are guaranteed to be retrieved in the same order as they were sent. The consumer may force
a message to be requeued by throwing the _DeferMessageAction_ exception. Of course such a message is by intention no longer in the correct order.

#### Competing consumers

When using the competing consumer pattern, multiple message consumers are available to handle messages of the same topic. This may lead to
out of order handling of messages (caused by eg. thread availability, machine load, network load).

#### Guarantees

- when the commandprocessor Post or PostAsync completes without exceptions, your message is guaranteed to be on the queue.
- the message is guaranteed to be removed from the queue at the moment the dispatcher retrieves it (this is **before** your handler gets executed).
Your registered handler is responsible for handling exceptional cases where you may need to requeue the message to a poison or dead letter queue.

#### Locking

Al sorts of concurrency and locking related problems are (hopefully) prevented by USING the **OUTPUT** Clause introduced first in SQL Server
2005. See: http://rusanu.com/2010/03/26/using-tables-as-queues/. This also introduces a dependency on the version of SQL Server being 2005
or newer.

## Examples

See the samples\MsSqlMessagingGatewaySamples folders for examples on how to configure and use the SQL Server based messaging gateway.

#### Simple post and receive

- A console mode program to post a Greeting event (.NET Core)
- A console mode program to receive and process Greeting events (.NET Core)
- A Windows Service to receive and process Greeting events (.NET Framework)

#### Competing consumers

- A console mode program to receive and process Competing Consumer Commands (.NET Core), multiple instances may be started to process the available messages.
The example handler will randomly throw an exception for 10% of the messages. This exception will be handled and cause the message to be reueued for later handling.
- A console mode program to send many Competing Consumer Commands (.NET Core) taking one argument: the number of messages to send, multiple instance may be started to send simultaneously.
This example will start a transactionscope, but never complete the transaction. This is done to illustrate the fact that a Post or PostAsync causes the message to 'escape' your domain
and can not be undone by rolling back the current transaction.


text:
layout: post
title: Docker parts and how it works on Windows and OSX
---

Hi, today I want to tell you about parts of Docker (yes, Docker it is not standalone application). In this article I'm not going describe internals of docker, its filesystem, what is container, image and how to use it. Instead you'll learn what is docker daemon and docker client and how docker and docker-beta (at the moment of this article it still beta) works on Windows and OSX.

This article is pretty simple with minimum technical terms.

What is docker
===============

Docker is containerisation tools (tool**s** - not a standalone app) that use LXC (Linux containers). LXC is also set of tools that use some Linux kernel's features and that features are available only in Linux kernel.
It means that docker can be used natively ONLY on Linux, period.

I saw people use it on their Windows/OSX machines
================================================

Yeah, I'm sure you saw it.

Let me tell you about the parts that Docker consists of.

The first and probably main part of Docker is **Docker Daemon**.
This guy is heart of Docker term. He do every job that you know Docker can do
and this guy **is only available on Linux**.

But when you type **docker** in your terminal you actually do not use docker daemon directly,
you invoke **Docker Client** and ask him to pipe commands you typed to the
**Docker Daemon** and Docker Client **is cross-platform tool**.

So, strictly speaking, you saw how people use Docker Client on their Windows/OSX machines.
They have/had virtual machine installed with Linux inside
where Docker Daemon was running.
Probably they used **docker-machine** which is just interface to the virtual box
or other similar virtualisation tools.

It means also that your containers were not running on your host machine
but on virtual machine which is not cool actually and brings some
issues with networking and filesystem sharing.

Docker Daemon can be running on separated machine and Docker Client
can connect to it by socket.

So this is how docker works on Windows and OSX.

Docker Beta
==========

Couple of months ago Docker team did something cool and their realised
**Docker for Windows and OSX**.
For you, as for Docker user, it means that you can run docker containers
natively on your host and access them via localhost with no issues with filesystem sharing.

But, it is not really truth.

**Docker Beta** is still using virtual machines.
On Windows it uses Hyper-V and on OSX it uses xhyve.
Both are native for their platforms and were developed for one platform with platform-specific features.
When you run Docker.exe or Docker.app the virtual machine will be started and you can forget about it at all,
you no need to set socket address in your docker client or do something else.
You can just run the app and start to use Docker.
Internally it uses Linux with Docker Daemon installed but you will not see it at all.
That's awesome and for Docker users it looks like it works natively.
Every port of your application (that is exposed of course)
can be accessed on localhost, you can share any part of your filesystem
with no issues.

Probably Docker will never be available on Windows and OSX natively because Docker is using Linux kernel features and these feature are not available on other platforms. But it doesn't mean you can't use Docker on Windows or OSX for your development needs.

I didn't describe a lot of internals of docker in this article, maybe I will do it in next one, but I really hope it brought some light to the how Docker and Docker Beta works on your machine.

Have a good day and always know how your tools are working.


text:
set -x
################################################################
# STEP: Get Persistent Volume (PV) name as argument            #
#                                                              #
# NOTES: Obtain the pv to upgrade via "kubectl get pv"         #
################################################################

target_upgrade_version="0.8.1"
current_version="0.6.0"

function usage() {
    echo
    echo "Usage:"
    echo
    echo "$0 <pv-name>"
    echo
    echo "  <pv-name> Get the PV name using: kubectl get pv"
    exit 1
}

function setDeploymentRecreateStrategy() {
    dns=$1 # deployment namespace
    dn=$2  # deployment name
    currStrategy=`kubectl get deploy -n $dns $dn -o jsonpath="{.spec.strategy.type}"`
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to get the deployment stratergy for $dn | Exit code: $rc"; exit; fi

    if [ $currStrategy != "Recreate" ]; then
       kubectl patch deployment --namespace $dns --type json $dn -p "$(cat patch-strategy-recreate.json)"
       rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch the deployment $dn | Exit code: $rc"; exit; fi
       echo "Deployment upgrade strategy set as recreate"
    else
       echo "Deployment upgrade strategy was already set as recreate"
    fi
}

if [ "$#" -ne 1 ]; then
    usage
fi

pv=$1
replica_node_label="openebs-jiva"

# Check if pv exists
kubectl get pv $pv &>/dev/null;check_pv=$?
if [ $check_pv -ne 0 ]; then
    echo "$pv not found";exit 1;
fi

ns=`kubectl get pv $pv -o jsonpath="{.spec.claimRef.namespace}"`
sc_name=`kubectl get pv $pv -o jsonpath="{.spec.storageClassName}"`
sc_res_ver=`kubectl get sc $sc_name -n $ns -o jsonpath="{.metadata.resourceVersion}"`
pv_capacity=`kubectl get pv $pv -o jsonpath="{.spec.capacity.storage}"`
pvc_name=`kubectl get pv $pv -o jsonpath="{.spec.claimRef.name}"`

#################################################################
# STEP: Generate deploy, replicaset and container names from PV #
#                                                               #
# NOTES: Ex: If PV="pvc-cec8e86d-0bcc-11e8-be1c-000c298ff5fc"   #
#                                                               #
# ctrl-dep: pvc-cec8e86d-0bcc-11e8-be1c-000c298ff5fc-ctrl       #
#################################################################

c_dep=$(kubectl get deploy -n $ns -l vsm=$pv,openebs/controller=jiva-controller -o jsonpath="{.items[*].metadata.name}")
r_dep=$(kubectl get deploy -n $ns -l vsm=$pv,openebs/replica=jiva-replica -o jsonpath="{.items[*].metadata.name}")
c_svc=$(kubectl get svc -n $ns -l vsm=$pv -o jsonpath="{.items[*].metadata.name}")
c_name=$(kubectl get deploy -n $ns $c_dep -o jsonpath="{range .spec.template.spec.containers[*]}{@.name}{'\n'}{end}" | grep "ctrl-con")
r_name=$(kubectl get deploy -n $ns $r_dep -o jsonpath="{range .spec.template.spec.containers[*]}{@.name}{'\n'}{end}" | grep "rep-con")

# Fetch the older target and replica - ReplicaSet objects which need to be
# deleted before upgrading. If not deleted, the new pods will be stuck in
# creating state - due to affinity rules.

c_rs=$(kubectl get rs -o name --namespace $ns -l vsm=$pv,openebs/controller=jiva-controller | cut -d '/' -f 2)
r_rs=$(kubectl get rs -o name --namespace $ns -l vsm=$pv,openebs/replica=jiva-replica | cut -d '/' -f 2)

################################################################
# STEP: Update patch files with appropriate resource names     #
#                                                              #
# NOTES: Placeholder for resourcename in the patch files are   #
# replaced with respective values derived from the PV in the   #
# previous step                                                #
################################################################

# Check if openebs resources exist and provisioned version is 0.8

if [[ -z $c_rs ]]; then
    echo "Target Replica set not found"; exit 1;
fi

if [[ -z $r_rs ]]; then
    echo "Replica Replica set not found"; exit 1;
fi

if [[ -z $c_dep ]]; then
    echo "Target deployment not found"; exit 1;
fi

if [[ -z $r_dep ]]; then
    echo "Replica deployment not found"; exit 1;
fi

if [[ -z $c_svc ]]; then
    echo "Target service not found"; exit 1;
fi

if [[ -z $r_name ]]; then
    echo "Replica container not found"; exit 1;
fi

if [[ -z $c_name ]]; then
    echo "Target container not found"; exit 1;
fi

controller_version=`kubectl get deployment $c_dep -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$controller_version" != "" ]] && [[ "$controller_version" == "$target_upgrade_version" ]]; then
    echo "Current Target deployment $c_dep version is not $current_version or $target_upgrade_version";exit 1;
fi
replica_version=`kubectl get deployment $r_dep -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$replica_version" != "" ]] && [[ "$replica_version" == "$target_upgrade_version" ]]; then
    echo "Current Replica deployment $r_dep version is not $current_version or $target_upgrade_version";exit 1;
fi
controller_svc_version=`kubectl get svc $c_svc -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$controller_svc_version" != "" ]] && [[ "$controller_svc_version" == "$target_upgrade_version" ]] ; then
    echo "Current Target service $c_svc version is not $current_version or $target_upgrade_version";exit 1;
fi

# Get the number of replicas configured.
# This field is currently not used, but can add additional validations
# based on the nodes and expected number of replicas
rep_count=`kubectl get deploy $r_dep --namespace $ns -o jsonpath="{.spec.replicas}"`

# Get the list of nodes where replica pods are running, delimited by ':'
rep_nodenames=`kubectl get pods -n $ns \
 -l "vsm=$pv" -l "openebs/replica=jiva-replica" \
 -o jsonpath="{range .items[*]}{@.spec.nodeName}:{end}"`

echo "Checking if the node with replica pod has been labeled with $replica_node_label"
for rep_node in `echo $rep_nodenames | tr ":" " "`; do
    nl="";nl=`kubectl get nodes $rep_node -o jsonpath="{.metadata.labels.openebs-pv-$pv}"`
    echo "Labeling $rep_node";
    kubectl label node $rep_node "openebs-pv-${pv}=$replica_node_label" --overwrite
done

sed "s/@sc_name@/$sc_name/g" jiva-replica-patch.tpl.json | sed  "s/@sc_resource_version@/$sc_res_ver/g" | sed  "s/@capacity@/$pv_capacity/g" | sed  "s/@replica_node_label@/$replica_node_label/g" | sed  "s/@r_name@/$r_name/g" | sed  "s/@pv-name@/$pv/g" | sed  "s/@target_version@/$target_upgrade_version/g" | sed  "s/@pvc-name@/$pvc_name/g" > jiva-replica-patch.json
sed "s/@sc_name@/$sc_name/g" jiva-target-patch.tpl.json | sed  "s/@sc_resource_version@/$sc_res_ver/g" | sed  "s/@c_name@/$c_name/g" | sed  "s/@target_version@/$target_upgrade_version/g"  | sed  "s/@pvc-name@/$pvc_name/g" | sed  "s/@pv-name@/$pv/g" | sed  "s/@rep_count@/$rep_count/g" > jiva-target-patch.json
sed "s/@sc_name@/$sc_name/g" jiva-target-svc-patch.tpl.json | sed  "s/@sc_resource_version@/$sc_res_ver/g" | sed  "s/@target_version@/$target_upgrade_version/g" | sed  "s/@pvc-name@/$pvc_name/g" | sed  "s/@pv-name@/$pv/g" > jiva-target-svc-patch.json

#################################################################################
# STEP: Patch OpenEBS volume deployments (jiva-target, jiva-replica & jiva-svc) #
#################################################################################

#### PATCH JIVA REPLICA DEPLOYMENT ####
if [[ $replica_version=="" ]] || [[ "$replica_version" != "$target_upgrade_version" ]]; then
    echo "Upgrading Replica Deployment to $target_upgrade_version"

    # Setting the update stratergy to recreate
    setDeploymentRecreateStrategy $ns $r_dep

    echo "Patching Replica deployment to $target_upgrade_version"

    kubectl patch deployment --namespace $ns $r_dep -p "$(cat jiva-replica-patch.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch the deployment $r_dep | Exit code: $rc"; exit; fi

    kubectl delete rs $r_rs --namespace $ns
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to delete ReplicaSet $r_rs  | Exit code: $rc"; exit; fi

    rollout_status=$(kubectl rollout status --namespace $ns deployment/$r_dep)
    rc=$?; if [[ ($rc -ne 0) || !($rollout_status =~ "successfully rolled out") ]];
    then echo " RollOut for $r_dep failed | Exit code: $rc"; exit; fi
else
    echo "Replica Deployment $r_dep is already at $target_upgrade_version"
fi

#### PATCH TARGET DEPLOYMENT ####
if [[ $controller_version=="" ]] || [[ "$controller_version" != "$target_upgrade_version" ]]; then
    echo "Upgrading Target Deployment to $target_upgrade_version"

    # Setting the update stratergy to recreate
    setDeploymentRecreateStrategy $ns $c_dep

    echo "Patching target deployment to 0.8.1"
    kubectl patch deployment  --namespace $ns $c_dep -p "$(cat jiva-target-patch.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch deployment $c_dep | Exit code: $rc"; exit; fi

    kubectl delete rs $c_rs --namespace $ns
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch deployment $c_rs | Exit code: $rc"; exit; fi

    rollout_status=$(kubectl rollout status --namespace $ns  deployment/$c_dep)
    rc=$?; if [[ ($rc -ne 0) || !($rollout_status =~ "successfully rolled out") ]];
    then echo " Failed to patch the deployment | Exit code: $rc"; exit; fi
else
    echo "Controller Deployment $c_dep is already at $target_upgrade_version"

fi

#### PATCH TARGET SERVICE ####
if [[ $controller_svc_version=="" ]] || [[ "$controller_svc_version" != "$target_upgrade_version" ]]; then
    echo "Upgrading Target Service to $target_upgrade_version"
    # Patching target service to 0.8.1
    kubectl patch service --namespace $ns $c_svc -p "$(cat jiva-target-svc-patch.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch the service $svc | Exit code: $rc"; exit; fi
else
    echo "Controller service $c_svc is already at $target_upgrade_version"
fi

# Annotating pv
kubectl annotate pv $pv openebs.io/cas-type=jiva

controller_version=`kubectl get deployment $c_dep -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$controller_version" == "$target_upgrade_version" ]]; then
    echo "Remove deprecated lables from Controller Deployment"
    c_rs=$(kubectl get rs -o name --namespace $ns -l openebs.io/persistent-volume=$pv,openebs.io/controller=jiva-controller | cut -d '/' -f 2)

    kubectl patch deployment  --namespace $ns $c_dep --type json -p "$(cat target-patch-remove-labels.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "ERROR: $rc"; exit; fi

    kubectl delete rs $c_rs --namespace $ns
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to patch deployment $c_rs | Exit code: $rc"; exit; fi

    rollout_status=$(kubectl rollout status --namespace $ns  deployment/$c_dep)
    rc=$?; if [[ ($rc -ne 0) || !($rollout_status =~ "successfully rolled out") ]];
    then echo " Failed to patch the deployment | Exit code: $rc"; exit; fi
fi

replica_version=`kubectl get deployment $r_dep -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$replica_version" == "$target_upgrade_version" ]]; then
    echo "Remove deprecated lables from Replica Deployment"
    r_rs=$(kubectl get rs -o name --namespace $ns -l openebs.io/persistent-volume=$pv,openebs.io/replica=jiva-replica | cut -d '/' -f 2)

    kubectl patch deployment --namespace $ns $r_dep --type json -p "$(cat replica-patch-remove-labels.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "ERROR: $rc"; exit; fi

    kubectl delete rs $r_rs --namespace $ns
    rc=$?; if [ $rc -ne 0 ]; then echo "Failed to delete ReplicaSet $r_rs  | Exit code: $rc"; exit; fi

    rollout_status=$(kubectl rollout status --namespace $ns deployment/$r_dep)
    rc=$?; if [[ ($rc -ne 0) || !($rollout_status =~ "successfully rolled out") ]];
    then echo " RollOut for $r_dep failed | Exit code: $rc"; exit; fi
fi

controller_svc_version=`kubectl get svc $c_svc -n $ns -o jsonpath='{.metadata.labels.openebs\.io/version}'`
if [[ "$controller_svc_version" == "$target_upgrade_version" ]] ; then
    echo "Remove deprecated lables from Replica Deployment"
    kubectl patch service --namespace $ns $c_svc --type json -p "$(cat target-svc-patch-remove-labels.json)"
    rc=$?; if [ $rc -ne 0 ]; then echo "ERROR: $rc"; exit; fi
    kubectl label svc --namespace $ns $c_svc "vsm-"
    kubectl label svc --namespace $ns $c_svc "openebs/controller-service-"
fi

echo "Clearing temporary files"
rm jiva-replica-patch.json
rm jiva-target-patch.json
rm jiva-target-svc-patch.json

echo "Successfully upgraded $pv to $target_upgrade_version Please run your application checks."
exit 0


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or (at
 *    your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful, but
 *    WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

/*
 *    DoubleVector.java
 *    Copyright (C) 2002 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.core.matrix;

import weka.core.RevisionHandler;
import weka.core.RevisionUtils;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * A vector specialized on doubles.
 *
 * @author Yong Wang
 * @version $Revision: 1.4 $
 */
public class  DoubleVector
  implements Cloneable, RevisionHandler {

  double[] V; // array for internal storage of elements.

  private int  sizeOfVector;      // size of the vector

  /* ------------------------
     Constructors
     * ------------------------ */

  /** Constructs a null vector.
   */
  public DoubleVector() {
    this( 0 );
  }

  /** Constructs an n-vector of zeros.
      @param n    length.
  */
  public DoubleVector( int n ){
    V = new double[ n ];
    setSize( n );
  }

  /** Constructs a constant n-vector.
      @param n    length.
      @param s    the scalar value used to fill the vector
  */
  public DoubleVector( int n, double s ){
    this( n );
    set( s );
  }

  /** Constructs a vector directly from a double array
   *  @param v   the array
   */
  public DoubleVector( double v[] ){
    if( v == null ) {
      V = new double[0];
      setSize( 0 );
    }
    else {
      V = v;
      setSize( v.length );
    }
  }

  /* ------------------------
   *  Public Methods
   * ------------------------ */

  /** Set a single element.
   *  @param i    Index.
   *  @param s    a[i].
   */
  public void  set( int i, double s ) {

    V[i] = s;
  }

  /** Set all elements to a value
   *  @param s    the value
   */
  public void  set( double s ) {
    set(0, size()-1, s);
  }

  /** Set some elements to a value
   *  @param i0 the index of the first element
   *  @param i1 the index of the second element
   *  @param s the value
   */
  public void set( int i0, int i1, double s ) {

    for(int i = i0; i <= i1; i++ )
      V[i] = s;
  }

  /** Set some elements using a 2-D array
   *  @param i0 the index of the first element
   *  @param i1 the index of the second element
   *  @param j0 the index of the starting element in the 2-D array
   *  @param v the values
   */
  public void  set( int i0, int i1, double [] v, int j0){
    for(int i = i0; i<= i1; i++)
      V[i] = v[j0 + i - i0];
  }

  /** Set the elements using a DoubleVector
   *  @param v the DoubleVector
   */
  public void  set( DoubleVector v ){
    set( 0, v.size() - 1, v, 0);
  }

  /** Set some elements using a DoubleVector.
   *  @param i0 the index of the first element
   *  @param i1 the index of the second element
   *  @param v the DoubleVector
   *  @param j0 the index of the starting element in the DoubleVector
   */
  public void  set( int i0, int i1, DoubleVector v, int j0){
    for(int i = i0; i<= i1; i++)
      V[i] = v.V[j0 + i - i0];
  }

  /** Access the internal one-dimensional array.
      @return     Pointer to the one-dimensional array of vector elements.
  */
  public double []  getArray() {
    return V;
  }

  void  setArray( double [] a ) {
    V = a;
  }

  /** Returns a copy of the DoubleVector usng a double array.
      @return the one-dimensional array.  */
  public double[] getArrayCopy() {
    double v[] = new double[size()];

    for(int i= 0; i < size(); i++ )
      v[i] = V[i];

    return v;
  }

  /** Sorts the array in place */
  public void  sort() {
    Arrays.sort( V, 0, size() );
  }

  /** Sorts the array in place with index returned */
  public IntVector  sortWithIndex() {
    IntVector index = IntVector.seq( 0, size()-1 );
    sortWithIndex( 0, size()-1, index );
    return index;
  }

  /** Sorts the array in place with index changed
   *  @param xi   first index
   *  @param xj   last index
   *  @param index array that stores all indices
   */
  public void  sortWithIndex( int xi, int xj, IntVector index ) {
    if( xi < xj ) {
      double x, f, k;
      int xm = (int) (xi + xj) / 2; // median index
      x = Math.min( V[xi],             // median of three
		    Math.max( V[xm], V[xj]));
      int i = xi;
      int j = xj;
      while( i < j ) {
	while( V[i] < x && i < xj ) i++;
	while( V[j] > x && j > xi ) j--;
	if( i <= j ){
	  swap(i, j);
	  index.swap(i, j);
	  i++;
	  j--;
	}
      }
      sortWithIndex(xi, j, index);
      sortWithIndex(i, xj, index);
    }
  }

  /** Gets the size of the vector.
      @return     the size
  */
  public int  size(){
    return sizeOfVector;
  }

  /**
   *  Sets the size of the vector
   *  @param m the size
   */
  public void  setSize( int m ){
    if( m > capacity() )
      throw new IllegalArgumentException("insufficient capacity");
    sizeOfVector = m;
  }

  /** Gets the capacity of the vector.
   *  @return     the capacity.
   */
  public int  capacity() {
    if( V == null ) return 0;
    return V.length;
  }

  /** Sets the capacity of the vector
   *  @param n the capacity.
   */
  public void  setCapacity ( int n ) {
    if( n == capacity() ) return;
    double [] oldV = V;
    int m = Math.min( n, size() );
    V = new double[ n ];
    setSize( m );
    set(0, m-1, oldV, 0);
  }

  /** Gets a single element.
   *  @param i    Index.
   *  @return     the value of the i-th element
   */
  public double  get( int i ) {
    return V[i];
  }

  /**
   *  Adds a value to an element
   *  @param i  the index of the element
   *  @param s the value
   */
  public void  setPlus( int i, double s ) {
    V[i] += s;
  }

  /**
   *  Multiplies a value to an element
   *  @param i  the index of the element
   *  @param s the value
   */
  public void  setTimes( int i, double s ) {
    V[i] *= s;
  }

  /**
   *  Adds an element into the vector
   *  @param x  the value of the new element
   */
  public void addElement( double x ) {
    if( capacity() == 0 ) setCapacity( 10 );
    if( size() == capacity() ) setCapacity( 2 * capacity() );
    V[size()] = x;
    setSize( size() + 1 );
  }

  /**
   *  Returns the squared vector
   */
  public DoubleVector square() {
    DoubleVector v = new DoubleVector( size() );
    for(int i = 0; i < size(); i++ ) v.V[i] = V[i] * V[i];
    return v;
  }

  /**
   *  Returns the square-root of all the elements in the vector
   */
  public DoubleVector sqrt() {
    DoubleVector v = new DoubleVector( size() );
    for(int i = 0; i < size(); i++ ) v.V[i] = Math.sqrt(V[i]);
    return v;
  }

  /** Makes a deep copy of the vector
   */
  public DoubleVector  copy() {
    return (DoubleVector) clone();
  }

  /** Clones the DoubleVector object.
   */
  public Object  clone() {
    int n = size();
    DoubleVector u = new DoubleVector( n );
    for( int i = 0; i < n; i++)
      u.V[i] = V[i];
    return u;
  }

  /**
   * Returns the inner product of two DoubleVectors
   * @param v the second DoubleVector
   * @return the product
   */
  public double  innerProduct(DoubleVector v) {
    if(size() != v.size())
      throw new IllegalArgumentException("sizes unmatch");
    double p = 0;
    for (int i = 0; i < size(); i++) {
      p += V[i] * v.V[i];
    }
    return p;
  }

  /**
   * Returns the signs of all elements in terms of -1, 0 and +1.
   */
  public DoubleVector sign()
  {
    DoubleVector s = new DoubleVector( size() );
    for( int i = 0; i < size(); i++ ) {
      if( V[i] > 0 ) s.V[i] = 1;
      else if( V[i] < 0 ) s.V[i] = -1;
      else s.V[i] = 0;
    }
    return s;
  }

  /** Returns the sum of all elements in the vector.
   */
  public double  sum()
  {
    double s = 0;
    for( int i=0; i< size(); i++) s += V[i];
    return s;
  }

  /** Returns the squared sum of all elements in the vector.
   */
  public double  sum2()
  {
    double s2 = 0;
    for( int i=0; i< size(); i++) s2 += V[i] * V[i];
    return s2;
  }

  /** Returns the L1-norm of the vector
   */
  public double norm1()
  {
    double s = 0;
    for( int i=0; i< size(); i++) s += Math.abs(V[i]);
    return s;
  }

  /** Returns the L2-norm of the vector
   */
  public double norm2()
  {
    return Math.sqrt( sum2() );
  }

  /** Returns ||u-v||^2
   *  @param v the second vector
   */
  public double sum2( DoubleVector v )
  {
    return minus( v ).sum2();
  }

  /** Returns a subvector.
   *  @param i0   the index of the first element
   *  @param i1   the index of the last element
   *  @return     v[i0:i1]
   */
  public DoubleVector  subvector( int i0, int i1 )
  {
    DoubleVector v = new DoubleVector( i1-i0+1 );
    v.set(0, i1 - i0, this, i0);
    return v;
  }

  /** Returns a subvector.
   *  @param index stores the indices of the needed elements
   *  @return     v[index]
   */
  public DoubleVector  subvector( IntVector index ) {
    DoubleVector v = new DoubleVector( index.size() );
    for( int i = 0; i < index.size(); i++ )
      v.V[i] = V[index.V[i]];
    return v;
  }

  /** Returns a vector from the pivoting indices. Elements not indexed are
   *  set to zero.
   *  @param index stores the pivoting indices
   *  @param length the total number of the potential elements
   *  @return the subvector */
  public DoubleVector  unpivoting( IntVector index, int length ) {
    if( index.size() > length )
      throw new IllegalArgumentException("index.size() > length ");
    DoubleVector u = new DoubleVector( length );
    for( int i = 0; i < index.size(); i++ ) {
      u.V[index.V[i]] =  V[i];
    }
    return u;
  }

  /** Adds a value to all the elements
   *  @param x the value
   */
  public DoubleVector  plus ( double x ) {
    return copy().plusEquals( x );
  }

  /** Adds a value to all the elements in place
   *  @param x the value
   */
  public DoubleVector plusEquals ( double x ) {
    for( int i = 0; i < size(); i++ )
      V[i] += x;
    return this;
  }

  /**
   *  Adds another vector element by element
   *  @param v the second vector
   */
  public DoubleVector  plus( DoubleVector v ) {
    return copy().plusEquals( v );
  }

  /**
   *  Adds another vector in place element by element
   *  @param v the second vector
   */
  public DoubleVector  plusEquals( DoubleVector v ) {
    for(int i = 0; i < size(); i++ )
      V[i] += v.V[i];
    return this;
  }

  /**
   *  Subtracts a value
   *  @param x the value
   */
  public DoubleVector  minus( double x ) {
    return plus( -x );
  }

  /**
   *  Subtracts a value in place
   *  @param x the value
   */
  public DoubleVector  minusEquals( double x ) {
    plusEquals( -x );
    return this;
  }

  /**
   *  Subtracts another DoubleVector element by element
   *  @param v the second DoubleVector
   */
  public DoubleVector  minus( DoubleVector v ) {
    return copy().minusEquals( v );
  }

  /**
   *  Subtracts another DoubleVector element by element in place
   *  @param v the second DoubleVector
   */
  public DoubleVector  minusEquals( DoubleVector v ) {
    for(int i = 0; i < size(); i++ )
      V[i] -=  v.V[i];
    return this;
  }

  /** Multiplies a scalar
      @param s    scalar
      @return     s * v
  */
  public DoubleVector  times( double s ) {
    return copy().timesEquals( s );
  }

  /** Multiply a vector by a scalar in place, u = s * u
      @param s    scalar
      @return     replace u by s * u
  */
  public DoubleVector  timesEquals( double s ) {
    for (int i = 0; i < size(); i++) {
      V[i] *= s;
    }
    return this;
  }

  /**
   *  Multiplies another DoubleVector element by element
   *  @param v the second DoubleVector
   */
  public DoubleVector  times( DoubleVector v ) {
    return copy().timesEquals( v );

  }

  /**
   *  Multiplies another DoubleVector element by element in place
   *  @param v the second DoubleVector
   */
  public DoubleVector  timesEquals( DoubleVector v ) {
    for(int i = 0; i < size(); i++ )
      V[i] *= v.V[i];
    return this;
  }

  /**
   *  Divided by another DoubleVector element by element
   *  @param v the second DoubleVector
   */
  public DoubleVector  dividedBy ( DoubleVector v ) {
    return copy().dividedByEquals( v );
  }

  /**
   *  Divided by another DoubleVector element by element in place
   *  @param v the second DoubleVector
   */
  public DoubleVector  dividedByEquals ( DoubleVector v ) {
    for( int i = 0; i < size(); i++ ) {
      V[i] /= v.V[i];
    }
    return this;
  }

  /**
   *  Checks if it is an empty vector
   */
  public boolean  isEmpty() {
    if( size() == 0 ) return true;
    return false;
  }

  /**
   * Returns a vector that stores the cumulated values of the original
   * vector */
  public DoubleVector cumulate()
  {
    return copy().cumulateInPlace();
  }

  /**
   * Cumulates the original vector in place
   */
  public DoubleVector cumulateInPlace()
  {
    for (int i = 1; i < size(); i++) {
      V[i] += V[i-1];
    }
    return this;
  }

  /**
   * Returns the index of the maximum. <p>
   * If multiple maximums exist, the index of the first is returned.
   */
  public int  indexOfMax()
  {
    int index = 0;
    double ma = V[0];

    for( int i = 1; i < size(); i++ ){
      if( ma < V[i] ) {
	ma = V[i];
	index = i;
      }
    }
    return index;
  }

  /**
   * Returns true if vector not sorted
   */
  public boolean unsorted () {
    if( size() < 2 ) return false;
    for( int i = 1; i < size(); i++ ) {
      if( V[i-1] > V[i] )
	return true;
    }
    return false;
  }

  /**
   *  Combine two vectors together
   *  @param v the second vector
   */
  public DoubleVector  cat( DoubleVector v ) {
    DoubleVector w = new DoubleVector( size() + v.size() );
    w.set(0, size() - 1, this, 0);
    w.set(size(), size() + v.size()-1, v, 0);
    return w;
  }

  /**
   *  Swaps the values stored at i and j
   *  @param i the index i
   *  @param j the index j
   */
  public void  swap( int i, int j ){
    if( i == j ) return;
    double t = V[i];
    V[i] = V[j];
    V[j] = t;
  }

  /**
   *  Returns the maximum value of all elements
   */
  public double max () {
    if( size() < 1 ) throw new IllegalArgumentException("zero size");
    double ma = V[0];
    if( size() < 2 ) return ma;
    for( int i = 1; i < size(); i++ ) {
      if( V[i] > ma ) ma = V[i];
    }
    return ma;
  }

  /**
   *  Applies a method to the vector
   *  @param className the class name
   *  @param method the method
   */
  public DoubleVector map( String className, String method ) {
    try {
      Class c = Class.forName( className );
      Class [] cs = new Class[1];
      cs[ 0 ] = Double.TYPE;
      Method m = c.getMethod( method, cs );

      DoubleVector w = new DoubleVector( size() );
      Object [] obj = new Object[1];
      for( int i = 0; i < size(); i++ ) {
	obj[0] = new Double( V[i] );
	w.set( i, Double.parseDouble(m.invoke( null, obj ).toString()) );
      }
      return w;
    }
    catch ( Exception e ) {
      e.printStackTrace();
      System.exit(1);
    }
    return null;
  }

  /**
   * Returns the reverse vector
   */
  public DoubleVector  rev() {
    int n = size();
    DoubleVector w = new DoubleVector( n );
    for(int i = 0; i < n; i++ )
      w.V[i] = V[n-i-1];
    return w;
  }

  /**
   * Returns a random vector of uniform distribution
   * @param n the size of the vector
   */
  public static DoubleVector  random( int n ) {
    DoubleVector v = new DoubleVector( n );
    for (int i = 0; i < n; i++) {
      v.V[i] = Math.random();
    }
    return v;
  }

  /** Convert the DoubleVecor to a string
   */
  public String  toString() {
    return toString( 5, false );
  }

  /** Convert the DoubleVecor to a string
   *  @param digits the number of digits after decimal point
   *  @param trailing true if trailing zeros are to be shown
   */
  public String  toString( int digits, boolean trailing ) {
    if( isEmpty() ) return "null vector";

    StringBuffer text = new StringBuffer();
    FlexibleDecimalFormat nf = new FlexibleDecimalFormat( digits,
							  trailing );
    nf.grouping( true );
    for( int i = 0; i < size(); i ++ ) nf.update( V[i] );
    int count = 0;
    int width = 80;
    String number;
    for( int i = 0; i < size(); i++ ) {
      number = nf.format(V[i]);
      count += 1 + number.length();
      if( count > width-1 ) {
	text.append('\n');
	count = 1 + number.length();
      }
      text.append( " " + number );
    }

    return text.toString();
  }

  /**
   * Returns the revision string.
   *
   * @return		the revision
   */
  public String getRevision() {
    return RevisionUtils.extract("$Revision: 1.4 $");
  }

  public static void  main( String args[] ) {

    DoubleVector u = random(10);
    DoubleVector v = random(10);
    DoubleVector a = random(10);
    DoubleVector w = a;

    System.out.println( random(10).plus(v).plus(w) );

  }
}


text:
"""Environment base class for StreetView-based navigation problems.

https://arxiv.org/abs/1811.12354

Supports either discrete actions {Left, Right, Forward, Stop} or panoramic
actions (-180 to 180 degrees or 'stop'). If panoramic actions are used, this
environment represents them as bins from 0 to K, where bins 0 to K-1 represent
angles -180 + i*360/K (0 <= i <= K-1), and K-th bin indicates the stop action.
"""

from __future__ import absolute_import
from __future__ import division

from __future__ import print_function

import collections

from absl import logging
from language.bert import tokenization
import numpy as np
from valan.framework import base_env
from valan.framework import common
from valan.streetview_common import graph_loader
from valan.streetview_common import streetview_constants

GraphState = graph_loader.GraphState
Entry = graph_loader.Entry
StepInfo = collections.namedtuple('StepInfo', ('distance_to_goal'))

class StreetViewEnv(base_env.BaseEnv):
  """Abstract environment class for StreetView problems.

  An object of this class holds two main data structures:
  1. The graph of the underlying StreetView environment.
  2. The paths from JSON files depending on the source of data.
  """

  ACTION_STR_TO_IDX = {'forward': 0, 'left': 1, 'right': 2, 'stop': 3}
  ACTION_IDX_TO_STR = {v: k for k, v in ACTION_STR_TO_IDX.items()}

  _DEFAULT_STEP_REWARD = -0.2
  _INF = 1e9

  def __init__(self,
               data_sources,
               env_config,
               debug_writer=None,
               worker_idx=0):
    """Construct the StreetView environment.

    Args:
      data_sources: A list of strings containing one or more of 'train', 'dev'
        and 'test'.
      env_config: The configuration object containing settings for the current
        run.
      debug_writer: Class for writing execution traces to dir.
      worker_idx: Restrict regions that this worker explores to those
        where worker_idx % region_idx == 0. Default 0 means include all regions.
        region_idx is defined as the order in a sorted list of region names.
    """
    super(StreetViewEnv, self).__init__()

    # Logging execution traces if enabled
    self._run_writer = debug_writer

    self._env_config = env_config

    # Action space
    self._panoramic_actions = env_config.panoramic_action_space
    self._panoramic_action_bins = env_config.panoramic_action_bins

    # Attributes prefixed by _all* are dictionaries indexed by region name
    self._all_regions = self._select_regions(env_config, worker_idx)
    self._all_graphs = self._init_graphs(env_config, self._all_regions)

    # Load entry sequences for each region, and activate the current region
    self._all_entry_sequences = self._init_entry_sequences(
        data_sources, env_config, self._all_regions)
    logging.info('Loaded %d regions with data sources %s',
                 len(self._all_entry_sequences), data_sources)
    for region_name, entry_sequence in self._all_entry_sequences.items():
      logging.info('Region %s has %d entries', region_name, len(entry_sequence))

    self._all_feature_loaders = self._init_feature_loaders(
        env_config, self._all_regions)

    # Using BERT word piece tokenizer.
    self._tokenizer = tokenization.FullTokenizer(
        vocab_file=env_config.vocab_file, do_lower_case=True)
    # Constants from env_config.
    self._max_actions_per_episode = env_config.max_agent_actions
    self._instruction_tok_len = env_config.instruction_tok_len

    # Constant parameter
    self._base_yaw_angle = env_config.base_yaw_angle

    # Class members.
    # Variables that identify current instruction (assigned in reset)
    self._graph = None
    self._current_region = ''
    self._current_sequence_idx = -1
    self._current_entry_idx = 0

    # State variables
    self._frame_count = 0
    self._goal_pano_id = -1
    self._graph_state = GraphState(-1, 0., 0., 0.)
    self._distance_to_goal = 0.

    # Information about current instruction
    self._golden_actions = None
    self._golden_path = None

  def _select_regions(self, env_config, worker_idx=0):
    """Returns a list of regions that this worker should traverse."""
    raise NotImplementedError('_select_regions should have been overridden')

  def _init_graphs(self, env_config, worker_regions):
    """Returns a dict of (region name, graph) that this env can traverse."""
    raise NotImplementedError('_init_graphs should have been overridden')

  def _init_entry_sequences(self, data_sources, env_config, worker_regions):
    """Returns a dict of lists of Entry that represent all annotations."""
    raise NotImplementedError(
        '_init_entry_sequences should have been overridden')

  def _init_feature_loaders(self, env_config, worker_regions):
    """Returns a dict of functions that take a panoid and return an ndarray."""
    raise NotImplementedError(
        '_init_feature_loaders should have been overridden')

  def _pano_heading_to_action_bin(self, heading_degrees):
    """Converts action heading to a bin index."""
    # 11-degrees should be rounded up to the 20-degree bin
    bin_size = 360 / self._panoramic_action_bins
    action_bin = int((180 + heading_degrees + bin_size / 2) *
                     float(self._panoramic_action_bins) / 360) % (
                         self._panoramic_action_bins)
    return action_bin

  def _pano_action_bin_to_heading(self, action_bin):
    """Converts bin index (int) to an action heading."""
    assert action_bin < self._panoramic_action_bins
    heading_yaw = action_bin * (360.0 / self._panoramic_action_bins) - 180
    # Make sure that int(float(int(heading_yaw))) would not round integers down
    heading_yaw += 1e-9
    return heading_yaw

  def _convert_golden_actions(self, golden_actions):
    """Convert heading angles / strings to discrete action bins."""
    if self._panoramic_actions:
      # Convert each angle to bin index, except for stop action
      golden_actions = [h if h == 'stop' else
                        int(self._pano_heading_to_action_bin(h))
                        for h in golden_actions]
      # Convert stop action to bin index
      golden_actions = [int(self._panoramic_action_bins) if h == 'stop'
                        else int(h)
                        for h in golden_actions]
    else:
      golden_actions = [self.ACTION_STR_TO_IDX[a] for a in golden_actions]
    return golden_actions

  def _reset(self):
    self._frame_count = 0

    # Switch to a new, random region among this worker's regions
    region_idx = np.random.randint(0, len(self._all_regions))
    self._current_region = self._all_regions[region_idx]
    self._graph = self._all_graphs[self._current_region]

    # Switch to a new, random instruction sequence from this region
    self._current_sequence_idx = np.random.randint(
        0, len(self._all_entry_sequences[self._current_region]))
    current_entry_sequence = (
        self._all_entry_sequences[
            self._current_region][self._current_sequence_idx])

    # Switch to a new, random instruction from this instruction sequence

    self._current_entry_idx = np.random.randint(
        0, len(current_entry_sequence))
    current_entry = current_entry_sequence[self._current_entry_idx]

    # The graph uses different action representations depending on action space
    # Convert to integer indices - the unifying representation used here
    golden_actions, self._golden_path = self._graph.get_golden_actions(
        current_entry)
    self._golden_actions = self._convert_golden_actions(golden_actions)

    self._goal_pano_id = current_entry.route[-1]

    self._graph_state = GraphState(current_entry.route[0],
                                   current_entry.start_heading, 0, 0)
    self._distance_to_goal = self.shortest_path_length(
        self._graph_state.pano_id, self._goal_pano_id)

    if self._run_writer:
      self._run_writer.reset()
      self._run_writer.log_run_data({
          'region': self._current_region,
          'route_id': current_entry.route_id,
          'segment_idx': self._current_entry_idx})

    return common.EnvOutput(
        reward=np.float32(0.),
        done=False,
        # We randomly choose prev_action_idx at the beginning of every episode.

        observation=self._get_current_observation(
            prev_action=np.random.choice(
                self._panoramic_action_bins + 1 if self._panoramic_actions else
                streetview_constants.NUM_DISCRETE_ACTIONS)),
        info=self._get_step_info())

  def shortest_path_length(self, start_pano_id, end_pano_id):
    return self._graph.shortest_path_length(start_pano_id, end_pano_id)

  def _step(self, action):
    """Steps the environment.

    Args:
      action:
        If not using panoramic actions, this is an integer index 0 to 3
        If using panoramic actions, this is an index 0 to K, where
          values 0 to K-1 are angle bins from -180 to 180, and K is the stop
          action

    Returns:
      The next environment output.
    """
    self._frame_count += 1
    # Update distance to goal. Note that at every step, self._distance_to_goal
    # is the distance to goal from the pano we reached in the prev step.
    self._distance_to_goal = self.shortest_path_length(
        self._graph_state.pano_id, self._goal_pano_id)

    if not isinstance(action, np.ndarray):
      action = np.array(action, dtype=np.int64)

    # Convert action idx to representation used by the graph
    if self._panoramic_actions:
      # go_towards is 'stop' or heading angle in degrees
      go_towards = ('stop' if action >= self._panoramic_action_bins
                    else self._pano_action_bin_to_heading(action))
    else:
      # go_towards is left, right, forward or stop.
      go_towards = self.ACTION_IDX_TO_STR[int(action)]

    reward = 0.
    done = False
    if go_towards == 'stop':
      # If the action is to stop.

      reward = 1. if self._goal_pano_id == self._graph_state.pano_id else -1.
      done = True
    else:
      # Else, take the step.
      next_graph_state = self._graph.get_next_graph_state(self._graph_state,
                                                          go_towards)

      if len(self._graph.nodes[next_graph_state.pano_id].neighbors) < 2:
        # stay still when running into the boundary of the graph
        logging.info('At the border (number of neighbors < 2). Did not go %s.',
                     str(go_towards))
        done = True
      else:
        prev_state_potential = self.shortest_path_length(
            self._graph_state.pano_id, self._goal_pano_id)
        cur_state_potential = self.shortest_path_length(
            next_graph_state.pano_id, self._goal_pano_id)

        dist_reward = prev_state_potential - cur_state_potential
        reward = self._DEFAULT_STEP_REWARD + dist_reward

        self._graph_state = next_graph_state

    if self._frame_count > self._max_actions_per_episode:
      done = True

    observation = self._get_current_observation(prev_action=action)

    # Log transition:
    if self._run_writer:
      self._run_writer.log_action(action, go_towards)
      self._run_writer.log_state(self._graph_state)
      self._run_writer.log_observation(observation)
      if done:
        self._run_writer.write()

    return common.EnvOutput(
        reward=reward,
        done=done,
        observation=observation,
        info=self._get_step_info())

  def _get_step_info(self):
    return StepInfo(self._distance_to_goal)

  def _get_current_observation(self, prev_action):
    oracle_next_action = np.int64(-1)

    if self._frame_count < len(self._golden_actions):
      oracle_next_action = self._golden_actions[self._frame_count]

    # Make sure the types are consistent and as expected
    prev_action = int(prev_action)
    oracle_next_action = int(oracle_next_action)

    pad_length = max(
        0, streetview_constants.MAX_GOLDEN_PATH_LENGTH - len(self._golden_path))
    self._golden_path = self._golden_path + [
        streetview_constants.INVALID_PANO_ID
    ] * pad_length

    return {
        streetview_constants.PANO_ID: self._graph_state.pano_id,
        streetview_constants.IMAGE_FEATURES: (
            self._get_image_feature(self._graph_state)),
        streetview_constants.HEADING: float(self._graph_state.heading),
        streetview_constants.LATITUDE: float(self._graph_state.latitude),
        streetview_constants.LONGITUDE: float(self._graph_state.longitude),
        streetview_constants.TIMESTEP: self._frame_count,
        streetview_constants.PREV_ACTION_IDX: prev_action,
        streetview_constants.ORACLE_NEXT_ACTION: oracle_next_action,
        streetview_constants.GOLDEN_PATH: self._golden_path,
    }

  def _get_image_feature(self, graph_state):
    """Retrieve image features for current pano."""
    # Expensive sstable call.
    image_feature = self._all_feature_loaders[self._current_region](
        graph_state.pano_id)

    # rotate the pano feature so the middle is the agent's heading direction
    # `shift_angle` is essential for adjusting to the correct heading
    # please include the following in your own `get_image_feature` function
    shift_angle = self._base_yaw_angle + self._graph.nodes[
        graph_state.pano_id].pano_yaw_angle - graph_state.heading

    # Pano feature shape for Touchdown (1, 8, 2048)
    width = image_feature.shape[1]
    shift = int(width * shift_angle / 360)
    image_feature = np.roll(image_feature, shift, axis=1)

    return image_feature

  def _get_text_feature(self, text):
    word_list = self._tokenizer.tokenize(text)
    # 0 vocab id can not be used since we are masking for RNN performance.
    # Therefore, shift all vocab ids by 1.
    token_embeddings = np.asarray(pad_or_truncate(
        [x + 1 for x in self._tokenizer.convert_tokens_to_ids(word_list)],
        self._instruction_tok_len))
    tokenized_length = np.asarray(
        min(len(word_list), self._instruction_tok_len))
    return token_embeddings, tokenized_length

def pad_or_truncate(x, desired_length, pad_num=0):
  if len(x) >= desired_length:
    return x[:desired_length]
  else:
    return x + [pad_num] * (desired_length - len(x))


text:
import api.Endpoint;
import api.IComponent;

public class MultiComponent extends CompoundComponent {

	private int m;
	private int n;

	private Endpoint[] inputs;
	private Endpoint[] outputs;

	public MultiComponent(IComponent[] components) {

		super(components[0].inputs().length * components.length, components.length);
		inputs = super.inputs();
		outputs = super.outputs();

		m = components[0].inputs().length;
		n = components.length;

		for(int i=0; i < n; ++i){

			components[i].invalidateInputs();
			components[i].invalidateOutputs();
		}

		for(int i=0; i < n; ++i){

			int inputHolder = 0;

			for(int j=i*m; j < (i + 1)*m; ++j){

					inputs()[j].connectTo(components[i].inputs()[inputHolder]);

					inputHolder++;
			}

			components[i].outputs()[0].connectTo(outputs()[i]);
			components[i].propagate();

		}

	}


text:
namespace GraphClimber
{
    public interface INullProcessor
    {
        void ProcessNull<TField>(IWriteOnlyValueDescriptor<TField> descriptor);
    }
}


text:
<?php

namespace Bolt\Extension\Bolt\BoltForms\Event;

use Symfony\Component\EventDispatcher\Event;

class BoltFormsCustomDataEvent extends Event
{
    /** @var string */
    protected $eventName;
    /** @var array */
    protected $eventParams;
    /** @var mixed */
    protected $data;

    /**
     * @param string $eventName
     * @param array  $eventParams
     */
    public function __construct($eventName, $eventParams)
    {
        $this->eventName = $eventName;
        $this->eventParams = $eventParams;
    }

    /**
     * Get the event name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->eventName;
    }

    /**
     * Get the user supplied parameters.
     *
     * @return array
     */
    public function getParameters()
    {
        return $this->eventParams;
    }

    /**
     * Get the event's data.
     *
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Set the event's data.
     *
     * @param mixed
     */
    public function setData($data)
    {
        $this->data = $data;
    }
}


text:
<?php

Yii::import('bootstrap.helpers.TbArray');

class WhSparkLines extends CWidget
{
    /**
     * @var string the tag name to render the sparkline to
     * NOTE: span type of tag may have issues.
     */
    public $tagName = 'div';

    /**
     * @var array the data to show on the chart
     * @see http://omnipotent.net/jquery.sparkline/#s-about
     */
    public $data = array();

    /**
     * @var array additional HTML attributes to the tag
     */
    public $htmlOptions = array();

    /**
     * @var array plugin options
     */
    public $pluginOptions = array();

    /**
     * Debug mode
     * Used to publish full js file instead of min version
     */
    public $debugMode = false;

    /**
     * Widget's initialization method
     */
    public function init()
    {
        if (empty($this->data)) {
            throw new CException(Yii::t('zii', '"data" attribute cannot be blank'));
        }

        $this->attachBehavior('ywplugin', array('class' => 'yiiwheels.behaviors.WhPlugin'));

        $this->htmlOptions['id'] = TbArray::getValue('id', $this->htmlOptions, $this->getId());
    }

    /**
     * Widget's run method
     */
    public function run()
    {
        echo CHtml::openTag($this->tagName, $this->htmlOptions);
        echo CHtml::closeTag($this->tagName);
        $this->registerClientScript();
    }

    /**
     * Registers required client script for sparklines
     */
    public function registerClientScript()
    {
        /* publish assets dir */
        $path      = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
        $assetsUrl = $this->getAssetsUrl($path);

        /* @var $cs CClientScript */
        $cs = Yii::app()->getClientScript();

        $script = $this->debugMode
            ? 'jquery.sparkline.js'
            : 'jquery.sparkline.min.js';

        $cs->registerScriptFile($assetsUrl . '/js/' . $script);
        $cs->registerCssFile($assetsUrl . '/css/jquery.sparkline.css');

        /* initialize plugin */
        $selector = '#' . TbArray::getValue('id', $this->htmlOptions, $this->getId());

        $data    = CJavaScript::encode($this->data);
        $options = CJavaScript::encode($this->pluginOptions);

        $cs->registerScript(__CLASS__ . '#' . $selector, "jQuery('{$selector}').sparkline({$data}, {$options});");
    }
}


text:
package com.tom.storage.tileentity.gui;

import net.minecraft.entity.player.InventoryPlayer;

import com.tom.storage.multipart.PartExportBus;
import com.tom.storage.tileentity.inventory.ContainerExportBus;

public class GuiExportBus extends GuiMultipartBase {

	public GuiExportBus(PartExportBus bus, InventoryPlayer playerInv) {
		super(new ContainerExportBus(bus, playerInv), "GuiImportBus", bus);
	}

	@Override
	public void initGui() {
		ySize = 176;
		super.initGui();
	}
}


text:
import os
import sys
from git import Repo
from builtins import input
from appdirs import *

"""
You need to have a valid SSH key added to your GitHub account
This key serves as a fingerprint and password authentication is skipped while pushing code
If SSH key has not been added then you will be prompted for password while pushing

To set up git_username and git_reponame run -
python lazygit new

To push code to remote repository run -
lazygit <checkout_dir>
"""

#Keywords
usage_message = 'usage: lazygit [new|check-out-directory]'
checkout_dir_error = 'checkout_dir does not exist'
git_remote_command = 'git remote set-url origin git@github.com:'
slash = "/"
git = ".git"

appname = "lazygit"
appauthor = "MayankSaxena"

info_dirname = user_data_dir(appname, appauthor)
info_filename = info_dirname + '/info.txt'

def main():
    if not os.path.exists(info_dirname) :
       os.makedirs(info_dirname)

    try :
      assert len(sys.argv) == 2
    except AssertionError as e:
        print(usage_message)
        return
    commandname =  sys.argv[1]
    commandname = commandname.lower()
    if commandname == 'new' :
            #Write git_username and git_reponame to info.txt file
            f = open(info_filename , 'w')
            git_username = input('Enter your GitHub username : ')
            f.write(git_username)
            f.write(os.linesep)
            git_reponame = input('Enter GitHub remote repository name : ')
            f.write(git_reponame)
            f.close()

    else :
            checkout_dir = sys.argv[1]
            if not os.path.exists(checkout_dir) :
               print(checkout_dir_error)
               return

            commit_msg = input('Write your commit message: ')
            repo = Repo(checkout_dir)
            branch = repo.active_branch
            print ('Active branch name is: ',branch.name)

            #Retrieve git_username and git_reponame from info.txt file

            with open(info_filename) as f:
                content = f.readlines()

            content = [x.strip('\n') for x in content]

            git_username = content[0]
            git_reponame = content[1]

            url = git_remote_command + git_username + slash + git_reponame + git

            #Path to local repository
            #path =  checkout_dir + '/' + repo_name + '/'

            os.chdir('%s' %checkout_dir)

            #Printing current wokring directory
            print ('Current working directory is : ')
            os.system('pwd')

            #Check whether git has been initialised in directory
            n = os.system('git rev-parse')
            #print n

            #If n == 0 git has been initialised already
            #If n != 0 initialise git and add set remote repo URL
            if n != 0 :
                print 'Current working directory is - '
                os.system('pwd')
                os.system('git init')
                os.system('git remote add origin https://github.com/' + git_username + slash + git_reponame + git)
                os.system('git remote add origin git@github.com:' + git_username + slash + git_reponame + git)
                os.system(url)

            txt = """#!/bin/sh

GIT_WORK_TREE = %s git checkout -f""" %checkout_dir

            #Run git add, commit, push
            os.system('git add .')
            os.system('git commit -m \'' + commit_msg + '\'')
            os.system('git push origin '+ branch.name)

if __name__ == "__main__" :
    main()


text:
MainWidget::MainWidget( QWidget* parent )
    : QWidget( parent )
{
    m_pSTW = NULL;

    QPushButton* b = new QPushButton( "Rotate" );
    QObject::connect( b, SIGNAL( released() ), this, SLOT( handleButtonPushed() ) );

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget( b );
    setLayout( layout );
}

void MainWidget::setTriangleWidget( SimpleTriangleWidget* w )
{
    m_pSTW = w;
}

void MainWidget::handleButtonPushed()
{
    if( m_pSTW != NULL )
    {
        m_pSTW->m_bRotating = !( m_pSTW->m_bRotating );
    }
}


text:
/**
 * Returns a new object with the key/value pairs from `obj` that are not in the array `omitKeys`.
 */
export default function (obj, omitKeys) {
  const result = {}
  Object.keys(obj).forEach((key) => {
    if (omitKeys.indexOf(key) === -1) {
      result[key] = obj[key]
    }
  })
  return result
}


text:
<?php

/**
 * This file is part of Droctrine Mongo
 *
 * (c) Korstiaan de Ridder <korstiaan@korstiaan.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Droctrine\Mongo\Helper;

class DrupalHelper
{
    public function getModuleList()
    {
        return module_list();
    }
}