text:
package com.pg85.otg.forge.mixin;

import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.ChunkPrimerWrapper;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.server.ChunkHolder;
import net.minecraft.world.server.ChunkManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg;

import java.util.function.Predicate;

@Mixin(ChunkManager.class)
public class MixinChunkManager
{
	@ModifyArg(method = "saveAllChunks(Z)V", at = @At(value = "INVOKE", target = "Ljava/util/stream/Stream;filter(Ljava/util/function/Predicate;)Ljava/util/stream/Stream;", ordinal = 0))
	private Predicate<ChunkHolder> alwaysAccessibleFlush(Predicate<ChunkHolder> chunk)
	{
		return c -> true;
	}

	@ModifyArg(method = "saveAllChunks(Z)V", at = @At(value = "INVOKE", target = "Ljava/util/stream/Stream;filter(Ljava/util/function/Predicate;)Ljava/util/stream/Stream;", ordinal = 1))
	private Predicate<IChunk> allowChunkPrimerFlush(Predicate<IChunk> chunk)
	{
		return c -> c instanceof ChunkPrimer || c instanceof ChunkPrimerWrapper || c instanceof Chunk;
	}
}


text:
body
{
	background-color: #333;
	background-image: url("/img/bg.jpg");
	font-family: Helvetica;
	margin: 0;
	padding: 20px;
}

div#MainContainer
{
	background-color: rgba(30, 30, 30, 0.7);
	-webkit-border-radius: 6px;
	-moz-border-radius: 6px;
	border-radius: 6px;
}

div#MainContainer h1
{
	color: #fff;
	padding-left: 14px;
	padding-top: 14px;
}

div#MainContainer table
{
	border-collapse: collapse;
	width: 100%;
}

div#MainContainer table thead tr
{
	background-color: #000;
}

div#MainContainer table thead tr th
{
	padding: 7px 14px 7px 14px;
	text-align: left;
}

div#MainContainer table thead tr th:first-child
{
	-webkit-border-top-left-radius: 6px;
	-moz-border-radius-topleft: 6px;
	border-top-left-radius: 6px;
	width: 200px;
}

div#MainContainer table thead tr th:last-child
{
	-webkit-border-top-right-radius: 6px;
	-moz-border-radius-topright: 6px;
	border-top-right-radius: 6px;
}

div#MainContainer table thead tr th
{
	color: #fff;
	font-weight: bold;
	font-family: Helvetica;
	font-size: 16px;
}

div#MainContainer table tbody tr:last-child td:first-child
{
	-webkit-border-bottom-left-radius: 6px;
	-moz-border-radius-bottomleft: 6px;
	border-bottom-left-radius: 6px;
}

div#MainContainer table tbody tr:last-child td:last-child
{
	-webkit-border-bottom-right-radius: 6px;
	-moz-border-radius-bottomright: 6px;
	border-bottom-right-radius: 6px;
}

div#MainContainer table tbody tr
{
	cursor: pointer;
}

div#MainContainer table tbody tr.Critical
{
	background-color: rgba(144, 0, 0, 0.6);
	/*background-color: #900;*/
	color: #fff;
}

div#MainContainer table tbody tr.Warning
{
	background-color: rgba(255, 165, 0, 0.6);
	/*background-color: #ffa500;*/
	color: #fff;
}

div#MainContainer table tbody tr td
{
	padding: 14px 14px 14px 14px;
	font-family: Helvetica;
	font-size: 14px;
}

redpajama_set_name: RedPajamaGithub


text:
package pobj.partiel2013nov;

interface IStrategie {
    int jouer(Plateau pl, Piece p) throws PasDeCoup;
}


text:
using System.Collections.Generic;
using ZAProxy.Infrastructure;

namespace ZAProxy.Components
{
    /// <summary>
    /// Component for testing protection against Cross Site Request Forgery.
    /// </summary>
    public class AntiCsrfComponent : ComponentBase
    {
        /// <summary>
        /// Initiates a new instance of the <see cref="AntiCsrfComponent"/> class.
        /// </summary>
        /// <param name="zapProcess">The ZAP process to connect to.</param>
        public AntiCsrfComponent(IZapProcess zapProcess)
            : this(null, zapProcess)
        { }

        /// <summary>
        /// Initiates a new instance of the <see cref="AntiCsrfComponent"/> class with a specific HTTP client implementation.
        /// </summary>
        /// <param name="httpClient">The HTTP client implementation.</param>
        /// <param name="zapProcess">The ZAP process to connect to.</param>
        public AntiCsrfComponent(IHttpClient httpClient, IZapProcess zapProcess)
            : base(httpClient, zapProcess, "acsrf")
        { }

        #region Views

        /// <summary>
        /// Gets all CSRF token names that are used in scanning/fuzzing.
        /// </summary>
        /// <returns>The CSRF token names used.</returns>
        public IEnumerable<string> GetOptionTokenNames()
        {
            return ParseJsonListString(CallView<string>("optionTokensNames", "TokensNames"));
        }

        #endregion

        #region Actions

        /// <summary>
        /// Adds a CSRF token name to the list of names that are used in scanning/fuzzing.
        /// </summary>
        /// <param name="name">The token name to add.</param>
        public void AddOptionTokenName(string name)
        {
            CallAction("addOptionToken", new Parameters
            {
                { "String", name }
            });
        }

        /// <summary>
        /// Removes a CSRF token name from the list of names that are used in scanning/fuzzing.
        /// </summary>
        /// <param name="name">The token name to remove.</param>
        public void RemoveOptionTokenName(string name)
        {
            CallAction("removeOptionToken", new Parameters
            {
                { "String", name }
            });
        }

        #endregion

        #region Others

        /// <summary>
        /// Generates an HTML page with a form to fuzz/test a specific POST message.
        /// </summary>
        /// <remarks>
        /// This method is mainly for internal use by ZAP.
        /// </remarks>
        /// <param name="messageId">The ID of a historic POST message to create this form for.</param>
        /// <returns>HTML to render a form for the specified POST message.</returns>
        public string GenerateForm(int messageId)
        {
            return CallOther("genForm", new Parameters
            {
                { "hrefId", messageId }
            });
        }

        #endregion
    }
}


text:
# Newman [![Build Status](https://travis-ci.org/postmanlabs/newman.svg?branch=master)](https://travis-ci.org/postmanlabs/newman) [![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)

Newman is a command-line collection runner for [Postman](http://getpostman.com). It allows you to effortlessly run and test a Postman collection directly from the command-line. It is built with extensibility in mind so that you can easily integrate it with your continuous integration servers and build systems.

Newman maintains feature parity with Postman and allows you to run collections just the way they are executed inside the collection runner in Postman.

[![NPM](https://nodei.co/npm/newman.png?downloads=true)](https://nodei.co/npm-dl/newman/)

## Getting Started
Newman is built on Node.js. To run Newman, make sure you have Node.js installed. Node.js can be downloaded and installed from [here](http://nodejs.org/download/) on Linux, Windows and Mac OSX.

#### Newman Stable
With that done, Newman is just one command away.
```bash
$ npm install -g newman # installs Newman globally on your system allowing you to run it from anywhere.
```
#### Newman Beta

We've released a beta of Newman v2.0, which supports Node v4.0+ as well. If you wish to install the beta,
```bash
$ npm install -g newman@beta # installs Newman globally on your system allowing you to run it from anywhere.
```
Notes on the Beta:
* The [``jsdom``](https://github.com/tmpvar/jsdom) dependency is no longer listed in package.json. The installation of this dependency has been moved to the postinstall script. This is because a different version of ``jsdom`` is required for node v0.x.x and Node v4.0+.
* The absence of ``jsdom`` from package.json should be specially noted. If you use any automated tools to audit dependencies, etc, this change can cause issues.
* For Windows users, if you are using Node v4.0+, you no longer need to install the Visual Studio Runtime. You do however need to ensure that the Node binary (node.exe) is on your system ``%PATH``.
* In the future, Newman will stop supporting Node v0.x.x, and only support Node version 4.0+. This will considerably reduce installation woes, especially on Windows.

#### Updating Newman
If you already have Newman, you can update with a simple command
```bash
$ npm update -g newman
```

#### Running Newman
The easiest way to run Newman is to run it with a collection. With the `-c` flag you can run any collection file lying on your file-system. Refer [the collection documentation](http://www.getpostman.com/docs/collections) to learn how to use and download collections.

```bash
$ newman -c mycollection.json
```

The `-u` flag allows you to pass a postman collection as a URL. Your collection probably uses environment variables. To provide an accompanying set of environment variables, [export them from Postman](http://www.getpostman.com/docs/environments)  and run them with the `-e` flag.
```bash
$ newman -u https://www.getpostman.com/collections/cb208e7e64056f5294e5 -e devenvironment.json
```

## Options
Newman provides a rich set of options to customize a run. A list of options can be retrieved by running it with the `-h` flag.

```bash
$ newman -h

Options:

Utility:
-h, --help                  output usage information
-V, --version               output the version number

Basic setup:
-c, --collection [file]     Specify a Postman collection as a JSON [file]
-u, --url [url]             Specify a Postman collection as a [url]
-f, --folder [folderName]   Specify a single folder to run from a collection. To be used with -c or -u.
-e, --environment [file]    Specify a Postman environment as a JSON [file]
-d, --data [file]           Specify a data file to use either json or csv
-g, --global [file]         Specify a Postman globals file as JSON [file]
-n, --number [number]       Define the number of iterations to run
-i, --import [file]         Import a Postman backup file, and save collections, environments, and globals. [file]
-p, --pretty                (Use with -i) Enable pretty-print while saving imported collections, environments, and globals

Request options:
-y, --delay [number]            Specify a delay (in ms) between requests [number]
-r, --requestTimeout [number]   Specify a request timeout (in ms) for a request

Misc.:
-s, --stopOnError           Stops the runner when a test case fails
-j, --noSummary             Doesn't show the summary for each iteration
-C, --noColor               Disable colored output
-k, --insecure              Disable strict ssl
-l, --tls                   Use TLSv1
-x, --exitCode              Continue running tests even after a failure, but exit with code=1

Output:
-o, --outputFile [file]     Path to file where output should be written. [file]
-t, --testReportFile [file] Path to file where results should be written as JUnit XML [file]
-H, --html                  Export a HTML report to a specified file [file]

```

Use the `-n` option to set the number of iterations you want to run the collection for.

```bash
$ newman -c mycollection.json -n 10  # runs the collection 10 times
```

To provide a different set of data i.e. variables for each iteration you can use the `-d` to specify a `json` or `csv` file. For example, a data file such as the one shown below will run *2* iterations, with each iteration using a set of variables.
```javascript
[{
	"url": "http://127.0.0.1:5000",
	"user_id": "1",
	"id": "1",
	"token_id": "123123",
},
{
	"url": "http://dump.getpostman.com",
	"user_id": "2",
	"id": "2",
	"token_id": "899899",
}]
```

```bash
$ newman -c mycollection.json -d data.json
```

The csv file for the above set of variables would look like
```
url, user_id, id, token_id
http://127.0.0.1:5000, 1, 1, 123123123
http://dump.getpostman.com, 2, 2, 899899
```

Newman, by default exits with a status code of 0 if everything runs well i.e. without any exceptions. Continuous integration tools respond to these exit codes and correspondingly pass or fail a build. You can use `-s` flag to tell Newman to halt on a test case error with a status code of 1 which can then be picked up by a CI tool or build system.

```bash
$ newman -c PostmanCollection.json -e environment.json -s

Iteration 1 of 1
200 17ms Blog posts http://127.0.0.1:5000/blog/posts
    ✔ Status code is 200
404 5ms Blog post http://127.0.0.1:5000/blog/posts/1
200 4ms New post without token http://127.0.0.1:5000/blog/posts
    ✔ Body has a message
    ✔ invalid credentials
Test case failed: Status code is 404
```

The results of all tests and requests can be exported into file and later imported in Postman for further analysis. Use the `-o` flag and a file name to save the runner output into a file.

```bash
$ newman -c mycollection.json -o outputfile.json
```

Newman can also be used to import a Postman backup file. The collections, environments, and globals will be saved to the 'data' folder. (Use the -p option to enable pretty-print)
```bash
newman -i /path/to/Backup.json -p
```

**NOTE** Newman allows you to use all [libraries](http://www.getpostman.com/docs/jetpacks_writing_tests) that Postman supports for running tests. For [x2js](https://code.google.com/p/x2js/) however, only  function `xmlToJson` is supported.

## Library
Newman has been built as a library from the ground-up so that it can be extended and put to varied uses. You can use it like so -

```javascript
var Newman = require('newman');

// read the collectionjson file
var collectionJson = JSON5.parse(fs.readFileSync("collection.json", 'utf8'));

// define Newman options
newmanOptions = {
	envJson: JSON5.parse(fs.readFileSync("envjson.json", "utf-8")), // environment file (in parsed json format)
	dataFile: data.csv,                    // data file if required
	iterationCount: 10,                    // define the number of times the runner should run
	outputFile: "outfile.json",            // the file to export to
	responseHandler: "TestResponseHandler", // the response handler to use
	asLibrary: true,         				// this makes sure the exit code is returned as an argument to the callback function
	stopOnError: true
}

// Optional Callback function which will be executed once Newman is done executing all its tasks.
Newman.execute(collectionJson, newmanOptions, callback);
```

## Cron
Want your test suite to run every hour? Newman can be used to schedule tests to run hourly, daily or weekly automatically in combination with the awesome Unix scheduler **CRON**.

Lets setup a simple script called `run_newman` to run our tests
```bash
#!/bin/bash

timestamp=$(date +"%s")
collection=/var/www/myapp/tests/collection.json
env=/var/www/myapp/tests/envfile.json

# create separate outfile for each run
outfile=/var/www/myapp/tests/outfile-$timestamp.json

# redirect all output to /dev/null
newman -c $collection -c $env -o $outfile > /dev/null2>&1
```
Make it an executable
```bash
$ chmod +x run_newman
```

To run Newman every hour, run `crontab -e` and enter the following -
```bash
0 * * * * /path/to/run_newman
```
Check your `cron` if it has been setup
```bash
$ crontab -l
0 * * * * /path/to/run_newman
```
With this, your Newman is set to run automatically every hour.

Note: Exact location for `cron` is dependent on the linux distribution you are running. See specific `cron` instructions for your distribution. For an introduction to `cron` checkout [this](http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800) article.

## License
Apache-2.0. See the LICENSE file for more information

[![Analytics](https://ga-beacon.appspot.com/UA-43979731-9/newman/readme)](https://www.getpostman.com)


text:
<?php
/**
 * Created by PhpStorm.
 * User: TI-tygangsta
 * Date: 18/06/2018
 * Time: 15:27
 */

namespace Tests\MainBundle\Repository;

use MainBundle\Entity\Motif;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class MotifRepositoryTest extends KernelTestCase
{

    private $em;

    protected function setUp()
    {
        self::bootKernel();

        $this->em = static::$kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }

    public function testFindAll(){
        $motifs = $this->em
            ->getRepository(Motif::class)
            ->findAll();

        $this->assertNotEmpty($motifs);
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em->close();
        $this->em = null; // avoid memory leaks
    }
}


text:
Package.describe({
  name: 'antonly:mcrypt',
  version: '1.0.0',
  // Brief, one-line summary of the package.
  summary: 'Encrypt users data with user-specific keys for later use!',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/AntonLydike/meteor-mcrypt',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.4.1.1');
  api.use(['ecmascript', 'underscore']);
  api.mainModule('mcrypt-core.js', 'server');
});

Package.onTest(function(api) {
  api.use(['ecmascript', 'underscore', 'tinytest', 'antonly:mcrypt']);
  api.mainModule('mcrypt-tests.js', 'server');
});


text:
require 'tilt'

module Scrapple::Plugins
  class Layout

    class << self
      def wrap(body, env)
        page = env['scrapple.page']
        return body if page.nil?

        layout_page = get_layout_page(page)
        return body if page.fullpath == layout_page.fullpath

        engine = Tilt[layout_page.type]
        return body if engine.nil?

        wrapped = engine.new { layout_page.content }.render(page, :env => env) { body }

        # Recursive wrapping
        page['layout'] = layout_page['layout']
        page['layout'] ? wrap(wrapped, page) : wrapped
      end

      def get_layout_page(page)
        page['layout'] ||= DEFAULT_LAYOUT
        Scrapple::Page.for(page['layout'], :fetch => true, :ignore_perdir_files => true)
      end
    end
  end
end


text:
package com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.vm;

import com.google.common.collect.ImmutableMap;
import com.microsoftopentechnologies.tooling.msservices.components.DefaultLoader;
import com.microsoftopentechnologies.tooling.msservices.helpers.NotNull;
import com.microsoftopentechnologies.tooling.msservices.helpers.azure.AzureCmdException;
import com.microsoftopentechnologies.tooling.msservices.helpers.azure.AzureManagerImpl;
import com.microsoftopentechnologies.tooling.msservices.model.vm.Endpoint;
import com.microsoftopentechnologies.tooling.msservices.model.vm.VirtualMachine;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.EventHelper.EventStateHandle;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.Node;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.NodeAction;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.NodeActionEvent;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.NodeActionListener;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.AzureNodeActionListener;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.AzureNodeActionPromptListener;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.AzureRefreshableNode;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

public class VMNode extends AzureRefreshableNode {
    private static abstract class VMNodeActionPromptListener extends AzureNodeActionPromptListener {
        private VMNode vmNode;

        public VMNodeActionPromptListener(@NotNull VMNode vmNode,
                                          @NotNull String promptMessageFormat,
                                          @NotNull String progressMessage) {
            super(vmNode, String.format(promptMessageFormat, vmNode.virtualMachine.getName()), progressMessage);
            this.vmNode = vmNode;
        }

        @Override
        protected void onSubscriptionsChanged(NodeActionEvent e)
                throws AzureCmdException {
        }
    }

    public class DeleteVMAction extends VMNodeActionPromptListener {
        public DeleteVMAction() {
            super(VMNode.this,
                    "This operation will delete virtual machine %s. The associated disks will not be deleted " +
                            "from your storage account. Are you sure you want to continue?",
                    "Deleting VM");
        }

        @Override
        protected void azureNodeAction(NodeActionEvent e, @NotNull EventStateHandle stateHandle)
                throws AzureCmdException {
            AzureManagerImpl.getManager().deleteVirtualMachine(virtualMachine, false);
            DefaultLoader.getIdeHelper().invokeLater(new Runnable() {
                @Override
                public void run() {
                    // instruct parent node to remove this node
                    getParent().removeDirectChildNode(VMNode.this);
                }
            });
        }
    }

    public class DownloadRDPAction extends AzureNodeActionListener {
        private JFileChooser saveFile;

        public DownloadRDPAction() {
            super(VMNode.this, "Downloading RDP File");
        }

        @NotNull
        @Override
        protected Callable<Boolean> beforeAsyncActionPerfomed() {
            return new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    saveFile = new JFileChooser();
                    saveFile.setDialogTitle("Save RDP file");

                    return (saveFile.showSaveDialog(null) == JFileChooser.APPROVE_OPTION);
                }
            };
        }

        @Override
        protected void azureNodeAction(NodeActionEvent e, @NotNull EventStateHandle stateHandle)
                throws AzureCmdException {
            try {
                File rdpFile = saveFile.getSelectedFile();

                if (rdpFile.exists() || rdpFile.createNewFile()) {
                    FileOutputStream fileOutputStream = new FileOutputStream(rdpFile);
                    fileOutputStream.write(AzureManagerImpl.getManager().downloadRDP(virtualMachine));
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (Exception ex) {
                DefaultLoader.getUIHelper().showException("Error downloading RDP file:", ex);
            }
        }

        @Override
        protected void onSubscriptionsChanged(NodeActionEvent e)
                throws AzureCmdException {
        }
    }

    public class ShutdownVMAction extends VMNodeActionPromptListener {
        public ShutdownVMAction() {
            super(VMNode.this,
                    "This operation will result in losing the VIP that was assigned to this virtual machine. " +
                            "Are you sure that you want to shut down virtual machine %s?",
                    "Shutting down VM");
        }

        @Override
        protected void azureNodeAction(NodeActionEvent e, @NotNull EventStateHandle stateHandle)
                throws AzureCmdException {
            AzureManagerImpl.getManager().shutdownVirtualMachine(virtualMachine, true);
        }
    }

    public class StartVMAction extends VMNodeActionPromptListener {
        public StartVMAction() {
            super(VMNode.this,
                    "Are you sure you want to start the virtual machine %s?",
                    "Starting VM");
        }

        @Override
        protected void azureNodeAction(NodeActionEvent e, @NotNull EventStateHandle stateHandle)
                throws AzureCmdException {
            AzureManagerImpl.getManager().startVirtualMachine(virtualMachine);
        }
    }

    public class RestartVMAction extends VMNodeActionPromptListener {
        public RestartVMAction() {
            super(VMNode.this,
                    "Are you sure you want to restart the virtual machine %s?",
                    "Restarting VM");
        }

        @Override
        protected void azureNodeAction(NodeActionEvent e, @NotNull EventStateHandle stateHandle)
                throws AzureCmdException {
            AzureManagerImpl.getManager().restartVirtualMachine(virtualMachine);
        }
    }

    private static final String WAIT_ICON_PATH = "virtualmachinewait.png";
    private static final String STOP_ICON_PATH = "virtualmachinestop.png";
    private static final String RUN_ICON_PATH = "virtualmachinerun.png";
    public static final String ACTION_DELETE = "Delete";
    public static final String ACTION_DOWNLOAD_RDP_FILE = "Connect Remote Desktop";
    public static final String ACTION_SHUTDOWN = "Shutdown";
    public static final String ACTION_START = "Start";
    public static final String ACTION_RESTART = "Restart";
    public static final int REMOTE_DESKTOP_PORT = 3389;

    protected VirtualMachine virtualMachine;

    public VMNode(Node parent, VirtualMachine virtualMachine)
            throws AzureCmdException {
        super(virtualMachine.getName(), virtualMachine.getName(), parent, WAIT_ICON_PATH, true);
        this.virtualMachine = virtualMachine;

        loadActions();

        // update vm icon based on vm status
        refreshItemsInternal();
    }

    private String getVMIconPath() {
        switch (virtualMachine.getStatus()) {
            case Ready:
                return RUN_ICON_PATH;
            case Stopped:
            case StoppedDeallocated:
                return STOP_ICON_PATH;
            default:
                return WAIT_ICON_PATH;
        }
    }

    @Override
    protected void refresh(@NotNull EventStateHandle eventState)
            throws AzureCmdException {
        virtualMachine = AzureManagerImpl.getManager().refreshVirtualMachineInformation(virtualMachine);

        if (eventState.isEventTriggered()) {
            return;
        }

        refreshItemsInternal();
    }

    private void refreshItemsInternal() {
        // update vm name and status icon
        setName(virtualMachine.getName());
        setIconPath(getVMIconPath());

        // load up the endpoint nodes
        removeAllChildNodes();

        for (Endpoint endpoint : virtualMachine.getEndpoints()) {
            VMEndpointNode vmEndPoint = new VMEndpointNode(this, endpoint);
            addChildNode(vmEndPoint);
        }
    }

    @Override
    protected Map<String, Class<? extends NodeActionListener>> initActions() {
        Map<String, Class<? extends NodeActionListener>> actionMap =
                new HashMap<String, Class<? extends NodeActionListener>>();

        actionMap.put(ACTION_DELETE, DeleteVMAction.class);
        actionMap.put(ACTION_DOWNLOAD_RDP_FILE, DownloadRDPAction.class);
        actionMap.put(ACTION_SHUTDOWN, ShutdownVMAction.class);
        actionMap.put(ACTION_START, StartVMAction.class);
        actionMap.put(ACTION_RESTART, RestartVMAction.class);

        return ImmutableMap.copyOf(actionMap);
    }

    @Override
    public List<NodeAction> getNodeActions() {
        // enable/disable menu items according to VM status
        boolean started = virtualMachine.getStatus().equals(VirtualMachine.Status.Ready);
        boolean stopped = virtualMachine.getStatus().equals(VirtualMachine.Status.Stopped) ||
                virtualMachine.getStatus().equals(VirtualMachine.Status.StoppedDeallocated);

        getNodeActionByName(ACTION_DOWNLOAD_RDP_FILE).setEnabled(!stopped && hasRDPPort(virtualMachine));
        getNodeActionByName(ACTION_SHUTDOWN).setEnabled(started);
        getNodeActionByName(ACTION_START).setEnabled(stopped);
        getNodeActionByName(ACTION_RESTART).setEnabled(started);

        return super.getNodeActions();
    }

    private boolean hasRDPPort(VirtualMachine virtualMachine) {
        for (Endpoint endpoint : virtualMachine.getEndpoints()) {
            if (endpoint.getPrivatePort() == REMOTE_DESKTOP_PORT) {
                return true;
            }
        }

        return false;
    }
}


text:
require './lib/ghit/ssh_globals'

describe Ghit::SshGlobals do

  let(:remote) { "origin\tgit@github.com:author/name.git (fetch)" }
  subject{ described_class.new(remote) }

  it 'extracts author name from remote' do
    expect(subject.author).to eq "author"
  end

  it 'extracts repo name from remote' do
    expect(subject.repository).to eq "name"
  end

  it 'extracts repo url from remote' do
    expect(subject.url).to eq "https://github.com/author/name"
  end

end


text:
{% load humanize %}
{% load endorsement_extras %}

{% if accounts %}

{% for account in accounts %}

                @{{ account.screen_name }}

                {{ account.followers_count|shorten }} followers

{% endfor %}

{% else %}

No Twitter accounts found

{% endif %}


text:
<?php

/*
 * This file is part of Mannequin.
 *
 * (c) 2017 Last Call Media, Rob Bayliss <rob@lastcallmedia.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace LastCall\Mannequin\Twig\Discovery;

use LastCall\Mannequin\Core\Component\BrokenComponent;
use LastCall\Mannequin\Core\Component\ComponentCollection;
use LastCall\Mannequin\Core\Component\ComponentInterface;
use LastCall\Mannequin\Core\Discovery\DiscoveryInterface;
use LastCall\Mannequin\Core\Discovery\IdEncoder;
use LastCall\Mannequin\Twig\Driver\TwigDriverInterface;
use LastCall\Mannequin\Twig\Component\TwigComponent;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * This class converts an iterable object of template names into TwigComponent
 * objects by using the Twig driver.
 */
class TwigDiscovery implements DiscoveryInterface, LoggerAwareInterface
{
    use IdEncoder;

    private $names;

    private $driver;

    private $logger;

    public function __construct(TwigDriverInterface $driver, $names)
    {
        $this->driver = $driver;
        if (!is_array($names) && !$names instanceof \Traversable) {
            throw new \InvalidArgumentException(
                '$names must be an array or a \Traversable object.'
            );
        }
        $this->names = $names;
        $this->logger = new NullLogger();
    }

    /**
     * {@inheritdoc}
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function discover(): ComponentCollection
    {
        $twig = $this->driver->getTwig();
        $components = [];
        foreach ($this->names as $names) {
            $aliases = (array) $names;
            $name = reset($aliases);
            try {
                $component = $this->createComponent($name, $aliases, $twig);
            } catch (\Twig_Error $e) {
                $this->logger->error('Twig error in {template}: {message}', ['template' => $name, 'message' => $e->getMessage()]);
                $component = $this->createBrokenComponent($name, $aliases);
                $component->addProblem($e->getMessage());
            }
            $component->setName($name);
            $components[] = $component;
        }

        return new ComponentCollection($components);
    }

    protected function createComponent(string $name, array $aliases, \Twig_Environment $twig): TwigComponent
    {
        return new TwigComponent(
            $this->encodeId($name),
            $aliases,
            $twig->load($name)->getSourceContext(),
            $twig
        );
    }

    protected function createBrokenComponent(string $name, array $aliases): ComponentInterface
    {
        return new BrokenComponent(
            $this->encodeId($name),
            $aliases
        );
    }
}


text:
module ActiveAdmin::ViewsHelper
  include ActiveAdmin::ComponentsHelper
  include ActiveAdmin::PluginsHelper
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <WebView
        android:id="@+id/wigle_registration_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</RelativeLayout>


text:
The third project for the [MO810](http://www.ic.unicamp.br/~esther/teaching/2017s1/mc959/index.html) class.

#Members:
* Mateus Coradini Santos - @[mateuscoradini](https://github.com/mateuscoradini)
* Luísa Cardoso Madeira - @[luwood](https://github.com/luwood)
* Guilherme Carreiro - @[karreiro](https://github.com/karreiro)

## Summary
This project implements a robot that searches for plants.

## Depencencies
- JDK 1.8
- Maven 3.X
- OpenCV 3
- V-REP 3.3.2

## Setup
Since the OpenCV does not have a remote Maven repository. You need to install it locally.

Execute the following command:
```
mvn install:install-file -Dfile=<OPENCV_JAR_PATH> -DgroupId=org.opencv -DartifactId=opencv -Dversion=3.2.0 -Dpackaging=jar
```
Note: It's important to replace the `<OPENCV_JAR_PATH>` by the `.jar` path, e.g., `/usr/local/opt/opencv3/share/OpenCV/java/opencv-320.jar`.

### Install the Fuzzylite library
```
cd /tmp
wget https://github.com/fuzzylite/jfuzzylite/archive/v6.0.zip
unzip v6.0.zip
cd jfuzzylite-6.0/jfuzzylite
mvn clean install
```

## Building
```
mvn clean install -DargLine="-Djava.library.path=<OPENCV_PATH>"
```
Note: It's important to replace the `<OPENCV_PATH>` by the opencv path, e.g., `/usr/local/opt/opencv3/share/OpenCV/java`.

## Running on Intellij
Go to `Run` > `Edit Configurations...` > `VM Options` and add:
```
-Djava.library.path=<OPENCV_PATH>:<VREP_PATH>
```
Note: It's important to replace the `<OPENCV_PATH>` and the `<VREP_PATH>` by the correct values, e.g., ` -Djava.library.path=/Users/karreiro/Projects/mo810/vrep/programming/remoteApiBindings/java/lib:/usr/local/opt/opencv3/share/OpenCV/java`

## License
This project is released under MIT License.

Check [LICENSE](https://github.com/mateuscoradini/VRepSimulator/blob/master/LICENSE.txt) file for more information.


text:
$(document).ready(function(){
	$("[type=radio]").prop('checked', false);

	$("input[type=text]").val('');

    $('[name=dis1][value=year]').click(function() {
       $("#dis1-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("Not correct.  If you wait until next year to get your $200, you'll lose one year's worth of interest that you could have earned in a bank.");
    });

    $('[name=dis1][value=today]').click(function() {
       $("#dis1-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("Correct!  $200 today is worth more than $200 a year from now.  If you get $200 now, you can put it in a bank account.  In a year, you'll have your $200, plus the interest it will earn.
In 2013, interest rates are low.  The bank may only add $1, but that's better than $0.");
       $("#dis1A-answer")
       .html("");
    });
    $('[name=dis1][value=same]').click(function() {
       $("#dis1-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("Even with no inflation and no risk of non-payment, getting the money sooner is better, because you can put money you get now in a bank and earn interest.");
    });

    $("#dis2-button").click(function(){
        var response = parseFloat($("#dis2-response").val(),10);
        if( response === 210.0) {
			$("#dis2-answer").addClass("correct")
       		.removeClass("incorrect")
            .html("Correct!  We'll have $210.
That's the $200 we started with, plus 5% of $200, which is $10.");
            $("#dis2A-answer")
            .html("");
        } else {
			$("#dis2-answer").addClass("incorrect")
       		.removeClass("correct")
            .text("No.  We will have $200 plus one year's simple interest.  5% of 200 is 10.");
        }
        if( response === 10.0) {
			$("#dis2-answer").addClass("incorrect")
       		.removeClass("correct")
            .text("$10 is the interest that will be added to the $200.  I am asking for the total.");
        }
    });

    $('[name=dis3][value=22050]').click(function() {
       $("#dis3-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("Correct!  After one year you have $210.  After the second year, you get 5% of $210, which is $10.50, in interest.  Your final total is $210 + $10.50 = $220.50.");
        $("#dis3A-answer")
            .html("");
    });

    $('[name=dis3][value=220]').click(function() {
       $("#dis3-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("Not quite.  Your original $200 will earn another $10 interest, but you'll also get interest on the first year's $10 interest. Getting interest on interest is called 'compounding.'");
    });

	$("#dis4-button").click(function(){
        var response = parseFloat($("#dis4-response").val(),10);
        if( response === 3.0) {
			$("#dis4-answer").addClass("correct")
       		.removeClass("incorrect")
            .html("Correct!");
            $("#dis4A-answer").html("

$200 ×(1.05)³ 	= $231.52

Present Value ×( 1+Interest Rate )³ 	= Future Value in Three Years

To calculate how much we will have in three years, we multiply by 1.05 three times, once for the first year, once for the second year, and once for the third year.");

        } else {
			$("#dis4-answer").addClass("incorrect")
       		.removeClass("correct")
            .text("No.  For the total after one year, we multiplied $200 by 1.05 once.  For two years, we multiplied by 1.05 twice.  For three years, ...");
        }
    });

    $('[name=dis5][value=19048]').click(function() {
       $("#dis5-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("Correct!");
       $("#dis5A-answer").html("
You want the amount that will grow to $200 in one year.
You want X such that
X \u00d7 (1.05) = $200.
Divide both sides of this by 1.05 to get:
X = $200/1.05
which calculates to
X = $190.48.");
    });
    $('[name=dis5][value=190]').click(function() {
       $("#dis5-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("$190 is not quite enough.  Subtracting 5% of $200 does not give the right answer.  If you did start with $190, your interest would be 5% of $190, which is $9.50.  You'd have $199.50 next year, not $200.");
    });
    $('[name=dis5][value=200]').click(function() {
       $("#dis5-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("You don't need $200 now. You only need the amount that will grow to $200 if you leave it in the bank and earn interest for a year.");
    });

    $('[name=dis6][value=18141]').click(function() {
       $("#dis6-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("Correct!");
       $("#dis6A-answer")
       .html("
We want to know the amount of money that will grow to $200 in two years at 5% interest.
This is the amount X such that
X×1.05² = $200.
Divide both sides of that by (1.05)² to solve for X:
X = $200/1.05² = $181.41");
    });

    $('[name=dis6][value!=18141]').click(function() {
       $("#dis6-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("No.  There is only one method that discounts future amounts correctly.");
    });
    $('[name=dis6][value=200]').click(function() {
       $("#dis6-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("You don't need $200 now. You only need the amount that will grow to $200 if you leave it in the bank and earn interest for two years.");
    });

	$("#dis7-button").click(function(){
        var response = parseFloat($("#dis7-response").val(),10);
        if( response === 3.0) {
			$("#dis7-answer").addClass("correct")
       		.removeClass("incorrect")
            .html("Correct!");
            $("#dis7A-answer").html("");

        } else {
			$("#dis7-answer").addClass("incorrect")
       		.removeClass("correct")
            .text("No.  For the present value of an amount one year in the future, we divided $200 by 1.05 once.  For $200 two years in the future, we divided by 1.05 twice.  For three years in the future, ...");
        }
    });

    $('[name=dis8][value=5]').click(function() {
       $("#dis8-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("
Correct!  The most you should be willing to pay is the amount that, if you put it in the bank for 5 years at 5% interest, would grow to $200.");
	   $("#dis8A-answer").html("
If the bond's price is lower than $156.71, you will buy the bond. If the bond's price is higher than $156.71, you will put your money in the bank instead.");
    });
    $('[name=dis8][value!=5]').click(function() {
       $("#dis8-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("No.  The bond matures in 5 years.");
    });

    $('[name=dis9][value=3]').click(function() {
       $("#dis9-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("
Correct!  With three years to go, the bond should be worth $172.77.  The closer it gets to maturity, the more it is worth.  When it finally gets to maturity, it will be worth the full $200.");
	   $("#dis9A-answer").html("");
    });
    $('[name=dis9][value!=3]').click(function() {
       $("#dis9-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("No.  The bond matures in 3 years.");
    });

    $('[name=dis10][value=0]').click(function() {
       $("#dis10percent")
       .html("0%");
       $("#dis10rate")
       .html(".00");
       $("#dis10value1")
       .html("$1000");
       $("#dis10value2")
       .html("$1000");
	   $("#dis10-answer").html("If the discount rate is zero, the bond sells for its value at maturity.");
    });

    $('[name=dis10][value=3]').click(function() {
       $("#dis10percent")
       .html("2.75%");
       $("#dis10rate")
       .html(".0275");
       $("#dis10value1")
       .html("$762.40");
       $("#dis10value2")
       .html("$762.40");
	   $("#dis10-answer").html("This is close to the interest rate on Treasury bonds at this writing (August 2013).");
    });

    $('[name=dis10][value=5]').click(function() {
       $("#dis10percent")
       .html("5%");
       $("#dis10rate")
       .html(".05");
       $("#dis10value1")
       .html("$613.91");
       $("#dis10value2")
       .html("$613.91");
	   $("#dis10-answer").html("The bond's price goes down when the discount rate goes up, and vise-versa.");
    });

    $('[name=dis10][value=15]').click(function() {
       $("#dis10percent")
       .html("15.8%");
       $("#dis10rate")
       .html(".158");
       $("#dis10value1")
       .html("$230.63");
       $("#dis10value2")
       .html("$230.63");
	   $("#dis10-answer").html("The is the highest rate that the U.S. Treasury ever had to pay. It was in September 1981.  The Federal Reserve sold so many government bonds that it forced the price down to this level.  (The Federal Reserve holds a lot of Treasury bonds.  It sells them when it wants to raise interest rates.  It buys them when it wants to lower interest rates.)  Bond prices crashed.");
    });

    $('[name=dis11][value=yes]').click(function() {
       $("#dis11-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("Correct, probably, but what if you'll starve before you get the hen and it starts laying?");
    });

    $('[name=dis11][value=no]').click(function() {
       $("#dis11-answer")
       .addClass("incorrect")
       .removeClass("correct")
       .html("Correct, if you would starve before you got the hen.");
    });

    $('[name=dis11][value=depends]').click(function() {
       $("#dis11-answer")
       .addClass("correct")
       .removeClass("incorrect")
       .html("Correct!  It depends on your rate of time preference, which is about how soon you really need to eat!");
    });

    $('[name=dis11][value=numbers]').click(function() {
       $("#dis11-answer")
       .removeClass("correct")
       .removeClass("incorrect")
       .addClass("hehe")
       .html("Your lucky numbers are 2 44 26 3 8 37.
 If these win the state lottery, you can buy the hen and the egg!");
    });

});


text:
* Contributor may contribute code, tests, ideas and feedback via e-mail: packages@subscribo.io or via GitHub
* Maintainers may, but not have to use the contribution
* Maintainers may use the contribution in its entirety, or just part(s) of it, modified or unmodified
* Contributor by contributing a contribution is giving consent for using and publishing the contribution under [MIT license](http://opensource.org/licenses/MIT) with current or future [license headers](LICENSE)
* Please contribute only those contributions for which you have right to contribute and to give before mentioned consent

##### Contributing code or tests via GitHub:

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Commit just the modifications, do not mess with the composer.json or CHANGELOG.md files.
* Ensure your code is nicely formatted in the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
  style and that all tests pass.
* Send the pull request.
* Check that the Travis CI build passed. If not, rinse and repeat.


text:
<?php

namespace App\Repositories\Backend\News;

use App\Models\CategoriesNews;
use App\Exceptions\GeneralException;
use App\Helper\Catalog\Image;
use App\Repositories\Repository;
use Illuminate\Database\Eloquent\Model;

/**
 * Class EloquentUserRepository
 * @package App\Repositories\User
 */
class CategoryRepository extends Repository
{
    /**
     * 关联储存模型
     */
    const MODEL = CategoriesNews::class;

    public function update(Model $category, array $input)
    {
        if (parent::update($category, $input)) {
            return true;
        }

        throw new GeneralException(trans('更新出错'));
    }

    public function delete(Model $category)
    {
        if ($category->delete()) {
            return true;
        }

        throw new GeneralException('删除出错');
    }
}


text:
package edu.cs4730.nearbyconstreamdemo;

import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.connection.AdvertisingOptions;
import com.google.android.gms.nearby.connection.ConnectionInfo;
import com.google.android.gms.nearby.connection.ConnectionLifecycleCallback;
import com.google.android.gms.nearby.connection.ConnectionResolution;
import com.google.android.gms.nearby.connection.ConnectionsStatusCodes;
import com.google.android.gms.nearby.connection.Payload;
import com.google.android.gms.nearby.connection.PayloadCallback;
import com.google.android.gms.nearby.connection.PayloadTransferUpdate;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * This is the advertise side of the Nearby API.  (server)
 */
public class AdvertiseFragment extends Fragment {

    String TAG = "AdvertiseFragment";
    String UserNickName = "AdvertiseNearbyDemo"; //idk what this should be.  doc's don't say.
    TextView logger;
    boolean mIsAdvertising = false;
    String ConnectedEndPointId;

    Camera2Preview mPreview;
    FrameLayout preview;
    //for taking a picture.
    Camera2CapturePic mCapture;
    Thread myThread;

    public AdvertiseFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_advertise, container, false);
        logger = myView.findViewById(R.id.ad_output);
        myView.findViewById(R.id.start_advertise).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsAdvertising)
                    stopAdvertising();  //already advertising, turn it off
                else
                    startAdvertising();
            }
        });
        myView.findViewById(R.id.end_advertise).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ConnectedEndPointId.compareTo("") != 0) { //connected to someone
                    Nearby.getConnectionsClient(requireContext()).disconnectFromEndpoint(ConnectedEndPointId);
                    ConnectedEndPointId = "";
                }
                if (mIsAdvertising) {
                    stopAdvertising();
                }
            }
        });
        //camera stuff
        preview = (FrameLayout) myView.findViewById(R.id.camera2_preview);

        //we have to pass the camera id that we want to use to the surfaceview
        CameraManager manager = (CameraManager) requireActivity().getSystemService(Context.CAMERA_SERVICE);
        try {
            String cameraId = manager.getCameraIdList()[0];
            mPreview = new Camera2Preview(requireContext(), cameraId);
            preview.addView(mPreview);

        } catch (CameraAccessException e) {
            Log.v(TAG, "Failed to get a camera ID!");
            e.printStackTrace();
        }

        return myView;
    }

    /**
     * Callbacks for connections to other devices.  These call backs are used when a connection is initiated
     * and connection, and disconnect.
     * <p>
     * we auto accept any connection.  We with another callback that allows us to read the data.
     */
    private final ConnectionLifecycleCallback mConnectionLifecycleCallback =
        new ConnectionLifecycleCallback() {
            @Override
            public void onConnectionInitiated(@NonNull String endpointId, ConnectionInfo connectionInfo) {
                logthis("Connection Initiated :" + endpointId + " Name is " + connectionInfo.getEndpointName());
                // Automatically accept the connection on both sides.
                // setups the callbacks to read data from the other connection.
                Nearby.getConnectionsClient(requireContext()).acceptConnection(endpointId, //mPayloadCallback);
                    new PayloadCallback() {
                        @Override
                        public void onPayloadReceived(@NonNull String endpointId, @NonNull Payload payload) {

                            if (payload.getType() == Payload.Type.BYTES) {
                                String stuff = new String(payload.asBytes());
                                logthis("Received data is " + stuff);

                            } else if (payload.getType() == Payload.Type.FILE)
                                logthis("We got a file.  not handled");
                            else if (payload.getType() == Payload.Type.STREAM)
                                //payload.asStream().asInputStream()
                                logthis("We got a stream, not handled");
                        }

                        @Override
                        public void onPayloadTransferUpdate(@NonNull String endpointId, @NonNull PayloadTransferUpdate payloadTransferUpdate) {
                            //if stream or file, we need to know when the transfer has finished.  ignoring this right now.
                        }
                    });
            }

            @Override
            public void onConnectionResult(@NonNull String endpointId, ConnectionResolution result) {
                logthis("Connection accept :" + endpointId + " result is " + result.toString());

                switch (result.getStatus().getStatusCode()) {
                    case ConnectionsStatusCodes.STATUS_OK:
                        // We're connected! Can now start sending and receiving data.
                        ConnectedEndPointId = endpointId;
                        //if we don't then more can be added to conversation, when an List<string> of endpointIds to send to, instead a string.
                        // ... .add(endpointId);
                        stopAdvertising();  //and comment this out to allow more then one connection.
                        logthis("Connected, now launch the picture taking.  wish it was stream... ");

                        sendPictures();

                        break;
                    case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
                        logthis("Status rejected.  :(");
                        // The connection was rejected by one or both sides.
                        break;
                    case ConnectionsStatusCodes.STATUS_ERROR:
                        logthis("Status error.");
                        // The connection broke before it was able to be accepted.
                        break;
                }
            }

            @Override
            public void onDisconnected(@NonNull String endpointId) {
                logthis("Connection disconnected :" + endpointId);
                ConnectedEndPointId = "";  //need a remove if using a list.
            }
        };

    /**
     * Start advertising the nearby.  It sets the callback from above with what to once we get a connection
     * request.
     */
    private void startAdvertising() {

        Nearby.getConnectionsClient(requireContext())
            .startAdvertising(
                UserNickName,    //human readable name for the endpoint.
                MainActivity.ServiceId,  //unique identifier for advertise endpoints
                mConnectionLifecycleCallback,  //callback notified when remote endpoints request a connection to this endpoint.
                new AdvertisingOptions.Builder().setStrategy(MainActivity.STRATEGY).build()
            )
            .addOnSuccessListener(
                new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unusedResult) {
                        mIsAdvertising = true;
                        logthis("we're advertising!");
                    }
                })
            .addOnFailureListener(
                new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        mIsAdvertising = false;
                        // We were unable to start advertising.
                        logthis("we're failed to advertise");
                        e.printStackTrace();
                    }
                });
    }

    /**
     * turn off advertising.  Note, you can not add success and failure listeners.
     */
    public void stopAdvertising() {
        mIsAdvertising = false;
        Nearby.getConnectionsClient(requireContext()).stopAdvertising();
        logthis("Advertising stopped.");
    }

    /**
     * Sends a {@link Payload} to all currently connected endpoints.
     */
    protected void send(File file) {

        //basic error checking
        if (ConnectedEndPointId.compareTo("") == 0)   //empty string, no connection
            return;

        Uri uri = Uri.fromFile(file);
        // Open the ParcelFileDescriptor for this URI with read access.
        ParcelFileDescriptor pfd = null;
        try {
            pfd = requireContext().getContentResolver().openFileDescriptor(uri, "r");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        Payload payload = Payload.fromFile(pfd);

        //Payload payload = Payload.fromBytes(data.getBytes());

        // sendPayload (List<String> endpointIds, Payload payload)  if more then one connection allowed.
        Nearby.getConnectionsClient(requireContext()).
            sendPayload(ConnectedEndPointId,  //end point to end to
                payload)   //the actual payload of data to send.
            .addOnSuccessListener(new OnSuccessListener<Void>() {  //don't know if need this one.
                @Override
                public void onSuccess(Void aVoid) {
                    logthis("Message send successfully.");
                }
            })
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    logthis("Message send completed.");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    logthis("Message send failed.");
                    e.printStackTrace();
                }
            });
    }

    @Override
    public void onStop() {
        super.onStop();
        stopAdvertising();
    }

    /**
     * helper function to log and add to a textview.
     */
    public void logthis(String msg) {
        logger.append(msg + "\n");
        Log.d(TAG, msg);
    }

    /**
     * So here we are going to send a series of pictures, instead of the camera stream, since videoplayer doesn't allow inpuststream... stupid.
     */
    void sendPictures() {
        myThread = new Thread(new sendPics(250));
        //so going have to be a thread or async task or this will overload the main activity.
        if (mCapture == null) // While I would like the declare this earlier, the camera is not setup yet, so wait until now.
            mCapture = new Camera2CapturePic(requireContext(), mPreview);
        mCapture.setThread(myThread);
        myThread.start();

    }

    class sendPics implements Runnable {
        int sleeptime =250;
        sendPics (int sleeptime) {
            this.sleeptime = sleeptime;
        }

        @Override
        public void run() {
            int i = 0;
            File mediaFile;
            File mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            // This location works best if you want the created images to be shared
            // between applications and persist after your app has been uninstalled.

            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("MyCameraApp", "failed to create directory");
                    return;
                }
            }
            while (!ConnectedEndPointId.equals("")) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + i + ".jpg");
                Log.d(TAG, "File is " + mediaFile.getAbsolutePath());
                // get an image from the camera
                if (mCapture.reader != null) {  //I'm sure it's setup correctly if reader is not null.
                    mCapture.TakePicture(mediaFile);
                    try {
                        synchronized (myThread) {
                            myThread.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "pic taken, now sending.");
                    send(mediaFile);
                    Log.d(TAG, "Send successful");
                }
                try {
                    Thread.sleep(sleeptime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                if (i == 4) i = 0;  //4 pictures a second?

            }
            Log.d(TAG, "Leaving thread!");
        }

    }
}


text:
from rest_framework import serializers

import pdb

from .models import *
from authentication.serializers import AccountSerializer

class ImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(max_length=128, use_url=True,)
    class Meta:
        model = Image
        fields = ('title', 'image', 'brew', 'brewery')

    def create(self, validated_data):
        return Image.objects.create(**validated_data)

class BrewDateSerializer(serializers.ModelSerializer):
    class Meta:
        model = BrewDate
        fields = ('brew', 'date', 'activity')

    def create(self, validated_data):
        return BrewDate.objects.create(**validated_data)

class BrewerySerializer(serializers.ModelSerializer):

    class Meta:
        model = Brewery
        fields = ('id', 'name', 'description')
        read_only_fields = ('id')

        def create(self, validated_data):
            return Brewery.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.name = validated_data.get('name', instance.name)
            instance.description = validated_data.get('description', instance.description)

            instance.save()
            return instance

        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(BrewerSerializer, self).get_validation_exclusions()

            return exclusions + ['brewery','user']

class BrewerSerializer(serializers.ModelSerializer):
    brewery = BrewerySerializer(read_only=True, required=False)
    user = AccountSerializer(read_only=True, required=False)

    class Meta:
        model = Brewer
        fields = ('id', 'brewery', 'user')
        read_only_fields = ('id')

        def create(self, validated_data):
            return Brewer.objects.create(**validated_data)

        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(BrewerSerializer, self).get_validation_exclusions()

            return exclusions + ['brewery','user']

class BrewSerializer(serializers.ModelSerializer):
    brewer = BrewerSerializer(read_only=True, required=False)
    images = ImageSerializer(read_only=True, many=True, required=False)

    class Meta:
        model = Brew
        fields = ('id', 'name', 'description', 'style', 'type', 'abv', 'brewer', 'images')
        read_only_fields = ('id')

        def create(self, validated_data):
            return Brew.objects.create(**validated_data)

        def update(self, instance, validated_data):
            instance.name = validated_data.get('name', instance.name)
            instance.description = validated_data.get('description', instance.description)

            instance.save()
            return instance
        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(BrewSerializer, self).get_validation_exclusions()
            return exclusions + ['brewer']

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ('id', 'tasting', 'category', 'key')
        read_only_fields = ('id')

        def create(self, validated_data):
            return Keyword.objects.create(**validated_data)

class TastingSerializer(serializers.ModelSerializer):
    brew = BrewSerializer(required=False, read_only=True)
    user = AccountSerializer(required=False, read_only=True)
    keywords = KeywordSerializer(many=True, required=False, read_only=True)

    class Meta:
        model = Tasting
        fields = ('id', 'brew', 'user', 'appearance', 'smell', 'taste', 'mouthfeel', 'overall', 'keywords')
        read_only_fields = ('id')
        extra_kwargs = {'brew_id': {'write_only': True}}

        def create(self, validated_data):
            pdb.set_trace()
            brew_id = validated_data.pop('brew_id')
            brew = Brew.objects.get(id=brew_id)
            return Tasting.objects.create(brew=brew, **validated_data)

        def update(self, instance, validated_data):
            instance.appearance = validated_data.get('appearance', instance.appearance)
            instance.smell = validated_data.get('smell', instance.smell)
            instance.taste = validated_data.get('taste', instance.taste)
            instance.mouthfeel = validated_data.get('mouthfeel', instance.mouthfeel)
            instance.overall = validated_data.get('overall', instance.overall)
            instance.keywords = validated_data.get('keywords', instance.keywords)

            instance.save()
            return instance


text:
package skadistats.clarity.model.csgo;

import com.google.protobuf.ByteString;
import com.google.protobuf.ZeroCopy;
import skadistats.clarity.io.Util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class PlayerInfoType {

    private static final int MAX_PLAYER_NAME_LENGTH = 128;
    private static final int SIGNED_GUID_LEN = 32;
    private static final int MAX_CUSTOM_FILES = 4;

    private final long version;
    private final long xuid;
    private final String name;
    private final int userId;
    private final String guid;
    private final int friendsId;
    private final String friendsName;
    private final boolean fakePlayer;
    private final boolean isHltv;
    private final int[] customFiles;

    public PlayerInfoType(ByteString byteString) throws IOException {
        ByteBuffer buf = ByteBuffer.wrap(ZeroCopy.extract(byteString)).order(ByteOrder.BIG_ENDIAN);
        version = buf.getLong();
        xuid = buf.getLong();
        name = readZeroTerminated(buf, MAX_PLAYER_NAME_LENGTH);
        userId = buf.getInt();
        guid = readZeroTerminated(buf, SIGNED_GUID_LEN + 1);
        friendsId = buf.getInt();
        buf.position(buf.position() + 3);
        friendsName = readZeroTerminated(buf, MAX_PLAYER_NAME_LENGTH);
        fakePlayer = buf.get() == (byte)1;
        isHltv = buf.get() == (byte)1;
        customFiles = new int[MAX_CUSTOM_FILES];
        for (int i = 0; i < MAX_CUSTOM_FILES; i++) {
            customFiles[i] = buf.getInt();
        }
        // TODO: still 6 bytes remaining, so something is wrong...
    }

    private String readZeroTerminated(ByteBuffer buffer, int size) throws IOException {
        return Util.readFixedZeroTerminated(buffer, size);
    }

    public long getVersion() {
        return version;
    }

    public long getXuid() {
        return xuid;
    }

    public String getName() {
        return name;
    }

    public int getUserId() {
        return userId;
    }

    public String getGuid() {
        return guid;
    }

    public int getFriendsId() {
        return friendsId;
    }

    public String getFriendsName() {
        return friendsName;
    }

    public boolean isFakePlayer() {
        return fakePlayer;
    }

    public boolean isHltv() {
        return isHltv;
    }

    public int[] getCustomFiles() {
        return customFiles;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("PlayerInfoType{");
        sb.append("version=").append(version);
        sb.append(", xuid=").append(xuid);
        sb.append(", name='").append(name).append('\'');
        sb.append(", userId=").append(userId);
        sb.append(", guid='").append(guid).append('\'');
        sb.append(", friendsId=").append(friendsId);
        sb.append(", friendsName='").append(friendsName).append('\'');
        sb.append(", fakePlayer=").append(fakePlayer);
        sb.append(", isHltv=").append(isHltv);
        sb.append(", customFiles=");
        if (customFiles == null) sb.append("null");
        else {
            sb.append('[');
            for (int i = 0; i < customFiles.length; ++i)
                sb.append(i == 0 ? "" : ", ").append(customFiles[i]);
            sb.append(']');
        }
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PlayerInfoType that = (PlayerInfoType) o;

        if (version != that.version) return false;
        if (xuid != that.xuid) return false;
        if (userId != that.userId) return false;
        if (friendsId != that.friendsId) return false;
        if (fakePlayer != that.fakePlayer) return false;
        if (isHltv != that.isHltv) return false;
        if (!name.equals(that.name)) return false;
        if (!guid.equals(that.guid)) return false;
        if (!friendsName.equals(that.friendsName)) return false;
        return Arrays.equals(customFiles, that.customFiles);
    }

    @Override
    public int hashCode() {
        int result = (int) (version ^ (version >>> 32));
        result = 31 * result + (int) (xuid ^ (xuid >>> 32));
        result = 31 * result + name.hashCode();
        result = 31 * result + userId;
        result = 31 * result + guid.hashCode();
        result = 31 * result + friendsId;
        result = 31 * result + friendsName.hashCode();
        result = 31 * result + (fakePlayer ? 1 : 0);
        result = 31 * result + (isHltv ? 1 : 0);
        result = 31 * result + Arrays.hashCode(customFiles);
        return result;
    }

}


text:
package org.apache.camel.component.file.remote.integration;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertFalse;

public class FtpConsumerDoneFileNameFixedIT extends FtpServerTestSupport {

    protected String getFtpUrl() {
        return "ftp://admin@localhost:{{ftp.server.port}}/done?password=admin&initialDelay=0&delay=100&stepwise=false";
    }

    @Test
    public void testDoneFileName() throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(0);

        template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");

        // wait a bit and it should not pickup the written file as there are no
        // done file
        await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> assertMockEndpointsSatisfied());

        resetMocks();

        getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");

        // write the done file
        template.sendBodyAndHeader(getFtpUrl(), "", Exchange.FILE_NAME, "fin.dat");

        assertMockEndpointsSatisfied();

        // give time for done file to be deleted
        File file = new File(service.getFtpRootDir() + "done/fin.dat");
        // done file should be deleted now
        await().atMost(1, TimeUnit.SECONDS)
                .untilAsserted(() -> assertFalse(file.exists(), "Done file should be deleted: " + file));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(getFtpUrl() + "&doneFileName=fin.dat").convertBodyTo(String.class).to("mock:result");
            }
        };
    }

}


text:
package org.jboss.netty.handler.ipfilter;

import java.net.InetAddress;

/**
 * This Interface defines an IpSet object.
 *
 * @author frederic bregier
 *
 */
public interface IpSet
{
   /**
    * Compares the given InetAddress against the IpSet and returns true if
    * the InetAddress is contained in this Rule and false if not.
    * @param inetAddress1
    * @return returns true if the given IP address is contained in the current
    * IpSet.
    */
   public boolean contains(InetAddress inetAddress1);
}


text:
package com.vityuk.ginger.provider;

import com.vityuk.ginger.LocaleResolver;
import com.vityuk.ginger.PropertyResolver;
import com.vityuk.ginger.cache.CacheBuilder;
import com.vityuk.ginger.cache.CacheLoader;
import com.vityuk.ginger.cache.LoadingCache;
import com.vityuk.ginger.loader.LocalizationLoader;
import com.vityuk.ginger.loader.ResourceLoader;
import com.vityuk.ginger.provider.format.MessageFormatFactory;
import com.vityuk.ginger.provider.plural.PluralFormSelectorResolver;
import com.vityuk.ginger.util.MiscUtils;
import com.vityuk.ginger.cache.ThreadLocalLoadingCache;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.vityuk.ginger.util.Preconditions.checkNotNull;

/**
 * @author Andriy Vityuk
 */
public class DefaultLocalizationProvider implements LocalizationProvider {
    public static final char LOCALE_SEPARATOR = '_';
    public static final char FILE_EXTENSION_SEPARATOR = '.';

    private static final String EMPTY_SELECTOR = "";
    private static final MessageFormat NULL_MESSAGE_FORMAT = new MessageFormat("");

    private final LocaleResolver localeResolver;
    private final ResourceLoader resourceLoader;
    private final LocalizationLoader localizationLoader;
    private final List<String> locations;
    private final MessageFormatFactory messageFormatFactory;
    private final PluralFormSelectorResolver pluralFormSelectorResolver;

    private final LoadingCache<Locale, PropertyResolver> propertyResolverCache;
    private final LoadingCache<MessageKey, MessageFormat> messageFormatCache;

    private DefaultLocalizationProvider(Builder builder) {
        localeResolver = checkNotNull(builder.localeResolver);
        resourceLoader = checkNotNull(builder.resourceLoader);
        localizationLoader = checkNotNull(builder.localizationLoader);
        locations = checkNotNull(builder.locations);
        messageFormatFactory = checkNotNull(builder.messageFormatFactory);
        pluralFormSelectorResolver = checkNotNull(builder.pluralFormSelectorResolver);

        propertyResolverCache = createPropertyResolverCache(builder, new CacheLoader<Locale, PropertyResolver>() {
            @Override
            public PropertyResolver load(Locale locale) throws Exception {
                return createPropertyResolver(locale);
            }
        });

        messageFormatCache = createMessageFormatCache(builder, new CacheLoader<MessageKey, MessageFormat>() {
            @Override
            public MessageFormat load(MessageKey key) throws Exception {
                return createMessageFormat(key.getLocale(), key.getKey(), key.getSelector());
            }
        });
    }

    @Override
    public String getString(String key) {
        return getPropertyResolver().getString(checkNotNull(key));
    }

    @Override
    public Boolean getBoolean(String key) {
        return getPropertyResolver().getBoolean(checkNotNull(key));
    }

    @Override
    public Integer getInteger(String key) {
        return getPropertyResolver().getInteger(checkNotNull(key));
    }

    @Override
    public Long getLong(String key) {
        return getPropertyResolver().getLong(checkNotNull(key));
    }

    @Override
    public Float getFloat(String key) {
        return getPropertyResolver().getFloat(checkNotNull(key));
    }

    @Override
    public Double getDouble(String key) {
        return getPropertyResolver().getDouble(checkNotNull(key));
    }

    @Override
    public List<String> getStringList(String key) {
        return getPropertyResolver().getStringList(checkNotNull(key));
    }

    @Override
    public Map<String, String> getStringMap(String key) {
        return getPropertyResolver().getStringMap(checkNotNull(key));
    }

    @Override
    public String getMessage(String key, Object... parameters) {
        return formatMessage(getMessageFormat(key), parameters);
    }

    @Override
    public MessageFormat getMessageFormat(String key) {
        return getSelectedMessageFormat(key, EMPTY_SELECTOR);
    }

    @Override
    public String getSelectedMessage(String key, String selector, Object... parameters) {
        return formatMessage(getSelectedMessageFormat(key, selector), parameters);
    }

    @Override
    public MessageFormat getSelectedMessageFormat(String key, String selector) {
        checkNotNull(key);
        checkNotNull(selector);
        Locale locale = getCurrentLocale();

        MessageFormat messageFormat = getMessageFormat(locale, key, selector);
        if (messageFormat == null && !isEmptySelector(selector)) {
            // Fallback to message without selector
            messageFormat = getMessageFormat(locale, key, EMPTY_SELECTOR);
        }
        return messageFormat;
    }

    @Override
    public String getPluralMessage(String key, Number count, Object... parameters) {
        MessageFormat messageFormat = getPluralMessageFormat(checkNotNull(key), count);
        return formatMessage(messageFormat, mergeParameters(count, parameters));
    }

    private PropertyResolver getPropertyResolver() {
        Locale locale = getCurrentLocale();
        return getPropertyResolver(locale);
    }

    private Locale getCurrentLocale() {
        return checkNotNull(localeResolver.getLocale(), "LocaleResolver must return not null Locale");
    }

    private String getPluralFormSelector(Locale locale, Number count) {
        return pluralFormSelectorResolver.resolve(locale.getLanguage(), count.intValue());
    }

    private PropertyResolver getPropertyResolver(Locale locale) {
        try {
            return propertyResolverCache.getUnchecked(locale);
        } catch (RuntimeException e) {
            throw MiscUtils.propagate(e.getCause());
        }
    }

    private MessageFormat getMessageFormat(Locale locale, String key, String selector) {
        try {
            MessageKey messageKey = new MessageKey(locale, key, selector);
            MessageFormat messageFormatOptional = messageFormatCache.getUnchecked(messageKey);
            if (messageFormatOptional == NULL_MESSAGE_FORMAT) {
                return null;
            }
            return messageFormatOptional;
        } catch (RuntimeException e) {
            throw MiscUtils.propagate(e.getCause());
        }
    }

    private PropertyResolver createPropertyResolver(Locale locale) {
        List<PropertyResolver> propertyResolvers = new ArrayList<PropertyResolver>(locations.size());
        for (String location : locations) {
            propertyResolvers.add(createPropertyResolver(location, locale));
        }
        return createMultiPropertyResolver(propertyResolvers);
    }

    public MessageFormat getPluralMessageFormat(String key, Number count) {
        Locale locale = getCurrentLocale();

        MessageFormat messageFormat = null;
        if (count.intValue() == 0 || count.intValue() == 1) {
            // Special cases, allows to define specific message for 0 and 1 count
            String selector = String.valueOf(count);
            messageFormat = getMessageFormat(locale, key, selector);
        }

        if (messageFormat == null) {
            String selector = getPluralFormSelector(locale, count);
            messageFormat = getMessageFormat(locale, key, selector);
        }

        if (messageFormat == null) {
            // Fallback to message without selector
            messageFormat = getMessageFormat(locale, key, EMPTY_SELECTOR);
        }

        return messageFormat;
    }

    private MessageFormat createMessageFormat(Locale locale, String key, String selector) {
        final String format = getMessageFormatString(locale, key, selector);
        if (format == null) {
            return NULL_MESSAGE_FORMAT;
        }
        return messageFormatFactory.create(locale, format);
    }

    private String getMessageFormatString(Locale locale, String key, String selector) {
        PropertyResolver propertyResolver = getPropertyResolver(locale);
        if (isEmptySelector(selector)) {
            return propertyResolver.getString(key);
        }

        Map<String, String> propertyMap = propertyResolver.getStringMap(key);
        return propertyMap == null ? null : propertyMap.get(selector);
    }

    private PropertyResolver createPropertyResolver(String location, Locale locale) {
        InputStream inputStream = openLocation(location, locale);
        try {
            return loadLocalization(location, inputStream);
        } finally {
            MiscUtils.closeQuietly(inputStream);
        }
    }

    private InputStream openLocation(String location, Locale locale) {
        if (!resourceLoader.isSupported(location)) {
            throw new UnsupportedLocationException(location);
        }
        return findResourceForLocale(location, locale);
    }

    private InputStream findResourceForLocale(String location, Locale locale) {
        int idx = location.lastIndexOf(FILE_EXTENSION_SEPARATOR);
        if (idx == -1) {
            throw new RuntimeException("Localization resource should have extension in location: '" + location + "'");
        }
        String prefix = location.substring(0, idx);
        String suffix = location.substring(idx);

        for (Locale candidateLocale : createCandidateLocales(locale)) {
            String localizedLocation = createLocalizedLocation(prefix, suffix, candidateLocale);
            InputStream inputStream = openStream(localizedLocation);
            if (inputStream != null) {
                return inputStream;
            }
        }

        throw new ResourceNotFoundException(location, locale);
    }

    private InputStream openStream(String location) {
        try {
            return resourceLoader.openStream(location);
        } catch (IOException e) {
            throw new RuntimeException("Unable to open location: '" + location + "'", e);
        }
    }

    private PropertyResolver loadLocalization(String location, InputStream inputStream) {
        try {
            return localizationLoader.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("Unable to load localization resource: '" + location + "'", e);
        }
    }

    private String formatMessage(MessageFormat messageFormat, Object[] obj) {
        return messageFormat == null ? null : messageFormat.format(obj);
    }

    public static Builder builder() {
        return new Builder();
    }

    private static LoadingCache<MessageKey, MessageFormat> createMessageFormatCache(Builder builder,
                                                                                CacheLoader<MessageKey, MessageFormat> cacheLoader) {
        if (builder.maxCacheTimeInSec == -1) {
            return ThreadLocalLoadingCache.create(cacheLoader);
        } else {
            return ThreadLocalLoadingCache.create(cacheLoader, builder.maxCacheTimeInSec, TimeUnit.SECONDS);
        }
    }

    private static LoadingCache<Locale, PropertyResolver> createPropertyResolverCache(Builder builder,
                                                                                CacheLoader<Locale, PropertyResolver> cacheLoader) {
        CacheBuilder<Object, Object> cacheBuilder = new CacheBuilder<Object, Object>();
        if (builder.maxCacheTimeInSec >= 0) {
            cacheBuilder.expireAfterWrite(builder.maxCacheTimeInSec, TimeUnit.SECONDS);
        }
        return cacheBuilder.build(cacheLoader);
    }

    private static List<Locale> createCandidateLocales(Locale locale) {
        List<Locale> locales = new ArrayList<Locale>(2);

        if (!locale.getCountry().isEmpty()) {
            locales.add(locale);
        }
        if (!locale.getLanguage().isEmpty()) {
            locales.add(locales.isEmpty() ? locale : new Locale(locale.getLanguage(), "", ""));
        }
        locales.add(Locale.ROOT);

        return locales;
    }

    private static String createLocalizedLocation(String locationPrefix, String locationSuffix, Locale locale) {
        StringBuilder builder = new StringBuilder(locationPrefix.length() + locationSuffix.length() + 6);

        builder.append(locationPrefix);
        if (!locale.getLanguage().isEmpty()) {
            builder.append(LOCALE_SEPARATOR);
            builder.append(locale.getLanguage());
        }
        if (!locale.getCountry().isEmpty()) {
            builder.append(LOCALE_SEPARATOR);
            builder.append(locale.getCountry());
        }
        builder.append(locationSuffix);

        return builder.toString();
    }

    private static PropertyResolver createMultiPropertyResolver(List<PropertyResolver> propertyResolvers) {
        if (propertyResolvers.size() == 1) {
            return propertyResolvers.get(0);
        }
        return new ChainedPropertyResolver(propertyResolvers);
    }

    private static Object[] mergeParameters(Number count, Object[] parameters) {
        Object[] mergedParameters = new Object[parameters.length + 1];
        mergedParameters[0] = count;
        System.arraycopy(parameters, 0, mergedParameters, 1, parameters.length);
        return mergedParameters;
    }

    private static boolean isEmptySelector(String selector) {
        return selector.isEmpty();
    }

    public static class Builder {
        private LocaleResolver localeResolver;
        private ResourceLoader resourceLoader;
        private LocalizationLoader localizationLoader;
        private List<String> locations;
        private MessageFormatFactory messageFormatFactory;
        private PluralFormSelectorResolver pluralFormSelectorResolver;
        private int maxCacheTimeInSec = -1;

        public Builder withLocaleResolver(LocaleResolver localeResolver) {
            this.localeResolver = localeResolver;
            return this;
        }

        public Builder withResourceLoader(ResourceLoader resourceLoader) {
            this.resourceLoader = resourceLoader;
            return this;
        }

        public Builder withLocalizationLoader(LocalizationLoader localizationLoader) {
            this.localizationLoader = localizationLoader;
            return this;
        }

        public Builder withLocations(List<String> locations) {
            this.locations = locations;
            return this;
        }

        public Builder withMessageFormatFactory(MessageFormatFactory messageFormatFactory) {
            this.messageFormatFactory = messageFormatFactory;
            return this;
        }

        public Builder withPluralFormSelectorResolver(PluralFormSelectorResolver pluralFormSelectorResolver) {
            this.pluralFormSelectorResolver = pluralFormSelectorResolver;
            return this;
        }

        public Builder withMaxCacheTimeInSec(int maxCacheTimeInSec) {
            this.maxCacheTimeInSec = maxCacheTimeInSec;
            return this;
        }

        public DefaultLocalizationProvider build() {
            return new DefaultLocalizationProvider(this);
        }
    }

    private static final class MessageKey {
        private final Locale locale;
        private final String key;
        private final String selector;

        public MessageKey(Locale locale, String key, String selector) {
            this.locale = locale;
            this.key = key;
            this.selector = selector;
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(new Object[] {key, selector, locale});
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            MessageKey that = (MessageKey) o;
            return MiscUtils.equal(key, that.key) && MiscUtils.equal(selector, selector) &&
                    MiscUtils.equal(locale, that.locale);
        }

        public Locale getLocale() {
            return locale;
        }

        public String getKey() {
            return key;
        }

        public String getSelector() {
            return selector;
        }
    }
}


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

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

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.nps.moves.dis7

Class SeparationVP

java.lang.Object

edu.nps.moves.dis7.SeparationVP

All Implemented Interfaces:

java.io.Serializable

public class SeparationVP
extends java.lang.Object
implements java.io.Serializable

Physical separation of an entity from another entity.  Section 6.2.94.6

 Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All rights reserved.
 This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html

Author:

DMcG

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

protected short
padding1

padding

protected int
padding2

padding

protected EntityID
parentEntityID

ID of parent

protected short
preEntityIndicator

Whether the entity existed prior to separation EBV

protected short
reasonForSeparation

Reason for separation.

protected short
recordType

the identification of the Variable Parameter record.

protected long
stationLocation

Station separated from

Constructor Summary

Constructors

Constructor and Description

SeparationVP()

Constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

boolean
equalsImpl(java.lang.Object obj)

Compare all fields that contribute to the state, ignoring
 transient and static fields, for this and the supplied object

int
getMarshalledSize()

short
getPadding1()

int
getPadding2()

EntityID
getParentEntityID()

short
getPreEntityIndicator()

short
getReasonForSeparation()

short
getRecordType()

long
getStationLocation()

void
marshal(java.nio.ByteBuffer buff)

Packs a Pdu into the ByteBuffer.

void
marshal(java.io.DataOutputStream dos)

void
setPadding1(short pPadding1)

void
setPadding2(int pPadding2)

void
setParentEntityID(EntityID pParentEntityID)

void
setPreEntityIndicator(short pPreEntityIndicator)

void
setReasonForSeparation(short pReasonForSeparation)

void
setRecordType(short pRecordType)

void
setStationLocation(long pStationLocation)

void
unmarshal(java.nio.ByteBuffer buff)

Unpacks a Pdu from the underlying data.

void
unmarshal(java.io.DataInputStream dis)

Methods inherited from class java.lang.Object

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

Field Detail

recordType

protected short recordType

the identification of the Variable Parameter record. Enumeration from EBV

reasonForSeparation

protected short reasonForSeparation

Reason for separation. EBV

preEntityIndicator

protected short preEntityIndicator

Whether the entity existed prior to separation EBV

padding1

protected short padding1

padding

parentEntityID

protected EntityID parentEntityID

ID of parent

padding2

protected int padding2

padding

stationLocation

protected long stationLocation

Station separated from

Constructor Detail

SeparationVP

public SeparationVP()

Constructor

Method Detail

getMarshalledSize

public int getMarshalledSize()

setRecordType

public void setRecordType(short pRecordType)

getRecordType

public short getRecordType()

setReasonForSeparation

public void setReasonForSeparation(short pReasonForSeparation)

getReasonForSeparation

public short getReasonForSeparation()

setPreEntityIndicator

public void setPreEntityIndicator(short pPreEntityIndicator)

getPreEntityIndicator

public short getPreEntityIndicator()

setPadding1

public void setPadding1(short pPadding1)

getPadding1

public short getPadding1()

setParentEntityID

public void setParentEntityID(EntityID pParentEntityID)

getParentEntityID

public EntityID getParentEntityID()

setPadding2

public void setPadding2(int pPadding2)

getPadding2

public int getPadding2()

setStationLocation

public void setStationLocation(long pStationLocation)

getStationLocation

public long getStationLocation()

marshal

public void marshal(java.io.DataOutputStream dos)

unmarshal

public void unmarshal(java.io.DataInputStream dis)

marshal

public void marshal(java.nio.ByteBuffer buff)

Packs a Pdu into the ByteBuffer.

Parameters:

buff - The ByteBuffer at the position to begin writing

Throws:

java.nio.BufferOverflowException - if buff is too small

java.nio.ReadOnlyBufferException - if buff is read only

Since:

??

See Also:

ByteBuffer

unmarshal

public void unmarshal(java.nio.ByteBuffer buff)

Unpacks a Pdu from the underlying data.

Parameters:

buff - The ByteBuffer at the position to begin reading

Throws:

java.nio.BufferUnderflowException - if buff is too small

Since:

??

See Also:

ByteBuffer

equals

public boolean equals(java.lang.Object obj)

Overrides:

equals in class java.lang.Object

equalsImpl

public boolean equalsImpl(java.lang.Object obj)

Compare all fields that contribute to the state, ignoring
 transient and static fields, for this and the supplied object

Parameters:

obj - the object to compare to

Returns:

true if the objects are equal, false otherwise.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php
/**
 * (c) Vespolina Project http://www.vespolina-project.org
 *
 * (c) Daniel Kucharski <daniel@xerias.be>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Vespolina\DocumentBundle\Model;

use Vespolina\CoreBundle\Component\Identifier\IdentifierInterface;
use Vespolina\DocumentBundle\Model\DocumentInterface;
use Vespolina\DocumentBundle\Model\DocumentItemInterface;
use Vespolina\DocumentBundle\Model\DocumentPartnerRoleInterface;
use Vespolina\PartnerBundle\Model\PartnerInterface;

class Document implements DocumentInterface
{
    protected $documentConfigurationName;
    protected $identifiers;
    protected $items;
    protected $partnersByRole;

    /**
     * Constructor
     */
    public function __construct($documentConfigurationName)
    {
        $this->documentConfigurationName = $documentConfigurationName;
        $this->identifiers = array();
        $this->items = array();
        $this->partnersByRole = array();
    }

    /**
     * @inheritdoc
     */
    public function addItem(DocumentItemInterface $documentItem)
    {
        $this->items[] = $documentItem;
    }

    /**
     * @inheritdoc
     */
    public function addPartner(PartnerInterface $partner, DocumentPartnerRoleInterface $partnerFunction)
    {
        $partnerRoleName = $partnerFunction->getName();

        if (!array_key_exists($partnerRoleName, $this->partnersByRole)) {
            $this->partnersByRole[$partnerRoleName] = array();
        }

        $this->partnersByRole[$partnerRoleName][] = $partner;
    }

    /**
     * @inheritdoc
     */
    public function getDocumentIdentifier($name)
    {
        return $this->identifiers[$name];
    }

    /**
     * @inheritdoc
     */
    public function getDocumentConfigurationName()
    {
        return $this->documentConfigurationName;
    }

    /**
     * @inheritdoc
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @inheritdoc
     */
    public function getPartners(DocumentPartnerRoleInterface $partnerRole = null)
    {
        if ($partnerRole) {
            return $this->partnersByRole[$partnerRole->getName()];
        } else {
            $partners = array();

            foreach ($this->partnersByRole as $partnersInRole) {
                foreach ($partnersInRole as $partnerInRole) {
                    $partners[] = $partnerInRole;
                }
            }
            return $partners;
        }
    }

    /**
     * @inheritdoc
     */
    public function setDocumentIdentifier($name, IdentifierInterface $documentIdentifier)
    {
        $this->identifiers[$name] = $documentIdentifier;
    }
}