text:
#include "tensorflow/compiler/xla/service/hlo_cost_analysis.h"

#include <cmath>

#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/bits.h"
#include "tensorflow/core/lib/core/errors.h"

namespace xla {

Status HloCostAnalysis::Preprocess(HloInstruction* hlo) {
  // Set current instruction cost values to reasonable default values. Each
  // handler can overwrite these values. In Postprocess, these value are
  // accumulated and written to the per-instruction maps.
  current_flop_count_ = 0;
  current_transcendental_count_ = 0;

  // The default element count for an instruction is the sum of elements in the
  // operands and output. The default ShapeUtil::ByteSizeOf does not handle
  // opaque types.
  current_bytes_accessed_ = shape_size_(hlo->shape());
  for (const HloInstruction* operand : hlo->operands()) {
    current_bytes_accessed_ += shape_size_(operand->shape());
  }

  return Status::OK();
}

Status HloCostAnalysis::Postprocess(HloInstruction* hlo) {
  // Accumulate cost values and write into per-instruction maps.
  flop_count_ += current_flop_count_;
  hlo_to_flop_count_[hlo] = current_flop_count_;

  transcendental_count_ += current_transcendental_count_;
  hlo_to_transcendental_count_[hlo] = current_transcendental_count_;

  bytes_accessed_ += current_bytes_accessed_;
  hlo_to_bytes_accessed_[hlo] = current_bytes_accessed_;

  return Status::OK();
}

Status HloCostAnalysis::HandleElementwiseOp(HloInstruction* hlo_instruction) {
  const auto& shape = hlo_instruction->shape();
  // For element-wise operations, the number of computations is the same as the
  // number of elements in the output shape.
  auto computation_count = ShapeUtil::ElementsIn(shape);
  auto opcode = hlo_instruction->opcode();
  // We treat the two opcodes (kExp, kPower) as transcendental operations.
  if (opcode == HloOpcode::kExp || opcode == HloOpcode::kPower) {
    current_transcendental_count_ = computation_count;
  } else {
    // Note: transcendental operations are considered a separate category from
    // FLOPs.
    current_flop_count_ = computation_count;
  }
  return Status::OK();
}

Status HloCostAnalysis::HandleElementwiseUnary(HloInstruction* hlo,
                                               HloOpcode opcode,
                                               HloInstruction* operand) {
  return HandleElementwiseOp(hlo);
}

Status HloCostAnalysis::HandleElementwiseBinary(HloInstruction* hlo,
                                                HloOpcode opcode,
                                                HloInstruction* lhs,
                                                HloInstruction* rhs) {
  return HandleElementwiseOp(hlo);
}

Status HloCostAnalysis::HandleCompare(HloInstruction* compare, HloOpcode opcode,
                                      HloInstruction* lhs,
                                      HloInstruction* rhs) {
  return HandleElementwiseOp(compare);
}

Status HloCostAnalysis::HandleClamp(HloInstruction* clamp,
                                    HloInstruction* min_instruction,
                                    HloInstruction* arg_instruction,
                                    HloInstruction* max_instruction) {
  return HandleElementwiseOp(clamp);
}

Status HloCostAnalysis::HandleParameter(HloInstruction* parameter) {
  current_bytes_accessed_ = 0;
  return Status::OK();
}

Status HloCostAnalysis::HandleConstant(HloInstruction* constant,
                                       const Literal& literal) {
  current_bytes_accessed_ = 0;
  return Status::OK();
}

Status HloCostAnalysis::HandleGetTupleElement(HloInstruction* get_tuple_element,
                                              HloInstruction* operand) {
  // GetTupleElement forwards a pointer and does not touch each element in the
  // output.
  current_bytes_accessed_ = 0;
  return Status::OK();
}

Status HloCostAnalysis::HandleSelect(HloInstruction* select,
                                     HloInstruction* pred,
                                     HloInstruction* on_true,
                                     HloInstruction* on_false) {
  return Status::OK();
}

Status HloCostAnalysis::HandleReverse(HloInstruction* reverse,
                                      HloInstruction* operand_instruction) {
  return Status::OK();
}

Status HloCostAnalysis::HandleSlice(HloInstruction* slice,
                                    HloInstruction* operand_instruction) {
  return Status::OK();
}

Status HloCostAnalysis::HandleDynamicSlice(
    HloInstruction* slice,
    tensorflow::gtl::ArraySlice<HloInstruction*> operands) {
  return Status::OK();
}

Status HloCostAnalysis::HandleDynamicUpdateSlice(
    HloInstruction* dynamic_update, HloInstruction* operand,
    HloInstruction* update, HloInstruction* start_indices) {
  return Status::OK();
}

Status HloCostAnalysis::HandleTuple(
    HloInstruction* tuple,
    tensorflow::gtl::ArraySlice<HloInstruction*> operands) {
  // The tuple instruction only gathers pointers from inputs (it doesn't iterate
  // through them). The memory touched is then only the size of the output
  // buffer.
  current_bytes_accessed_ = shape_size_(tuple->shape());
  return Status::OK();
}

Status HloCostAnalysis::HandleConcatenate(
    HloInstruction* concatenate,
    tensorflow::gtl::ArraySlice<HloInstruction*> operands) {
  return Status::OK();
}

Status HloCostAnalysis::HandleConvert(HloInstruction* convert,
                                      HloInstruction* operand) {
  return HandleElementwiseOp(convert);
}

Status HloCostAnalysis::HandleCopy(HloInstruction* copy,
                                   HloInstruction* operand) {
  return Status::OK();
}

Status HloCostAnalysis::HandleDot(HloInstruction* dot,
                                  HloInstruction* lhs_instruction,
                                  HloInstruction* rhs_instruction) {
  const Shape& lhs_shape = lhs_instruction->shape();
  const Shape& rhs_shape = rhs_instruction->shape();
  // Count of elements along the reduction dimension (last dimension for the
  // rhs).
  int64 reduction_width = lhs_shape.dimensions(ShapeUtil::Rank(lhs_shape) - 1);

  // First divide by reduction width before multiplying by rhs elements to avoid
  // overflow.
  int64 fma_count;
  if (reduction_width == 0) {
    fma_count = 0;
  } else {
    fma_count = (ShapeUtil::ElementsIn(lhs_shape) / reduction_width) *
                ShapeUtil::ElementsIn(rhs_shape);
  }

  // We count an FMA operation as 2 floating point operations.
  current_flop_count_ = kFmaFlops * fma_count;
  return Status::OK();
}

Status HloCostAnalysis::HandleInfeed(HloInstruction* infeed) {
  return Status::OK();
}

Status HloCostAnalysis::HandleOutfeed(HloInstruction* outfeed) {
  return Status::OK();
}

Status HloCostAnalysis::HandleMap(
    HloInstruction* map, tensorflow::gtl::ArraySlice<HloInstruction*> operands,
    HloComputation* function,
    tensorflow::gtl::ArraySlice<HloInstruction*> /*static_operands*/) {
  // Compute the cost of the user function.
  HloInstruction* function_instruction = function->root_instruction();
  HloCostAnalysis visitor(shape_size_);
  TF_RETURN_IF_ERROR(function_instruction->Accept(&visitor));

  // Compute the cost of all elements for this Map operation.
  int64 element_count = ShapeUtil::ElementsIn(map->shape());
  current_transcendental_count_ =
      element_count * visitor.transcendental_count();
  current_flop_count_ = element_count * visitor.flop_count();
  return Status::OK();
}

Status HloCostAnalysis::HandleReduce(
    HloInstruction* reduce, HloInstruction* arg, HloInstruction* init_value,
    tensorflow::gtl::ArraySlice<int64> dimensions, HloComputation* function) {
  // Compute the cost of the user function.
  HloInstruction* function_instruction = function->root_instruction();
  HloCostAnalysis visitor(shape_size_);
  TF_RETURN_IF_ERROR(function_instruction->Accept(&visitor));

  // Compute the cost of all elements for this Reduce operation.
  int64 reduction_count = ShapeUtil::ElementsIn(arg->shape()) -
                          ShapeUtil::ElementsIn(reduce->shape());
  current_flop_count_ = reduction_count * visitor.flop_count();
  current_transcendental_count_ =
      reduction_count * visitor.transcendental_count();
  return Status::OK();
}

Status HloCostAnalysis::HandleReduceWindow(HloInstruction* reduce_window,
                                           HloInstruction* operand,
                                           const Window& window,
                                           HloComputation* function) {
  // Compute the cost of the user function.
  HloInstruction* function_instruction = function->root_instruction();
  HloCostAnalysis visitor(shape_size_);
  TF_RETURN_IF_ERROR(function_instruction->Accept(&visitor));

  // Compute the cost of all elements for this ReduceWindow operation. For each
  // output element, (window_size - 1) number of user computations are applied.
  auto output_size = ShapeUtil::ElementsIn(reduce_window->shape());
  int64 window_size = 1;
  for (const auto& dimension : window.dimensions()) {
    window_size *= dimension.size();
  }
  current_flop_count_ = output_size * (window_size - 1) * visitor.flop_count();
  current_transcendental_count_ =
      output_size * (window_size - 1) * visitor.transcendental_count();
  return Status::OK();
}

Status HloCostAnalysis::HandleSelectAndScatter(HloInstruction* instruction) {
  // Compute the cost of the select and scatter function.
  HloInstruction* select = instruction->select()->root_instruction();
  HloCostAnalysis select_visitor(shape_size_);
  TF_RETURN_IF_ERROR(select->Accept(&select_visitor));
  HloInstruction* scatter = instruction->scatter()->root_instruction();
  HloCostAnalysis scatter_visitor(shape_size_);
  TF_RETURN_IF_ERROR(scatter->Accept(&scatter_visitor));

  // Compute the cost of all elements for this operation. For each scatter
  // source element, (window_size - 1) number of select computations and 1
  // scatter computation are applied.
  const auto source = instruction->operand(1);
  const auto source_element_count = ShapeUtil::ElementsIn(source->shape());
  int64 window_size = 1;
  for (const auto& dimension : instruction->window().dimensions()) {
    window_size *= dimension.size();
  }
  current_flop_count_ =
      source_element_count * ((window_size - 1) * select_visitor.flop_count() +
                              scatter_visitor.flop_count());
  current_transcendental_count_ =
      source_element_count *
      ((window_size - 1) * select_visitor.transcendental_count() +
       scatter_visitor.transcendental_count());
  return Status::OK();
}

Status HloCostAnalysis::HandleBitcast(HloInstruction* bitcast) {
  // A bitcast does no computation and touches no memory.
  current_bytes_accessed_ = 0;
  return Status::OK();
}

Status HloCostAnalysis::HandleBroadcast(HloInstruction* broadcast) {
  return Status::OK();
}

Status HloCostAnalysis::HandlePad(HloInstruction* pad) { return Status::OK(); }

Status HloCostAnalysis::HandleSend(HloInstruction* send) {
  return Status::OK();
}

Status HloCostAnalysis::HandleRecv(HloInstruction* recv) {
  return Status::OK();
}

Status HloCostAnalysis::HandleReshape(HloInstruction* reshape) {
  return Status::OK();
}

Status HloCostAnalysis::HandleTranspose(HloInstruction* transpose) {
  return Status::OK();
}

Status HloCostAnalysis::HandleConvolution(HloInstruction* convolution,
                                          HloInstruction* lhs_instruction,
                                          HloInstruction* rhs_instruction,
                                          const Window& window) {
  const auto& dnums = convolution->convolution_dimension_numbers();
  const int64 output_features =
      convolution->shape().dimensions(dnums.feature_dimension());

  // For each output element, we do one fma per element in the
  // kernel at some given output feature index.
  const int64 fmas_per_output_element =
      ShapeUtil::ElementsIn(rhs_instruction->shape()) / output_features;
  const int64 output_elements = ShapeUtil::ElementsIn(convolution->shape());
  current_flop_count_ = output_elements * fmas_per_output_element * kFmaFlops;
  return Status::OK();
}

Status HloCostAnalysis::HandleCrossReplicaSum(HloInstruction* crs) {
  // We assume 2 replicas, so that each output element is the sum of two input
  // elements.
  //
  // TODO(b/33004697): Compute correct cost here, taking the actual number of
  // replicas into account.
  current_flop_count_ = ShapeUtil::ElementsIn(crs->shape());
  return Status::OK();
}

Status HloCostAnalysis::HandleRng(HloInstruction* random,
                                  RandomDistribution distribution) {
  // TODO(b/26346211): Implement better estimates for the RNG cost, since the
  // cost changes with the implementation and the distribution. For now, assume
  // the cost of each RNG is same as a transcendental operation.
  current_transcendental_count_ = ShapeUtil::ElementsIn(random->shape());
  return Status::OK();
}

Status HloCostAnalysis::HandleFusion(HloInstruction* fusion) {
  // Compute the cost of the fused expression.
  HloInstruction* fused_expression_root = fusion->fused_expression_root();
  HloCostAnalysis visitor(shape_size_);
  TF_RETURN_IF_ERROR(fused_expression_root->Accept(&visitor));

  // Attribute the cost of the fused expression to the fusion node.
  current_transcendental_count_ = visitor.transcendental_count();
  current_flop_count_ = visitor.flop_count();
  return Status::OK();
}

Status HloCostAnalysis::HandleCall(
    HloInstruction* call, tensorflow::gtl::ArraySlice<HloInstruction*> operands,
    HloComputation* computation) {
  return Unimplemented("call");
}

Status HloCostAnalysis::HandleCustomCall(
    HloInstruction* custom_call,
    tensorflow::gtl::ArraySlice<HloInstruction*> operands,
    tensorflow::StringPiece custom_call_target) {
  return Unimplemented("custom-call");
}

Status HloCostAnalysis::HandleSort(HloInstruction* sort,
                                   HloInstruction* operand_instruction) {
  // The cost of sort is implementation dependent, so cannot determine at HLO
  // level. Assume comparison based N*log(N) sorting.
  int64 elements = ShapeUtil::ElementsIn(operand_instruction->shape());
  current_flop_count_ = elements * tensorflow::Log2Ceiling(elements);
  return Status::OK();
}

Status HloCostAnalysis::HandleWhile(HloInstruction* xla_while,
                                    HloInstruction* init,
                                    HloComputation* condition,
                                    HloComputation* body) {
  // Since the number of iterations of the while node is not statically
  // determined, we cannot precisely compute the cost of a while node. For now
  // compute the cost of a single iteration.
  // TODO(b/26346211): Improve the cost analysis for while node.
  HloCostAnalysis body_visitor(shape_size_);
  TF_RETURN_IF_ERROR(body->Accept(&body_visitor));
  HloCostAnalysis condition_visitor(shape_size_);
  TF_RETURN_IF_ERROR(condition->Accept(&condition_visitor));

  current_flop_count_ =
      body_visitor.flop_count() + condition_visitor.flop_count();
  current_transcendental_count_ = body_visitor.transcendental_count() +
                                  condition_visitor.transcendental_count();
  current_bytes_accessed_ =
      body_visitor.bytes_accessed() + condition_visitor.bytes_accessed();

  return Status::OK();
}

Status HloCostAnalysis::FinishVisit(HloInstruction* root) {
  return Status::OK();
}

int64 HloCostAnalysis::flop_count(const HloInstruction& hlo) const {
  auto it = hlo_to_flop_count_.find(&hlo);
  return it == hlo_to_flop_count_.end() ? 0 : it->second;
}

int64 HloCostAnalysis::transcendental_count(const HloInstruction& hlo) const {
  auto it = hlo_to_transcendental_count_.find(&hlo);
  return it == hlo_to_transcendental_count_.end() ? 0 : it->second;
}

int64 HloCostAnalysis::bytes_accessed(const HloInstruction& hlo) const {
  auto it = hlo_to_bytes_accessed_.find(&hlo);
  return it == hlo_to_bytes_accessed_.end() ? 0 : it->second;
}

}  // namespace xla

redpajama_set_name: RedPajamaGithub


text:
RSpec::Matchers.define :a_monitor_with do |name, refresh_interval|
  match do |actual_monitor|
    actual % expected == 0
  end

  chain :of_type_build do
    @monitor_type = 1
  end
end


text:
var profanityFilter = require('../index');
var assert = require('assert');

describe('ProfanityFilter', function() {
  describe('filter', function() {
    it('Should replace swear words with asterisks.', function() {
      assert.equal("**** you!", profanityFilter.filter("Fuck you!"));
    });
  });
  describe('addWords', function() {
    it('Should add words to the current bad words list.', function() {
      profanityFilter.addWords(["add", "custom", "words"]);
      assert.equal("These are ****** bad *****.", profanityFilter.filter("These are custom bad words."));
      assert.equal("Old one still ****ing works.", profanityFilter.filter("Old one still fucking works."));
    });
  });
  describe('replaceWords', function() {
    it('Should replace bad words list with input array.', function() {
      profanityFilter.replaceWords(["add", "custom", "words"]);
      assert.equal("These are ****** bad *****.", profanityFilter.filter("These are custom bad words."));
      assert.equal("Old one no longer fucking works.", profanityFilter.filter("Old one no longer fucking works."));
    });
  });
});


text:
module IconsHelper
  def icon_tags
    regular_icon_tags +
      apple_icon_tags +
      windows_icon_tags
  end

  private

  def favicon_tag(path, type)
    tag(:link, rel: "icon", href: image_path(path), type: type)
  end

  def regular_icon_tags
    favicon_tag("icons/favicon.ico", "image/x-icon") +
      favicon_tag("icons/favicon.png", "image/png")
  end

  def apple_icon_tags
    safe_join(%w(57 72 114 144 60 120 76 152).map do |s|
      tag(:link,
          rel: "apple-touch-icon-precomposed",
          sizes: "#{s}x#{s}",
          href: image_path("icons/apple-touch-icon-#{s}x#{s}.png"))
    end)
  end

  def windows_icon_tags
    safe_join({
      smalltile: "square70x70logo",
      mediumtile: "square150x150logo",
      widetile: "wide310x150logo",
      largetile: "square310x310logo"
    }.map do |f, n|
      tag(:meta,
          name: "msapplication-#{n}",
          content: image_path("icons/#{f}.png"))
    end)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"

    card_view:cardPreventCornerOverlap="false"
    card_view:cardBackgroundColor="@android:color/transparent"

    android:paddingBottom="@dimen/slice_align"

    android:layout_marginStart="2dp"
    android:layout_marginEnd="2dp"

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

<LinearLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:paddingTop="@dimen/round_padding"
    android:paddingBottom="@dimen/round_padding"
    android:paddingStart="@dimen/slice_align"
    android:paddingEnd="@dimen/slice_align"

    android:background="@color/angel_white"
    android:orientation="vertical">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/round_padding"

            android:gravity="left"

            android:id="@+id/sku"

            android:text="MES102BGT6"

            android:textColor="@color/supreme_blue"
            android:textSize="23sp"/>

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

            android:orientation="horizontal"
            android:gravity="right">

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

                android:visibility="gone"

                android:id="@+id/sell_out_bar"

                android:layout_gravity="center_vertical"

                android:layout_marginEnd="@dimen/slice_align">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:text="ยอดขาย"
                    android:textColor="@color/lemon_resonance_structure"
                    android:textSize="@dimen/font_text_view"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:layout_marginStart="@dimen/round_padding"
                    android:layout_marginEnd="@dimen/round_padding"

                    android:id="@+id/XBar"

                    android:text="35"
                    android:textColor="@color/stone_gray"
                    android:textSize="@dimen/font_text_view"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:text="@string/currency_piece_th"
                    android:textColor="@color/lemon_resonance_structure"
                    android:textSize="@dimen/font_text_view"/>
            </LinearLayout>

            <Button
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:layout_gravity="center"

                android:background="@drawable/ic_chevron_right_gray_24dp"

                android:id="@+id/more_info"
                style="@style/Base.Widget.AppCompat.Button.Borderless" />
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"

        android:paddingTop="@dimen/slice_align"
        android:paddingStart="@dimen/round_padding"

        android:layout_marginEnd="@dimen/slice_align">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center_vertical|left">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:text="สต็อก"
                    android:textColor="@color/lemon_resonance_structure"
                    android:textSize="@dimen/font_text_view"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:layout_marginStart="@dimen/round_padding"
                    android:layout_marginEnd="@dimen/round_padding"

                    android:id="@+id/storage"

                    android:text="35"
                    android:textColor="@color/stone_gray"
                    android:textSize="@dimen/font_text_view"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:id="@+id/unit"

                    android:text="@string/currency_piece_th"
                    android:textColor="@color/lemon_resonance_structure"
                    android:textSize="@dimen/font_text_view"/>

            </LinearLayout>

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

                android:orientation="horizontal"
                android:gravity="right">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:textSize="@dimen/font_text_view"
                    android:textColor="@color/rising_green"
                    android:text="Day Cover " />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:layout_marginStart="@dimen/round_padding"
                    android:layout_marginEnd="@dimen/round_padding"

                    android:id="@+id/day_cover"

                    android:textSize="@dimen/font_text_view"

                    android:textColor="@color/stone_gray"
                    android:text="999,999" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"

                    android:id="@+id/unit_day_cover"

                    android:text="@string/currency_date_th"
                    android:textColor="@color/lemon_resonance_structure"
                    android:textSize="@dimen/font_text_view"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>


text:
[Deploy Tracker](http://libraries.io/rubygems/deploytracking)
==============

Capistrano plugin for <http://deploytracking.com>

[![Gem Version](https://badge.fury.io/rb/deploytracking.png)](http://badge.fury.io/rb/deploytracking)
[![Build Status](https://secure.travis-ci.org/andrew/deploytracking.png?branch=master)](http://travis-ci.org/andrew/deploytracking)
[![Dependency Status](https://gemnasium.com/andrew/deploytracking.png)](https://gemnasium.com/andrew/deploytracking)
[![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/andrew/deploytracking)
Install
---------------

In your Gemfile add:

```ruby
gem 'deploytracking'
```

Place the following line at the bottom config/deploy.rb:

```ruby
set :deploy_tracking_api_key, 'YOURAPIKEY'
require 'deploytracking/capistrano'
```

Then run:

```bash
bundle install
```

Note on Patches/Pull Requests
-----------------------------

 * Fork the project.
 * Make your feature addition or bug fix.
 * Add tests for it. This is important so I don't break it in a
   future version unintentionally.
 * Commit, do not mess with rakefile, version, or history.
   (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
 * Send me a pull request. Bonus points for topic branches.

Copyright
---------

Copyright (c) 2013 Andrew Nesbitt. See LICENSE for details.


text:
function [A] = cm2A(cm)
% Convert length from centimeters to angstroms.
% Chad A. Greene 2012
A = cm*100000000;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Platymiscium nigrum Ducke

### Remarks
null


text:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
    <ActionBar title="Party Map" class="actionBar">
        <ActionBar.titleView>
            <StackLayout orientation="horizontal">
                <Button text="Add Party"  tap="{{ addParty }}" />
                <Button text="All Parties"  tap="{{ allParties }}" />
            </StackLayout>
        </ActionBar.titleView>
    </ActionBar>
    <StackLayout>
        <ActivityIndicator busy="{{ isLoading }}" verticalAlignment="center" horizontalAlignment="center"/>
        <ListView id="partiesList" items="{{ parties }}" >
            <ListView.itemTemplate>
                <GridLayout rows="1*, 1*" cssClass="big" columns="*, auto">
                    <Label row="0" text="{{ $value.Name }}" />
                    <Image src="~/images/DeleteRed.png" col="1" tap="delete" class="delete"/>
                </GridLayout>
            </ListView.itemTemplate>
        </ListView>
    </StackLayout>
</Page>


text:
import { bindable, observable, View } from 'aurelia-framework';
import { GameOfLife, Cell } from './game-of-life';

export class GameOfLifeGame {
  @observable
  size: string = "50";
  @observable({ changeHandler: 'delayOrRunChanged' })
  run: boolean = false;
  @observable({ changeHandler: 'delayOrRunChanged' })
  delay: string = "30";
  @observable({ changeHandler: 'drawCanvas' })
  cellSize: string = "8";

  @observable({ changeHandler: 'drawCanvas' })
  displayCanvas: boolean = true;
  displayTable: boolean = false;

  canvas: HTMLCanvasElement;

  game: GameOfLife;

  private intervalId: number | null = null;

  constructor() {
    this.sizeChanged();
  }

  attached() {
    this.drawCanvas();
  }

  detached() {
    this.clearInterval();
  }

  sizeChanged() {
    const oldGame = this.game;
    const size = +this.size;
    this.game = new GameOfLife(size, size);
    if (oldGame) {
      this.game.wrapAround = oldGame.wrapAround;
      this.game.copyStateFrom(oldGame);
    }
    this.drawCanvas();
  }

  private clearInterval() {
    if (this.intervalId !== null) {
      window.clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }

  delayOrRunChanged() {
    this.clearInterval();
    if (this.run) {
      this.intervalId = window.setInterval(() => this.nextState(), this.delay);
    }
  }

  toggleRun() {
    this.run = !this.run;
  }

  nextState() {
    this.game.nextState();
    this.drawCanvas();
  }

  randomizeCells(probability: number) {
    this.game.randomizeCells(probability);
    this.drawCanvas();
  }

  click(cell: Cell) {
    cell.alive = !cell.alive;
    this.drawCanvas();
  }

  clickCanvas(e: MouseEvent) {
    const cellSize = +this.cellSize;
    const clientRect = this.canvas.getBoundingClientRect();
    const x = Math.floor((e.clientX - clientRect.left) / cellSize);
    const y = Math.floor((e.clientY - clientRect.top) / cellSize);
    const cell = this.game.cell(x, y);
    if (cell) {
      this.click(cell);
    }
  }

  private drawCanvas() {
    const canvas = this.canvas;
    const game = this.game;
    if (this.displayCanvas && canvas && game) {
      const liveColor = "red";
      const deadColor = "lightgrey";

      const cellSize = +this.cellSize;
      canvas.width = (game.width * cellSize) + 1;
      canvas.height = (game.height * cellSize) + 1;

      const context = canvas.getContext("2d");
      if (context) {
        context.save();
        context.clearRect(0, 0, canvas.width, canvas.height);
        for (let x = 0; x < game.width; ++x) {
          for (let y = 0; y < game.height; ++y) {
            const alive = game.cellAlive(x, y);
            context.fillStyle = alive ? liveColor : deadColor
            context.fillRect((x * cellSize) + 1, (y * cellSize) + 1, cellSize - 1, cellSize - 1);
          }
        }
        context.restore();
      }
    }
  }

}


text:
<?php

namespace Iyzipay\Tests\Model\Mapper;

use Iyzipay\Model\Card;
use Iyzipay\Model\Locale;
use Iyzipay\Model\Mapper\CardMapper;
use Iyzipay\Model\Status;
use Iyzipay\Tests\TestCase;

class CardMapperTest extends TestCase
{
    public function test_should_map_card()
    {
        $json = $this->retrieveJsonFile("create-card.json");

        $card = CardMapper::create($json)->jsonDecode()->mapCard(new Card());

        $this->assertNotEmpty($card);
        $this->assertEquals(Status::FAILURE, $card->getStatus());
        $this->assertEquals("10000", $card->getErrorCode());
        $this->assertEquals("error message", $card->getErrorMessage());
        $this->assertEquals("ERROR_GROUP", $card->getErrorGroup());
        $this->assertEquals(Locale::TR, $card->getLocale());
        $this->assertEquals("1458545234852", $card->getSystemTime());
        $this->assertEquals("123456", $card->getConversationId());
        $this->assertEquals("123456", $card->getExternalId());
        $this->assertEquals("email", $card->getEmail());
        $this->assertEquals("cardUserKey", $card->getCardUserKey());
        $this->assertEquals("cardToken", $card->getCardToken());
        $this->assertEquals("cardAlias", $card->getCardAlias());
        $this->assertEquals("554960", $card->getBinNumber());
        $this->assertEquals("CREDIT_CARD", $card->getCardType());
        $this->assertEquals("MASTER_CARD", $card->getCardAssociation());
        $this->assertEquals("Bonus", $card->getCardFamily());
        $this->assertEquals("10", $card->getCardBankCode());
        $this->assertEquals("Ziraat Bankası", $card->getCardBankName());
        $this->assertJson($card->getRawResult());
        $this->assertJsonStringEqualsJsonString($json, $card->getRawResult());
    }
}


text:
#ifndef Q_POLY_COLLIDER_H
#define Q_POLY_COLLIDER_H

#include "Q_Collider2D.h"

namespace Quantum2D {
/**
 Points must contain at least three vectors forming
 the boundary of a convex polygon. Consecutive points
 should be adjacent on the polygon in a consistent order
 (clockwise or counterclockwise).
*/
class PolyCollider : public Collider2D {
 public:
  PolyCollider(const BodyList &bodylist, body2d_id body, void *parent,
               const std::function<void(void *other)> &onCollision,
               const PointList2D &points, QLayer layer = 0);

  /**
   Get the coordinates of this polygon's vertices
   in the parent rigidbody's local space.
   Points are in clockwise order.
  */
  const PointList2D &points() const { return m_points; }

  /**
   Get the current coordinates of this polygon's vertices
   in world space.
  */
  const PointList2D &worldPoints() const { return m_worldPoints; }

  void update(tQ_delta delta) override;

 private:
  PointList2D m_points;
  PointList2D m_worldPoints;
};
}  // namespace Quantum2D

#endif  // Q_POLY_COLLIDER_H


text:
function nextElement(el) {
    el = el.nextSibling;
    while (el && el.nodeType != 1) {
        el = el.nextSibling;
    }
    return el;
}
function indexOf(arr, o) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == o) return i;
    }
    return -1;
}
function contains(arr, o) { return indexOf(arr, o) != -1 }
function getClasses(el) { return el.className.split(" "); }
function pushClass(el, cls) {
    var classes = getClasses(el);
    classes.push(cls);
    el.className = classes.join(" ");
    return el.className;
}
function removeClass(el, cls) {
    var classes = getClasses(el);
    classes.splice(indexOf(classes, "selected"), 1)
    el.className = classes.join(" ");
    return el.className;
}
function toggleRef(el) {
    if (contains(getClasses(el), "selected")) {
        removeClass(el, "selected");
    }
    else {
        pushClass(el, "selected");
    }
}

var show = true;
function localToggle() {
    document.getElementById("col2").style.display = show ? "none" : "";
    document.getElementById("toggle-col1").style.display = show ? "inline" : "none";
    document.getElementById("ref-button").parentNode.className = (show = !show) ? "separator selected" : "separator";
    return false;
}
function toggleNavSummary(hide) {
    document.getElementById("nav-summary-childs").style.display = !hide ? "block" : "none";
    document.getElementById("nav-summary").className = hide ? "" : "active";
}

var hiddenBlocksShown = false;
function toggleHidden() {
    var elements = document.getElementsByClassName("hidden-block");
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.display = hiddenBlocksShown ? "none" : "block";
    }

    hiddenBlocksShown = !hiddenBlocksShown
}


text:
/* This file is included at the beginning of every header file and/or
   C or C++ file.  It must be compilable for C as well as C++ files,
   so no C++-specific code or syntax can be put here. */

#ifndef PANDATOOLBASE_H
#define PANDATOOLBASE_H

#include "pandabase.h"
#include "pandatoolsymbols.h"

#endif


text:
import math
from PIL import Image
import numpy as np
import os

# YOLOv3-608 has been trained with these 80 categories from COCO:
# Lin, Tsung-Yi, et al. "Microsoft COCO: Common Objects in Context."
# European Conference on Computer Vision. Springer, Cham, 2014.

def load_label_categories(label_file_path):
    categories = [line.rstrip("\n") for line in open(label_file_path)]
    return categories

LABEL_FILE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "coco_labels.txt")
ALL_CATEGORIES = load_label_categories(LABEL_FILE_PATH)

# Let's make sure that there are 80 classes, as expected for the COCO data set:
CATEGORY_NUM = len(ALL_CATEGORIES)
assert CATEGORY_NUM == 80

class PreprocessYOLO(object):
    """A simple class for loading images with PIL and reshaping them to the specified
    input resolution for YOLOv3-608.
    """

    def __init__(self, yolo_input_resolution):
        """Initialize with the input resolution for YOLOv3, which will stay fixed in this sample.

        Keyword arguments:
        yolo_input_resolution -- two-dimensional tuple with the target network's (spatial)
        input resolution in HW order
        """
        self.yolo_input_resolution = yolo_input_resolution

    def process(self, input_image_path):
        """Load an image from the specified input path,
        and return it together with a pre-processed version required for feeding it into a
        YOLOv3 network.

        Keyword arguments:
        input_image_path -- string path of the image to be loaded
        """
        image_raw, image_resized = self._load_and_resize(input_image_path)
        image_preprocessed = self._shuffle_and_normalize(image_resized)
        return image_raw, image_preprocessed

    def _load_and_resize(self, input_image_path):
        """Load an image from the specified path and resize it to the input resolution.
        Return the input image before resizing as a PIL Image (required for visualization),
        and the resized image as a NumPy float array.

        Keyword arguments:
        input_image_path -- string path of the image to be loaded
        """

        image_raw = Image.open(input_image_path)
        # Expecting yolo_input_resolution in (height, width) format, adjusting to PIL
        # convention (width, height) in PIL:
        new_resolution = (self.yolo_input_resolution[1], self.yolo_input_resolution[0])
        image_resized = image_raw.resize(new_resolution, resample=Image.BICUBIC)
        image_resized = np.array(image_resized, dtype=np.float32, order="C")
        return image_raw, image_resized

    def _shuffle_and_normalize(self, image):
        """Normalize a NumPy array representing an image to the range [0, 1], and
        convert it from HWC format ("channels last") to NCHW format ("channels first"
        with leading batch dimension).

        Keyword arguments:
        image -- image as three-dimensional NumPy float array, in HWC format
        """
        image /= 255.0
        # HWC to CHW format:
        image = np.transpose(image, [2, 0, 1])
        # CHW to NCHW format
        image = np.expand_dims(image, axis=0)
        # Convert the image to row-major order, also known as "C order":
        image = np.array(image, dtype=np.float32, order="C")
        return image

class PostprocessYOLO(object):
    """Class for post-processing the three outputs tensors from YOLOv3-608."""

    def __init__(self, yolo_masks, yolo_anchors, obj_threshold, nms_threshold, yolo_input_resolution):
        """Initialize with all values that will be kept when processing several frames.
        Assuming 3 outputs of the network in the case of (large) YOLOv3.

        Keyword arguments:
        yolo_masks -- a list of 3 three-dimensional tuples for the YOLO masks
        yolo_anchors -- a list of 9 two-dimensional tuples for the YOLO anchors
        object_threshold -- threshold for object coverage, float value between 0 and 1
        nms_threshold -- threshold for non-max suppression algorithm,
        float value between 0 and 1
        input_resolution_yolo -- two-dimensional tuple with the target network's (spatial)
        input resolution in HW order
        """
        self.masks = yolo_masks
        self.anchors = yolo_anchors
        self.object_threshold = obj_threshold
        self.nms_threshold = nms_threshold
        self.input_resolution_yolo = yolo_input_resolution

    def process(self, outputs, resolution_raw):
        """Take the YOLOv3 outputs generated from a TensorRT forward pass, post-process them
        and return a list of bounding boxes for detected object together with their category
        and their confidences in separate lists.

        Keyword arguments:
        outputs -- outputs from a TensorRT engine in NCHW format
        resolution_raw -- the original spatial resolution from the input PIL image in WH order
        """
        outputs_reshaped = list()
        for output in outputs:
            outputs_reshaped.append(self._reshape_output(output))

        boxes, categories, confidences = self._process_yolo_output(outputs_reshaped, resolution_raw)

        return boxes, categories, confidences

    def _reshape_output(self, output):
        """Reshape a TensorRT output from NCHW to NHWC format (with expected C=255),
        and then return it in (height,width,3,85) dimensionality after further reshaping.

        Keyword argument:
        output -- an output from a TensorRT engine after inference
        """
        output = np.transpose(output, [0, 2, 3, 1])
        _, height, width, _ = output.shape
        dim1, dim2 = height, width
        dim3 = 3
        # There are CATEGORY_NUM=80 object categories:
        dim4 = 4 + 1 + CATEGORY_NUM
        return np.reshape(output, (dim1, dim2, dim3, dim4))

    def _process_yolo_output(self, outputs_reshaped, resolution_raw):
        """Take in a list of three reshaped YOLO outputs in (height,width,3,85) shape and return
        return a list of bounding boxes for detected object together with their category and their
        confidences in separate lists.

        Keyword arguments:
        outputs_reshaped -- list of three reshaped YOLO outputs as NumPy arrays
        with shape (height,width,3,85)
        resolution_raw -- the original spatial resolution from the input PIL image in WH order
        """

        # E.g. in YOLOv3-608, there are three output tensors, which we associate with their
        # respective masks. Then we iterate through all output-mask pairs and generate candidates
        # for bounding boxes, their corresponding category predictions and their confidences:
        boxes, categories, confidences = list(), list(), list()
        for output, mask in zip(outputs_reshaped, self.masks):
            box, category, confidence = self._process_feats(output, mask)
            box, category, confidence = self._filter_boxes(box, category, confidence)
            boxes.append(box)
            categories.append(category)
            confidences.append(confidence)

        boxes = np.concatenate(boxes)
        categories = np.concatenate(categories)
        confidences = np.concatenate(confidences)

        # Scale boxes back to original image shape:
        width, height = resolution_raw
        image_dims = [width, height, width, height]
        boxes = boxes * image_dims

        # Using the candidates from the previous (loop) step, we apply the non-max suppression
        # algorithm that clusters adjacent bounding boxes to a single bounding box:
        nms_boxes, nms_categories, nscores = list(), list(), list()
        for category in set(categories):
            idxs = np.where(categories == category)
            box = boxes[idxs]
            category = categories[idxs]
            confidence = confidences[idxs]

            keep = self._nms_boxes(box, confidence)

            nms_boxes.append(box[keep])
            nms_categories.append(category[keep])
            nscores.append(confidence[keep])

        if not nms_categories and not nscores:
            return None, None, None

        boxes = np.concatenate(nms_boxes)
        categories = np.concatenate(nms_categories)
        confidences = np.concatenate(nscores)

        return boxes, categories, confidences

    def _process_feats(self, output_reshaped, mask):
        """Take in a reshaped YOLO output in height,width,3,85 format together with its
        corresponding YOLO mask and return the detected bounding boxes, the confidence,
        and the class probability in each cell/pixel.

        Keyword arguments:
        output_reshaped -- reshaped YOLO output as NumPy arrays with shape (height,width,3,85)
        mask -- 2-dimensional tuple with mask specification for this output
        """

        # Two in-line functions required for calculating the bounding box
        # descriptors:
        def sigmoid(value):
            """Return the sigmoid of the input."""
            return 1.0 / (1.0 + math.exp(-value))

        def exponential(value):
            """Return the exponential of the input."""
            return math.exp(value)

        # Vectorized calculation of above two functions:
        sigmoid_v = np.vectorize(sigmoid)
        exponential_v = np.vectorize(exponential)

        grid_h, grid_w, _, _ = output_reshaped.shape

        anchors = [self.anchors[i] for i in mask]

        # Reshape to N, height, width, num_anchors, box_params:
        anchors_tensor = np.reshape(anchors, [1, 1, len(anchors), 2])
        box_xy = sigmoid_v(output_reshaped[..., :2])
        box_wh = exponential_v(output_reshaped[..., 2:4]) * anchors_tensor
        box_confidence = sigmoid_v(output_reshaped[..., 4])

        box_confidence = np.expand_dims(box_confidence, axis=-1)
        box_class_probs = sigmoid_v(output_reshaped[..., 5:])

        col = np.tile(np.arange(0, grid_w), grid_w).reshape(-1, grid_w)
        row = np.tile(np.arange(0, grid_h).reshape(-1, 1), grid_h)

        col = col.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)
        row = row.reshape(grid_h, grid_w, 1, 1).repeat(3, axis=-2)
        grid = np.concatenate((col, row), axis=-1)

        box_xy += grid
        box_xy /= (grid_w, grid_h)
        box_wh /= self.input_resolution_yolo
        box_xy -= box_wh / 2.0
        boxes = np.concatenate((box_xy, box_wh), axis=-1)

        # boxes: centroids, box_confidence: confidence level, box_class_probs:
        # class confidence
        return boxes, box_confidence, box_class_probs

    def _filter_boxes(self, boxes, box_confidences, box_class_probs):
        """Take in the unfiltered bounding box descriptors and discard each cell
        whose score is lower than the object threshold set during class initialization.

        Keyword arguments:
        boxes -- bounding box coordinates with shape (height,width,3,4); 4 for
        x,y,height,width coordinates of the boxes
        box_confidences -- bounding box confidences with shape (height,width,3,1); 1 for as
        confidence scalar per element
        box_class_probs -- class probabilities with shape (height,width,3,CATEGORY_NUM)

        """
        box_scores = box_confidences * box_class_probs
        box_classes = np.argmax(box_scores, axis=-1)
        box_class_scores = np.max(box_scores, axis=-1)
        pos = np.where(box_class_scores >= self.object_threshold)

        boxes = boxes[pos]
        classes = box_classes[pos]
        scores = box_class_scores[pos]

        return boxes, classes, scores

    def _nms_boxes(self, boxes, box_confidences):
        """Apply the Non-Maximum Suppression (NMS) algorithm on the bounding boxes with their
        confidence scores and return an array with the indexes of the bounding boxes we want to
        keep (and display later).

        Keyword arguments:
        boxes -- a NumPy array containing N bounding-box coordinates that survived filtering,
        with shape (N,4); 4 for x,y,height,width coordinates of the boxes
        box_confidences -- a Numpy array containing the corresponding confidences with shape N
        """
        x_coord = boxes[:, 0]
        y_coord = boxes[:, 1]
        width = boxes[:, 2]
        height = boxes[:, 3]

        areas = width * height
        ordered = box_confidences.argsort()[::-1]

        keep = list()
        while ordered.size > 0:
            # Index of the current element:
            i = ordered[0]
            keep.append(i)
            xx1 = np.maximum(x_coord[i], x_coord[ordered[1:]])
            yy1 = np.maximum(y_coord[i], y_coord[ordered[1:]])
            xx2 = np.minimum(x_coord[i] + width[i], x_coord[ordered[1:]] + width[ordered[1:]])
            yy2 = np.minimum(y_coord[i] + height[i], y_coord[ordered[1:]] + height[ordered[1:]])

            width1 = np.maximum(0.0, xx2 - xx1 + 1)
            height1 = np.maximum(0.0, yy2 - yy1 + 1)
            intersection = width1 * height1
            union = areas[i] + areas[ordered[1:]] - intersection

            # Compute the Intersection over Union (IoU) score:
            iou = intersection / union

            # The goal of the NMS algorithm is to reduce the number of adjacent bounding-box
            # candidates to a minimum. In this step, we keep only those elements whose overlap
            # with the current bounding box is lower than the threshold:
            indexes = np.where(iou <= self.nms_threshold)[0]
            ordered = ordered[indexes + 1]

        keep = np.array(keep)
        return keep


text:
<?php
/**
 * Created by PhpStorm.
 * User: Gary.F.Dong
 * Date: 2016/12/26
 * Time: 13:51
 * Desc:
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;

class TagsData extends Model
{
    use Notifiable;

    protected $table = "tags_data";

    protected $fillable = ['tag_id','data_id','category_id','model_id'];

    public function tags()
    {
        return $this->belongsTo('App\Models\Tags', 'tag_id', 'id');
    }

}


text:
FOUNDATION_EXPORT double PippinLibraryVersionNumber;
FOUNDATION_EXPORT const unsigned char PippinLibraryVersionString[];


text:
package main

// Import required packages
import (
	"flag"
	"fmt"
	"os"
)

// PrintLicense function
// Outputs license details to the command line
func PrintLicense() {
	licenseText := `pathlength - calculates resolution and sensitivity in reflective superposition compound eyes.

Copyright (C) 2020 Dr Stephen P Moss

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>`

	fmt.Println(licenseText)
	os.Exit(0)
}

// PrintCitation function
// Outputs citation information to the command line
func PrintCitation() {
	citationText := `Gaten, E., Moss, S., Johnson, M. 2013. The Reniform Reflecting Superposition Compound Eyes of Nephrops Norvegicus:
Optics, Susceptibility to Light-Induced Damage, Electrophysiology and a Ray Tracing Model. In: M. L. Johnson and M. P. Johnson, ed(s).
Advances in Marine Biology: The Ecology and Biology of Nephrops norvegicus. Oxford: Academic Press, 107:148.`

	fmt.Println(citationText)
	os.Exit(0)
}

// PrintUsage function
// Outputs usage information to the command line
func PrintUsage(exitCode int) {
	fmt.Println("Usage:")
	flag.PrintDefaults()
	os.Exit(exitCode)
}

// PrintVersion function
// Outputs the version of the program to the command line
func PrintVersion() {
	fmt.Println("pathlength version", pathlengthVersion)
	os.Exit(0)
}


text:
<?php

class ThemeShortcodeRecentposts extends ThemeShortcode {

    public function tag() {
        return 'recentposts';
    }

    public function process($atts, $content=null) {
        extract(shortcode_atts(
            array(
                'columns' => 2,
                'count' => 4,
                'categories' => '',
                'tags' => '',
                'excerpt' => 160,
            ), $atts));
        $args = array(
            'post_type' => 'post',
            'numberposts' => $count,
            'order' => 'DESC',
            'tag' => $tags,
            'category_name' => $categories,
            'posts_per_page' => $count,
        );
        $html = '';
        $query = new WP_Query($args);

        if ($query->have_posts()) {
            $html .= '
';
            while ($query->have_posts()) {
                $query->the_post();
                //
                $meta = new ThemeMetaboxFeaturedcontent();
                $thumnbail = $meta->get_content(get_the_ID(), 'blog-thumb');
                $title = get_the_title();
                $content = ThemeUtils::cutExcerpt(get_the_excerpt(), $excerpt);
                $date = get_the_time(get_option('date_format'));
                $comments = sprintf('%s %s', get_comments_number(), __r('Comments'));
                $permalink = get_permalink();
                $posthtml = <<< EOT
$thumnbail

$title

    $date
    $comments

$content

EOT;
                $calc = ($query->current_post+1) / $columns;
                $html .= do_shortcode(sprintf('[column class="1/%s"]%s[/column]', $columns.( floor($calc)==$calc || ($query->current_post + 1 >= $query->post_count) ? ' last' : ''), $posthtml));
            }
            $html .= '
';
        }
        return $html;
    }
}

?>


text:
package org.hsqldb.types;

import java.sql.Array;

import org.hsqldb.OpTypes;
import org.hsqldb.Session;
import org.hsqldb.SessionInterface;
import org.hsqldb.SortAndSlice;
import org.hsqldb.Tokens;
import org.hsqldb.error.Error;
import org.hsqldb.error.ErrorCode;
import org.hsqldb.jdbc.JDBCArray;
import org.hsqldb.jdbc.JDBCArrayBasic;
import org.hsqldb.lib.ArraySort;

/**
 * Class for ARRAY type objects.<p>
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 2.2.1
 * @since 2.0.0
 */
public class ArrayType extends Type {

    public static final int defaultArrayCardinality      = 1024;
    public static final int defaultLargeArrayCardinality = Integer.MAX_VALUE;
    final Type              dataType;
    final int               maxCardinality;

    public ArrayType(Type dataType, int cardinality) {

        super(Types.SQL_ARRAY, Types.SQL_ARRAY, 0, 0);

        if (dataType == null) {
            dataType = Type.SQL_ALL_TYPES;
        }

        this.dataType       = dataType;
        this.maxCardinality = cardinality;
    }

    public int displaySize() {
        return 7 + (dataType.displaySize() + 1) * maxCardinality;
    }

    public int getJDBCTypeCode() {
        return Types.ARRAY;
    }

    public Class getJDBCClass() {
        return java.sql.Array.class;
    }

    public String getJDBCClassName() {
        return "java.sql.Array";
    }

    public int getJDBCScale() {
        return 0;
    }

    public int getJDBCPrecision() {
        return 0;
    }

    public int getSQLGenericTypeCode() {
        return 0;
    }

    public String getNameString() {

        StringBuffer sb = new StringBuffer();

        sb.append(dataType.getNameString()).append(' ');
        sb.append(Tokens.T_ARRAY);

        if (maxCardinality != defaultArrayCardinality) {
            sb.append('[').append(maxCardinality).append(']');
        }

        return sb.toString();
    }

    public String getFullNameString() {

        StringBuffer sb = new StringBuffer();

        sb.append(dataType.getFullNameString()).append(' ');
        sb.append(Tokens.T_ARRAY);

        if (maxCardinality != defaultArrayCardinality) {
            sb.append('[').append(maxCardinality).append(']');
        }

        return sb.toString();
    }

    public String getDefinition() {

        StringBuffer sb = new StringBuffer();

        sb.append(dataType.getDefinition()).append(' ');
        sb.append(Tokens.T_ARRAY);

        if (maxCardinality != defaultArrayCardinality) {
            sb.append('[').append(maxCardinality).append(']');
        }

        return sb.toString();
    }

    public int compare(Session session, Object a, Object b) {

        if (a == b) {
            return 0;
        }

        if (a == null) {
            return -1;
        }

        if (b == null) {
            return 1;
        }

        Object[] arra   = (Object[]) a;
        Object[] arrb   = (Object[]) b;
        int      length = arra.length;

        if (arrb.length < length) {
            length = arrb.length;
        }

        for (int i = 0; i < length; i++) {
            int result = dataType.compare(session, arra[i], arrb[i]);

            if (result != 0) {
                return result;
            }
        }

        if (arra.length > arrb.length) {
            return 1;
        } else if (arra.length < arrb.length) {
            return -1;
        }

        return 0;
    }

    public Object convertToTypeLimits(SessionInterface session, Object a) {

        if (a == null) {
            return null;
        }

        Object[] arra = (Object[]) a;

        if (arra.length > maxCardinality) {
            throw Error.error(ErrorCode.X_2202F);
        }

        Object[] arrb = new Object[arra.length];

        for (int i = 0; i < arra.length; i++) {
            arrb[i] = dataType.convertToTypeLimits(session, arra[i]);
        }

        return arrb;
    }

    public Object convertToType(SessionInterface session, Object a,
                                Type otherType) {

        if (a == null) {
            return null;
        }

        if (otherType == null) {
            return a;
        }

        if (!otherType.isArrayType()) {
            throw Error.error(ErrorCode.X_42562);
        }

        Object[] arra = (Object[]) a;

        if (arra.length > maxCardinality) {
            throw Error.error(ErrorCode.X_2202F);
        }

        Type otherComponent = otherType.collectionBaseType();

        if (dataType.equals(otherComponent)) {
            return a;
        }

        Object[] arrb = new Object[arra.length];

        for (int i = 0; i < arra.length; i++) {
            arrb[i] = dataType.convertToType(session, arra[i], otherComponent);
        }

        return arrb;
    }

    public Object convertJavaToSQL(SessionInterface session, Object a) {

        Object[] data;
        boolean  convert = false;

        if (a == null) {
            return null;
        }

        if (a instanceof Object[]) {
            data    = (Object[]) a;
            convert = true;
        } else if (a instanceof JDBCArray) {
            data = ((JDBCArray) a).getArrayInternal();
        } else if (a instanceof JDBCArrayBasic) {
            data    = (Object[]) ((JDBCArrayBasic) a).getArray();
            convert = true;
        } else if (a instanceof java.sql.Array) {
            try {
                data    = (Object[]) ((Array) a).getArray();
                convert = true;
            } catch (Exception e) {
                throw Error.error(ErrorCode.X_42561);
            }
        } else {
            throw Error.error(ErrorCode.X_42561);
        }

        if (convert) {
            Object[] array = new Object[data.length];

            for (int i = 0; i < data.length; i++) {
                array[i] = dataType.convertJavaToSQL(session, data[i]);
                array[i] = dataType.convertToTypeLimits(session, data[i]);
            }

            return array;
        }

        return data;
    }

    public Object convertSQLToJava(SessionInterface session, Object a) {

        if (a instanceof Object[]) {
            Object[] data = (Object[]) a;

            return new JDBCArray(data, this.collectionBaseType(), this,
                                 session);
        }

        throw Error.error(ErrorCode.X_42561);
    }

    public Object convertToDefaultType(SessionInterface sessionInterface,
                                       Object o) {
        return o;
    }

    public String convertToString(Object a) {

        if (a == null) {
            return null;
        }

        return convertToSQLString(a);
    }

    public String convertToSQLString(Object a) {

        if (a == null) {
            return Tokens.T_NULL;
        }

        Object[]     arra = (Object[]) a;
        StringBuffer sb   = new StringBuffer();

        sb.append(Tokens.T_ARRAY);
        sb.append('[');

        for (int i = 0; i < arra.length; i++) {
            if (i > 0) {
                sb.append(',');
            }

            sb.append(dataType.convertToSQLString(arra[i]));
        }

        sb.append(']');

        return sb.toString();
    }

    public boolean canConvertFrom(Type otherType) {

        if (otherType == null) {
            return true;
        }

        if (!otherType.isArrayType()) {
            return false;
        }

        Type otherComponent = otherType.collectionBaseType();

        return dataType.canConvertFrom(otherComponent);
    }

    public int canMoveFrom(Type otherType) {

        if (otherType == this) {
            return 0;
        }

        if (!otherType.isArrayType()) {
            return -1;
        }

        if (maxCardinality >= ((ArrayType) otherType).maxCardinality) {
            return dataType.canMoveFrom((ArrayType) otherType);
        } else {
            if (dataType.canMoveFrom((ArrayType) otherType) == -1) {
                return -1;
            }

            return 1;
        }
    }

    public boolean canBeAssignedFrom(Type otherType) {

        if (otherType == null) {
            return true;
        }

        Type otherComponent = otherType.collectionBaseType();

        return otherComponent != null
               && dataType.canBeAssignedFrom(otherComponent);
    }

    public Type collectionBaseType() {
        return dataType;
    }

    public int arrayLimitCardinality() {
        return maxCardinality;
    }

    public boolean isArrayType() {
        return true;
    }

    public Type getAggregateType(Type other) {

        if (other == null) {
            return this;
        }

        if (other == SQL_ALL_TYPES) {
            return this;
        }

        if (this == other) {
            return this;
        }

        if (!other.isArrayType()) {
            throw Error.error(ErrorCode.X_42562);
        }

        Type otherComponent = other.collectionBaseType();

        if (dataType.equals(otherComponent)) {
            return ((ArrayType) other).maxCardinality > maxCardinality ? other
                                                                       : this;
        }

        Type newComponent = dataType.getAggregateType(otherComponent);
        int cardinality = ((ArrayType) other).maxCardinality > maxCardinality
                          ? ((ArrayType) other).maxCardinality
                          : maxCardinality;

        return new ArrayType(newComponent, cardinality);
    }

    public Type getCombinedType(Session session, Type other, int operation) {

        ArrayType type = (ArrayType) getAggregateType(other);

        if (other == null) {
            return type;
        }

        if (operation != OpTypes.CONCAT) {
            return type;
        }

        if (type.maxCardinality == ArrayType.defaultLargeArrayCardinality) {
            return type;
        }

        long card = (long) ((ArrayType) other).maxCardinality + maxCardinality;

        if (card > ArrayType.defaultLargeArrayCardinality) {
            card = ArrayType.defaultLargeArrayCardinality;
        }

        return new ArrayType(dataType, (int) card);
    }

    public int cardinality(Session session, Object a) {

        if (a == null) {
            return 0;
        }

        return ((Object[]) a).length;
    }

    public Object concat(Session session, Object a, Object b) {

        if (a == null || b == null) {
            return null;
        }

        int      size  = ((Object[]) a).length + ((Object[]) b).length;
        Object[] array = new Object[size];

        System.arraycopy(a, 0, array, 0, ((Object[]) a).length);
        System.arraycopy(b, 0, array, ((Object[]) a).length,
                         ((Object[]) b).length);

        return array;
    }

    public boolean equals(Object other) {

        if (other == this) {
            return true;
        }

        if (other instanceof Type) {
            if (((Type) other).typeCode != Types.SQL_ARRAY) {
                return false;
            }

            return maxCardinality == ((ArrayType) other).maxCardinality
                   && dataType.equals(((ArrayType) other).dataType);
        }

        return false;
    }

    public void sort(Session session, Object a, SortAndSlice sort) {

        Object[]        array      = (Object[]) a;
        TypedComparator comparator = session.getComparator();

        comparator.setType(dataType, sort);
        ArraySort.sort(array, 0, array.length, comparator);
    }

    public int deDuplicate(Session session, Object a, SortAndSlice sort) {

        Object[]        array      = (Object[]) a;
        TypedComparator comparator = session.getComparator();

        comparator.setType(dataType, sort);

        return ArraySort.deDuplicate(array, 0, array.length, comparator);
    }
}


text:
@implementation AfloatDisableOverlaysCommand

- (id) performDefaultImplementation {
	[[NSApp delegate] rearmDeathTimer];

	[[NSDistributedNotificationCenter defaultCenter]
	 postNotificationName:kAfloatScriptDisableAllOverlaysNotification object:kAfloatScriptWireObject];
	return nil;
}

@end


text:
package blobstore
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type Blobstore struct {

	/*AdminUsers - Descr: List of Username and Password pairs that have admin access to the blobstore. Cloud Controller must use one of these to access the blobstore via HTTP Basic Auth.
Example:
  users:
  - username: user1
    password: password1
  - username: user2
    password: password2
 Default: <nil>
*/
	AdminUsers interface{} `yaml:"admin_users,omitempty"`

	/*SecureLink - Descr: The secret used for signing URLs Default: <nil>
*/
	SecureLink *SecureLink `yaml:"secure_link,omitempty"`

	/*MaxUploadSize - Descr: Max allowed file size for upload Default: 5000m
*/
	MaxUploadSize interface{} `yaml:"max_upload_size,omitempty"`

	/*Port - Descr: TCP port on which the blobstore server (nginx) listens Default: 8080
*/
	Port interface{} `yaml:"port,omitempty"`

	/*Tls - Descr: The PEM-encoded private key for signing TLS/SSL traffic Default: <nil>
*/
	Tls *Tls `yaml:"tls,omitempty"`

	/*NginxWorkersPerCore - Descr: Number of NGINX worker processes per CPU core Default: 2
*/
	NginxWorkersPerCore interface{} `yaml:"nginx_workers_per_core,omitempty"`

	/*InternalAccessRules - Descr: List of allow / deny rules for the blobstore internal server. Defaults to RFC 1918 Private Networks. Will be followed by 'deny all'. See http://nginx.org/en/docs/http/ngx_http_access_module.html for valid rules Default: [allow 10.0.0.0/8; allow 172.16.0.0/12; allow 192.168.0.0/16;]
*/
	InternalAccessRules interface{} `yaml:"internal_access_rules,omitempty"`

}


text:
<?php

namespace Portal\Controller;

/**
 * Importación de librerías
 */
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Db\ResultSet\ResultSet;

/**
 * Define el objeto que permite la interacción
 * entre el modelo y la vista asociadas.
 *
 * Contiene funciones específicas para el funcionamiento
 * adecuado de la clase controladora.
 */
class ClienteController extends AbstractActionController
{

    /**
     * Almacena la clase para referencia
     * de base de datos y sobrecarga el tableGateway
     *
     * @return object|bool $clienteDao
     */
    protected $clienteDao;

    /**
     * Almacena la clase para referencia
     * de base de datos y sobrecarga el tableGateway
     *
     * @return object|bool $aseguradoraClienteDao
     */
    protected $aseguradoraClienteDao;

    /**
     * Almacena la clase para referencia
     * de base de datos y sobrecarga el tableGateway
     *
     * @return object|bool $historialDao
     */
    protected $historialDao;

    /**
     * Almacena la clase para referencia
     * de base de datos y sobrecarga el tableGateway
     *
     * @return object|bool $detalleHistoriaDao
     */
    protected $detalleHistoriaDao;

    /**
     * Almacena la clase para referencia
     * de base de datos y sobrecarga el tableGateway
     *
     * @return object|bool $fotosDetalleHistoriaDao
     */
    protected $fotosDetalleHistoriaDao;

    /**
     * Action: Muestra el total de registros del objeto
     *
     * @return array
     */
    public function perfilAction()
    {
        $cli_id = (int) $this->params()->fromRoute('id', 0);
        $historial = array();
        $detalleHistorial = null;
        $detalleHistorialFotos = null;

        $cliente = $this->getClienteDao()->traer($cli_id);
        $aseguradora_cliente = $this->getAseguradoraClienteDao()->traerAseguradorasDelCliente($cli_id);

        foreach ($aseguradora_cliente as $aseguradora){
            $historial[] = $this->getHistorialDao()->traerHistorialPorAseguradoraPorCliente($aseguradora->getAseguradora_ase_id(), $aseguradora->getCliente_cli_id());
        }

        //Se elimina del arreglo la informacion que no tiene una historia
        foreach ($historial as $val => $row){
            if(count($row) == 0){
                unset($historial[$val]);
            }

        }

        /* echo '
';
        print_r($historial);
        echo '
';
        $cont = 0; */

        foreach ($historial as $val => $row){
           echo $id = $row[0]['his_id'];

           if(!empty($id) && !is_null($id)){
               $detalleHistorial[$id] = $this->getDetalleHistoriaDao()->traerDetallePorHistoria($row[0]['his_id']);
               $detalleHistorialFotos[$id] = $this->getFotosDetalleHistoriaDao()->traerFotosDetalleHistoria($detalleHistorial[$id][0]['det_his_id']);
           }

           //$cont++;
        }

       // die();
        /* echo '
';
        print_r($historial);
        echo '
';

        echo '
';
        print_r($detalleHistorial);
        echo '
';

        echo '
';
        print_r($detalleHistorialFotos);
        echo '
';

        die(); */

        return array(
            'cliente' => $cliente,
            'aseguradoraCliente' => $aseguradora_cliente,
            'historial' => $historial,
            'detalleHistorial' => $detalleHistorial,
            'detalleHistorialFotos' => $detalleHistorialFotos,
        );
    }

    /**
     * Obtiene el objeto registrado en el service manager
     * de la clase module (Application)
     *
     * @return object|bool
     */
    private function getHistorialDao()
    {
        if (! $this->historialDao) {
            $sm = $this->getServiceLocator();
            $this->historialDao = $sm->get('Application\Model\Dao\HistorialDao');
        }
        return $this->historialDao;
    }

    /**
     * Obtiene el objeto registrado en el service manager
     * de la clase module (Application)
     *
     * @return object|bool
     */
    private function getClienteDao()
    {
        if (! $this->clienteDao) {
            $sm = $this->getServiceLocator();
            $this->clienteDao = $sm->get('Application\Model\Dao\ClienteDao');
        }
        return $this->clienteDao;
    }

    /**
     * Obtiene el objeto registrado en el service manager
     * de la clase module (Application)
     *
     * @return object|bool
     */
    private function getAseguradoraClienteDao()
    {
        if (! $this->aseguradoraClienteDao) {
            $sm = $this->getServiceLocator();
            $this->aseguradoraClienteDao = $sm->get('Application\Model\Dao\AseguradoraClienteDao');
        }
        return $this->aseguradoraClienteDao;
    }

    /**
     * Obtiene el objeto registrado en el service manager
     * de la clase module (Application)
     *
     * @return object|bool
     */
    private function getDetalleHistoriaDao()
    {
        if (! $this->detalleHistoriaDao) {
            $sm = $this->getServiceLocator();
            $this->detalleHistoriaDao = $sm->get('Application\Model\Dao\DetalleHistoriaDao');
        }
        return $this->detalleHistoriaDao;
    }

    /**
     * Obtiene el objeto registrado en el service manager
     * de la clase module (Application)
     *
     * @return object|bool
     */
    private function getFotosDetalleHistoriaDao()
    {
        if (! $this->fotosDetalleHistoriaDao) {
            $sm = $this->getServiceLocator();
            $this->fotosDetalleHistoriaDao = $sm->get('Application\Model\Dao\FotosDetalleHistoriaDao');
        }
        return $this->fotosDetalleHistoriaDao;
    }
}


text:
This example displays events stored in Amazon CloudWatch log groups.

`go run GetLogEventsv2.go -g LOG-GROUP -s LOG-STREAM`

- _LOG-GROUP_ is the name of the CloudWatch Log Group.
- _LOG-STREAM_ is within a Log Group, contains events.

The unit test accepts similar values in _config.json_.


text:
namespace Microsoft.OneDrive.Sdk
{
    using System;

    /// <summary>
    /// The type VersionsCollectionPage.
    /// </summary>
    public partial class VersionsCollectionPage : CollectionPage<Item>, IVersionsCollectionPage
    {
        /// <summary>
        /// Gets the next page <see cref="IVersionsCollectionRequest"/> instance.
        /// </summary>
        public IVersionsCollectionRequest NextPageRequest { get; private set; }

        /// <summary>
        /// Initializes the NextPageRequest property.
        /// </summary>
        public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
        {
            if (!string.IsNullOrEmpty(nextPageLinkString))
            {
                this.NextPageRequest = new VersionsCollectionRequest(
                    nextPageLinkString,
                    client,
                    null);
            }
        }
    }
}


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

<TITLE>
RawMeasurement
</TITLE>

<META NAME="date" CONTENT="2013-02-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      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

fi.vtt.activitylogger

Class RawMeasurement

java.lang.Object
  fi.vtt.activitylogger.RawMeasurement

public class RawMeasurement
extends java.lang.Object

Field Summary

private  int
cellId

private  java.lang.String
deviceName

private  double
latitude

private  java.lang.String
loggerApplicationName

private  double
longitude

private  long
measurementId

private  java.lang.String
measurementTimestamp

Constructor Summary

RawMeasurement()

          Default constructor needed for annotations to avoid exception at run time

RawMeasurement(long measurementId,
               java.lang.String measurementTimestamp,
               double latitude,
               double longitude,
               int cellId,
               java.lang.String loggerApplicationName,
               java.lang.String deviceName)

          Constructor

Method Summary

 int
getCellId()

 java.lang.String
getDeviceName()

 double
getLatitude()

 java.lang.String
getloggerApplicationName()

 double
getLongitude()

 long
getMeasurementId()

 java.lang.String
getMeasurementTimestamp()

 void
setCellId(int cellId)

 void
setDeviceName(java.lang.String deviceName)

 void
setLatitude(double latitude)

 void
setloggerApplicationName(java.lang.String loggerApplicationName)

 void
setLongitude(double longitude)

 void
setMeasurementId(long measurementId)

 void
setMeasurementTimestamp(java.lang.String measurementTimestamp)

Methods inherited from class java.lang.Object

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

Field Detail

measurementId

private long measurementId

measurementTimestamp

private java.lang.String measurementTimestamp

latitude

private double latitude

longitude

private double longitude

cellId

private int cellId

loggerApplicationName

private java.lang.String loggerApplicationName

deviceName

private java.lang.String deviceName

Constructor Detail

RawMeasurement

public RawMeasurement()

Default constructor needed for annotations to avoid exception at run time

RawMeasurement

public RawMeasurement(long measurementId,
                      java.lang.String measurementTimestamp,
                      double latitude,
                      double longitude,
                      int cellId,
                      java.lang.String loggerApplicationName,
                      java.lang.String deviceName)

Constructor

Parameters:
measurementId -
measurementTimestamp -
latitude -
longitude -
cellId -
loggerApplicationName -
deviceName -

Method Detail

getMeasurementId

public long getMeasurementId()

setMeasurementId

public void setMeasurementId(long measurementId)

getMeasurementTimestamp

public java.lang.String getMeasurementTimestamp()

setMeasurementTimestamp

public void setMeasurementTimestamp(java.lang.String measurementTimestamp)

getLatitude

public double getLatitude()

setLatitude

public void setLatitude(double latitude)

getLongitude

public double getLongitude()

setLongitude

public void setLongitude(double longitude)

getCellId

public int getCellId()

setCellId

public void setCellId(int cellId)

getloggerApplicationName

public java.lang.String getloggerApplicationName()

setloggerApplicationName

public void setloggerApplicationName(java.lang.String loggerApplicationName)

getDeviceName

public java.lang.String getDeviceName()

setDeviceName

public void setDeviceName(java.lang.String deviceName)

      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


text:
This is my collection of "hello world" programs written in various languages
and dialects. In general, the goal is to simply output "hello world" (with no
linebreak) at the command line. There are a few minor exceptions.

## Workstation Setup

The only prerequisite for code in this repo is that I've successfully run it on
my machine.

I use Mac OS X with [`homebrew`](http://brew.sh/) as my package manager. Most
of the languages that I've used are either pre-installed with Mac OS X,
installed with the Mac OS Developer Tools or installed with `homebrew`.
CoffeeScript requires the [corresponding node module](https://www.npmjs.com/package/coffee-script)
is installed globally.

## Contributions

Many of the applications were written by myself with the aid of official
reference materials available freely on the web. Contributions from others
in the GitHub community are marked as such in the list below.

The Objective-C example originally came from [this StackOverflow question](http://stackoverflow.com/questions/7473246/compile-an-ios-objective-c-command-line-app-through-gcc-on-mac).

## Languages

 * [Bash](./bash)
 * [Brainfuck](./brainfuck) - by [RobLoach](https://github.com/RobLoach)
 * [C](./c)
 * [C#](./csharp) - by [jackmott](https://github.com/jackmott)
 * [C++](./cpp) - by [RobLoach](https://github.com/RobLoach)
 * [Clojure](./clojure)
 * [COBOL](./cobol)
 * [CoffeeScript](./coffeescript)
 * [Common Lisp](./common-lisp) - by [davidselivanov](https://github.com/davidselivanov)
 * [D](./d) - by [RobLoach](https://github.com/RobLoach)
 * [Emacs-Lisp](./emacs-lisp) - by [davidselivanov](https://github.com/davidselivanov)
 * [Erlang](./erlang)
 * [F#](./fsharp) - by [jackmott](https://github.com/jackmott)
 * [Fortran](./fortran) - by [DanmerZ](https://github.com/DanmerZ)
 * [Go](./go)
 * [Haskell](./haskell) - by [jackmott](https://github.com/jackmott)
 * [Java](./java)
 * [JavaScript](./javascript)
 * [Lua](./lua)
 * [Objective-C](./objective-c)
 * [Perl](./perl)
 * [PHP](./php)
 * [Python](./python)
 * [Ruby](./ruby)
 * [Rust](./rust)
 * [Scala](./scala)
 * [Smalltalk](./smalltalk)
 * [Swift](./swift)

## License

[MIT License](LICENSE.md)


text:
package org.apache.activemq.broker.virtual;

import java.io.IOException;
import java.net.URI;

import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.activemq.EmbeddedBrokerTestSupport;

import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.DestinationFilter;
import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.Message;
import org.apache.activemq.xbean.XBeanBrokerFactory;

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

/**
 * Test for AMQ-4571.
 * checks that durable subscription is fully unregistered
 * when using nested destination interceptors.
 */
public class DestinationInterceptorDurableSubTest extends EmbeddedBrokerTestSupport {

    private static final transient Logger LOG = LoggerFactory.getLogger(DestinationInterceptorDurableSubTest.class);
    private MBeanServerConnection mbsc = null;
    public static final String JMX_CONTEXT_BASE_NAME = "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Topic,destinationName=";

    /**
     * Tests AMQ-4571.
     * @throws Exception
     */
    public void testVirtualTopicRemoval() throws Exception {

        LOG.debug("Running testVirtualTopicRemoval()");
        String clientId1 = "myId1";
        String clientId2 = "myId2";

        Connection conn = null;
        Session session = null;

        try {
            assertTrue(broker.isStarted());

            // create durable sub 1
            conn = createConnection();
            conn.setClientID(clientId1);
            conn.start();
            session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // Topic topic = session.createTopic(destination.getPhysicalName());
            TopicSubscriber sub1 = session.createDurableSubscriber((Topic) destination, clientId1);

            // create durable sub 2
            TopicSubscriber sub2 = session.createDurableSubscriber((Topic) destination, clientId2);

            // verify two subs registered in JMX
            assertSubscriptionCount(destination.getPhysicalName(), 2);
            assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1));
            assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2));

            // delete sub 1
            sub1.close();
            session.unsubscribe(clientId1);

            // verify only one sub registered in JMX
            assertSubscriptionCount(destination.getPhysicalName(), 1);
            assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1));
            assertTrue(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2));

            // delete sub 2
            sub2.close();
            session.unsubscribe(clientId2);

            // verify no sub registered in JMX
            assertSubscriptionCount(destination.getPhysicalName(), 0);
            assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId1));
            assertFalse(isSubRegisteredInJmx(destination.getPhysicalName(), clientId2));
        } finally {
            session.close();
            conn.close();
        }
    }

    /**
     * Connects to broker using JMX
     * @return The JMX connection
     * @throws IOException in case of any errors
     */
    protected MBeanServerConnection connectJMXBroker() throws IOException {
        // connect to broker via JMX
        JMXServiceURL url =  new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:1299/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        LOG.debug("JMX connection established");
        return mbsc;
    }

    /**
     * Asserts that the Subscriptions JMX attribute of a topic has the expected
     * count.
     * @param topicName name of the topic destination
     * @param expectedCount expected number of subscriptions
     * @return
     */
    protected boolean assertSubscriptionCount(String topicName, int expectedCount) {
        try {
            if (mbsc == null) {
                mbsc = connectJMXBroker();
            }
            // query broker queue size
            ObjectName[] tmp = (ObjectName[])mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions");
            assertEquals(expectedCount, tmp.length);
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
            return false;
        }
        return true;
    }

    /**
     * Checks if a subscriptions for topic topicName with subName is registered in JMX
     *
     * @param topicName physical name of topic destination (excluding prefix 'topic://')
     * @param subName name of the durable subscription
     * @return true if registered, false otherwise
     */
    protected boolean isSubRegisteredInJmx(String topicName, String subName) {

        try {
            if (mbsc == null) {
                mbsc = connectJMXBroker();
            }

            // A durable sub is registered under the Subscriptions JMX attribute of the topic and
            // as its own ObjectInstance under the topic's Consumer namespace.
            // AMQ-4571 only removed the latter not the former on unsubscribe(), so we need
            // to check against both.
            ObjectName[] names = (ObjectName[])mbsc.getAttribute(new ObjectName(JMX_CONTEXT_BASE_NAME + topicName), "Subscriptions");
            ObjectInstance instance = (ObjectInstance)mbsc.getObjectInstance(
                new ObjectName(JMX_CONTEXT_BASE_NAME +
                    topicName +
                    ",endpoint=Consumer,clientId=myId1,consumerId=Durable(myId1_" +
                    subName +
                    ")")
            );

            if (instance == null)
                return false;

            for (int i=0; i < names.length; i++) {
                if (names[i].toString().contains(subName))
                    return true;
            }
        } catch (InstanceNotFoundException ine) {
            //this may be expected so log at info level
            LOG.info(ine.toString());
            return false;
        }
        catch (Exception ex) {
            LOG.error(ex.toString());
            return false;
        }
        return false;
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    protected BrokerService createBroker() throws Exception {
        XBeanBrokerFactory factory = new XBeanBrokerFactory();
        BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri()));

        // lets disable persistence as we are a test
        answer.setPersistent(false);
        useTopic = true;
        return answer;
    }

    protected String getBrokerConfigUri() {
        return "org/apache/activemq/broker/virtual/virtual-topics-and-interceptor.xml";
    }

    /**
     * Simple but custom topic interceptor.
     * To be used for testing nested interceptors in conjunction with
     * virtual topic interceptor.
     */
    public static class SimpleDestinationInterceptor implements DestinationInterceptor {

        private final Logger LOG = LoggerFactory.getLogger(SimpleDestinationInterceptor.class);
        private BrokerService broker;

        public SimpleDestinationInterceptor() {
        }

        /* (non-Javadoc)
         * @see org.apache.activemq.broker.BrokerServiceAware#setBrokerService(org.apache.activemq.broker.BrokerService)
         */
        public void setBrokerService(BrokerService brokerService) {
            LOG.info("setBrokerService()");
            this.broker = brokerService;
        }

        /* (non-Javadoc)
         * @see org.apache.activemq.broker.region.DestinationInterceptor#intercept(org.apache.activemq.broker.region.Destination)
         */
        public Destination intercept(final Destination destination) {
            LOG.info("intercept({})", destination.getName());

            if (!destination.getActiveMQDestination().getPhysicalName().startsWith("ActiveMQ")) {
                return new DestinationFilter(destination) {
                  public void send(ProducerBrokerExchange context, Message message) throws Exception {
                    // Send message to Destination
                    if (LOG.isDebugEnabled()) {
                      LOG.debug("SimpleDestinationInterceptor: Sending message to destination:"
                          + this.getActiveMQDestination().getPhysicalName());
                    }
                    // message.setDestination(destination.getActiveMQDestination());
                    super.send(context, message);
                  }
                };
              }
              return destination;
        }

        /* (non-Javadoc)
         * @see org.apache.activemq.broker.region.DestinationInterceptor#remove(org.apache.activemq.broker.region.Destination)
         */
        public void remove(Destination destination) {
            LOG.info("remove({})", destination.getName());
            this.broker = null;
        }

        /* (non-Javadoc)
         * @see org.apache.activemq.broker.region.DestinationInterceptor#create(org.apache.activemq.broker.Broker, org.apache.activemq.broker.ConnectionContext, org.apache.activemq.command.ActiveMQDestination)
         */
        public void create(Broker broker, ConnectionContext context, ActiveMQDestination destination) throws Exception {
            LOG.info("create("+ broker.getBrokerName() + ", " + context.toString() + ", " + destination.getPhysicalName());
        }
    }
}


text:
package settings

import (
	"context"
	"net/http"
	"strings"

	"github.com/onsi/ginkgo"
	"github.com/stretchr/testify/assert"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	policyv1beta1 "k8s.io/api/policy/v1beta1"
	rbacv1 "k8s.io/api/rbac/v1"
	k8sErrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/ingress-nginx/test/e2e/framework"
)

const (
	ingressControllerPSP = "ingress-controller-psp"
)

var _ = framework.IngressNginxDescribe("[Security] Pod Security Policies", func() {
	f := framework.NewDefaultFramework("pod-security-policies")

	ginkgo.It("should be running with a Pod Security Policy", func() {
		psp := createPodSecurityPolicy()
		_, err := f.KubeClientSet.PolicyV1beta1().PodSecurityPolicies().Create(context.TODO(), psp, metav1.CreateOptions{})
		if !k8sErrors.IsAlreadyExists(err) {
			assert.Nil(ginkgo.GinkgoT(), err, "creating Pod Security Policy")
		}

		role, err := f.KubeClientSet.RbacV1().Roles(f.Namespace).Get(context.TODO(), "nginx-ingress", metav1.GetOptions{})
		assert.Nil(ginkgo.GinkgoT(), err, "getting ingress controller cluster role")
		assert.NotNil(ginkgo.GinkgoT(), role)

		role.Rules = append(role.Rules, rbacv1.PolicyRule{
			APIGroups:     []string{"policy"},
			Resources:     []string{"podsecuritypolicies"},
			ResourceNames: []string{ingressControllerPSP},
			Verbs:         []string{"use"},
		})

		_, err = f.KubeClientSet.RbacV1().Roles(f.Namespace).Update(context.TODO(), role, metav1.UpdateOptions{})
		assert.Nil(ginkgo.GinkgoT(), err, "updating ingress controller cluster role to use a pod security policy")

		// update the deployment just to trigger a rolling update and the use of the security policy
		err = f.UpdateIngressControllerDeployment(func(deployment *appsv1.Deployment) error {
			args := deployment.Spec.Template.Spec.Containers[0].Args
			args = append(args, "--v=2")
			deployment.Spec.Template.Spec.Containers[0].Args = args
			_, err := f.KubeClientSet.AppsV1().Deployments(f.Namespace).Update(context.TODO(), deployment, metav1.UpdateOptions{})

			return err
		})
		assert.Nil(ginkgo.GinkgoT(), err, "unexpected error updating ingress controller deployment flags")

		f.WaitForNginxListening(80)

		f.NewEchoDeployment()

		f.WaitForNginxConfiguration(
			func(cfg string) bool {
				return strings.Contains(cfg, "server_tokens off")
			})

		f.HTTPTestClient().
			GET("/").
			WithHeader("Host", "foo.bar.com").
			Expect().
			Status(http.StatusNotFound)
	})
})

func createPodSecurityPolicy() *policyv1beta1.PodSecurityPolicy {
	trueValue := true
	return &policyv1beta1.PodSecurityPolicy{
		ObjectMeta: metav1.ObjectMeta{
			Name: ingressControllerPSP,
		},
		Spec: policyv1beta1.PodSecurityPolicySpec{
			AllowPrivilegeEscalation: &trueValue,
			RequiredDropCapabilities: []corev1.Capability{"All"},
			RunAsUser: policyv1beta1.RunAsUserStrategyOptions{
				Rule: "RunAsAny",
			},
			SELinux: policyv1beta1.SELinuxStrategyOptions{
				Rule: "RunAsAny",
			},
			FSGroup: policyv1beta1.FSGroupStrategyOptions{
				Ranges: []policyv1beta1.IDRange{
					{
						Min: 1,
						Max: 65535,
					},
				},
				Rule: "MustRunAs",
			},
			SupplementalGroups: policyv1beta1.SupplementalGroupsStrategyOptions{
				Ranges: []policyv1beta1.IDRange{
					{
						Min: 1,
						Max: 65535,
					},
				},
				Rule: "MustRunAs",
			},
		},
	}
}


text:
//
//   Copyright 2018  SenX S.A.S.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package io.warp10.script.functions;

import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;

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

import org.apache.commons.math3.distribution.NormalDistribution;

/**
 * Pushes onto the stack a list of M-1 bounds defining M + 2 intervals between 'a' and 'b'
 * plus the two intervals before 'a' and after 'b'
 *
 * Expects on the stack
 *
 * 3: a
 * 2: b
 * 1: M
 *
 */
public class LBOUNDS extends NamedWarpScriptFunction implements WarpScriptStackFunction {

  public LBOUNDS(String name) {
    super(name);
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object top = stack.pop();

    if (!(top instanceof Long)) {
      throw new WarpScriptException(getName() + " expects a number of intervals on top of the stack.");
    }

    int n = ((Number) top).intValue();

    if (n < 1) {
      throw new WarpScriptException(getName() + " cannot generate bounds for less than 1 interval.");
    }

    if (n > 65536) {
      throw new WarpScriptException(getName() + " cannot generate bounds for more than 65536 intervals.");
    }

    top = stack.pop();

    if (!(top instanceof Number)) {
      throw new WarpScriptException(getName() + " expects an upper bound below the number of intervals.");
    }

    double upper = ((Number) top).doubleValue();

    top = stack.pop();

    if (!(top instanceof Number)) {
      throw new WarpScriptException(getName() + " expects a lower bounds below the upper bound.");
    }

    double lower = ((Number) top).doubleValue();

    if (lower >= upper) {
      throw new WarpScriptException(getName() + " expects the lower bound to be strictly less than the upper bound.");
    }

    List<Object> bounds = new ArrayList<Object>(n - 1);

    double bound = lower;
    double step = (upper - lower) / n;

    if (0.0 == step) {
      throw new WarpScriptException(getName() + " cannot operate if bounds are too close.");
    }

    bounds.add(lower);

    for (int i = 1; i < n; i++) {
      bounds.add(lower + i * step);
    }

    bounds.add(upper);

    stack.push(bounds);

    return stack;
  }
}