text:
"logfmt" is the name of a key-value logging convention, where log lines are
formatted as "key=value" pairs.

This package decodes individual log lines or streams of log lines. Individual
log lines are decoded as `Map<String, dynamic>` objects, and streams passing
through the `streamDecoder` transform will emit `Map<String, dynamic>` objects, as well.

## Usage

### Logger

A class which can log `Map<String, dynamic>`, and optionally include elapsed
time since the logger was created.

```dart
import 'package:logfmt/logfmt.dart' as logfmt;

void main() {
  logfmt.Logger logger = new logfmt.Logger();
  logger.log({ 'key': 'value' }); // Logs "key=value" to stdout.
  logger.logWithElapsed({ 'key': 'value' }); // Logs "key=value elapsed=1ms" to stdout.
}
```

### #decode

Given a logfmt-style log line, decode it into a `Map<String, dynamic>` using `#decode`:

```dart
import 'package:logfmt/logfmt.dart' as logfmt;
import 'package:unittest/unittest.dart';

void main() {
  test('key=value pairs of non-null and non-boolean strings decode into [Map<String, String>].', () {
    expect(logfmt.decode('key=value'), equals({ 'key': 'value' }));
  });

  test('"flag"s are decoded into [Map<String, bool>] where `bool` is `true`.', () {
    expect(logfmt.decode('flag'), equals({ 'flag': true }));
  });

  test('Pairs with "true" or "false" as values are decoded into [Map<String, bool>], as appropriate.', () {
    expect(logfmt.decode('key=false'), equals({ 'key': false }));
  });

  test('Pairs with "null" values are decoded into [Map<String, Null>].', () {
    expect(logfmt.decode('key=null'), equals({ 'key': null }));
  });

  test('Quoted keys and values are preserved.', () {
    expect(logfmt.decode('"quoted key"="quoted value"'), equals({ 'quoted key': 'quoted value' }));
  });
}
```

### #encode

Given a `Map<String, dynamic>`, encode it into a logfmt-style string using `#encode`:

```dart
import 'package:logfmt/logfmt.dart' as logfmt;
import 'package:unittest/unittest.dart';

void main() {
  test('encodes Map<String, String> into plain key=value.', () {
    expect(logfmt.encode({ 'key': 'value' }), equals('key=value'));
  });

  test('encodes Map<String, bool> into key=${bool.toString}', () {
    expect(logfmt.encode({ 'key': true }), equals('key=true'));
  });

  test('encodes Map<String, Null> into key=${null.toString}', () {
    expect(logfmt.encode({ 'key': null }), equals('key=null'));
  });

  test('encodes long doubles as truncated', () {
    expect(logfmt.encode({ 'longDouble': 0.44444444444444444444 }),
      equals('longDouble=0.4444444444444444'));
  });

  test('encodes dates as UTC ISO 8601', () {
    DateTime date = new DateTime.now();

    expect(logfmt.encode({ 'date': date }),
      equals('date=${date.toUtc().toIso8601String()}'));
  });

  test('encodes multi-word strings as quoted', () {
    expect(logfmt.encode({ 'key': 'quoted value' }),
      equals('key="quoted value"'));
  });

  test('encodes quotes as escaped quotes', () {
    expect(logfmt.encode({ 'key': '"value' }), equals(r'key=\"value'));
  });

  test('encodes new lines with literal \\n characters', () {
    expect(logfmt.encode({ 'key': '\nvalue' }), equals(r'key=\nvalue'));
  });
}
```

### #log

Logs a `Map<String, dynamic>` to either standard out or a given `StringSink`.

```dart
import 'package:logfmt/logfmt.dart' as logfmt;

logfmt.log({ 'key': 'value' }); // "key=value" is logged to standard out.
logfmt.log({ 'key': 'value' }, sink: sink); // The log is written to `sink`.
```

### streamDecoder

A stream of lines can be sent to the `streamDecoder` transformer, which will return a stream emitting `Map<String, dynamic>` objects.

```dart
import 'dart:convert';
import 'dart:io';
import 'package:logfmt/logfmt.dart' as logfmt;

void main() {
  new File('test/log.txt').openRead()
    .transform(new Utf8Decoder())
    .transform(new LineSplitter())
    .transform(logfmt.streamDecoder())
    .listen((Map<String, dynamic> map) {
      print(map);
    });
}
```

### streamEncoder

A stream of `Map<String, dynamic>` can be sent to the `streamEncoder`
transformer, which will return a stream emitting logfmt-style strings.

```dart
import 'dart:async';
import 'package:logfmt/logfmt.dart' as logfmt;

void main() {
  new Stream.fromIterable(maps)
    .transform(logfmt.streamEncoder())
    .listen((String line) {
      print(line);
    });
}
```

## Todo

- Implement an example request logger.


text:
from .ip_v4 import IPv4
from .domain_name import DomainName
from .url_verbatim import URLVerbatim
from .md5 import MD5
from .sha1 import SHA1
from .sha256 import SHA256

redpajama_set_name: RedPajamaGithub


text:
package com.androhi.qitton;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity implements MainFragment.Callbacks {
    private static final String TAG = MainActivity.class.getSimpleName();

    private boolean mTwoPane;

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

        /*
        if (findViewById(R.id.item_detail_container) != null) {
            mTwoPane = true;

            ((MainFragment) getFragmentManager()
            .findFragmentById(R.id.main_fragment))
            .setActivateOnItemClick(true);
        }
        */
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onItemSelected(String id) {
        if (mTwoPane) {
            // 2ペイン表示
        } else {
            Intent detailIntent = new Intent(this, DetailActivity.class);
            detailIntent.putExtra(DetailFragment.ARG_INFO_ID, id);
            startActivity(detailIntent);
        }
    }
}


text:
<?php
/**
 * composer scripthandler
 */

namespace Graviton\GeneratorBundle\Composer;

use Graviton\CoreBundle\Composer\ScriptHandlerBase;
use Composer\Script\Event;

/**
 * ScriptHandler for Composer, wrapping our symfony console commands..
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     http://swisscom.ch
 */
class ScriptHandler extends ScriptHandlerBase
{
    /**
     * Generates dynamic bundles
     *
     * @param CommandEvent $event Event
     *
     * @return void
     */
    public static function generateDynamicBundles(Event $event)
    {
        $options = self::getOptions($event);
        $consolePath = $options['symfony-app-dir'];

        self::executeCommand(
            $event,
            $consolePath,
            ['graviton:generate:dynamicbundles', '--json']
        );
    }
}


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// 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.
//

using System;
using Microsoft.SqlServer.Server;
using Microsoft.WindowsAzure.Common.OData;

namespace Microsoft.Azure.Insights
{
    /// <summary>
    /// The parameters to get the events for a subscription
    /// </summary>
    public class GetCountSummaryParameters
    {
        /// <summary>
        /// Gets or sets the start time
        /// </summary>
        [FilterParameter("startTime", "O")]
        public DateTime StartTime { get; set; }

        /// <summary>
        /// Gets or sets the end time.
        /// </summary>
        [FilterParameter("endTime", "O")]
        public DateTime? EndTime { get; set; }
    }

    /// <summary>
    /// The parameters to get the event count summary for an event source
    /// </summary>
    public class GetCountSummaryForEventSourceParameters : GetCountSummaryParameters
    {
        /// <summary>
        /// Gets or sets the event source
        /// </summary>
        [FilterParameter("eventSource")]
        public string EventSource { get; set; }
    }

    /// <summary>
    /// The parameters to get the event count summary for a resource
    /// </summary>
    public class GetCountSummaryForResourceParameters : GetCountSummaryParameters
    {
        /// <summary>
        /// Gets or sets the resource uri
        /// </summary>
        [FilterParameter("resourceUri")]
        public string ResourceUri { get; set; }
    }

    /// <summary>
    /// The parameters to get the event count summary for a resource group
    /// </summary>
    public class GetCountSummaryForResourceGroupParameters : GetCountSummaryParameters
    {
        /// <summary>
        /// Gets or sets the resource group name
        /// </summary>
        [FilterParameter("resourceGroupName")]
        public string ResourceGroupName { get; set; }
    }

    /// <summary>
    /// The parameters to get the event count summary for a resource provider
    /// </summary>
    public class GetCountSummaryForResourceProviderParameters : GetCountSummaryParameters
    {
        /// <summary>
        /// Gets or sets the resource provider
        /// </summary>
        [FilterParameter("resourceProvider")]
        public string ResourceProvider { get; set; }
    }
}


text:
from flask import render_template, session, redirect, request
from run import app
import pyrebase

config = {
    "apiKey": "AIzaSyB5lNPIMw2taY-RqTAH39NUquFVn54ECLk",
    "authDomain": "codebrew2k17.firebaseapp.com",
    "databaseURL": "https://codebrew2k17.firebaseio.com",
    "storageBucket": "codebrew2k17.appspot.com",
    "serviceAccount": "codebrew2k17-firebase-adminsdk-pv7y6-8935885448.json"
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()

@app.route("/sign-up",methods=['GET','POST'])
def sign_up():

	return render_template("sign-up.html")


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum LicenseFeatureInfoSourceRestriction {
  unrestricted ("unrestricted"),
  served ("served"),
  file ("file");

  @SuppressWarnings("unused")
  private final String val;
  private LicenseFeatureInfoSourceRestriction(String val)
  {
    this.val = val;
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Celsia cretica L.

### Remarks
null


text:
alter table ACT_RU_TASK add column IS_COUNT_ENABLED_ smallint check(IS_MI_ROOT_ in (1,0));
alter table ACT_RU_TASK add column VAR_COUNT_ integer;
alter table ACT_RU_TASK add column ID_LINK_COUNT_ integer;

update ACT_GE_PROPERTY set VALUE_ = '6.0.0.5' where NAME_ = 'schema.version';


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CommentReply extends Model
{
    public $incrementing = false;
}


text:
<?php
/**
 *
 */

namespace common\models;

use admin\models\CrudAction;
use admin\models\Status;
use Yii;
use yii\base\BootstrapInterface;

class Settings implements BootstrapInterface
{

    private $db;

    public function __construct()
    {
        $this->db = Yii::$app->db;
    }

    /**
     * Bootstrap method to be called during application bootstrap stage.
     * Loads all the settings into the Yii::$app->params array
     * @param Application $app the application currently running
     */

    public function bootstrap($app)
    {
        // Get status from database
        $status = Status::find()->select(['id', 'status'])->asArray()->all();
        foreach ($status as $s) {
            Yii::$app->params['status'][$s['status']] = $s['id'];
        }

        // Get crud actions from database
        /*$status = CrudAction::find()->select(['id', 'action'])->asArray()->all();
        foreach ($status as $s) {
            Yii::$app->params['crud_action'][$s['action']] = $s['id'];
        }*/
    }
}


text:
package com.matthewlogan.selectablemapfragment.library;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

/**
 * Created by matthewlogan on 5/20/14.
 */
public class SupportSelectableMapFragment extends MapFragment
        implements TouchableMapWrapper.OnMapTouchListener, GoogleMap.OnMapClickListener {

    public static final float sBaseOverlaySquareSize = 10000;

    private View mContentView;
    private GoogleMap mGoogleMap;

    private GroundOverlayOptions mDraggableOverlayBoxOptions;
    private GroundOverlay mDraggableOverlayBox;

    private OnOverlayDragListener mListener;

    private boolean mIsDraggingBox;

    private float mLastX;
    private float mLastY;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        mContentView = super.onCreateView(inflater, parent, savedInstanceState);

        TouchableMapWrapper touchableMapWrapper = new TouchableMapWrapper(getActivity());
        touchableMapWrapper.addView(mContentView);
        touchableMapWrapper.setOnMapTouchListener(this);

        return touchableMapWrapper;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleMap == null) {
            mGoogleMap = getMap();
            if (mGoogleMap != null) {
                mGoogleMap.setOnMapClickListener(this);
            }
        }
    }

    @Override
    public View getView() {
        return mContentView;
    }

    @Override
    public void onMapTouch(MotionEvent event) {

        if (event.getPointerCount() == 1 && mDraggableOverlayBox != null) {

            final int w = getView().getWidth();
            final int h = getView().getHeight();

            LatLng touchPoint = OverlayUtils.convertPointToLatLng(w, h,
                    event.getX(), h - event.getY(), mGoogleMap);

            switch (event.getActionMasked()) {

                case MotionEvent.ACTION_DOWN:
                    if (OverlayUtils.isPointContainedInOverlay(mDraggableOverlayBox, touchPoint)) {
                        mIsDraggingBox = true;
                        mGoogleMap.getUiSettings().setScrollGesturesEnabled(Boolean.FALSE);
                        mLastX = event.getX();
                        mLastY = event.getY();
                    }
                    break;

                case MotionEvent.ACTION_MOVE:
                    if (mIsDraggingBox) {
                        LatLng lastTouchPoint = OverlayUtils.convertPointToLatLng(w, h,
                                mLastX, h - mLastY, mGoogleMap);

                        LatLng oldPos = mDraggableOverlayBox.getPosition();

                        double diffLat = touchPoint.latitude - lastTouchPoint.latitude;
                        double diffLng = touchPoint.longitude - lastTouchPoint.longitude;

                        mDraggableOverlayBox.setPosition(new LatLng(
                                oldPos.latitude + diffLat,
                                oldPos.longitude + diffLng));

                        if (mListener != null) {
                            mListener.onOverlayDrag(mDraggableOverlayBox.getBounds());
                        }

                        mLastX = event.getX();
                        mLastY = event.getY();
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    mIsDraggingBox = false;
                    mGoogleMap.getUiSettings().setScrollGesturesEnabled(Boolean.TRUE);
                    break;

                default:
                    break;
            }

        } else {
            mGoogleMap.getUiSettings().setScrollGesturesEnabled(Boolean.TRUE);
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (mDraggableOverlayBox != null) {
            mDraggableOverlayBox.setPosition(latLng);
            if (mListener != null) {
                mListener.onOverlayDrag(mDraggableOverlayBox.getBounds());
            }
        }
    }

    public void setOnOverlayDragListener(OnOverlayDragListener listener) {
        mListener = listener;
    }

    public void showSelectionBox() {
        if (mDraggableOverlayBoxOptions == null) {
            Bitmap bm = OverlayUtils.makeSquareOverlayBitmap(getActivity());
            LatLng startPosition = mGoogleMap.getCameraPosition().target;

            mDraggableOverlayBoxOptions = new GroundOverlayOptions()
                    .image(BitmapDescriptorFactory.fromBitmap(bm))
                    .zIndex(1)
                    .position(startPosition, sBaseOverlaySquareSize);
        }

        mDraggableOverlayBox = mGoogleMap.addGroundOverlay(mDraggableOverlayBoxOptions);
        mDraggableOverlayBox.setPosition(mGoogleMap.getCameraPosition().target);
    }

    public void hideSelectionBox() {
        if (mDraggableOverlayBox != null) {
            mDraggableOverlayBox.setVisible(false);
            mDraggableOverlayBox = null;
        }
    }

    public void setSelectionBoxVisible(boolean visible) {
        if (visible) {
            showSelectionBox();
        } else {
            hideSelectionBox();
        }
    }

    public boolean isSelectionBoxVisible() {
        return mDraggableOverlayBox != null;
    }

    public LatLngBounds getSelectionBoxBounds() {
        if (mDraggableOverlayBox != null) {
            return mDraggableOverlayBox.getBounds();
        }
        return null;
    }
}


text:
package io.github.movementspeed.nhglib.input.models;

/**
 * Created by Fausto Napoli on 22/01/2017.
 */
public class InputSource {
    private String name;
    private Object value;

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public boolean is(String name) {
        return name.contentEquals(name);
    }

    public String getName() {
        return name;
    }

    public Object getValue() {
        return value;
    }
}


text:
package com.dibujaron.BetterPassives;

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

import org.bukkit.configuration.Configuration;
import org.bukkit.entity.EntityType;

public class Settings {

	private static List<EntityType> passives;
	private static List<EntityType> hostiles;
	private static HashMap<Planet, List<String>> specials = new HashMap<Planet, List<String>>();
	private static HashMap<String, Planet> planets = new HashMap<String, Planet>();
	private static int tamedPerChunk = 16;
	private static int hostilesPerChunk = 16;

	public static void loadSettings(Configuration c) {
		if (c.contains("passivesperchunk")) {
			tamedPerChunk = c.getInt("passivesperchunk");
		}
		if(c.contains("hostilesPerChunk"))
			hostilesPerChunk = c.getInt("hostilesPerChunk");
		passives = new ArrayList<EntityType>();
		for (String s : c.getStringList("allPassives")) {
			EntityType t = EntityType.valueOf(s.toUpperCase());
			if (t == null) {
				System.out.println("No EntityType found for " + s + "!");
			} else {
				passives.add(EntityType.valueOf(s.toUpperCase()));
			}
		}

		hostiles = new ArrayList<EntityType>();
		for (String s : c.getStringList("allHostiles")) {
			EntityType t = EntityType.valueOf(s.toUpperCase());
			if (t == null) {
				System.out.println("No EntityType found for " + s + "!");
			} else {
				hostiles.add(t);
			}
		}

		for (String key : c.getConfigurationSection("planets").getKeys(false)) {
			List<String> passives = c.getStringList("planets." + key + ".passives");
			List<String> hostiles = c.getStringList("planets." + key + ".hostiles");
			System.out
					.println("Loaded " + passives.size() + " passives and " + hostiles.size() + " hostiles for " + key);
			Planet p = new Planet(key, hostiles, passives);
			planets.put(key.toLowerCase(), p);

			List<String> specialProperties = c.getStringList("planets." + key + ".specials");
			System.out.println("Loaded " + specialProperties.size() + " special properties for " + key);
			specials.put(p, specialProperties);
		}
	}

	public static int getTamedPerChunk() {
		return tamedPerChunk;
	}

	public static int getHostilesPerChunk()
	{
		return hostilesPerChunk;
	}

	public static List<EntityType> getAllHostiles() {
		return hostiles;
	}

	public static List<EntityType> getAllPassives() {
		return passives;
	}

	/**
	 * Gets a list of all allowed hostiles for a planet, defined in the config.<br>
	 * Returns null if there are no hostiles in the config for a planet
	 * @param planet planet name
	 * @return An EntityType list of the allowed hostiles for a planet
	 */
	public static List<EntityType> getHostilesOfPlanet(String planet) {
		Planet p = planets.get(planet.toLowerCase());
		if (p != null) {
			if (p.hostiles().size() > 0) {
				return p.hostiles();
			}
		}
		return null;
	}

	public static List<EntityType> getPassivesOfPlanet(String planet) {
		Planet p = planets.get(planet.toLowerCase());
		if (p != null) {
			if (p.passives().size() > 0)
				return p.passives();
		}
		return null;
	}

	/**
	 *
	 * @param planet name
	 * @return String list containing all the special properties for a planet or null if the planet name is not valid.
	 */
	public static List<String> getSpecialPropertiesOfPlanet(String planet)
	{
		Planet p = planets.get(planet.toLowerCase());
		if(p != null)
		{
			List<String> specialProperties = specials.get(p);
			return specialProperties;
		}
		else
			return null;
	}

	private static class Planet {

		String name;
		List<EntityType> hostiles;
		List<EntityType> passives;

		public Planet(String name, List<String> hostiles, List<String> passives) {
			this.name = name;
			this.hostiles = new ArrayList<EntityType>();
			for (String s : hostiles) {
				s = s.toUpperCase();
				EntityType t = EntityType.valueOf(s);
				if (t == null) {
					System.out.println("No EntityType found for " + s + "!");
				} else {
					this.hostiles.add(EntityType.valueOf(s));
				}
			}

			this.passives = new ArrayList<EntityType>();
			for (String s : passives) {
				s = s.toUpperCase();
				EntityType t = EntityType.valueOf(s);
				if (t == null) {
					System.out.println("No EntityType found for " + s + "!");
				} else {
					this.passives.add(EntityType.valueOf(s));
				}
			}
		}

		@SuppressWarnings("unused")
		public String getName() {
			return name;
		}

		public List<EntityType> hostiles() {
			return hostiles;
		}

		public List<EntityType> passives() {
			return passives;
		}
	}
}


text:
<!--
    JBoss, Home of Professional Open Source
    Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual contributors.

    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.
-->
<configuration xmlns="urn:hornetq">

   <connection-factory name="ConnectionFactory">
      <connectors>
        <connector-ref connector-name="invm-connector"/>
      </connectors>

      <entries>
         <entry name="ConnectionFactory"/>
      </entries>
   </connection-factory>

   <queue name="GreetingServiceQueue">
      <entry name="GreetingServiceQueue"/>
   </queue>

</configuration>


text:
{% extends "registration/base.html" %}

{% block title %}Edit: {{ object.name }} - {{ block.super }}{% endblock title %}

{% block section_title %}
Edit: {{ object.name }}
{% endblock section_title %}

{% block section %}

<form method="post" action="{{ object.get_edit_url }}" enctype="multipart/form-data">
  {% include "includes/form.html" with form=form %}
  <p>
    {% csrf_token %}
    <button type="submit">Update</button>
  </p>
</form>
{% endblock section %}

{% block extra_scripts %}{{ form.media }}{% endblock extra_scripts %}


text:
  $date$ / Ng Wei En

$title$

$body$

You can view the history of changes made to this post at this
  website's GitHub repository.


text:
// UpdateProperties.java
// (C) 2016 Masato Kokubo

package org.lightsleep.entity;

import java.lang.annotation.*;

/**
 * Indicates an array of UpdateProperty annotations.
 *
 * @since 1.3.0
 * @author Masato Kokubo
 * @see UpdateProperty
 * @see UpdateProperties
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface UpdateProperties {
    /** @return the array of UpdateProperty annotations */
    UpdateProperty[] value();
}


text:
require 'rails_helper'
require 'support/controller_macros'
require 'public_activity/testing'

describe TasksController do

    before(:each) do
      PublicActivity.enabled = false
      login_admin
      authenticate_admin(@admin)
    end

    it "has an admin present" do
      expect(current_admin).to be_present
    end

    describe 'GET #index' do
      it "receives a success response for get 'index' route" do
        get :index
        expect(response).to be_success
      end
      it "renders the :index template" do
        get :index
        expect(response).to render_template :index
      end
    end

end


text:
<?php

namespace interactivesolutions\honeycombecommerceorders\app\models\ecommerce\orders;

use interactivesolutions\honeycombcore\models\HCUuidModel;
use interactivesolutions\honeycombecommercecarriers\app\models\ecommerce\HCECCarriers;
use interactivesolutions\honeycombecommerceorders\app\models\ecommerce\HCECOrders;

class HCECOrderCarriers extends HCUuidModel
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'hc_order_carriers';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id', 'order_id', 'carrier_id', 'name', 'weight', 'shipping_price', 'shipping_price_before_tax', 'shipping_tax_amount', 'tax_name', 'tax_value', 'user_note', 'tracking_number', 'location'];

    /**
     * Relation to order
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function order()
    {
        return $this->belongsTo(HCECOrders::class, 'order_id', 'id');
    }

    /**
     * Relation to order
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function carrier()
    {
        return $this->belongsTo(HCECCarriers::class, 'carrier_id', 'id');
    }
}


text:
package org.broadinstitute.hellbender.engine.dataflow.transforms.examples;

import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.testing.DataflowAssert;
import com.google.cloud.dataflow.sdk.transforms.Create;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.DoFnTester;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.common.collect.Lists;
import org.broadinstitute.hellbender.engine.dataflow.GATKTestPipeline;
import org.broadinstitute.hellbender.engine.ReferenceShard;
import org.broadinstitute.hellbender.utils.test.BaseTest;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public final class SampleUnitTest extends BaseTest{

    @DataProvider(name = "refAndInts")
    public Object[][] refAndInts(){
        Integer[] integers = new Integer[]{1, 2, 3, 4};
        Set<KV<ReferenceShard, Integer>> s = new HashSet<>();
        s.add(KV.of(new ReferenceShard(1, "1"), 1));
        s.add(KV.of(new ReferenceShard(2, "2"), 2));
        s.add(KV.of(new ReferenceShard(3, "3"), 3));
        s.add(KV.of(new ReferenceShard(4, "4"), 4));

        return new Object[][]{
                { integers, s}
        };
    }

    @DataProvider(name = "refs")
    public Object[][] refs(){
        ReferenceShard[] integers = new ReferenceShard[]{
                new ReferenceShard(1, "1"),
                new ReferenceShard(2, "2"),
                new ReferenceShard(3, "3"),
                new ReferenceShard(4, "4")
        };
        Set<ReferenceShard> s = new HashSet<>();
        s.add(new ReferenceShard(1, "1"));
        s.add(new ReferenceShard(2, "2"));
        s.add(new ReferenceShard(3, "3"));
        s.add(new ReferenceShard(4, "4"));

        return new Object[][]{
                { integers, s}
        };
    }

    static class GroupIntsDoFn extends DoFn<Integer, KV<ReferenceShard, Integer>> {
        private static final long serialVersionUID = 1L;
        @Override
        public void processElement(ProcessContext c) throws Exception {
            Integer i = c.element();
            c.output(KV.of(new ReferenceShard(i.intValue(), i.toString()), i));
        }
    }

    static class IterableRefShardsDoFn extends DoFn<ReferenceShard, Iterable<ReferenceShard>> {
        private static final long serialVersionUID = 1L;
        @Override
        public void processElement(ProcessContext c) throws Exception {
            ReferenceShard i = c.element();
            c.output(Lists.newArrayList(i, i, i));
        }
    }

    @Test(dataProvider = "refAndInts")
    public void GroupIntsTest(Integer[] integers, Set<KV<ReferenceShard, Integer>> s) {
        DoFnTester<Integer, KV<ReferenceShard, Integer>> fnTester = DoFnTester.of(new GroupIntsDoFn());
        List<KV<ReferenceShard, Integer>> kvs = fnTester.processBatch(integers);
        for (KV<ReferenceShard, Integer> r : kvs) {
            Assert.assertTrue(s.contains(r));
        }
    }

    @Test(dataProvider = "refs")
    public void anotherDoFnTest(ReferenceShard[] referenceShards, Set<ReferenceShard> s) {
        DoFnTester<ReferenceShard, Iterable<ReferenceShard>> fnTester = DoFnTester.of(new IterableRefShardsDoFn());
        List<Iterable<ReferenceShard>> kvs = fnTester.processBatch(referenceShards);

        Assert.assertEquals(referenceShards.length, kvs.size());
        for (Iterable<ReferenceShard> intz : kvs) {
            int size = 0;
            for (ReferenceShard i : intz) {
                size++;
                Assert.assertTrue(s.contains(i));
            }
            Assert.assertEquals(3, size);
        }
    }

    @Test(dataProvider = "refs")
    public void createRefsTest(ReferenceShard[] referenceShards, Set<ReferenceShard> s) {
        // The simplist way to figure out if a class is coded correctly is to create a PCollection
        // of that type and see if matches the List version.
        Pipeline p = GATKTestPipeline.create();
        // We don't need to call:
        p.getCoderRegistry().registerCoder(ReferenceShard.class, ReferenceShard.CODER);
        // because we use the DefaultCoder annotation on the class.
        List<ReferenceShard> shards = Lists.newArrayList(referenceShards);
        List<ReferenceShard> shards2 = Lists.newArrayList(referenceShards);
        PCollection<ReferenceShard> pShards = p.apply(Create.of(shards));
        DataflowAssert.that(pShards).containsInAnyOrder(shards2);
        p.run();
    }

    @Test(dataProvider = "refAndInts")
    public void transformExampleTest(Integer[] integers, Set<KV<ReferenceShard, Integer>> s) {
        Pipeline p = GATKTestPipeline.create();
        p.getCoderRegistry().registerCoder(ReferenceShard.class, ReferenceShard.CODER);

        List<Integer> ints = Lists.newArrayList(integers);
        PCollection<Integer> pInts = p.apply(Create.of(ints));

        // Note that we needed to make the Transform a full class (not anonymous).
        // So, you can't test a PTransform by writing it within a test.
        PCollection<KV<ReferenceShard, Integer>> keyedInts =
                pInts.apply(new TransformExample());
        List<KV<ReferenceShard, Integer>> e = Lists.newArrayList(s);
        DataflowAssert.that(keyedInts).containsInAnyOrder(e);

        p.run();
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SalesForceBackup.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)]
        [global::System.Configuration.DefaultSettingValueAttribute("https://login.salesforce.com/services/Soap/c/32.0/0DFo000000004N4")]
        public string SalesForceBackup_SFDC_SforceService {
            get {
                return ((string)(this["SalesForceBackup_SFDC_SforceService"]));
            }
        }
    }
}


text:
package com.jmco.utils;

/**
 *
 * @author mhusam [m-husam@hotmail.com]
 * @since 1.0.0
 * @datetime Jun 30, 2017 2:05:27 PM
 */
public interface ProgressListener {

    void finished();

    void message(String message);

    void progress(long poisition, long end);
}


text:
#include <boost/python.hpp>
#include <ImathHalfLimits.h>
#include <string>
#include <sstream>

namespace bp = boost::python;

// to-python converter
struct half_to_float
{
	static PyObject* convert(const half& h) {
		return bp::incref(bp::object(h.operator float()).ptr());
	}
};

// from-python converter
struct half_from_number
{
	static void* convertible(PyObject* obj_ptr)
	{
		return (PyFloat_Check(obj_ptr) || PyInt_Check(obj_ptr))?
			obj_ptr : NULL;
	}

	static void construct(PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data)
	{
		float f = (PyFloat_Check(obj_ptr))?
			static_cast<float>(PyFloat_AsDouble(obj_ptr)) :
			static_cast<float>(PyInt_AsLong(obj_ptr));

		void* storage = ((bp::converter::rvalue_from_python_storage<half>*)data)->storage.bytes;
		new(storage) half(f);
		data->convertible = storage;
	}
};

void _pimath_export_half()
{
	bp::to_python_converter<half, half_to_float>();

	bp::converter::registry::push_back(&half_from_number::convertible,
		&half_from_number::construct, bp::type_id<half>());
}


text:
package org.limeprotocol.network.modules;

import org.junit.Before;
import org.junit.Test;
import org.limeprotocol.Command;
import org.limeprotocol.Message;
import org.limeprotocol.Session;
import org.limeprotocol.client.ClientChannel;
import org.limeprotocol.network.Channel;
import org.limeprotocol.network.Transport;
import org.limeprotocol.testHelpers.Dummy;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.IOException;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.limeprotocol.testHelpers.Dummy.*;
import static org.mockito.Mockito.*;

public class RemotePingChannelModuleTest {

    @Mock
    private ClientChannel channel;
    @Mock
    private Transport transport;
    @Captor
    private ArgumentCaptor<Command> commandCaptor;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        when(transport.isConnected()).thenReturn(true);
        when(channel.getTransport()).thenReturn(transport);
        when(channel.getState()).thenReturn(Session.SessionState.ESTABLISHED);
    }

    private RemotePingChannelModule getTarget(long pingInterval, long pingDisconnectionInterval) {
        return RemotePingChannelModule.createAndRegister(channel, pingInterval, pingDisconnectionInterval);
    }

    @Test
    public void onStateChanged_established_sendsPingsAfterPingInterval() throws InterruptedException, IOException {
        // Arrange
        RemotePingChannelModule target = getTarget(100, 400);

        // Act
        target.onStateChanged(Session.SessionState.ESTABLISHED);
        Thread.sleep(500);

        // Assert
        verify(channel, times(3)).sendCommand(commandCaptor.capture());
        assertEquals("/ping", commandCaptor.getValue().getUri().toString());
        assertEquals(Command.CommandMethod.GET, commandCaptor.getValue().getMethod());
    }

    @Test
    public void onStateChanged_established_sendsFinishingSessionAfterDisconnectionInterval() throws InterruptedException, IOException {
        // Arrange
        RemotePingChannelModule target = getTarget(100, 100);

        // Act
        target.onStateChanged(Session.SessionState.ESTABLISHED);
        Thread.sleep(150);

        // Assert
        verify(channel, times(1)).sendFinishingSession();
    }

    @Test
    public void onReceived_schedulePing_doNotSendPing() throws InterruptedException, IOException {
        // Arrange
        Message message = createMessage(createTextContent());
        RemotePingChannelModule target = getTarget(200, 0);
        target.onStateChanged(Session.SessionState.ESTABLISHED);

        // Act
        Thread.sleep(125);
        target.onReceiving(message);
        Thread.sleep(125);

        // Assert
        verify(channel, never()).sendCommand(any(Command.class));
    }
}


text:
package org.apache.geode.cache.lucene.internal.results;

import org.apache.geode.cache.execute.FunctionException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.distributed.DistributedMember;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MapResultCollector implements ResultCollector<List<PageEntry>, Map<Object, Object>> {
  private final Map<Object, Object> results = new HashMap<>();

  @Override
  public Map<Object, Object> getResult() throws FunctionException {
    return results;
  }

  @Override
  public Map<Object, Object> getResult(final long timeout, final TimeUnit unit)
      throws FunctionException, InterruptedException {
    return results;
  }

  @Override
  public void addResult(final DistributedMember memberID,
      final List<PageEntry> resultOfSingleExecution) {
    for (PageEntry entry : resultOfSingleExecution) {
      results.put(entry.getKey(), entry.getValue());
    }
  }

  @Override
  public void endResults() {

  }

  @Override
  public void clearResults() {
    results.clear();

  }
}


text:
package org.wso2.developerstudio.eclipse.ds.impl;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;

import org.wso2.developerstudio.eclipse.ds.DsPackage;
import org.wso2.developerstudio.eclipse.ds.WorkBookName;

/**
 *
 * An implementation of the model object 'Work Book Name'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.wso2.developerstudio.eclipse.ds.impl.WorkBookNameImpl#getValue Value}

 *

 *

 *
 * @generated
 */
public class WorkBookNameImpl extends EObjectImpl implements WorkBookName {
	/**
	 * The default value of the '{@link #getValue() Value}' attribute.
	 *
	 *
	 * @see #getValue()
	 * @generated
	 * @ordered
	 */
	protected static final String VALUE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getValue() Value}' attribute.
	 *
	 *
	 * @see #getValue()
	 * @generated
	 * @ordered
	 */
	protected String value = VALUE_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected WorkBookNameImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	protected EClass eStaticClass() {
		return DsPackage.Literals.WORK_BOOK_NAME;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getValue() {
		return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setValue(String newValue) {
		String oldValue = value;
		value = newValue;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DsPackage.WORK_BOOK_NAME__VALUE, oldValue, value));
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case DsPackage.WORK_BOOK_NAME__VALUE:
				return getValue();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case DsPackage.WORK_BOOK_NAME__VALUE:
				setValue((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DsPackage.WORK_BOOK_NAME__VALUE:
				setValue(VALUE_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case DsPackage.WORK_BOOK_NAME__VALUE:
				return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */

	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (value: ");
		result.append(value);
		result.append(')');
		return result.toString();
	}

} // WorkBookNameImpl


text:
void setupMenu();
void updateControlMenu();

#endif


text:
/*
Provides a simple, 'Pub-Sub' library for Go. For a description of Publish-Subscriber (also known as Pub-Sub), please see
See http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern for a description of the Publish-Subscribe pattern.

Please note, that go routines and channels are used in the background, not queues for the purpose of delivering messages. This design has been recently
revamped to use a single go-routine behind the scenes for routing messages. Each Subscribe and Publish event occurs in its own dedicated go-routine, so that
in case it blocks - other go-routines are unaffected. Bear in mind the architecture here is highly asynchronous.

Effort has been placed to make sure 'listening' occurs before an event is actually sent. In case of problems (which you can't cross out entirely due to the
asynchronous behaviour) events that have been published but that do not find a recipient are 'requeued' back with a progressively bigger delay.

For more information, please see the README at: https://github.com/tholowka/pub-sub.
*/
package events

import (
    "time"
)

/*
The Publisher in the Publish-Subscribe pattern, or a shorthand for a function which you may call each time you want to inform about a particular event. Publishers can be created by any Topic instance.
*/
type Publisher func(interface{})
/*
The Subscriber in the Publish-Subscribe pattern, or a shorthand for a function which you may provide, that is invoked whenever an event is published to the Topic.
*/
type Subscriber func(interface{})
/*
A typical Topic used in a Pub-Sub pattern. The Topic has a name, which in theory should identify it uniquely among other topics.
The implementation does not use this name, unless for informative reasons. Topics can create Publishers and Subscribers.
Topics can be closed and this closes the Topic permanently.
*/
type Topic interface {
    //Allows you to create a new Publisher for a Topic.
	//Publishing may occur in its own go-routine, and
	//it's not guaranteed that the order you call Publishers is preserved
	//(especially if you write to multiple Topics).
    NewPublisher() Publisher
    //Allows you to register an arbitrary Subscriber for events in the Topic.
    //Subscribing may occur in its own go-routine, hence even if the act of
	//subscribing 'blocks' (for example due to the waiting on channel), the
	//remaining Topics still execute normally.
    NewSubscriber(subscriber Subscriber)
    //Returns the topic's name
    String() string
    //Close frees the underlying resources, and depending on the implementation
	//may render the Topic unusable
    Close() error
}

/**
This is the access point to the library.
Exposes the top most layer of this library, which allows you to create Topics and Join them.

The advantage of using Subscribers in factory methods (e.g. NewTopic/AndGate/OrGate) instead of calling them explicitly after Topic construction (i.e. NewSubscriber()) is that you don't get into a
race condition: the subscribers are registered exactly at the moment the topic is registered.

Since 2.0
*/

type Factory interface {
	//Creates a new standard Topic
    NewTopic(string, ...Subscriber) Topic
	//Creates a Topic, backed by a Go Ticker, which can be subscribed
	//to for Tick events. Publishing to it does not make sense.
    NewTickerTopic(string, time.Duration) Topic
	//Closes all Topics created by this Factory.
    Close() error
	//Creates a Topic implementing an AND gate (i.e. collecting
	//multiple events from various topics together and firing
	//only when all Topic have been Published to)
    AndGate([]Topic, ...Subscriber) Topic
	//Creates a Topic implementing an OR gate (i.e. collecting
	//any event from various topics, and firing when any
	//such event has been registered
    OrGate([]Topic, ...Subscriber) Topic
}


text:
What is included in directories?

Each directory consists of at least following files:

 * fuzzer -stub to act as the interface between the `libfuzzer` and the test target
 * build.sh - script to build the library, and the stub and to link them with the fuzzer
 * Dockerfile - to build Docker image

# Building

Base image can be pulled from Dockerhub to avoid building locally.

```console
$ docker pull ouspg/libfuzzer-base
```

Stub images can be built using docker-compose

```console
$ docker-compose build <stub-name>
```

# Running

## Starting the container

```console
$ docker-compose run <stub-name>
```

Fuzzer is started automatically when container is started with docker-compose.

```console
INFO: Seed: 50837522
INFO: -max_len is not provided, using 64
INFO: A corpus is not provided, starting from an empty corpus
#0      READ   units: 1 exec/s: 0
#1      INITED cov: 12 bits: 12 units: 1 exec/s: 0
#2      NEW    cov: 15 bits: 15 units: 2 exec/s: 0 L: 64 MS: 0
...
```

# Example

[mysamplelib readme](mysamplelib/README.md) is also suggested to read to get started testing and writing your own stubs.


text:
package org.apache.nifi.hbase;

import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.hbase.io.JsonFullRowSerializer;
import org.apache.nifi.hbase.io.JsonQualifierAndValueRowSerializer;
import org.apache.nifi.hbase.io.RowSerializer;
import org.apache.nifi.hbase.scan.Column;
import org.apache.nifi.hbase.scan.ResultCell;
import org.apache.nifi.hbase.scan.ResultHandler;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
@Tags({"hbase", "scan", "fetch", "get", "enrich"})
@CapabilityDescription("Fetches a row from an HBase table. The Destination property controls whether the cells are added as flow file attributes, " +
        "or the row is written to the flow file content as JSON. This processor may be used to fetch a fixed row on a interval by specifying the " +
        "table and row id directly in the processor, or it may be used to dynamically fetch rows by referencing the table and row id from " +
        "incoming flow files.")
@WritesAttributes({
        @WritesAttribute(attribute = "hbase.table", description = "The name of the HBase table that the row was fetched from"),
        @WritesAttribute(attribute = "hbase.row", description = "A JSON document representing the row. This property is only written when a Destination of flowfile-attributes is selected."),
        @WritesAttribute(attribute = "mime.type", description = "Set to application/json when using a Destination of flowfile-content, not set or modified otherwise")
})
public class FetchHBaseRow extends AbstractProcessor {

    static final Pattern COLUMNS_PATTERN = Pattern.compile("\\w+(:\\w+)?(?:,\\w+(:\\w+)?)*");

    static final PropertyDescriptor HBASE_CLIENT_SERVICE = new PropertyDescriptor.Builder()
            .name("HBase Client Service")
            .description("Specifies the Controller Service to use for accessing HBase.")
            .required(true)
            .identifiesControllerService(HBaseClientService.class)
            .build();

    static final PropertyDescriptor TABLE_NAME = new PropertyDescriptor.Builder()
            .name("Table Name")
            .description("The name of the HBase Table to fetch from.")
            .required(true)
            .expressionLanguageSupported(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();

    static final PropertyDescriptor ROW_ID = new PropertyDescriptor.Builder()
            .name("Row Identifier")
            .description("The identifier of the row to fetch.")
            .required(true)
            .expressionLanguageSupported(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();

    static final PropertyDescriptor COLUMNS = new PropertyDescriptor.Builder()
            .name("Columns")
            .description("An optional comma-separated list of \"<colFamily>:<colQualifier>\" pairs to fetch. To return all columns " +
                    "for a given family, leave off the qualifier such as \"<colFamily1>,<colFamily2>\".")
            .required(false)
            .expressionLanguageSupported(true)
            .addValidator(StandardValidators.createRegexMatchingValidator(COLUMNS_PATTERN))
            .build();

    static final AllowableValue DESTINATION_ATTRIBUTES = new AllowableValue("flowfile-attributes", "flowfile-attributes",
            "Adds the JSON document representing the row that was fetched as an attribute named hbase.row. " +
                    "The format of the JSON document is determined by the JSON Format property. " +
                    "NOTE: Fetching many large rows into attributes may have a negative impact on performance.");

    static final AllowableValue DESTINATION_CONTENT = new AllowableValue("flowfile-content", "flowfile-content",
            "Overwrites the FlowFile content with a JSON document representing the row that was fetched. " +
                    "The format of the JSON document is determined by the JSON Format property.");

    static final PropertyDescriptor DESTINATION = new PropertyDescriptor.Builder()
            .name("Destination")
            .description("Indicates whether the row fetched from HBase is written to FlowFile content or FlowFile Attributes.")
            .required(true)
            .allowableValues(DESTINATION_ATTRIBUTES, DESTINATION_CONTENT)
            .defaultValue(DESTINATION_ATTRIBUTES.getValue())
            .build();

    static final AllowableValue JSON_FORMAT_FULL_ROW = new AllowableValue("full-row", "full-row",
            "Creates a JSON document with the format: {\"row\":<row-id>, \"cells\":[{\"fam\":<col-fam>, \"qual\":<col-val>, \"val\":<value>, \"ts\":<timestamp>}]}.");
    static final AllowableValue JSON_FORMAT_QUALIFIER_AND_VALUE = new AllowableValue("col-qual-and-val", "col-qual-and-val",
            "Creates a JSON document with the format: {\"<col-qual>\":\"<value>\", \"<col-qual>\":\"<value>\".");

    static final PropertyDescriptor JSON_FORMAT = new PropertyDescriptor.Builder()
            .name("JSON Format")
            .description("Specifies how to represent the HBase row as a JSON document.")
            .required(true)
            .allowableValues(JSON_FORMAT_FULL_ROW, JSON_FORMAT_QUALIFIER_AND_VALUE)
            .defaultValue(JSON_FORMAT_FULL_ROW.getValue())
            .build();

    static final AllowableValue ENCODING_NONE = new AllowableValue("none", "none", "Creates a String using the bytes of given data and the given Character Set.");
    static final AllowableValue ENCODING_BASE64 = new AllowableValue("base64", "base64", "Creates a Base64 encoded String of the given data.");

    static final PropertyDescriptor JSON_VALUE_ENCODING = new PropertyDescriptor.Builder()
            .name("JSON Value Encoding")
            .description("Specifies how to represent row ids, column families, column qualifiers, and values when stored in FlowFile attributes, or written to JSON.")
            .required(true)
            .allowableValues(ENCODING_NONE, ENCODING_BASE64)
            .defaultValue(ENCODING_NONE.getValue())
            .build();

    static final PropertyDescriptor DECODE_CHARSET = new PropertyDescriptor.Builder()
            .name("Decode Character Set")
            .description("The character set used to decode data from HBase.")
            .required(true)
            .defaultValue("UTF-8")
            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
            .build();

    static final PropertyDescriptor ENCODE_CHARSET = new PropertyDescriptor.Builder()
            .name("Encode Character Set")
            .description("The character set used to encode the JSON representation of the row.")
            .required(true)
            .defaultValue("UTF-8")
            .addValidator(StandardValidators.CHARACTER_SET_VALIDATOR)
            .build();

    static final Relationship REL_SUCCESS = new Relationship.Builder()
            .name("success")
            .description("All successful fetches are routed to this relationship.")
            .build();
    static final Relationship REL_FAILURE = new Relationship.Builder()
            .name("failure")
            .description("All failed fetches are routed to this relationship.")
            .build();
    static final Relationship REL_NOT_FOUND = new Relationship.Builder()
            .name("not found")
            .description("All fetches where the row id is not found are routed to this relationship.")
            .build();

    static final String HBASE_TABLE_ATTR = "hbase.table";
    static final String HBASE_ROW_ATTR = "hbase.row";

    static final List<PropertyDescriptor> properties;
    static {
        List<PropertyDescriptor> props = new ArrayList<>();
        props.add(HBASE_CLIENT_SERVICE);
        props.add(TABLE_NAME);
        props.add(ROW_ID);
        props.add(COLUMNS);
        props.add(DESTINATION);
        props.add(JSON_FORMAT);
        props.add(JSON_VALUE_ENCODING);
        props.add(ENCODE_CHARSET);
        props.add(DECODE_CHARSET);
        properties = Collections.unmodifiableList(props);
    }

    static final Set<Relationship> relationships;
    static {
        Set<Relationship> rels = new HashSet<>();
        rels.add(REL_SUCCESS);
        rels.add(REL_FAILURE);
        rels.add(REL_NOT_FOUND);
        relationships = Collections.unmodifiableSet(rels);
    }

    private volatile Charset decodeCharset;
    private volatile Charset encodeCharset;
    private volatile RowSerializer regularRowSerializer;
    private volatile RowSerializer base64RowSerializer;

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return properties;
    }

    @Override
    public Set<Relationship> getRelationships() {
        return relationships;
    }

    @OnScheduled
    public void onScheduled(ProcessContext context) {
        this.decodeCharset = Charset.forName(context.getProperty(DECODE_CHARSET).getValue());
        this.encodeCharset = Charset.forName(context.getProperty(ENCODE_CHARSET).getValue());

        final String jsonFormat = context.getProperty(JSON_FORMAT).getValue();
        if (jsonFormat.equals(JSON_FORMAT_FULL_ROW.getValue())) {
            this.regularRowSerializer = new JsonFullRowSerializer(decodeCharset, encodeCharset);
            this.base64RowSerializer = new JsonFullRowSerializer(decodeCharset, encodeCharset, true);
        } else {
            this.regularRowSerializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset);
            this.base64RowSerializer = new JsonQualifierAndValueRowSerializer(decodeCharset, encodeCharset, true);
        }
    }

    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        final FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
        if (StringUtils.isBlank(tableName)) {
            getLogger().error("Table Name is blank or null for {}, transferring to failure", new Object[] {flowFile});
            session.transfer(session.penalize(flowFile), REL_FAILURE);
            return;
        }

        final String rowId = context.getProperty(ROW_ID).evaluateAttributeExpressions(flowFile).getValue();
        if (StringUtils.isBlank(rowId)) {
            getLogger().error("Row Identifier is blank or null for {}, transferring to failure", new Object[] {flowFile});
            session.transfer(session.penalize(flowFile), REL_FAILURE);
            return;
        }

        final List<Column> columns = getColumns(context.getProperty(COLUMNS).evaluateAttributeExpressions(flowFile).getValue());
        final HBaseClientService hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
        final String destination = context.getProperty(DESTINATION).getValue();
        final boolean base64Encode = context.getProperty(JSON_VALUE_ENCODING).getValue().equals(ENCODING_BASE64.getValue());

        final RowSerializer rowSerializer = base64Encode ? base64RowSerializer : regularRowSerializer;

        final FetchHBaseRowHandler handler = destination.equals(DESTINATION_CONTENT.getValue())
                ? new FlowFileContentHandler(flowFile, session, rowSerializer) : new FlowFileAttributeHandler(flowFile, session, rowSerializer);

        final byte[] rowIdBytes = rowId.getBytes(StandardCharsets.UTF_8);

        try {
            hBaseClientService.scan(tableName, rowIdBytes, rowIdBytes, columns, handler);
        } catch (Exception e) {
            getLogger().error("Unable to fetch row {} from  {} due to {}", new Object[] {rowId, tableName, e});
            session.transfer(handler.getFlowFile(), REL_FAILURE);
            return;
        }

        FlowFile handlerFlowFile = handler.getFlowFile();
        if (!handler.handledRow()) {
            getLogger().debug("Row {} not found in {}, transferring to not found", new Object[] {rowId, tableName});
            session.transfer(handlerFlowFile, REL_NOT_FOUND);
            return;
        }

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Fetched {} from {} with row id {}", new Object[]{handlerFlowFile, tableName, rowId});
        }

        final Map<String, String> attributes = new HashMap<>();
        attributes.put(HBASE_TABLE_ATTR, tableName);
        if (destination.equals(DESTINATION_CONTENT.getValue())) {
            attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
        }

        handlerFlowFile = session.putAllAttributes(handlerFlowFile, attributes);

        final String transitUri = hBaseClientService.toTransitUri(tableName, rowId);
        // Regardless to where the result is written to, emit a fetch event.
        session.getProvenanceReporter().fetch(handlerFlowFile, transitUri);
        if (!destination.equals(DESTINATION_CONTENT.getValue())) {
            session.getProvenanceReporter().modifyAttributes(handlerFlowFile, "Added attributes to FlowFile from " + transitUri);
        }

        session.transfer(handlerFlowFile, REL_SUCCESS);
    }

    /**
     * @param columnsValue a String in the form colFam:colQual,colFam:colQual
     * @return a list of Columns based on parsing the given String
     */
    private List<Column> getColumns(final String columnsValue) {
        final String[] columns = (columnsValue == null || columnsValue.isEmpty() ? new String[0] : columnsValue.split(","));

        List<Column> columnsList = new ArrayList<>(columns.length);

        for (final String column : columns) {
            if (column.contains(":"))  {
                final String[] parts = column.split(":");
                final byte[] cf = parts[0].getBytes(StandardCharsets.UTF_8);
                final byte[] cq = parts[1].getBytes(StandardCharsets.UTF_8);
                columnsList.add(new Column(cf, cq));
            } else {
                final byte[] cf = column.getBytes(StandardCharsets.UTF_8);
                columnsList.add(new Column(cf, null));
            }
        }

        return columnsList;
    }

    /**
     * A ResultHandler that also provides access to a resulting FlowFile reference.
     */
    private interface FetchHBaseRowHandler extends ResultHandler {

        /**
         * @return returns the flow file reference that was used by this handler
         */
        FlowFile getFlowFile();

        /**
         * @return returns true if this handler handled a row
         */
        boolean handledRow();

    }

    /**
     * A FetchHBaseRowHandler that writes the resulting row to the FlowFile content.
     */
    private static class FlowFileContentHandler implements FetchHBaseRowHandler {

        private FlowFile flowFile;
        private final ProcessSession session;
        private final RowSerializer serializer;
        private boolean handledRow = false;

        public FlowFileContentHandler(final FlowFile flowFile, final ProcessSession session, final RowSerializer serializer) {
            this.flowFile = flowFile;
            this.session = session;
            this.serializer = serializer;
        }

        @Override
        public void handle(byte[] row, ResultCell[] resultCells) {
            flowFile = session.write(flowFile, (out) -> {
                serializer.serialize(row, resultCells, out);
            });
            handledRow = true;
        }

        @Override
        public FlowFile getFlowFile() {
            return flowFile;
        }

        @Override
        public boolean handledRow() {
            return handledRow;
        }
    }

    /**
     * A FetchHBaseRowHandler that writes the resulting row to FlowFile attributes.
     */
    private static class FlowFileAttributeHandler implements FetchHBaseRowHandler {

        private FlowFile flowFile;
        private final ProcessSession session;
        private final RowSerializer rowSerializer;
        private boolean handledRow = false;

        public FlowFileAttributeHandler(final FlowFile flowFile, final ProcessSession session, final RowSerializer serializer) {
            this.flowFile = flowFile;
            this.session = session;
            this.rowSerializer = serializer;
        }

        @Override
        public void handle(byte[] row, ResultCell[] resultCells) {
            final String serializedRow = rowSerializer.serialize(row, resultCells);
            flowFile = session.putAttribute(flowFile, HBASE_ROW_ATTR, serializedRow);
            handledRow = true;
        }

        @Override
        public FlowFile getFlowFile() {
            return flowFile;
        }

        @Override
        public boolean handledRow() {
            return handledRow;
        }

    }
}


text:
using JetBrains.Annotations;

namespace Abp.Web.Mvc.Alerts
{
    public class AlertMessage
    {
        [NotNull]
        public string Text
        {
            get => _text;
            set => _text = Check.NotNullOrWhiteSpace(value, nameof(value));
        }
        private string _text;

        public AlertType Type { get; set; }

        [CanBeNull]
        public string Title { get; set; }

        public bool Dismissible { get; set; }

        public AlertMessage(AlertType type, [NotNull] string text, string title = null, bool dismissible = true)
        {
            Type = type;
            Text = Check.NotNullOrWhiteSpace(text, nameof(text));
            Title = title;
            Dismissible = dismissible;
        }
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.mojo.bindings.Interface;
import org.chromium.mojo.bindings.Interface.Proxy;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.impl.CoreImpl;

/**
 * Java wrapper over Mojo ServiceRegistry held by the browser.
 */
@JNINamespace("content")
public class ServiceRegistry {

    interface ImplementationFactory<I extends Interface> {
        I createImpl();
    }

    <I extends Interface, P extends Proxy> void addService(
            Interface.Manager<I, P> manager, ImplementationFactory<I> factory) {
        nativeAddService(mNativeServiceRegistryAndroid, manager, factory, manager.getName());
    }

    <I extends Interface, P extends Proxy> void removeService(
            Interface.Manager<I, P> manager) {
        nativeRemoveService(mNativeServiceRegistryAndroid, manager.getName());
    }

    <I extends Interface, P extends Proxy> void connectToRemoteService(
            Interface.Manager<I, P> manager, InterfaceRequest<I> request) {
        int nativeHandle = request.passHandle().releaseNativeHandle();
        nativeConnectToRemoteService(
                mNativeServiceRegistryAndroid, manager.getName(), nativeHandle);
    }

    private long mNativeServiceRegistryAndroid;
    private final Core mCore;

    private ServiceRegistry(long nativeServiceRegistryAndroid, Core core) {
        mNativeServiceRegistryAndroid = nativeServiceRegistryAndroid;
        mCore = core;
    }

    @CalledByNative
    private static ServiceRegistry create(long nativeServiceRegistryAndroid) {
        return new ServiceRegistry(nativeServiceRegistryAndroid, CoreImpl.getInstance());
    }

    @CalledByNative
    private void destroy() {
        mNativeServiceRegistryAndroid = 0;
    }

    // Declaring parametrized argument type for manager and factory breaks the JNI generator.
    // TODO(ppi): support parametrized argument types in the JNI generator.
    @SuppressWarnings("unchecked")
    @CalledByNative
    private void createImplAndAttach(int nativeHandle, Interface.Manager manager,
            ImplementationFactory factory) {
        MessagePipeHandle handle = mCore.acquireNativeHandle(nativeHandle).toMessagePipeHandle();
        manager.bind(factory.createImpl(), handle);
    }

    private native void nativeAddService(long nativeServiceRegistryAndroid,
            Interface.Manager manager, ImplementationFactory factory, String name);
    private native void nativeRemoveService(long nativeServiceRegistryAndroid, String name);
    private native void nativeConnectToRemoteService(long nativeServiceRegistryAndroid, String name,
            int handle);
}


text:
const express = require('express'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),

    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    mongodb = require('./libs/mongodb'),

    bodyParser = require('body-parser'),

    routes = require('./routes/index'),
    users = require('./routes/users'),
    exercises = require('./routes/exercises'),
    learn = require('./routes/learn'),
    api = require('./routes/api'),
    auth = require('./libs/authentication');

const tracer = require('./libs/ironmanLogger');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: 'really secret',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 24 * 60 * 60 * 1000
    },
    store: new MongoStore({ mongooseConnection: mongodb.connection })
}));

app.use(express.static(path.join(__dirname, 'public')));

app.use(/.*/, auth.checkAuth);
app.use('/', routes);
app.use('/users', users);
app.use('/exercises', exercises);
app.use('/learn', learn);
app.use('/api', api);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    tracer.error(req.baseUrl + req.path);
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.locals.pretty = true;

    app.use(function (err, req, res) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
package com.dxy.android.statistics.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Utilities for working with strings, like splitting, url-encoding, and MD5 digests.
 *
 * @author brokge@gmail.com
 */
public class StringUtils {

    /** Splits a String based on a single character, which is usually faster than regex-based String.split(). */
    public static String[] fastSplit(String string, char delimiter) {
        List<String> list = new ArrayList<String>();
        int size = string.length();
        int start = 0;
        for (int i = 0; i < size; i++) {
            if (string.charAt(i) == delimiter) {
                if (start < i) {
                    list.add(string.substring(start, i));
                } else {
                    list.add("");
                }
                start = i + 1;
            } else if (i == size - 1) {
                list.add(string.substring(start, size));
            }
        }
        String[] elements = new String[list.size()];
        list.toArray(elements);
        return elements;
    }

    /**
     * URL-Encodes a given string using UTF-8 (some web pages have problems with UTF-8 and umlauts, consider
     * {@link #encodeUrlIso(String)} also). No UnsupportedEncodingException to handle as it is dealt with in this
     * method.
     */
    public static String encodeUrl(String stringToEncode) {
        try {
            return URLEncoder.encode(stringToEncode, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1);
        }
    }

    /**
     * URL-encodes a given string using ISO-8859-1, which may work better with web pages and umlauts compared to UTF-8.
     * No UnsupportedEncodingException to handle as it is dealt with in this method.
     */
    public static String encodeUrlIso(String stringToEncode) {
        try {
            return URLEncoder.encode(stringToEncode, "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1);
        }
    }

    /**
     * URL-Decodes a given string using UTF-8. No UnsupportedEncodingException to handle as it is dealt with in this
     * method.
     */
    public static String decodeUrl(String stringToDecode) {
        try {
            return URLDecoder.decode(stringToDecode, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1);
        }
    }

    /**
     * URL-Decodes a given string using ISO-8859-1. No UnsupportedEncodingException to handle as it is dealt with in
     * this method.
     */
    public static String decodeUrlIso(String stringToDecode) {
        try {
            return URLDecoder.decode(stringToDecode, "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1);
        }
    }

    /**
     * Generates the MD5 digest for a given String based on UTF-8. The digest is padded with zeroes in the front if
     * necessary.
     *
     * @return MD5 digest (32 characters).
     */
    public static String generateMD5String(String stringToEncode) {
        return generateDigestString(stringToEncode, "MD5", "UTF-8", 32);
    }

    /**
     * Generates the SHA-1 digest for a given String based on UTF-8. The digest is padded with zeroes in the front if
     * necessary. The SHA-1 algorithm is considers to produce less collisions than MD5.
     *
     * @return SHA-1 digest (40 characters).
     */
    public static String generateSHA1String(String stringToEncode) {
        return generateDigestString(stringToEncode, "SHA-1", "UTF-8", 40);
    }

    public static String
    generateDigestString(String stringToEncode, String digestAlgo, String encoding, int lengthToPad) {
        // Loosely inspired by http://workbench.cadenhead.org/news/1428/creating-md5-hashed-passwords-java
        MessageDigest digester;
        try {
            digester = MessageDigest.getInstance(digestAlgo);
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException(nsae);
        }
        try {
            digester.update(stringToEncode.getBytes(encoding));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return toHexString(digester.digest(), lengthToPad);
    }

    public static String toHexString(byte[] bytes, int lengthToPad) {
        BigInteger hash = new BigInteger(1, bytes);
        String digest = hash.toString(16);

        while (digest.length() < lengthToPad) {
            digest = "0" + digest;
        }
        return digest;
    }

    /**
     * Simple HTML/XML entity resolving: Only supports unicode enitities and a very limited number text represented
     * entities (apos, quot, gt, lt, and amp). There are many more: http://www.w3.org/TR/REC-html40/sgml/dtd.html
     *
     * @param entity The entity name without & and ; (null throws NPE)
     * @return Resolved entity or the entity itself if it could not be resolved.
     */
    public static String resolveEntity(String entity) {
        if (entity.length() > 1 && entity.charAt(0) == '#') {
            if (entity.charAt(1) == 'x') {
                return String.valueOf((char) Integer.parseInt(entity.substring(2), 16));
            } else {
                return String.valueOf((char) Integer.parseInt(entity.substring(1)));
            }
        } else if (entity.equals("apos")) {
            return "'";
        } else if (entity.equals("quot")) {
            return "\"";
        } else if (entity.equals("gt")) {
            return ">";
        } else if (entity.equals("lt")) {
            return "<";
        } else if (entity.equals("amp")) {
            return "&";
        } else {
            return entity;
        }
    }

    /**
     * Cuts the string at the end if it's longer than maxLength and appends "..." to it. The length of the resulting
     * string including "..." is always less or equal to the given maxLength. It's valid to pass a null text; in this
     * case null is returned.
     */
    public static String ellipsize(String text, int maxLength) {
        if (text != null && text.length() > maxLength) {
            return text.substring(0, maxLength - 3) + "...";
        }
        return text;
    }

    public static String[] splitLines(String text, boolean skipEmptyLines) {
        if (skipEmptyLines) {
            return text.split("[\n\r]+");
        } else {
            return text.split("\\r?\\n");
        }
    }

    public static List<String> findLinesContaining(String text, String searchText) {
        String[] splitLinesSkipEmpty = splitLines(text, true);
        List<String> matching = new ArrayList<String>();
        for (String line : splitLinesSkipEmpty) {
            if (line.contains(searchText)) {
                matching.add(line);
            }
        }
        return matching;
    }

    /**
     * Returns a concatenated string consisting of the given lines seperated by a new line character \n. The last line
     * does not have a \n at the end.
     */
    public static String concatLines(List<String> lines) {
        StringBuilder builder = new StringBuilder();
        int countMinus1 = lines.size() - 1;
        for (int i = 0; i < countMinus1; i++) {
            builder.append(lines.get(i)).append('\n');
        }
        if (!lines.isEmpty()) {
            builder.append(lines.get(countMinus1));
        }
        return builder.toString();
    }

    public static String joinIterableOnComma(Iterable<?> iterable) {
        if (iterable != null) {

            StringBuilder buf = new StringBuilder();
            Iterator<?> it = iterable.iterator();
            while (it.hasNext()) {
                buf.append(it.next());
                if (it.hasNext()) {
                    buf.append(',');
                }
            }
            return buf.toString();
        } else {
            return "";
        }
    }

    public static String joinArrayOnComma(int[] array) {
        if (array != null) {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < array.length; i++) {
                if (i != 0) {
                    buf.append(',');
                }
                buf.append(array[i]);
            }
            return buf.toString();
        } else {
            return "";
        }

    }

    public static String joinArrayOnComma(String[] array) {
        if (array != null) {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < array.length; i++) {
                if (i != 0) {
                    buf.append(',');
                }
                buf.append(array[i]);
            }
            return buf.toString();
        } else {
            return "";
        }

    }
    // /** not really public yet, umlauts!? */
    // public static boolean __isValidEmail(String email) {
    // // TODO compile and cache pattern using a ThreadLocal
    // return Pattern.matches("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+", email);
    // }

}


text:
package org.scalameter.picklers

import language.higherKinds

import java.util.Date
import org.scalameter.picklers.Implicits._
import scala.annotation.tailrec
import scala.collection.generic.CanBuildFrom

abstract class TraversablePickler[C[_] <: Traversable[_], T: Pickler] extends Pickler[C[T]] {
  protected def canBuildFrom: CanBuildFrom[Nothing, T, C[T]]

  def pickle(x: C[T]): Array[Byte] = {
    val pickler = implicitly[Pickler[T]].asInstanceOf[Pickler[Any]]
    val builder = Array.newBuilder[Byte]
    builder ++= IntPickler.pickle(x.size)
    x.foreach { e: Any =>
      builder ++= pickler.pickle(e)
    }
    builder.result()
  }

  def unpickle(a: Array[Byte], from: Int): (C[T], Int) = {
    val pickler = implicitly[Pickler[T]]
    val builder = canBuildFrom()

    @tailrec
    def unpickle(times: Int, from: Int): (C[T], Int) = {
      if (times > 0 && from > 0) {
        val (obj, newFrom) = pickler.unpickle(a, from)
        builder += obj
        unpickle(times - 1, newFrom)
      } else (builder.result(), from)
    }

    val (len, newFrom) = IntPickler.unpickle(a, from)
    unpickle(len, newFrom)
  }
}

abstract class OptionPickler[T: Pickler] extends Pickler[Option[T]] {
  def pickle(x: Option[T]): Array[Byte] = {
    x match {
      case Some(e) => implicitly[Pickler[T]].pickle(e)
      case None => Array.empty[Byte]
    }
  }

  def unpickle(a: Array[Byte], from: Int): (Option[T], Int) = {
    if (a.isEmpty) (None, -1)
    else {
      val (obj, pos) = implicitly[Pickler[T]].unpickle(a, from)
      (Some(obj), pos)
    }
  }
}

object StringListPickler extends TraversablePickler[List, String] {
  protected def canBuildFrom = implicitly[CanBuildFrom[Nothing, String, List[String]]]
}

object LongSeqPickler extends TraversablePickler[Seq, Long]  {
  protected def canBuildFrom = implicitly[CanBuildFrom[Nothing, Long, Seq[Long]]]
}

object DateOptionPickler extends OptionPickler[Date]


text:
Contributing Guidelines
=======================

Setup
-----

1. [Fork the project][how-to-fork] and clone the fork to your machine.
2. Create a feature branch to work in. `$ git checkout -b name-of-feature`

Writing Code
------------

* Use the project's coding style, not your own. If the code you write looks drastically different than the preexisting code, you're doing it wrong.
* Include tests that fail without your code, and pass with it.
* Commits should have meaningful messages. If you end up with a bunch of commits with garbage messages, squash your commits before submitting a pull request.

Pull Requests
-------------

1. Push your feature branch to your remote repo on GitHub. `$ git push origin name-of-feature`
2. [Create a pull request][create-pull-request] against master.
3. Write a meaningful title and description. If you've added a new feature or break backwards compatibility, let us know so we can updated the docs accordingly.
5. Submit the pull request!

[how-to-fork]: https://help.github.com/articles/fork-a-repo
[create-pull-request]: https://help.github.com/articles/creating-a-pull-request

License
-------

By contributing your code,

You agree to license your contribution under the terms of the MIT License
https://github.com/trongrg/bootstrap-limit/blob/master/LICENSE


text:
/* 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 org.flowable.cmmn.engine.impl.agenda.operation;

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

import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.engine.impl.persistence.entity.CaseInstanceEntity;
import org.flowable.cmmn.engine.impl.persistence.entity.PlanItemInstanceEntity;
import org.flowable.cmmn.engine.impl.persistence.entity.PlanItemInstanceEntityManager;
import org.flowable.cmmn.engine.impl.repository.CaseDefinitionUtil;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.cmmn.model.PlanItem;
import org.flowable.cmmn.model.PlanItemDefinition;
import org.flowable.cmmn.model.Stage;
import org.flowable.engine.common.api.delegate.Expression;
import org.flowable.engine.common.impl.el.ExpressionManager;
import org.flowable.engine.common.impl.interceptor.CommandContext;

/**
 * @author Joram Barrez
 */
public abstract class CmmnOperation implements Runnable {

    protected CommandContext commandContext;

    public CmmnOperation() {
    }

    public CmmnOperation(CommandContext commandContext) {
        this.commandContext = commandContext;
    }

    protected Stage getStage(PlanItemInstanceEntity planItemInstanceEntity) {
        if (planItemInstanceEntity.getPlanItem() != null
                && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() != null) {
            PlanItemDefinition planItemDefinition = planItemInstanceEntity.getPlanItem().getPlanItemDefinition();
            if (planItemDefinition instanceof Stage) {
                return (Stage) planItemDefinition;
            } else {
                return planItemDefinition.getParentStage();
            }
        } else {
            return getStage(planItemInstanceEntity.getCaseDefinitionId(), planItemInstanceEntity.getElementId());
        }
    }

    protected Stage getStage(String caseDefinitionId, String stageId) {
        return CaseDefinitionUtil.getCase(caseDefinitionId).findStage(stageId);
    }

    protected boolean isStage(PlanItemInstanceEntity planItemInstanceEntity) {
        return (planItemInstanceEntity.getPlanItem() != null
                && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() != null
                && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof Stage);
    }

    protected Stage getPlanModel(CaseInstanceEntity caseInstanceEntity) {
        return CaseDefinitionUtil.getCase(caseInstanceEntity.getCaseDefinitionId()).getPlanModel();
    }

    protected List<PlanItemInstanceEntity> createPlanItemInstances(CommandContext commandContext,
                                                                        List<PlanItem> planItems,
                                                                        String caseDefinitionId,
                                                                        String caseInstanceId,
                                                                        String stagePlanItemInstanceId,
                                                                        String tenantId) {
        ExpressionManager expressionManager = CommandContextUtil.getExpressionManager(commandContext);
        PlanItemInstanceEntityManager planItemInstanceEntityManager = CommandContextUtil.getPlanItemInstanceEntityManager(commandContext);
        CaseInstanceEntity caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceId);

        List<PlanItemInstanceEntity> planItemInstances = new ArrayList<>();
        for (PlanItem planItem : planItems) {
            PlanItemInstanceEntity planItemInstanceEntity = planItemInstanceEntityManager.create();
            planItemInstanceEntity.setCaseDefinitionId(caseDefinitionId);
            planItemInstanceEntity.setCaseInstanceId(caseInstanceId);
            if (planItem.getName() != null) {
                Expression nameExpression = expressionManager.createExpression(planItem.getName());
                planItemInstanceEntity.setName(nameExpression.getValue(caseInstanceEntity).toString());
            }
            planItemInstanceEntity.setState(PlanItemInstanceState.AVAILABLE);
            planItemInstanceEntity.setStartTime(CommandContextUtil.getCmmnEngineConfiguration(commandContext).getClock().getCurrentTime());
            planItemInstanceEntity.setElementId(planItem.getId());
            planItemInstanceEntity.setStage(false);
            planItemInstanceEntity.setStageInstanceId(stagePlanItemInstanceId);
            planItemInstanceEntity.setTenantId(tenantId);

            planItemInstanceEntityManager.insert(planItemInstanceEntity);
            planItemInstances.add(planItemInstanceEntity);
        }

        return planItemInstances;
    }

}