text:
.class public final Lcom/tencent/qrom/R$animator;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/tencent/qrom/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "animator"
.end annotation

# static fields
.field public static final fade_in:I = 0x7a050000

.field public static final fade_out:I = 0x7a050001

.field public static final fragment_close_enter:I = 0x7a050002

.field public static final fragment_close_exit:I = 0x7a050003

.field public static final fragment_fade_enter:I = 0x7a050004

.field public static final fragment_fade_exit:I = 0x7a050005

.field public static final fragment_open_enter:I = 0x7a050006

.field public static final fragment_open_exit:I = 0x7a050007

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 106
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
+++
widget = "posts"
date = "2017-01-01T00:00:00Z"
math = false
highlight = false

# Optional featured image (relative to `static/img/` folder).
[header]
image = "headers/rabbit.svg"
caption = "Image credit: [**Academic**](https://github.com/gcushen/hugo-academic/)"
+++


text:
OpenShift Node Certificates
===========================

This role determines if OpenShift node certificates must be created, delegates certificate creation to the `openshift_ca_host` and then deploys those certificates to node hosts which this role is being applied to.

Requirements
------------

* Ansible 2.2

Role Variables
--------------

From `openshift_ca`:

| Name                                | Default value                                                           | Description                                                                                |
|-------------------------------------|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|
| openshift_ca_host                   | None (Required)                                                         | The hostname of the system where the OpenShift CA will be (or has been) created.                                          |

From this role:

| Name                                | Default value                                                           | Description                                                                                |
|-------------------------------------|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|
| openshift_generated_configs_dir     | `{{ openshift.common.config_base }}/generated-configs`                  | Directory in which per-node generated config directories will be created on the `openshift_ca_host`.                      |
| openshift_node_cert_subdir          | `node-{{ openshift.common.hostname }}`                                  | Directory within `openshift_generated_configs_dir` where per-node certificates will be placed on the `openshift_ca_host`. |
| openshift_node_config_dir           | `{{ openshift.common.config_base }}/node`                               | Node configuration directory in which certificates will be deployed on nodes.                                             |
| openshift_node_generated_config_dir | `{{ openshift_generated_configs_dir }}/{{ openshift_node_cert_subdir }` | Full path to the per-node generated config directory.                                                                     |

Dependencies
------------

* openshift_ca

Example Playbook
----------------

```
- name: Create OpenShift Node Certificates
  hosts: nodes
  roles:
  - role: openshift_node_certificates
    openshift_ca_host: master1.example.com
```

License
-------

Apache License Version 2.0

Author Information
------------------

Jason DeTiberus (jdetiber@redhat.com)


text:
ACCEPTED

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

#### Published in
Nova Hedwigia 52(3-4): 289 (1991)

#### Original name
Trichothelium longisporum Lücking

### Remarks
null


text:
/**
 * @fileoverview Utility functions for handling procedures.
 * @author fraser@google.com (Neil Fraser)
 */

/**
 */
Blockly.Procedures = {};

Blockly.Procedures.NAME_TYPE = 'procedure';

/**
 * Find all user-created procedure definitions.
 * @return {!Array.<!Array.<!Array>>} Pair of arrays, the
 *     first contains procedures without return variables, the second with.
 *     Each procedure is defined by a three-element list of name, parameter
 *     list, and return value boolean.
 */
Blockly.Procedures.allProcedures = function() {
  var blocks = Blockly.mainWorkspace.getAllBlocks(false);
  var proceduresReturn = [];
  var proceduresNoReturn = [];
  for (var x = 0; x < blocks.length; x++) {
    var func = blocks[x].getProcedureDef;
    if (func) {
      var tuple = func.call(blocks[x]);
      if (tuple) {
        if (tuple[2]) {
          proceduresReturn.push(tuple);
        } else {
          proceduresNoReturn.push(tuple);
        }
      }
    }
  }

  function tupleComparator(ta, tb) {
    a = ta[0].toLowerCase();
    b = tb[0].toLowerCase();
    if (a > b) {
      return 1;
    }
    if (a < b) {
      return -1;
    }
    return 0;
  }

  proceduresNoReturn.sort(tupleComparator);
  proceduresReturn.sort(tupleComparator);
  return [proceduresNoReturn, proceduresReturn];
};

/**
 * Ensure two identically-named procedures don't exist.
 * @param {string} name Proposed procedure name.
 * @param {!Blockly.Block} block Block to disambiguate.
 * @return {string} Non-colliding name.
 */
Blockly.Procedures.findLegalName = function(name, block) {
  if (!block.workspace.editable) {
    return name;
  }
  while (!Blockly.Procedures.isLegalName(name, block.workspace, block)) {
    // Collision with another procedure.
    var r = name.match(/^(.*?)(\d+)$/);
    if (!r) {
      name += '2';
    } else {
      name = r[1] + (parseInt(r[2], 10) + 1);
    }
  }
  return name;
};

/**
 * Does this procedure have a legal name?  Illegal names include names of
 * procedures already defined.
 * @param {string} name The questionable name.
 * @param {!Blockly.Workspace} workspace The workspace to scan for collisions.
 * @param {Blockly.Block} opt_exclude Optional block to exclude from
 *     comparisons (one doesn't want to collide with oneself).
 * @return {boolean} True if the name is legal.
 */
Blockly.Procedures.isLegalName = function(name, workspace, opt_exclude) {
  var blocks = workspace.getAllBlocks(false);
  // Iterate through every block and check the name.
  for (var x = 0; x < blocks.length; x++) {
    if (blocks[x] == opt_exclude) {
      continue;
    }
    var func = blocks[x].getProcedureDef;
    if (func) {
      var procName = func.call(blocks[x]);
      if (Blockly.Names.equals(procName[0], name)) {
        return false;
      }
    }
  }
  return true;
};

/**
 * Rename a procedure.  Called by the editable field.
 * @param {string} text The proposed new name.
 * @return {?string} The accepted name, or null if rejected.
 */
Blockly.Procedures.rename = function(text) {
  if (!this.sourceBlock_.editable) {
    return text;
  }
  // Strip leading and trailing whitespace.  Beyond this, all names are legal.
  text = text.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
  if (!text) {
    return null;
  }
  // Ensure two identically-named procedures don't exist.
  text = Blockly.Procedures.findLegalName(text, this.sourceBlock_);
  // Rename any callers.
  var blocks = this.sourceBlock_.workspace.getAllBlocks(false);
  for (var x = 0; x < blocks.length; x++) {
    var func = blocks[x].renameProcedure;
    if (func) {
      func.call(blocks[x], this.text_, text);
    }
  }
  window.setTimeout(Blockly.Procedures.refreshFlyoutCategory, 1);
  return text;
};

/**
 * Construct the blocks required by the flyout for the procedure category.
 * @param {!Array.<!Blockly.Block>} blocks List of blocks to show.
 * @param {!Array.<number>} gaps List of widths between blocks.
 * @param {number} margin Standard margin width for calculating gaps.
 * @param {!Blockly.Workspace} workspace The flyout's workspace.
 */
Blockly.Procedures.flyoutCategory = function(blocks, gaps, margin, workspace) {
  if (Blockly.Language.procedures_defnoreturn) {
    var block = new Blockly.Block(workspace, 'procedures_defnoreturn');
    block.initSvg();
    blocks.push(block);
    gaps.push(margin * 2);
  }
  if (Blockly.Language.procedures_defreturn) {
    var block = new Blockly.Block(workspace, 'procedures_defreturn');
    block.initSvg();
    blocks.push(block);
    gaps.push(margin * 2);
  }

  function populateProcedures(procedureList, templateName) {
    for (var x = 0; x < procedureList.length; x++) {
      var block = new Blockly.Block(workspace, templateName);
      block.setTitleText(procedureList[x][0], 'NAME');
      var tempIds = [];
      for (var t = 0; t < procedureList[x][1].length; t++) {
        tempIds[t] = 'ARG' + t;
      }
      block.setProcedureParameters(procedureList[x][1], tempIds);
      block.initSvg();
      blocks.push(block);
      gaps.push(margin * 2);
    }
  }

  var tuple = Blockly.Procedures.allProcedures();
  populateProcedures(tuple[0], 'procedures_callnoreturn');
  populateProcedures(tuple[1], 'procedures_callreturn');
};

/**
 * Refresh the procedure flyout if it is open.
 * Only used if the flyout's autoClose is false.
 */
Blockly.Procedures.refreshFlyoutCategory = function() {
  if (Blockly.Toolbox && Blockly.Toolbox.flyout_.isVisible() &&
      Blockly.Toolbox.selectedOption_.cat == Blockly.MSG_PROCEDURE_CATEGORY) {
    Blockly.Toolbox.flyout_.hide();
    Blockly.Toolbox.flyout_.show(Blockly.MSG_PROCEDURE_CATEGORY);
  }
};

/**
 * Find all the callers of a named procedure.
 * @param {string} name Name of procedure.
 * @param {!Blockly.Workspace} workspace The workspace to find callers in.
 * @return {!Array.<!Blockly.Block>} Array of caller blocks.
 */
Blockly.Procedures.getCallers = function(name, workspace) {
  callers = [];
  var blocks = workspace.getAllBlocks(false);
  // Iterate through every block and check the name.
  for (var x = 0; x < blocks.length; x++) {
    var func = blocks[x].getProcedureCall;
    if (func) {
      var procName = func.call(blocks[x]);
      // Procedure name may be null if the block is only half-built.
      if (procName && Blockly.Names.equals(procName, name)) {
        callers.push(blocks[x]);
      }
    }
  }
  return callers;
};

/**
 * When a procedure definition is destroyed, find and destroy all its callers.
 * @param {string} name Name of deleted procedure definition.
 * @param {!Blockly.Workspace} workspace The workspace to delete callers from.
 */
Blockly.Procedures.destroyCallers = function(name, workspace) {
  var callers = Blockly.Procedures.getCallers(name, workspace);
  for (var x = 0; x < callers.length; x++) {
    callers[x].destroy(true, false);
  }
  window.setTimeout(Blockly.Procedures.refreshFlyoutCategory, 1);
};

/**
 * When a procedure definition changes its parameters, find and edit all its
 * callers.
 * @param {string} name Name of edited procedure definition.
 * @param {!Blockly.Workspace} workspace The workspace to delete callers from.
 * @param {!Array.<string>} paramNames Array of parameter names.
 * @param {!Array.<string>} paramIds Array of unique parameter IDs.
 */
Blockly.Procedures.mutateCallers = function(name, workspace,
                                            paramNames, paramIds) {
  var callers = Blockly.Procedures.getCallers(name, workspace);
  for (var x = 0; x < callers.length; x++) {
    callers[x].setProcedureParameters(paramNames, paramIds);
  }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:id="@+id/send_req"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/com_facebook_button_blue"
        android:padding="8dp"
        android:textSize="22sp"
        android:drawableLeft="@drawable/fbshare"
        android:text="@string/send_req"
        android:textColor="#fff" />

</RelativeLayout>


text:
<?php
/**
 * Available Template Variables :
 *
 * @var mixed  $data Data comes unserialized
 * @var array  $field
 * @var array  $field_name
 * @var object $form Form generator
 * @package Setting\Templates
 * */

$data = get_option( $field_name );

if ( ( ! $data ) && isset( $field['def'] ) ) {
	$data = $field['def'];
}

$required    = ( isset( $field['rules']['required'] ) && $field['rules']['required'] ) ? 'required="required"' : '';
$max_length  = ( isset( $field['rules']['maxlength'] ) ) ? $field['rules']['maxlength'] : 250;
$min_length  = ( isset( $field['rules']['minlength'] ) ) ? $field['rules']['minlength'] : 0;
$placeholder = isset( $field['placeholder'] ) ? $field['placeholder'] : '';
$class       = isset( $field['class'] ) ? $field['class'] : '';
$id          = isset( $field['id'] ) ? $field['id'] : '';
?>

<input id="<?php echo esc_attr( $id ); ?>" class="<?php echo esc_attr( $class ); ?>" type="<?php echo esc_attr( $field['type'] ) ?>"
	name="<?php echo esc_attr( $field_name ) ?>" value="<?php echo esc_attr( $data ); ?>" <?php echo filter_var( $required ); ?>
	maxlength="<?php echo esc_attr( $max_length ); ?>" minlength="<?php echo esc_attr( $min_length ); ?>"
	placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"/>


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

/*! \file rx-element_at.hpp

    \brief Pulls an item located at a specified index location in the sequence of items and emits that item as its own sole emission.

    \param index  the index of the element to return.

    \return An observable that emit an item located at a specified index location.

    \sample
    \snippet element_at.cpp element_at sample
    \snippet output.txt element_at sample
*/

#if !defined(RXCPP_OPERATORS_RX_ELEMENT_AT_HPP)
#define RXCPP_OPERATORS_RX_ELEMENT_AT_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace operators {

namespace detail {

template<class... AN>
struct element_at_invalid_arguments {};

template<class... AN>
struct element_at_invalid : public rxo::operator_base<element_at_invalid_arguments<AN...>> {
    using type = observable<element_at_invalid_arguments<AN...>, element_at_invalid<AN...>>;
};
template<class... AN>
using element_at_invalid_t = typename element_at_invalid<AN...>::type;

template<class T>
struct element_at {
    using source_value_type = rxu::decay_t<T>;

    struct element_at_values {
        element_at_values(int i)
            : index(i)
        {
        }
        int index;
    };

    element_at_values initial;

    element_at(int i)
        : initial(i)
    {
    }

    template<class Subscriber>
    struct element_at_observer : public element_at_values
    {
        using this_type = element_at_observer<Subscriber>;
        using value_type = source_value_type;
        using dest_type = rxu::decay_t<Subscriber>;
        using observer_type = observer<value_type, this_type>;
        dest_type dest;
        mutable int current;

        element_at_observer(dest_type d, element_at_values v)
            : element_at_values(v),
              dest(d),
              current(0)
        {
        }
        template<typename U>
        void on_next(U&& v) const {
            if (current++ == this->index) {
                dest.on_next(std::forward<U>(v));
                dest.on_completed();
            }
        }
        void on_error(rxu::error_ptr e) const {
            dest.on_error(e);
        }
        void on_completed() const {
            if(current <= this->index) {
                dest.on_error(rxu::make_error_ptr(std::range_error("index is out of bounds")));
            }
        }

        static subscriber<value_type, observer_type> make(dest_type d, element_at_values v) {
            return make_subscriber<value_type>(d, this_type(d, v));
        }
    };

    template<class Subscriber>
    auto operator()(Subscriber dest) const
        -> decltype(element_at_observer<Subscriber>::make(std::move(dest), initial)) {
        return      element_at_observer<Subscriber>::make(std::move(dest), initial);
    }
};

}

/*! @copydoc rx-element_at.hpp
*/
template<class... AN>
auto element_at(AN&&... an)
    ->      operator_factory<element_at_tag, AN...> {
     return operator_factory<element_at_tag, AN...>(std::make_tuple(std::forward<AN>(an)...));
}

}

template<>
struct member_overload<element_at_tag>
{
    template<class Observable,
        class Enabled = rxu::enable_if_all_true_type_t<
            is_observable<Observable>
            >,
        class SourceValue = rxu::value_type_t<Observable>,
        class element_at = rxo::detail::element_at<SourceValue>>
    static auto member(Observable&& o, int index)
        -> decltype(o.template lift<SourceValue>(element_at(index))) {
        return      o.template lift<SourceValue>(element_at(index));
    }

    template<class... AN>
    static operators::detail::element_at_invalid_t<AN...> member(const AN...) {
        std::terminate();
        return {};
        static_assert(sizeof...(AN) == 10000, "element_at takes (required int)");
    }
};

}

#endif


text:
@implementation MRCReposSearchResultsItemViewModel

@synthesize name = _name;
@synthesize repoDescription = _repoDescription;
@synthesize updateTime = _updateTime;

- (NSAttributedString *)name {
    if (!_name) {
        NSString *uniqueName = [NSString stringWithFormat:@"%@/%@", self.repository.ownerLogin, self.repository.name];

        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:uniqueName];
        [attributedString addAttribute:NSForegroundColorAttributeName value:HexRGB(colorI3) range:[uniqueName rangeOfString:uniqueName]];

        for (NSDictionary *textMatche in self.repository.textMatches) {
            if ([textMatche[@"property"] isEqualToString:@"name"]) {
                for (NSDictionary *matche in textMatche[@"matches"]) {
                    NSUInteger loc = [[matche[@"indices"] firstObject] unsignedIntegerValue];
                    NSUInteger len = [[matche[@"indices"] lastObject] unsignedIntegerValue] - loc ;
                    [attributedString addAttribute:NSBackgroundColorAttributeName value:RGBAlpha(255, 255, 140, 0.5) range:NSMakeRange(loc + self.repository.ownerLogin.length + 1, len)];
                }
            }
        }

        _name = attributedString;
    }
    return _name;
}

- (NSAttributedString *)repoDescription {
    if (!_repoDescription) {
        NSMutableAttributedString *attributedString = nil;

        if (self.repository.repoDescription) {
            attributedString = [[NSMutableAttributedString alloc] initWithString:self.repository.repoDescription];
            for (NSDictionary *textMatche in self.repository.textMatches) {
                if ([textMatche[@"property"] isEqualToString:@"description"]) {
                    for (NSDictionary *matche in textMatche[@"matches"]) {
                        NSUInteger loc = [[matche[@"indices"] firstObject] unsignedIntegerValue];
                        NSUInteger len = [[matche[@"indices"] lastObject] unsignedIntegerValue] - loc ;
                        [attributedString addAttribute:NSBackgroundColorAttributeName value:RGBAlpha(255, 255, 140, 0.5) range:NSMakeRange(loc, len)];
                    }
                }
            }
        }

        _repoDescription = attributedString.copy;
    }
    return _repoDescription;
}

- (NSString *)updateTime {
    if (!_updateTime) {
        TTTTimeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];
        timeIntervalFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        _updateTime = [timeIntervalFormatter stringForTimeIntervalFromDate:[NSDate date] toDate:self.repository.dateUpdated].copy;
    }
    return _updateTime;
}

@end


text:
define(function(require){
  return 'confirmWithSelectDialog';
})


text:
<template name="overlay">

    Alvin
    Alvin
    Alvin
    Alvin

    {{> Template.dynamic template=template data=data}}

</template>


text:
package com.bandeira.sidnei.appleitor;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bandeira.sidnei.appleitor.Classes.Coleta;
import com.bandeira.sidnei.appleitor.Repositorio.ColetaRepositorio;

import java.io.FileNotFoundException;

public class CadastraColetaActivity extends AppCompatActivity {
    public static String nomeColeta = "";
    private Long codColeta ;
    private EditText edtDescricao;
    private Button btConfirma;
    private Button btCancela;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastra_coleta);

        edtDescricao = (EditText)findViewById(R.id.edtDescricao);
        btConfirma = (Button)findViewById(R.id.btConfirma);
        btCancela = (Button)findViewById(R.id.btCancela);
    }

    public void btCofirma(View view) throws FileNotFoundException {
        nomeColeta = edtDescricao.getText().toString();

        if (nomeColeta.isEmpty()){
            Toast.makeText(this,"Escolha uma descrição para o arquivo de coleta.",Toast.LENGTH_SHORT).show();
            edtDescricao.hasFocus();
        }else{
            gravarColeta();
            Intent it = new Intent(this, ColetaActivity.class);
            it.putExtra("codigoColeta", String.valueOf( codColeta));
            //startActivity(it);
            startActivityForResult(it,1);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            edtDescricao.setText("");
            edtDescricao.requestFocus();
        }
    }

    private void gravarColeta(){
        ColetaRepositorio rep = new ColetaRepositorio(this);
        Coleta novaColeta = new Coleta();
        novaColeta.setcoletadescricao(nomeColeta);
        rep.salvar(novaColeta);
        if (novaColeta.get_id() <= 0) {
            Toast.makeText(getApplicationContext(), "Erro ao gravar a coleta!", Toast.LENGTH_SHORT).show();
            edtDescricao.hasFocus();
        }else{
            codColeta = novaColeta.get_id();
        }
    }
}


text:
<!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script>
  var numCallsScroll = 0;
  var numCallsResize = 0;

  var t = async_test('verify that the resize events get fired when the window is resized.');

  window.onload = t.step_func(function() {
    testRunner.useUnfortunateSynchronousResizeMode();

    // Turn off smooth scrolling.
    internals.settings.setScrollAnimatorEnabled(false);

    window.visualViewport.addEventListener('scroll', function(e) {
      numCallsScroll++;
    });

    window.visualViewport.addEventListener('resize', function(e) {
      numCallsResize++;
    });

    window.resizeTo(window.outerWidth - 24, window.outerHeight - 24);
    requestAnimationFrame(function() {
      t.step(function() {
        assert_equals(numCallsScroll, 0, "resize 1 doesn't fire scroll event");
        assert_equals(numCallsResize, 1, "resize 1 fires resize event");
      });
      window.resizeTo(window.outerWidth + 24, window.outerHeight + 24);
      requestAnimationFrame(function() {
        t.step(function() {
          assert_equals(numCallsScroll, 0, "resize 2 doesn't fire scroll event");
          assert_equals(numCallsResize, 2, "resize 2 fires resize event");
          t.done();
        });
      });
    });
  });
</script>


text:
namespace OpenApoc
{

class GameState;
class CityView;
class BattleView;
class Form;
enum class GameEventType;

class NotificationScreen : public Stage
{
  private:
	sp<Form> menuform;
	GameEventType eventType;
	sp<GameState> state;

  public:
	NotificationScreen(sp<GameState> state, CityView &cityView, const UString &message,
	                   GameEventType eventType);
	NotificationScreen(sp<GameState> state, BattleView &battleView, const UString &message,
	                   GameEventType eventType);
	~NotificationScreen() override;
	// Stage control
	void begin() override;
	void pause() override;
	void resume() override;
	void finish() override;
	void eventOccurred(Event *e) override;
	void update() override;
	void render() override;
	bool isTransition() override;
};
}; // namespace OpenApoc


text:
package com.psddev.dari.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * {@link HttpServletResponse} implementation that buffers and captures
 * the response output.
 */
public class CapturingResponse extends HttpServletResponseWrapper {

    private ByteArrayServletOutputStream outputStreamCapture;
    private StringWriter writerCapture;
    private PrintWriter writer;

    public CapturingResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (writerCapture != null) {
            throw new IllegalStateException();

        } else {
            if (outputStreamCapture == null) {
                outputStreamCapture = new ByteArrayServletOutputStream();
            }

            return outputStreamCapture;
        }
    }

    @Override
    public PrintWriter getWriter() {
        if (outputStreamCapture != null) {
            throw new IllegalStateException();

        } else {
            if (writerCapture == null) {
                writerCapture = new StringWriter();
                writer = new PrintWriter(writerCapture);
            }

            return writer;
        }
    }

    /**
     * Returns the output captured so far. If {@link
     * ServletResponse#getOutputStream} was used to write the output,
     * always returns an empty string.
     *
     * @return Never {@code null}.
     */
    public String getOutput() {
        return writerCapture != null ? writerCapture.toString() : "";
    }

    /**
     * Writes the output captured so far to the underlying response.
     */
    public void writeOutput() throws IOException {
        if (outputStreamCapture != null) {
            getResponse().getOutputStream().write(outputStreamCapture.delegate.toByteArray());

        } else if (writerCapture != null) {
            getResponse().getWriter().write(writerCapture.toString());
        }
    }

    private static class ByteArrayServletOutputStream extends ServletOutputStream {

        private final ByteArrayOutputStream delegate = new ByteArrayOutputStream();

        @Override
        public boolean isReady() {
            throw new UnsupportedOperationException();
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void write(int b) {
            delegate.write(b);
        }
    }
}


text:
class RbenvDefaultGems < Formula
  desc "Auto-installs gems for Ruby installs"
  homepage "https://github.com/sstephenson/rbenv-default-gems"
  url "https://github.com/sstephenson/rbenv-default-gems/archive/v1.0.0.tar.gz"
  sha256 "8271d58168ab10f0ace285dc4c394e2de8f2d1ccc24032e6ed5924f38dc24822"
  license "MIT"
  revision 1
  head "https://github.com/sstephenson/rbenv-default-gems.git"

  bottle :unneeded

  depends_on "rbenv"

  # Upstream patch: https://github.com/sstephenson/rbenv-default-gems/pull/3
  patch do
    url "https://github.com/sstephenson/rbenv-default-gems/commit/ead67889c91c53ad967f85f5a89d986fdb98f6fb.patch?full_index=1"
    sha256 "ac6a5654c11d3ef74a97029ed86b8a7b6ae75f4ca7ff4d56df3fb35e7ae0acb8"
  end

  def install
    prefix.install Dir["*"]
  end

  test do
    assert_match "default-gems.bash", shell_output("rbenv hooks install")
  end
end


text:
using Newtonsoft.Json;
using s4pi.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace TS4_STBL_Editor
{
    public partial class CreateNewSTBLInPackage : Form
    {
        MainUI mainUI;
        public CreateNewSTBLInPackage(MainUI mainUI)
        {
            InitializeComponent();
            this.mainUI = mainUI;
        }

        private void CreateNewSTBLInPackage_Load(object sender, EventArgs e)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "TS4_STBL_Editor.LangCodesList.xml";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();

                TextReader tr = new StringReader(result);
                LangCodesDS.ReadXml(tr);

                string[] allArr = new string[2];
                allArr[0] = "Add All Langs At Once";
                allArr[1] = "Add All Langs At Once";

                DataRow dr = LangCodesDS.Tables[0].NewRow();
                dr.ItemArray = allArr;

                LangCodesDS.Tables[0].Rows.InsertAt(dr, 0);

                comboBox1.DataSource = LangCodesDS.Tables[0];
                comboBox1.DisplayMember = "name";
                comboBox1.ValueMember = "id";
            }

            if (File.Exists("settings.json"))
            {
                string json = File.ReadAllText("settings.json", Encoding.UTF8);
                Dictionary<string, string> settings = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                stblNameFld.Text = settings["stblFileName"];
            }
        }

        private String getStblNameHash(string langCode)
        {
            var s = FNVHasherDLL.FNVHasherStrFunctions.fnv64HighBitHexString(stblNameFld.Text);

            string fn = s.Replace("0x", "");
            fn = fn.Substring(2);

            s = langCode + fn;

            return s;
        }

        private void stblNameFld_TextChanged(object sender, EventArgs e)
        {
            string langCode = comboBox1.SelectedValue.ToString();

            if (!langCode.Equals("Add All Langs At Once"))
            {
                langCode = langCode.Substring(2);

                string s = getStblNameHash(langCode);

                calculatedHashOfNameFld.Text = "0x" + s;
            }

            // Save name
            Dictionary<string, string> settings = new Dictionary<string, string>();
            settings.Add("stblFileName", stblNameFld.Text);

            string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

            File.WriteAllText("settings.json", json, Encoding.UTF8);
        }

        private void Save_Click(object sender, EventArgs e)
        {
            if (calculatedHashOfNameFld.Text.Length < 5)
            {
                MessageBox.Show("Enter file name!");
            }
            else
            {
                string lang = comboBox1.SelectedValue.ToString();
                if (lang.Equals("Add All Langs At Once"))
                {
                    DataTable dt = comboBox1.DataSource as DataTable;
                    foreach (DataRow dr in dt.Rows)
                    {
                        string l = dr.ItemArray[0].ToString();
                        if (!l.Equals("Add All Langs At Once"))
                        {
                            string fn = getStblNameHash(l);

                            UInt64 fnU = Convert.ToUInt64(fn, 16);
                            //ulong a = (ulong)FNVHasherStrFunctions.fnv64HighBit("qqqq");

                            TGIBlock newnmrk = new TGIBlock(0,
                                null,
                                0x220557DA,
                                0x80000000,
                                fnU);
                            Stream s = new MemoryStream();

                            List<uint> textResourceID = new List<uint>();
                            List<string> textString = new List<string>();

                            ArrayList tempList = new ArrayList();

                            tempList.Add(textResourceID);
                            tempList.Add(textString);

                            mainUI.WriteSTBLStream(tempList, s);
                            var addedResIndexEntry = MainUI.imppkg.AddResource(newnmrk, s, true);
                        }
                    }
                    mainUI.saveSTBL();
                    mainUI.closeSTBL();
                    mainUI.SavePackage();
                    mainUI.closePackage();
                }
                else
                {
                    string fn = getStblNameHash(lang);

                    UInt64 fnU = Convert.ToUInt64(fn, 16);
                    //ulong a = (ulong)FNVHasherStrFunctions.fnv64HighBit("qqqq");

                    TGIBlock newnmrk = new TGIBlock(0,
                        null,
                        0x220557DA,
                        0x80000000,
                        fnU);
                    Stream s = new MemoryStream();

                    List<uint> textResourceID = new List<uint>();
                    List<string> textString = new List<string>();

                    ArrayList tempList = new ArrayList();

                    tempList.Add(textResourceID);
                    tempList.Add(textString);

                    mainUI.WriteSTBLStream(tempList, s);
                    var addedResIndexEntry = MainUI.imppkg.AddResource(newnmrk, s, true);
                    MainUI.lrie.Add(addedResIndexEntry);

                    BigInteger bi = BigInteger.Parse(addedResIndexEntry.Instance.ToString());
                    MainUI.packageElId = bi;

                    ArrayList textResourceID2 = new ArrayList();
                    ArrayList textString2 = new ArrayList();

                    tempList = new ArrayList();

                    tempList.Add(textResourceID2);
                    tempList.Add(textString2);

                    mainUI.STBLToDataGridView(tempList);

                    MainUI.imppkg.SavePackage();
                    MainUI.imppkg.Dispose();

                    mainUI.openPackageFile(MainUI.pathToOpenedPackageFile);
                }

                MessageBox.Show("Successfully done!");

            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var s = FNVHasherDLL.FNVHasherStrFunctions.fnv64HighBitHexString(stblNameFld.Text);

            string fn = s.Replace("0x", "");
            fn = fn.Substring(2);

            string langCode = comboBox1.SelectedValue.ToString();
            langCode = langCode.Substring(2);

            s = langCode + fn;

            calculatedHashOfNameFld.Text = "0x" + s;
        }
    }
}


text:
__author__ = 'hiroki'

from kokemomo.plugins.recommend.model.km_history_table import find_list
from kokemomo.plugins.engine.utils.km_config import get_character_set_setting

"""
Reccomend class for Kokemomo CMS.
Adopt a user-based collaborative filtering.

[Design information]
--Table Column--
id, user_id, contents, count

--Data example--
0001, user01, AAA, 1
0002, user01, BBB, 1
0003, user01, CCC, 1
0004, user02, AAA, 1
0005, user03, BBB, 1

--Data example[After shaping]--
      |AAA|BBB|CCC|
user01|  1|  1|  1|
user02|  1|   |   |
user03|   |  1|   |

[Example]
If the target is user02.

--Code--
column = ["AAA", "BBB", "CCC"]
user_similarity = get_reccomend("user02", column)

--Result--
'user01': 0.3333333333333333
'user02': 1.0
'user03': 0.0

user01 is similar!

"""

charset = get_character_set_setting()

def get_recommend(user_id, columns, session):
    """
    Based on the history list, get the recommended level for the given user.

    :param user_id: target user_id
    :param columns: columns
    :return:recommend dictionary
    """
    history_list = find_list(10, session) # TODO: 期限を設定ファイルに抜き出し
    # Generate a user record that becomes a condition.
    user_record = create_user_record(user_id, history_list, columns)
    # Comparison with history.
    check_list = {}
    for history in history_list:
        if history.user_id is not user_id and not history.user_id in check_list:
            check_list[history.user_id] = create_user_record(history.user_id, history_list, columns)
    # Check similarity.
    result = {}
    for target in check_list:
        target = target.encode(charset)
        similarity = jaccard(user_record, check_list[target])
        result[target]=similarity
    return result

def create_user_record(user_id, history_list, columns):
    """
    Based on the item and the history list, you generate a record of the specified user.

    :param user_id: user id
    :param history_list: history list
    :param columns: columns
    :return: user record
    """
    record = []
    for i, column in enumerate(columns):
        record.append(0)
        for history in history_list:
            history_user = history.user_id.encode(charset)
            history_column =  history.contents.encode(charset)
            if user_id == history_user and column == history_column:
                record[i] = 1
                break
    return record

def jaccard(dic_x, dic_y):
    """
    Using jaccard coefficient, to determine the similarity.

    :param dic_x: matrix
    :param dic_y: matrix
    :return: similarity
    """
    product_set = 0.
    union = 0.
    for i in xrange(len(dic_x)):
        if dic_x[i] == 1 or dic_y[i] == 1:
            union += 1
            if dic_x[i] == 1 and dic_y[i] == 1:
                product_set += 1
    try:
        return product_set / union
    except ZeroDivisionError:
        return 0.0


text:
package com.tq.requisition.infrastructure.Specifications.hpt;

import com.tq.requisition.domain.Specification.Specification;
import com.tq.requisition.domain.Specification.expression.IHqlExpression;
import com.tq.requisition.domain.Specification.expression.OperationType;
import com.tq.requisition.domain.model.housePuraseTicket.HousePuraseTicket;
import com.tq.requisition.domain.model.share.TicketState;
import com.tq.requisition.infrastructure.Specifications.Expression.HqlExpression;
import com.tq.requisition.presentation.dto.hpt.HPTFuzzyQueryModel;

/**
 * 购房券发放台账规约查询条件
 * @author jjh
 * @time 2015-01-04 1:39
 *
 */
public class HPTProvideTableSpecification extends Specification<HousePuraseTicket>{
	private HPTFuzzyQueryModel queryModel;

	public HPTProvideTableSpecification(Class<HousePuraseTicket> _t,HPTFuzzyQueryModel queryModel) {
		super(_t);
		this.queryModel = queryModel;
	}

	@Override
	public IHqlExpression getHqlExpression() {
		IHqlExpression expression = new HqlExpression();
		StringBuilder sb = new StringBuilder();
		sb.append("select new com.tq.requisition.presentation.dto.hpt.HPTReceiveTableDto(");
		sb.append(" fi.proId,fi.proName,fi.id,h.id,fi.name,fi.idNumber,pi.name,h.ticketNumber,pi.evidenceOfGetting,pi.gettingDate,h.bonus) ");
		sb.append(" from HPTProviderInfo pi, HousePuraseTicket h,FamilyItem fi");
		sb.append(" where h.fmlItemId=fi.id and pi.ticketId=h.id and h.del=false and (h.state=? or h.state=? or h.state=?)");
		if(queryModel.getProName()!=null)
		{
			sb.append(" and fi.proName like '%"+queryModel.getProName()+"%'");
		}
		if(queryModel.getIdNumber()!=null && !(queryModel.getIdNumber().trim().equals(""))){
			sb.append(" and fi.idNumber='"+queryModel.getIdNumber()+"'");
		}
		if(queryModel.getName()!=null && !(queryModel.getName().trim().equals("")))
		{
			sb.append(" and fi.name like '%"+queryModel.getName()+"%'");
		}
		if(queryModel.getTicketNumber()!=null && !(queryModel.getTicketNumber().trim().equals(""))){
			sb.append(" and h.ticketNumber='"+queryModel.getTicketNumber()+"'");
		}
		expression.setHql(sb.toString());
		expression.setParameters(TicketState.RECEIVED,TicketState.USED,TicketState.CASHED);
		expression.setType(OperationType.HQL);
		return expression;
	}
}


text:
require 'spec_helper'

describe Gws::Board::TrashPurgeJob, dbscope: :example do
  let(:site) { gws_site }
  let(:now) { Time.zone.now.beginning_of_minute }
  let!(:item) { create(:gws_board_topic, cur_site: site, deleted: now - 7.days) }

  describe '#perform' do
    context 'no board topics are purged' do
      it do
        expect { described_class.bind(site_id: site).perform_now }.not_to(change { Gws::Board::Topic.topic.count })

        expect(Job::Log.count).to eq 1
        Job::Log.first.tap do |log|
          expect(log.logs).to include(include("INFO -- : Started Job"))
          expect(log.logs).to include(include("INFO -- : Completed Job"))
        end
      end
    end

    context 'board topics are purged' do
      it do
        expect { described_class.bind(site_id: site).perform_now(threshold: '7') }.to \
          change { Gws::Board::Topic.topic.count }.by(-1)

        expect(Job::Log.count).to eq 1
        Job::Log.first.tap do |log|
          expect(log.logs).to include(include("INFO -- : Started Job"))
          expect(log.logs).to include(include("INFO -- : Completed Job"))
        end
      end
    end
  end
end


text:
<?php if (!defined('IDIR')) { die; }

/**
* ubb_threads_008 Import Poll module
*
* @package			ImpEx.ubb_threads
*
*/
class ubb_threads_008 extends ubb_threads_000
{
	var $_dependent 	= '006';

	function ubb_threads_008(&$displayobject)
	{
		$this->_modulestring = $displayobject->phrases['import_poll'];
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_polls'))
				{
					$displayobject->display_now("
{$displayobject->phrases['poll_restart_ok']}
");
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error(substr(get_class($this) , -3), $displayobject->phrases['poll_restart_failed'], $displayobject->phrases['check_db_permissions']);
				}
			}

			// Start up the table
			$displayobject->update_basic('title', $displayobject->phrases['import_poll']);
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_table_header($displayobject->phrases['import_poll']));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code($displayobject->phrases['polls_per_page'],'pollperpage',50));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'], $displayobject->phrases['reset']));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('pollstartat','0');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description("
{$displayobject->phrases['dependant_on']} " . $sessionobject->get_module_title($this->_dependent) . " {$displayobject->phrases['cant_run']} ."));
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'],''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		// Set up working variables.
		$displayobject->update_basic('displaymodules','FALSE');
		$target_database_type	= $sessionobject->get_session_var('targetdatabasetype');
		$target_table_prefix	= $sessionobject->get_session_var('targettableprefix');
		$source_database_type	= $sessionobject->get_session_var('sourcedatabasetype');
		$source_table_prefix	= $sessionobject->get_session_var('sourcetableprefix');

		// Per page vars
		$poll_start_at			= $sessionobject->get_session_var('pollstartat');
		$poll_per_page			= $sessionobject->get_session_var('pollperpage');
		$class_num				= substr(get_class($this) , -3);

		// Start the timing
		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		// Get an array of poll details
		$poll_array 	= $this->get_ubb_threads_poll_question($Db_source, $source_database_type, $source_table_prefix, $poll_start_at, $poll_per_page);

		// Display count and pass time
		$displayobject->display_now("
{$displayobject->phrases['importing']} " . count($poll_array) . " {$displayobject->phrases['polls']}

{$displayobject->phrases['from']} : " . $poll_start_at . " ::  {$displayobject->phrases['to']} : " . ($poll_start_at + count($poll_array)) . "
");

		$poll_object = new ImpExData($Db_target, $sessionobject, 'poll');

		foreach ($poll_array as $poll_id => $poll_question)
		{
			$poll_options 	= $this->get_ubb_threads_poll_options($Db_source, $source_database_type, $source_table_prefix, $poll_id, $poll_question['P_QuestionNum']);
			$import_thread	= $this->get_ubb_threads_poll_thread_id($Db_source, $source_database_type, $source_table_prefix, $poll_id);

			unset($options, $votes, $numberoptions, $voters, $question);

			foreach($poll_options as $id => $data)
			{
				$options 	.=  $data['P_Option'] . '|||';
				$votes		.=  $this->get_ubb_threads_poll_votes($Db_source, $source_database_type, $source_table_prefix, $data['P_OptionNum'], $poll_question['P_QuestionNum'] ) . '|||';

				$numberoptions++;
			}

			$options = substr($options, 0, -3);
			$votes = substr($votes, 0, -3);

			$try = (phpversion() < '5' ? $poll_object : clone($poll_object));
			// Mandatory
			$try->set_value('mandatory', 'question',			$poll_question['P_Question']);
			$try->set_value('mandatory', 'dateline',			time());
			$try->set_value('mandatory', 'options',				$options);
			$try->set_value('mandatory', 'votes',				$votes);
			$try->set_value('mandatory', 'importpollid',		$poll_id);

			// Non Mandatory
			$try->set_value('nonmandatory', 'active',			'1');
			$try->set_value('nonmandatory', 'numberoptions',	$numberoptions);
			$try->set_value('nonmandatory', 'timeout',			'0');
			$try->set_value('nonmandatory', 'multiple',			'0');
			$try->set_value('nonmandatory', 'voters',			$voters);
			$try->set_value('nonmandatory', 'public',			'1');

			// Check if poll object is valid
			if($try->is_valid())
			{
				$result = $try->import_poll($Db_target, $target_database_type, $target_table_prefix);
				$vb_poll_id = $Db_target->insert_id();
				$imported = false;

				if($result)
				{
					$try->import_poll_to_thread($Db_target, $target_database_type, $target_table_prefix, $vb_poll_id, $import_thread);

					$displayobject->display_now('
' . $try->how_complete() . '% ' . $displayobject->phrases['poll'] . ' -> ' . $try->get_value('mandatory', 'question'));
					$sessionobject->add_session_var($class_num . '_objects_done', intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1);
				}
				else
				{
					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
					$sessionobject->add_error($poll_id, $displayobject->phrases['poll_not_imported_3'], $displayobject->phrases['poll_not_imported_rem']);
					$displayobject->display_now("
{$displayobject->phrases['failed']} :: {$displayobject->phrases['poll_not_imported']}");
				}
			}
			else
			{
				$displayobject->display_now("
{$displayobject->phrases['invalid_object']}" . $try->_failedon);
				$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
			}
			unset($try);
		}// End resume

		// Check for page end
		if (count($poll_array) == 0 OR count($poll_array) < $poll_per_page)
		{
			$sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit'));
			$sessionobject->remove_session_var($class_num . '_start');

			$displayobject->update_html($displayobject->module_finished($this->_modulestring,
				$sessionobject->return_stats($class_num, '_time_taken'),
				$sessionobject->return_stats($class_num, '_objects_done'),
				$sessionobject->return_stats($class_num, '_objects_failed')
			));

			$sessionobject->set_session_var($class_num ,'FINISHED');
			$sessionobject->set_session_var('module','000');
			$sessionobject->set_session_var('autosubmit','0');
			$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
		}

		$sessionobject->set_session_var('pollstartat',$poll_start_at+$poll_per_page);
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}// End resume
}//End Class
# Autogenerated on : May 17, 2004, 10:34 pm
# By ImpEx-generator 1.0.
/*======================================================================*/
?>


text:
module.exports = function(object, propertyName, value) {
  Object.defineProperty(object, propertyName, {
    value: value,
    enumerable: false,
    writable: true
  });
};


text:
import { module, test } from "qunit";
import { setupRenderingTest } from "ember-qunit";
import { buildResolver } from "test-utils";
import { render, clearRender } from "@ember/test-helpers";
import hbs from "htmlbars-inline-precompile";
import sinon from "sinon";

import Moment from "moment";

import { helper as TimeFromNowHelper } from "ui/components/helper/time-from-now";

module( "ui/components/helper/time-from-now", function( hooks ) {
	setupRenderingTest( hooks, {
		resolver: buildResolver({
			TimeFromNowHelper
		})
	});

	hooks.before(function() {
		Moment.locale( "en" );
	});
	hooks.beforeEach(function() {
		this.fakeTimer = sinon.useFakeTimers({
			toFake: [ "Date", "setTimeout", "clearTimeout" ],
			target: window
		});
	});
	hooks.afterEach(function() {
		this.fakeTimer.restore();
	});

	test( "Unit test", async function( assert ) {
		const Helper = this.owner.factoryFor( "helper:time-from-now" );
		const helper = Helper.create();
		const time = new Date() - Math.PI * 60 * 1000;

		assert.strictEqual(
			helper.compute( [ time ], {} ),
			"3 minutes ago",
			"Time from now with suffix"
		);

		assert.strictEqual(
			helper.compute( [ time ], { suffix: true } ),
			"3 minutes",
			"Time from now without suffix"
		);
	});

	test( "Interval", async function( assert ) {
		this.set( "time", new Date() );
		await render( hbs`{{time-from-now time interval=60000}}` );

		assert.strictEqual(
			this.element.innerText,
			"a few seconds ago",
			"Initial content"
		);

		this.fakeTimer.tick( 59999 );
		assert.strictEqual(
			this.element.innerText,
			"a few seconds ago",
			"Interval not yet completed"
		);

		this.fakeTimer.tick( 1 );
		assert.strictEqual(
			this.element.innerText,
			"a minute ago",
			"Updated content"
		);

		await clearRender();
		this.fakeTimer.tick( 60000 );
	});

});


text:
package com.mattunderscore.trees.base;

import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

import java.util.Iterator;
import java.util.NoSuchElementException;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import com.mattunderscore.iterators.SingletonIterator;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.tree.Node;

/**
 * Unit tests for {@link MutableChildIterator}.
 *
 * @author Matt Champion on 29/08/2015
 */
public final class MutableChildIteratorTest {
    @Mock
    private MutableNode<String> parent;
    @Mock
    private MutableNode<String> child;

    private Iterator<? extends MutableNode<String>> iterator;

    @Before
    public void setUp() {
        initMocks(this);

        iterator = new SingletonIterator<>(child);
    }

    @Test
    public void hasNext() {
        final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
        assertTrue(mutableIterator.hasNext());
        mutableIterator.next();
        assertFalse(mutableIterator.hasNext());
    }

    @Test(expected = NoSuchElementException.class)
    public void next() {
        final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
        final MutableNode<String> node = mutableIterator.next();
        assertSame(child, node);
        mutableIterator.next();
    }

    @Test
    public void remove() {
        final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
        mutableIterator.next();

        mutableIterator.remove();

        verify(parent).removeChild(child);
    }
}


text:
The 0.15.12 release of **rofi** focusses on improving overall user experience.  These improvements mostly focussed on
three things, first we (tried to) fix the problems with complex keyboard layouts, second we tried to make theming of
**rofi** easier. Also we added several speedups. Below I will highlight these bigger changes in more details

Now that **rofi** reached an acceptable maturity level, we will start using more common
version numbering. Right now rofi uses `0.year.month` for version numbers.
Starting with next version the widely used `major.minor.bugfix` scheme will be used.
This means, that next rofi version will either be

* 0.15.13 (bugfix release)
* 0.16.0 (minor release) or (if no major bugs are discovered)
* 1.0.0 (major release)

## Keyboard Layouts

**Rofi** used to have problems with keyboard layouts that used modifier keys to switch between different layers.
These problems should now be a thing of the past.

**Note** the syntax for binding keys has slightly changed. The *Mod1*, *Mod2*, etc. keywords are no longer available.
There was no good way to detect how these keys where mapped and if they could be used as modifiers.  E.g. if the right
alt (say *Mod3*) is configured to switch between layouts, it cannot work as modifier key to make a `Mod3-p` keybinding.
**Rofi** will now check if the current layout has the *SuperR*,*SuperL*,*AltGr*,*HyperL*,*HyperR* keys available.  If
they are available they can be used for keybindings, if not, the user gets a warning.

![Rofi Keyboard Warning](rofi-warning.png)

## Speedups

### DMenu reading from stdin

**Rofi** used to have a custom `fgets` implementation that supported custom separators. The has been repaced by the
`getdelim` feature of POSIX '08, this gave a speedup of 6x (from 648 ms for 202000 lines down to 108ms).

### Multi-Core power

Still disabled by default, **rofi** can now spawn multiple threads for filtering rows. Depending on the underlying
hardware we saw a 1.5x speedup running on a dual core ARM and up to a 3.5x speedup on a quadcore (8 threads) i7 CPU.
It uses Glib's GThreadPool and will therefore spawn threads as needed and clean them up again afterwards.

To enable this option pass the `-threads 0` option, this will autodetect the number number of hw-threads. Pass `-threads 4`
to force it to use 4 threads. Setting the number to 1, disables it.

## Themes

**Rofi** color themes can be specified in a lot of detail, including the use of transparency to get desired results.
However color syntax proved to be difficult and testing it can be a hassle. To solve this we added a web frontend for writing
themes (with live preview) and a themes repository.

To make things even easier, you can now take screenshots of **rofi** from within **rofi** with a simple keybinding.

![Rofi Internal Screenshot](rofi-screenshot.png)

### Theme repository

This has been requested several times and rofi's website actually has a theming page. This however got outdated quickly
and neither the themes or the screenshots are correct anymore. The newly added rofi-themes git repository allows you to
add themes easily: Fork the repository and export your current color theme with **rofi -dump-xresources-theme**. Place
it in the theme directory of the repository and run the update script. This will automatically generate screenshots and
update the page.  Update your fork and send a pull request. This way your theme will appear on official themes page,
once it's merged.

The repository can be found [here](https://github.com/DaveDavenport/rofi-themes/)

![Rofi Theme Site](rofi-theme-site.png)

### Themenator

The second tool is a website allowing you to easily create themes and preview all changes life, the
[themenator](https://davedavenport.github.io/rofi/generator.html) Big thanks to
[SardemFF7](https://github.com/sardemff7) who got tired of me complaining, took the very rough prototype and turned it
into something beautiful.

Hopefully people will make beautiful themes and submit them to the [theme repository](https://github.com/DaveDavenport/rofi-themes/).

![Rofi Themenator](rofi-themenator.png)

## Full ChangeLog

### New features:
- Initial `-dump` command for dmenu mode. (#216)
- Threading support.
    - Parallel checking for ASCII.
    - Parallel string matching.
    - Autodetect number of HW-threads.
    - Disabled by default.
- Highlight multiple selected rows (#287,#293)
- Dmenu can read from file instead of stdin.
- Regex matching (#113)
- Take Screenshot of rofi using keybinding.
- Hotkey for sorting: (#298)
- Option to set scrollbar width.

### Improvements:

- Fix return code of multi-select.
- Update manpage (#289, #291)
- Improve speed of reading stdin in dmenu mode.
- Correctly handle modifier keys now. Should now support most weird keyboard layouts and switching between them.
(#268, #265, #286)
- Correctly set locale, fixing issues with entering special characters. (#282)
- DRun mode support `NoDisplay` setting (#283)
- Pango markup is matched when filtering. (#273)

### Bug fixes:

- Improve error message (#290)
- Correctly switch to next entry on multi-select when list is filtered (#292)
- Switch __FUNCTION__ for __func__. (#288)
- Fix segfault on empty list and moving through it. (#256,#275)
- Fix one off of colors (#269)
- Drun fix uninitialized memory (#285)


text:
import Mustache from 'mustache';

export default class TmplTasks {
  constructor() {
    this.taskItemTemplate = `

          {{title}}

          <button class="task-controls__buttons" data-bind="done">
            done
          </button>
          <button class="task-controls__buttons" data-bind="edit">
            edit
          </button>
          <button class="task-controls__buttons" data-bind="delete">
            delete
          </button>

    `;

    this.taskItemDoneTemplate = `

          {{title}}

          <button class="task-controls__buttons" data-bind="redo">
            redo
          </button>
          <button class="task-controls__buttons" data-bind="delete">
            delete
          </button>

    `;
  }

  show(data) {
    const view = data.map( item => {

      if (item.completed) { return; }

      return Mustache.render(this.taskItemTemplate, item);
    });
    return view.join('');
  }

  //TODO: Improve with concept DRY
  showDone(data) {
    const view = data.map((item) => {

      if(!item.completed) { return; }

      return Mustache.render(this.taskItemDoneTemplate, item);
    });
    return view.join('');
  }
}


text:
namespace perfetto {
namespace protos {
namespace pbzero {
class ChromeCompositorSchedulerState;
}
}  // namespace protos
}  // namespace perfetto
namespace base {
class SingleThreadTaskRunner;
}

namespace viz {
struct FrameTimingDetails;
}

namespace cc {
struct BeginMainFrameMetrics;
class CompositorTimingHistory;
class CompositorFrameReportingController;

enum class FrameSkippedReason {
  kRecoverLatency,
  kNoDamage,
  kWaitingOnMain,
  kDrawThrottled,
};

class SchedulerClient {
 public:
  // Returns whether the frame has damage.
  virtual bool WillBeginImplFrame(const viz::BeginFrameArgs& args) = 0;
  virtual void ScheduledActionSendBeginMainFrame(
      const viz::BeginFrameArgs& args) = 0;
  virtual DrawResult ScheduledActionDrawIfPossible() = 0;
  virtual DrawResult ScheduledActionDrawForced() = 0;

  // The Commit step occurs when the client received the BeginFrame from the
  // source and we perform at most one commit per BeginFrame. In this step the
  // main thread collects all updates then blocks and gives control to the
  // compositor thread, which allows Compositor thread to update its layer tree
  // to match the state of the layer tree on the main thread.
  virtual void ScheduledActionCommit() = 0;
  virtual void ScheduledActionActivateSyncTree() = 0;
  virtual void ScheduledActionBeginLayerTreeFrameSinkCreation() = 0;
  virtual void ScheduledActionPrepareTiles() = 0;
  virtual void ScheduledActionInvalidateLayerTreeFrameSink(
      bool needs_redraw) = 0;
  virtual void ScheduledActionPerformImplSideInvalidation() = 0;
  // Called when the scheduler is done processing a frame. Note that the
  // BeginFrameArgs instance passed may not necessarily be the same instance
  // that was passed to WillBeginImplFrame(). Rather, |last_activated_args|
  // represents the latest BeginFrameArgs instance that caused an activation to
  // happen.
  virtual void DidFinishImplFrame(
      const viz::BeginFrameArgs& last_activated_args) = 0;
  virtual void DidNotProduceFrame(const viz::BeginFrameAck& ack,
                                  FrameSkippedReason reason) = 0;
  virtual void WillNotReceiveBeginFrame() = 0;
  virtual void SendBeginMainFrameNotExpectedSoon() = 0;
  virtual void ScheduledActionBeginMainFrameNotExpectedUntil(
      base::TimeTicks time) = 0;
  virtual void FrameIntervalUpdated(base::TimeDelta interval) = 0;

  // Functions used for reporting animation targeting UMA, crbug.com/758439.
  virtual bool HasInvalidationAnimation() const = 0;

 protected:
  virtual ~SchedulerClient() {}
};

class CC_EXPORT Scheduler : public viz::BeginFrameObserverBase {
 public:
  Scheduler(
      SchedulerClient* client,
      const SchedulerSettings& scheduler_settings,
      int layer_tree_host_id,
      base::SingleThreadTaskRunner* task_runner,
      std::unique_ptr<CompositorTimingHistory> compositor_timing_history,
      CompositorFrameReportingController* compositor_frame_reporting_controller,
      power_scheduler::PowerModeArbiter* power_mode_arbiter);
  Scheduler(const Scheduler&) = delete;
  ~Scheduler() override;

  Scheduler& operator=(const Scheduler&) = delete;

  // This is needed so that the scheduler doesn't perform spurious actions while
  // the compositor is being torn down.
  void Stop();

  // BeginFrameObserverBase
  void OnBeginFrameSourcePausedChanged(bool paused) override;
  bool OnBeginFrameDerivedImpl(const viz::BeginFrameArgs& args) override;

  void OnDrawForLayerTreeFrameSink(bool resourceless_software_draw,
                                   bool skip_draw);

  const SchedulerSettings& settings() const { return settings_; }

  void SetVisible(bool visible);
  bool visible() { return state_machine_.visible(); }
  void SetCanDraw(bool can_draw);

  // We have 2 copies of the layer trees on the compositor thread: pending_tree
  // and active_tree. When we finish asynchronously rastering all tiles on
  // pending_tree, call this method to notify that this pending tree is ready to
  // be activated, that is to be copied to the active tree.
  void NotifyReadyToActivate();
  void NotifyReadyToDraw();
  void SetBeginFrameSource(viz::BeginFrameSource* source);

  using AnimationWorkletState = SchedulerStateMachine::AnimationWorkletState;
  using PaintWorkletState = SchedulerStateMachine::PaintWorkletState;
  using TreeType = SchedulerStateMachine::TreeType;

  // Sets whether asynchronous animation worklet mutations are running.
  // Mutations on the pending tree should block activiation. Mutations on the
  // active tree should delay draw to allow time for the mutations to complete.
  void NotifyAnimationWorkletStateChange(AnimationWorkletState state,
                                         TreeType tree);

  // Sets whether asynchronous paint worklets are running. Paint worklets
  // running should block activation of the pending tree, as it isn't fully
  // painted until they are done.
  void NotifyPaintWorkletStateChange(PaintWorkletState state);

  // Set |needs_begin_main_frame_| to true, which will cause the BeginFrame
  // source to be told to send BeginFrames to this client so that this client
  // can send a CompositorFrame to the display compositor with appropriate
  // timing.
  void SetNeedsBeginMainFrame();
  bool needs_begin_main_frame() const {
    return state_machine_.needs_begin_main_frame();
  }

  // Requests a single impl frame (after the current frame if there is one
  // active).
  void SetNeedsOneBeginImplFrame();

  void SetNeedsRedraw();

  void SetNeedsPrepareTiles();

  // Requests a pending tree should be created to invalidate content on the impl
  // thread, after the current tree is activated, if any. If the request
  // necessitates creating a pending tree only for impl-side invalidations, the
  // |client_| is informed to perform this action using
  // ScheduledActionRunImplSideInvalidation.
  // If ScheduledActionCommit is performed, the impl-side invalidations should
  // be merged with the main frame and the request is assumed to be completed.
  // If |needs_first_draw_on_activation| is set to true, an impl-side pending
  // tree creates for this invalidation must be drawn at least once before a
  // new tree can be activated.
  void SetNeedsImplSideInvalidation(bool needs_first_draw_on_activation);

  // Drawing should result in submitting a CompositorFrame to the
  // LayerTreeFrameSink and then calling this.
  void DidSubmitCompositorFrame(uint32_t frame_token,
                                base::TimeTicks submit_time,
                                EventMetricsSet events_metrics,
                                bool has_missing_content);
  // The LayerTreeFrameSink acks when it is ready for a new frame which
  // should result in this getting called to unblock the next draw.
  void DidReceiveCompositorFrameAck();

  void SetTreePrioritiesAndScrollState(TreePriority tree_priority,
                                       ScrollHandlerState scroll_handler_state);

  // Commit step happens after the main thread has completed updating for a
  // BeginMainFrame request from the compositor, and blocks the main thread
  // to copy the layer tree to the compositor thread. Call this method when the
  // main thread updates are completed to signal it is ready for the commmit.
  void NotifyReadyToCommit(std::unique_ptr<BeginMainFrameMetrics> details);
  void BeginMainFrameAborted(CommitEarlyOutReason reason);
  void DidCommit();

  // In the PrepareTiles step, compositor thread divides the layers into tiles
  // to reduce cost of raster large layers. Then, each tile is rastered by a
  // dedicated thread.
  // |WillPrepareTiles| is called before PrepareTiles step to have the scheduler
  // track when PrepareTiles starts.
  void WillPrepareTiles();
  // |DidPrepareTiles| is called after PrepareTiles step to have the scheduler
  // track how long PrepareTiles takes.
  void DidPrepareTiles();

  // |DidPresentCompositorFrame| is called when the renderer receives
  // presentation feedback.
  void DidPresentCompositorFrame(uint32_t frame_token,
                                 const viz::FrameTimingDetails& details);

  void DidLoseLayerTreeFrameSink();
  void DidCreateAndInitializeLayerTreeFrameSink();

  // Tests do not want to shut down until all possible BeginMainFrames have
  // occured to prevent flakiness.
  bool MainFrameForTestingWillHappen() const {
    return state_machine_.CommitPending() ||
           state_machine_.CouldSendBeginMainFrame();
  }

  bool CommitPending() const { return state_machine_.CommitPending(); }
  bool RedrawPending() const { return state_machine_.RedrawPending(); }
  bool PrepareTilesPending() const {
    return state_machine_.PrepareTilesPending();
  }
  bool ImplLatencyTakesPriority() const {
    return state_machine_.ImplLatencyTakesPriority();
  }

  // Pass in a main_thread_start_time of base::TimeTicks() if it is not
  // known or not trustworthy (e.g. blink is running on a remote channel)
  // to signal that the start time isn't known and should not be used for
  // scheduling or statistics purposes.
  void NotifyBeginMainFrameStarted(base::TimeTicks main_thread_start_time);

  base::TimeTicks LastBeginImplFrameTime();

  // Deferring begin main frame prevents all document lkifecycle updates and
  // updates of new layer tree state.
  void SetDeferBeginMainFrame(bool defer_begin_main_frame);

  // Controls whether the BeginMainFrameNotExpected messages should be sent to
  // the main thread by the cc scheduler.
  void SetMainThreadWantsBeginMainFrameNotExpected(bool new_state);

  void AsProtozeroInto(
      perfetto::EventContext& ctx,
      perfetto::protos::pbzero::ChromeCompositorSchedulerState* state) const;

  void SetVideoNeedsBeginFrames(bool video_needs_begin_frames);

  const viz::BeginFrameSource* begin_frame_source() const {
    return begin_frame_source_;
  }

  viz::BeginFrameAck CurrentBeginFrameAckForActiveTree() const;

  const viz::BeginFrameArgs& last_dispatched_begin_main_frame_args() const {
    return last_dispatched_begin_main_frame_args_;
  }
  const viz::BeginFrameArgs& last_activate_origin_frame_args() const {
    return last_activate_origin_frame_args_;
  }

  void ClearHistory();

  bool IsBeginMainFrameSent() const;

  size_t CommitDurationSampleCountForTesting() const;

 protected:
  // Virtual for testing.
  virtual base::TimeTicks Now() const;

  const SchedulerSettings settings_;
  const raw_ptr<SchedulerClient> client_;
  const int layer_tree_host_id_;
  raw_ptr<base::SingleThreadTaskRunner> task_runner_;

  raw_ptr<viz::BeginFrameSource> begin_frame_source_ = nullptr;
  bool observing_begin_frame_source_ = false;

  bool skipped_last_frame_missed_exceeded_deadline_ = false;

  std::unique_ptr<CompositorTimingHistory> compositor_timing_history_;

  // Owned by LayerTreeHostImpl and is destroyed when LayerTreeHostImpl is
  // destroyed.
  raw_ptr<CompositorFrameReportingController>
      compositor_frame_reporting_controller_;

  // What the latest deadline was, and when it was scheduled.
  base::TimeTicks deadline_;
  base::TimeTicks deadline_scheduled_at_;
  SchedulerStateMachine::BeginImplFrameDeadlineMode deadline_mode_ =
      SchedulerStateMachine::BeginImplFrameDeadlineMode::NONE;

  BeginFrameTracker begin_impl_frame_tracker_;
  viz::BeginFrameAck last_begin_frame_ack_;
  viz::BeginFrameArgs begin_main_frame_args_;

  // For keeping track of the original BeginFrameArgs from the Main Thread
  // that led to the corresponding action, i.e.:
  //    BeginMainFrame => Commit => Activate => Submit
  // So, |last_commit_origin_frame_args_| is the BeginFrameArgs that was
  // dispatched to the main-thread, and lead to the commit to happen.
  // |last_activate_origin_frame_args_| is then set to that BeginFrameArgs when
  // the committed change is activated.
  viz::BeginFrameArgs last_dispatched_begin_main_frame_args_;
  viz::BeginFrameArgs last_commit_origin_frame_args_;
  viz::BeginFrameArgs last_activate_origin_frame_args_;

  // Task posted for the deadline or drawing phase of the scheduler. This task
  // can be rescheduled e.g. when the condition for the deadline is met, it is
  // scheduled to run immediately.
  // NOTE: Scheduler weak ptrs are not necessary if CancelableOnceCallback is
  // used.
  base::DeadlineTimer begin_impl_frame_deadline_timer_;

  // This is used for queueing begin frames while scheduler is waiting for
  // previous frame's deadline, or if it's inside ProcessScheduledActions().
  // Only one such task is posted at any time, but the args are updated as we
  // get new begin frames.
  viz::BeginFrameArgs pending_begin_frame_args_;
  base::CancelableOnceClosure pending_begin_frame_task_;

  SchedulerStateMachine state_machine_;
  bool inside_process_scheduled_actions_ = false;
  bool inside_scheduled_action_ = false;
  SchedulerStateMachine::Action inside_action_ =
      SchedulerStateMachine::Action::NONE;

  bool stopped_ = false;

  bool needs_finish_frame_for_synchronous_compositor_ = false;

  // Keeps track of the begin frame interval from the last BeginFrameArgs to
  // arrive so that |client_| can be informed about changes.
  base::TimeDelta last_frame_interval_;

  std::unique_ptr<power_scheduler::PowerModeVoter> power_mode_voter_;
  power_scheduler::PowerMode last_power_mode_vote_ =
      power_scheduler::PowerMode::kIdle;

 private:
  // Posts the deadline task if needed by checking
  // SchedulerStateMachine::CurrentBeginImplFrameDeadlineMode(). This only
  // happens when the scheduler is processing a begin frame
  // (BeginImplFrameState::INSIDE_BEGIN_FRAME).
  void ScheduleBeginImplFrameDeadline();

  // Starts or stops begin frames as needed by checking
  // SchedulerStateMachine::BeginFrameNeeded(). This only happens when the
  // scheduler is not processing a begin frame (BeginImplFrameState::IDLE).
  void StartOrStopBeginFrames();

  // This will only post a task if the args are valid and there's no existing
  // task. That implies that we're still expecting begin frames. If begin frames
  // aren't needed this will be a nop. This only happens when the scheduler is
  // not processing a begin frame (BeginImplFrameState::IDLE).
  void PostPendingBeginFrameTask();

  // Use |pending_begin_frame_args_| to begin a new frame like it was received
  // in OnBeginFrameDerivedImpl().
  void HandlePendingBeginFrame();

  // Used to drop the pending begin frame before we go idle.
  void CancelPendingBeginFrameTask();

  void BeginMainFrameNotExpectedUntil(base::TimeTicks time);
  void BeginMainFrameNotExpectedSoon();
  void DrawIfPossible();
  void DrawForced();
  void ProcessScheduledActions();
  void UpdateCompositorTimingHistoryRecordingEnabled();
  void AdvanceCommitStateIfPossible();

  void BeginImplFrameWithDeadline(const viz::BeginFrameArgs& args);
  void BeginImplFrameSynchronous(const viz::BeginFrameArgs& args);
  void FinishImplFrameSynchronous();
  void BeginImplFrame(const viz::BeginFrameArgs& args, base::TimeTicks now);
  void FinishImplFrame();
  void SendDidNotProduceFrame(const viz::BeginFrameArgs& args,
                              FrameSkippedReason reason);
  void OnBeginImplFrameDeadline();
  void PollToAdvanceCommitState();
  void BeginMainFrameAnimateAndLayoutOnly(const viz::BeginFrameArgs& args);

  bool IsInsideAction(SchedulerStateMachine::Action action) {
    return inside_action_ == action;
  }

  void UpdatePowerModeVote();

  // Used only for UMa metric calculations.
  base::TimeDelta cc_frame_time_available_;
  base::TimeTicks cc_frame_start_;  // Begin impl frame time.
};

}  // namespace cc

#endif  // CC_SCHEDULER_SCHEDULER_H_


text:
import './context'
import './events'
import './lazyload'
import './lifecycle'
import './link'
import './render'


text:
RSpec.describe TimeInterval do
  describe '.parse' do
    context 'iso8601 is a valid time and duration' do
      let(:iso8601) { '2007-03-01T13:00:00Z/P1M' }

      it 'should return a TimeWithDuration' do
        expect(TimeInterval.parse(iso8601)).to be_a TimeWithDuration
      end
    end

    context 'iso8601 is a valid time pair' do
      let(:iso8601) { '2007-03-01T13:00:00Z/2008-05-11T15:30:00Z' }

      it 'should return a TimePair' do
        expect(TimeInterval.parse(iso8601)).to be_a TimePair
      end
    end

    context 'iso8601 is a valid repeating interval' do
      let(:iso8601) { 'R/2007-03-01T13:00:00Z/P1M' }

      it 'should return a RepeatingInterval' do
        expect(TimeInterval.parse(iso8601)).to be_a RepeatingInterval
      end
    end

    context 'iso8601 is not an interval' do
      let(:iso8601) { '2007-03-01T13:00:00Z' }

      it 'should return a TimePair with no duration' do
        parsed = TimeInterval.parse(iso8601)

        expect(parsed).to be_a TimePair
        expect(parsed.start_time).to eq parsed.end_time
      end
    end
  end
end


text:
set -o errexit
set -o nounset

#---------------------------------------------------------------------#
## Check dependencies
# GIT setup
hash git 2>/dev/null || { echo >&2 "There is no local installation of GIT available. Script cannot be executed."; exit 0; }
# Define or locate property list to update
# If the PList is not available at the target location, it will be created.
GIT_INFO_LIST="${PROJECT_DIR}/GIT-Info.plist"
PROJECT_INFO_LIST="${TARGET_BUILD_DIR}/${INFOPLIST_PATH}"

# Define the branch to use, this should be master in almost every usecase.
TARGET_BRANCH="master"

#---------------------------------------------------------------------#
## Execute GIT information fetch
LATEST_TAG=$(git describe --tags --match 'v*' --abbrev=0 2>/dev/null) || LATEST_TAG="HEAD"
MOST_RECENT_VERSION_TAG=$(git describe --abbrev=0 --tags)
REVISION_HASH_HEAD=$(git rev-parse HEAD)
CURRENT_BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
LAST_COMMIT=$(git log -1 --pretty=format:"%h - %an, %ar : %s")

COMMIT_COUNT_SINCE_TAG=0

#---------------------------------------------------------------------#
## Current branch: Calculate amount commits since most recent tag.
if [ $LATEST_TAG == "HEAD" ]
then COMMIT_COUNT=$(git rev-list --count HEAD)
LATEST_TAG="0.$COMMIT_COUNT"
COMMIT_COUNT_SINCE_TAG=0
else
COMMIT_COUNT_SINCE_TAG=$(git rev-list --count ${LATEST_TAG}..)
fi

## Calculate overall amount of commits in current branch & master branch
if [ $(git rev-parse --abbrev-ref HEAD) = master ]; then
TARGET_BRANCH_COMMIT_COUNT=$(git rev-list --count HEAD)
BRANCH_COMMIT_COUNT=0
else
##TARGET_BRANCH_COMMIT_COUNT=$(git rev-list --count $(git rev-list master.. | tail -n 1)^)
BRANCH_COMMIT_COUNT=$(git rev-list --count $CURRENT_BRANCH_NAME..)
TARGET_BRANCH_COMMIT_COUNT=$(git rev-list --count master..)
fi

#---------------------------------------------------------------------#
## Generate Full Version Definition - this differs from Project to Project, adjust as you like.
FULL_VERSION="$MOST_RECENT_VERSION_TAG.$TARGET_BRANCH_COMMIT_COUNT"

#---------------------------------------------------------------------#
## Debug the information to the console
echo ""
echo "--------------------- GIT Bash Script - PList Updater ---------------------"
echo "LATEST_TAG:                   $LATEST_TAG"
echo "MOST_RECENT_VERSION_TAG:      $MOST_RECENT_VERSION_TAG"
echo "REVISION_HASH_HEAD:           $REVISION_HASH_HEAD"
echo "TARGET_BRANCH:                $TARGET_BRANCH"
echo "CURRENT_BRANCH_NAME:          $CURRENT_BRANCH_NAME"
echo "LAST_COMMIT:                  $LAST_COMMIT"
echo "TARGET_BRANCH_COMMIT_COUNT:   $TARGET_BRANCH_COMMIT_COUNT"
echo "BRANCH_COMMIT_COUNT:          $BRANCH_COMMIT_COUNT"
echo "---------------------------------------------------------------------------"

#---------------------------------------------------------------------#
## Save for future use
/usr/libexec/PlistBuddy -c "Add :GITVersionTag string $MOST_RECENT_VERSION_TAG" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITVersionTag $MOST_RECENT_VERSION_TAG" "$GIT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :GITRevisionHash string $REVISION_HASH_HEAD" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITRevisionHash $REVISION_HASH_HEAD" "$GIT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :GITMasterCommitCount string $TARGET_BRANCH_COMMIT_COUNT" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITMasterCommitCount $TARGET_BRANCH_COMMIT_COUNT" "$GIT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :GITCurrentBranchName string $CURRENT_BRANCH_NAME" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITCurrentBranchName $CURRENT_BRANCH_NAME" "$GIT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :GITCurrentBranchCommitCount string $BRANCH_COMMIT_COUNT" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITCurrentBranchCommitCount $BRANCH_COMMIT_COUNT" "$GIT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :GITLastCommitLog string $LAST_COMMIT" "$GIT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :GITLastCommitLog $LAST_COMMIT" "$GIT_INFO_LIST"

## Update iOS Properties
/usr/libexec/PlistBuddy -c "Add :CFBundleShortVersionString string $MOST_RECENT_VERSION_TAG" "$PROJECT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $MOST_RECENT_VERSION_TAG" "$PROJECT_INFO_LIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleVersion string $FULL_VERSION" "$PROJECT_INFO_LIST" 2>/dev/null || /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $FULL_VERSION" "$PROJECT_INFO_LIST"


text:
"""Bridge to Java virtual machine

.. module:: bridge.java
   :platform: Unix
   :synopsis: Bridge to Java virtual machine
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>

"""

"""
Events:
-------
java_before_start
java_after_start
java_before_stop
java_after_stop

"""

from hydratk.core.masterhead import MasterHead
from hydratk.core import event
import hydratk.lib.system.config as syscfg
from os import path, walk

try:
    from jpype import JByte, JShort, JInt, JLong, JFloat, JDouble, JChar, JString, JBoolean
    from jpype import get_default_jvm_path, isJVMStarted, startJVM, shutdownJVM, JavaException
    from jpype import JClass, JPackage
except ImportError:
    raise NotImplementedError('Java bridge is not supported for PyPy')

java_types = {
    'byte': JByte,
    'short': JShort,
    'int': JInt,
    'long': JLong,
    'float': JFloat,
    'double': JDouble,
    'char': JChar,
    'string': JString,
    'bool': JBoolean
}

class JavaBridge(object):
    """Class JavaBridge
    """

    _mh = None
    _jvm_path = None
    _classpath = None
    _status = None

    def __init__(self, jvm_path=None, classpath=None):
        """Class constructor

        Called when the object is initialized

        Args:
           jvm_path (str): JVM location, default from configuration
           classpath (str): Java classpath, default from configuration

        """

        self._mh = MasterHead.get_head()
        self._mh.find_module('hydratk.lib.bridge.java', None)

        if (jvm_path != None):
            self._jvm_path = jvm_path
        else:
            cfg = self._mh.cfg['Libraries']['hydratk.lib.bridge.java']['jvm_path']
            self._jvm_path = cfg if (cfg != 'default') else get_default_jvm_path()

        self._classpath = self._set_classpath(classpath)

    @property
    def jvm_path(self):
        """ JVM path property getter """

        return self._jvm_path

    @property
    def classpath(self):
        """ JVM classpath property getter """

        return self._classpath

    @property
    def status(self):
        """ JVM status property getter """

        return self._status

    def start(self, options=[]):
        """Method starts JVM

        Args:
           options (list): JVM options

        Returns:
           bool: result

        Raises:
           event: java_before_start
           event: java_after_start

        """

        try:

            if (self._status):
                self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                    'htk_java_already_started'), self._mh.fromhere())
                return True
            elif (isJVMStarted()):
                self._mh.demsg('htk_on_warning', self._mh._trn.msg(
                    'htk_java_restart_tried'), self._mh.fromhere())
                return False

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg('htk_java_starting_jvm', self._jvm_path,
                                                                 self.classpath, options), self._mh.fromhere())

            ev = event.Event('java_before_start', options)
            if (self._mh.fire_event(ev) > 0):
                options = ev.argv(0)

            if (ev.will_run_default()):
                if (self._classpath != None):
                    options.append(
                        '-Djava.class.path={0}'.format(self._classpath))

                startJVM(self._jvm_path, *options)

                self._status = True
                result = True

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_java_started'), self._mh.fromhere())
            ev = event.Event('java_after_start')
            self._mh.fire_event(ev)

            return result

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def stop(self):
        """Method stops JVM

        Args:
           none

        Returns:
           bool: result

        Raises:
           event: java_before_stop
           event: java_after_stop

        """

        try:

            if (not self._status):
                self._mh.demsg('htk_on_warning', self._mh._trn.msg(
                    'htk_java_not_started'), self._mh.fromhere())
                return False

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_java_stopping_jvm'), self._mh.fromhere())
            ev = event.Event('java_before_stop')
            self._mh.fire_event(ev)

            shutdownJVM()
            self._status = False
            result = True

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_java_stopped'), self._mh.fromhere())
            ev = event.Event('java_after_stop')
            self._mh.fire_event(ev)

            return result

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def get_var(self, datatype, value):
        """Method creates Java variable

        Args:
           datatype (str): byte|short|int|long|float|double|char|string|bool
           value (str): initial value

        Returns:
           obj: Java variable

        """

        try:

            if (datatype not in java_types):
                self._mh.demsg('htk_on_error', self._mh._trn.msg(
                    'htk_java_unknown_type', datatype), self._mh.fromhere())
                return None
            else:
                return java_types[datatype](value)

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def get_class(self, name, *attrs):
        """Method creates Java class instance

        Args:
           name (str): class name
           attrs (args): constructor attributes

        Returns:
           obj: class instance

        """

        try:

            return JClass(name)(*attrs)

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def desc_class(self, name):
        """Method describes Java class

        Args:
           name (str): class name

        Returns:
           tuple: attribute names, method names

        """

        try:

            attrs = []
            methods = []

            for name, type in JClass(name).__dict__.items():
                if (type.__class__.__name__ == 'property'):
                    attrs.append(name)
                elif (type.__class__.__name__ == 'JavaMethod'):
                    methods.append(name)

            return attrs, methods

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def get_package(self, name):
        """Method returns package

        Args:
           name (str): package name

        Returns:
           obj: method

        """

        try:

            package = JPackage(name)
            return package

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def init_arraylist(self, array):
        """Method initializes Java ArrayList

        Args:
           list (list): Python list

        Returns:
           obj: Java ArrayList

        """

        try:

            arraylist = self.get_class('java.util.ArrayList')
            for value in array:
                arraylist.add(str(value))

            return arraylist

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def init_hashmap(self, dictionary):
        """Method initializes Java HashMap

        Args:
           dictionary (dict): Python dictionary

        Returns:
           obj: Java HashMap

        """

        try:

            hashmap = self.get_class('java.util.concurrent.ConcurrentHashMap')
            for key, value in dictionary.items():
                hashmap.put(str(key), str(value))

            return hashmap

        except (RuntimeError, JavaException) as ex:
            self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
            return None

    def _set_classpath(self, classpath=None):
        """Method sets classpath

        Args:
           classpath (str): path to be appended to configured classpath

        Returns:
           str: classpath

        """

        cfg = self._mh.cfg['Libraries']['hydratk.lib.bridge.java']['classpath'].format(var_dir=syscfg.HTK_VAR_DIR)
        if (classpath != None):
            cfg += ':' + classpath

        exp_classpath = ''
        for entry in cfg.split(':'):

            if (path.isfile(entry)):
                exp_classpath += entry + ':'
            else:

                for dirname, _, filelist in walk(entry):
                    exp_classpath += dirname + ':'
                    for filename in filelist:
                        if (filename.split('.')[-1] == 'jar'):
                            exp_classpath += path.join(dirname, filename) + ':'

        return exp_classpath[:-1]