text:
Contributing to pandoc-citeproc
===============================

Have a question?
----------------

Ask on [pandoc-discuss].

Found a bug?
------------

Bug reports are welcome!  Please report all bugs on
pandoc-citeproc's [issue tracker].

Before you submit a bug report, search the [open issues] *and* [closed issues]
to make sure the issue hasn't come up before. Also, check the
[pandoc(1)] man page and the [Citations section from the pandoc
User's Guide] for anything relevant.

Make sure you can reproduce the bug with the latest released
version of pandoc and pandoc-citeproc (or, even better, the
development version).

Your report should give detailed, *reproducible* instructions, including

  * the pandoc version (check using `pandoc --version`)
  * the pandoc-citeproc version (check using `pandoc-citeproc --version`)
  * the exact command line used
  * the exact input used
  * the output received
  * the output you expected instead

A small test case (just a few lines) is ideal.  If your input is large,
try to whittle it down to a *minimum working example*.

For an example of an ideal bug report, see
[#267](https://github.com/jgm/pandoc-citeproc/issues/267).

Patches and pull requests
-------------------------

Patches and pull requests are welcome.  If your proposed change might
be controversial, it is a good idea to discuss it first on [pandoc-discuss].

Please follow these guidelines:

1.  Each patch (commit) should make a single logical change (fix a bug, add
    a feature, clean up some code, add documentation).  Everything
    related to that change should be included (including tests and
    documentation), and nothing unrelated should be included.

2.  The first line of the commit message should be a short description
    of the whole commit (ideally <= 50 characters).  Then there should
    be a blank line, followed by a more detailed description of the
    change.

3.  Follow the stylistic conventions you find in the existing
    code.  Use spaces, not tabs, and wrap code to 80 columns.
    Always include type signatures for top-level functions.

4.  Your code should compile without warnings (`-Wall` clean).

5.  Run the tests to make sure your code does not introduce new bugs.
    (See below under [Tests](#tests).)  All tests should pass.

6.  You should add a regression test for the bug you are fixing.  (See
    below under [Tests](#tests).)

7.  If you are adding a new feature, include updates to the
    markdown source for the man page [pandoc-citeproc(1)].

8.  All code must be released under the general license
    governing pandoc-citeproc.

9.  It is better not to introduce new dependencies.  Dependencies on
    external C libraries should especially be avoided.

10. We aim for compatibility with ghc versions from 7.10.3 to the
    latest release.

Tests
-----

Tests can be run as follows:

    cabal install --only-dependencies --enable-tests
    cabal configure --enable-tests
    cabal build
    cabal test

or, if you're using [stack],

    stack setup
    stack test

The test program is `tests/test-pandoc-citeproc.hs`.

The easiest way to create a test is to make a small markdown
file that includes the needed references in metadata, and that
tests the issue. In the case of issue
[#267](https://github.com/jgm/pandoc-citeproc/issues/267) this
would be

```
Foo [@k].

# References {-}

---
csl: tests/journal-of-common-market-studies.csl
references:
- id: k
  type: article-journal
  author:
  - family: Koshland
    given: D. E.
  issued:
  - year: '1988'
  title: Random samples
  container-title: Science
  page: '1261'
  volume: '240'
  issue: '4857'
  language: en-US
```

Save this as `issue267.md`.  Since `tests` doesn't currently
contain `journal-of-common-market-studies.csl`, you'd need to
add this file and commit it to the repository.

Then convert the markdown file to native:

    pandoc issue267.md -s -o tests/issue267.in.native

Then run pandoc-citeproc on this this to generated the "expected" result:

    pandoc tests/issue267.in.native -s -F pandoc-citeproc -o tests/issue267.expected.native

Check the resulting file carefully for correctness. (You can
convert it to HTML using pandoc to make this easier.) If all is
well, add `tests/issue267.*.native` to the repository.

You may wish to use the testing utility to streamline all this.

    ./mktest.sh -h

    # to generate .in.native and .expected.native, and then open an HTML preview
    ./mktest.sh issue267.md -gpo

[pandoc-discuss]: http://groups.google.com/group/pandoc-discuss
[pandoc-citeproc(1)]: https://github.com/jgm/pandoc-citeproc/blob/master/man/pandoc-citeproc.1.md
[issue tracker]: https://github.com/jgm/pandoc-citeproc/issues
[open issues]: https://github.com/jgm/pandoc-citeproc/issues
[closed issues]: https://github.com/jgm/pandoc-citeproc/issues?q=is%3Aissue+is%3Aclosed
[Citations section from the pandoc User's Guide]: https://pandoc.org/MANUAL.html#citations


text:
package index

import (
	"bytes"

	"github.com/asdine/storm/internal"
	"github.com/boltdb/bolt"
)

// NewListIndex loads a ListIndex
func NewListIndex(parent *bolt.Bucket, indexName []byte) (*ListIndex, error) {
	var err error
	b := parent.Bucket(indexName)
	if b == nil {
		if !parent.Writable() {
			return nil, ErrNotFound
		}
		b, err = parent.CreateBucket(indexName)
		if err != nil {
			return nil, err
		}
	}

	ids, err := NewUniqueIndex(b, []byte("storm__ids"))
	if err != nil {
		return nil, err
	}

	return &ListIndex{
		IndexBucket: b,
		Parent:      parent,
		IDs:         ids,
	}, nil
}

// ListIndex is an index that references values and the corresponding IDs.
type ListIndex struct {
	Parent      *bolt.Bucket
	IndexBucket *bolt.Bucket
	IDs         *UniqueIndex
}

// Add a value to the list index
func (idx *ListIndex) Add(value []byte, targetID []byte) error {
	if value == nil || len(value) == 0 {
		return ErrNilParam
	}
	if targetID == nil || len(targetID) == 0 {
		return ErrNilParam
	}

	oldValue := idx.IDs.Get(targetID)
	if oldValue != nil {
		uni, err := NewUniqueIndex(idx.IndexBucket, oldValue)
		if err != nil {
			return err
		}

		err = uni.Remove(targetID)
		if err != nil {
			return err
		}

		err = idx.IDs.Remove(targetID)
		if err != nil {
			return err
		}
	}

	uni, err := NewUniqueIndex(idx.IndexBucket, value)
	if err != nil {
		return err
	}

	err = uni.Add(targetID, targetID)
	if err != nil {
		return err
	}

	return idx.IDs.Add(targetID, value)
}

// Remove a value from the unique index
func (idx *ListIndex) Remove(value []byte) error {
	err := idx.IDs.RemoveID(value)
	if err != nil {
		return err
	}
	return idx.IndexBucket.DeleteBucket(value)
}

// RemoveID removes an ID from the list index
func (idx *ListIndex) RemoveID(targetID []byte) error {
	c := idx.IndexBucket.Cursor()
	var emptyBuckets [][]byte

	for bucketName, val := c.First(); bucketName != nil; bucketName, val = c.Next() {
		if val != nil || bytes.Equal(bucketName, []byte("storm__ids")) {
			continue
		}

		uni, err := NewUniqueIndex(idx.IndexBucket, bucketName)
		if err != nil {
			return err
		}

		err = uni.Remove(targetID)
		if err != nil {
			return err
		}

		cd := uni.IndexBucket.Cursor()
		empty := true
		for k, _ := cd.First(); k != nil; k, _ = cd.Next() {
			empty = false
			break
		}

		if empty {
			emptyBuckets = append(emptyBuckets, bucketName)
		}
	}

	for _, bucketName := range emptyBuckets {
		err := idx.IndexBucket.DeleteBucket(bucketName)
		if err != nil {
			return err
		}
	}

	return idx.IDs.Remove(targetID)
}

// Get the first ID corresponding to the given value
func (idx *ListIndex) Get(value []byte) []byte {
	uni, err := NewUniqueIndex(idx.IndexBucket, value)
	if err != nil {
		return nil
	}
	return uni.first()
}

// All the IDs corresponding to the given value
func (idx *ListIndex) All(value []byte, opts *Options) ([][]byte, error) {
	uni, err := NewUniqueIndex(idx.IndexBucket, value)
	if err != nil {
		return nil, err
	}
	return uni.AllRecords(opts)
}

// AllRecords returns all the IDs of this index
func (idx *ListIndex) AllRecords(opts *Options) ([][]byte, error) {
	var list [][]byte

	c := internal.Cursor{C: idx.IndexBucket.Cursor(), Reverse: opts != nil && opts.Reverse}

	for bucketName, val := c.First(); bucketName != nil; bucketName, val = c.Next() {
		if val != nil || bytes.Equal(bucketName, []byte("storm__ids")) {
			continue
		}

		uni, err := NewUniqueIndex(idx.IndexBucket, bucketName)
		if err != nil {
			return nil, err
		}

		all, err := uni.AllRecords(opts)
		if err != nil {
			return nil, err
		}
		list = append(list, all...)
	}

	return list, nil
}

// Range returns the ids corresponding to the given range of values
func (idx *ListIndex) Range(min []byte, max []byte, opts *Options) ([][]byte, error) {
	var list [][]byte

	c := internal.RangeCursor{
		C:       idx.IndexBucket.Cursor(),
		Reverse: opts != nil && opts.Reverse,
		Min:     min,
		Max:     max,
	}

	for bucketName, val := c.First(); c.Continue(bucketName); bucketName, val = c.Next() {
		if val != nil || bytes.Equal(bucketName, []byte("storm__ids")) {
			continue
		}

		uni, err := NewUniqueIndex(idx.IndexBucket, bucketName)
		if err != nil {
			return nil, err
		}

		all, err := uni.AllRecords(opts)
		if err != nil {
			return nil, err
		}

		list = append(list, all...)
	}

	return list, nil
}

redpajama_set_name: RedPajamaGithub


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

<title>Uses of Class javax.swing.event.PopupMenuEvent (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Class
javax.swing.event.PopupMenuEvent

Packages that use PopupMenuEvent

Package
Description

javax.swing.event

Provides for events fired by Swing components.

Uses of PopupMenuEvent in javax.swing.event

Methods in javax.swing.event with parameters of type PopupMenuEvent

Modifier and Type
Method and Description

void
PopupMenuListener.popupMenuCanceled(PopupMenuEvent e)

This method is called when the popup menu is canceled

void
PopupMenuListener.popupMenuWillBecomeInvisible(PopupMenuEvent e)

This method is called before the popup menu becomes invisible
 Note that a JPopupMenu can become invisible any time

void
PopupMenuListener.popupMenuWillBecomeVisible(PopupMenuEvent e)

This method is called before the popup menu becomes visible

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
path=~/out/real/gowinda/
fname=cands.final.txt
fname=reg.txt
echo $fname
cd $path
ann=dmel.5.7.gtf
gs=goassociation.FBgn
out=$fname.tsv
log=~/gowinda.txt
java -Xmx4g -jar ~/bin/Gowinda-1.12.jar --snp-file allsnps.txt --candidate-snp-file $fname --gene-set-file $gs --annotation-file $ann \
--simulations 10000000 --min-significance 0.001 --min-genes 3 --gene-definition updownstream2000 --threads 8 --output-file $out --mode snp
#>>$log 2>>$log
#    wc -l $out


text:
import time

import paho.mqtt.client as mqtt

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileCreatedEvent
from watchdog.events import FileDeletedEvent
from watchdog.events import FileModifiedEvent

testing = True
update_period_sec = 20
morning_hour = 9
evening_hour = 17

#
# File Commanded States:
# 0 --> CLOSED
# 1 --> OPEN
# 2 --> AUTO (time of day)
#

class FileChangedHandler(FileSystemEventHandler):

    def __init__(self):
        self.filename ="door.state"
        self.state = 0

    def on_deleted(self, event):
        if isinstance(event, FileDeletedEvent):
            print("File deleted", event.src_path)
            if event.src_path == "./" + self.filename:
                self.state = 2

    def on_created(self, event):
        if isinstance(event, FileCreatedEvent):
            print("File created", event.src_path)
            if event.src_path == "./" + self.filename:
                self.state = 0

    def on_modified(self, event):
        if isinstance(event, FileModifiedEvent):
            print("File modified:", event.src_path)
            if event.src_path == "./" + self.filename:
                self.read_state()

    def read_state(self):
        try:
            with open(self.filename) as file:
                line = file.readline()
                try:
                    self.state = int(line)
                except Exception as error:
                    print("Line is not valid!")
                    print(error)
                    self.state = 0
                file.close
        except Exception as error:
            print("File could not be read!")
            print(error)
            self.state = 2

class DoorMaster(object):
    def __init__(self, mqtt_client, server):
        self.client = mqtt_client
        self.topic = "/doormaster/command"
        print("connect to ", server)
        self.client.connect(server)

    def push_state(self, state):
        print("send command:", state)
        self.client.publish(self.topic, state)

    def on_connect(self, client, userdata, flags, rc):
        print("Connected "+str(client)+" with result code "+str(rc))
        self.client.subscribe("/deckdoor/#")

    def on_message(self, client, userdata, msg):
        userdata[msg.topic](msg)

def deckdoor_state(msg):
    print("deckdoor state: "+str(bytes.decode(msg.payload)))

def deckdoor_message(msg):
    print("deckdoor message: "+bytes.decode(msg.payload))

topiclist = {
    '/deckdoor/state' : deckdoor_state,
    '/deckdoor/message' : deckdoor_message
}

mqtt_client = mqtt.Client("DoorMaster", True, topiclist)
door_master = DoorMaster(mqtt_client, "172.16.0.11")
mqtt_client.on_connect = door_master.on_connect
mqtt_client.on_message = door_master.on_message

event_handler = FileChangedHandler()

observer = Observer()
observer.schedule(event_handler, ".")
observer.start()
mqtt_client.loop_start()

time.sleep(3)
event_handler.read_state()

flip = True
last_update = time.time()

try:
    while True:
        now = time.time()
        if ( now - last_update > update_period_sec):
            last_update = now
            if event_handler.state == 2: # this is automatic mode
                if not testing: # set open or close depending the time of day
                    now = time.localtime()
                    if morning_hour <= now.tm_hour and now.tm_hour <= evening_hour:
                        door_master.push_state(1)
                    else:
                        door_master.push_state(0)
                else: # flip-flop open-closed for testing
                    if flip:
                        door_master.push_state(1)
                        flip = False
                    else:
                        door_master.push_state(0)
                        flip = True
            else: # this is override mode (file based)
                if event_handler.state == 1:
                    door_master.push_state(1)
                else:
                    door_master.push_state(0)
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
    mqtt_client.loop_stop()
observer.join()


text:
package org.elasticsearch.xpack.core.transform;

import org.elasticsearch.xcontent.ParseField;

/*
 * Utility class to hold common fields and strings for transform.
 */
public final class TransformField {

    // common parse fields
    public static final ParseField AGGREGATIONS = new ParseField("aggregations");
    public static final ParseField AGGS = new ParseField("aggs");
    public static final ParseField ID = new ParseField("id");
    public static final ParseField TRANSFORMS = new ParseField("transforms");
    public static final ParseField COUNT = new ParseField("count");
    public static final ParseField GROUP_BY = new ParseField("group_by");
    public static final ParseField TIMEOUT = new ParseField("timeout");
    public static final ParseField WAIT_FOR_COMPLETION = new ParseField("wait_for_completion");
    public static final ParseField WAIT_FOR_CHECKPOINT = new ParseField("wait_for_checkpoint");
    public static final ParseField STATS_FIELD = new ParseField("stats");
    public static final ParseField INDEX_DOC_TYPE = new ParseField("doc_type");
    public static final ParseField SOURCE = new ParseField("source");
    public static final ParseField DESCRIPTION = new ParseField("description");
    public static final ParseField VERSION = new ParseField("version");
    public static final ParseField CREATE_TIME = new ParseField("create_time");
    public static final ParseField DESTINATION = new ParseField("dest");
    public static final ParseField SETTINGS = new ParseField("settings");
    public static final ParseField METADATA = new ParseField("_meta");
    public static final ParseField FREQUENCY = new ParseField("frequency");
    public static final ParseField FORCE = new ParseField("force");
    public static final ParseField MAX_PAGE_SEARCH_SIZE = new ParseField("max_page_search_size");
    public static final ParseField DOCS_PER_SECOND = new ParseField("docs_per_second");
    public static final ParseField DATES_AS_EPOCH_MILLIS = new ParseField("dates_as_epoch_millis");
    public static final ParseField ALIGN_CHECKPOINTS = new ParseField("align_checkpoints");
    public static final ParseField USE_PIT = new ParseField("use_point_in_time");
    public static final ParseField FIELD = new ParseField("field");
    public static final ParseField SYNC = new ParseField("sync");
    public static final ParseField TIME = new ParseField("time");
    public static final ParseField DELAY = new ParseField("delay");
    // TODO: Rename to "defer_data_validation" or similar to emphasize that not all validation is deferred
    public static final ParseField DEFER_VALIDATION = new ParseField("defer_validation");
    public static final ParseField DRY_RUN = new ParseField("dry_run");
    public static final ParseField RETENTION_POLICY = new ParseField("retention_policy");
    public static final ParseField MAX_AGE = new ParseField("max_age");

    public static final ParseField ALLOW_NO_MATCH = new ParseField("allow_no_match");
    /**
     * Fields for checkpointing
     */
    // the timestamp of the checkpoint, mandatory
    public static final ParseField CHECKPOINT = new ParseField("checkpoint");
    public static final ParseField INDEXER_STATE = new ParseField("indexer_state");
    public static final ParseField POSITION = new ParseField("position");
    public static final ParseField CHECKPOINT_PROGRESS = new ParseField("checkpoint_progress");
    public static final ParseField TIMESTAMP_MILLIS = new ParseField("timestamp_millis");
    public static final ParseField TIMESTAMP = new ParseField("timestamp");
    // checkpoint for for time based sync
    // TODO: consider a lower bound for usecases where you want to transform on a window of a stream
    public static final ParseField TIME_UPPER_BOUND_MILLIS = new ParseField("time_upper_bound_millis");
    public static final ParseField TIME_UPPER_BOUND = new ParseField("time_upper_bound");

    // common strings
    public static final String TASK_NAME = "data_frame/transforms";
    public static final String REST_BASE_PATH_TRANSFORMS = "/_transform/";
    public static final String REST_BASE_PATH_TRANSFORMS_BY_ID = REST_BASE_PATH_TRANSFORMS + "{id}/";

    public static final String TRANSFORM_ID = "transform_id";

    // note: this is used to match tasks
    public static final String PERSISTENT_TASK_DESCRIPTION_PREFIX = "data_frame_";

    // strings for meta information
    public static final String META_FIELDNAME = "_transform";
    public static final String CREATION_DATE_MILLIS = "creation_date_in_millis";
    public static final String CREATED = "created";
    public static final String CREATED_BY = "created_by";
    public static final String TRANSFORM = "transform";
    public static final String TRANSFORM_SIGNATURE = "transform";

    /**
     * Parameter to indicate whether we are serialising to X Content for internal storage. Default the field is invisible (e.g. for get
     * API's)
     */
    public static final String FOR_INTERNAL_STORAGE = "for_internal_storage";
    public static final String EXCLUDE_GENERATED = "exclude_generated";

    // internal document id
    public static String DOCUMENT_ID_FIELD = "_id";

    private TransformField() {}
}


text:
<resources>

    <attr format="reference" name="cardStyle"/>
    <!-- Base application themes. -->
    <!-- Yellow over black -->
    <style name="AppTheme1" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/colorYellow</item>
        <item name="android:listViewStyle">@style/YellowBlackListViewStyle</item>
        <item name="cardStyle">@style/CardViewStyle1</item>
    </style>
    <style name="CardViewStyle1" parent="CardView">
        <item name="cardBackgroundColor">@color/colorBlack</item>
    </style>
    <style name="YellowBlackListViewStyle">
        <item name="android:background">@color/colorBlack</item>
        <item name="android:textColor">@color/colorYellow</item>
        <item name="android:divider">@color/colorYellow</item>
        <item name="android:dividerHeight">1dp</item>
        <item name="android:drawSelectorOnTop">false</item>
    </style>
    <style name="AppTheme1.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme1.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme1.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <!-- Red over green -->
    <style name="AppTheme2" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/colorRed</item>
        <item name="android:listViewStyle">@style/GreenRedListViewStyle</item>
        <item name="cardStyle">@style/CardViewStyle2</item>
    </style>
    <style name="CardViewStyle2" parent="CardView">
        <item name="cardBackgroundColor">@color/colorGreen</item>
    </style>
    <style name="GreenRedListViewStyle">
        <item name="android:background">@color/colorGreen</item>
        <item name="android:textColor">@color/colorRed</item>
        <item name="android:divider">@color/colorRed</item>
        <item name="android:dividerHeight">1dp</item>
        <item name="android:drawSelectorOnTop">false</item>
    </style>
    <style name="AppTheme2.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme2.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme2.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <!-- White over purple -->
    <style name="AppTheme3" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textColor">@color/colorWhite</item>
        <item name="android:listViewStyle">@style/PurpleWhiteListViewStyle</item>
        <item name="cardStyle">@style/CardViewStyle3</item>
    </style>
    <style name="CardViewStyle3" parent="CardView">
        <item name="cardBackgroundColor">@color/colorPurple</item>
    </style>
    <style name="PurpleWhiteListViewStyle">
        <item name="android:background">@color/colorPurple</item>
        <item name="android:textColor">@color/colorWhite</item>
        <item name="android:divider">@color/colorWhite</item>
        <item name="android:dividerHeight">1dp</item>
        <item name="android:drawSelectorOnTop">false</item>
    </style>
    <style name="AppTheme3.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme3.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme3.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


text:
package org.apache.causeway.viewer.restfulobjects.applib.domainobjects;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * @since 1.x {@index}
 */
public class ObjectPropertyRepresentation extends AbstractObjectMemberRepresentation {

    public ObjectPropertyRepresentation(final JsonNode jsonNode) {
        super(jsonNode);
    }
}


text:
//
// Reaktion - An audio reactive animation toolkit for Unity.
//
// Copyright (C) 2013, 2014 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using UnityEngine;
using System.Collections;

#pragma warning disable 618

namespace Reaktion {

[AddComponentMenu("Reaktion/Gear/Particle System Gear")]
public class ParticleSystemGear : MonoBehaviour
{
    public ReaktorLink reaktor;

    public Trigger burst;
    public int burstNumber = 10;

    public Modifier emissionRate = Modifier.Linear(0, 20);

    public Modifier size = Modifier.Linear(0.5f, 1.5f);

    ParticleSystem.Particle[] tempArray;

    void Awake()
    {
        reaktor.Initialize(this);
    }

    void Update()
    {
        if (burst.Update(reaktor.Output))
        {
            GetComponent<ParticleSystem>().Emit(burstNumber);
            GetComponent<ParticleSystem>().Play();
        }

        if (emissionRate.enabled)
            GetComponent<ParticleSystem>().emissionRate = emissionRate.Evaluate(reaktor.Output);

        if (size.enabled)
            ResizeParticles(size.Evaluate(reaktor.Output));
    }

    void ResizeParticles(float newSize)
    {
        if (tempArray == null || tempArray.Length != GetComponent<ParticleSystem>().maxParticles)
            tempArray = new ParticleSystem.Particle[GetComponent<ParticleSystem>().maxParticles];

        var count = GetComponent<ParticleSystem>().GetParticles(tempArray);

        for (var i = 0; i < count; i++)
            tempArray[i].size = newSize;

        GetComponent<ParticleSystem>().SetParticles(tempArray, count);
    }
}

} // namespace Reaktion


text:
package com.onplan.adviser;

import com.onplan.domain.transitory.PriceTick;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.onplan.util.MorePreconditions.checkNotNullOrEmpty;

/**
 * Basic class for adviser events.
 */
public abstract class AbstractAdviserEvent implements AdviserEvent {
  protected final String adviserId;
  protected final PriceTick priceTick;
  protected final long createdOn;

  public String getAdviserId() {
    return adviserId;
  }

  @Override
  public PriceTick getPriceTick() {
    return priceTick;
  }

  @Override
  public long getCreatedOn() {
    return createdOn;
  }

  public AbstractAdviserEvent(String adviserId, PriceTick priceTick, long createdOn) {
    this.adviserId = checkNotNullOrEmpty(adviserId);
    this.priceTick = checkNotNull(priceTick);
    checkArgument(createdOn > 0, "Expected a positive value for createdOn.");
    this.createdOn = createdOn;
  }
}


text:
<?php
namespace backend\views\myasset;

use yii\web\AssetBundle;

class ThemeAssetMoreUpload extends AssetBundle
{

	public $sourcePath = '@backend/views/static';
	public $css = [
		//'css/jedate.css'
		'css/zyUpload.css'
	];

	public $js = [
		'js/uP_demo.js',
		'js/zyFile.js',
		'js/zyUpload.js'
	];

	public $depends = [
		'backend\views\myasset\PublicAsset',
	];
}


text:
/
#endregion

using System;
using System.Collections.Generic;
using System.Globalization;
using GSF.Units;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GSF.Core.Tests
{

    ///
    ///This is a test class for MassTest and is intended
    ///to contain all MassTest Unit Tests
    ///
    [TestClass]
    public class MassTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for Mass Constructor
        ///
        [TestMethod]
        public void MassConstructorTest()
        {
            List<Double> values = new List<Double>();

            //Initialization
            values.Add(0);

            foreach (Double value in values)
            {
                Mass target = new Mass(value);
                Assert.IsInstanceOfType(target, typeof(Mass));
                Assert.IsNotNull(target);
            }
            values.Clear();

        }

        ///
        /// A test for CompareTo
        /// Compares this instance to a specified <see cref="double"/> and returns an indication of their
        /// relative values.
        ///
        /// <param name="value">A <see cref="double"/> to compare.</param>
        /// <returns>
        /// A signed number indicating the relative values of this instance and value. Returns less than zero
        /// if this instance is less than value, zero if this instance is equal to value, or greater than zero
        /// if this instance is greater than value.
        /// </returns>
        [TestMethod]
        public void CompareToDoubleTest()
        {
            Mass target = new Mass(10F);
            double value = 10F;
            int expected = 0;
            int actual;
            actual = target.CompareTo(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for CompareTo
        /// Returns a value indicating whether this instance is equal to a specified <see cref="Mass"/> value.
        ///
        /// <param name="obj">A <see cref="Mass"/> value to compare to this instance.</param>
        /// <returns>
        /// True if obj has the same value as this instance; otherwise, False.
        /// </returns>
        [TestMethod]
        public void CompareToMassTest()
        {
            Mass target = new Mass(10F);
            Mass value = new Mass(10F);
            int expected = 0;
            int actual;
            actual = target.CompareTo(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for CompareTo
        /// Compares this instance to a specified object and returns an indication of their relative values.
        ///
        /// <param name="value">An object to compare, or null.</param>
        /// <returns>
        /// A signed number indicating the relative values of this instance and value. Returns less than zero
        /// if this instance is less than value, zero if this instance is equal to value, or greater than zero
        /// if this instance is greater than value.
        /// </returns>
        /// <exception cref="ArgumentException">value is not a <see cref="Double"/> or <see cref="Mass"/>.</exception>
        [TestMethod]
        public void CompareToTest2()
        {
            Mass target = new Mass(10F);
            object value = new Mass(10F);
            int expected = 0;
            int actual;
            actual = target.CompareTo(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Equals
        /// Returns a value indicating whether this instance is equal to a specified <see cref="Mass"/> value.
        ///
        /// <param name="obj">A <see cref="Mass"/> value to compare to this instance.</param>
        /// <returns>
        /// True if obj has the same value as this instance; otherwise, False.
        /// </returns>
        [TestMethod]
        public void EqualsTest()
        {
            Mass target = new Mass(10F);
            Mass obj = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = target.Equals(obj);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Equals
        /// Returns a value indicating whether this instance is equal to a specified <see cref="Double"/> value.
        ///
        /// <param name="obj">A <see cref="Double"/> value to compare to this instance.</param>
        /// <returns>
        /// True if obj has the same value as this instance; otherwise, False.
        /// </returns>
        [TestMethod]
        public void EqualsDoubleTest()
        {
            Mass target = new Mass(10F);
            double obj = 10F;
            bool expected = true;
            bool actual;
            actual = target.Equals(obj);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Equals
        /// Returns a value indicating whether this instance is equal to a specified <see cref="Double"/> value.
        ///
        /// <param name="obj">A <see cref="Double"/> value to compare to this instance.</param>
        /// <returns>
        /// True if obj has the same value as this instance; otherwise, False.
        /// </returns>
        [TestMethod]
        public void EqualsObjectTest()
        {
            Mass target = new Mass(10F);
            object obj = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = target.Equals(obj);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for FromLongTons
        /// Creates a new <see cref="Mass"/>value from the specified <paramref name="value"/> in long tons.
        ///
        /// <param name="value">New <see cref="Mass"/> value in long tons.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in long tons.</returns>
        [TestMethod]
        public void FromLongTonsTest()
        {
            double value = 10F;
            Mass expected = new Mass(10160.469088);
            Mass actual;
            actual = Mass.FromLongTons(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for FromMetricPounds
        /// Creates a new <see cref="Mass"/> value from the specified <paramref name="value"/> in metric pounds.
        ///
        /// <param name="value">New <see cref="Mass"/> value in metric pounds.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in metric pounds.</returns>
        [TestMethod]
        public void FromMetricPoundsTest()
        {
            double value = 10F;
            Mass expected = new Mass(5F);
            Mass actual;
            actual = Mass.FromMetricPounds(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for FromMetricTons
        /// Creates a new <see cref="Mass"/> value from the specified <paramref name="value"/> in metric tons.
        ///
        /// <param name="value">New <see cref="Mass"/> value in metric tons.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in metric tons.</returns>
        [TestMethod]
        public void FromMetricTonsTest()
        {
            double value = 10F;
            Mass expected = new Mass(10000);
            Mass actual;
            actual = Mass.FromMetricTons(value);
            Assert.AreEqual(expected, actual);

        }

        ///
        /// A test for FromOunces
        /// Creates a new <see cref="Mass"/> value from the specified <paramref name="value"/> in ounces (avoirdupois).
        ///
        /// <param name="value">New <see cref="Mass"/> value in ounces.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in ounces.</returns>
        [TestMethod]
        public void FromOuncesTest()
        {
            double value = 10F;
            Mass expected = new Mass(0.28349523125);
            Mass actual;
            actual = Mass.FromOunces(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for FromPounds
        /// Creates a new <see cref="Mass"/> value from the specified <paramref name="value"/> in pounds (avoirdupois).
        ///
        /// <param name="value">New <see cref="Mass"/> value in pounds.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in pounds.</returns>
        [TestMethod]
        public void FromPoundsTest()
        {
            double value = 10F;
            Mass expected = new Mass(4.5359237);
            Mass actual;
            actual = Mass.FromPounds(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for FromTons
        /// Creates a new <see cref="Mass"/> value from the specified <paramref name="value"/> in short tons.
        ///
        /// <param name="value">New <see cref="Mass"/> value in short tons.</param>
        /// <returns>New <see cref="Mass"/> object from the specified <paramref name="value"/> in short tons.</returns>
        [TestMethod]
        public void FromTonsTest()
        {
            double value = 10F;
            Mass expected = new Mass(9071.8474);
            Mass actual;
            actual = Mass.FromTons(value);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for GetHashCode
        /// Returns the hash code for this instance.
        ///
        /// <returns>
        /// A 32-bit signed integer hash code.
        /// </returns>
        [TestMethod]
        public void GetHashCodeTest()
        {
            Mass target = new Mass(10F);
            int expected = 1076101120;
            int actual;
            actual = target.GetHashCode();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for GetTypeCode
        /// Returns the <see cref="TypeCode"/> for value type <see cref="Double"/>.
        ///
        /// <returns>The enumerated constant, <see cref="TypeCode.Double"/>.</returns>
        [TestMethod]
        public void GetTypeCodeTest()
        {
            Mass target = new Mass(10F);
            TypeCode expected = new TypeCode();
            expected = Type.GetTypeCode(typeof(Double));
            TypeCode actual;
            actual = target.GetTypeCode();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Parse
        /// Converts the string representation of a number to its <see cref="Mass"/> equivalent.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <returns>
        /// A <see cref="Mass"/> equivalent to the number contained in s.
        /// </returns>
        /// <exception cref="ArgumentNullException">s is null.</exception>
        /// <exception cref="OverflowException">
        /// s represents a number less than <see cref="Mass.MinValue"/> or greater than <see cref="Mass.MaxValue"/>.
        /// </exception>
        /// <exception cref="FormatException">s is not in the correct format.</exception>
        [TestMethod]
        public void ParseTest()
        {
            double value = 10F;
            string s = value.ToString();
            Mass expected = new Mass(value);
            Mass actual;
            actual = Mass.Parse(s);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Parse
        /// Converts the string representation of a number in a specified style to its <see cref="Mass"/> equivalent.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <param name="style">
        /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s.
        /// </param>
        /// <returns>
        /// A <see cref="Mass"/> equivalent to the number contained in s.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of
        /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values.
        /// </exception>
        /// <exception cref="ArgumentNullException">s is null.</exception>
        /// <exception cref="OverflowException">
        /// s represents a number less than <see cref="Mass.MinValue"/> or greater than <see cref="Mass.MaxValue"/>.
        /// </exception>
        /// <exception cref="FormatException">s is not in a format compliant with style.</exception>
        [TestMethod]
        public void ParseStyleTest()
        {
            double value = 10F;
            string s = value.ToString();
            NumberStyles style = new NumberStyles();
            Mass expected = new Mass(value);
            Mass actual;
            actual = Mass.Parse(s, style);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Parse
        /// Converts the string representation of a number in a specified culture-specific format to its <see cref="Mass"/> equivalent.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <param name="provider">
        /// A <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information about s.
        /// </param>
        /// <returns>
        /// A <see cref="Mass"/> equivalent to the number contained in s.
        /// </returns>
        /// <exception cref="ArgumentNullException">s is null.</exception>
        /// <exception cref="OverflowException">
        /// s represents a number less than <see cref="Mass.MinValue"/> or greater than <see cref="Mass.MaxValue"/>.
        /// </exception>
        /// <exception cref="FormatException">s is not in the correct format.</exception>
        [TestMethod]
        public void ParseProviderTest()
        {
            double value = 10F;
            string s = value.ToString();
            IFormatProvider provider = null;
            Mass expected = new Mass(value);
            Mass actual;
            actual = Mass.Parse(s, provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for Parse
        /// Converts the string representation of a number in a specified style and culture-specific format to its <see cref="Mass"/> equivalent.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <param name="style">
        /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s.
        /// </param>
        /// <param name="provider">
        /// A <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information about s.
        /// </param>
        /// <returns>
        /// A <see cref="Mass"/> equivalent to the number contained in s.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of
        /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values.
        /// </exception>
        /// <exception cref="ArgumentNullException">s is null.</exception>
        /// <exception cref="OverflowException">
        /// s represents a number less than <see cref="Mass.MinValue"/> or greater than <see cref="Mass.MaxValue"/>.
        /// </exception>
        /// <exception cref="FormatException">s is not in a format compliant with style.</exception>
        [TestMethod]
        public void ParseStyleProviderTest()
        {
            double value = 10F;
            string s = value.ToString();
            NumberStyles style = new NumberStyles();
            IFormatProvider provider = null;
            Mass expected = new Mass(value);
            Mass actual;
            actual = Mass.Parse(s, style, provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToBoolean
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToBooleanTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            bool expected = false;
            bool actual;
            actual = target.ToBoolean(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToByte
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToByteTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            byte expected = 10;
            byte actual;
            actual = target.ToByte(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToChar
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToCharTest()
        {
            /*
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            char expected = '\0';
            char actual;
            actual = target.ToChar(provider);
            Assert.AreEqual(expected, actual);
            */
            Assert.Inconclusive("Invalid cast from 'Double' to 'Char'.");
        }

        ///
        ///A test for System.IConvertible.ToDateTime
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToDateTimeTest()
        {
            /*
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            DateTime expected = new DateTime();
            DateTime actual;
            actual = target.ToDateTime(provider);
            Assert.AreEqual(expected, actual);
            */
            Assert.Inconclusive("Invalid cast from 'Double' to 'DateTime'.");
        }

        ///
        ///A test for System.IConvertible.ToDecimal
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToDecimalTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            Decimal expected = new Decimal(10F);
            Decimal actual;
            actual = target.ToDecimal(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToDouble
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToDoubleTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            double expected = 10F;
            double actual;
            actual = target.ToDouble(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToInt16
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToInt16Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            short expected = 10;
            short actual;
            actual = target.ToInt16(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToInt32
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToInt32Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            int expected = 10;
            int actual;
            actual = target.ToInt32(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToInt64
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToInt64Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            long expected = 10;
            long actual;
            actual = target.ToInt64(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToSByte
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToSByteTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            sbyte expected = 10;
            sbyte actual;
            actual = target.ToSByte(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToSingle
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToSingleTest()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            float expected = 10F;
            float actual;
            actual = target.ToSingle(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToType
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToTypeTest()
        {
            IConvertible target = new Mass(10F);
            Type conversionType = typeof(Double);
            IFormatProvider provider = null;
            object expected = new Mass(10F);
            object actual;
            actual = target.ToType(conversionType, provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToUInt16
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToUInt16Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            ushort expected = 10;
            ushort actual;
            actual = target.ToUInt16(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToUInt32
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToUInt32Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            uint expected = 10;
            uint actual;
            actual = target.ToUInt32(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for System.IConvertible.ToUInt64
        ///
        [TestMethod]
        [DeploymentItem("GSF.Core.dll")]
        public void ToUInt64Test()
        {
            IConvertible target = new Mass(10F);
            IFormatProvider provider = null;
            ulong expected = 10;
            ulong actual;
            actual = target.ToUInt64(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToLongTons
        /// Gets the <see cref="Mass"/> value in long tons.
        ///
        /// <returns>Value of <see cref="Mass"/> in long tons.</returns>
        [TestMethod]
        public void ToLongTonsTest()
        {
            Mass target = new Mass(10F);
            double expected = 0.0098420652761106071;
            double actual;
            actual = target.ToLongTons();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToMetricPounds
        /// Gets the <see cref="Mass"/> value in metric pounds.
        ///
        /// <returns>Value of <see cref="Mass"/> in metric pounds.</returns>
        public void ToMetricPoundsTest()
        {
            Mass target = new Mass(10F);
            double expected = 10F;
            double actual;
            actual = target.ToMetricPounds();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToMetricTons
        /// Gets the <see cref="Mass"/> value in metric tons.
        ///
        /// <returns>Value of <see cref="Mass"/> in metric tons.</returns>
        [TestMethod]
        public void ToMetricTonsTest()
        {
            Mass target = new Mass(10F);
            double expected = 0.01;
            double actual;
            actual = target.ToMetricTons();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToOunces
        /// Gets the <see cref="Mass"/> value in ounces (avoirdupois).
        ///
        /// <returns>Value of <see cref="Mass"/> in ounces.</returns>
        [TestMethod]
        public void ToOuncesTest()
        {
            Mass target = new Mass(10F);
            double expected = 352.73961949580411;
            double actual;
            actual = target.ToOunces();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToPounds
        /// Gets the <see cref="Mass"/> value in pounds (avoirdupois).
        ///
        /// <returns>Value of <see cref="Mass"/> in pounds.</returns>
        [TestMethod]
        public void ToPoundsTest()
        {
            Mass target = new Mass(10F);
            double expected = 22.046226218487757;
            double actual;
            actual = target.ToPounds();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToString
        /// Converts the numeric value of this instance to its equivalent string representation using the
        /// specified format and culture-specific format information.
        ///
        /// <param name="format">A format specification.</param>
        /// <param name="provider">
        /// A <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.
        /// </param>
        /// <returns>
        /// The string representation of the value of this instance as specified by format and provider.
        /// </returns>
        [TestMethod]
        public void ToStringFormatProviderTest()
        {
            double value = 10F;
            Mass target = new Mass(10F);
            string format = string.Empty;
            IFormatProvider provider = null;
            string expected = value.ToString();
            string actual;
            actual = target.ToString(format, provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToString
        /// Converts the numeric value of this instance to its equivalent string representation.
        ///
        /// <returns>
        /// The string representation of the value of this instance, consisting of a minus sign if
        /// the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes.
        /// </returns>
        [TestMethod]
        public void ToStringTest()
        {
            double value = 10F;
            Mass target = new Mass();
            string expected = value.ToString();
            string actual;
            actual = target.ToString();
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToString
        /// Converts the numeric value of this instance to its equivalent string representation using the
        /// specified culture-specific format information.
        ///
        /// <param name="provider">
        /// A <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.
        /// </param>
        /// <returns>
        /// The string representation of the value of this instance as specified by provider.
        /// </returns>
        [TestMethod]
        public void ToStringProviderTest()
        {
            double value = 10F;
            Mass target = new Mass(10F);
            IFormatProvider provider = null;
            string expected = value.ToString();
            string actual;
            actual = target.ToString(provider);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToString
        /// Converts the numeric value of this instance to its equivalent string representation, using
        /// the specified format.
        ///
        /// <param name="format">A format string.</param>
        /// <returns>
        /// The string representation of the value of this instance as specified by format.
        /// </returns>
        [TestMethod]
        public void ToStringFormatTest()
        {
            double value = 10F;
            Mass target = new Mass(value);
            string format = string.Empty;
            string expected = value.ToString();
            string actual;
            actual = target.ToString(format);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for ToTons
        /// Gets the <see cref="Mass"/> value in short tons.
        ///
        /// <returns>Value of <see cref="Mass"/> in short tons.</returns>
        [TestMethod]
        public void ToTonsTest()
        {
            Mass target = new Mass(10F);
            double expected = 0.011023113109243879;
            double actual;
            actual = target.ToTons();
            Assert.AreEqual(expected, actual);
        }
        ///
        /// A test for TryParse
        /// Converts the string representation of a number to its <see cref="Mass"/> equivalent. A return value
        /// indicates whether the conversion succeeded or failed.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <param name="result">
        /// When this method returns, contains the <see cref="Mass"/> value equivalent to the number contained in s,
        /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s paraampere is null,
        /// is not of the correct format, or represents a number less than <see cref="Mass.MinValue"/> or greater than <see cref="Mass.MaxValue"/>.
        /// This paraampere is passed uninitialized.
        /// </param>
        /// <returns>true if s was converted successfully; otherwise, false.</returns>
        [TestMethod]
        public void TryParseResultTest()
        {
            double value = 10F;
            string s = value.ToString();
            Mass result = new Mass(value);
            Mass resultExpected = new Mass(value);
            bool expected = true;
            bool actual;
            actual = Mass.TryParse(s, out result);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }

        ///
        /// A test for TryParse
        /// A test for op_Addition
        /// Converts the string representation of a number in a specified style and culture-specific format to its
        /// <see cref="Mass"/> equivalent. A return value indicates whether the conversion succeeded or failed.
        ///
        /// <param name="s">A string containing a number to convert.</param>
        /// <param name="style">
        /// A bitwise combination of System.Globalization.NumberStyles values that indicates the permitted format of s.
        /// </param>
        /// <param name="result">
        /// When this method returns, contains the <see cref="Mass"/> value equivalent to the number contained in s,
        /// if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s paraampere is null,
        /// is not in a format compliant with style, or represents a number less than <see cref="Mass.MinValue"/> or
        /// greater than <see cref="Mass.MaxValue"/>. This paraampere is passed uninitialized.
        /// </param>
        /// <param name="provider">
        /// A <see cref="System.IFormatProvider"/> object that supplies culture-specific formatting information about s.
        /// </param>
        /// <returns>true if s was converted successfully; otherwise, false.</returns>
        /// <exception cref="ArgumentException">
        /// style is not a System.Globalization.NumberStyles value. -or- style is not a combination of
        /// System.Globalization.NumberStyles.AllowHexSpecifier and System.Globalization.NumberStyles.HexNumber values.
        /// </exception>
        [TestMethod]
        public void TryParseStyleProviderTest()
        {
            double value = 10F;
            string s = value.ToString();
            NumberStyles style = new NumberStyles();
            IFormatProvider provider = null;
            Mass result = new Mass(value);
            Mass resultExpected = new Mass(value);
            bool expected = true;
            bool actual;
            actual = Mass.TryParse(s, style, provider, out result);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void op_AdditionTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            Mass expected = new Mass(20F);
            Mass actual;
            actual = (value1 + value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Division
        ///
        [TestMethod]
        public void op_DivisionTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            Mass expected = new Mass(1 / 2F);
            Mass actual;
            actual = (value1 / value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Equality
        ///
        [TestMethod]
        public void op_EqualityTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = (value1 == value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Exponent
        ///
        [TestMethod]
        public void op_ExponentTest()
        {
            Mass value1 = new Mass(2F);
            Mass value2 = new Mass(3F);
            double expected = 8F;
            double actual;
            actual = Mass.op_Exponent(value1, value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_GreaterThan
        ///
        [TestMethod]
        public void op_GreaterThanTest()
        {
            Mass value1 = new Mass(11F);
            Mass value2 = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = (value1 > value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_GreaterThanOrEqual
        ///
        [TestMethod]
        public void op_GreaterThanOrEqualTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = (value1 >= value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Implicit
        ///
        [TestMethod]
        public void op_ImplicitMassTest()
        {
            double value = 10F;
            Mass expected = new Mass(10);
            Mass actual;
            actual = value;
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Implicit
        ///
        [TestMethod]
        public void op_ImplicitDoubleTest()
        {
            Mass value = new Mass(10F);
            double expected = 10F;
            double actual;
            actual = value;
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Inequality
        ///
        [TestMethod]
        public void op_InequalityTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            bool expected = false;
            bool actual;
            actual = (value1 != value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_LessThan
        ///
        [TestMethod]
        public void op_LessThanTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(11F);
            bool expected = true;
            bool actual;
            actual = (value1 < value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_LessThanOrEqual
        ///
        [TestMethod]
        public void op_LessThanOrEqualTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            bool expected = true;
            bool actual;
            actual = (value1 <= value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Modulus
        ///
        [TestMethod]
        public void op_ModulusTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            Mass expected = new Mass(0F);
            Mass actual;
            actual = (value1 % value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Multiply
        ///
        [TestMethod]
        public void op_MultiplyTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            Mass expected = new Mass(100F);
            Mass actual;
            actual = (value1 * value2);
            Assert.AreEqual(expected, actual);
        }

        ///
        ///A test for op_Subtraction
        ///
        [TestMethod]
        public void op_SubtractionTest()
        {
            Mass value1 = new Mass(10F);
            Mass value2 = new Mass(10F);
            Mass expected = new Mass(0F);
            Mass actual;
            actual = (value1 - value2);
            Assert.AreEqual(expected, actual);
        }
    }
}


text:
<?php
namespace Codeception\Command;

use Codeception\Lib\Generator\Helper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Console\Question\Question;

/**
 * Creates default config, tests directory and sample suites for current project. Use this command to start building a test suite.
 *
 * By default it will create 3 suites **acceptance**, **functional**, and **unit**.
 *
 * * `codecept bootstrap` - creates `tests` dir and `codeception.yml` in current dir.
 * * `codecept bootstrap --empty` - creates `tests` dir without suites
 * * `codecept bootstrap --namespace Frontend` - creates tests, and use `Frontend` namespace for actor classes and helpers.
 * * `codecept bootstrap --actor Wizard` - sets actor as Wizard, to have `TestWizard` actor in tests.
 * * `codecept bootstrap path/to/the/project` - provide different path to a project, where tests should be placed
 *
 */
class Bootstrap extends Command
{
    // defaults
    protected $namespace = '';
    protected $actorSuffix = 'Tester';
    protected $supportDir = 'tests/_support';
    protected $logDir = 'tests/_output';
    protected $dataDir = 'tests/_data';
    protected $envsDir = 'tests/_envs';

    protected function configure()
    {
        $this->setDefinition(
            [
                new InputArgument('path', InputArgument::OPTIONAL, 'custom installation path', '.'),
                new InputOption('namespace', 'ns', InputOption::VALUE_OPTIONAL, 'Namespace to add for actor classes and helpers'),
                new InputOption('actor', 'a', InputOption::VALUE_OPTIONAL, 'Custom actor instead of Tester'),
                new InputOption('empty', 'e', InputOption::VALUE_NONE, 'Don\'t create standard suites')
            ]
        );
    }

    public function getDescription()
    {
        return "Creates default test suites and generates all requires files";
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('namespace')) {
            $this->namespace = trim($input->getOption('namespace'), '\\') . '\\';
        }

        if ($input->getOption('actor')) {
            $this->actorSuffix = $input->getOption('actor');
        }

        $path = $input->getArgument('path');

        if (!is_dir($path)) {
            $output->writeln("<error>\nDirectory '$path' does not exist\n</error>");
            return;
        }

        $realpath = realpath($path);
        chdir($path);

        if (file_exists('codeception.yml')) {
            $output->writeln("<error>\nProject is already initialized in '$path'\n</error>");
            return;
        }

        $output->writeln(
            "<fg=white;bg=magenta> Initializing Codeception in " . $realpath . " </fg=white;bg=magenta>\n"
        );

        $this->createGlobalConfig();
        $output->writeln("File codeception.yml created       <- global configuration");

        $this->createDirs();

        if (!$input->getOption('empty')) {
            $this->createUnitSuite();
            $output->writeln("tests/unit created                 <- unit tests");
            $output->writeln("tests/unit.suite.yml written       <- unit tests suite configuration");
            $this->createFunctionalSuite();
            $output->writeln("tests/functional created           <- functional tests");
            $output->writeln("tests/functional.suite.yml written <- functional tests suite configuration");
            $this->createAcceptanceSuite();
            $output->writeln("tests/acceptance created           <- acceptance tests");
            $output->writeln("tests/acceptance.suite.yml written <- acceptance tests suite configuration");
        }

        if (file_exists('.gitignore')) {
            file_put_contents('tests/_output/.gitignore', '');
            file_put_contents('.gitignore', file_get_contents('.gitignore') . "\ntests/_output/*");
            $output->writeln("tests/_output was added to .gitignore");
        }

        $output->writeln(" --- ");
        $this->ignoreFolderContent('tests/_output');

        file_put_contents('tests/_bootstrap.php', "<?php\n// This is global bootstrap for autoloading\n");
        $output->writeln("tests/_bootstrap.php written <- global bootstrap file");

        $output->writeln("<info>Building initial {$this->actorSuffix} classes</info>");
        $this->getApplication()->find('build')->run(
            new ArrayInput(['command' => 'build']),
            $output
        );

        $output->writeln("<info>\nBootstrap is done. Check out " . $realpath . "/tests directory</info>");
    }

    public function createGlobalConfig()
    {
        $basicConfig = [
            'actor'    => $this->actorSuffix,
            'paths'    => [
                'tests'   => 'tests',
                'log'     => $this->logDir,
                'data'    => $this->dataDir,
                'support' => $this->supportDir,
                'envs'    => $this->envsDir,
            ],
            'settings' => [
                'bootstrap'    => '_bootstrap.php',
                'colors'       => (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'),
                'memory_limit' => '1024M'
            ],
            'extensions' => [
                'enabled' => ['Codeception\Extension\RunFailed']
            ],
            'modules'  => [
                'config' => [
                    'Db' => [
                        'dsn'      => '',
                        'user'     => '',
                        'password' => '',
                        'dump'     => 'tests/_data/dump.sql'
                    ]
                ]
            ]
        ];

        $str = Yaml::dump($basicConfig, 4);
        if ($this->namespace) {
            $str = "namespace: {$this->namespace}\n" . $str;
        }
        file_put_contents('codeception.yml', $str);
    }

    protected function createFunctionalSuite($actor = 'Functional')
    {
        $suiteConfig = <<<EOF
# Codeception Test Suite Configuration
#
# Suite for functional (integration) tests
# Emulate web requests and make application process them
# Include one of framework modules (Symfony2, Yii2, Laravel5) to use it

class_name: $actor{$this->actorSuffix}
modules:
    enabled:
        # add framework module here
        - \\{$this->namespace}Helper\Functional
EOF;
        $this->createSuite('functional', $actor, $suiteConfig);
    }

    protected function createAcceptanceSuite($actor = 'Acceptance')
    {
            $suiteConfig = <<<EOF
# Codeception Test Suite Configuration
#
# Suite for acceptance tests.
# Perform tests in browser using the WebDriver or PhpBrowser.
# If you need both WebDriver and PHPBrowser tests - create a separate suite.

class_name: $actor{$this->actorSuffix}
modules:
    enabled:
        - PhpBrowser:
            url: http://localhost/myapp
        - \\{$this->namespace}Helper\Acceptance
EOF;
        $this->createSuite('acceptance', $actor, $suiteConfig);
    }

    protected function createUnitSuite($actor = 'Unit')
    {
        $suiteConfig = <<<EOF
# Codeception Test Suite Configuration
#
# Suite for unit (internal) tests.

class_name: $actor{$this->actorSuffix}
modules:
    enabled:
        - Asserts
        - \\{$this->namespace}Helper\Unit
EOF;
        $this->createSuite('unit', $actor, $suiteConfig);
    }

    protected function createSuite($suite, $actor, $config)
    {
        @mkdir("tests/$suite");
        file_put_contents(
            "tests/$suite/_bootstrap.php",
            "<?php\n// Here you can initialize variables that will be available to your tests\n"
        );
        @mkdir($this->supportDir . DIRECTORY_SEPARATOR . "Helper");
        file_put_contents(
            $this->supportDir . DIRECTORY_SEPARATOR . "Helper" . DIRECTORY_SEPARATOR . "$actor.php",
            (new Helper($actor, rtrim($this->namespace, '\\')))->produce()
        );
        file_put_contents("tests/$suite.suite.yml", $config);
    }

    protected function ignoreFolderContent($path)
    {
        if (file_exists('.gitignore')) {
            file_put_contents("{$path}/.gitignore", "*\n!.gitignore");
        }
    }

    protected function createDirs()
    {
        @mkdir('tests');
        @mkdir($this->logDir);
        @mkdir($this->dataDir);
        @mkdir($this->supportDir);
        @mkdir($this->envsDir);
        file_put_contents(
            $this->dataDir . '/dump.sql',
            '/* Replace this file with actual dump of your database */'
        );
    }

}


text:
<?php
//Direct Load
require_once dirname( __FILE__ ) . '/hustle-local-list.php';
require_once dirname( __FILE__ ) . '/hustle-local-list-form-settings.php';
require_once dirname( __FILE__ ) . '/hustle-local-list-form-hooks.php';
Hustle_Providers::get_instance()->register( 'Hustle_Local_List' );


text:
from designate.tests.test_api import ApiTestCase
from designate.api import service

class ApiServiceTest(ApiTestCase):
    def setUp(self):
        super(ApiServiceTest, self).setUp()

        # Use a random port for the API
        self.config(api_port=0, group='service:api')

        self.service = service.Service()

    def test_start_and_stop(self):
        # NOTE: Start is already done by the fixture in start_service()
        self.service.start()
        self.service.stop()


text:
from django import template
from anthill.utils import get_items_as_tag
from anthill.events.models import Event

register = template.Library()

@register.tag
def get_official_events(parser, token):
    return get_items_as_tag(token, Event.objects.future().filter(official=True))

@register.tag
def get_upcoming_events(parser, token):
    return get_items_as_tag(token, Event.objects.future())


text:
package uima.modules.qa.en

import uima.modules.qa.MultiLingualQueryGenerator
import us.feliscat.m17n.English
import us.feliscat.text.analyzer.SentenceQuotationParser
import us.feliscat.text.term.en.EnglishTermExpander
import us.feliscat.text.{StringNone, StringOption, StringSome}

import scala.collection.mutable.ListBuffer

/**
  * <pre>
  * Created on 2017/02/09.
  * </pre>
  *
  * @author K.Sakamoto
  */
object EnglishQueryGenerator extends MultiLingualQueryGenerator with English {
  override protected def expand(keywordOpt: StringOption): Seq[(String, Boolean)] = {
    val expansionBuffer = ListBuffer.empty[(String, Boolean)]
    keywordOpt match {
      case StringSome(keyword) =>
        expansionBuffer += ((keyword, true))
        var keywordTmp: String = keyword
        var quotedSequenceOpt: Option[(Quotation, Range)] = SentenceQuotationParser.getFirstMatchOpt(StringOption(keywordTmp))
        while (quotedSequenceOpt.nonEmpty) {
          val quotedSequence: (Quotation, Range) = quotedSequenceOpt.get
          val range: Range = quotedSequence._2
          expansionBuffer += ((keywordTmp.substring(range.start + 1, range.end - 1), true))
          keywordTmp = keywordTmp.substring(0, range.start) concat keywordTmp.substring(range.end, keywordTmp.length)
          quotedSequenceOpt = SentenceQuotationParser.getFirstMatchOpt(StringOption(keywordTmp))
        }
        expansionBuffer += ((keywordTmp, true))

        expansionBuffer ++= EnglishTermExpander.expand(keywordOpt)
      case StringNone =>
        // Do nothing
    }
    expansionBuffer.result.distinct
  }
}


text:
package com.lenis0012.bukkit.npc;

import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * Class that contains all api functions from npc's in NPCFactory
 *
 * @author lenis0012
 */
public interface NPC {

    /**
     * Get an org.bukkit.entity.Player instance from the npc.
     *
     * @return NPC's player instance.
     */
    public Player getBukkitEntity();

    /**
     * Check whether or not an npc can get damaged
     *
     * @return NPC can be damaged?
     */
    public boolean isGodmode();

    /**
     * Set whether or not an npc can get damaged
     *
     * @param invulnerable NPC can be damaged?
     */
    public void setGodmode(boolean invulnerable);

    /**
     * Check whether or not an npc has gravity enabled.
     *
     * @return NPC had gravity?
     */
    public boolean isGravity();

    /**
     * Set whether or not an npc has gravity enabled.
     *
     * @param gravity NPC has gravity?
     */
    public void setGravity(boolean gravity);

    /**
     * Sets the player lying down or standing up.
     * Proper use of NPCAnimation.LEAVE_BED;
     *
     * @param x the body's x co-ordinate
     *          (Set to null to make entity stand up)
     * @param y the body's y co-ordinate
     *          (Set to null to make entity stand up)
     * @param z the body's z co-ordinate
     *          (Set to null to make entity stand up)
     *          <p/>
     *          Will only make NPC stand up if all
     *          3 co-ordinates are set to null and
     *          NPC is lying down.
     */

    public void setLying(double x, double y, double z);

    /**
     * Checks whether the entity is lying down
     *
     * @return Boolean value of whether the entity is lying down
     */

    public boolean isLying();

    /**
     * Walk to a location
     *
     * @param location Location to walk to
     * @return True if path created and applied correctly.
     */
    public boolean pathfindTo(Location location);

    /**
     * Walk to a location with custom speed
     *
     * @param location Location to walk to
     * @param speed    Speed to walk with (max 1.0, 0.2 default)
     * @return True if path created and applied correctly.
     */
    public boolean pathfindTo(Location location, double speed);

    /**
     * Walk to a location with custom speed and range.
     *
     * @param location Location to walk to
     * @param speed    Speed to walk with (max 1.0, 0.2 default)
     * @param range    Block radius limit for path finding (30 default)
     * @return True if path created and applied correctly.
     */
    public boolean pathfindTo(Location location, double speed, double range);

    /**
     * Make NPC look at an entity.
     *
     * @param target Entity to look at
     */
    public void setTarget(Entity target);

    /**
     * Get the entity the npc is looking at
     *
     * @return Entity npc is looking at (null if not found)
     */
    public Entity getTarget();

    /**
     * Make npc look at a certain location
     *
     * @param location Location to look at
     */
    public void lookAt(Location location);

    /**
     * Change npc's yaw the proper way
     *
     * @param yaw New npc yaw
     */
    public void setYaw(float yaw);

    /**
     * Play an animation on the npc
     *
     * @param animation Animation type to display
     */
    public void playAnimation(NPCAnimation animation);

    /**
     * Set npc equipment.
     *
     * @param slot Slot type for the equipment
     * @param item Item to put on slot
     */
    public void setEquipment(EquipmentSlot slot, ItemStack item);

    /**
     * Get if an npc with collide with other entities.
     *
     * @param location Get entity collision for npc.
     * @return
     */
    public boolean getEntityCollision();

    /**
     * Set if an npc with collide with other entities.
     *
     * @param location Set entity collision for npc.
     * @return
     */
    public void setEntityCollision(boolean entityCollision);

}


text:
using Entitas;
using Entitas.CodeGeneration.Attributes;

[Context("Test"), Unique, FlagPrefix("My")]
public sealed class CustomPrefixFlagComponent : IComponent {
}


text:
export = DownloadFile;
declare function DownloadFile(name: string, contentFileName: string, contentType: string): void;
declare class DownloadFile {
    constructor(name: string, contentFileName: string, contentType: string);
    openFile(): File;
}
import File = require('@nginstack/engine/lib/io/File.js');


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

<title>BitThief</title>
<meta name="date" content="2017-02-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

experiment.effort.noseine.bitthief

Class BitThief

java.lang.Object

experiment.effort.noseine.bitthief.BitThief

All Implemented Interfaces:

java.lang.Cloneable, peersim.core.Protocol, peersim.edsim.EDProtocol

public class BitThief
extends java.lang.Object
implements peersim.edsim.EDProtocol

This is the class that implements the BitTorrent module for Peersim

Field Summary

Fields

Modifier and Type
Field and Description

int
maxGrowth

Defines how much the network can grow with respect to the <tt>network.size</tt>
  when NetworkDynamics is used.

int
nPieceCompleted

Current number of piece completed.

int
nPiecesDown

Current number of pieces in download to the local peer.

int
nPiecesUp

Current number of pieces in upload from the local peer.

Constructor Summary

Constructors

Constructor and Description

BitThief(java.lang.String prefix)

The default constructor.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
addNeighbor(peersim.core.Node neighbor)

Adds a neighbor to the cache of the local node.

boolean
alive(peersim.core.Node node)

Checks if a node is still alive in the simulated network.

java.lang.Object
clone()

Clone method of the class.

byte
getCodeNodeModel()

byte
getCodeSelfishnessModel()

int[]
getFileStatus()

Gets the file status of the local node.

int
getNNodes()

Gets the number of neighbors currently stored in the cache of the local node.

int
getNPieces()

Returns the file's size as number of pieces of 256KB.

int
getPeerStatus()

Gets the status of the local node.

int
getStatus(int index)

Gets the number of blocks for a given piece owned by the local node.

long
getThisNodeID()

Gets the ID of the local node.

peersim.core.Node
getTracker()

Gets the reference to the tracker node.

void
initializeTracker()

Initializes the tracker node.

void
processEvent(peersim.core.Node node,
            int pid,
            java.lang.Object event)

The standard method that processes incoming events.

void
processNeighborListSize(peersim.core.Node node,
                       int pid,
                       int numberNodes)

Checks the number of neighbors and if it is equal to 20
        sends a TRACKER messages to the tracker, asking for a new
        peer set.

void
processRequest(peersim.core.Node node,
              int pid,
              java.lang.Object event)

boolean
removeNeighbor(peersim.core.Node neighbor)

Removes a neighbor from the cache of the local node.

experiment.effort.noseine.bitthief.Element
search(long ID)

Searches the node with the given ID.

void
sendHaveMessage(java.lang.Object ev,
               int pid,
               peersim.core.Node node)

void
setBandwidth(int value)

Sets the maximum bandwdith for the local node.

void
setCompleted(int number)

Used by NodeInitializer to set
        the number of piece completed from the beginning in according with
        the distribution in the configuration file.

void
setPeerStatus(int status)

Sets the status of the local node.

void
setStatus(int index,
         int value)

Sets the status (the set of blocks) of the file for the current node.

void
setThisNodeID(long id)

Sets the ID of the local node.

void
setTracker(peersim.core.Node t)

Sets the reference to the tracker node.

void
sortByBandwidth()

Sorts the array byBandwidth using QuickSort algorithm.

void
sortByPeer()

Sorts byPeer array by peer's ID.

void
updateMaxBandwidth(int bandwidthConsumption)

void
updateSwarmSize(int swarmSizeMod,
               boolean isIncrease)

Methods inherited from class java.lang.Object

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

Field Detail

maxGrowth

public int maxGrowth

Defines how much the network can grow with respect to the <tt>network.size</tt>
  when NetworkDynamics is used.

nPiecesUp

public int nPiecesUp

Current number of pieces in upload from the local peer.

nPiecesDown

public int nPiecesDown

Current number of pieces in download to the local peer.

nPieceCompleted

public int nPieceCompleted

Current number of piece completed.

Constructor Detail

BitThief

public BitThief(java.lang.String prefix)

The default constructor. Reads the configuration file and initializes the
        configuration parameters.

Parameters:

prefix - the component prefix declared in the configuration file

Method Detail

getTracker

public peersim.core.Node getTracker()

Gets the reference to the tracker node.

Returns:

the reference to the tracker

getNNodes

public int getNNodes()

Gets the number of neighbors currently stored in the cache of the local node.

Returns:

the number of neighbors in the cache

setTracker

public void setTracker(peersim.core.Node t)

Sets the reference to the tracker node.

Parameters:

t - the tracker node

setThisNodeID

public void setThisNodeID(long id)

Sets the ID of the local node.

Parameters:

id - the ID of the node

updateSwarmSize

public void updateSwarmSize(int swarmSizeMod,
                            boolean isIncrease)

getThisNodeID

public long getThisNodeID()

Gets the ID of the local node.

Returns:

the ID of the local node

getFileStatus

public int[] getFileStatus()

Gets the file status of the local node.

Returns:

the file status of the local node

initializeTracker

public void initializeTracker()

Initializes the tracker node. This method
        only performs the initialization of the tracker's cache.

processNeighborListSize

public void processNeighborListSize(peersim.core.Node node,
                                    int pid,
                                    int numberNodes)

Checks the number of neighbors and if it is equal to 20
        sends a TRACKER messages to the tracker, asking for a new
        peer set.

This method *must* be called after every call of removeNeighbor(peersim.core.Node)
        in processEvent(peersim.core.Node, int, java.lang.Object).

processEvent

public void processEvent(peersim.core.Node node,
                         int pid,
                         java.lang.Object event)

The standard method that processes incoming events.

Specified by:

processEvent in interface peersim.edsim.EDProtocol

Parameters:

node - reference to the local node for which the event is going to be processed

pid - BitTorrent's protocol id

event - the event to process

sendHaveMessage

public void sendHaveMessage(java.lang.Object ev,
                            int pid,
                            peersim.core.Node node)

processRequest

public void processRequest(peersim.core.Node node,
                           int pid,
                           java.lang.Object event)

setCompleted

public void setCompleted(int number)

Used by NodeInitializer to set
        the number of piece completed from the beginning in according with
        the distribution in the configuration file.

Parameters:

number - the number of piece completed

setStatus

public void setStatus(int index,
                      int value)

Sets the status (the set of blocks) of the file for the current node.
  Note that a piece is considered completed if the number
  of downloaded blocks is 16.

Parameters:

index - The index of the piece

value - Number of blocks downloaded for the piece index.

setPeerStatus

public void setPeerStatus(int status)

Sets the status of the local node.

Parameters:

status - The status of the node: 1 means seeder, 0 leecher

getPeerStatus

public int getPeerStatus()

Gets the status of the local node.

Returns:

The status of the local node: 1 means seeder, 0 leecher

getStatus

public int getStatus(int index)

Gets the number of blocks for a given piece owned by the local node.

Parameters:

index - The index of the piece

Returns:

Number of blocks downloaded for the piece index

setBandwidth

public void setBandwidth(int value)

Sets the maximum bandwdith for the local node.

Parameters:

value - The value of bandwidth in Kbps

alive

public boolean alive(peersim.core.Node node)

Checks if a node is still alive in the simulated network.

Parameters:

node - The node to check

Returns:

true if the node <tt>node</tt> is up, false otherwise

See Also:

GeneralNode.isUp()

addNeighbor

public boolean addNeighbor(peersim.core.Node neighbor)

Adds a neighbor to the cache of the local node.
  The new neighbor is put in the first null position.

Parameters:

neighbor - The neighbor node to add

Returns:

<tt>false</tt> if the neighbor is already present in the cache (this can happen when the peer requests a
        new peer set to the tracker an there is still this neighbor within) or no place is available.
        Otherwise, returns true if the node is correctly added to the cache.

removeNeighbor

public boolean removeNeighbor(peersim.core.Node neighbor)

Removes a neighbor from the cache of the local node.

Parameters:

neighbor - The node to remove

Returns:

true if the node is correctly removed, false otherwise.

getNPieces

public int getNPieces()

Returns the file's size as number of pieces of 256KB.

Returns:

number of pieces that compose the file.

clone

public java.lang.Object clone()

Clone method of the class. Returns a deep copy of the BitTorrent class. Used
        by the simulation to initialize the Network

Specified by:

clone in interface peersim.core.Protocol

Overrides:

clone in class java.lang.Object

Returns:

the deep copy of the BitTorrent class.

sortByPeer

public void sortByPeer()

Sorts byPeer array by peer's ID. It implements the InsertionSort
        algorithm.

sortByBandwidth

public void sortByBandwidth()

Sorts the array byBandwidth using QuickSort algorithm.
        <tt>null</tt> elements and seeders are moved to the end of the array.

search

public experiment.effort.noseine.bitthief.Element search(long ID)

Searches the node with the given ID. It does a dychotomic
        search.

Parameters:

ID - ID of the node to search.

Returns:

the Element in byPeer which represents the node with the
        given ID.

getCodeNodeModel

public byte getCodeNodeModel()

getCodeSelfishnessModel

public byte getCodeSelfishnessModel()

updateMaxBandwidth

public void updateMaxBandwidth(int bandwidthConsumption)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR
import CCSDS.FRAME, CCSDS.PACKET
import UTIL.DU

###########
# classes #
###########
# =============================================================================
class Packetizer():
  """Converter from TM frames to TM packets"""
  # ---------------------------------------------------------------------------
  def __init__(self, expectedVCID):
    """default constructor"""
    self.pendingPacketFragment = None
    self.expectedVCID = expectedVCID
  # ---------------------------------------------------------------------------
  def reset(self):
    """resets pending packet fragment"""
    self.pendingPacketFragment = None
  # ---------------------------------------------------------------------------
  def isPacketPending(self):
    """checks if there is a pending packet (waiting for next fragment)"""
    return (self.pendingPacketFragment != None)
  # ---------------------------------------------------------------------------
  def pushTMframe(self, binFrame):
    """consumes a telemetry frame"""
    # extract packets incl. fragments from frame
    try:
      frameDU = CCSDS.FRAME.TMframe(binFrame)
      leadingFragment, packets, trailingFragment = frameDU.getPackets()
    except Exception as ex:
      LOG_ERROR("error in TM packet extraction from TM frame: " + str(ex))
      self.reset()
      return
    # consistency check
    if frameDU.virtualChannelId != self.expectedVCID:
      LOG_WARNING("frame has unexpected virtual channel ID: " + str(frameDU.virtualChannelId))
      return
    # --- leading fragment ---
    if leadingFragment:
      # there must be a pending packet fragment from the previous frame
      if self.pendingPacketFragment:
        packet = self.pendingPacketFragment + leadingFragment
        newPacketSize = len(packet)
        expectedPacketSize = CCSDS.PACKET.getPacketSize(packet)
        if newPacketSize < expectedPacketSize:
          # consistency check
          if len(packets) > 0 or trailingFragment:
            LOG_ERROR("TM packet fragment not fully assembled")
            self.reset()
          else:
            # other fragment(s) should follow in next frame
            self.pendingPacketFragment = packet
            return
        elif newPacketSize == expectedPacketSize:
          # spillover packet complete assembled
          self.notifyTMpacketCallback(packet)
          self.reset()
        else:
          # assembled packet does not match the expected size (too large)
          LOG_ERROR("invalid TM packet fragment size in TM frame")
          self.reset()
      else:
        LOG_ERROR("unexpected TM packet fragment in TM frame")
        # ignore the packet fragment, regular packets should follow
    # --- complete packets ---
    if len(packets) > 0:
      for packet in packets:
        self.notifyTMpacketCallback(packet)
    # --- trailing fragment ---
    if trailingFragment:
      self.pendingPacketFragment = trailingFragment
  # ---------------------------------------------------------------------------
  def notifyTMpacketCallback(self, binPacket):
    """notifies when the next TM packet is assembled"""
    # shall be overloaded in derived class, default implementaion logs packet
    LOG("Packetizer.notifyTMpacketCallback" + UTIL.DU.array2str(binPacket))