text:
package com.ikeirnez.pluginmessageframework.bukkit;

import com.ikeirnez.pluginmessageframework.internal.ServerGatewaySupport;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.plugin.messaging.PluginMessageListener;

import java.io.IOException;
import java.util.Collection;

/**
 * The default Bukkit implementation of a {@link com.ikeirnez.pluginmessageframework.gateway.ServerGateway}.
 */
public class ImplBukkitGateway extends ServerGatewaySupport<Player> implements Listener, PluginMessageListener {

    protected final Plugin plugin;

    protected ImplBukkitGateway(String channel, final Plugin plugin) {
        super(channel);

        if (plugin == null) {
            throw new IllegalArgumentException("Plugin cannot be null.");
        }

        this.plugin = plugin;

        Messenger messenger = plugin.getServer().getMessenger();
        messenger.registerOutgoingPluginChannel(plugin, getChannel());
        messenger.registerIncomingPluginChannel(plugin, getChannel(), this);
        plugin.getServer().getPluginManager().registerEvents(this, plugin);
    }

    @Override
    public void sendPayload(Player connection, byte[] bytes) {
        connection.sendPluginMessage(plugin, getChannel(), bytes);
    }

    @Override
    public Player getConnection() {
        Collection<? extends Player> players = Bukkit.getOnlinePlayers();
        return players.size() > 0 ? players.iterator().next() : null;
    }

    @Override
    public void onPluginMessageReceived(String channel, Player player, byte[] message) {
        if (channel.equals(getChannel())) {
            try {
                incomingPayload(player, message);
            } catch (IOException e) {
                logger.error("Error handling incoming payload.", e);
            }
        }
    }

    @EventHandler
    public void onPlayerJoin(final PlayerJoinEvent event) {
        Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { // delay to work around plugin messages not sending when players first join
            @Override
            public void run() {
                if (queuedPackets()) {
                    sendQueuedPackets(event.getPlayer());
                }
            }
        }, 10L);
    }

}


text:
@extends('layouts.app')

@section('content')

    @if(isset($_GET["id"]))
        @php
            $gameID = htmlspecialchars($_GET["id"]);
            $board = \App\Game::find($gameID)->board;
            $time = \App\Game::find($gameID)->time;
            $score = \App\Game::find($gameID)->score;
        @endphp
    @endif

Home

Play

                Success! Everything went as expected.

                Warning! Better check yourself, you're not looking too good.

Game finished!

Username

Score

Time

{{ Auth::User()->username }}

<button class="btn btn-primary" onclick="saveGame()">Upload score</button>

Play options:

            <form>
                <input type="hidden" name="_method" value="PUT">
                <input type="hidden" id="user_id" name="user_id" value="{{ Auth::User()->id }}">

                            <input id="default-gap" type="radio" name="gap" value="pos-4-4" required checked>
                            Default Gap

                            <input id="random-gap" type="radio" name="gap" value="random" required>
                            Random Gap

                    Set Seconds

                            <input id="timer-option" type="number" name="timer-option" value="" placeholder="Time">
                            0 or blank for Timeless

                        @if(isset($_GET["id"]))
                            <button type="button" class="btn btn-primary" onclick="saveGame()">Save Game</button>
                        @else
                            <button type="button" class="btn btn-success" onclick="createBoard()">Play</button>
                        @endif

            </form>

                    @if(isset($_GET["id"]))

Timer: {!! $time !!}

                    @else

Timer:

                    @endif

                    @if(isset($_GET["id"]))

Score: {!! $score !!}

                    @else

Score:

                    @endif

            @if(isset($_GET["id"]))

{!! $board !!}

            @else

            @endif

@endsection

redpajama_set_name: RedPajamaGithub


text:
namespace Installation_v2.InstallationLogic.Enums {
    public enum SystemVersion {
        Any,
        XP,
        Vista,
        Win7,
        Unknown
    }
}


text:
package kbdex.app.manager;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import clib.common.filesystem.CDirectory;
import clib.common.thread.ICTask;
import clib.view.actions.CAction;
import clib.view.actions.CActionManager;
import clib.view.actions.CActionUtils;
import clib.view.app.javainfo.CJavaInfoPanels;
import clib.view.dialogs.CCreateNameDialog;
import clib.view.list.CDirectoryListModel;
import clib.view.list.CListPanel;
import clib.view.panels.CPanelUtils;
import clib.view.progress.CPanelProcessingMonitor;
import kbdex.app.KBDeX;
import kbdex.app.ext.KKF5Importer;
import kbdex.app.ext.KKF6Importer;
import kbdex.app.ext.KKFDiscourseImporter;
import kbdex.app.ext.KKaniChatCSVImporter;
import kbdex.model.discourse.KDDiscourseFile;

/**
 * @author macchan
 *
 */
public class KDiscourseManagerFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	private KDDiscourseManager manager;

	private CListPanel<CDirectory> listPanel = new CListPanel<CDirectory>();
	private CreateNameDialog createNameDialog = new CreateNameDialog(this);

	private CActionManager actionManager = new CActionManager();
	private Action actionOpen = actionManager.createAction("Open",
			new ICTask() {
				public void doTask() {
					doOpen();
				}
			});
	private Action actionRename = actionManager.createAction("Rename",
			new ICTask() {
				public void doTask() {
					doRename();
				}
			});
	private Action actionCopy = actionManager.createAction("Copy",
			new ICTask() {
				public void doTask() {
					doCopy();
				}
			});
	private Action actionDelete = actionManager.createAction("Delete",
			new ICTask() {
				public void doTask() {
					doDelete();
				}
			});

	public KDiscourseManagerFrame(KDDiscourseManager manager,
			String windowTitle) {
		this.manager = manager;
		setTitle(windowTitle);
		initialize();
	}

	private void initialize() {
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setIconImage(KBDeX.getInstance().getIconImage32());
		initializePanel();
		initializeMenu();
	}

	private void initializeMenu() {
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		{
			JMenu menu = new JMenu("Import");
			menuBar.add(menu);
			{
				final KKF6Importer importer = new KKF6Importer();
				CAction action = CActionUtils.createAction("From KF6",
						new ICTask() {
							@Override
							public void doTask() {
								importer.doLoad();
								refreshDiscourseList();
							}
						});
				menu.add(action);
			}
			{
				final KKF5Importer importer = new KKF5Importer();
				CAction action = CActionUtils.createAction("From KF5",
						new ICTask() {
							@Override
							public void doTask() {
								importer.doLoad();
								refreshDiscourseList();
							}
						});
				menu.add(action);
			}
			{
				final KKFDiscourseImporter importer = new KKFDiscourseImporter();
				CAction action = CActionUtils.createAction("From KF4",
						new ICTask() {
							@Override
							public void doTask() {
								importer.doLoad();
								refreshDiscourseList();
							}
						});
				menu.add(action);
			}
			{
				final KKaniChatCSVImporter importer = new KKaniChatCSVImporter();
				CAction action = CActionUtils.createAction("From KaniChat CSV",
						new ICTask() {
							@Override
							public void doTask() {
								importer.doImport(KDiscourseManagerFrame.this);
								refreshDiscourseList();
							}
						});
				menu.add(action);
			}
		}

		{
			JMenu menu = new JMenu("Info");
			menuBar.add(menu);
			menu.add(CJavaInfoPanels.createJavaInformationAction());
		}

	}

	private void initializePanel() {

		//ListPanel
		listPanel.getJList()
				.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listPanel.setModel(new CDirectoryListModel(manager.getBaseDirectory()));
		listPanel.getJList().getSelectionModel()
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						updateButtonState();
					}
				});
		listPanel.refresh();
		listPanel.getJList().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					doOpen();
				}
			}
		});
		getContentPane().add(listPanel);

		//ButtonPanel
		JPanel buttonPanel = CPanelUtils.createListPanel();
		int w = 100;
		int h = new JButton().getPreferredSize().height;

		{
			JButton button = new JButton(actionOpen);
			button.setPreferredSize(new Dimension(w, h));
			buttonPanel.add(button);
		}

		{
			JButton button = new JButton(actionRename);
			button.setPreferredSize(new Dimension(w, h));
			buttonPanel.add(button);
		}

		{
			JButton button = new JButton(actionCopy);
			button.setPreferredSize(new Dimension(w, h));
			buttonPanel.add(button);
		}

		{
			JButton button = new JButton(actionDelete);
			button.setPreferredSize(new Dimension(w, h));
			buttonPanel.add(button);
		}

		updateButtonState();
		getContentPane().add(buttonPanel, BorderLayout.EAST);
	}

	public void openWindowInDefaultSize() {
		setLocation(100, 100);
		setSize(500, 250);
		setVisible(true);
	}

	protected void doOpen() {
		final CDirectory dir = listPanel.getSelectedElement();
		final CPanelProcessingMonitor monitor = KBDeX.getInstance()
				.getMonitor();
		monitor.doTaskWithDialog(new ICTask() {
			public void doTask() {
				try {
					manager.openDiscourse(dir.getNameByString(), monitor);
				} catch (Exception ex) {
					KBDeX.getInstance()
							.handleException(KDiscourseManagerFrame.this, ex);
				}
			}
		});
	}

	protected void doRename() {
		KDDiscourseFile file = new KDDiscourseFile(
				listPanel.getSelectedElement());

		createNameDialog.setTitle("Rename");
		createNameDialog.setDefaultName(file.getName());
		createNameDialog.open();
		if (createNameDialog.getState() != CCreateNameDialog.State.INPUTTED) {
			return;
		}

		file.renameTo(createNameDialog.getInputtedName());
		refreshDiscourseList();
	}

	protected void doCopy() {
		KDDiscourseFile file = new KDDiscourseFile(
				listPanel.getSelectedElement());

		createNameDialog.setTitle("Copy");
		createNameDialog.setDefaultName(file.getName());
		createNameDialog.open();
		if (createNameDialog.getState() != CCreateNameDialog.State.INPUTTED) {
			return;
		}

		file.copyTo(createNameDialog.getInputtedName());
		refreshDiscourseList();
	}

	protected void doDelete() {
		KDDiscourseFile file = new KDDiscourseFile(
				listPanel.getSelectedElement());
		int res = JOptionPane.showConfirmDialog(this,
				"Do you want to delete the file \"" + file.getName() + "\" ?",
				"Final Confirm", JOptionPane.WARNING_MESSAGE);
		if (res != JOptionPane.OK_OPTION) {
			return;
		}

		file.delete();
		refreshDiscourseList();
	}

	private void updateButtonState() {
		boolean active = listPanel.getSelectedElement() != null;
		actionManager.setActionStates(active);
	}

	public void refreshDiscourseList() {
		listPanel.refresh();
	}

	class CreateNameDialog extends CCreateNameDialog {
		private static final long serialVersionUID = 1L;

		public CreateNameDialog(Frame owner) {
			super(owner);
		}

		protected String validCheck(String text) {
			if (manager.existsDiscourse(text)) {
				return "ERROR: The name is already used.";
			} else {
				return null;
			}
		}

		protected String getInputTitle() {
			return "Name";
		}
	};
}


text:
The project implements java concurrent (Listenable) Future in very cheap and flexible way.

The performance is for obvious reasons (additional support of listeners) slightly lower than original JDK Future but significantly higher than similar implementations in Guava and Spring.

### Release

```
<dependency>
	<groupId>net.dryuf</groupId>
	<artifactId>dryuf-concurrent</artifactId>
	<version>1.3.1</version>
</dependency>
```

### Flexibility

Additionally it solves several design issues from which suffer Guava and Spring implementations:
- allows several types of listeners, which can just implement Runnable or receive the original Future or receive directly the result to appropriate method
- distinguishes failure and cancellation when invoking listener
- distinguishes not started and running state
- allows delayed cancel notifications, i.e. the notification about cancel can be postponed until the task really exits, this is useful when task occupies some shared resource like network port

### Performance

The performance comparison looks like (measured on my low voltage i7 x86_64):

#### No listener
```
Benchmark                                    Mode  Cnt    Score   Error  Units
NoListenerAsyncBenchmark.benchmarkGuava     thrpt    2  157.510          ops/s
NoListenerAsyncBenchmark.benchmarkJdk       thrpt    2  241.154          ops/s
NoListenerAsyncBenchmark.benchmarkLwFuture  thrpt    2  279.774          ops/s
NoListenerAsyncBenchmark.benchmarkSpring    thrpt    2  117.028          ops/s
```

It's 78% faster than Guava, 139% faster than Spring and 16% faster than JDK.

#### Single listener set prior to run
```
Benchmark                                           Mode  Cnt    Score   Error  Units
SinglePreListenerAsyncBenchmark.benchmarkGuava     thrpt    2   98.639          ops/s
SinglePreListenerAsyncBenchmark.benchmarkJdk       thrpt    2  239.813          ops/s
SinglePreListenerAsyncBenchmark.benchmarkLwFuture  thrpt    2  204.984          ops/s
SinglePreListenerAsyncBenchmark.benchmarkSpring    thrpt    2   82.673          ops/s
```

It's 108% faster than Guava, 148% faster than Spring and 15% slower than JDK (but JDK test runs without  listener).

### Implementations

Currenty there are two implementations that differ in details how to handle atomic operations. The performance difference is about 10% but may change with JRE version:
- feature/atomic-field-updaters - uses AtomicFieldUpdaters to manage the atomic fields, should be faster but with current JIT it's slower
- feature/atomic-type-instances - uses AtomicInteger and AtomicReference instances, although the access is indirect, with current JIT this is faster
- feature/unsafe-volatiles - uses Unsafe instance to read and write volatile members, fastest solution, with NoListener test even outperforms JDK Future

## Lazily built LoadingCache

Class allowing caching results of Function, strongly enhancing performance of ConcurrentHashMap.

Common usage of this class is to build constant program metadata which never change and only grow over time but get fixed at some point (reflection based data commonly used by serializers for example). Implementation propagates the data built in ConcurrentHashMap to regular Map with some delay, increasing its performance. Its performance is similar to ConcurrentHashMap in cold start but gets to HashMap performance after data get fixed.

### Performance

```
Benchmark                                                               Mode  Cnt    Score   Error  Units
LazilyBuiltLoadingCacheBenchmark.coldLazilyBuiltLoadingCacheBenchmark  thrpt    2   31.449          ops/s
LazilyBuiltLoadingCacheBenchmark.directConcurrentBenchmark             thrpt    2   42.302          ops/s
LazilyBuiltLoadingCacheBenchmark.warmLazilyBuiltLoadingCacheBenchmark  thrpt    2  318.348          ops/s
```

Measurement was done in 1M batches on 4-core laptop x86_64 CPU, may be different on server CPU and even more significant on more relaxed CPU architecture (requiring LoadLoad barriers for example). Using this warming cache is about 8 times faster than using ConcurrentHashMap and is only 25% slower during initialization.

## Instance type based Function

Class wrapping instanceof checks into Function interface, delegating the calls according to type of passed argument.

Instead of writing many ```instanceof``` checks, it allows specifying the Map of types and the callback to call for the matching type. The implementation is smart enough to figure any subclasses, in the order items coming from the Map. There are two ways of specifying the Map of callback functions, one of them wraps only Function objects, the other wraps into BiFunction objects, allowing specifying the owner object first. The latter allows the callback delegator to be shared among multiple calling instances.

### Usage

```
public Callee
{
	// Note the second parameter to add method is BiFunction, so it is real instance method reference, not static reference
	private static BiFunction<Callee, Object, Object> ownerCaller = new TypeDelegatingOwnerBiFunction<>(TypeDelegatingOwnerBiFunction.<Callee, Object, Object>callbacksBuilder()
			.add(First.class, Callee::callFirst)
			.add(Second.class, Callee::callSecond)
			.add(Third.class, Callee::callThird)
			.add(Fourth.class, Callee::callFourth)
			.add(Fifth.class, Callee::callFifth)
			.build()
	);

	public Object call(Object input)
	{
		ownerCaller.call(this, input);
	}

	private Object callFirst(First input) { ... }
	private Object callSecond(Second input) { ... }

	...
}
```

### Performance

```
Benchmark                                                   Mode  Cnt   Score   Error  Units
TypeDelegatingFunctionBenchmark.directInstanceofBenchmark  thrpt    2  24.092          ops/s
TypeDelegatingFunctionBenchmark.instanceCallerBenchmark    thrpt    2  67.543          ops/s
TypeDelegatingFunctionBenchmark.ownerCallerBenchmark       thrpt    2  67.262          ops/s
```

Done in 1M batches. Apart from convenience and type safety, you can see the callback delegator is about 3 times faster than instanceof based code (the benchmark is based on 5 different classes passed as argument).

## Custom Executor

### CloseableExecutor

Interface allowing automatically closing Executor in try-with-resources statements, mostly to simplify unit tests.

### ClosingExecutor

Implementation of the above, wrapping the existing ExecutorService into another Executor and shutting down in `close()` method.

### ResultSerializingExecutor

Executor executing tasks in parallel but serializing the results in the order of submission.

### CapacityResultSerializingExecutor

Executor serializing tasks in parallel but serializing the results in the order of submission.  Additionally, it controls throughput by given capacity and number of parallel tasks.  Typically, the capacity is constrained by memory or disk size or number of connections.

### SingleConsumerQueue

Queue for submitting tasks and consuming them from single consumer, guaranteed to be executed in unique instance.

## License

The code is released under version 2.0 of the [Apache License][].

## Stay in Touch

Feel free to contact me at kvr000@gmail.com  and http://github.com/kvr000/ and http://github.com/dryuf/

[Apache License]: http://www.apache.org/licenses/LICENSE-2.0


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = require('babel-runtime/core-js/set');

var _set2 = _interopRequireDefault(_set);

exports.default = withSideEffect;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _utils = require('./utils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function withSideEffect(reduceComponentsToState, handleStateChangeOnClient, mapStateOnServer) {
  if (typeof reduceComponentsToState !== 'function') {
    throw new Error('Expected reduceComponentsToState to be a function.');
  }

  if (typeof handleStateChangeOnClient !== 'function') {
    throw new Error('Expected handleStateChangeOnClient to be a function.');
  }

  if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {
    throw new Error('Expected mapStateOnServer to either be undefined or a function.');
  }

  return function wrap(WrappedComponent) {
    if (typeof WrappedComponent !== 'function') {
      throw new Error('Expected WrappedComponent to be a React component.');
    }

    var mountedInstances = new _set2.default();
    var state = void 0;

    function emitChange(component) {
      state = reduceComponentsToState([].concat((0, _toConsumableArray3.default)(mountedInstances)));

      if (SideEffect.canUseDOM) {
        handleStateChangeOnClient.call(component, state);
      } else if (mapStateOnServer) {
        state = mapStateOnServer(state);
      }
    }

    var SideEffect = function (_Component) {
      (0, _inherits3.default)(SideEffect, _Component);

      function SideEffect() {
        (0, _classCallCheck3.default)(this, SideEffect);
        return (0, _possibleConstructorReturn3.default)(this, (SideEffect.__proto__ || (0, _getPrototypeOf2.default)(SideEffect)).apply(this, arguments));
      }

      (0, _createClass3.default)(SideEffect, [{
        key: 'componentWillMount',
        value: function componentWillMount() {
          mountedInstances.add(this);
          emitChange(this);
        }
      }, {
        key: 'componentDidUpdate',
        value: function componentDidUpdate() {
          emitChange(this);
        }
      }, {
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {
          mountedInstances.delete(this);
          emitChange(this);
        }
      }, {
        key: 'render',
        value: function render() {
          return _react2.default.createElement(
            WrappedComponent,
            null,
            this.props.children
          );
        }
      }], [{
        key: 'peek',
        value: function peek() {
          return state;
        }

        // Expose canUseDOM so tests can monkeypatch it

        // Try to use displayName of wrapped component

      }, {
        key: 'rewind',
        value: function rewind() {
          if (SideEffect.canUseDOM) {
            throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');
          }

          var recordedState = state;
          state = undefined;
          mountedInstances.clear();
          return recordedState;
        }
      }]);
      return SideEffect;
    }(_react.Component);

    SideEffect.displayName = 'SideEffect(' + (0, _utils.getDisplayName)(WrappedComponent) + ')';
    SideEffect.contextTypes = WrappedComponent.contextTypes;
    SideEffect.canUseDOM = typeof window !== 'undefined';

    return SideEffect;
  };
}


text:
namespace mp4v2 { namespace util {

///////////////////////////////////////////////////////////////////////////////

/// Class representing SMPTE timecode.
///
/// Objects of this class represent a specific time or duration and can
/// be converted to/from string values, and various epochs.
///
/// The standard pattern for string representation is as follows:
///     @li HH:MM:SS:FF
///     @li HH:MM:SS.DDD
///
/// where:
///     @li HH specifies hours
///     @li MM specifies minutes
///     @li SS specifies seconds
///     @li : specifies normal timecode
///     @li FF specifies the frame number
///     @li . specifies decimal fractions of a second follow
///     @li DDD specifies decimal fractions of a second, rounded down to closest scale
///
class MP4V2_EXPORT Timecode {
public:
    enum Format {
        FRAME,
        DECIMAL,
    };

private:
    double   _scale;
    uint64_t _duration;
    Format   _format;
    string   _svalue;

    uint64_t _hours;
    uint64_t _minutes;
    uint64_t _seconds;
    uint64_t _subseconds;

public:
    const double&   scale;
    const uint64_t& duration;
    const Format&   format;
    const string&   svalue;

    const uint64_t& hours;
    const uint64_t& minutes;
    const uint64_t& seconds;
    const uint64_t& subseconds;

public:
    Timecode( const Timecode& );
    explicit Timecode( const string&, double = 1.0 );
    explicit Timecode( uint64_t = 0, double = 1.0 );

    Timecode& operator=  ( const Timecode& );
    Timecode& operator+= ( const Timecode& );
    Timecode& operator-= ( const Timecode& );

    bool operator<  ( const Timecode& ) const;
    bool operator<= ( const Timecode& ) const;
    bool operator>  ( const Timecode& ) const;
    bool operator>= ( const Timecode& ) const;
    bool operator!= ( const Timecode& ) const;
    bool operator== ( const Timecode& ) const;

    Timecode operator+ ( const Timecode& ) const;
    Timecode operator- ( const Timecode& ) const;

    bool parse( const string&, string* = NULL );

    void reset();

    void setScale    ( double );
    void setDuration ( uint64_t, double = 0.0 );
    void setFormat   ( Format );

    void setHours      ( uint64_t );
    void setMinutes    ( uint64_t );
    void setSeconds    ( uint64_t );
    void setSubseconds ( uint64_t );

private:
    uint64_t convertDuration( const Timecode& ) const;
    void recompute();
};

///////////////////////////////////////////////////////////////////////////////

}} // namespace mp4v2::util

#endif // MP4V2_UTIL_TIMECODE_H


text:
exports.run = (client, guild) => {
  if (!guild.available) return;
  client.configuration.insert(client, guild);
};


text:
import { createHash } from "crypto"
import { readJson, realpathSync } from "fs-extra"
import * as fs from "fs/promises"
import { isCI as isCi } from "ci-info"
import { tmpdir } from "os"
import * as path from "path"
import { deleteOldElectronVersion, downloadAllRequiredElectronVersions } from "./downloadElectron"

const baseDir = process.env.APP_BUILDER_TMP_DIR || realpathSync(tmpdir())
const APP_BUILDER_TMP_DIR = path.join(baseDir, `et-${createHash("md5").update(__dirname).digest("hex")}`)

runTests().catch(error => {
  console.error(error.stack || error)
  process.exit(1)
})

async function runTests() {
  await fs.rm(APP_BUILDER_TMP_DIR, { recursive: true, force: true })
  await fs.mkdir(APP_BUILDER_TMP_DIR, { recursive: true })
  if (!process.env.CIRCLECI) {
    await Promise.all([deleteOldElectronVersion(), downloadAllRequiredElectronVersions()])
  }

  const testFiles = process.env.TEST_FILES

  const testPatterns: Array<string> = []
  if (testFiles != null && testFiles.length !== 0) {
    console.log(`Test files: ${testFiles}`)
    testPatterns.push(...testFiles.split(","))
  } else if (process.env.CIRCLE_NODE_INDEX != null && process.env.CIRCLE_NODE_INDEX.length !== 0) {
    const circleNodeIndex = parseInt(process.env.CIRCLE_NODE_INDEX!!, 10)
    if (circleNodeIndex === 0) {
      testPatterns.push("debTest")
      testPatterns.push("fpmTest")
      testPatterns.push("winPackagerTest")
      testPatterns.push("winCodeSignTest")
      testPatterns.push("macArchiveTest")
      testPatterns.push("webInstallerTest")
    } else if (circleNodeIndex === 1) {
      testPatterns.push("oneClickInstallerTest")
    } else if (circleNodeIndex === 2) {
      testPatterns.push("snapTest")
      testPatterns.push("macPackagerTest")
      testPatterns.push("msiTest")
      testPatterns.push("portableTest")
      testPatterns.push("BuildTest")
      testPatterns.push("squirrelWindowsTest")
    } else {
      testPatterns.push("assistedInstallerTest")
      testPatterns.push("macCodeSignTest")
    }
    console.log(`Test files for node ${circleNodeIndex}: ${testPatterns.join(", ")}`)
  }

  process.env.APP_BUILDER_TMP_DIR = APP_BUILDER_TMP_DIR

  const rootDir = path.join(__dirname, "..", "..")

  process.chdir(rootDir)

  const config = (await readJson(path.join(rootDir, "package.json"))).jest
  // use custom cache dir to avoid https://github.com/facebook/jest/issues/1903#issuecomment-261212137
  config.cacheDirectory = process.env.JEST_CACHE_DIR || "/tmp/jest-electron-builder-tests"
  config.bail = process.env.TEST_BAIL === "true"

  let runInBand = false
  const scriptArgs = process.argv.slice(2)

  const testPathIgnorePatterns = config.testPathIgnorePatterns
  if (scriptArgs.length > 0) {
    for (const scriptArg of scriptArgs) {
      console.log(`custom opt: ${scriptArg}`)
      if ("runInBand" === scriptArg) {
        runInBand = true
      } else if (scriptArg.includes("=")) {
        const equalIndex = scriptArg.indexOf("=")
        const envName = scriptArg.substring(0, equalIndex)
        let envValue = scriptArg.substring(equalIndex + 1)
        if (envValue === "isCi") {
          envValue = isCi ? "true" : "false"
        }

        process.env[envName] = envValue
        console.log(`Custom env ${envName}=${envValue}`)

        if (envName === "ALL_TESTS" && envValue === "false") {
          config.cacheDirectory += "-basic"
        }
      } else if (scriptArg.startsWith("skip")) {
        if (!isCi) {
          const suffix = scriptArg.substring("skip".length)
          if (scriptArg === "skipArtifactPublisher") {
            testPathIgnorePatterns.push("[\\/]{1}ArtifactPublisherTest.js$")
            config.cacheDirectory += `-${suffix}`
          } else {
            throw new Error(`Unknown opt ${scriptArg}`)
          }
        }
      } else {
        config[scriptArg] = true
      }
    }
  }

  const jestOptions: any = {
    verbose: true,
    updateSnapshot: process.env.UPDATE_SNAPSHOT === "true",
    config,
    runInBand,
    projects: [rootDir],
  }

  if (testPatterns.length > 0) {
    jestOptions.testPathPattern = testPatterns.map(it => (it.endsWith(".ts") || it.endsWith("*") ? it : `${it}\\.ts$`))
  }
  if (process.env.CIRCLECI != null || process.env.TEST_JUNIT_REPORT === "true") {
    jestOptions.reporters = ["default", "jest-junit"]
  }

  const testResult = await require("@jest/core").runCLI(jestOptions, jestOptions.projects)
  const exitCode = testResult.results == null || testResult.results.success ? 0 : testResult.globalConfig.testFailureExitCode
  if (isCi) {
    process.exit(exitCode)
  }

  await fs.rm(APP_BUILDER_TMP_DIR, { recursive: true, force: true })
  process.exitCode = exitCode
  if (testResult.globalConfig.forceExit) {
    process.exit(exitCode)
  }
}


text:
package org.apache.ignite.compatibility.testframework.util;

import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Provides some useful methods to work with Maven.
 */
public class MavenUtils {
    /** Path to Maven local repository. For caching. */
    private static String locRepPath = null;

    /** */
    private static final String GG_MVN_REPO = "http://www.gridgainsystems.com/nexus/content/repositories/external";

    /** Set this flag to true if running PDS compatibility tests locally. */
    private static boolean useGgRepo;

    /**
     * Gets a path to an artifact with given version and groupId=org.apache.ignite and artifactId={@code artifactId}.
     *

     * At first, artifact is looked for in the Maven local repository, if it isn't exists there, it will be downloaded
     * and stored via Maven.
     *

     *
     * @param groupId group name, e.g. 'org.apache.ignite'.
     * @param ver Version of ignite or 3rd party library artifact.
     * @param classifier Artifact classifier.
     * @return Path to the artifact.
     * @throws Exception In case of an error.
     * @see #getPathToArtifact(String)
     */
    public static String getPathToIgniteArtifact(@NotNull String groupId,
        @NotNull String artifactId, @NotNull String ver,
        @Nullable String classifier) throws Exception {
        String artifact = groupId +
            ":" + artifactId + ":" + ver;

        if (classifier != null)
            artifact += ":jar:" + classifier;

        return getPathToArtifact(artifact);
    }

    /**
     * Gets a path to an artifact with given identifier.
     *
     * At first, artifact is looked for in the Maven local repository, if it isn't exists there, it will be downloaded
     * and stored via Maven.
     *
     * @param artifact Artifact identifier, must match pattern [groupId:artifactId:version[:packaging[:classifier]]].
     * @return Path to the artifact.
     * @throws Exception In case of an error.
     */
    public static String getPathToArtifact(@NotNull String artifact) throws Exception {
        String[] names = artifact.split(":");

        assert names.length >= 3;

        String groupId = names[0];
        String artifactId = names[1];
        String version = names[2];
        String packaging = names.length > 3 ? names[3] : null;
        String classifier = names.length > 4 ? names[4] : null;

        String jarFileName = String.format("%s-%s%s.%s",
            artifactId,
            version,
            (classifier == null ? "" : "-" + classifier),
            (packaging == null ? "jar" : packaging)
        );

        String pathToArtifact = getMavenLocalRepositoryPath() + File.separator +
            groupId.replace(".", File.separator) + File.separator +
            artifactId.replace(".", File.separator) + File.separator +
            version + File.separator + jarFileName;

        if (Files.notExists(Paths.get(pathToArtifact)))
            downloadArtifact(artifact);

        return pathToArtifact;
    }

    /**
     * Gets a path to the Maven local repository.
     *
     * @return Path to the Maven local repository.
     * @throws Exception In case of an error.
     */
    public static String getMavenLocalRepositoryPath() throws Exception {
        if (locRepPath == null)
            locRepPath = defineMavenLocalRepositoryPath();

        return locRepPath;
    }

    /**
     * Defines a path to the Maven local repository.
     *
     * @return Path to the Maven local repository.
     * @throws Exception In case of an error.
     */
    private static String defineMavenLocalRepositoryPath() throws Exception {
        String output = exec(buildMvnCommand() + " help:effective-settings");

        int endTagPos = output.indexOf("</localRepository>");

        assert endTagPos >= 0 : "Couldn't define path to Maven local repository";

        return output.substring(output.lastIndexOf('>', endTagPos) + 1, endTagPos);
    }

    /**
     * Downloads and stores in local repository an artifact with given identifier.
     *
     * @param artifact Artifact identifier, must match pattern [groupId:artifactId:version].
     * @throws Exception In case of an error.
     */
    private static void downloadArtifact(String artifact) throws Exception {
        X.println("Downloading artifact... Identifier: " + artifact);

        // Default platform independ path for maven settings file.
        Path localProxyMavenSettings = Paths.get(System.getProperty("user.home"), ".m2", "local-proxy.xml");

        String localProxyMavenSettingsFromEnv = System.getenv("LOCAL_PROXY_MAVEN_SETTINGS");

        SB mavenCommandArgs = new SB(" org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -Dartifact=" + artifact);

        if (!F.isEmpty(localProxyMavenSettingsFromEnv))
            localProxyMavenSettings = Paths.get(localProxyMavenSettingsFromEnv);

        if (Files.exists(localProxyMavenSettings))
            mavenCommandArgs.a(" -s " + localProxyMavenSettings.toString());
        else
            mavenCommandArgs.a(useGgRepo ? " -DremoteRepositories=" + GG_MVN_REPO : "");

        exec(buildMvnCommand() + mavenCommandArgs.toString());

        X.println("Download is finished");
    }

    /**
     * Executes given command in operation system.
     *
     * @param cmd Command to execute.
     * @return Output of result of executed command.
     * @throws Exception In case of an error.
     */
    private static String exec(String cmd) throws Exception {
        ProcessBuilder pb = new ProcessBuilder();
        pb.redirectErrorStream(true);

        pb.command(U.isWindows() ?
            new String[] {"cmd", "/c", cmd} :
            new String[] {"/bin/bash", "-c", cmd});

        final Process p = pb.start();

        Future<String> fut = Executors.newSingleThreadExecutor().submit(new Callable<String>() {
            @Override public String call() throws Exception {
                String output = CharStreams.toString(new InputStreamReader(p.getInputStream(), Charsets.UTF_8));

                p.waitFor();

                return output;
            }
        });

        String output = null;

        try {
            output = fut.get(5, TimeUnit.MINUTES);

            int exitVal = p.exitValue();

            if (exitVal != 0)
                throw new Exception(String.format("Abnormal exit value of %s for pid %s", exitVal, U.jvmPid()));

            return output;
        }
        catch (Exception e) {
            p.destroy();

            X.printerrln("Command='" + cmd + "' couldn't be executed: " + output, Charsets.UTF_8, e);

            throw e;
        }
    }

    /**
     * @return Maven executable command.
     */
    private static String buildMvnCommand() {
        String m2Home = System.getenv("M2_HOME");

        if (m2Home == null)
            m2Home = System.getProperty("M2_HOME");

        if (m2Home == null)
            return "mvn";

        return m2Home + "/bin/mvn";
    }
}


text:
/**
 * node-wegene
 *
 * This file was automatically generated by APIMATIC BETA v2.0 on 02/19/2016
 */

var request = require('../Http/Client/RequestClient'),
    configuration = require('../configuration'),
    APIHelper = require('../APIHelper');

var Allele = {

    /**
     * Allele data
     * @param {string} profileId    Required parameter: Genetic Profile Id
     * @param {array} locations    Required parameter: Allele locations in array
     * @param {function} callback    Required parameter: Callback function in the form of function(error, response)
     *
     * @return {mixed}
     */
    getAllele : function(profileId, locations, callback){

        //prepare query string for API call;
        var baseUri = configuration.BASEURI;

        var queryBuilder = baseUri + "/genotypes/{profile_id}";

        //Process template parameters
        queryBuilder = APIHelper.appendUrlWithTemplateParameters(queryBuilder, {
            "profile_id" : profileId
        });

        //validate and preprocess url
        var queryUrl = APIHelper.cleanUrl(queryBuilder);

        //prepare headers
        var headers = {
            "accept" : "application/json",
            "Authorization" : "Bearer " + configuration.oAuthAccessToken
        };

        //prepare form data
        var form = {
            "locations" : locations
        };

        //Remove null values
        APIHelper.cleanObject(form);

        //Construct the request
        var options = {
            queryUrl: queryUrl,
            method: "POST",
            headers: headers,
            form : form,
        };

        //Build the response processing.
        function cb(error, response, context) {
            if(error){
                callback({errorMessage: error.message, errorCode: error.code},null,context);
            }else if (response.statusCode >= 200 && response.statusCode <= 206) {
                callback(null,JSON.parse(response.body),context);
            }else{
                //Error handling using HTTP status codes
                callback({errorMessage: "HTTP Response Not OK", errorCode: response.statusCode, errorResponse:response.body},null,context);
            }
        }
        request(options, cb);

    }

};

module.exports = Allele;


text:
package com.hubspot.singularity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;

public class SingularityTaskShellCommandUpdate {

  public enum UpdateType {
    INVALID(true), ACKED(false), STARTED(false), FINISHED(true), FAILED(true);

    private final boolean finished;

    UpdateType(boolean finished) {
      this.finished = finished;
    }

    public boolean isFinished() {
      return finished;
    }
  }

  private final SingularityTaskShellCommandRequestId shellRequestId;
  private final long timestamp;
  private final Optional<String> message;
  private final Optional<String> outputFilename;
  private final UpdateType updateType;

  @JsonCreator
  public SingularityTaskShellCommandUpdate(@JsonProperty("shellRequestId") SingularityTaskShellCommandRequestId shellRequestId, @JsonProperty("timestamp") long timestamp,
      @JsonProperty("message") Optional<String> message, @JsonProperty("outputFilename") Optional<String> outputFilename, @JsonProperty("updateType") UpdateType updateType) {
    this.shellRequestId = shellRequestId;
    this.timestamp = timestamp;
    this.message = message;
    this.outputFilename = outputFilename;
    this.updateType = updateType;
  }

  public SingularityTaskShellCommandRequestId getShellRequestId() {
    return shellRequestId;
  }

  public long getTimestamp() {
    return timestamp;
  }

  public Optional<String> getMessage() {
    return message;
  }

  public Optional<String> getOutputFilename() {
    return outputFilename;
  }

  public UpdateType getUpdateType() {
    return updateType;
  }

  @Override
  public String toString() {
    return "SingularityTaskShellCommandUpdate{" +
        "shellRequestId=" + shellRequestId +
        ", timestamp=" + timestamp +
        ", message=" + message +
        ", outputFilename=" + outputFilename +
        ", updateType=" + updateType +
        '}';
  }
}


text: Simple analogue stack overflow.


text:
package org.zstack.header.storage.primary;

import org.zstack.header.message.MessageReply;

/**
 */
public class CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply extends MessageReply {
    private String installPath;
    private long size;
    private long actualSize;

    public long getActualSize() {
        return actualSize;
    }

    public void setActualSize(long actualSize) {
        this.actualSize = actualSize;
    }

    public String getInstallPath() {
        return installPath;
    }

    public void setInstallPath(String installPath) {
        this.installPath = installPath;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Smithson. Contr. bot. 25: 31 (1975)

#### Original name
Parmelina degelii Hale

### Remarks
null


text:
package edu.umd.cs.psl.model.set.membership;

import edu.umd.cs.psl.model.argument.GroundTerm;

public class SoftTermMembership extends SoftMembership<GroundTerm> implements TermMembership {

}


text:
<?php

namespace AppBundle\Serializer\Normalizer;

use AppBundle\Serializer\Exception\DepthException;
use AppBundle\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\{
    NormalizerInterface, ObjectNormalizer
};

/**
 * Class EntityNormalizer
 * @package AppBundle\Serializer\Normalizer
 * @author Rafał Lorenz <vardius@gmail.com>
 */
class EntityNormalizer extends ObjectNormalizer
{
    const DEPTH_LEVEL = 1;
    const MAX_DEPTH_UNSET = -1;
    /**
     * @var array
     */
    protected $attributesCache = array();

    /**
     * @var callable
     */
    protected $maxDepthHandler;

    protected $helper;

    public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null)
    {
        parent::__construct($classMetadataFactory, $nameConverter, $propertyAccessor);

        $this->setCircularReferenceHandler(function ($object) {
            return method_exists($object, 'getId') ? $object->getId() : (string)$object;
        });

        $this->setMaxDepthHandler(function ($object) {

            if (method_exists($object, 'getId')) {
                return $object->getId();
            }

            if ($object instanceof \DateTime) {
                return $object->getTimestamp();
            }

            if (is_array($object)) {
                return $object;
            }

            return null;
        });
    }

    /**
     * Gets attributes to normalize using groups.
     *
     * @param string|object $classOrObject
     * @param array $context Context options for the normalizer
     *
     * @return string[]|AttributeMetadata[]|bool
     */
    protected function getMaxDepth($classOrObject, array $context)
    {
        $maxDepths = [];
        foreach ($this->classMetadataFactory->getMetadataFor($classOrObject)->getAttributesMetadata() as $attributeMetadata) {
            $depth = $attributeMetadata->getDepth();
            if ($depth > 0) {
                $maxDepths[$attributeMetadata->getName()] = $depth + $context['depth'];
            }
        }

        return $maxDepths;
    }

    /**
     * Handles max depth.
     *
     * @param object $object object to normalize
     * @param array $context Context options for the normalizer
     *
     * @return mixed
     *
     * @throws DepthException
     */
    protected function handleMaxDepth($object, array $context)
    {
        if ($this->maxDepthHandler) {
            return call_user_func($this->maxDepthHandler, $object);
        }

        throw new DepthException(sprintf('Max depth has been detected (configured limit: %d).', $context['max_depth']));
    }

    /**
     * Set max depth handler.
     *
     * @param callable $maxDepthHandler
     *
     * @return self
     */
    public function setMaxDepthHandler(callable $maxDepthHandler)
    {
        $this->maxDepthHandler = $maxDepthHandler;

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function normalize($object, $format = null, array $context = array())
    {
        if (!isset($context['cache_key'])) {
            $context['cache_key'] = $this->getCacheKey($context);
        }

        if (!isset($context['depth'])) {
            $context['depth'] = static::DEPTH_LEVEL;
        }

        if (!isset($context['max_depth'])) {
            $context['max_depth'] = static::MAX_DEPTH_UNSET;
        }

        if (!isset($context['max_depths'])) {
            $context['max_depths'] = [];
        }

        if ($context['max_depth'] === static::MAX_DEPTH_UNSET) {
            $context['max_depths'] = $this->getMaxDepth($object, $context);
        }

        if ($this->isCircularReference($object, $context)) {
            return $this->handleCircularReference($object);
        }

        $data = array();
        $attributes = $this->getAttributes($object, $context);

        foreach ($attributes as $attribute) {
            if (in_array($attribute, $this->ignoredAttributes)) {
                continue;
            }

            $attributeValue = $this->propertyAccessor->getValue($object, $attribute);

            if (isset($this->callbacks[$attribute])) {
                $attributeValue = call_user_func($this->callbacks[$attribute], $attributeValue);
            }

            $attributeValue = $attributeValue instanceof \DateTime
                ? $attributeValue->getTimestamp()
                : $attributeValue;

            if (null !== $attributeValue && !is_scalar($attributeValue)) {
                if (!$this->serializer instanceof NormalizerInterface) {
                    throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a AppBundle\Serializer\Normalizer\ObjectNormalizer', $attribute));
                }

                if ($context['max_depth'] === static::MAX_DEPTH_UNSET && isset($context['max_depths'][$attribute])) {
                    $context['max_depth'] = $context['max_depths'][$attribute];
                }

                if ($context['max_depth'] !== static::MAX_DEPTH_UNSET && $context['depth'] >= $context['max_depth']) {
                    $attributeValue = $this->handleMaxDepth($attributeValue, $context);
                } else {
                    $newContext = $context;
                    $newContext['depth'] = $newContext['depth'] + 1;
                    $attributeValue = $this->serializer->normalize($attributeValue, $format, $newContext);
                }
            }

            if ($this->nameConverter) {
                $attribute = $this->nameConverter->normalize($attribute);
            }

            if ($attributeValue !== null) {
                $data[$attribute] = $attributeValue;
            }
        }

        return $data;
    }

    protected function getCacheKey(array $context)
    {
        try {
            return md5(serialize($context));
        } catch (\Exception $exception) {
            // The context cannot be serialized, skip the cache
            return false;
        }
    }

    /**
     * Gets and caches attributes for this class and context.
     *
     * @param object $object
     * @param array $context
     *
     * @return string[]
     */
    protected function getAttributes($object, array $context)
    {
        $class = get_class($object);
        $key = $class . '-' . $context['cache_key'];

        if (isset($this->attributesCache[$key])) {
            return $this->attributesCache[$key];
        }

        $allowedAttributes = $this->getAllowedAttributes($object, $context, true);

        if (false !== $allowedAttributes) {
            if ($context['cache_key']) {
                $this->attributesCache[$key] = $allowedAttributes;
            }

            return $allowedAttributes;
        }

        if (isset($this->attributesCache[$class])) {
            return $this->attributesCache[$class];
        }

        return $this->attributesCache[$class] = $this->extractAttributes($object);
    }

    /**
     * Extracts attributes for this class and context.
     *
     * @param object $object
     *
     * @return string[]
     */
    protected function extractAttributes($object)
    {
        // If not using groups, detect manually
        $attributes = array();

        // methods
        $reflClass = new \ReflectionClass($object);
        foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
            if (
                $reflMethod->getNumberOfRequiredParameters() !== 0 ||
                $reflMethod->isStatic() ||
                $reflMethod->isConstructor() ||
                $reflMethod->isDestructor()
            ) {
                continue;
            }

            $name = $reflMethod->name;

            if (0 === strpos($name, 'get') || 0 === strpos($name, 'has')) {
                // getters and hassers
                $attributes[lcfirst(substr($name, 3))] = true;
            } elseif (strpos($name, 'is') === 0) {
                // issers
                $attributes[lcfirst(substr($name, 2))] = true;
            }
        }

        // properties
        foreach ($reflClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $reflProperty) {
            if ($reflProperty->isStatic()) {
                continue;
            }

            $attributes[$reflProperty->name] = true;
        }

        return array_keys($attributes);
    }
}


text:
package "httpd" do
  action :install
end

service "httpd" do
  action [ :enable, :start ]
end

template "/var/www/html/index.html" do
  source "index.html.erb"
  mode "0644"
end


text:
module XXP.State ( XXP
                   -- Some convenience exports for stuff you might want to do
                   -- in the XXP monad
                 , get
                 , put
                 , liftIO
                 , throwIO
                 ) where

import XXP.Experiment
import Control.Monad.Trans.State.Strict
import Control.Monad.IO.Class
import Control.Exception.Lifted

type XXP = StateT XPState IO


text:
package pro.schmid.android.androidonfire;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

import pro.schmid.android.androidonfire.callbacks.DataEvent;
import pro.schmid.android.androidonfire.callbacks.EventType;
import pro.schmid.android.androidonfire.callbacks.SynchonizedToServer;
import pro.schmid.android.androidonfire.callbacks.Transaction;
import pro.schmid.android.androidonfire.callbacks.TransactionComplete;
import android.app.Activity;
import android.os.Looper;
import android.util.Log;
import android.util.SparseArray;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.google.gson.JsonElement;
import com.google.gson.JsonNull;

/**
 * Class used internally to access the {@link WebView}.
 */
class FirebaseJavaScriptInterface {
	private static final String TAG = FirebaseJavaScriptInterface.class.getSimpleName();

	private final WebView mWebView;
	private final Activity mActivity;

	private final SparseArray<DataEvent> mListenersIds = new SparseArray<DataEvent>();
	private final SparseArray<SynchonizedToServer> mSynchronizedToServer = new SparseArray<SynchonizedToServer>();
	private final SparseArray<Transaction> mTransactions = new SparseArray<Transaction>();
	private final SparseArray<TransactionComplete> mTransactionsComplete = new SparseArray<TransactionComplete>();

	// Endpoint => Event type => Callbacks => method id list
	private final ConcurrentHashMap<String, Map<EventType, Map<DataEvent, List<Integer>>>> mListenersMap = new ConcurrentHashMap<String, Map<EventType, Map<DataEvent, List<Integer>>>>();

	// Endpoint => Query => Event type => Callbacks => method id list
	private final ConcurrentHashMap<String, Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>>> mQueryListenersMap = new ConcurrentHashMap<String, Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>>>();

	// Counter for the methods
	private final AtomicInteger mMethodCounter = new AtomicInteger();

	protected FirebaseJavaScriptInterface(WebView webView, Activity activity) {
		this.mWebView = webView;
		this.mActivity = activity;
	}

	protected void set(String endpoint, JsonElement obj, SynchonizedToServer onComplete) {

		if (obj == null) {
			obj = JsonNull.INSTANCE;
		}

		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "set('" + endpoint + "', " + obj.toString() + ", " + methodId + ")";
		} else {
			method = "set('" + endpoint + "', " + obj.toString() + ")";
		}
		loadMethod(method);
	}

	protected void update(String endpoint, JsonElement obj, SynchonizedToServer onComplete) {

		if (obj == null) {
			obj = JsonNull.INSTANCE;
		}

		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "update('" + endpoint + "', " + obj.toString() + ", " + methodId + ")";
		} else {
			method = "update('" + endpoint + "', " + obj.toString() + ")";
		}

		loadMethod(method);
	}

	protected void remove(String endpoint, SynchonizedToServer onComplete) {
		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "remove('" + endpoint + "', " + methodId + ")";
		} else {
			method = "remove('" + endpoint + "')";
		}

		loadMethod(method);
	}

	private String mPushName = null;
	private final Semaphore mSemaphore = new Semaphore(0, true);

	protected synchronized Firebase push(Firebase endpoint, JsonElement obj, SynchonizedToServer onComplete) {

		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "push('" + endpoint.toString() + "', " + obj.toString() + ", " + methodId + ")";
		} else if (obj != null) {
			method = "push('" + endpoint.toString() + "', " + obj.toString() + ")";
		} else {
			method = "push('" + endpoint.toString() + "')";
		}
		loadMethod(method);

		try {
			mSemaphore.acquire();
		} catch (InterruptedException e) {
			return null;
		}

		Firebase newBase = endpoint.child(mPushName);
		return newBase;
	}

	@JavascriptInterface
	public void pushed(String name) {
		mPushName = name;
		mSemaphore.release();
	}

	protected void setWithPriority(String endpoint, JsonElement obj, String priority, SynchonizedToServer onComplete) {

		if (obj == null) {
			obj = JsonNull.INSTANCE;
		}

		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "setWithPriority('" + endpoint + "', " + obj.toString() + ", '" + priority + "', " + methodId + ")";
		} else {
			method = "setWithPriority('" + endpoint + "', " + obj.toString() + ", '" + priority + "')";
		}
		loadMethod(method);
	}

	protected void setPriority(String endpoint, String priority, SynchonizedToServer onComplete) {
		String method = null;
		if (onComplete != null) {
			int methodId = mMethodCounter.incrementAndGet();
			mSynchronizedToServer.put(methodId, onComplete);
			method = "setPriority('" + endpoint + "', '" + priority + "', " + methodId + ")";
		} else {
			method = "setPriority('" + endpoint + "', '" + priority + "')";
		}
		loadMethod(method);
	}

	protected void transaction(String endpoint, Transaction transaction, TransactionComplete onComplete) {
		int methodId = mMethodCounter.incrementAndGet();
		mTransactions.put(methodId, transaction);
		mTransactionsComplete.put(methodId, onComplete);

		String method = "transaction('" + endpoint + "', " + methodId + ")";
		loadMethod(method);
	}

	@JavascriptInterface
	public String callTransactionMethod(String endpoint, int methodId, String json) {
		Transaction transaction = mTransactions.get(methodId);

		if (transaction == null) {
			return JsonNull.INSTANCE.toString();
		}

		JsonElement obj = FirebaseJsonParser.getInstance().parse(json);

		JsonElement ret = transaction.transaction(obj);

		if (ret != null) {
			return ret.toString();
		} else {
			return null;
		}
	}

	@JavascriptInterface
	public void transactionComplete(String endpoint, int methodId, boolean success, String val, String reason) {

		Firebase parent = FirebaseEngine.getInstance().newFirebase(endpoint);
		DataSnapshot snapshot = new DataSnapshot(parent, val);

		TransactionComplete transactionComplete = mTransactionsComplete.get(methodId);

		if (transactionComplete != null) {
			transactionComplete.onComplete(success, snapshot, reason);
		}

		mTransactions.remove(methodId);
		mTransactionsComplete.remove(methodId);
	}

	protected void setOnDisconnect(String endpoint, JsonElement obj) {

		if (obj == null) {
			obj = JsonNull.INSTANCE;
		}

		String method = "setOnDisconnect('" + endpoint + "', " + obj.toString() + ")";
		loadMethod(method);
	}

	protected void removeOnDisconnect(String endpoint) {
		String method = "removeOnDisconnect('" + endpoint + "')";
		loadMethod(method);
	}

	protected void on(String endpoint, EventType ev, DataEvent callback) {
		int methodId = mMethodCounter.incrementAndGet();
		this.mListenersIds.put(methodId, callback);
		putCallBack(endpoint, ev, callback, methodId);

		String method = "onFirebase('" + endpoint + "', '" + ev + "', " + methodId + ")";
		loadMethod(method);
	}

	private void putCallBack(String endpoint, EventType ev, DataEvent callback, int methodId) {
		// Endpoint => event type
		Map<EventType, Map<DataEvent, List<Integer>>> child = this.mListenersMap.get(endpoint);
		if (child == null) {
			child = new ConcurrentHashMap<EventType, Map<DataEvent, List<Integer>>>();
			this.mListenersMap.put(endpoint, child);
		}

		// event type => callbacks
		Map<DataEvent, List<Integer>> callbacks = child.get(ev);
		if (callbacks == null) {
			callbacks = new ConcurrentHashMap<DataEvent, List<Integer>>();
			child.put(ev, callbacks);
		}

		// Callback => method ids list
		List<Integer> list = callbacks.get(callback);
		if (list == null) {
			list = new ArrayList<Integer>();
			callbacks.put(callback, list);
		}

		list.add(methodId);
	}

	protected void off(String endpoint) {
		removeMethods(endpoint);

		String method = "offFirebase('" + endpoint.toString() + "')";
		loadMethod(method);
	}

	protected void off(String endpoint, EventType ev) {
		removeMethods(endpoint, ev);

		String method = "offFirebase('" + endpoint.toString() + "', '" + ev + "')";
		loadMethod(method);
	}

	protected void off(String endpoint, EventType ev, DataEvent callback) {
		Integer methodId = removeMethod(endpoint, ev, callback);

		if (methodId == null) {
			return;
		}

		String method = "offFirebase('" + endpoint.toString() + "', '" + ev + "', " + methodId + ")";
		loadMethod(method);
	}

	private void removeMethods(String endpoint) {
		Map<EventType, Map<DataEvent, List<Integer>>> parent = this.mListenersMap.remove(endpoint);
		if (parent == null) {
			return;
		}

		for (Map<DataEvent, List<Integer>> map : parent.values()) {
			for (List<Integer> item : map.values()) {
				for (Integer integer : item) {
					this.mListenersIds.remove(integer);
				}
			}
		}
	}

	private void removeMethods(String endpoint, EventType ev) {
		Map<EventType, Map<DataEvent, List<Integer>>> child = this.mListenersMap.get(endpoint);
		if (child == null) {
			return;
		}

		Map<DataEvent, List<Integer>> map = child.remove(ev);
		for (List<Integer> item : map.values()) {
			for (Integer integer : item) {
				this.mListenersIds.remove(integer);
			}
		}
	}

	private Integer removeMethod(String endpoint, EventType ev, DataEvent callback) {
		Map<EventType, Map<DataEvent, List<Integer>>> child = this.mListenersMap.get(endpoint);
		if (child == null) {
			return null;
		}

		Map<DataEvent, List<Integer>> callbacks = child.get(ev);
		if (callbacks == null) {
			return null;
		}

		List<Integer> list = callbacks.get(callback);
		if (list == null) {
			return null;
		}

		if (list.size() <= 0) {
			return null;
		}

		Integer id = list.remove(0);
		if (id != null) {
			this.mListenersIds.remove(id);
		}
		return id;
	}

	protected void once(final String endpoint, final EventType ev, final DataEvent callback) {
		this.on(endpoint, ev, new DataEvent() {
			@Override
			public void callback(DataSnapshot snapshot, String prevChildName) {
				off(endpoint, ev, this);
				callback.callback(snapshot, prevChildName);
			}
		});
	}

	protected void onQuery(String endpoint, Query query, EventType ev, DataEvent callback) {

		int methodId = mMethodCounter.incrementAndGet();
		this.mListenersIds.put(methodId, callback);
		putCallBack(endpoint, query, ev, callback, methodId);

		StringBuilder sb = new StringBuilder();
		sb.append("onQuery('" + endpoint + "', '" + ev + "', " + methodId);
		addQueryToMethod(query, sb);
		sb.append(")");

		String method = sb.toString();
		loadMethod(method);
	}

	private void putCallBack(String endpoint, Query query, EventType ev, DataEvent callback, int methodId) {
		// Endpoint => Query
		Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>> endpointChild = this.mQueryListenersMap.get(endpoint);
		if (endpointChild == null) {
			endpointChild = new ConcurrentHashMap<Query, Map<EventType, Map<DataEvent, List<Integer>>>>();
			this.mQueryListenersMap.put(endpoint, endpointChild);
		}

		// Query => event type
		Map<EventType, Map<DataEvent, List<Integer>>> queryChild = endpointChild.get(query);
		if (queryChild == null) {
			queryChild = new ConcurrentHashMap<EventType, Map<DataEvent, List<Integer>>>();
			endpointChild.put(query, queryChild);
		}

		// event type => callbacks
		Map<DataEvent, List<Integer>> callbacks = queryChild.get(ev);
		if (callbacks == null) {
			callbacks = new ConcurrentHashMap<DataEvent, List<Integer>>();
			queryChild.put(ev, callbacks);
		}

		// Callback => method ids list
		List<Integer> list = callbacks.get(callback);
		if (list == null) {
			list = new ArrayList<Integer>();
			callbacks.put(callback, list);
		}

		list.add(methodId);
	}

	protected void offQuery(String endpoint, Query query) {

		removeMethods(endpoint, query);

		StringBuilder sb = new StringBuilder();
		sb.append("offQuery('" + endpoint + "', undefined, undefined");
		addQueryToMethod(query, sb);
		sb.append(")");

		String method = sb.toString();
		loadMethod(method);

	}

	protected void offQuery(String endpoint, Query query, EventType ev) {

		removeMethods(endpoint, query, ev);

		StringBuilder sb = new StringBuilder();
		sb.append("offQuery('" + endpoint + "', '" + ev + "', undefined");
		addQueryToMethod(query, sb);
		sb.append(")");

		String method = sb.toString();
		loadMethod(method);
	}

	protected void offQuery(String endpoint, Query query, EventType ev, DataEvent callback) {

		Integer methodId = removeMethod(endpoint, query, ev, callback);

		if (methodId == null) {
			return;
		}

		StringBuilder sb = new StringBuilder();
		sb.append("offQuery('" + endpoint + "', '" + ev + "', " + methodId);
		addQueryToMethod(query, sb);
		sb.append(")");

		String method = sb.toString();
		loadMethod(method);
	}

	private void removeMethods(String endpoint, Query query) {
		Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>> parent = this.mQueryListenersMap.remove(endpoint);
		if (parent == null) {
			return;
		}

		Map<EventType, Map<DataEvent, List<Integer>>> child = parent.get(query);
		if (child == null) {
			return;
		}

		for (Map<DataEvent, List<Integer>> map : child.values()) {
			for (List<Integer> item : map.values()) {
				for (Integer integer : item) {
					this.mListenersIds.remove(integer);
				}
			}
		}
	}

	private void removeMethods(String endpoint, Query query, EventType ev) {
		Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>> parent = this.mQueryListenersMap.get(endpoint);
		if (parent == null) {
			return;
		}

		Map<EventType, Map<DataEvent, List<Integer>>> child = parent.get(query);
		if (child == null) {
			return;
		}

		Map<DataEvent, List<Integer>> map = child.remove(ev);
		for (List<Integer> item : map.values()) {
			for (Integer integer : item) {
				this.mListenersIds.remove(integer);
			}
		}
	}

	private Integer removeMethod(String endpoint, Query query, EventType ev, DataEvent callback) {
		Map<Query, Map<EventType, Map<DataEvent, List<Integer>>>> parent = this.mQueryListenersMap.get(endpoint);
		if (parent == null) {
			return null;
		}

		Map<EventType, Map<DataEvent, List<Integer>>> child = parent.get(query);
		if (child == null) {
			return null;
		}

		Map<DataEvent, List<Integer>> callbacks = child.get(ev);
		if (callbacks == null) {
			return null;
		}

		List<Integer> list = callbacks.get(callback);
		if (list == null) {
			return null;
		}

		if (list.size() <= 0) {
			return null;
		}

		Integer id = list.remove(0);
		if (id != null) {
			this.mListenersIds.remove(id);
		}
		return id;
	}

	protected void onceQuery(final String endpoint, final Query query, final EventType ev, final DataEvent callback) {
		this.onQuery(endpoint, query, ev, new DataEvent() {
			@Override
			public void callback(DataSnapshot snapshot, String prevChildName) {
				offQuery(endpoint, query, ev, this);
				callback.callback(snapshot, prevChildName);
			}
		});
	}

	private void addQueryToMethod(Query query, StringBuilder sb) {
		if (query.mLimit > -1) {
			sb.append(", " + query.mLimit);
		} else {
			sb.append(", undefined");
		}

		sb.append(", " + query.mStartSpecified.toString());

		if (query.mStartPriority != null) {
			sb.append(", '" + query.mStartPriority + "'");
		} else {
			sb.append(", undefined");
		}

		if (query.mStartName != null) {
			sb.append(", '" + query.mStartName + "'");
		} else {
			sb.append(", undefined");
		}

		sb.append(", " + query.mEndSpecified.toString());

		if (query.mEndPriority != null) {
			sb.append(", '" + query.mEndPriority + "'");
		} else {
			sb.append(", undefined");
		}

		if (query.mEndName != null) {
			sb.append(", '" + query.mEndName + "'");
		} else {
			sb.append(", undefined");
		}
	}

	@JavascriptInterface
	public void onEvent(String endpoint, int methodId, String val, String priority, String prevChildName) {
		DataEvent listener;
		if ((listener = this.mListenersIds.get(methodId)) != null) {
			Firebase parent = FirebaseEngine.getInstance().newFirebase(endpoint);
			DataSnapshot snapshot = new DataSnapshot(parent, val, priority);
			listener.callback(snapshot, prevChildName);
		}
	}

	@JavascriptInterface
	public void synchronizedToServer(int methodId, boolean success) {
		SynchonizedToServer pushComplete = mSynchronizedToServer.get(methodId);
		if (pushComplete != null) {
			pushComplete.onComplete(success);
			mSynchronizedToServer.remove(methodId);
		}
	}

	private void loadMethod(String method) {
		Log.d(TAG, method);
		final String loadMethod = "javascript:" + method;

		if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
			mWebView.loadUrl(loadMethod);
		} else {
			this.mActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mWebView.loadUrl(loadMethod);
				}
			});
		}
	}
}


text:
package org.usfirst.frc364.Robot2016;

import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.VictorSP;
import edu.wpi.first.wpilibj.interfaces.Gyro;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.livewindow.LiveWindow;

public class RobotMap {

    public static SpeedController driveSystemleftFront;
    public static SpeedController driveSystemleftRear;
    public static SpeedController driveSystemrightFront;
    public static SpeedController driveSystemrightRear;
    public static RobotDrive driveSystemrobotDrive;
    public static SpeedController intakeSystemintakeMotor;
    public static DigitalInput intakeSystemballSensor;
    public static SpeedController shootSystemshootMotor;
    public static SpeedController shootSystemshootMotor2;
    public static AnalogGyro driveSystemgyro;
    public static SpeedController hangSystemwenchMotor;
    public static SpeedController flipSystemflipMotor;
    public static AnalogInput hangSystemwenchPot;
	public static AnalogInput intakeSystemintakePot;
	public static AnalogInput flipSystemflipPot;
	public static SpeedController intakeSystemintakePulley;

    public static void init() {

        driveSystemleftFront = new VictorSP(4);
        driveSystemleftRear = new VictorSP(5);
        driveSystemrightFront = new VictorSP(1);
        driveSystemrightRear = new VictorSP(0);

        driveSystemrobotDrive = new RobotDrive(driveSystemleftFront, driveSystemleftRear,
              driveSystemrightFront, driveSystemrightRear);

        driveSystemrobotDrive.setSafetyEnabled(true);
        driveSystemrobotDrive.setExpiration(0.1);
        driveSystemrobotDrive.setSensitivity(0.5);
        driveSystemrobotDrive.setMaxOutput(1.0);
        driveSystemgyro = new AnalogGyro(0);

        intakeSystemintakeMotor = new VictorSP(8);
        intakeSystemballSensor = new DigitalInput(9);
        intakeSystemintakePot = new AnalogInput(1);
        intakeSystemintakePulley = new VictorSP(9);

        shootSystemshootMotor = new VictorSP(7);
        shootSystemshootMotor2 = new VictorSP(6);

        hangSystemwenchMotor = new VictorSP(2);
        flipSystemflipMotor = new VictorSP(3);
        hangSystemwenchPot = new AnalogInput(2);
        flipSystemflipPot = new AnalogInput(3);

    }
}


text:
import random

from players import HumanPlayer
from players import ClassicAIPlayer

class BaseGame:
    def prepare_game(self):
        raise NotImplementedError

class TwoPlayerGame(BaseGame):
    def prepare_game(self):
        """Creates two players asking their name. Randomly assigns a playable symbol."""
        first_player_name = input('Enter first player name: ')
        second_player_name = input('Enter second player name: ')

        coin_toss = round(random.uniform(0, 1))
        first_player_symbol = HumanPlayer.symbols[coin_toss]
        second_player_symbol = HumanPlayer.symbols[abs(1 - coin_toss)]

        first_player = HumanPlayer(first_player_name, first_player_symbol)
        second_player = HumanPlayer(second_player_name, second_player_symbol)

        current_player = first_player if first_player.symbol == 'X' else second_player

        return first_player, second_player, current_player

class ClassicAIGame(BaseGame):
    def prepare_game(self):
        """Creates a human player and a classicAI player. Randomly assigns a playable symbol."""
        player_name = input('Enter your name: ')

        coin_toss = round(random.uniform(0, 1))
        player_symbol = HumanPlayer.symbols[coin_toss]
        computer_symbol = ClassicAIPlayer.symbols[abs(1 - coin_toss)]

        first_player = HumanPlayer(player_name, player_symbol)
        classic_ai_player = ClassicAIPlayer('Mistontli', computer_symbol)

        return first_player, classic_ai_player, first_player


text:
define(function(require, exports, module) {
'use strict';

var debug = require('debug')('get-new-pictures');
var picture = navigator.getDeviceStorage('pictures');

module.exports = function(since, done) {
  return new Promise(function(resolve, reject) {
    debug('get pictures since: %s', since);
    since = Number(since || 0);

    var cursor = picture.enumerate();
    var files = [];

    cursor.onsuccess = function () {
      if (this.done) return resolve(files);
      var file = this.result;
      var isNew = Number(file.lastModified) > since;
      debug(Number(file.lastModified) - since);
      var shouldSync = isNew && !hidden(file);
      if (shouldSync) files.push(file);
      debug('file: %s, isNew: %s, shouldSync: %s', file.name, isNew, shouldSync, file.lastModified);
      this.continue();
    };

    cursor.onerror = function () { reject(this.error); };
  });
};

function hidden(file) {
  if (!file) return;
  var filename = nameFromPath(file.name);
  return filename[0] === '.';
}

function nameFromPath(path) {
  var lastSlash = path.lastIndexOf('/') + 1;
  return path.slice(lastSlash);
}

});


text:
package org.knowm.xchange.coinbase;

import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.coinbase.service.polling.CoinbaseAccountService;
import org.knowm.xchange.coinbase.service.polling.CoinbaseMarketDataService;
import org.knowm.xchange.coinbase.service.polling.CoinbaseTradeService;
import org.knowm.xchange.utils.nonce.CurrentTimeNonceFactory;

import si.mazi.rescu.SynchronizedValueFactory;

/**
 * @author jamespedwards42
 */
public class CoinbaseExchange extends BaseExchange implements Exchange {

  private SynchronizedValueFactory<Long> nonceFactory = new CurrentTimeNonceFactory();

  @Override
  protected void initServices() {
    this.pollingMarketDataService = new CoinbaseMarketDataService(this);
    this.pollingAccountService = new CoinbaseAccountService(this);
    this.pollingTradeService = new CoinbaseTradeService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    final ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
    exchangeSpecification.setSslUri("https://coinbase.com");
    exchangeSpecification.setHost("coinbase.com");
    exchangeSpecification.setExchangeName("Coinbase");
    exchangeSpecification.setExchangeDescription(
        "Founded in June of 2012, Coinbase is a bitcoin wallet and platform where merchants and consumers can transact with the new digital currency bitcoin.");
    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {

    return nonceFactory;
  }
}


text:
package ca.ualberta.commande.android.commande_godo.data;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.util.JsonReader;

public class TodoJsonReader {
	public static List<TodoItem> readJsonStream(InputStream in) throws IOException {
		JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
		try {
			return readTodosArray(reader);
		} finally {
			reader.close();
		}
	}

	public static List<TodoItem> readTodosArray(JsonReader reader) throws IOException {
		List<TodoItem> todos = new ArrayList<TodoItem>();

		reader.beginArray();
		while (reader.hasNext()) {
			todos.add(readTodo(reader));
		}
		reader.endArray();
		return todos;
	}

	public static TodoItem readTodo(JsonReader reader) throws IOException {
		String key = null;
		String title = null;
		boolean completed = false;
		boolean archived = false;

		reader.beginObject();
		while (reader.hasNext()) {
			String name = reader.nextName();
			if (name.equals("key")) {
				key = reader.nextString();
			} else if (name.equals("title")) {
				title = reader.nextString();
			} else if (name.equals("completed")) {
				completed = reader.nextBoolean();
			} else if (name.equals("archived")) {
				archived = reader.nextBoolean();
			} else {
				reader.skipValue();
			}
		}
		reader.endObject();
		return TodoItem.getNew(key, title, completed, archived);
	}
}


text:
<?php
/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $activkey
 * @property integer $superuser
 * @property integer $status
 * @property string $create_at
 * @property string $lastvisit_at
 */
class Users extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'users';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('create_at', 'required'),
            array('superuser, status', 'numerical', 'integerOnly'=>true),
            array('username', 'length', 'max'=>20),
            array('password, email, activkey', 'length', 'max'=>128),
            array('lastvisit_at', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, username, password, email, activkey, superuser, status, create_at, lastvisit_at', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
            'activkey' => 'Activkey',
            'superuser' => 'Superuser',
            'status' => 'Status',
            'create_at' => 'Create At',
            'lastvisit_at' => 'Lastvisit At',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('activkey',$this->activkey,true);
        $criteria->compare('superuser',$this->superuser);
        $criteria->compare('status',$this->status);
        $criteria->compare('create_at',$this->create_at,true);
        $criteria->compare('lastvisit_at',$this->lastvisit_at,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    public function normalusers()
    {
        {
            // @todo Please modify the following code to remove attributes that should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id);
            $criteria->compare('username',$this->username,true);
            $criteria->compare('password',$this->password,true);
            $criteria->compare('email',$this->email,true);
            $criteria->compare('activkey',$this->activkey,true);
            $criteria->compare('superuser','0');
            $criteria->compare('status',$this->status);
            $criteria->compare('create_at',$this->create_at,true);
            $criteria->compare('lastvisit_at',$this->lastvisit_at,true);

            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
            ));
        }
    }

    public function userlink()
    {
        echo  CHtml::link($this->username,array('create','user_id'=>$this->id));
    }
    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Users the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Linq;
using System.Threading;
#if !CODE_STYLE
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
#endif
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal partial class ITypeSymbolExtensions
    {
        private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax>
        {
            private readonly bool _nameOnly;

            private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new TypeSyntaxGeneratorVisitor(nameOnly: true);
            private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new TypeSyntaxGeneratorVisitor(nameOnly: false);

            private TypeSyntaxGeneratorVisitor(bool nameOnly)
                => _nameOnly = nameOnly;

            public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false)
                => nameOnly ? NameOnlyInstance : NotNameOnlyInstance;

            public override TypeSyntax DefaultVisit(ISymbol node)
                => throw new NotImplementedException();

            private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol)
                where TTypeSyntax : TypeSyntax
            {
                syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker);
                syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol));

                return syntax;
            }

            public override TypeSyntax VisitAlias(IAliasSymbol symbol)
                => AddInformationTo(symbol.Name.ToIdentifierName(), symbol);

            private void ThrowIfNameOnly()
            {
                if (_nameOnly)
                {
                    throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax");
                }
            }

            public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                ITypeSymbol underlyingType = symbol;

                while (underlyingType is IArrayTypeSymbol innerArray)
                {
                    underlyingType = innerArray.ElementType;

                    if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated)
                    {
                        // If the inner array we just moved to is also nullable, then
                        // we must terminate the digging now so we produce the syntax for that,
                        // and then append the ranks we passed through at the end. This is because
                        // nullability annotations acts as a "barrier" where we won't reorder array
                        // through. So whereas:
                        //
                        //     string[][,]
                        //
                        // is really an array of rank 1 that has an element of rank 2,
                        //
                        //     string[]?[,]
                        //
                        // is really an array of rank 2 that has nullable elements of rank 1.

                        break;
                    }
                }

                var elementTypeSyntax = underlyingType.GenerateTypeSyntax();
                using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks);

                var arrayType = symbol;
                while (arrayType != null && !arrayType.Equals(underlyingType))
                {
                    ranks.Add(SyntaxFactory.ArrayRankSpecifier(
                        SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank))));

                    arrayType = arrayType.ElementType as IArrayTypeSymbol;
                }

                TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList());

                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax);
                }

                return AddInformationTo(arrayTypeSyntax, symbol);
            }

            public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol)
                => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol);

            public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, out TypeSyntax syntax)
            {
#if !CODE_STYLE // TODO: Remove the #if once IsNativeIntegerType is available.
                // https://github.com/dotnet/roslyn/issues/41462 tracks adding this support
                if (symbol.IsNativeIntegerType)
                {
                    syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint");
                    return true;
                }
#endif

                syntax = null;
                return false;
            }

#if !CODE_STYLE

            public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
            {
                // TODO(https://github.com/dotnet/roslyn/issues/39865): generate the calling convention once exposed through the API
                var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGenerator.GetParameterModifiers(p.RefKind)))
                    .Concat(SpecializedCollections.SingletonEnumerable((
                        Type: symbol.Signature.ReturnType,
                        RefKindModifiers: CSharpSyntaxGenerator.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true))))
                    .SelectAsArray(t => SyntaxFactory.Parameter(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)).WithModifiers(t.RefKindModifiers).WithType(t.Type.GenerateTypeSyntax()));

                return AddInformationTo(
                    SyntaxFactory.FunctionPointerType(SyntaxFactory.SeparatedList(parameters)), symbol);
            }

#endif

            public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol)
            {
                if (!_nameOnly)
                {
                    var syntax = TryCreateSpecializedNamedTypeSyntax(symbol);
                    if (syntax != null)
                        return syntax;
                }

                if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType))
                {
                    return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType);
                }

                if (symbol.Name == string.Empty || symbol.IsAnonymousType)
                {
                    return CreateSystemObject();
                }

                if (symbol.TypeParameters.Length == 0)
                {
                    if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var")
                    {
                        return CreateSystemObject();
                    }

                    return symbol.Name.ToIdentifierName();
                }

                var typeArguments = symbol.IsUnboundGenericType
                    ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length)
                    : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax());

                return SyntaxFactory.GenericName(
                    symbol.Name.ToIdentifierToken(),
                    SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments)));
            }

            private static QualifiedNameSyntax CreateSystemObject()
            {
                return SyntaxFactory.QualifiedName(
                    SyntaxFactory.AliasQualifiedName(
                        CreateGlobalIdentifier(),
                        SyntaxFactory.IdentifierName("System")),
                    SyntaxFactory.IdentifierName("Object"));
            }

            private static IdentifierNameSyntax CreateGlobalIdentifier()
                => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));

            private static TypeSyntax TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol)
            {
                if (symbol.SpecialType == SpecialType.System_Void)
                {
                    return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword));
                }

                if (symbol.IsTupleType && symbol.TupleElements.Length >= 2)
                {
                    return CreateTupleTypeSyntax(symbol);
                }

                if (symbol.IsNullable())
                {
                    // Can't have a nullable of a pointer type.  i.e. "int*?" is illegal.
                    var innerType = symbol.TypeArguments.First();
                    if (innerType.TypeKind != TypeKind.Pointer)
                    {
                        return AddInformationTo(
                            SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol);
                    }
                }

                return null;
            }

            private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol)
            {
                var list = new SeparatedSyntaxList<TupleElementSyntax>();

                foreach (var element in symbol.TupleElements)
                {
                    var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name);
                    list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name));
                }

                return AddInformationTo(SyntaxFactory.TupleType(list), symbol);
            }

            public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol)
            {
                if (TryCreateNativeIntegerType(symbol, out var typeSyntax))
                    return typeSyntax;

                typeSyntax = CreateSimpleTypeSyntax(symbol);
                if (!(typeSyntax is SimpleNameSyntax))
                    return typeSyntax;

                var simpleNameSyntax = (SimpleNameSyntax)typeSyntax;
                if (symbol.ContainingType != null)
                {
                    if (symbol.ContainingType.TypeKind != TypeKind.Submission)
                    {
                        var containingTypeSyntax = symbol.ContainingType.Accept(this);
                        if (containingTypeSyntax is NameSyntax name)
                        {
                            typeSyntax = AddInformationTo(
                                SyntaxFactory.QualifiedName(name, simpleNameSyntax),
                                symbol);
                        }
                        else
                        {
                            typeSyntax = AddInformationTo(simpleNameSyntax, symbol);
                        }
                    }
                }
                else if (symbol.ContainingNamespace != null)
                {
                    if (symbol.ContainingNamespace.IsGlobalNamespace)
                    {
                        if (symbol.TypeKind != TypeKind.Error)
                        {
                            typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax);
                        }
                    }
                    else
                    {
                        var container = symbol.ContainingNamespace.Accept(this);
                        typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName(
                            (NameSyntax)container,
                            simpleNameSyntax), symbol);
                    }
                }

                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol);
                }

                return typeSyntax;
            }

            public override TypeSyntax VisitNamespace(INamespaceSymbol symbol)
            {
                var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol);
                if (symbol.ContainingNamespace == null)
                {
                    return syntax;
                }

                if (symbol.ContainingNamespace.IsGlobalNamespace)
                {
                    return AddGlobalAlias(symbol, syntax);
                }
                else
                {
                    var container = symbol.ContainingNamespace.Accept(this);
                    return AddInformationTo(SyntaxFactory.QualifiedName(
                        (NameSyntax)container,
                        syntax), symbol);
                }
            }

            /// <summary>
            /// We always unilaterally add "global::" to all named types/namespaces.  This
            /// will then be trimmed off if possible by calls to
            /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/>
            /// </summary>
            private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax)
            {
                return AddInformationTo(
                    SyntaxFactory.AliasQualifiedName(
                        CreateGlobalIdentifier(),
                        syntax), symbol);
            }

            public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                return AddInformationTo(
                    SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()),
                    symbol);
            }

            public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol)
            {
                TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol);
                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                    typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol);

                return typeSyntax;
            }
        }
    }
}