text:
<!DOCTYPE HTML>

		<title>LjsVariates Class Reference</title>
		<meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8" />
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<meta name="viewport" content="width=550" />
		<link rel="stylesheet" type="text/css" href="../css/styles.css" />
		<meta name="generator" content="appledoc 2.0.5 (build 789)" />

LjsVariates Class Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="class_methods">Class Methods</option>

	<option value="//api/name/_factorialHelperWithN:accumulator:">    + _factorialHelperWithN:accumulator:</option>

	<option value="//api/name/factorial:">    + factorial:</option>

	<option value="//api/name/flip">    + flip</option>

	<option value="//api/name/flipWithProbilityOfYes:">    + flipWithProbilityOfYes:</option>

	<option value="//api/name/possionWithK:lambda:">    + possionWithK:lambda:</option>

	<option value="//api/name/randomDecimalDouble">    + randomDecimalDouble</option>

	<option value="//api/name/randomDecimalDoubleWithMin:max:">    + randomDecimalDoubleWithMin:max:</option>

	<option value="//api/name/randomDecimalInteger">    + randomDecimalInteger</option>

	<option value="//api/name/randomDecimalIntegerWithMin:max:">    + randomDecimalIntegerWithMin:max:</option>

	<option value="//api/name/randomDouble">    + randomDouble</option>

	<option value="//api/name/randomDoubleWithMin:max:">    + randomDoubleWithMin:max:</option>

	<option value="//api/name/randomElement:">    + randomElement:</option>

	<option value="//api/name/randomInteger">    + randomInteger</option>

	<option value="//api/name/randomIntegerWithMin:max:">    + randomIntegerWithMin:max:</option>

	<option value="//api/name/randomStringWithLength:">    + randomStringWithLength:</option>

	<option value="//api/name/sampleWithReplacement:number:">    + sampleWithReplacement:number:</option>

	<option value="//api/name/sampleWithoutReplacement:number:">    + sampleWithoutReplacement:number:</option>

	<option value="//api/name/shuffle:">    + shuffle:</option>

</select>

Overview

Tasks

Class Methods

_factorialHelperWithN:accumulator:

factorial:

flip

flipWithProbilityOfYes:

possionWithK:lambda:

randomDecimalDouble

randomDecimalDoubleWithMin:max:

randomDecimalInteger

randomDecimalIntegerWithMin:max:

randomDouble

randomDoubleWithMin:max:

randomElement:

randomInteger

randomIntegerWithMin:max:

randomStringWithLength:

sampleWithReplacement:number:

sampleWithoutReplacement:number:

shuffle:

Index

Hierarchy

LjsVariates Class Reference

	Inherits from
	NSObject

	Declared in
	LjsVariates.h
LjsVariates.m

Overview

Uses the arc4random algorithm to produce pseudo random numbers.

No manual seeding is required (or allowed) because arc4random self-seeds.

arc4random_uniform does not seem to work with Cocoa, so we replace with our
own logic avoiding using % (modulo) and regenerating random integers when we
need to (about once every million or so calls).

Tasks

		+ factorial:

uses tail recursion to compute factorial of n

		+ _factorialHelperWithN:accumulator:

the helper for factorial function

		+ flip

a random BOOL value

		+ flipWithProbilityOfYes:

a random BOOL with aProbabilty of YES

		+ possionWithK:lambda:

Discussion
e is the base of the natural logarithm (e = 2.71828…)
k is the number of occurrences of an event — the probability of which is given by the function
k! is the factorial of k
λ is a positive real number, equal to the expected number of occurrences during the given interval. For instance, if the events occur on average 4 times per minute, and one is interested in the probability of an event occurring k times in a 10 minute interval, one would use a Poisson distribution as the model with λ = 10×4 = 40.
As a function of k, this is the probability mass function. The Poisson distribution can be derived as a limiting case of the binomial distribution.

		+ randomDouble

Generates a random double from 0.0 to 1.0 inclusive – (0.0, 1.0)

		+ randomDecimalDouble

Generates a random double.

		+ randomDoubleWithMin:max:

Generates a random double from min to max inclusive = (min, max)

		+ randomDecimalDoubleWithMin:max:

Generates a random double and returns it as an NSDecimalNumber.

		+ randomInteger

Generates a random integer between two large numbers.  I thought range was
( –(232) – 1, (232) -1 ), but I find the range to be much larger when I
unit test.

		+ randomDecimalInteger

Generates a random integer and returns it as an NSDecimalNumber.

		+ randomIntegerWithMin:max:

Generates a random int from min to max inclusive = (min, max)

		+ randomDecimalIntegerWithMin:max:

Generates a random int from min to max inclusive = (min, max)

		+ sampleWithReplacement:number:

randomly samples a number of elements from array using replacement

		+ sampleWithoutReplacement:number:

randomly samples a number of elements from array without replacement.
if number > array count, then this method returns nil.

		+ randomElement:

a random element from the array

		+ shuffle:

a shuffled array

		+ randomStringWithLength:

returns a string of random alpha-numeric characters

Class Methods

_factorialHelperWithN:accumulator:

the helper for factorial function

+ (NSUInteger)_factorialHelperWithN:(NSUInteger)n accumulator:(NSUInteger)accumulator

Parameters

n

n

accumulator

the accumulated value

Return Value

accumulated n

Discussion

the helper for factorial function

Declared In

		LjsVariates.h

factorial:

uses tail recursion to compute factorial of n

+ (NSUInteger)factorial:(NSUInteger)n

Parameters

n

n

Return Value

the factorial of n (n!)

Discussion

uses tail recursion to compute factorial of n

Declared In

		LjsVariates.h

flip

a random BOOL value

+ (BOOL)flip

Return Value

a random BOOL value

Declared In

		LjsVariates.h

flipWithProbilityOfYes:

a random BOOL with aProbabilty of YES

+ (BOOL)flipWithProbilityOfYes:(double)aProbability

Parameters

aProbability

the probability of a YES

Return Value

a random BOOL with aProbabilty of YES

Declared In

		LjsVariates.h

possionWithK:lambda:

Discussion
e is the base of the natural logarithm (e = 2.71828…)
k is the number of occurrences of an event — the probability of which is given by the function
k! is the factorial of k
λ is a positive real number, equal to the expected number of occurrences during the given interval. For instance, if the events occur on average 4 times per minute, and one is interested in the probability of an event occurring k times in a 10 minute interval, one would use a Poisson distribution as the model with λ = 10×4 = 40.
As a function of k, this is the probability mass function. The Poisson distribution can be derived as a limiting case of the binomial distribution.

+ (double)possionWithK:(NSUInteger)aK lambda:(double)aLambda

Parameters

aK

is the number of occurrences of an event — the probability of which is given by the function

aLambda

s a positive real number, equal to the expected number of occurrences during the given interval. For instance, if the events occur on average 4 times per minute, and one is interested in the probability of an event occurring k times in a 10 minute interval, one would use a Poisson distribution as the model with λ = 10×4 = 40.

Return Value

a poission random value

Discussion

Discussion
e is the base of the natural logarithm (e = 2.71828…)
k is the number of occurrences of an event — the probability of which is given by the function
k! is the factorial of k
λ is a positive real number, equal to the expected number of occurrences during the given interval. For instance, if the events occur on average 4 times per minute, and one is interested in the probability of an event occurring k times in a 10 minute interval, one would use a Poisson distribution as the model with λ = 10×4 = 40.
As a function of k, this is the probability mass function. The Poisson distribution can be derived as a limiting case of the binomial distribution.

Declared In

		LjsVariates.h

randomDecimalDouble

Generates a random double.

+ (NSDecimalNumber *)randomDecimalDouble

Return Value

a random double

Discussion

Generates a random double.

Declared In

		LjsVariates.h

randomDecimalDoubleWithMin:max:

Generates a random double and returns it as an NSDecimalNumber.

+ (NSDecimalNumber *)randomDecimalDoubleWithMin:(NSDecimalNumber *)min max:(NSDecimalNumber *)max

Parameters

min

the lowest value returned

max

the hightest value returned

Return Value

a random double on (min, max) wrapped in NSDecimalNumber

Discussion

Generates a random double and returns it as an NSDecimalNumber.

Declared In

		LjsVariates.h

randomDecimalInteger

Generates a random integer and returns it as an NSDecimalNumber.

+ (NSDecimalNumber *)randomDecimalInteger

Return Value

a positive or negative integer wrapped as an NSDecimalNumber.

Discussion

Generates a random integer and returns it as an NSDecimalNumber.

See Also

+ randomInteger

Declared In

		LjsVariates.h

randomDecimalIntegerWithMin:max:

Generates a random int from min to max inclusive = (min, max)

+ (NSDecimalNumber *)randomDecimalIntegerWithMin:(NSDecimalNumber *)min max:(NSDecimalNumber *)max

Parameters

min

the lowest value returned

max

the hightest value returned

Return Value

a random int on (min, max) wrapped in an NSDecimalNumber

Discussion

Generates a random int from min to max inclusive = (min, max)

This method will occassionally (once every tens of millions of calls) produce
a number that is +1 larger than max.  When this happens, another random integer
is produced until the result is less-or-equal to the max.  This is expected.

Declared In

		LjsVariates.h

randomDouble

Generates a random double from 0.0 to 1.0 inclusive – (0.0, 1.0)

+ (double)randomDouble

Return Value

a random double on (0.0, 1.0)

Discussion

Generates a random double from 0.0 to 1.0 inclusive – (0.0, 1.0)

Declared In

		LjsVariates.h

randomDoubleWithMin:max:

Generates a random double from min to max inclusive = (min, max)

+ (double)randomDoubleWithMin:(double)min max:(double)max

Parameters

min

the lowest value returned

max

the hightest value returned

Return Value

a random double on (min, max)

Discussion

Generates a random double from min to max inclusive = (min, max)

Declared In

		LjsVariates.h

randomElement:

a random element from the array

+ (id)randomElement:(NSArray *)array

Parameters

array

the array to sample

Return Value

a random element from the array

Declared In

		LjsVariates.h

randomInteger

Generates a random integer between two large numbers.  I thought range was
( –(232) – 1, (232) -1 ), but I find the range to be much larger when I
unit test.

+ (NSInteger)randomInteger

Return Value

a positive or negative integer

Discussion

Generates a random integer between two large numbers.  I thought range was
( –(232) – 1, (232) -1 ), but I find the range to be much larger when I
unit test.

This is from the docs:  The arc4random() function provides a high quality

                     32-bit pseudo-random number very quickly.

Suffice it to say that it produces a randomw integer between a very large
negative integer and a very large positive integer.

Declared In

		LjsVariates.h

randomIntegerWithMin:max:

Generates a random int from min to max inclusive = (min, max)

+ (NSInteger)randomIntegerWithMin:(NSInteger)min max:(NSInteger)max

Parameters

min

the lowest value returned

max

the hightest value returned

Return Value

a random int on (min, max)

Discussion

Generates a random int from min to max inclusive = (min, max)

This method will occassionally (once every tens of millions of calls) produce
a number that is +1 larger than max.  When this happens, another random integer
is produced until the result is less-or-equal to the max.  This is expected.

Declared In

		LjsVariates.h

randomStringWithLength:

returns a string of random alpha-numeric characters

+ (NSString *)randomStringWithLength:(NSUInteger)length

Parameters

length

the number of characters in the created string

Return Value

a string of random alpha-numeric characters

Discussion

returns a string of random alpha-numeric characters

Declared In

		LjsVariates.h

sampleWithReplacement:number:

randomly samples a number of elements from array using replacement

+ (NSArray *)sampleWithReplacement:(NSArray *)array number:(NSUInteger)number

Parameters

array

the array to sample

number

the number to sample

Return Value

an array with randomly sampled elements

Discussion

randomly samples a number of elements from array using replacement

Declared In

		LjsVariates.h

sampleWithoutReplacement:number:

randomly samples a number of elements from array without replacement.
if number > array count, then this method returns nil.

+ (NSArray *)sampleWithoutReplacement:(NSArray *)array number:(NSUInteger)number

Parameters

array

the array to sample

number

the number to sample

Return Value

an array with randomly sampled elements

Discussion

randomly samples a number of elements from array without replacement.
if number > array count, then this method returns nil.

Declared In

		LjsVariates.h

shuffle:

a shuffled array

+ (NSArray *)shuffle:(NSArray *)array

Parameters

array

the array to shuffle

Return Value

a shuffled array

Declared In

		LjsVariates.h

Index

Hierarchy

© 2012 Little Joy Software. All rights reserved. (Last updated: 2012-11-30)

						Generated by appledoc 2.0.5 (build 789).


text:
package de.egore911.versioning.persistence.dao;

import java.util.UUID;

import de.egore911.appframework.testing.persistence.dao.AbstractDaoCRUDTest;
import de.egore911.versioning.persistence.model.ActionReplacementEntity;
import de.egore911.versioning.persistence.model.ProjectEntity;

public class ActionReplacementDaoProjectTest
		extends AbstractDaoCRUDTest<ActionReplacementEntity> {

	@Override
	protected ActionReplacementEntity createFixture() {
		ProjectEntity project = new ProjectDaoTest().createFixture();
		project = new ProjectDao().save(project);

		ActionReplacementEntity actionReplacement = new ActionReplacementEntity();
		actionReplacement.setProject(project);
		actionReplacement.getWildcards().add(UUID.randomUUID().toString());
		return actionReplacement;
	}

	@Override
	protected void modifyFixture(ActionReplacementEntity actionReplacement) {
		actionReplacement.getWildcards().add(UUID.randomUUID().toString());
	}

	@Override
	protected ActionReplacementDao getDao() {
		return new ActionReplacementDao();
	}

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __LOGGING_H__
#define __LOGGING_H__

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmismatched-tags"
#endif

#include <boost/units/detail/utility.hpp>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#define TYPE_NAME(_type) boost::units::detail::demangle(typeid(_type).name())

#define LOG(_Level, _Msg)                                        \
    do {                                                         \
        if (LoggingDisabled()) break;                            \
        log4cplus::Logger logger = log4cplus::Logger::getRoot(); \
        LOG4CPLUS_##_Level(logger, _Msg);                        \
    } while (0)

void LoggingInit();
void LoggingInit(std::string filename, long maxFileSize = 10*1024*1024,
                 int maxBackupIndex = 1);

//
// Disable logging - For testing purposes only
//
bool LoggingDisabled();
void SetLoggingDisabled(bool flag);

#endif /* __LOGGING_H__ */


text:
@class ActiveRecord;

@interface ARFactory : NSObject

+ (NSArray *)buildFew:(NSInteger)aCount recordsNamed:(NSString *)aRecordName;
+ (NSArray *)buildFew:(NSInteger)aCount records:(Class)aRecordClass;

+ (ActiveRecord *)buildRecordWithName:(NSString *)aRecordName withSeed:(NSInteger)aSeed;
+ (ActiveRecord *)buildPropertiesOfRecord:(ActiveRecord *)aRecord withSeed:(NSInteger)aSeed;

@end


text: {% yield %}


text:
const char *ws_opcode_str(ws_opcode_t opcode);

///
/// Unpacks a websocket header from a byte buffer into
/// a header struct.
///
/// @param[out]	h 			A pointer to a header struct to store the result in.
/// @param[out] header_len 	The size of the header in bytes.
/// @param[in]	b 			The buffer that should be parsed.
/// @param[in]  len 		The number of bytes the buffer contains.
///
/// @returns A parse state. WS_PARSE_STATE_SUCCESS if the header was
///			 parsed successfully. WS_PARSE_STATE_NEED_MORE if more
///			 data is needed.
///
ws_parse_state_t ws_unpack_header(ws_header_t *h, size_t *header_len,
					const unsigned char *b, size_t len);

///
/// Packs a websocket header struct into a network byte order
/// octet stream.
///
/// @param[in]	h 			A pointer to the header to pack.
/// @param[in]	b 			The byte buffer to pack the header in.
///							Must be at least #WS_HDR_MAX_SIZE big.
/// @param[in]	len 		The size of the buffer.
/// @param[out] header_len	Will contain the final size of the packed header.
///
void ws_pack_header(ws_header_t *h, uint8_t *b, size_t len, size_t *header_len);

#endif // __LIBWS_HEADER_H__


text:
import json
import logging
import traceback
from functools import wraps

from django import http
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.urls import reverse as _reverse
from django.utils.http import urlencode

from dimagi.utils.logging import notify_exception
from dimagi.utils.web import get_url_base

from corehq.util import global_request

JSON = 'application/json'
logger = logging.getLogger('django.request')

def set_file_download(response, filename):
    response["Content-Disposition"] = 'attachment; filename="%s"' % filename

class BadRequest(Exception):
    """Error to be used with @json_error to signal a bad request

    Inspired by https://github.com/jsocol/django-jsonview ::

    HTTP does not have a great status code for "you submitted a form that didn't
    validate," and so Django doesn't support it very well. Most examples just
    return 200 OK.

    Normally, this is fine. But if you're submitting a form via Ajax, it's nice
    to have a distinct status for "OK" and "Nope." The HTTP 400 Bad Request
    response is the fallback for issues with a request not-otherwise-specified,
    so let's do that.

    To cause @json_error to return a 400, just raise this exception with
    whatever appropriate error message.
    """

def json_error(f):
    """A decorator for request handlers that returns structured error responses

    Inspired by (and some parts shamelessly copied from)
    https://github.com/jsocol/django-jsonview
    """
    @wraps(f)
    def inner(request, *args, **kwargs):
        from . import as_text
        try:
            response = f(request, *args, **kwargs)

            # Some errors are not exceptions. :\
            if isinstance(response, http.HttpResponseNotAllowed):
                blob = json.dumps({
                    'error': 405,
                    'message': 'HTTP method not allowed.'
                })
                return http.HttpResponse(blob, status=405, content_type=JSON)

            return response

        except http.Http404 as e:
            return _get_json_exception_response(404, request, e, log_message='Not found: %s')
        except PermissionDenied as e:
            return _get_json_exception_response(403, request, e, log_message='Forbidden (Permission denied): %s')
        except BadRequest as e:
            return _get_json_exception_response(400, request, e)
        except Exception as e:
            message = f'JSON exception response: {as_text(e)}'
            notify_exception(request, message)
            return _get_json_exception_response(500, request, e)
    return inner

def _get_json_exception_response(code, request, exception, log_message=None):
    if log_message:
        logger.warning(
            log_message, request.path,
            extra={
                'status_code': code,
                'request': request,
            })

    data = _json_exception_response_data(code, exception)

    return http.HttpResponse(
        status=code,
        content=json.dumps(data),
        content_type=JSON
    )

def _json_exception_response_data(code, exception):
    if exception.args and isinstance(exception.args[0], bytes):
        message = exception.args[0].decode('utf-8')
    else:
        message = str(exception)
    data = {
        'error': code,
        'message': message
    }
    if code == 500 and settings.DEBUG:
        data['traceback'] = traceback.format_exc()
    return data

def get_request():
    return global_request.get_request()

def reverse(viewname, params=None, absolute=False, **kwargs):
    """
    >>> reverse('create_location', args=["test"], params={"selected": "foo"})
    '/a/test/settings/locations/new/?selected=foo'
    """
    url = _reverse(viewname, **kwargs)
    if absolute:
        url = "{}{}".format(get_url_base(), url)
    if params:
        url = "{}?{}".format(url, urlencode(params))
    return url

def absolute_reverse(*args, **kwargs):
    return reverse(*args, absolute=True, **kwargs)

def get_case_or_404(domain, case_id):
    from corehq.form_processor.exceptions import CaseNotFound
    from corehq.form_processor.models import CommCareCase
    try:
        case = CommCareCase.objects.get_case(case_id, domain)
        if case.domain != domain or case.is_deleted:
            raise Http404()
        return case
    except CaseNotFound:
        raise Http404()

def get_form_or_404(domain, id):
    from corehq.form_processor.exceptions import XFormNotFound
    from corehq.form_processor.models import XFormInstance
    try:
        form = XFormInstance.objects.get_form(id, domain)
        if form.is_deleted:
            raise Http404()
        return form
    except XFormNotFound:
        raise Http404()

def request_as_dict(request):
    """
    Function returns the dictionary which contains the data of request object.
    :Parameter request:
            Object of HttpRequest

    :Return request_data:
            Dict containing the request data
    """

    # This is a parameter that is provided by middleware that may or may not exist
    can_access_all_locations = getattr(request, 'can_access_all_locations', False)

    request_data = dict(
        GET=request.GET if request.method == 'GET' else request.POST,
        META=dict(
            QUERY_STRING=request.META.get('QUERY_STRING'),
            PATH_INFO=request.META.get('PATH_INFO')
        ),
        datespan=request.datespan,
        couch_user=None,
        can_access_all_locations=can_access_all_locations
    )

    try:
        request_data.update(couch_user=request.couch_user.get_id)
    except Exception as e:
        logging.error("Could not pickle the couch_user id from the request object. Error: %s" % e)

    return request_data

def is_ajax(request):
    """Check if requested with XMLHttpRequest

    HttpRequest.is_ajax() was deprecated in Django 3.1
    https://docs.djangoproject.com/en/4.0/releases/3.1/#id2
    """
    return request.headers.get('x-requested-with') == 'XMLHttpRequest'


text:
using System;
using Cairo;
using Gtk;
using Pinta.Core;
using Mono.Unix;

namespace Pinta.Tools
{
	public class EraserTool : BaseBrushTool
	{
		private Point last_point = point_empty;

		public EraserTool ()
		{
		}

		protected override void OnBuildToolBar(Toolbar tb)
		{
			base.OnBuildToolBar(tb);

			// Change the cursor when the BrushWidth is changed.
			brush_width.ComboBox.Changed += (sender, e) => SetCursor (DefaultCursor);
		}

		#region Properties
		public override string Name { get { return Catalog.GetString ("Eraser"); } }
		public override string Icon { get { return "Tools.Eraser.png"; } }
		public override string StatusBarText { get { return Catalog.GetString ("Left click to erase to transparent, right click to erase to secondary color. "); } }

		public override Gdk.Cursor DefaultCursor {
			get {
				int iconOffsetX, iconOffsetY;
				var icon = CreateIconWithShape ("Cursor.Eraser.png",
				                                CursorShape.Ellipse, BrushWidth, 8, 22,
				                                out iconOffsetX, out iconOffsetY);
                return new Gdk.Cursor (Gdk.Display.Default, icon, iconOffsetX, iconOffsetY);
			}
		}
		public override bool CursorChangesOnZoom { get { return true; } }

		public override Gdk.Key ShortcutKey { get { return Gdk.Key.E; } }
		public override int Priority { get { return 27; } }
		#endregion

		#region Mouse Handlers
		protected override void OnMouseMove (object o, Gtk.MotionNotifyEventArgs args, Cairo.PointD point)
		{
			Document doc = PintaCore.Workspace.ActiveDocument;

			if (mouse_button <= 0) {
				last_point = point_empty;
				return;
			}

			int x = (int)point.X;
			int y = (int)point.Y;

			if (last_point.Equals (point_empty))
				last_point = new Point (x, y);

			if (doc.Workspace.PointInCanvas (point))
				surface_modified = true;

			ImageSurface surf = doc.CurrentUserLayer.Surface;

			using (Context g = new Context (surf)) {
				g.AppendPath (doc.Selection.SelectionPath);
				g.FillRule = FillRule.EvenOdd;
				g.Clip ();

				g.Antialias = UseAntialiasing ? Antialias.Subpixel : Antialias.None;

				// Adding 0.5 forces cairo into the correct square:
				// See https://bugs.launchpad.net/bugs/672232
				g.MoveTo (last_point.X + 0.5, last_point.Y + 0.5);
				g.LineTo (x + 0.5, y + 0.5);

				// Right-click is erase to background color, left-click is transparent
				if (mouse_button == 3)
					g.SetSourceColor (PintaCore.Palette.SecondaryColor);
				else
					g.Operator = Operator.Clear;

				g.LineWidth = BrushWidth;
				g.LineJoin = LineJoin.Round;
				g.LineCap = LineCap.Round;

				g.Stroke ();
			}

			Gdk.Rectangle r = GetRectangleFromPoints (last_point, new Point (x, y));

			if (doc.Workspace.IsPartiallyOffscreen (r)) {
				doc.Workspace.Invalidate ();
			} else {
				doc.Workspace.Invalidate (doc.ClampToImageSize (r));
			}

			last_point = new Point (x, y);
		}
		#endregion
	}
}


text:
@implementation ErodeOperation

- (void)processImage:(vImage_Buffer *)inputBuffer outputBuffer:(vImage_Buffer *)outputBuffer {
    vImageMin_ARGB8888(inputBuffer,
                       outputBuffer,
                       NULL,
                       0,
                       0,
                       3,
                       3,
                       kvImageLeaveAlphaUnchanged);
}

@end


text:
package com.hannesdorfmann.mosby3.mvp.viewstate.lce.data;

import android.os.Parcel;
import android.os.Parcelable;
import com.hannesdorfmann.mosby3.mvp.lce.MvpLceView;
import com.hannesdorfmann.mosby3.mvp.viewstate.RestorableViewState;
import com.hannesdorfmann.mosby3.mvp.viewstate.lce.AbsParcelableLceViewState;
import com.hannesdorfmann.mosby3.mvp.viewstate.lce.LceViewState;
import java.util.ArrayList;
import java.util.List;

/**
 * A {@link LceViewState} and {@link RestorableViewState} that uses ArrayList containing
 * Parcelables as content data. It uses the default class loader (you could override {@link
 * #getClassLoader()}. It uses {@link Parcel#writeList(List)}
 * and {@link Parcel#readArrayList(ClassLoader)} for serialisation.
 *
 * <p>
 * Can be used for Activites and Fragments.
 * </p>
 *
 * @param <D> the type of the data / model that is put in an ArrayList
 * @param <V> the type of the view
 * @author Hannes Dorfmann
 * @since 1.0.0
 * @deprecated User {@link ParcelableListLceViewState}
 */
@Deprecated
public class ArrayListLceViewState<D extends ArrayList<? extends Parcelable>, V extends MvpLceView<D>>
    extends AbsParcelableLceViewState<D, V> {

  public static final Parcelable.Creator<ArrayListLceViewState> CREATOR =
      new Parcelable.Creator<ArrayListLceViewState>() {
        @Override public ArrayListLceViewState createFromParcel(Parcel source) {
          return new ArrayListLceViewState(source);
        }

        @Override public ArrayListLceViewState[] newArray(int size) {
          return new ArrayListLceViewState[size];
        }
      };

  public ArrayListLceViewState() {
  }

  private ArrayListLceViewState(Parcel source) {
    readFromParcel(source);
  }

  @Override public void writeToParcel(Parcel dest, int flags) {

    dest.writeList(loadedData);

    super.writeToParcel(dest, flags);
  }

  @Override protected void readFromParcel(Parcel source) {

    loadedData = (D) source.readArrayList(getClassLoader());

    super.readFromParcel(source);
  }

  /**
   * The class loader used for deserializing the list of parcelable items
   */
  protected ClassLoader getClassLoader() {
    return getClass().getClassLoader();
  }
}


text:
using System.Collections.Generic;
using Orchard.ContentManagement;

namespace Orchard.Lists.ViewModels {
    public class ChooseContentsViewModel  {
        public ChooseContentsViewModel() {
            OrderBy = ContentsOrder.Modified;
        }

        public string FilterByContentType { get; set; }
        public int SourceContainerId { get; set; }
        public int TargetContainerId { get; set; }

        public int? Page { get; set; }

        public string SelectedFilter { get; set; }
        public IEnumerable<KeyValuePair<string, string>> FilterOptions { get; set; }
        public ContentsOrder OrderBy { get; set; }
    }

}


text:
> **Note**
- Dates and times depend on current system time and will differ depending on when the testing is being carried out.

------
## Load Sample Data
------
> **Steps:**
- 1. Copy `SampleData.xml` into the same folder as `FlexiTrack.jar`
- 2. Rename `SampleData.xml` into `tasktracker.xml`
- 2. Run `FlexiTrack.jar`

------
## 0. Help Command
------
### 0.1 Overall help
> **Command:** `help`

> **Result:**
- Result display panel posts message:

`help: Shows program usage instructions.`

`List of Commands: add, clear, delete, edit, exit, find, list, mark, unmark, block, cs(Change Storage Path), undo, redo, gap `

`Example: help clear`

### 0.2 Specific command help
> **Command:** `h edit`

> **Result:**
- Result display panel posts message:

`edit, Shortcut [e]: Edits the specified task attributes of the task identified by the index number used in the last task listing.`

`Parameters to edit an event: [index] (must be a posi<br>tive integer) from/ [starting time] to/ [ending time]`
`Example: edit 1 from/ 01062016 to/ 01/072016`

`Parameters to edit a task: [index] (must be a positive integer) by/ [due date]`

`Example: edit 1 by/ 01062016`

------
## 1. Add Command
------
### 1.1 Add a floating task
> **Command:** `add Floating Task`

> **Result:**

- Result display panel posts message:

`New task added: Floating Task`

- TaskList panel displays newly added card which is white in color.

### 1.2 Add a task
> **Command:** `add Task by/Sunday 9am`

> **Result:**

- Result display panel posts message:

`New task added: Task by/Nov 13 2016 09:00`

- TaskList panel displays newly added card which is orange in color.

### 1.3 Add an event
> **Command:** `a Event from/ Sunday to/ Monday 10am`

> **Result:**

- Result display panel posts message:

`New task added: Event from/Nov 13 2016 08:00 to/Nov 14 2016 10:00`

`Duration of the event is: 1 day 2 hours.`

`Warning: this event is overlaping a existing event!`

- TaskList panel displays newly added card which is brown in color.

### 1.4 Add a recurring task
> **Command:** `add Recurring Task fr/3 ty/week by/tuesday`

> **Result:**

- Result display panel posts message:

`New task added: Recurring Task by/Nov 08 2016 08:00`. (Deadline of first added task)

- TaskList panel displays 3 newly added cards which are orange in color.

### 1.5 Add a recurring event
> **Command:** `a Recurring Event fr/2 ty/day from/tomorrow 8am to/ tomorrow 9am`

> **Result:**

- Result display panel posts message:

`New task added: Recurring Event from/Nov 08 2016 08:00 to/Nov 08 2016 09:00`

`Duration of the event is: 1 hour.` (Info of the first added event)

`Warning: this event is overlaping a existing event!`

- TaskList panel displays 2 newly added cards which are brown in color.

------
## 2. Block Command
------
### 2.1 Block Time
> **Command:** `block Visit Gramdma?? from/christmas to/christmas`

> **Result:**

- Result display panel posts message:

`Block the date for (Blocked) Visit Grandma?? from/Dec 25 2016 08:00 to/Dec 25 2016 17:00`

`Duration of the event is: 9 hours.`

- TaskList panel displays the newly added card which is brown in color and contains the prefix '(Blocked)'.

### 2.2 Add event over blocked time
> **Command:** `add Shopping from/christmas 10am to/christmas 12pm`

> **Result:**

- Result display panel posts message:

`This period of time has already taken by other event, Please choose another time.`

------
## 3. Gap Command
------
### 3.1 Find next available slot
> **Command:** `gap 2 hours n/1`

> **Result:**

- Result display panel posts message:

`The earliest 2 hours free time are found... `

`Between:  Nov 07 2016 21:00  to: Nov 08 2016 08:00`

### 3.2 Find next few available slots
> **Command:** `g 4 hours`

> **Result:**

- Result display panel posts message:

`The earliest 4 hours free time are found... `

`Between:  Nov 07 2016 21:00  to: Nov 08 2016 08:00`

`Between:  Nov 08 2016 11:00  to: Nov 09 2016 08:00`

`Between:  Nov 14 2016 10:00  to: Nov 14 2016 19:00`

------
## 4. Delete Command
------
### 4.1 Delete by index
> **Command:** `delete 1`

> **Result:**

- Result display panel posts message:

`Deleted task: Cook dinner for family`

- TaskList panel updates without the deleted task.

### 4.2 Delete index out of bounds
> **Command:** `delete 100`

> **Result:**

- Result display panel posts message:

`The task index provided is invalid `

------
## 5. Edit Command
------
### 5.1 Edit name
> **Command:** `edit 1 n/Name Edited`

> **Result:**

- Result display panel posts message:

`Edited: Cut hair into Cut hair @ beauty salon`

- TaskList panel updates with the edited task card.

### 5.2 Edit due date
> **Command:** `edit 9 by/ nov 9 11:59pm`

> **Result:**

- Result display panel posts message:

`Edited: CN4122 Project into CN4122 Project`

- TaskList panel updates with the edited task card.

### 5.3 Edit start time
> **Command:** `edit 7 from/nov 6 11am`

> **Result:**

- Result display panel posts message:

`Edited: Tuition @Serangoon into Tuition @Serangoon`

`Duration of the event is: 1 hour.`

- TaskList panel updates with the edited task card.

### 5.4 Edit end time
> **Command:** `edit 7 to/nov 6 1pm`

> **Result:**

- Result display panel posts message:

`Edited: Tuition @Serangoon into Tuition @Serangoon`

`Duration of the event is: 2 hours.`

- TaskList panel updates with the edited task card.

### 5.5 Edit floating task into task
> **Command:** `edit 1 by/ next tuesday 4pm`

> **Result:**

- Result display panel posts message:

`Edited: Cut hair @ beauty salon into Cut hair @ beauty salon`

- TaskList panel updates with the edited task card which is now orange.

### 5.6 Edit floating task into event
> **Command:** `edit 2 from/ tomorrow 5pm to/ tomorrow 6pm`

> **Result:**

- Result display panel posts message:

`Edited: Run 5km into Run 5km`

`Duration of the event is: 1 hour.`

- TaskList panel updates with the edited task card which is now brown.

### 5.7 Edit multiple parameters in any order (valid)
> **Command:** `edit 6 to/ nov 7 7pm from/ nov 7 5pm n/Chemistry Tuition @ Cantonment`

> **Result:**

- Result display panel posts message:

`Edited: chemistry tuition into Chemistry Tuition @ Cantonment`
`Duration of the event is: 2 hours.`

- TaskList panel updates with the edited task card.

------
## 6. Undo Command
------
### 6.1 Undo
> **Command:** `undo`

> **Result:**

- Result display panel posts message:

`Your last command has been undone!`

`Undid edit: chemistry tuition into Chemistry Tuition @ Cantonment`

- TaskList panel reverts to the state before part 5.7.

### 6.2 Undo shortcut
> **Command:** `ud`

> **Result:**

- Result display panel posts message:

`Your last command has been undone!`

`Undid edit: Run 5km into Run 5km `

- TaskList panel reverts to the state before part 5.6.

------
## 7. Redo Command
------
### 7.1 Redo
> **Command:** `redo`

> **Result:**

- Result display panel posts message:

`Your last command has been redone!`

`Edited: Run 5km into Run 5km`

`Duration of the event is: 1 hour.`

- TaskList panel reverts to the state after part 5.6.

### 7.2 Redo shortcut
> **Command:** `rd`

> **Result:**

- Result display panel posts message:

`Your last command has been redone!`

`Edited: chemistry tuition into Chemistry Tuition @ Cantonment`

`Duration of the event is: 2 hours. `

- TaskList panel reverts to the state after part 5.7.

------
## Test Storage
------
> **Steps:**
- 1. Close application
- 2. Run `FlexiTrack.jar`
> **Result:**

- Application should have loaded with the same data as before exiting.

------
## 8. Mark Command
------
### 8.1 Mark by index
> **Command:** `mark 5`

> **Result:**

- Result display panel posts message:

`Marked Task: 5`

- TaskList panel updates with the updated card which is now green with the prefix '(Done)'.

### 8.2 Mark something already marked
> **Command:** `m 59`

> **Result:**

- Result display panel posts message:

`Task already marked! `

------
## 9. Unmark Command
------
### 9.1 Unmark by index
> **Command:** `unmark 51`

> **Result:**

- Result display panel posts message:

`Unmark Task: 51`

- TaskList panel updates with the updated card which is now orange.

### 9.2 Unmark something not marked
> **Command:** `unmark 1`

> **Result:**

- Result display panel posts message:

`Task already unmarked!`

------
## 10. Find Command
------
### 10.1 Find by any keyword
> **Command:** `find chemistry tuition`

> **Result:**

- Result display panel posts message:

`12 tasks listed!`

- TaskList panel updates to show any card with 'chemistry' or 'tuition' in the name.

### 10.2 Find by exact phrase
> **Command:** `f f/ Chemistry Tuition`

> **Result:**

- Result display panel posts message:

`3 tasks listed!`

- TaskList panel updates to show any card with the exact phrase 'Chemistry Tuition' (not case sensitive) in the name.

------
## 11. List Command
------
### 11.1 List future
> **Command:** `list future`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only future unmarked cards. Floating tasks are also shown.

### 11.2 List past
> **Command:** `list past`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only past and marked cards. Floating tasks are also shown.

### 11.3 List specific date
> **Command:** `list christmas`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only cards which either are due on the specific date entered, or occur on that day (may start earlier and end later).

### 11.4 List past time frame
> **Command:** `list last week`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only cards that fall in that time frame.

### 11.5 List future time frame
> **Command:** `list next month`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only cards that fall in that time frame.

### 11.6 List marked items
> **Command:** `l mark`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only marked cards.

### 11.7 List unmarked items
> **Command:** `l unmark`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only unmarked cards.

### 11.8 List blocks
> **Command:** `l block`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show only blocks.

### 11.9 List all
> **Command:** `l`

> **Result:**

- Result display panel posts message:

`Listed all tasks`

- TaskList panel updates to show all items.

------
## 12. Clear Command
------
### 12.1 Clear
> **Command:** `clear`

> **Result:**

- Result display panel posts message:

`FlexiTrack has been cleared!`

- TaskList panel updates to become empty.
- All data is deleted.

------
## 13. Change Storage Command
------
### 13.1 Change storage
> **Command:** `cs newfile`

> **Result:**

- Result display panel posts message:

`Storage location changed: newfile.xml`

- newfile.xml is created in the FlexiTrack.xml directory and will be used as the new storage file.

------
## 14. Exit Command
------
### 14.1 exit
> **Command:** `q`

> **Result:**

- FlexiTrack exits.

------
## End
------


text:
package com.java110.api.listener.workflow;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.workflow.IWorkflowBMO;
import com.java110.api.bmo.workflow.IWorkflowStepStaffBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.workflow.WorkflowDto;
import com.java110.dto.workflow.WorkflowStepDto;
import com.java110.dto.workflow.WorkflowStepStaffDto;
import com.java110.intf.common.IWorkflowInnerServiceSMO;
import com.java110.intf.common.IWorkflowStepInnerServiceSMO;
import com.java110.intf.common.IWorkflowStepStaffInnerServiceSMO;
import com.java110.po.workflow.WorkflowPo;
import com.java110.po.workflow.WorkflowStepPo;
import com.java110.po.workflow.WorkflowStepStaffPo;
import com.java110.utils.constant.BusinessTypeConstant;
import com.java110.utils.constant.ServiceCodeWorkflowConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

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

/**
 * 保存工作流侦听
 * add by wuxw 2019-06-30
 */
@Java110Listener("updateWorkflowListener")
public class UpdateWorkflowListener extends AbstractServiceApiPlusListener {

    @Autowired
    private IWorkflowBMO workflowBMOImpl;

    @Autowired
    private IWorkflowStepStaffBMO workflowStepStaffBMO;

    @Autowired
    private IWorkflowStepStaffInnerServiceSMO workflowStepStaffInnerServiceSMOImpl;

    @Autowired
    private IWorkflowStepInnerServiceSMO workflowStepInnerServiceSMOImpl;

    @Autowired
    private IWorkflowInnerServiceSMO workflowInnerServiceSMOImpl;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {

        Assert.hasKeyAndValue(reqJson, "flowId", "flowId不能为空");
        Assert.hasKeyAndValue(reqJson, "flowName", "请求报文中未包含flowName");
        Assert.hasKeyAndValue(reqJson, "communityId", "请求报文中未包含communityId");
        Assert.hasKeyAndValue(reqJson, "storeId", "请求报文中未包含商户ID");

//        if (!reqJson.containsKey("steps")) {
//            Assert.hasKeyAndValue(reqJson, "steps", "请求报文中未包含步骤节点");
//        }

        JSONArray steps = reqJson.getJSONArray("steps");
        if (steps == null || steps.size() < 1) {
            //throw new IllegalArgumentException("未包含步骤");
            return;
        }
        JSONObject step = null;
        JSONObject subStaff = null;
        for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
            step = steps.getJSONObject(stepIndex);

            Assert.hasKeyAndValue(step, "staffId", "步骤中未包含员工");
            Assert.hasKeyAndValue(step, "staffName", "步骤中未包含员工");
            Assert.hasKeyAndValue(step, "type", "步骤中类型会签还是正常流程");

            //正常流程
            if (WorkflowStepDto.TYPE_NORMAL.equals(step.getString("type"))) {
                continue;
            }

            //会签流程
            if (!step.containsKey("subStaff")) {
                throw new IllegalArgumentException("未包含会签员工信息");
            }

            JSONArray subStaffs = step.getJSONArray("subStaff");

            if (subStaffs == null || subStaffs.size() < 1) {
                throw new IllegalArgumentException("未包含会签员工信息");
            }

            for (int subStaffIndex = 0; subStaffIndex < subStaffs.size(); subStaffIndex++) {
                subStaff = subStaffs.getJSONObject(subStaffIndex);
                Assert.hasKeyAndValue(subStaff, "staffId", "会签中未包含员工");
                Assert.hasKeyAndValue(subStaff, "staffName", "会签中未包含员工");
            }
        }

    }

    /**
     * {"flowId":"752020061762800001","flowName":"投诉建议流程","describle":"xxxx",
     * "steps":[{"seq":0,"staffId":"302020060983230118","staffName":"孙印玉测试","type":"1",
     * "subStaff":[{"id":"d1aa0277-ff10-480e-855c-c90a1789909b","staffId":"302020061069500135","staffName":"天宫妹"}]},
     * {"seq":1,"staffId":"302020042299500115","staffName":"阿光","type":"2","subStaff":[]}]}"
     *
     * @param event   事件对象
     * @param context 数据上文对象
     * @param reqJson 请求报文
     */
    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {

        if (reqJson.containsKey("flowType")) {
            String flowType = reqJson.getString("flowType");
            if (WorkflowDto.FLOW_TYPE_PURCHASE.equals(flowType)
                    || WorkflowDto.FLOW_TYPE_CONTRACT_CHANGE.equals(flowType)
                    || WorkflowDto.FLOW_TYPE_ALLOCATION_STOREHOUSE.equals(flowType)
                    || WorkflowDto.FLOW_TYPE_CONTRACT_APPLY.equals(flowType)) {
                reqJson.put("communityId", "9999");
            }
        }

        WorkflowStepDto workflowStepDto = new WorkflowStepDto();
        workflowStepDto.setFlowId(reqJson.getString("flowId"));
        workflowStepDto.setCommunityId(reqJson.getString("communityId"));
        List<WorkflowStepDto> workflowStepDtos = workflowStepInnerServiceSMOImpl.queryWorkflowSteps(workflowStepDto);
        if (workflowStepDtos != null) {
            for (WorkflowStepDto tmpWorkflowStepDto : workflowStepDtos) {
                deleteWorkflowStepAndStaff(context, reqJson, tmpWorkflowStepDto);
            }
        }

        //修改 工作流程
        WorkflowPo workflowPo = new WorkflowPo();
        workflowPo.setFlowId(reqJson.getString("flowId"));
        workflowPo.setFlowName(reqJson.getString("flowName"));
        workflowPo.setCommunityId(reqJson.getString("communityId"));
        workflowPo.setDescrible(reqJson.getString("describle"));

        //保存 工作流程步骤
        JSONArray steps = reqJson.getJSONArray("steps");
        String processDefinitionKey = "";
        if (steps != null && steps.size() > 0) { // 有步骤
            JSONObject step = null;
            JSONObject subStaff = null;
            WorkflowStepStaffPo workflowStepStaffPo = null;
            List<WorkflowStepDto> tmpWorkflowStepDtos = new ArrayList<>();
            for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
                step = steps.getJSONObject(stepIndex);
                WorkflowStepPo workflowStepPo = new WorkflowStepPo();
                workflowStepPo.setStepId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_flowId));
                workflowStepPo.setCommunityId(workflowPo.getCommunityId());
                workflowStepPo.setFlowId(workflowPo.getFlowId());
                workflowStepPo.setSeq((stepIndex + 1) + "");
                workflowStepPo.setType(step.getString("type"));
                workflowStepPo.setStoreId(reqJson.getString("storeId"));
                super.insert(context, workflowStepPo, BusinessTypeConstant.BUSINESS_TYPE_SAVE_WORKFLOW_STEP);
                WorkflowStepDto tmpWorkflowStepDto = BeanConvertUtil.covertBean(workflowStepPo, WorkflowStepDto.class);
                //正常流程
                List<WorkflowStepStaffDto> workflowStepStaffDtos = new ArrayList<>();
                workflowStepStaffPo = new WorkflowStepStaffPo();
                workflowStepStaffPo.setWssId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_wssId));
                workflowStepStaffPo.setCommunityId(workflowPo.getCommunityId());
                workflowStepStaffPo.setStaffId(step.getString("staffId"));
                workflowStepStaffPo.setStaffName(step.getString("staffName"));
                workflowStepStaffPo.setStepId(workflowStepPo.getStepId());
                workflowStepStaffPo.setFlowType(reqJson.getString("flowType"));
                workflowStepStaffPo.setStaffRole(StringUtil.isEmpty(step.getString("staffRole")) ? "1001" : step.getString("staffRole"));

                if (!"1001".equals(workflowStepStaffPo.getStaffRole()) && workflowStepStaffPo.getStaffRole().startsWith("${")) {
                    throw new IllegalArgumentException("采购人员或者物品领用人员必须指定人,不能是动态指定");
                }
                super.insert(context, workflowStepStaffPo, BusinessTypeConstant.BUSINESS_TYPE_SAVE_WORKFLOW_STEP_STAFF);
                workflowStepStaffDtos.add(BeanConvertUtil.covertBean(workflowStepStaffPo, WorkflowStepStaffDto.class));
                //会签流程
                JSONArray subStaffs = step.getJSONArray("subStaff");
                if (subStaffs != null && subStaffs.size() > 0) {
                    for (int subStaffIndex = 0; subStaffIndex < subStaffs.size(); subStaffIndex++) {
                        subStaff = subStaffs.getJSONObject(subStaffIndex);
                        workflowStepStaffPo = new WorkflowStepStaffPo();
                        workflowStepStaffPo.setWssId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_wssId));
                        workflowStepStaffPo.setCommunityId(workflowPo.getCommunityId());
                        workflowStepStaffPo.setStaffId(subStaff.getString("staffId"));
                        workflowStepStaffPo.setStaffName(subStaff.getString("staffName"));
                        workflowStepStaffPo.setStepId(workflowStepPo.getStepId());
                        workflowStepStaffPo.setStaffRole(StringUtil.isEmpty(subStaff.getString("staffRole")) ? "1001" : subStaff.getString("staffRole"));

                        super.insert(context, workflowStepStaffPo, BusinessTypeConstant.BUSINESS_TYPE_SAVE_WORKFLOW_STEP_STAFF);
                        workflowStepStaffDtos.add(BeanConvertUtil.covertBean(workflowStepStaffPo, WorkflowStepStaffDto.class));
                    }
                }

                tmpWorkflowStepDto.setWorkflowStepStaffs(workflowStepStaffDtos);

                tmpWorkflowStepDtos.add(tmpWorkflowStepDto);
            }

            WorkflowDto workflowDto = BeanConvertUtil.covertBean(workflowPo, WorkflowDto.class);
            workflowDto.setWorkflowSteps(tmpWorkflowStepDtos);
            WorkflowDto tmpWorkflowDto = workflowInnerServiceSMOImpl.addFlowDeployment(workflowDto);
            processDefinitionKey = tmpWorkflowDto.getProcessDefinitionKey();
        } else {
            processDefinitionKey = "-1";
        }
        //提交
        //commit(context);
        workflowPo.setProcessDefinitionKey(processDefinitionKey);
        super.update(context, workflowPo, BusinessTypeConstant.BUSINESS_TYPE_UPDATE_WORKFLOW);

    }

    private void deleteWorkflowStepAndStaff(DataFlowContext context, JSONObject reqJson, WorkflowStepDto workflowStepDto) {
        WorkflowStepStaffDto workflowStepStaffDto = new WorkflowStepStaffDto();
        workflowStepStaffDto.setStepId(workflowStepDto.getStepId());
        workflowStepStaffDto.setCommunityId(workflowStepDto.getCommunityId());
        List<WorkflowStepStaffDto> workflowStepStaffDtos = workflowStepStaffInnerServiceSMOImpl.queryWorkflowStepStaffs(workflowStepStaffDto);

        WorkflowStepPo workflowStepPo = new WorkflowStepPo();
        workflowStepPo.setCommunityId(workflowStepDto.getCommunityId());
        workflowStepPo.setStepId(workflowStepDto.getStepId());
        super.delete(context, workflowStepPo, BusinessTypeConstant.BUSINESS_TYPE_DELETE_WORKFLOW_STEP);
        if (workflowStepStaffDtos == null) {
            return;
        }
        for (WorkflowStepStaffDto tmpWorkflowStepStaffDto : workflowStepStaffDtos) {
            WorkflowStepStaffPo workflowStepStaffPo = new WorkflowStepStaffPo();
            workflowStepStaffPo.setCommunityId(workflowStepDto.getCommunityId());
            workflowStepStaffPo.setWssId(tmpWorkflowStepStaffDto.getWssId());
            super.delete(context, workflowStepStaffPo, BusinessTypeConstant.BUSINESS_TYPE_DELETE_WORKFLOW_STEP_STAFF);
        }
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeWorkflowConstant.UPDATE_WORKFLOW;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }
}


text:
#include "cpu/pred/ras.hh"

void
ReturnAddrStack::init(unsigned _numEntries)
{
     numEntries  = _numEntries;
     addrStack.resize(numEntries);
     reset();
}

void
ReturnAddrStack::reset()
{
    usedEntries = 0;
    tos = 0;
    for (unsigned i = 0; i < numEntries; ++i)
        addrStack[i].set(0);
}

void
ReturnAddrStack::push(const TheISA::PCState &return_addr)
{
    incrTos();

    addrStack[tos] = return_addr;

    if (usedEntries != numEntries) {
        ++usedEntries;
    }
}

void
ReturnAddrStack::pop()
{
    if (usedEntries > 0) {
        --usedEntries;
    }

    decrTos();
}

void
ReturnAddrStack::restore(unsigned top_entry_idx,
                         const TheISA::PCState &restored)
{
    tos = top_entry_idx;

    addrStack[tos] = restored;
}


text:
package quarks.runtime.etiao.graph.model;

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

import quarks.graph.Edge;

/**
 * Represents an edge between two {@link VertexType} nodes.
 */
public class EdgeType {
    /** Source vertex identifier */
	private final String sourceId;
    /** Source output port index */
	private final int sourceOutputPort;
    /** Target vertex identifier */
	private final String targetId;
    /** Target input port index */
	private final int targetInputPort;
    /** Set of tags associated with this edge */
    private final Set<String> tags;

    public EdgeType() {
        this.sourceId = null;
        this.sourceOutputPort = 0;
        this.targetId = null;
        this.targetInputPort = 0;
        this.tags = new HashSet<>();
    }

    public EdgeType(Edge value, IdMapper<String> ids) {
        this.sourceId = ids.getId(value.getSource()).toString();
        this.sourceOutputPort = value.getSourceOutputPort();
        this.targetId = ids.getId(value.getTarget()).toString();
        this.targetInputPort = value.getTargetInputPort();
        this.tags = value.getTags();
    }

    public String getSourceId() {
        return sourceId;
    }

    public int getSourceOutputPort() {
        return sourceOutputPort;
    }

    public String getTargetId() {
        return targetId;
    }

    public int getTargetInputPort() {
        return targetInputPort;
    }

    public Set<String> getTags() {
        return tags;
    }
}


text:
package com.github.groovylabs.lyre.engine.scanner;

import com.github.groovylabs.lyre.config.LyreProperties;
import com.github.groovylabs.lyre.engine.reader.Reader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class Scanner {

    private static final Logger LOGGER = LoggerFactory.getLogger(Scanner.class);

    @Autowired
    private Reader reader;

    @Autowired
    private LyreProperties lyreProperties;

    private List<File> files = new ArrayList<>();

    private Thread watcherInstance = null;

    private Watcher watcher = null;

    @PostConstruct
    public void init() {
        scan();
    }

    public void scan() {

        LOGGER.info("Scanning [*{}] files on path: [{}]",
            lyreProperties.getFileFormat(), lyreProperties.getScanPath());

        File folder = new File(lyreProperties.getScanPath());

        if (folder.isDirectory()) {

            File[] fileList = folder.listFiles();

            searchFiles(fileList);

            startWatcher(files);

            reader.read(files.toArray(new File[]{}));

        } else {
            LOGGER.error("Error while scanning, scan-path property must point to a valid directory.");
        }

    }

    public final void startWatcher(List<File> files) {
        if (watcherInstance == null) {
            if (lyreProperties.isEnableLiveReload()) {
                watcher = new Watcher(this, files, lyreProperties);
                watcherInstance = new Thread(watcher);
                watcherInstance.start();
            } else {
                LOGGER.info("Watcher disabled, " +
                    "to enable live-reload feature set 'lyre.enable-live-reload=true' on properties");
            }
        }
    }

    private List<File> searchFiles(File[] fileList) {

        for (File file : fileList) {

            if (file.isFile() && file.getName().endsWith(lyreProperties.getFileFormat()))
                files.add(file);
            else if (file.isDirectory())
                searchFiles(file.listFiles());

        }

        return files;
    }

    public Reader getReader() {
        return reader;
    }

    public void setReader(Reader reader) {
        this.reader = reader;
    }

    public LyreProperties getLyreProperties() {
        return lyreProperties;
    }

    public void setLyreProperties(LyreProperties lyreProperties) {
        this.lyreProperties = lyreProperties;
    }

    public List<File> getFiles() {
        return files;
    }

    public void setFiles(List<File> files) {
        this.files = files;
    }

    public final Thread getWatcherInstance() {
        return watcherInstance;
    }

    public final Watcher getWatcher() {
        return watcher;
    }
}


text:
package models

type Author struct {
	Role string `json:"role,omitempty"`
	User *User  `json:"user,omitempty"`
}

type Comment struct {
	Author      *User      `json:"author,omitempty"`
	Comments    []*Comment `json:"comments,omitempty"`
	CreatedDate int64      `json:"createdDate,omitempty"`
	ID          int64      `json:"id,omitempty"`
	Text        string     `json:"text,omitempty"`
	UpdatedDate int64      `json:"updatedDate,omitempty"`
	Version     int64      `json:"version,omitempty"`
}

type CommitsResponse struct {
	IsLastPage    bool  `json:"isLastPage,omitempty"`
	Limit         int64 `json:"limit,omitempty"`
	NextPageStart int64 `json:"nextPageStart,omitempty"`
	Size          int64 `json:"size,omitempty"`
	Start         int64 `json:"start,omitempty"`
}

type Link struct {
	Rel string `json:"rel,omitempty"`
	URL string `json:"url,omitempty"`
}

/** PR stuff */
type PullRequest struct {
	Author      *Author           `json:"author,omitempty"`
	CreatedDate int64             `json:"createdDate,omitempty"`
	Description string            `json:"description,omitempty"`
	ID          int64             `json:"id,omitempty"`
	Links       *PullRequestLinks `json:"links,omitempty"`
	State       string            `json:"state,omitempty"`
	Title       string            `json:"title,omitempty"`
	UpdatedDate int64             `json:"updatedDate,omitempty"`
	Version     int64             `json:"version,omitempty"`
}

type PullRequestLinks struct {
	Self []*PullRequestSelfItems0 `json:"self,omitempty"`
}

type PullRequestSelfItems0 struct {
	Href string `json:"href,omitempty"`
}

type PullRequestActivitiesResponse struct {
	IsLastPage    bool                   `json:"isLastPage,omitempty"`
	Limit         int64                  `json:"limit,omitempty"`
	NextPageStart int64                  `json:"nextPageStart,omitempty"`
	Size          int64                  `json:"size,omitempty"`
	Start         int64                  `json:"start,omitempty"`
	Values        []*PullRequestActivity `json:"values,omitempty"`
}

type PullRequestActivity struct {
	/** COMMENTED, OPENED, APPROVED, RESCOPED, MERGED, DECLINED, UNAPPROVED, some others i think too */
	Action      string   `json:"action,omitempty"`
	Comment     *Comment `json:"comment,omitempty"`
	CreatedDate int64    `json:"createdDate,omitempty"`
	ID          int64    `json:"id,omitempty"`
	User        *User    `json:"user,omitempty"`
}

type PullRequestResponse struct {
	Author      *Author `json:"author,omitempty"`
	CreatedDate int64   `json:"createdDate,omitempty"`
	Description string  `json:"description,omitempty"`
	ID          int64   `json:"id,omitempty"`
	State       string  `json:"state,omitempty"`
	Title       string  `json:"title,omitempty"`
	UpdatedDate int64   `json:"updatedDate,omitempty"`
	Version     int64   `json:"version,omitempty"`
}

type PullRequestsResponse struct {
	IsLastPage    bool           `json:"isLastPage,omitempty"`
	Limit         int64          `json:"limit,omitempty"`
	NextPageStart int64          `json:"nextPageStart,omitempty"`
	Size          int64          `json:"size,omitempty"`
	Start         int64          `json:"start,omitempty"`
	Values        []*PullRequest `json:"values,omitempty"`
}

type User struct {
	DisplayName  string `json:"displayName,omitempty"`
	EmailAddress string `json:"emailAddress,omitempty"`
	ID           int64  `json:"id,omitempty"`
	Link         *Link  `json:"link,omitempty"`
	Name         string `json:"name,omitempty"`
	Slug         string `json:"slug,omitempty"`
}


text:
CLASS({
  package: 'foam.apps.builder.kiosk',
  name: 'ImportWizard',
  extends: 'foam.apps.builder.wizard.WizardPage',

  imports: [
    'importExportManager$',
  ],

  requires: [
    'foam.apps.builder.ImportExportFlow',
    'foam.apps.builder.ImportExportFlowView',
    'foam.apps.builder.kiosk.ChromeWizard',
  ],

  properties: [
    'importExportManager',
    {
      name: 'title',
      defaultValue: 'Import existing app',
    },
    {
      type: 'Int',
      name: 'appBuilderVersion',
      defaultValue: 1,
    },
    {
      name: 'importFlow',
      lazyFactory: function() {
        return this.ImportExportFlow.create({
          config$: this.data$,
          dao$: this.dao$,
          actionName: this.getActionName(),
          title: 'Import App',
        }, this.Y);
      },
    },
  ],

  methods: [
    function getActionName() {
      return 'importV' + this.appBuilderVersion.toString() + 'App';
    },
    function onCancel() {
      this.SUPER();
      // remove the unfinished app. The user must have backed out of
      // every other wizard page to get back here.
      this.dao && this.dao.remove(this.data);
    },

  ],

  actions: [
    {
      name: 'chooseFolder',
      code: function() {
        var view = this.ImportExportFlowView.create({
          data: this.importFlow,
          showHeader: false,
          showFooter: false,
        }, this.Y);
        var content = this.X.$(this.id + '-centered-content');
        content.innerHTML = view.toHTML();
        view.initHTML();
        this.importExportManager[this.getActionName()](this.importFlow);
      },
    },
    {
      name: 'nextAction',
      isEnabled: function() {
        this.importFlow;
        return this.importFlow && (this.importFlow.state === 'FAILED' ||
            this.importFlow.state === 'COMPLETED');
      },
    },
  ],

  templates: [
    function instructionHTML() {/*

        Click the button below to select the folder that contains the unpackaged
        source of your <% if ( this.appBuilderVersion === 1 ) { %>Chrome App
        Builder Version 1<% } else { %>App Builder Version 2<% } %> app. App
        Builder will automatically lookup your app configuration
        <% if ( this.appBuilderVersion === 1 ) { %>and upgrade it to App Builder
        2.0<% } %>.

    */},
    function contentHTML() {/*

        $$chooseFolder

    */},
    function CSS() {/*
      .centered-content {
        flex-grow: 1;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    */},
  ],
});


text:
package crx3

import (
	"archive/zip"
	"io"
	"os"
	"path/filepath"
)

// Zip creates a *.zip archive and adds all the files to it.
func Zip(w io.Writer, unpacked string) error {
	if !isDir(unpacked) {
		return ErrPathNotFound
	}
	wz := zip.NewWriter(w)
	defer wz.Close()
	return filepath.Walk(unpacked, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}
		relpath, err := filepath.Rel(unpacked, path)
		if err != nil {
			return err
		}
		return writeToZip(wz, path, relpath)
	})
}

func writeToZip(w *zip.Writer, filename string, metaname string) error {
	fd, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer fd.Close()

	info, err := fd.Stat()
	if err != nil {
		return err
	}

	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}

	header.Name = metaname
	header.Method = zip.Deflate
	writer, err := w.CreateHeader(header)
	if err != nil {
		return err
	}
	_, err = io.Copy(writer, fd)
	return err
}


text:
"use strict";

const log = require("gitpunch-lib/log").default;
const { SQS } = require("aws-sdk");

let {
  SQS_URL,
  RECEIVE_MAX_EVENTS = 40,
  SQS_REQUEST_TIMEOUT = 2000,
  DONT_DELETE_EVENTS = false,
} = process.env;
RECEIVE_MAX_EVENTS = +RECEIVE_MAX_EVENTS;
SQS_REQUEST_TIMEOUT = +SQS_REQUEST_TIMEOUT;

const sqs = new SQS({
  apiVersion: "2012-11-05",
});

module.exports.default = async function getRecentlyReleasedRepos(limit) {
  try {
    const messages = await receiveQueuedMesages(limit);
    const repos = [...new Set(messages.map((e) => e.repoName))];
    log("recentlyReleasedRepos", { repos, count: repos.length });
    return repos;
  } catch (e) {
    log("error", { error: e });
    return [];
  }
};

async function receiveQueuedMesages(limit) {
  try {
    const params = {
      QueueUrl: SQS_URL,
      MaxNumberOfMessages: 10,
    };
    const responses = [];
    const messages = [];
    while (messages.length < limit) {
      const response = await receiveMessage(params);
      responses.push(response);
      messages.push(
        ...response.Messages.map((m) => {
          try {
            return JSON.parse(m.Body);
          } catch (e) {
            return null;
          }
        })
        .filter(Boolean)
      );
      if (!response.Messages.length) {
        break;
      }
    }
    if (!DONT_DELETE_EVENTS) {
      await Promise.all(responses.map(deleteMessageBatch));
    }
    return messages;
  } catch (e) {
    return [];
  }
}

function receiveMessage(params) {
  const request = sqs.receiveMessage(params);
  setTimeout(() => request.abort(), SQS_REQUEST_TIMEOUT);
  return request.promise().catch((e) => {
    log("receiveMessageError", { error: e });
    return { Messages: [] };
  });
}

function deleteMessageBatch({ Messages }) {
  if (!Messages || !Messages.length) {
    return;
  }
  const request = sqs.deleteMessageBatch({
    QueueUrl: SQS_URL,
    Entries: Messages.map((message, index) => ({
      Id: `${index}`,
      ReceiptHandle: message.ReceiptHandle,
    })),
  });
  setTimeout(() => request.abort(), SQS_REQUEST_TIMEOUT);
  return request
    .promise()
    .catch((e) => log("deleteMessageBatchError", { error: e }));
}


text:
require 'factory'
module RSpec
  module Rails
    module Mocks
      def method_missing(method,*args,&blk)
        method_name = method.to_s.split('_',2)
        if method_name.first == 'mock' and defined?(method_name.last.camelize)
          class_name = method_name.last
          mock_model(class_name.camelize.constantize,*args)
        else
          super(method,*args,&blk)
        end
      end
    end
  end

  module Mocks
    module Methods
      def stub_association!(association_name, methods_to_be_stubbed = {})
        mock_association = RSpec::Mocks::Mock.new(association_name.to_s)
        methods_to_be_stubbed.each do |method, return_value|
          mock_association.stub!(method).and_return(return_value)
        end
        self.stub!(association_name).and_return(mock_association)
      end
    end
  end
end


text:
package org.spongepowered.common.data.manipulator.mutable.block;

import static com.google.common.base.Preconditions.checkNotNull;

import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableShrubData;
import org.spongepowered.api.data.manipulator.mutable.block.ShrubData;
import org.spongepowered.api.data.type.ShrubType;
import org.spongepowered.api.data.type.ShrubTypes;
import org.spongepowered.common.data.manipulator.immutable.block.ImmutableSpongeShrubData;
import org.spongepowered.common.data.manipulator.mutable.common.AbstractSingleCatalogData;

public class SpongeShrubData extends AbstractSingleCatalogData<ShrubType, ShrubData, ImmutableShrubData> implements ShrubData {

    public SpongeShrubData(ShrubType variant) {
        super(ShrubData.class, checkNotNull(variant), Keys.SHRUB_TYPE, ImmutableSpongeShrubData.class);
    }

    public SpongeShrubData() {
        this(ShrubTypes.TALL_GRASS);
    }
}


text:
using Newtonsoft.Json;
using System;
using System.Globalization;

namespace Odachi.JsonRpc.Common.Converters
{
	public class DateOnlyConverter : JsonConverter<DateOnly>
	{
		private const string DateFormat = "yyyy-MM-dd";

		public override DateOnly ReadJson(JsonReader reader, Type objectType, DateOnly existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			return DateOnly.ParseExact((string)reader.Value, DateFormat, CultureInfo.InvariantCulture);
		}

		public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer)
		{
			writer.WriteValue(value.ToString(DateFormat, CultureInfo.InvariantCulture));
		}
	}
}


text:
define([], function() {
    'use strict';
    /**
     * Comment section, currently only used for travel expense reports.
     * Comments are expected to have the fields submissionDate, employee and text.
     * <p>
     * Attributes:
     * * comments: {Array} A reference to the comments array
     * * preprocessor: {Function} A function that is called on a new comment before it is POSTed. Users can add new fields to it. Not optional!
     * * url: {String} A string that is the entity Restangular should use to POST, e.g. 'travelExpenseReportComments'
     */
    return [function() {
        return {
            restrict: 'E',
            templateUrl: 'src/modules/trackr/directives/commentSection.tpl.html',
            scope: {comments: '=', preprocessor: '=', url: '@'},
            controller: ['$scope', 'Restangular', 'trackr.services.employee', function($scope, Restangular, EmployeeService) {
                var controller = this;

                $scope.comment = {};
                $scope.errors = {};

                controller.addComment = function(comment, employee, url) {
                    comment.employee = employee._links.self.href;
                    comment.submissionDate = new Date();
                    return Restangular.all(url).post(comment);
                };

                $scope.addComment = function() {
                    var _comment = $scope.preprocessor($scope.comment);
                    controller.addComment(_comment, EmployeeService.getEmployee(), $scope.url)
                        .then(function(comment) {
                            // The REST service does not return the employee but it is needed for display.
                            comment.employee = EmployeeService.getEmployee();
                            $scope.comments.push(comment);
                            $scope.comment = {};
                        });
                };
            }]
        };
    }];
});


text:
#ifndef __curlcpp__curl_sender__
#define __curlcpp__curl_sender__

#include "curl_easy.h"

namespace curl {
    /**
     * This class implements a sender that sends raw data on an established
     * connection on an easy handler.
     */
    template<class T> class curl_sender {
    public:
        /**
         * The constructor initializes the easy handler and the number of
         * sent bytes.
         */
        curl_sender(curl_easy &easy);
        /**
         * This method wraps the curl_easy_send function that sends raw data
         * on an established connection on an easy handler.
         */
        void send(const T, const size_t);
        /**
         * Simple getter method that returns sent's current byte number.
         */
        size_t get_sent_bytes() const;
    private:
        curl_easy &_easy;
        size_t _sent_bytes;
    };

    // Implementation of constructor.
    template<class T> curl_sender<T>::curl_sender(curl_easy &easy) : _easy(easy), _sent_bytes(0) {
        // ... nothing to do here ...
    }

    // Implementation of send method.
    template<class T> void curl_sender<T>::send(const T buffer, const size_t size) {
        const CURLcode code = curl_easy_send(_easy.get_curl(),buffer,size,&_sent_bytes);
        if (code != CURLE_OK) {
            throw curl_easy_exception(code,__FUNCTION__);
        }
    }

    // Implementation of get_sent_bytes method.
    template<class T> inline size_t curl_sender<T>::get_sent_bytes() const {
        return _sent_bytes;
    }

    /**
     * Template specialization for strings. C++ string type is not supported by libcurl C
     * functions, so we must treat it as a const char pointer. This is the purpose of
     * this class.
     */
    template<> class curl_sender<std::string> {
    public:
        /**
         * The constructor initializes the easy handler and the number of
         * sent bytes.
         */
        curl_sender(curl_easy &easy) : _easy(easy), _sent_bytes(0) {}
        /**
         * This method wraps the curl_easy_send function that sends raw data
         * on an established connection on an easy handler, treating strings
         * as const char pointers.
         */
        void send(const std::string buffer) {
            const CURLcode code = curl_easy_send(_easy.get_curl(),buffer.c_str(),buffer.length(),&_sent_bytes);
            if (code != CURLE_OK) {
                throw curl_easy_exception(code,__FUNCTION__);
            }
        }
        /**
         * Simple getter method that returns sent's current byte number.
         */
        inline size_t get_sent_bytes() const {
            return _sent_bytes;
        }
    private:
        curl_easy &_easy;
        size_t _sent_bytes;
    };
}

#endif /* defined(__curlcpp__curl_sender__) */


text:
<?php

namespace Magento\Bundle\Model\Product;

/**
 * Price model for external catalogs
 */
class CatalogPrice implements \Magento\Catalog\Model\Product\CatalogPriceInterface
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Catalog\Model\Product\CatalogPrice
     */
    protected $commonPriceModel;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $coreRegistry;

    /**
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Catalog\Model\Product\CatalogPrice $commonPriceModel
     * @param \Magento\Framework\Registry $coreRegistry
     */
    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\Product\CatalogPrice $commonPriceModel,
        \Magento\Framework\Registry $coreRegistry
    ) {
        $this->storeManager = $storeManager;
        $this->commonPriceModel = $commonPriceModel;
        $this->coreRegistry = $coreRegistry;
    }

    /**
     * {@inheritdoc}
     */
    public function getCatalogPrice(
        \Magento\Catalog\Model\Product $product,
        \Magento\Store\Api\Data\StoreInterface $store = null,
        $inclTax = false
    ) {
        if ($store instanceof \Magento\Store\Api\Data\StoreInterface) {
            $currentStore = $this->storeManager->getStore();
            $this->storeManager->setCurrentStore($store->getId());
        }

        $this->coreRegistry->unregister('rule_data');
        $this->coreRegistry->register(
            'rule_data',
            new \Magento\Framework\DataObject(
                [
                    'store_id' => $product->getStoreId(),
                    'website_id' => $product->getWebsiteId(),
                    'customer_group_id' => $product->getCustomerGroupId(),
                ]
            )
        );

        $minPrice = $product->getPriceModel()->getTotalPrices($product, 'min', $inclTax);

        if ($store instanceof \Magento\Store\Api\Data\StoreInterface) {
            $this->storeManager->setCurrentStore($currentStore->getId());
        }
        return $minPrice;
    }

    /**
     * Regular catalog price not applicable for bundle product
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return null
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function getCatalogRegularPrice(\Magento\Catalog\Model\Product $product)
    {
        return null;
    }
}


text:
package org.ohdsi.olympus.controller;

import java.util.List;

import javax.servlet.ServletContext;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.ohdsi.olympus.model.AppProperties;
import org.ohdsi.olympus.model.WebApiProperties;
import org.ohdsi.olympus.model.WebApiRemote;
import org.ohdsi.olympus.model.WebApiService;
import org.ohdsi.olympus.view.factory.CommonTemplateFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 */
@Controller
@RequestMapping("/webapi")
public class WebApiController {

    private static final Log log = LogFactory.getLog(WebApiController.class);

    private static final String CONFIG_MODEL_ATTR = "config";

    private static final String APPPROPERTIES_MODEL_ATTR = "appproperties";

    private static final String REMOTE_MODEL_ATTR = "remote";

    private static final String CONFIGURATION_TEMPLATE_NAME = "home/config";

    @Autowired
    private EmbeddedWebApplicationContext server;

    @Autowired
    private ServletContext sc;

    @Autowired
    private ContextHandlerCollection contextHandlerCollection;

    @Autowired
    private WebApiService webApi;

    @Autowired
    private CommonTemplateFactory templateFactory;

    @Autowired
    private MainController mainController;

    @Autowired
    private Validator webApiPropertiesValidator;

    @ModelAttribute(value = "remotes")
    public List<WebApiRemote> getRemotes() {
        return this.webApi.getRemotes();
    }

    @ModelAttribute(value = APPPROPERTIES_MODEL_ATTR)
    public AppProperties getAppProperties() {
        return this.webApi.getAppProperties();
    }

    @ModelAttribute(value = CONFIG_MODEL_ATTR)
    public WebApiProperties getWebApiProperties() {
        return this.webApi.getProperties();
    }

    @InitBinder(value = CONFIG_MODEL_ATTR)
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(this.webApiPropertiesValidator);
    }

    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public HttpEntity<List<WebApiRemote>> webApis() {
        return new ResponseEntity<List<WebApiRemote>>(this.webApi.getWebApis(), HttpStatus.OK);
    }

    @RequestMapping(value = "/" + CONFIG_MODEL_ATTR)
    public ModelAndView handleConfigurationRequest(String errorMsg) throws Exception {
        log.debug("Get config");
        ModelAndView modelAndView = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
        modelAndView.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
        modelAndView.addObject(APPPROPERTIES_MODEL_ATTR, getAppProperties());
        if (errorMsg != null) {
            modelAndView.addObject("errorMsg", errorMsg);
        }
        return modelAndView;
    }

    @RequestMapping(value = "/" + REMOTE_MODEL_ATTR, method = RequestMethod.POST)
    public ModelAndView handleConfigurationSubmission(@Valid @ModelAttribute(REMOTE_MODEL_ATTR) WebApiRemote remote,
                                                      BindingResult result) throws Exception {
        if (result.hasErrors() || isDuplicate(remote, getRemotes()) || remote.getName().equalsIgnoreCase("local")) {
            ModelAndView view = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
            view.addObject(CONFIG_MODEL_ATTR, getWebApiProperties());
            view.addObject(APPPROPERTIES_MODEL_ATTR, getAppProperties());
            view.addObject(REMOTE_MODEL_ATTR, remote);
            if (!result.hasErrors()) {
                //duplicate or "local" reserved name
                if (remote.getName().equalsIgnoreCase("local")) {
                    result.addError(new FieldError("remote", "name", "'Local' is reserved"));
                } else {
                    result.addError(new FieldError("remote", "name", "Name must be unique"));
                }
            }
            log.info("Has Errors: " + result);
            view.addObject("errors", result);
            return view;
        }
        if (!remote.getUrl().endsWith("/")) {
            remote.setUrl(remote.getUrl().concat("/"));
        }

        log.debug("Saving WebApi Remote");
        remote = this.webApi.saveRemote(remote);
        String msg = "Saved WebApi Remote";
        log.info(msg);

        ModelAndView modelAndView = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
        modelAndView.addObject(CONFIG_MODEL_ATTR, getWebApiProperties());
        modelAndView.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
        modelAndView.addObject(APPPROPERTIES_MODEL_ATTR, getAppProperties());
        modelAndView.addObject("remotes", getRemotes());
        modelAndView.addObject("msg", msg);
        return modelAndView;
    }

    @RequestMapping(value = "/" + APPPROPERTIES_MODEL_ATTR, method = RequestMethod.POST)
    public ModelAndView handleConfigurationSubmission(@Valid @ModelAttribute(APPPROPERTIES_MODEL_ATTR) AppProperties appProperties,
                                                      BindingResult result) throws Exception {
        if (result.hasErrors()) {
            ModelAndView view = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
            view.addObject(CONFIG_MODEL_ATTR, getWebApiProperties());
            view.addObject(APPPROPERTIES_MODEL_ATTR, appProperties);
            view.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
            log.info("Has Errors: " + result);
            view.addObject("errors", result);
            return view;
        }

        log.debug("Saving application-specific properties");
        appProperties = this.webApi.saveAppProperties(appProperties);
        String msg = "Saved application properties";
        log.info(msg);

        WebApiService.setSystemProperties(appProperties);

        ModelAndView modelAndView = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
        modelAndView.addObject(CONFIG_MODEL_ATTR, getWebApiProperties());
        modelAndView.addObject(APPPROPERTIES_MODEL_ATTR, getAppProperties());
        modelAndView.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
        modelAndView.addObject("remotes", getRemotes());
        modelAndView.addObject("msg", msg);
        return modelAndView;
    }

    @RequestMapping(value = "/" + CONFIG_MODEL_ATTR, method = RequestMethod.POST)
    public ModelAndView handleConfigurationSubmission(@Valid @ModelAttribute(CONFIG_MODEL_ATTR) WebApiProperties props,
                                                      BindingResult result) throws Exception {
        if (result.hasErrors()) {
            log.info("Has Errors: " + result);
            ModelAndView view = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
            view.addObject(CONFIG_MODEL_ATTR, props);
            view.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
            view.addObject(APPPROPERTIES_MODEL_ATTR, new AppProperties());
            view.addObject("errors", result);
            return view;
        }

        log.debug("Saving properties");
        props = this.webApi.saveProperties(props);
        String msg = "Saved properties";
        log.debug(msg);

        WebApiService.setSystemProperties(props);
        log.info("Set saved properties on the system");

        ModelAndView modelAndView = templateFactory.createMasterView(CONFIGURATION_TEMPLATE_NAME, null);
        modelAndView.addObject(CONFIG_MODEL_ATTR, props);
        modelAndView.addObject(REMOTE_MODEL_ATTR, new WebApiRemote());
        modelAndView.addObject(APPPROPERTIES_MODEL_ATTR, new AppProperties());
        modelAndView.addObject("msg", msg);
        return modelAndView;
    }

    @RequestMapping(value = "/request-start", method = RequestMethod.POST)
    public ModelAndView handleStartSubmission() throws Exception {
        String errorMsg = null;
        try {
            start();
        } catch (Exception e) {
            errorMsg = String.format("WebAPI was not able to start up successfully, please check your configuration. (%s)",
                e.getMessage());
            log.error(errorMsg, e);
        }
        if (errorMsg != null) {
            return handleConfigurationRequest(errorMsg);
        } else {
            return mainController.handleIndexRequest();
        }

    }

    @RequestMapping(value = "/stop", method = RequestMethod.POST)
    public ResponseEntity stop() throws Exception {
        this.webApi.stop();
        return new ResponseEntity<String>("WebApi stopped", HttpStatus.OK);
    }

    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public ResponseEntity start() throws Exception {

        this.webApi.start();
        return new ResponseEntity<String>("WebApi started", HttpStatus.OK);
    }

    private boolean isDuplicate(WebApiRemote remote, Iterable<WebApiRemote> remotes) {
        for (WebApiRemote r : remotes) {
            if (remote.getName().equalsIgnoreCase(r.getName())) {
                return true;
            }
        }
        return false;
    }
    /*    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleWebApiException() {
        return "meters/notfound";
    }*/
}


text:
require 'bio-ucsc'
describe "Bio::Ucsc::Hg18::Fox2ClipClusters" do

  describe "#find_by_interval" do
    context "given range chr1:1-1,000,000" do
      it 'returns (r.chrom == "chr1")' do
        Bio::Ucsc::Hg18::DBConnection.default
        Bio::Ucsc::Hg18::DBConnection.connect
        i = Bio::GenomicInterval.parse("chr1:1-1,000,000")
        r = Bio::Ucsc::Hg18::Fox2ClipClusters.find_by_interval(i)
        r.chrom.should == "chr1"
      end
    end
  end

end


text:
MEDUSA_BEGIN;

class RenderStateSet:public INonCopyable
{
public:
	RenderStateSet();
	virtual ~RenderStateSet(void);

	Event<void(IRenderState&)> OnStateChanged;
	Event<void(IRenderState&)> OnStateAdded;
	Event<void(RenderStateType)> OnStateRemoved;

public:
	void Apply()const;
	void Restore()const;

	bool Equals(const RenderStateSet& states)const;
public:
	Share<IRenderState> GetState(RenderStateType type)const;
	Share<IRenderState> AllocState(RenderStateType type);
	Share<IRenderState> RemoveState(RenderStateType type);

	template<typename T>
	Share<T> GetState()const
	{
		return GetState(T::GetTypeIdStatic()).CastPtr<T>();
	}

	template<typename T>
	Share<T> AllocState()
	{
		return AllocState(T::GetTypeIdStatic()).CastPtr<T>();
	}

	template<typename T>
	Share<T> RemoveState()
	{
		return RemoveState(T::GetTypeIdStatic()).CastPtr<T>();
	}
public:

	void UpdateFromParent(const RenderStateSet& selfRenderState, const RenderStateSet& parentRenderState, const Matrix4& selfWorldMatrix, RenderStateType flag);
	void UpdateFromSelf(const RenderStateSet& selfRenderState, const Matrix4& selfWorldMatrix, RenderStateType flag);
public:
	//blend
	bool IsBlendEnabled()const;
	void EnableBlend(bool val);
	void SetBlendFunc(GraphicsBlendSrcFunc srcFunc, GraphicsBlendDestFunc destFunc);
	Share<BlendRenderState> RemoveBlend();

	//scissor
	bool HasScissorBox()const;
	bool IsScissorEnabled()const;
	void SetScissorBox(const Rect2F& val);
	void EnableScissor(bool val);
	Share<ScissorRenderState> RemoveScissor();

	const Rect2F* TryGetScissorBox() const;
	const Rect2F& GetScissorBoxOrEmpty() const;

	//rasterizer

	//shader uniform
	ShaderUniformValue* FindOrCreateUniform(StringRef name);
protected:
	void OnStateChangedEvent(IRenderState& state);
protected:
	Array<Share<IRenderState>, (uint32)RenderStateType::Count> mItems;

};

MEDUSA_END;