text:
#pragma once
#include <aws/storagegateway/StorageGateway_EXPORTS.h>
#include <aws/storagegateway/StorageGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace StorageGateway
{
namespace Model
{

  /**
   *
A JSON object containing the following fields:

   * UpdateMaintenanceStartTimeInput$DayOfMonth

   * UpdateMaintenanceStartTimeInput$DayOfWeek

   * UpdateMaintenanceStartTimeInput$HourOfDay

   * UpdateMaintenanceStartTimeInput$MinuteOfHour

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_STORAGEGATEWAY_API UpdateMaintenanceStartTimeRequest : public StorageGatewayRequest
  {
  public:
    UpdateMaintenanceStartTimeRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateMaintenanceStartTime"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    inline const Aws::String& GetGatewayARN() const{ return m_gatewayARN; }

    inline bool GatewayARNHasBeenSet() const { return m_gatewayARNHasBeenSet; }

    inline void SetGatewayARN(const Aws::String& value) { m_gatewayARNHasBeenSet = true; m_gatewayARN = value; }

    inline void SetGatewayARN(Aws::String&& value) { m_gatewayARNHasBeenSet = true; m_gatewayARN = std::move(value); }

    inline void SetGatewayARN(const char* value) { m_gatewayARNHasBeenSet = true; m_gatewayARN.assign(value); }

    inline UpdateMaintenanceStartTimeRequest& WithGatewayARN(const Aws::String& value) { SetGatewayARN(value); return *this;}

    inline UpdateMaintenanceStartTimeRequest& WithGatewayARN(Aws::String&& value) { SetGatewayARN(std::move(value)); return *this;}

    inline UpdateMaintenanceStartTimeRequest& WithGatewayARN(const char* value) { SetGatewayARN(value); return *this;}

    /**
     *
The hour component of the maintenance start time represented as hh,
     * where hh is the hour (00 to 23). The hour of the day is in the time zone
     * of the gateway.

     */
    inline int GetHourOfDay() const{ return m_hourOfDay; }

    /**
     *
The hour component of the maintenance start time represented as hh,
     * where hh is the hour (00 to 23). The hour of the day is in the time zone
     * of the gateway.

     */
    inline bool HourOfDayHasBeenSet() const { return m_hourOfDayHasBeenSet; }

    /**
     *
The hour component of the maintenance start time represented as hh,
     * where hh is the hour (00 to 23). The hour of the day is in the time zone
     * of the gateway.

     */
    inline void SetHourOfDay(int value) { m_hourOfDayHasBeenSet = true; m_hourOfDay = value; }

    /**
     *
The hour component of the maintenance start time represented as hh,
     * where hh is the hour (00 to 23). The hour of the day is in the time zone
     * of the gateway.

     */
    inline UpdateMaintenanceStartTimeRequest& WithHourOfDay(int value) { SetHourOfDay(value); return *this;}

    /**
     *
The minute component of the maintenance start time represented as mm,
     * where mm is the minute (00 to 59). The minute of the hour is in the time
     * zone of the gateway.

     */
    inline int GetMinuteOfHour() const{ return m_minuteOfHour; }

    /**
     *
The minute component of the maintenance start time represented as mm,
     * where mm is the minute (00 to 59). The minute of the hour is in the time
     * zone of the gateway.

     */
    inline bool MinuteOfHourHasBeenSet() const { return m_minuteOfHourHasBeenSet; }

    /**
     *
The minute component of the maintenance start time represented as mm,
     * where mm is the minute (00 to 59). The minute of the hour is in the time
     * zone of the gateway.

     */
    inline void SetMinuteOfHour(int value) { m_minuteOfHourHasBeenSet = true; m_minuteOfHour = value; }

    /**
     *
The minute component of the maintenance start time represented as mm,
     * where mm is the minute (00 to 59). The minute of the hour is in the time
     * zone of the gateway.

     */
    inline UpdateMaintenanceStartTimeRequest& WithMinuteOfHour(int value) { SetMinuteOfHour(value); return *this;}

    /**
     *
The day of the week component of the maintenance start time week represented
     * as an ordinal number from 0 to 6, where 0 represents Sunday and 6 Saturday.

     */
    inline int GetDayOfWeek() const{ return m_dayOfWeek; }

    /**
     *
The day of the week component of the maintenance start time week represented
     * as an ordinal number from 0 to 6, where 0 represents Sunday and 6 Saturday.

     */
    inline bool DayOfWeekHasBeenSet() const { return m_dayOfWeekHasBeenSet; }

    /**
     *
The day of the week component of the maintenance start time week represented
     * as an ordinal number from 0 to 6, where 0 represents Sunday and 6 Saturday.

     */
    inline void SetDayOfWeek(int value) { m_dayOfWeekHasBeenSet = true; m_dayOfWeek = value; }

    /**
     *
The day of the week component of the maintenance start time week represented
     * as an ordinal number from 0 to 6, where 0 represents Sunday and 6 Saturday.

     */
    inline UpdateMaintenanceStartTimeRequest& WithDayOfWeek(int value) { SetDayOfWeek(value); return *this;}

    /**
     *
The day of the month component of the maintenance start time represented as
     * an ordinal number from 1 to 28, where 1 represents the first day of the month
     * and 28 represents the last day of the month.

     */
    inline int GetDayOfMonth() const{ return m_dayOfMonth; }

    /**
     *
The day of the month component of the maintenance start time represented as
     * an ordinal number from 1 to 28, where 1 represents the first day of the month
     * and 28 represents the last day of the month.

     */
    inline bool DayOfMonthHasBeenSet() const { return m_dayOfMonthHasBeenSet; }

    /**
     *
The day of the month component of the maintenance start time represented as
     * an ordinal number from 1 to 28, where 1 represents the first day of the month
     * and 28 represents the last day of the month.

     */
    inline void SetDayOfMonth(int value) { m_dayOfMonthHasBeenSet = true; m_dayOfMonth = value; }

    /**
     *
The day of the month component of the maintenance start time represented as
     * an ordinal number from 1 to 28, where 1 represents the first day of the month
     * and 28 represents the last day of the month.

     */
    inline UpdateMaintenanceStartTimeRequest& WithDayOfMonth(int value) { SetDayOfMonth(value); return *this;}

  private:

    Aws::String m_gatewayARN;
    bool m_gatewayARNHasBeenSet;

    int m_hourOfDay;
    bool m_hourOfDayHasBeenSet;

    int m_minuteOfHour;
    bool m_minuteOfHourHasBeenSet;

    int m_dayOfWeek;
    bool m_dayOfWeekHasBeenSet;

    int m_dayOfMonth;
    bool m_dayOfMonthHasBeenSet;
  };

} // namespace Model
} // namespace StorageGateway
} // namespace Aws


text:
import DataType from 'sequelize';
import Model from '../sequelize';

const Record = Model.define('Record', {
  id: {
    type: DataType.UUID,
    defaultValue: DataType.UUIDV4,
    primaryKey: true,
  },

  date: {
    type: DataType.DATE(50),
  },
});

export default Record;

redpajama_set_name: RedPajamaGithub


text:
package ${package}.util;

import java.util.UUID;

public class IdUtil {
    public static String createUUID() {
        return UUID.randomUUID().toString();
    }
}


text:
pub trait TraitWithDefaultMethod : Sized {
    fn method(self) {
        ()
    }
}

struct MyStruct;

impl TraitWithDefaultMethod for MyStruct { }

pub fn main() {
    MyStruct.method();
}


text:
/**
 * @fileoverview Telnet server for Code City.
 */

//////////////////////////////////////////////////////////////////////
// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!
//////////////////////////////////////////////////////////////////////

$.servers.telnet = {};
$.servers.telnet.connection = (new 'Object.create')($.connection);
$.servers.telnet.connection.onReceiveLine = function onReceiveLine(text) {
  if (this.user) {  // Logged in?
    // Set 'user' for this thread, and permissions for call
    Object.setOwnerOf(Thread.current(), this.user);
    setPerms(this.user);
    this.user.onInput(text);
    return;
  }
  // Remainder of function handles login.
  // TODO(fraser): Make sure that no security issues exist due to
  // called code suspending or timing out unexpectedly.
  var m = text.match(/identify as ([0-9a-f]+)/);
  if (!m) {
    this.write('{type: "narrate", text: "Unknown command: ' +
               $.utils.html.preserveWhitespace(text) + '"}');
    return;
  }
  var id = m[1];
  var user = $.userDatabase.get(id) || $.servers.login.createUser(id);
  this.user = user;
  var rebind = false;
  if (user.connection) {
    rebind = true;
    try {
      user.connection.close();
    } catch (e) {
      // Ignore; maybe connection already closed (e.g., due to crash/reboot).
    }
    $.system.log('Rebinding connection to ' + user.name);
  } else {
    $.system.log('Binding connection to ' + user.name);
  }
  user.connection = this;
  Object.setOwnerOf(Thread.current(), user);
  setPerms(this.user);
  new Thread(user.onConnect, 0, user, rebind);
};
Object.setOwnerOf($.servers.telnet.connection.onReceiveLine, $.physicals.Maximilian);
$.servers.telnet.connection.onEnd = function onEnd() {
  var user = this.user;
  // Mark connection as closed.
  $.connection.onEnd.call(this);
  if (user) {
    // Unbind connection from user.
    this.user = null;
    if (user.connection === this) {
      user.connection = null;
      $.system.log('Unbinding connection from ' + user.name);
      (function () {
        setPerms(user);
        new Thread(user.onDisconnect, 0, user);
      })();
    }
  }
  // Remove this and any other closed / debound connections from array of open connections.
  $.servers.telnet.validate();
};
Object.setOwnerOf($.servers.telnet.connection.onEnd, $.physicals.Maximilian);
$.servers.telnet.connection.onConnect = function onConnect() {
  // super call.  Records .connectTime (as number of ms since epoch).
  $.connection.onConnect.apply(this, arguments);
  // Add this connection to list of active telnet connections.
  $.servers.telnet.connected.push(this);
  setTimeout((function onConnect_timeout() {
    if (!this.user) this.close();
  }).bind(this), $.servers.telnet.LOGIN_TIMEOUT_MS);
};
Object.setOwnerOf($.servers.telnet.connection.onConnect, $.physicals.Maximilian);
Object.setOwnerOf($.servers.telnet.connection.onConnect.prototype, $.physicals.Maximilian);
$.servers.telnet.validate = function validate() {
  // Examine supposedly-open connections and close and/or remove
  // closed / timed-out / debound ones from the .connected arary.
  var limit = Date.now() - this.LOGIN_TIMEOUT_MS;
  this.connected = this.connected.filter(function(c) {
    // Close any connections that haven't logged in promptly.
    if (!c.user && c.connectTime < limit) {
      try {
        // Call .close().  Note that that this won't result in the
        // object's .connected property being set to false
        // immediately, but only after an async callback to
        // connection.onEnd() - which will result in another call
        // to $.servers.telnet.validate().
        c.close();
      } catch (e) {
        // Connection was already closed.  Mark it as such.
        c.connected = false;
      }
    }
    return c.connected && (!c.user || c.user.connection === c);
  });
};
Object.setOwnerOf($.servers.telnet.validate, $.physicals.Maximilian);
Object.setOwnerOf($.servers.telnet.validate.prototype, $.physicals.Maximilian);
$.servers.telnet.LOGIN_TIMEOUT_MS = 20000;

$.servers.telnet.connected = [];


text: puts("Hello world!")


text:
<link rel="stylesheet" href="../asset/css/bootstrap.min.css">
<script src="../asset/js/bootstrap.min.js"></script>
<script src="../asset/js/angular.min.js"></script>


text:
package library.network.utils;

import java.net.Socket;

/**
 * Wrapper around Threaded Socket
 */
public abstract class AbstractConcurrentServer extends AbstractServer
{
    public AbstractConcurrentServer(int port)
    {
        super(port);
        System.out.println("Concurrent AbstractServer");
    }

    protected void processRequest(Socket client)
    {
        Thread tw = createWorker(client);
        tw.start();
    }

    protected abstract Thread createWorker(Socket client);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
	<string name="apptitle">snapamigo</string>
	<string name="no_network_title">Connection Required</string>
	<string name="no_network_msg">We cannot detect a network connection.</string>
	<string name="twitter_time_lessminute">less than a minute ago</string>
	<string name="twitter_minuteago">a minute ago</string>
	<string name="twitter_minutesago"> minutes ago</string>
	<string name="twitter_hourago">about 1 hour ago</string>
	<string name="twitter_aboutnum">about </string>
	<string name="twitter_hoursago"> hours ago</string>
	<string name="twitter_oneday">1 day ago</string>
	<string name="twitter_daysago"> days ago</string>
	<string name="twitter_monthago">about 1 month ago</string>
	<string name="twitter_monthsago"> months ago</string>
	<string name="twitter_yearago">about 1 year ago</string>
	<string name="twitter_over">over </string>
	<string name="twitter_yearsago"> years ago</string>
</resources>


text:
#ifndef CAF_ABSTRACT_UNIFORM_TYPE_INFO_HPP
#define CAF_ABSTRACT_UNIFORM_TYPE_INFO_HPP

#include "caf/message.hpp"
#include "caf/deserializer.hpp"
#include "caf/uniform_type_info.hpp"

#include "caf/detail/type_traits.hpp"

namespace caf {

/// Implements all pure virtual functions of `uniform_type_info`
/// except serialize() and deserialize().
template <class T>
class abstract_uniform_type_info : public uniform_type_info {
public:
  const char* name() const override {
    return name_.c_str();
  }

  message as_message(void* instance) const override {
    return make_message(deref(instance));
  }

  bool equal_to(const std::type_info& tinfo) const override {
    return native_ == &tinfo || *native_ == tinfo;
  }

  bool equals(const void* lhs, const void* rhs) const override {
    return eq(deref(lhs), deref(rhs));
  }

  uniform_value create(const uniform_value& other) const override {
    return create_impl<T>(other);
  }

protected:
  abstract_uniform_type_info(std::string tname)
      : name_(std::move(tname)),
        native_(&typeid(T)) {
    // nop
  }

  static const T& deref(const void* ptr) {
    return *reinterpret_cast<const T*>(ptr);
  }

  static T& deref(void* ptr) {
    return *reinterpret_cast<T*>(ptr);
  }

  // can be overridden in subclasses to compare POD types
  // by comparing each individual member
  virtual bool pod_mems_equals(const T&, const T&) const {
    return false;
  }

  std::string name_;
  const std::type_info* native_;

private:
  template <class C>
  typename std::enable_if<std::is_empty<C>::value, bool>::type
  eq(const C&, const C&) const {
    return true;
  }

  template <class C>
  typename std::enable_if<
    ! std::is_empty<C>::value && detail::is_comparable<C, C>::value,
    bool
  >::type
  eq(const C& lhs, const C& rhs) const {
    return lhs == rhs;
  }

  template <class C>
  typename std::enable_if<
    ! std::is_empty<C>::value
    && ! detail::is_comparable<C, C>::value
    && std::is_pod<C>::value,
    bool
  >::type
  eq(const C& lhs, const C& rhs) const {
    return pod_mems_equals(lhs, rhs);
  }
};

} // namespace caf

#endif // CAF_ABSTRACT_UNIFORM_TYPE_INFO_HPP


text:
<?php declare(strict_types=1);

namespace SebastianBergmann\Comparator;

use PHPUnit\Framework\TestCase;
use stdClass;

/**
 * @covers \SebastianBergmann\Comparator\ObjectComparator
 *
 * @uses \SebastianBergmann\Comparator\Comparator
 * @uses \SebastianBergmann\Comparator\ComparisonFailure
 * @uses \SebastianBergmann\Comparator\Factory
 */
final class ObjectComparatorTest extends TestCase
{
    /**
     * @var ObjectComparator
     */
    private $comparator;

    protected function setUp(): void
    {
        $this->comparator = new ObjectComparator;
        $this->comparator->setFactory(new Factory);
    }

    public function acceptsSucceedsProvider()
    {
        return [
            [new TestClass, new TestClass],
            [new stdClass, new stdClass],
            [new stdClass, new TestClass],
        ];
    }

    public function acceptsFailsProvider()
    {
        return [
            [new stdClass, null],
            [null, new stdClass],
            [null, null],
        ];
    }

    public function assertEqualsSucceedsProvider()
    {
        // cyclic dependencies
        $book1                  = new Book;
        $book1->author          = new Author('Terry Pratchett');
        $book1->author->books[] = $book1;
        $book2                  = new Book;
        $book2->author          = new Author('Terry Pratchett');
        $book2->author->books[] = $book2;

        $object1 = new SampleClass(4, 8, 15);
        $object2 = new SampleClass(4, 8, 15);

        return [
            [$object1, $object1],
            [$object1, $object2],
            [$book1, $book1],
            [$book1, $book2],
            [new Struct(2.3), new Struct(2.5), 0.5],
        ];
    }

    public function assertEqualsFailsProvider()
    {
        $typeMessage  = 'is not instance of expected class';
        $equalMessage = 'Failed asserting that two objects are equal.';

        // cyclic dependencies
        $book1                  = new Book;
        $book1->author          = new Author('Terry Pratchett');
        $book1->author->books[] = $book1;
        $book2                  = new Book;
        $book2->author          = new Author('Terry Pratch');
        $book2->author->books[] = $book2;

        $book3         = new Book;
        $book3->author = 'Terry Pratchett';
        $book4         = new stdClass;
        $book4->author = 'Terry Pratchett';

        $object1 = new SampleClass(4, 8, 15);
        $object2 = new SampleClass(16, 23, 42);

        return [
            [new SampleClass(4, 8, 15), new SampleClass(16, 23, 42), $equalMessage],
            [$object1, $object2, $equalMessage],
            [$book1, $book2, $equalMessage],
            [$book3, $book4, $typeMessage],
            [new Struct(2.3), new Struct(4.2), $equalMessage, 0.5],
        ];
    }

    /**
     * @dataProvider acceptsSucceedsProvider
     */
    public function testAcceptsSucceeds($expected, $actual): void
    {
        $this->assertTrue(
            $this->comparator->accepts($expected, $actual)
        );
    }

    /**
     * @dataProvider acceptsFailsProvider
     */
    public function testAcceptsFails($expected, $actual): void
    {
        $this->assertFalse(
            $this->comparator->accepts($expected, $actual)
        );
    }

    /**
     * @dataProvider assertEqualsSucceedsProvider
     */
    public function testAssertEqualsSucceeds($expected, $actual, $delta = 0.0): void
    {
        $exception = null;

        try {
            $this->comparator->assertEquals($expected, $actual, $delta);
        } catch (ComparisonFailure $exception) {
        }

        $this->assertNull($exception, 'Unexpected ComparisonFailure');
    }

    /**
     * @dataProvider assertEqualsFailsProvider
     */
    public function testAssertEqualsFails($expected, $actual, $message, $delta = 0.0): void
    {
        $this->expectException(ComparisonFailure::class);
        $this->expectExceptionMessage($message);

        $this->comparator->assertEquals($expected, $actual, $delta);
    }
}


text:
> 2.1 [Installing Visual Studio]() - TODO

#### 3. Installing on Linux
> 3.1 [Installing IntelliJ]() - TODO

#### 4. API Documentation
> 4.1. [PyAPI](./api/pyapi.md) - The C++ <=> Python binding

#### 5. Help Section
> 5.1. [Questions and Answers](./api/issues/qa.md) - Problems i've stumbled upon

#### 6. Research
> 6.1. [Monte Carlo Methods](./pages/monte_carlo_methods.md) - General Infromation about MCM

> 6.2. [Monte Carlo Graph Search](./pages/mcgs/index.md) - Algorithm overview of MCGS

> 6.3. [Monte Carlo Tree Search](./pages/mcts/index.md) - Algorithm overview of MCTS

> 6.4. [MSC. Presentation](./pages/presentation.md) - Meeting minutes presentation (Incremental)

> 6.5. **Deep Q Network**

> 6.5.1 [Initial Results](./pages/dqn/results_1/results_1.md) - The first results from running trials

#### 7. Other
> 7.1. [Performance Log](./pages/performance_log.md) - Log over DeepRTS Performance

> 7.2. [MCGS Idea Email](./emails/mcgs_idea.md) - The initial idea of MCGS

> 7.3. [JSON Performance Considerations](./pages/json_performance.md)


text:
---
layout: post
title: Design Pattern 19-java 备忘录模式(Memento Pattern)
date:  2017-03-14 19:52:28 +0800
categories: [Design Pattern]
tags: [design pattern, sf]
published: true
---

# 备忘录模式

备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。

备忘录模式属于行为型模式。

# 实际案例

类信息概览:

| 类名 | 说明 |
|:----|:----|
| Main.java | 方法的总入口 |
| Memento.java | 记忆者 |
| MementoManager.java | 记忆管理者 |
| Original.java | 原始内容 |

## 定义

- Memento.java

```java
package com.ryo.design.pattern.note.memento;

/**
 * @author houbinbin
 * @version 1.0
 * @on 2017/8/17
 * @since 1.7
 */
public class Memento {

    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

```

- MementoManager.java

```java
package com.ryo.design.pattern.note.memento;

import java.util.LinkedList;
import java.util.List;

/**
 * @author houbinbin
 * @version 1.0
 * @on 2017/8/17
 * @since 1.7
 */
public class MementoManager {

    private List<Memento> mementoList = new LinkedList<>();

    public void add(Memento memento) {
        this.mementoList.add(memento);
    }

    public Memento get(int index) {
        return mementoList.get(index);
    }

}

```

- Original.java

```java
package com.ryo.design.pattern.note.memento;

/**
 * @author houbinbin
 * @version 1.0
 * @on 2017/8/17
 * @since 1.7
 */
public class Original {

    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    //-------------------public method;

    /**
     * 保存到 记忆体中
     * @return
     */
    public Memento saveToMemento() {
        return new Memento(this.getState());
    }

    /**
     * 从记忆体中获取对应的状态
     * @param memento
     */
    public void getStateFromMemento(Memento memento) {
        String state = memento.getState();
        this.state = state;;
    }

}

```

## 测试

- Main.java

```java
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright (c) 2012-2018. houbinbini Inc.
 * design-pattern All rights reserved.
 */

package com.ryo.design.pattern.note.memento;

/**
 * <p> </p>
 *
 * <pre> Created: 2018/5/23 下午8:46  </pre>
 * <pre> Project: design-pattern  </pre>
 *
 * @author houbinbin
 * @version 1.0
 * @since JDK 1.7
 */
public class Main {

    public static void main(String[] args) {
        Original original = new Original();
        MementoManager manager = new MementoManager();
        original.setState("State #1");
        original.setState("State #2");
        manager.add(original.saveToMemento());
        original.setState("State #3");
        manager.add(original.saveToMemento());
        original.setState("State #4");

        System.out.println("Current State: " + original.getState());
        original.getStateFromMemento(manager.get(0));
        System.out.println("First saved State: " + original.getState());
        original.getStateFromMemento(manager.get(1));
        System.out.println("Second saved State: " + original.getState());
    }

}

```

- 测试结果

```
Current State: State #4
First saved State: State #2
Second saved State: State #3
```

# 实现方式

# UML & Code

## UML

UML 图示如下

## Code

代码地址

> [备忘录模式](https://github.com/houbb/design-pattern/tree/master/design-pattern-note/src/main/java/com/ryo/design/pattern/note/memento)

# 系列导航

> [系列导航](https://blog.csdn.net/ryo1060732496/article/details/80214740)

* any list
{:toc}


text:
package gw.plugin.ij.framework.generator;

import com.intellij.psi.PsiFile;
import gw.plugin.ij.framework.GosuTestCase;

import java.util.ArrayList;
import java.util.List;

public class ResourceFactory2 {

  public static GosuTestingResource create(String text) {
    String cleanText = GosuTestingResource.removeMarkers(text.trim());
    String uncommentedText = null;
    List<String> tags = new ArrayList<>();
    if (cleanText.startsWith("//")) {
      uncommentedText = text.substring(text.indexOf('\n') + 1, text.length());
      String propsString = cleanText.substring(2, cleanText.indexOf('\n')).trim();
      String[] split = propsString.split(",");
      for (String s : split) {
        tags.add(s.trim());
      }
      for (String tag : tags) {
        if (!tag.contains("/")) {
          ResourceTags.valueOf(tag);
        }
      }
    }
//    if (tags.contains(ResourceTags.JAVA.name()) && JavaClassFile.isJavaClass(cleanText)) {
//      return new JavaClassFile(text);
//    } else if (tags.contains(ResourceTags.JAVA.name()) && JavaInterfaceFile.isJavaInterface(cleanText)) {
//      return new JavaInterfaceFile(text);
//    } else if (tags.contains(ResourceTags.JAVA.name()) && JavaEnumFile.isEnum(cleanText)) {
//      return new JavaEnumFile(text);
//    } else if (GosuAnnotationFile.isGosuAnnotation(cleanText)) {
//      return new GosuAnnotationFile(text);
//    } else
    if (GosuClassFile.isClass(cleanText)) {
      return new GosuClassFile(text);
//    } else if (GosuInterfaceFile.isInterface(cleanText)) {
//      return new GosuInterfaceFile(text);
//    } else if (GosuEnumFile.isEnum(cleanText)) {
//      return new GosuEnumFile(text);
//    } else if (GosuEnhancementFile.isEnhancement(cleanText)) {
//      return new GosuEnhancementFile(text);
//    } else if (tags.contains(ResourceTags.PROGRAM.name())) {
//      tags.remove(ResourceTags.PROGRAM.name());
//      return new GosuProgramFile(tags.single() + ".gsp", uncommentedText);
//    } else if (tags.contains(ResourceTags.TEMPLATE.name())) {
//      tags.remove(ResourceTags.TEMPLATE.name());
//      return new GosuTemplateFile(tags.single() + ".gst", uncommentedText);
//    } else if (JavaAnnotationFile.isJavaAnnotation(cleanText)) {
//      return new JavaAnnotationFile(text);
    } else {
      throw new RuntimeException("Cannot derive resource type from text: " + text);
    }
  }

  static PsiFile createFile(GosuTestCase test, String text) {
    GosuTestingResource resource = create(text);
    return test.configureByText(resource.fileName, resource.content);
  }

  static PsiFile createFile(GosuTestCase test, String module, String text) {
    GosuTestingResource resource = create(text);
    return test.configureByText(module, resource.fileName, resource.content);
  }

}


text:
package all

import (
	//Blank imports for plugins to register themselves
	_ "github.com/influxdata/telegraf/plugins/outputs/amon"
	_ "github.com/influxdata/telegraf/plugins/outputs/amqp"
	_ "github.com/influxdata/telegraf/plugins/outputs/application_insights"
	_ "github.com/influxdata/telegraf/plugins/outputs/azure_data_explorer"
	_ "github.com/influxdata/telegraf/plugins/outputs/azure_monitor"
	_ "github.com/influxdata/telegraf/plugins/outputs/bigquery"
	_ "github.com/influxdata/telegraf/plugins/outputs/cloud_pubsub"
	_ "github.com/influxdata/telegraf/plugins/outputs/cloudwatch"
	_ "github.com/influxdata/telegraf/plugins/outputs/cloudwatch_logs"
	_ "github.com/influxdata/telegraf/plugins/outputs/cratedb"
	_ "github.com/influxdata/telegraf/plugins/outputs/datadog"
	_ "github.com/influxdata/telegraf/plugins/outputs/discard"
	_ "github.com/influxdata/telegraf/plugins/outputs/dynatrace"
	_ "github.com/influxdata/telegraf/plugins/outputs/elasticsearch"
	_ "github.com/influxdata/telegraf/plugins/outputs/event_hubs"
	_ "github.com/influxdata/telegraf/plugins/outputs/exec"
	_ "github.com/influxdata/telegraf/plugins/outputs/execd"
	_ "github.com/influxdata/telegraf/plugins/outputs/file"
	_ "github.com/influxdata/telegraf/plugins/outputs/graphite"
	_ "github.com/influxdata/telegraf/plugins/outputs/graylog"
	_ "github.com/influxdata/telegraf/plugins/outputs/groundwork"
	_ "github.com/influxdata/telegraf/plugins/outputs/health"
	_ "github.com/influxdata/telegraf/plugins/outputs/http"
	_ "github.com/influxdata/telegraf/plugins/outputs/influxdb"
	_ "github.com/influxdata/telegraf/plugins/outputs/influxdb_v2"
	_ "github.com/influxdata/telegraf/plugins/outputs/instrumental"
	_ "github.com/influxdata/telegraf/plugins/outputs/kafka"
	_ "github.com/influxdata/telegraf/plugins/outputs/kinesis"
	_ "github.com/influxdata/telegraf/plugins/outputs/librato"
	_ "github.com/influxdata/telegraf/plugins/outputs/logzio"
	_ "github.com/influxdata/telegraf/plugins/outputs/loki"
	_ "github.com/influxdata/telegraf/plugins/outputs/mongodb"
	_ "github.com/influxdata/telegraf/plugins/outputs/mqtt"
	_ "github.com/influxdata/telegraf/plugins/outputs/nats"
	_ "github.com/influxdata/telegraf/plugins/outputs/newrelic"
	_ "github.com/influxdata/telegraf/plugins/outputs/nsq"
	_ "github.com/influxdata/telegraf/plugins/outputs/opentelemetry"
	_ "github.com/influxdata/telegraf/plugins/outputs/opentsdb"
	_ "github.com/influxdata/telegraf/plugins/outputs/prometheus_client"
	_ "github.com/influxdata/telegraf/plugins/outputs/riemann"
	_ "github.com/influxdata/telegraf/plugins/outputs/riemann_legacy"
	_ "github.com/influxdata/telegraf/plugins/outputs/sensu"
	_ "github.com/influxdata/telegraf/plugins/outputs/signalfx"
	_ "github.com/influxdata/telegraf/plugins/outputs/socket_writer"
	_ "github.com/influxdata/telegraf/plugins/outputs/sql"
	_ "github.com/influxdata/telegraf/plugins/outputs/stackdriver"
	_ "github.com/influxdata/telegraf/plugins/outputs/sumologic"
	_ "github.com/influxdata/telegraf/plugins/outputs/syslog"
	_ "github.com/influxdata/telegraf/plugins/outputs/timestream"
	_ "github.com/influxdata/telegraf/plugins/outputs/warp10"
	_ "github.com/influxdata/telegraf/plugins/outputs/wavefront"
	_ "github.com/influxdata/telegraf/plugins/outputs/websocket"
	_ "github.com/influxdata/telegraf/plugins/outputs/yandex_cloud_monitoring"

	// D2L imports
	_ "github.com/influxdata/telegraf/plugins/outputs/d2l_kinesis"
)


text:
#include "stdafx.h"

#include "module_version.h"
#include <zorbatypes/URI.h>

namespace zorba {

/**
 * Utility function: Given a string aStr and position aPos, populate
 * aInt with the integer at that position in the string. aPos will be
 * updated to next character.
 * @return true if an integer found, false if not.
 */
static bool
getInteger(zstring const& aStr, size_t& aPos, int& aInt)
{
  char lChar;
  size_t lLen = aStr.length();
  size_t const lOrigPos = aPos;

  aInt = 0;
  while (aPos < lLen && isdigit(lChar = aStr[aPos])) {
    aInt = aInt * 10 + (lChar - '0');
    aPos++;
  }
  return (aPos != lOrigPos);
}

ModuleVersion::ModuleVersion(zstring const& aUri)
  : theMinMajor(0),
    theMaxMajor(1000000),
    theMinMinor(0),
    theMinPatch(0),
    theIsExact(false),
    theValidVersion(false),
    theNamespaceURI(aUri),
    theVersionedURI(aUri)
{
  URI lUri(aUri);

  // Check for fragment in URI; if none, no versioning to be attempted.
  zstring const lFrag = lUri.get_encoded_fragment();
  if (lFrag == "") {
    return;
  }

  if (initValues(lFrag)) {
    lUri.clear_fragment();
    theNamespaceURI = lUri.toString();
  }
}

ModuleVersion::ModuleVersion(zstring const& aUri, zstring const& aVersionDef)
  : theMinMajor(0),
    theMaxMajor(1000000),
    theMinMinor(0),
    theMinPatch(0),
    theIsExact(false),
    theValidVersion(false),
    theNamespaceURI(aUri),
    theVersionedURI(aUri)
{
  if (initValues(aVersionDef)) {
    // "cons up" a fully-versioned URI
    theVersionedURI.append("#");
    theVersionedURI.append(aVersionDef);
  }
}

bool
ModuleVersion::initValues(zstring const& aVersionDef)
{
  // Parse fragment for legal version specification. If any illegal
  // characters found, no versioning to be attempted.
  int lMajor, lMinor, lPatch = 0, lMajorB = -1;
  bool lExact = false;
  size_t lPos = 0;
  size_t lLen = aVersionDef.length();
  if (!getInteger(aVersionDef, lPos, lMajor)) {
    return false;
  }
  if (lPos >= lLen) {
    return false;
  }
  if (aVersionDef[lPos++] != '.') {
    return false;
  }
  if (!getInteger(aVersionDef, lPos, lMinor)) {
    return false;
  }
  if (lPos < lLen && aVersionDef[lPos] == '.') {
    // There's (potentially) a patch version specified as well
    lPos ++;
    if (lPos >= lLen) {
      return false;
    }
    if (!getInteger(aVersionDef, lPos, lPatch)) {
      return false;
    }
  }
  if (lPos < lLen) {
    // Found legal major.minor, but there's more to parse - could be "!"
    // or "-major.0"
    char lChar = aVersionDef[lPos++];
    if (lChar == '!' && lPos == lLen) {
      lExact = true;
    }
    else if (lChar == '-') {
      if (!getInteger(aVersionDef, lPos, lMajorB)) {
        return false;
      }
      if (lPos >= lLen || aVersionDef[lPos++] != '.') {
        return false;
      }
      if (lPos >= lLen || aVersionDef[lPos++] != '0') {
        return false;
      }
    }
    else {
      return false;
    }
  }

  // Verify there's no more to read.
  if (lPos != lLen) {
    return false;
  }

  // Ok, we successfully parsed a version definition; set all our variables.
  theMinMajor = lMajor;
  theMinMinor = lMinor;
  theMinPatch = lPatch;
  theMaxMajor = lMajorB == -1 ? lMajor : lMajorB;
  theIsExact = lExact;
  theValidVersion = true;
  return true;
}

bool
ModuleVersion::satisfies(const ModuleVersion &aOther) const
{
  // 1. The namespace URIs must be equal.
  if (theNamespaceURI != aOther.namespace_uri()) {
    return false;
  }

  // 4. If the given ModuleVersion is "exact", then this ModuleVersion must
  // have exactly the same min_major, max_major, and min_minor. If the given
  // ModuleVersion has a non-zero min_patch, then this ModuleVersion must also
  // have exactly the same min_patch.
  if (aOther.is_exact()) {
    int const lOtherMinPatch = aOther.min_patch();
    return (theMinMajor == aOther.min_major() &&
            theMaxMajor == aOther.max_major() &&
            theMinMinor == aOther.min_minor() &&
            (lOtherMinPatch == 0 || theMinPatch == lOtherMinPatch));
  }

  // 2. The minimum major version of this ModuleVersion must be in the range
  // [min_major, max_major] of the given ModuleVersion.
  if (theMinMajor < aOther.min_major() || theMinMajor > aOther.max_major()) {
    return false;
  }

  // 3. If the minimum major of this ModuleVersion is equal to the given
  // ModuleVersion's min_major, then the minimum minor version of this
  // ModuleVersion must be in the range [min_minor, infinity).
  if (theMinMajor == aOther.min_major() && theMinMinor < aOther.min_minor()) {
    return false;
  }

  return true;
}

} // namespace zorba
/* vim:set et sw=2 ts=2: */


text:
<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

/*
| Route EventoController
*/

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => ['web']], function () {
  Route::get('/', function () {
    return view('/pages/pre-home/home');
  });
  /*
  | Route UsuarioController
  */
  Route::get('/informacion', ['middleware' => 'auth','uses'=>'UsuarioController@showUser']);
  Route::post('/informacion',['middleware' => 'auth','uses' => 'UsuarioController@edit']);
  Route::post('/informacion/eliminar',['middleware' => 'auth','uses' => 'UsuarioController@delete']);
  Route::get('/historial', ['middleware' => 'auth','uses'=>'UsuarioController@historial']);
  // route to logout an user
  Route::get('/logout', ['middleware' => 'auth','uses'=>'UsuarioController@doLogout']);
  // route to show home for the username
  // route to show the login form
  Route::get('/signin',['middleware' => 'guest','uses' => 'UsuarioController@showLogin']);
  // route to process the form
  Route::post('/signin',['uses' => 'UsuarioController@doLogin']);
  // route to show the register form
  Route::resource('/register','UsuarioController');
  Route::post('/home/{currentUser}',['middleware' => 'auth','uses'=>'EventoController@store']);
  Route::get('/home/{currentUser}',['middleware' => 'auth','uses' => 'UsuarioController@showHome']);
  Route::post('/home/{currentUser}/busqueda',['middleware' => 'auth','uses' => 'UsuarioController@filterEvent']);

  Route::post('/home/{currentUser}/colaborando/busqueda',['middleware' => 'auth','uses' => 'UsuarioController@filterEventColaborador']);
  Route::get('/home/{currentUser}/colaborando',['middleware' => 'auth','uses'=>'UsuarioController@showCollaborations']);

  Route::get('/home/{currentUser}/evento/{currentEvent}',['middleware' => 'auth','uses' => 'EventoController@showEvent']);
  Route::post('/home/{currentUser}/evento/{currentEvent}',['middleware' => 'auth','uses'=>'EventoController@edit']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/eliminar',['middleware' => 'auth','uses' => 'EventoController@delete']);
  Route::get('/home/{currentUser}/evento/{currentEvent}/cotizaciones',['middleware' => 'auth','uses' => 'EventoController@cotizaciones']);
  Route::get('/home/{currentUser}/evento/{currentEvent}/colaboradores',['middleware' => 'auth','uses' => 'EventoController@colaboradores']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/colaboradores/añadir',['middleware' => 'auth','uses' => 'EventoController@addCollaborator']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/colaboradores/eliminar',['middleware' => 'auth','uses' => 'EventoController@deleteCollaborator']);
  Route::get('/home/{currentUser}/evento/{currentEvent}/toDo',['middleware' => 'auth','uses' => 'ToDoController@ShowToDo']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/toDo/añadir',['middleware' => 'auth','uses' => 'ToDoController@store']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/toDo/eliminar',['middleware' => 'auth','uses' => 'ToDoController@delete']);
  Route::post('/home/{currentUser}/evento/{currentEvent}/toDo/modificar',['middleware' => 'auth','uses' => 'ToDoController@edit']);

  Route::get('/evento/{currentEvent}/drag',['middleware' => 'auth','uses' => 'ObjetoController@consultarPlano']);

  Route::get('/evento/{currentEvent}/invitados',['middleware' => 'auth','uses' => 'InvitadoController@showInvitados']);
  Route::post('/evento/{currentEvent}/invitados',['middleware' => 'auth','uses' => 'InvitadoController@store']);
  Route::post('/evento/{currentEvent}/invitados/eliminar',['middleware' => 'auth','uses' => 'InvitadoController@delete']);
  Route::post('/evento/{currentEvent}/invitados/busqueda',['middleware' => 'auth','uses' => 'InvitadoController@filterInvitado']);
  Route::get('/evento/{currentEvent}/invitado/{email}',['middleware' => 'guest','uses' => 'InvitadoController@confirmInvitation']);
  Route::get('/evento/{currentEvent}/carrito_compras',['middleware' => 'auth','uses' => 'CategoriaController@showCarritoCompras']);
  Route::post('/evento/{currentEvent}/carrito_compras/eliminar',['middleware' => 'auth','uses' => 'CategoriaController@deleteCarrito']);
  Route::post('/evento/{currentEvent}/carrito_compras/{idCategoria}/agregar',['middleware' => 'auth','uses' => 'CategoriaController@addCarrito']);
  Route::get('/evento/{currentEvent}/cotizaciones',['middleware' => 'auth','uses' => 'CategoriaController@showCotizacion']);
  Route::post('/evento/{currentEvent}/cotizaciones/eliminar',['middleware' => 'auth','uses' => 'CategoriaController@deleteCotizacion']);
  Route::get('/evento/{currentEvent}/proveedores/{idCategoria}',['middleware' => 'auth','uses' => 'CategoriaController@showAddSupppliers']);
  Route::post('/evento/{currentEvent}/proveedores/{idCategoria}/agregar',['middleware' => 'auth','uses' => 'CategoriaController@addSuppplier']);
});


text:
@interface JCHATUpdatePasswordCtl : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *pressBtn;
@property (weak, nonatomic) IBOutlet UITextField *oldpassword;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UITextField *passwordFieldAgain;
@property (weak, nonatomic) IBOutlet UILabel *separateLine1;

@property (weak, nonatomic) IBOutlet UILabel *separateLine2;
@property (weak, nonatomic) IBOutlet UILabel *separateLine3;

@end


text:
package DDG::Spice::BrainyQuote;
# ABSTRACT: Return famous quotations

use strict;
use DDG::Spice;

primary_example_queries "John Kennedy quotes", "Brad Pitt quotations";
secondary_example_queries "quotes about motivation";
description "Provides quotations on and about given topics";
name "Quotations";
code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/BrainyQuote.pm";
icon_url "http://brainyquote.com/favicon.ico";
topics "everyday", "trivia";
category "reference";
source "BrainyQuote.com";
attribution web => ['http://www.brainyquote.com','BrainyQuote.com'];

triggers startend => 'quote', 'quotes', 'quotation', 'quotations';

spice to => 'http://www.brainyquote.com/api/ddg?q=$1';
spice wrap_jsonp_callback => 1;

handle remainder => sub {
    # Convert queries such as J.R.R. Tolkien to J. R. R. Tolkien.
    # We're doing this because the first one is rejected by BrainyQuote.
    if(/^\w\.\w/) {
        s/\./\. /g;
    }

    # Avoid triggering on 'stock' quotes; these are handled by Stocks IA
    if ($req->query_lc =~ m/stock quote/) {
       return;
    }

    return $_ if $_;
    return;
};

1;


text:
<?xml version='1.0' encoding='UTF-8'?>
<slave>
  <name>Foo</name>
  <description></description>
  <remoteFS>/myfs/jenkins/agent</remoteFS>
  <numExecutors>1</numExecutors>
  <mode>NORMAL</mode>
  <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/>
  <launcher class="hudson.slaves.JNLPLauncher">
    <!-- No WorkDir settings  -->
  </launcher>
  <label>foo bar</label>
  <nodeProperties/>
</slave>


text:
/* create users table */
CREATE TABLE users (
  username      VARCHAR(128) NOT NULL PRIMARY KEY,
  email         VARCHAR(128) NOT NULL,
  password      VARCHAR(128) NOT NULL,  /* in plain text */
  role          INTEGER NOT NULL,       /* 0: normal user, 1: administrator */
  first_name    VARCHAR(128),
  last_name     VARCHAR(128)
);


text:
/*********************************************************************/
/* Copyright 2009, 2010 The University of Texas at Austin.           */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. Redistributions in binary form must reproduce the above      */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer in the documentation and/or other materials       */
/*      provided with the distribution.                              */
/*                                                                   */
/*    THIS  SOFTWARE IS PROVIDED  BY THE  UNIVERSITY OF  TEXAS AT    */
/*    AUSTIN  ``AS IS''  AND ANY  EXPRESS OR  IMPLIED WARRANTIES,    */
/*    INCLUDING, BUT  NOT LIMITED  TO, THE IMPLIED  WARRANTIES OF    */
/*    MERCHANTABILITY  AND FITNESS FOR  A PARTICULAR  PURPOSE ARE    */
/*    DISCLAIMED.  IN  NO EVENT SHALL THE UNIVERSITY  OF TEXAS AT    */
/*    AUSTIN OR CONTRIBUTORS BE  LIABLE FOR ANY DIRECT, INDIRECT,    */
/*    INCIDENTAL,  SPECIAL, EXEMPLARY,  OR  CONSEQUENTIAL DAMAGES    */
/*    (INCLUDING, BUT  NOT LIMITED TO,  PROCUREMENT OF SUBSTITUTE    */
/*    GOODS  OR  SERVICES; LOSS  OF  USE,  DATA,  OR PROFITS;  OR    */
/*    BUSINESS INTERRUPTION) HOWEVER CAUSED  AND ON ANY THEORY OF    */
/*    LIABILITY, WHETHER  IN CONTRACT, STRICT  LIABILITY, OR TORT    */
/*    (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY WAY OUT    */
/*    OF  THE  USE OF  THIS  SOFTWARE,  EVEN  IF ADVISED  OF  THE    */
/*    POSSIBILITY OF SUCH DAMAGE.                                    */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of The University of Texas at Austin.                 */
/*********************************************************************/

#include <stdio.h>
#include "common.h"
#ifdef FUNCTION_PROFILE
#include "functable.h"
#endif

#ifndef CBLAS

void NAME(blasint *N, FLOAT *x, blasint *INCX, FLOAT *y, blasint *INCY){

  BLASLONG n    = *N;
  BLASLONG incx = *INCX;
  BLASLONG incy = *INCY;

  PRINT_DEBUG_NAME;

#else

void CNAME(blasint n, FLOAT *x, blasint incx, FLOAT *y, blasint incy){

  PRINT_DEBUG_CNAME;

#endif

  if (n <= 0) return;

  IDEBUG_START;

  FUNCTION_PROFILE_START();

  if (incx < 0) x -= (n - 1) * incx * COMPSIZE;
  if (incy < 0) y -= (n - 1) * incy * COMPSIZE;

  COPY_K(n, x, incx, y, incy);

  FUNCTION_PROFILE_END(COMPSIZE, COMPSIZE * n, 0);

  IDEBUG_END;

  return;

}


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

<title>StreamScope (Edgent v1.0.0)</title>
<meta name="date" content="2016-11-19">
<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 Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.edgent.streamscope

Class StreamScope<T>

java.lang.Object

org.apache.edgent.streamscope.StreamScope<T>

Type Parameters:

T - Tuple type

All Implemented Interfaces:

java.io.Serializable, Consumer<T>

public class StreamScope<T>
extends java.lang.Object
implements Consumer<T>

A Stream "oscilloscope" for capturing stream tuples for analysis / debug.

 A StreamScope is expected to be used as parameter to
 StreamScope oplet.

 A StreamScope.TriggerManager controls which tuples are captured.
 A StreamScope.BufferManager controls the retention policy for captured tuples.

 A StreamScope.Sample is created for each captured tuple containing the tuple
 (not copied) and capture timestamps.  Samples are retrieved using getSamples().

 Sample capture can be enabled/disabled (setEnabled(boolean).
 It is disabled by default.  Capture can also be paused and resumed via
 the TriggerManager.

 StreamScope instances are typically registered in and located via
 a StreamScopeRegistry runtime service
 and StreamScopeRegistryMXBean runtime ControlService.

See Also:

StreamScopeRegistry,
DevelopmentProvider,
Serialized Form

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
StreamScope.BufferManager<T>

Control the retention of captured tuples.

static class
StreamScope.Sample<T>

A captured tuple.

static class
StreamScope.TriggerManager<T>

Control what triggers capturing of tuples.

Constructor Summary

Constructors

Constructor and Description

StreamScope()

Create a new instance.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
accept(T tuple)

Apply the function to value.

StreamScope.BufferManager<T>
bufferMgr()

Get the StreamScope.BufferManager

int
getSampleCount()

Get the number of Samples currently captured

java.util.List<StreamScope.Sample<T>>
getSamples()

Get all captured tuples.

boolean
isEnabled()

Is tuple capture enabled?

void
setEnabled(boolean isEnabled)

Enable or disable tuple capture.

java.lang.String
toString()

StreamScope.TriggerManager<T>
triggerMgr()

Get the StreamScope.TriggerManager

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

StreamScope

public StreamScope()

Create a new instance.

 Sample capture is disabled.

Method Detail

isEnabled

public boolean isEnabled()

Is tuple capture enabled?

Returns:

true if enabled.

setEnabled

public void setEnabled(boolean isEnabled)

Enable or disable tuple capture.

 Disabling releases the capture buffer.

Parameters:

isEnabled - true to enable, false to disable.

bufferMgr

public StreamScope.BufferManager<T> bufferMgr()

Get the StreamScope.BufferManager

Returns:

the manager

triggerMgr

public StreamScope.TriggerManager<T> triggerMgr()

Get the StreamScope.TriggerManager

Returns:

the manager

getSamples

public java.util.List<StreamScope.Sample<T>> getSamples()

Get all captured tuples.

 The returned samples are removed from the capture buffer.

Returns:

unmodifiable list of captured samples

getSampleCount

public int getSampleCount()

Get the number of Samples currently captured

Returns:

the count

accept

public void accept(T tuple)

Description copied from interface: Consumer

Apply the function to value.

Specified by:

accept in interface Consumer<T>

Parameters:

tuple - Value function is applied to.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Apache Edgent (incubating)

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation. All Rights Reserved - 73539fa-20161119-2136


text:
<?php

/* NelmioApiDocBundle::layout.html.twig */
class __TwigTemplate_f7341e2eb44c777a63467c91ae788d064d02ced079beb601fe4af230763f39f1 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'content' => array($this, 'block_content'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_5d8b486fc798c861b6fb60f1aad7e21a6b9052a66b7b508bc41229b0b3d9a329 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_5d8b486fc798c861b6fb60f1aad7e21a6b9052a66b7b508bc41229b0b3d9a329->enter($__internal_5d8b486fc798c861b6fb60f1aad7e21a6b9052a66b7b508bc41229b0b3d9a329_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NelmioApiDocBundle::layout.html.twig"));

        $__internal_98306619790a4833d1f906d0d28c1785b2ae0f9b191b671b204a94adfe988fe6 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_98306619790a4833d1f906d0d28c1785b2ae0f9b191b671b204a94adfe988fe6->enter($__internal_98306619790a4833d1f906d0d28c1785b2ae0f9b191b671b204a94adfe988fe6_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NelmioApiDocBundle::layout.html.twig"));

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

        <meta charset=\"utf-8\" />

        <meta content=\"IE=edge,chrome=1\" http-equiv=\"X-UA-Compatible\" />
        <title>";
        // line 7
        echo twig_escape_filter($this->env, (isset($context["apiName"]) ? $context["apiName"] : $this->getContext($context, "apiName")), "html", null, true);
        echo "</title>

            env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("nelmio_api_doc_index");
        echo "\">
";
        echo twig_escape_filter($this->env, (isset($context["apiName"]) ? $context["apiName"] : $this->getContext($context, "apiName")), "html", null, true);
        echo "

            ";
        // line 18
        if ((isset($context["enableSandbox"]) ? $context["enableSandbox"] : $this->getContext($context, "enableSandbox"))) {
            // line 19
            echo "

                    ";
            // line 20
            if ((twig_length_filter($this->env, (isset($context["bodyFormats"]) ? $context["bodyFormats"] : $this->getContext($context, "bodyFormats"))) > 0)) {
                // line 21
                echo "                    body format:
                    <select id=\"body_format\">
                        ";
                // line 23
                if (twig_in_filter("form", (isset($context["bodyFormats"]) ? $context["bodyFormats"] : $this->getContext($context, "bodyFormats")))) {
                    echo "<option value=\"form\"";
                    echo ((((isset($context["defaultBodyFormat"]) ? $context["defaultBodyFormat"] : $this->getContext($context, "defaultBodyFormat")) == "form")) ? (" selected") : (""));
                    echo ">Form Data</option>";
                }
                // line 24
                echo "                        ";
                if (twig_in_filter("json", (isset($context["bodyFormats"]) ? $context["bodyFormats"] : $this->getContext($context, "bodyFormats")))) {
                    echo "<option value=\"json\"";
                    echo ((((isset($context["defaultBodyFormat"]) ? $context["defaultBodyFormat"] : $this->getContext($context, "defaultBodyFormat")) == "json")) ? (" selected") : (""));
                    echo ">JSON</option>";
                }
                // line 25
                echo "                    </select>
                    ";
            }
            // line 27
            echo "                    ";
            if ((twig_length_filter($this->env, (isset($context["requestFormats"]) ? $context["requestFormats"] : $this->getContext($context, "requestFormats"))) > 0)) {
                // line 28
                echo "                    request format:
                    <select id=\"request_format\">
                    ";
                // line 30
                $context['_parent'] = $context;
                $context['_seq'] = twig_ensure_traversable((isset($context["requestFormats"]) ? $context["requestFormats"] : $this->getContext($context, "requestFormats")));
                foreach ($context['_seq'] as $context["format"] => $context["header"]) {
                    // line 31
                    echo "                        <option value=\"";
                    echo twig_escape_filter($this->env, $context["header"], "html", null, true);
                    echo "\"";
                    echo ((((isset($context["defaultRequestFormat"]) ? $context["defaultRequestFormat"] : $this->getContext($context, "defaultRequestFormat")) == $context["format"])) ? (" selected") : (""));
                    echo ">";
                    echo twig_escape_filter($this->env, $context["format"], "html", null, true);
                    echo "</option>
                    ";
                }
                $_parent = $context['_parent'];
                unset($context['_seq'], $context['_iterated'], $context['format'], $context['header'], $context['_parent'], $context['loop']);
                $context = array_intersect_key($context, $_parent) + $_parent;
                // line 33
                echo "                    ";
            }
            // line 34
            echo "                    </select>
                    ";
            // line 35
            if ((isset($context["authentication"]) ? $context["authentication"] : $this->getContext($context, "authentication"))) {
                // line 36
                echo "                        ";
                if ((($this->getAttribute((isset($context["authentication"]) ? $context["authentication"] : $this->getContext($context, "authentication")), "delivery", array()) == "http") && ($this->getAttribute((isset($context["authentication"]) ? $context["authentication"] : $this->getContext($context, "authentication")), "type", array()) == "basic"))) {
                    // line 37
                    echo "                            api login: <input type=\"text\" id=\"api_login\" value=\"\"/>
                            api password: <input type=\"text\" id=\"api_pass\" value=\"\"/>
                        ";
                } elseif (twig_in_filter($this->getAttribute(                // line 39
(isset($context["authentication"]) ? $context["authentication"] : $this->getContext($context, "authentication")), "delivery", array()), array(0 => "query", 1 => "http", 2 => "header"))) {
                    // line 40
                    echo "                            api key: <input type=\"text\" id=\"api_key\" value=\"\"/>
                        ";
                }
                // line 42
                echo "
                        ";
                // line 43
                if ($this->getAttribute((isset($context["authentication"]) ? $context["authentication"] : $this->getContext($context, "authentication")), "custom_endpoint", array())) {
                    // line 44
                    echo "                            api endpoint: <input type=\"text\" id=\"api_endpoint\" value=\"\"/>
                        ";
                }
                // line 46
                echo "                        <button id=\"save_api_auth\" type=\"button\">Save</button>
                        <button id=\"clear_api_auth\" type=\"button\">Clear</button>
                    ";
            }
            // line 49
            echo "

            ";
        }
        // line 51
        echo "

        ";
        // line 53
        $this->loadTemplate((isset($context["motdTemplate"]) ? $context["motdTemplate"] : $this->getContext($context, "motdTemplate")), "NelmioApiDocBundle::layout.html.twig", 53)->display($context);
        // line 54
        echo "

                ";
        // line 56
        $this->displayBlock('content', $context, $blocks);
        // line 57
        echo "

            Documentation auto-generated on ";
        // line 60
        echo twig_escape_filter($this->env, (isset($context["date"]) ? $context["date"] : $this->getContext($context, "date")), "html", null, true);
        echo "

";

        $__internal_5d8b486fc798c861b6fb60f1aad7e21a6b9052a66b7b508bc41229b0b3d9a329->leave($__internal_5d8b486fc798c861b6fb60f1aad7e21a6b9052a66b7b508bc41229b0b3d9a329_prof);

        $__internal_98306619790a4833d1f906d0d28c1785b2ae0f9b191b671b204a94adfe988fe6->leave($__internal_98306619790a4833d1f906d0d28c1785b2ae0f9b191b671b204a94adfe988fe6_prof);

    }

    // line 56
    public function block_content($context, array $blocks = array())
    {
        $__internal_798996e9ac826d604f463b3e29b6aa6f13806a73bc79b5a4a10b522e1437e09b = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_798996e9ac826d604f463b3e29b6aa6f13806a73bc79b5a4a10b522e1437e09b->enter($__internal_798996e9ac826d604f463b3e29b6aa6f13806a73bc79b5a4a10b522e1437e09b_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "content"));

        $__internal_56e3bef878789ed04a23fb14211c3119cda03f761a37f360833774845d3733b8 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_56e3bef878789ed04a23fb14211c3119cda03f761a37f360833774845d3733b8->enter($__internal_56e3bef878789ed04a23fb14211c3119cda03f761a37f360833774845d3733b8_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "content"));

        $__internal_56e3bef878789ed04a23fb14211c3119cda03f761a37f360833774845d3733b8->leave($__internal_56e3bef878789ed04a23fb14211c3119cda03f761a37f360833774845d3733b8_prof);

        $__internal_798996e9ac826d604f463b3e29b6aa6f13806a73bc79b5a4a10b522e1437e09b->leave($__internal_798996e9ac826d604f463b3e29b6aa6f13806a73bc79b5a4a10b522e1437e09b_prof);

    }

    public function getTemplateName()
    {
        return "NelmioApiDocBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  999 => 56,  986 => 817,  983 => 816,  979 => 814,  974 => 812,  969 => 811,  967 => 810,  951 => 797,  946 => 796,  944 => 795,  940 => 794,  936 => 793,  931 => 792,  929 => 791,  740 => 604,  734 => 600,  732 => 599,  726 => 597,  720 => 595,  718 => 594,  584 => 463,  572 => 454,  267 => 151,  265 => 150,  218 => 105,  214 => 103,  212 => 102,  167 => 60,  162 => 57,  160 => 56,  156 => 54,  154 => 53,  150 => 51,  146 => 49,  141 => 46,  137 => 44,  135 => 43,  132 => 42,  128 => 40,  126 => 39,  122 => 37,  119 => 36,  117 => 35,  114 => 34,  111 => 33,  98 => 31,  94 => 30,  90 => 28,  87 => 27,  83 => 25,  76 => 24,  70 => 23,  66 => 21,  64 => 20,  61 => 19,  59 => 18,  53 => 17,  45 => 12,  39 => 9,  34 => 7,  26 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">

        <meta charset=\"utf-8\" />

        <meta content=\"IE=edge,chrome=1\" http-equiv=\"X-UA-Compatible\" />
        <title>{{ apiName }}</title>

{{ apiName }}

            {% if enableSandbox %}

                    {% if bodyFormats|length > 0 %}
                    body format:
                    <select id=\"body_format\">
                        {% if 'form' in bodyFormats %}<option value=\"form\"{{ defaultBodyFormat == 'form' ? ' selected' : '' }}>Form Data</option>{% endif %}
                        {% if 'json' in bodyFormats %}<option value=\"json\"{{ defaultBodyFormat == 'json' ? ' selected' : '' }}>JSON</option>{% endif %}
                    </select>
                    {% endif %}
                    {% if requestFormats|length > 0 %}
                    request format:
                    <select id=\"request_format\">
                    {% for format, header in requestFormats %}
                        <option value=\"{{ header }}\"{{ defaultRequestFormat == format ? ' selected' : '' }}>{{ format }}</option>
                    {% endfor %}
                    {% endif %}
                    </select>
                    {% if authentication %}
                        {% if authentication.delivery == 'http' and authentication.type == 'basic' %}
                            api login: <input type=\"text\" id=\"api_login\" value=\"\"/>
                            api password: <input type=\"text\" id=\"api_pass\" value=\"\"/>
                        {% elseif authentication.delivery in ['query', 'http', 'header'] %}
                            api key: <input type=\"text\" id=\"api_key\" value=\"\"/>
                        {% endif %}

                        {% if authentication.custom_endpoint %}
                            api endpoint: <input type=\"text\" id=\"api_endpoint\" value=\"\"/>
                        {% endif %}
                        <button id=\"save_api_auth\" type=\"button\">Save</button>
                        <button id=\"clear_api_auth\" type=\"button\">Clear</button>
                    {% endif %}

            {% endif %}

        {% include motdTemplate %}

                {% block content %}{% endblock %}

            Documentation auto-generated on {{ date }}

", "NelmioApiDocBundle::layout.html.twig", "C:\\xampp\\symfonyprojects\\symfony_api_project\\vendor\\nelmio\\api-doc-bundle\\Nelmio\\ApiDocBundle/Resources/views/layout.html.twig");
    }
}


text:
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
//   Tool : Bond Compiler 3.02
//   File : CrashData_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------

#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion

namespace Microsoft.HockeyApp.Extensibility.Implementation.External
{
    using System.Collections.Generic;

    [System.CodeDom.Compiler.GeneratedCode("gbc", "3.02")]
    internal partial class CrashDataThread
    {

        public int id { get; set; }

        public IList<CrashDataThreadFrame> frames { get; set; }

        public CrashDataThread()
            : this("AI.CrashDataThread", "CrashDataThread")
        {}

        protected CrashDataThread(string fullName, string name)
        {
            id = 0;
            frames = new List<CrashDataThreadFrame>();
        }
    }
} // AI


text:
use clean::*;
use std::iter::Extend;
use std::mem::{replace, swap};

pub trait DocFolder : Sized {
    fn fold_item(&mut self, item: Item) -> Option<Item> {
        self.fold_item_recur(item)
    }

    /// don't override!
    fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
        let Item { attrs, name, source, visibility, def_id, inner, stability } = item;
        let inner = inner;
        let inner = match inner {
            StructItem(mut i) => {
                let mut foo = Vec::new(); swap(&mut foo, &mut i.fields);
                let num_fields = foo.len();
                i.fields.extend(foo.into_iter().filter_map(|x| self.fold_item(x)));
                i.fields_stripped |= num_fields != i.fields.len();
                StructItem(i)
            },
            ModuleItem(i) => {
                ModuleItem(self.fold_mod(i))
            },
            EnumItem(mut i) => {
                let mut foo = Vec::new(); swap(&mut foo, &mut i.variants);
                let num_variants = foo.len();
                i.variants.extend(foo.into_iter().filter_map(|x| self.fold_item(x)));
                i.variants_stripped |= num_variants != i.variants.len();
                EnumItem(i)
            },
            TraitItem(mut i) => {
                let mut foo = Vec::new(); swap(&mut foo, &mut i.items);
                i.items.extend(foo.into_iter().filter_map(|x| self.fold_item(x)));
                TraitItem(i)
            },
            ImplItem(mut i) => {
                let mut foo = Vec::new(); swap(&mut foo, &mut i.items);
                i.items.extend(foo.into_iter().filter_map(|x| self.fold_item(x)));
                ImplItem(i)
            },
            VariantItem(i) => {
                let i2 = i.clone(); // this clone is small
                match i.kind {
                    StructVariant(mut j) => {
                        let mut foo = Vec::new(); swap(&mut foo, &mut j.fields);
                        let num_fields = foo.len();
                        j.fields.extend(foo.into_iter().filter_map(|x| self.fold_item(x)));
                        j.fields_stripped |= num_fields != j.fields.len();
                        VariantItem(Variant {kind: StructVariant(j), ..i2})
                    },
                    _ => VariantItem(i2)
                }
            },
            x => x
        };

        Some(Item { attrs: attrs, name: name, source: source, inner: inner,
                    visibility: visibility, stability: stability, def_id: def_id })
    }

    fn fold_mod(&mut self, m: Module) -> Module {
        Module {
            is_crate: m.is_crate,
            items: m.items.into_iter().filter_map(|i| self.fold_item(i)).collect()
        }
    }

    fn fold_crate(&mut self, mut c: Crate) -> Crate {
        c.module = match replace(&mut c.module, None) {
            Some(module) => self.fold_item(module), None => None
        };
        return c;
    }
}


text:
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Scheduling
{
    using System;

    public interface ScheduledMessage
    {
        Guid TokenId { get; }
        DateTime ScheduledTime { get; }
        Uri Destination { get; }
    }

    public interface ScheduledMessage<out T> :
        ScheduledMessage
        where T : class
    {
        T Payload { get; }
    }
}


text:
import { Tree, TWithLineage } from "lib/treeUtils";

export interface DocRefType {
  uuid: string;
  type: string;
  name?: string;
}

export const copyDocRef = (input: DocRefType): DocRefType => {
  return {
    uuid: input.uuid,
    type: input.type,
    name: input.name,
  };
};

export interface DocRefInfoType {
  docRef: DocRefType;
  createTime: number;
  updateTime: number;
  createUser: string;
  updateUser: string;
  otherInfo: string;
}

export interface DocRefTree extends DocRefType, Tree<DocRefType> {}

export type DocRefWithLineage = TWithLineage<DocRefType>;

export type DocRefConsumer = (d: DocRefType) => void;

export interface DocumentBase<T extends string> {
  uuid: string;
  type: T;
  name?: string;
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>OmniPay - The PHP Library for Payment Gateways</title>

		<meta name="description" content="Payment gateways are hard to integrate. OmniPay helps to make is easier through a more consistent interface.">
		<meta name="author" content="Jason Judge">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

		<link rel="stylesheet" type="text/css" href="lib/css/ri-grid.css" />

OmniPay

The PHP Library for Payment Gateways

							Presentation
							for DrupalCamp North
							/ @DrupalCampNE
							by Jason Judge
							/ @JasonDJudge

							(Background notes are in these slides - press 'S' to see them)

What Are Payment Gateways?

The means to collect payment from a user

The means to authorise payment from a user

The means to collect against authorisation

All through web services

Drupal Payment Gateways

Gateway modules built for projects

Other commerce projects

Much duplication

Inconsistent support of gateways

						* Each of these projects have their own payments framework, modules, and way of
						  working.
						* Inconsistent support: each e-commerce product supports a different set of
						  payment gateways, whatever happened to scratch people's itch at the time.

The Problems to Solve

The gateways are all so different; can we abstract them?

Difficult to switch between gateways

Gateway supplied SDKs are awful

To provide the common services easily
(authorize/void/capture/payment)

						* There are many gateways out there, all operating differently, and with their
						  own quirks. Which you use will depend largely on business needs, so you need
						  to be able to plug in whatever gateway at a technical level.
						* To provide a simple way to add payment gateways to your system,
						  without having to understand too much about the specific gateways.
						* To be able to switch between gateways easily through a consistent interface,
						  especially when your gateway does not yet exist for your particular application.
						* To avoid needing to use the SDKs that gateway providers supply,
						  because most of them suck.
						* Scope: authorize/void/capture/payment – simple shop stuff.

The Drupal Payment Module

Plugable platform for processing payments

Solves the duplication problem:

The gateway modules still need to be written

						* The Drupal Payment module provides some helper functions, GUIs, forms,
						  admin pages etc.
						* Crutially, it knows how to interface to the projects, so the gateway
						  modules do not need to.
						* These payment gateway modules can now be shared between lots of projects.
						* But still these gateway modules need to be written by someone.

Introducing...

OmniPay

Not to be confused with a company with fancy logos in Ireland

OmniPay Basic Architecture

Installed using composer

Core omnipay/common package

Official omnipay/{gateway-name} drivers

Unofficial third party drivers

All drivers built from message specs; no SDKs

						* Unofficial drivers don't sit in the OmniPay namespace.
						* Unofficial drivers are still listed on the OmniPay website.
						* Only pull the drivers you want.
						* composer package `omnipay/omnipay` will pull in all drivers it knows about.

Some Current Figures

Version: 2.3.x

PHP: 5.3+

Official gateways: 27

Unofficial gateways: 25

Dependencies: Guzzle, Symfony

Author: Adrian Macneil, now The PHP League with many contributors

Activity: high

Official Gateways (1)

						* omnipay/2checkout
						* **omnipay/authorizenet**
						* omnipay/buckaroo
						* omnipay/cardsave
						* omnipay/coinbase
						* omnipay/eway
						* omnipay/firstdata
						* omnipay/gocardless
						* omnipay/manual
						* omnipay/migs

Official Gateways (2)

						* omnipay/mollie
						* omnipay/multisafepay
						* omnipay/netaxept
						* omnipay/netbanx
						* omnipay/payfast
						* omnipay/payflow
						* omnipay/paymentexpress
						* omnipay/paypal
						* omnipay/pin
						* **omnipay/sagepay**

Official Gateways (3)

						* omnipay/securepay
						* omnipay/stripe
						* omnipay/targetpay
						* omnipay/worldpay

Unofficial Gateways (1)

						* **academe/omnipay-helcim**
						* agmscode/omnipay-agms
						* alfaproject/omnipay-neteller
						* alfaproject/omnipay-skrill
						* andreas22/omnipay-fasapay
						* andylibrian/omnipay-veritrans
						* cardgate/omnipay-cardgate
						* coatesap/omnipay-datacash
						* coatesap/omnipay-paymentsense
						* coatesap/omnipay-realex

Unofficial Gateways (2)

						* dabsquared/omnipay-cybersource-soap
						* delatbabel/omnipay-fatzebra
						* dercoder/omnipay-ecopayz
						* dercoder/omnipay-globalcloudpay
						* dioscouri/omnipay-cybersource
						* fruitcakestudio/omnipay-sisow
						* igaponov/omnipay-wirecard
						* justinbusschau/omnipay-secpay
						* lokielse/omnipay-alipay
						* mfauveau/omnipay-nmi

Unofficial Gateways (3)

						* mfauveau/omnipay-pacnet
						* omnipay/payu
						* paypronl/omnipay-paypro
						* samvaughton/omnipay-barclays-epdq
						* teaandcode/omnipay-worldpay-xml

That's a Lot of Payment Gateways

						* Having these gateways available does not mean there is not some work involved
						  to integrate it, but it does make the life of the developer easier.
						* Remember, the choice of gateway is often going to be a business decision and
						  not one based on technical reasons.

Composer - a slight diversion

PHP dependency manager.

Installs from a number of sources.

Used in many frameworks and projects.

Shared code; shared effort. DRY!

More central to Drupal 8.

						* The sources include packagist, other composer repositories (one for WordPress,
						  one for Drupal, private respos, git, svn, etc.)
						* There is plenty of work going on to bring composer into Drupal 8.
						* The "island" mentality is hard to discard, but it seems to be shifting.
						* Once you base work around composer, you will find it hard to leave it.

Gateway Architectures

Traditionally:

On-site

User never leaves the site

Server to Serverc comms

High PCI responsibility

Off-site

User leaves the site (maybe only in an iframe)

May use back-end notify channel

						## Onsite
						* These gateway APIs just handle server talking to server.
						  There is no user interaction at all, so any user input must pass
						  through your server before it is passed to the gateway to get a
						  result. Only do this if you have a big budget to cater for the
						  intense PCI scrutiny to get compliance.
						* Note that with 3D Secure and suchlike, the user may still have
						  to be sent to a third-party site to fill out some security details.
						## Offsite
						* The user is taken to the payment gateway to complete their details.
						  On return, the transaction is completed according to the authorisation
						  result. There are variations on this:
						  * The remote site can be in an iframe, so the user appears not to
						    have left the main site.
						  * The result can be sent back via the user's browser, with an
						    encrypted GET parameter.
						  * The result can be sent back via a notification URL. The
						    consequences of this, are that you need to keep the transaction
						    in non-volatile storage that can be shared between the user's
						    session, and the session-less notification handler.
						## Shared
						* In this type of gateway, the payment form is on your site, but the
						  credit card details are never submitted directly to your site.
						  There are two ways this works:
						  * JavaScript API, where the form submission is caught by JavaScript
						    and POSTed direct to the gateway site. The response is either an
						    error message indicating what needs to be corrected on the form,
						    or the result is added to the form and it is then allowed to post
						    direct back to you site (without the credit card details).
						    The user never leaves your site.
						  * The form is POSTed direct to the gateway site. The details are
						    verified and the result is POSTed direct to your site (usually
						    via a back-channel) and the user is then returned back to your
						    site. The user is taken away from your site, but only for a moment,
						    and with no interaction.

Onsite/Offsite is not Helpful

Same thing to application.

Want heavy PCI compliance? Take CC details.

The meanings are blurred - Stripe, Authorize.Net DPM.

OmniPay can handle all these.

						* The application should not care where the user goes - it only needs to
						  know whether the payment has been authorised.
						* If you let credit card details pass *through* your server, then you are
						  putting yourself and your customers at risk.
						* Even offsite you are not risk free.
						* The hybrid gateways offer forms on your site, but CC details are posted
						  direct to the gateway site.
						* Direct posting does not mean your site is totally safe from PCI - some
						  malicious javascript on your site could still capture CC details from
						  your front-end form and send it off to a third party, so not a panacea.

How to Use OmniPay

OmniPay handles the messaging

You handle the routing and data

Some Code Now Follows

Common Use

1. Create the Gateway Object:

					~~~php
					$gateway = OmniPay::create('SagePay\Direct')
						->setVendor('academe')
						->setTestMode(true);
					~~~

All credentials are set at this stage:

					~~~php
						->setAccount('myAccount')
						->setKey('myKey')
						->setSecret('mySecret')
					~~~

Common Use

2. Create the Credit Card/Customer Object:

					~~~php
					$card = new CreditCard([
						'firstName' => 'Jason',
						'lastName' => 'Judge',

						'number' => '4929000000006',
						'expiryMonth' => '12',
						'expiryYear' => '2016',
						'CVV' => '123',

						'billingAddress1' => 'Campus North',
						'billingCity' => 'Newcastle Upon Tyne',
						// ...

						'shippingAddress1' => 'Campus North',
						// ...
					]);
					~~~

Common Use

3. Create the Request Message:

					~~~php
					// Purchase Request
					$requestMessage = $gateway->purchase([
						'amount' => '99.99',
						'currency' => 'GBP',
						'card' => $card,
						'transactionId' => $transactionId,
						'description' => 'Pizzas for everyone',

						'returnUrl' => 'http://example.com/complete',
						'cancelUrl' => 'http://example.com/complete',
						'errorUrl' => 'http://example.com/complete',
					]);
					~~~

Common Use

4. Send the request message:

					~~~php
					$responseMessage = $requestMessage->send();
					~~~

Get a Response message in return.

Handle any exceptions.

Common Use

5. Take next action based on response:

					~~~php
					if ($responseMessage->isSuccessful()) {
						// All finished and all successful.
						// ...
					} elseif ($responseMessage->isRedirect()) {
						// Do the redirect.
						$responseMessage->redirect();
					} else {
						// Some kind of error:
						// Log $responseMessage->getMessage();
						// ...
					}
					~~~

Some gateways may have other required actions.

Common Use

6. If returning from a redirect:

Repeat steps 1-5 with the "complete" version of the service.

					~~~php
					// Use completePurchase() to complete the Purchase.
					$requestMessage = $gateway->completePurchase([
						'transactionId' => $transactionId,
						'transactionReference' => $transactionReference,
					]);

					$responseMessage = $requestMessage->send();

					// Then check the result as before.
					~~~

					Some notes:
					* The messages are active messages; they "send" themselves.
					* Sending a message may or may not involve the remote gateway.
					  For direct gateway APIs it will, for others, often not (but it may).
					* The messages honour a standard interface, so details provided and results
					  received will be done through a common set of methods. Gateway drivers will
					  often extend those interfaces to support features only that gateway has.
					* The messages translate the fields for you, between OmniPay field names
					  and gateway field names.
					* The messages use the appropriate HTTP service of Guzzle to send and receive
					  data in the right format. You don't need to worry about the HTTP body formats.

Integration

					* drupal 8: Omnipay - Bart Feenstra

					* So far all integration has one thing in common: they integrate at a low level,
					  and you have to build all the machinery around that (forms, storage, routing, etc.)

Integration

					* composer: ignited/laravel-omnipay - Alex Whiteside
					* composer: barryvdh/laravel-omnipay - Barry vd. Heuvel

The Ideal Situation

					* The Omnipay module interfaces Drupal Payment, the gateway modules and
					  the composer OmniPay gateway packages.
					* The gateway modules *should* be simple and quick to implement; most of
					  the common handling code is in the Drupal OmniPay and the Drupal Payment
					  modules.

Some Gateway Trends

More "hybrid" options; JavaScript and direct POSTing.

Token-based payments taking off; increasing number of subscription services grow.

					* Stripe popularised the idea that payment gateways can rely on
					  JavaScript to perform the communications, and that can mean the
					  customer not ever having to leave your site. All the major gateways
					  are leaping into this approach. I hear a rumour that even SagePay
					  is going to launch one of these very soon. JavaScript posting makes
					  PCI compliance a little lighter.
					* Token-based APIs are becoming more popular, allowing a site to get
					  authorization to take a payment, or multiple payments, at a later date
					  using a token that does not require the storage of credit card numbers
					  (which we hope no-one is doing anyway).

Coming Up Version 3.0

Planned for end 2015

Improved Documentation; more consistency

Namespace change vendor to League

Remove dependencies: Guzzle and Symfony

PSR-7 HTTP models instead

More classes to handle the data

More metadata to automate plumbing better

					* Maybe more metadata to help automate the plumbing, e.g. defining
					  capabilities in more detail and listing what fields are mandatory
					  or optional, and what validation needs to be applied to them.

Demo Time

Demo: SagePay Direct

Demo: SagePay Direct

One script:

authorise.php

User stays on one site

Authorisation in one step

						The full demo scripts are available at

						https://github.com/academe/OmniPay-SagePay-Demo

Demo: Switch to SagePay Server

Demo: Switch to SagePay Server

Three scripts (for the three steps):

authorise.php

sagepay-confirm.php

final.php

User redirected to SagePay site

Summary

Fragmented Payment Modules are painful

OmniPay pulls in skills from many sources

composer is fab

The core of 50 gateways in our hands

Needs more work to join the pieces

Thank You

Feedback most welcome


text:
<?php
/**
 * WordPress implementation for PHP functions either missing from older PHP versions or not included by default.
 *
 * @package PHP
 * @access private
 */

// If gettext isn't available
if ( !function_exists('_') ) {
	function _($string) {
		return $string;
	}
}

/**
 * Returns whether PCRE/u (PCRE_UTF8 modifier) is available for use.
 *
 * @ignore
 * @since 4.2.2
 * @access private
 *
 * @staticvar string $utf8_pcre
 *
 * @param bool $set - Used for testing only
 *             null   : default - get PCRE/u capability
 *             false  : Used for testing - return false for future calls to this function
 *             'reset': Used for testing - restore default behavior of this function
 */
function _wp_can_use_pcre_u( $set = null ) {
	static $utf8_pcre = 'reset';

	if ( null !== $set ) {
		$utf8_pcre = $set;
	}

	if ( 'reset' === $utf8_pcre ) {
		$utf8_pcre = @preg_match( '/^./u', 'a' );
	}

	return $utf8_pcre;
}

if ( ! function_exists( 'mb_substr' ) ) :
	function mb_substr( $str, $start, $length = null, $encoding = null ) {
		return _mb_substr( $str, $start, $length, $encoding );
	}
endif;

/*
 * Only understands UTF-8 and 8bit.  All other character sets will be treated as 8bit.
 * For $encoding === UTF-8, the $str input is expected to be a valid UTF-8 byte sequence.
 * The behavior of this function for invalid inputs is undefined.
 */
function _mb_substr( $str, $start, $length = null, $encoding = null ) {
	if ( null === $encoding ) {
		$encoding = get_option( 'blog_charset' );
	}

	// The solution below works only for UTF-8,
	// so in case of a different charset just use built-in substr()
	if ( ! in_array( $encoding, array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) ) {
		return is_null( $length ) ? substr( $str, $start ) : substr( $str, $start, $length );
	}

	if ( _wp_can_use_pcre_u() ) {
		// Use the regex unicode support to separate the UTF-8 characters into an array
		preg_match_all( '/./us', $str, $match );
		$chars = is_null( $length ) ? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length );
		return implode( '', $chars );
	}

	$regex = '/(
		  [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
		| [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
		| \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
		| [\xE1-\xEC][\x80-\xBF]{2}
		| \xED[\x80-\x9F][\x80-\xBF]
		| [\xEE-\xEF][\x80-\xBF]{2}
		| \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
		| [\xF1-\xF3][\x80-\xBF]{3}
		| \xF4[\x80-\x8F][\x80-\xBF]{2}
	)/x';

	$chars = array( '' ); // Start with 1 element instead of 0 since the first thing we do is pop
	do {
		// We had some string left over from the last round, but we counted it in that last round.
		array_pop( $chars );

		// Split by UTF-8 character, limit to 1000 characters (last array element will contain the rest of the string)
		$pieces = preg_split( $regex, $str, 1000, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );

		$chars = array_merge( $chars, $pieces );
	} while ( count( $pieces ) > 1 && $str = array_pop( $pieces ) ); // If there's anything left over, repeat the loop.

	return join( '', array_slice( $chars, $start, $length ) );
}

if ( ! function_exists( 'mb_strlen' ) ) :
	function mb_strlen( $str, $encoding = null ) {
		return _mb_strlen( $str, $encoding );
	}
endif;

/*
 * Only understands UTF-8 and 8bit.  All other character sets will be treated as 8bit.
 * For $encoding === UTF-8, the $str input is expected to be a valid UTF-8 byte sequence.
 * The behavior of this function for invalid inputs is undefined.
 */
function _mb_strlen( $str, $encoding = null ) {
	if ( null === $encoding ) {
		$encoding = get_option( 'blog_charset' );
	}

	// The solution below works only for UTF-8,
	// so in case of a different charset just use built-in strlen()
	if ( ! in_array( $encoding, array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) ) {
		return strlen( $str );
	}

	if ( _wp_can_use_pcre_u() ) {
		// Use the regex unicode support to separate the UTF-8 characters into an array
		preg_match_all( '/./us', $str, $match );
		return count( $match[0] );
	}

	$regex = '/(?:
		  [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
		| [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
		| \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
		| [\xE1-\xEC][\x80-\xBF]{2}
		| \xED[\x80-\x9F][\x80-\xBF]
		| [\xEE-\xEF][\x80-\xBF]{2}
		| \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
		| [\xF1-\xF3][\x80-\xBF]{3}
		| \xF4[\x80-\x8F][\x80-\xBF]{2}
	)/x';

	$count = 1; // Start at 1 instead of 0 since the first thing we do is decrement
	do {
		// We had some string left over from the last round, but we counted it in that last round.
		$count--;

		// Split by UTF-8 character, limit to 1000 characters (last array element will contain the rest of the string)
		$pieces = preg_split( $regex, $str, 1000 );

		// Increment
		$count += count( $pieces );
	} while ( $str = array_pop( $pieces ) ); // If there's anything left over, repeat the loop.

	// Fencepost: preg_split() always returns one extra item in the array
	return --$count;
}

if ( !function_exists('hash_hmac') ):
function hash_hmac($algo, $data, $key, $raw_output = false) {
	return _hash_hmac($algo, $data, $key, $raw_output);
}
endif;

function _hash_hmac($algo, $data, $key, $raw_output = false) {
	$packs = array('md5' => 'H32', 'sha1' => 'H40');

	if ( !isset($packs[$algo]) )
		return false;

	$pack = $packs[$algo];

	if (strlen($key) > 64)
		$key = pack($pack, $algo($key));

	$key = str_pad($key, 64, chr(0));

	$ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
	$opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));

	$hmac = $algo($opad . pack($pack, $algo($ipad . $data)));

	if ( $raw_output )
		return pack( $pack, $hmac );
	return $hmac;
}

if ( !function_exists('json_encode') ) {
	function json_encode( $string ) {
		global $wp_json;

		if ( ! ( $wp_json instanceof Services_JSON ) ) {
			require_once( ABSPATH . WPINC . '/class-json.php' );
			$wp_json = new Services_JSON();
		}

		return $wp_json->encodeUnsafe( $string );
	}
}

if ( !function_exists('json_decode') ) {
	/**
	 * @global Services_JSON $wp_json
	 * @param string $string
	 * @param bool   $assoc_array
	 * @return object|array
	 */
	function json_decode( $string, $assoc_array = false ) {
		global $wp_json;

		if ( ! ($wp_json instanceof Services_JSON ) ) {
			require_once( ABSPATH . WPINC . '/class-json.php' );
			$wp_json = new Services_JSON();
		}

		$res = $wp_json->decode( $string );
		if ( $assoc_array )
			$res = _json_decode_object_helper( $res );
		return $res;
	}

	/**
	 * @param object $data
	 * @return array
	 */
	function _json_decode_object_helper($data) {
		if ( is_object($data) )
			$data = get_object_vars($data);
		return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
	}
}

if ( ! function_exists( 'hash_equals' ) ) :
/**
 * Compare two strings in constant time.
 *
 * This function was added in PHP 5.6.
 * It can leak the length of a string.
 *
 * @since 3.9.2
 *
 * @param string $a Expected string.
 * @param string $b Actual string.
 * @return bool Whether strings are equal.
 */
function hash_equals( $a, $b ) {
	$a_length = strlen( $a );
	if ( $a_length !== strlen( $b ) ) {
		return false;
	}
	$result = 0;

	// Do not attempt to "optimize" this.
	for ( $i = 0; $i < $a_length; $i++ ) {
		$result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
	}

	return $result === 0;
}
endif;

// JSON_PRETTY_PRINT was introduced in PHP 5.4
// Defined here to prevent a notice when using it with wp_json_encode()
if ( ! defined( 'JSON_PRETTY_PRINT' ) ) {
	define( 'JSON_PRETTY_PRINT', 128 );
}

if ( ! function_exists( 'json_last_error_msg' ) ) :
	/**
	 * Retrieves the error string of the last json_encode() or json_decode() call.
	 *
	 * @since 4.4.0
	 *
	 * @internal This is a compatibility function for PHP <5.5
	 *
	 * @return bool|string Returns the error message on success, "No Error" if no error has occurred,
	 *                     or false on failure.
	 */
	function json_last_error_msg() {
		// See https://core.trac.wordpress.org/ticket/27799.
		if ( ! function_exists( 'json_last_error' ) ) {
			return false;
		}

		$last_error_code = json_last_error();

		// Just in case JSON_ERROR_NONE is not defined.
		$error_code_none = defined( 'JSON_ERROR_NONE' ) ? JSON_ERROR_NONE : 0;

		switch ( true ) {
			case $last_error_code === $error_code_none:
				return 'No error';

			case defined( 'JSON_ERROR_DEPTH' ) && JSON_ERROR_DEPTH === $last_error_code:
				return 'Maximum stack depth exceeded';

			case defined( 'JSON_ERROR_STATE_MISMATCH' ) && JSON_ERROR_STATE_MISMATCH === $last_error_code:
				return 'State mismatch (invalid or malformed JSON)';

			case defined( 'JSON_ERROR_CTRL_CHAR' ) && JSON_ERROR_CTRL_CHAR === $last_error_code:
				return 'Control character error, possibly incorrectly encoded';

			case defined( 'JSON_ERROR_SYNTAX' ) && JSON_ERROR_SYNTAX === $last_error_code:
				return 'Syntax error';

			case defined( 'JSON_ERROR_UTF8' ) && JSON_ERROR_UTF8 === $last_error_code:
				return 'Malformed UTF-8 characters, possibly incorrectly encoded';

			case defined( 'JSON_ERROR_RECURSION' ) && JSON_ERROR_RECURSION === $last_error_code:
				return 'Recursion detected';

			case defined( 'JSON_ERROR_INF_OR_NAN' ) && JSON_ERROR_INF_OR_NAN === $last_error_code:
				return 'Inf and NaN cannot be JSON encoded';

			case defined( 'JSON_ERROR_UNSUPPORTED_TYPE' ) && JSON_ERROR_UNSUPPORTED_TYPE === $last_error_code:
				return 'Type is not supported';

			default:
				return 'An unknown error occurred';
		}
	}
endif;

if ( ! interface_exists( 'JsonSerializable' ) ) {
	define( 'WP_JSON_SERIALIZE_COMPATIBLE', true );
	/**
	 * JsonSerializable interface.
	 *
	 * Compatibility shim for PHP <5.4
	 *
     * @link http://php.net/jsonserializable
	 *
	 * @since 4.4.0
	 */
	interface JsonSerializable {
		public function jsonSerialize();
	}
}

// random_int was introduced in PHP 7.0
if ( ! function_exists( 'random_int' ) ) {
	require ABSPATH . WPINC . '/random_compat/random.php';
}


text:
sandbox
=======

Small sandbox for executing code from the browser, part of protoboard.org