text:
package org.jboss.arquillian.container.test.api;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Defines that the target should operate within the context of the referenced deployment.
 *

 * When using multiple {@link Deployment}'s within the same TestCase you need to specify which deployment the
 * individual test methods should operate on.
 *

 * Within the context of a deployment you will have access to the meta data provided by the
 * deployment and the container where it is deployed, e.g. URLs
 *

 * Usage Example for test method:

 *

 * @Deployment(name = "X")
 * public static WebArchive create() {
 *      return ShrinkWrap.create(WebArchive.class)
 *          .addClass(MyServletX.class);
 * }
 *
 * @Deployment(name = "Y")
 * public static WebArchive create() {
 *      return ShrinkWrap.create(WebArchive.class)
 *          .addClass(MyServletY.class);
 * }
 *
 * @Test @OperatesOnDeployment("X")
 * public void shouldExecuteInX() { ... }
 *
 * @Test @OperatesOnDeployment("Y")
 * public void shouldExecuteInY() { ... }
 *

 *

 * Additionally you can reference another deployments metadata from within another context by qualifiing
 * OperateOnDeployment on ArquillianResource injection points.
 *

 *

 * Usage Example for ArquillianResource:

 *

 * @Deployment(name = "X")
 * public static WebArchive create() {
 *      return ShrinkWrap.create(WebArchive.class)
 *          .addClass(MyServletX.class);
 * }
 * @Deployment(name = "Y")
 * public static WebArchive create() {
 *      return ShrinkWrap.create(WebArchive.class)
 *          .addClass(MyServletY.class);
 * }
 *
 * @Test @OperatesOnDeployment("X")
 * public void shouldExecuteInX() { ... }
 *
 * @Test @OperatesOnDeployment("Y") @RunAsClient
 * public void shouldExecuteInY(@ArquillianResource @OperateOnDeployment("X") URL deploymentXURLContext) { ... }
 *

 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@Documented
@Retention(RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface OperateOnDeployment {
    /**
     * Refer to the deployment name this should operate on.
     *
     * @return The Deployment name this method operates on
     *
     * @see Deployment#name()
     */
    String value();
}

redpajama_set_name: RedPajamaGithub


text:
should-promised
===============

There some helpers for asserting promises.

## .Promise

Assert given object is promise

## .fulfilled

Assert given promise will be fulfilled. It will return promise.

```
it('should be allow to check if promise fulfilled', function() {
  return promised(10).should.be.fulfilled();
});
```

## .fulfilledWith

Assert given promise will be fulfilled with an expected value. It will return promise.

```
it('should be allow to check if promise fulfilledWith an expected value', function() {
  return promised(10).should.be.fulfilledWith(10);
});
```

## .rejected

Assert given promise will be rejected. It will return promise.

```
it('should be allow to check if promise rejected', function() {
  return promiseFail().should.be.rejected();
});
```

## .rejectedWith

Assert given promise will be rejected with matched Error. Arguments are the same as Assertion\#throw.

## .finally or .eventually

This method begin assertions for promises, all next .chain calls will be shortcuts for .thenable calls on promise.

So you can do like this

```js
promised('abc').should.finally.be.exactly('abc')
      .and.be.a.String;

//or combine with any of Promise methods as any assertion will return Promise itself

Promise.all([
  promised(10).should.finally.be.a.Number,
  promised('abc').should.finally.be.a.String
])
```

## Before .finally

Everything you did before .finally saved into new assertion (but that is not quite usefull as object will be promise).
Main idea is to save `.not` and `.any`.


text:
package stack.simulator.des;

import java.util.LinkedList;

public class EventBucket extends LinkedList<Event>{
	private static final long serialVersionUID = 1L;
	public int timestep;

	public EventBucket(int timestep){
		super();
		this.timestep = timestep;
	}
}


text:
<?php

declare(strict_types=1);

namespace Prooph\ServiceBus\Message\HumusAmqp;

use DateTimeImmutable;
use DateTimeZone;
use Humus\Amqp\DeliveryResult;
use Humus\Amqp\Envelope;
use Humus\Amqp\Queue;
use Prooph\Common\Messaging\MessageFactory;
use Prooph\EventStore\Exception\ConcurrencyException;
use Prooph\ServiceBus\EventBus;

final class AmqpEventConsumerCallback
{
    /**
     * @var EventBus
     */
    private $eventBus;

    /**
     * @var MessageFactory
     */
    private $messageFactory;

    public function __construct(EventBus $eventBus, MessageFactory $messageFactory)
    {
        $this->eventBus = $eventBus;
        $this->messageFactory = $messageFactory;
    }

    public function __invoke(Envelope $envelope, Queue $queue): DeliveryResult
    {
        $data = \json_decode($envelope->getBody(), true);

        if (! isset($data['created_at'])) {
            return DeliveryResult::MSG_REJECT();
        }

        $data['created_at'] = DateTimeImmutable::createFromFormat(
            'Y-m-d\TH:i:s.u',
            $data['created_at'],
            new DateTimeZone('UTC')
        );

        if (false === $data['created_at']) {
            return DeliveryResult::MSG_REJECT();
        }

        try {
            $event = $this->messageFactory->createMessageFromArray($envelope->getType(), $data);
            $this->eventBus->dispatch($event);
        } catch (\Throwable $e) {
            while ($e = $e->getPrevious()) {
                if ($e instanceof ConcurrencyException) {
                    return DeliveryResult::MSG_REJECT_REQUEUE();
                }
            }

            return DeliveryResult::MSG_REJECT();
        }

        return DeliveryResult::MSG_ACK();
    }
}


text:
/**
 * file: shared/tabs/index.js
 *
 * React components to render MDL tabs components
 * See: https://github.com/google/material-design-lite/tree/v1.2.1/src/tabs
 */
 import Tabs from './Tabs';

 /*** exports ***/
 export default Tabs;
 export {TabBar as TabsTabBar} from './TabBar';
 export {Tab as TabsTab} from './Tab';
 export {Panel as TabsPanel} from './Panel';


text:
open-hydro-dp-a
===============

A library using discrete dynamic programming to help determine efficient operating settings for individual hydropower turbines. The model works better for lower head, seperate-intake configurations. It supports generator efficiency curves (%eff vs output at reference head) and turbine curves (%eff vs output at reference head with adjustments).


text:
function cvx_setpath( arg ) %#ok

%CVX_SETPATH   Sets the cvx path.
%   CVX_SETPATH adds the internal cvx directories to Matlab's path so that the
%   CVX system can find the functions that they contain. There is no reason to
%   call this function during normal use of CVX; it is done automatically as
%   needed. However, if you are debugging CVX, calling this function can help to
%   insure that breakpoints stay valid.

% Set the hold flag
global cvx___
cvx_global
if ~cvx___.path.active,
    s = warning('off'); %#ok
    path([cvx___.path.string,path]);
    warning(s);
    cvx___.path.active = true;
end
if nargin == 0,
    cvx___.path.hold = true;
end
if cvx___.path.hold,
    cvx_setspath;
end

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
if [[ $(id -u) == 0 ]]; then
    unlink /etc/supervisord
    unlink /etc/supervisord.conf
    unlink /var/log/supervisord
    unlink /var/run/supervisord
fi


text:
from __future__ import print_function

import itertools
import sys
import re
import os
import json

from pwn import log

"""
Try to monitor all methods of a class
"""

import frida

CONSTRUCTOR_METHOD = 1
STATIC_METHOD = 2
INSTANCE_METHOD = 3

CONFIG_FILE_NAME = "config/java.json"

CLASSES = [{"name": "javax.crypto.Cipher"},
           {"name": "javax.crypto.spec.IvParameterSpec"}]

jscode = """
Java.perform(function () {

    var c = null;
    try {
        c = Java.use('%s');
    }
    catch(err) {
        // class not found...
        send("<none>");
        return;
    }

    if (c !== null) {
        var cproto = Object.getPrototypeOf(c);
        var members = Object.getOwnPropertyNames(cproto);
    }
    else {
        send("<none>");
        return;
    }

    method_list = [];

    for (var m in members) {
        var member = members[m];

        if (member !== '$className' && member !== '$new' && 'overloads' in c[member]) {
            // a method can have several overloads (same name, but different params)
            // therefore iterate over them
            for (var ovld in c[member].overloads) {
                method_list.push({'name': member, 'parameters': c[member].overloads[ovld].argumentTypes,
                                  'type': c[member].overloads[ovld].type, 'returnType': c[member].overloads[ovld].returnType});
            }
        }
    }

    send(method_list);

    // test hooking
    c.onEnter.overload().implementation = function() {
        send("onEnter called");
        return this.onEnter();
    }

});
"""

hook_jscode_header = """
Java.perform(function() {{

    var c = Java.use('{0}');
"""

hook_jscode = """
    c.{0}.overload({1}).implementation = function ({2}) {{
       var r=this.{0}.overload({1}).call({3});
       send({4});
       return r;
    }}
"""

hook_jscode_constructor = """
    c.{0}.overload({1}).implementation = function ({2}) {{
       this.{0}.overload({1}).call({3});
       send({4});
    }}
"""

hook_jscode_footer = """
    }); // end of Java.perform
"""

def _gen_hook_jscode_for_method(class_name, method_description):

    name = method_description["name"]
    return_type = method_description["returnType"]["className"]

    #if name == "$init":
    #    # do not hook $init (constructor) - causes problems (probably because of return value)
    #    return ""

    #if method_description["type"] == CONSTRUCTOR_METHOD:
    #    #TODO: don't know how to handle constructor methods
    #    return ""

    parameters = method_description["parameters"]
    signature_list = [p["className"] for p in parameters]
    num_parameters = len(parameters)
    signature = ",".join("'{0}'".format(s) for s in signature_list)

    dummy_params_list = ["a{0}".format(i+1) for i in range(num_parameters)]
    dummy_params = ",".join(dummy_params_list)

    # for non-static methods, 'this' is the first parameter
    if method_description["type"] != STATIC_METHOD:
        signature_list_and_this = [class_name] + signature_list
        this_and_dummy_params_list = ["this"] + dummy_params_list
    else:
        signature_list_and_this = signature_list
        this_and_dummy_params_list = dummy_params_list

    #needed for constructing the call to the original method
    this_and_dummy_params_string = ",".join(itertools.chain(["this"], dummy_params_list))

    param_info = ",".join("{{'name':'{0}','content':{0},'type':'{1}'}}".format(n,t) for n,t in zip(this_and_dummy_params_list, signature_list_and_this))

    #use slightly different code for special method $init, although the general hook code also seemed to work
    if name == "$init":
        fstring = "{{'name': '{0}.{1}', 'parameters':[{2}], 'returns':{{'type':'{3}'}} }}".format(class_name, name, param_info, return_type)
        return hook_jscode_constructor.format(name, signature, dummy_params, this_and_dummy_params_string, fstring)

    fstring = "{{'name': '{0}.{1}', 'parameters':[{2}], 'returns':{{'content':r,'type':'{3}'}} }}".format(class_name, name, param_info, return_type)

    return hook_jscode.format(name, signature, dummy_params, this_and_dummy_params_string, fstring)

def pretty_print(msg, print_function):
    """Print a monitoring message in a more readable way"""
    print_function("{0}:".format(msg["name"]))
    print_function("  parameters:")
    for entry in msg["parameters"]:
        print_function("    {0} ({1}): {2}".format(entry["name"], entry["type"], entry["content"]))
    print_function("  returns:")

    ret = msg["returns"]
    if "content" in ret:
        content = ret["content"]
    else:
        content = ""

    print_function("    ({0}): {1}".format(ret["type"], content))
    print_function("")

class Method_List_Receiver:
    """Retrieves methods of given classes and adds hooks for monitoring"""

    def __init__(self, process, config, path, callback_when_finished):
        self.class_counter = 0
        self.script = ""
        self.classes = config["classes"]
        self.print_calls = config["settings"]["print_calls"]
        self.write_results = config["settings"]["write_results"]
        self.callback = callback_when_finished
        self.process = process # frida process object
        self.num_classes = len(self.classes)

        self.path = path

    def start_hooking(self):
        log.info("Hooking classes. This may take a while...")
        self._hook_next()

    def _hook_next(self):
        if self.class_counter < self.num_classes:
            self.script = self.process.create_script(jscode % self.classes[self.class_counter]["name"])
            self.script.on('message', self._on_method_receive)
            self.script.load()
        else:
            self.callback()

    def _on_message(self, message, data):
        """Process the method call messages"""
        if message['type'] == 'send':
            #info = json.loads(str(message['payload']).encode('string-escape'), strict=False)
            info = message['payload']

            if self.print_calls:
                pretty_print(info, log.info)

            if self.write_results:
                filename = os.path.join(self.path, info["name"] + ".dat")
                with open(filename, "a+") as f:
                    json.dump(info, f)
                    f.write("\n")
        else:
            log.warning(str(message).encode('string-escape'))

    def _on_method_receive(self, message, data):
        """After method list is received - upload the hook script"""

        class_counter = self.class_counter

        if message['type'] != 'send':
            return

        class_name = self.classes[self.class_counter]["name"]

        if message['payload'] != '<none>':
            method_list = message['payload']

            #print(method_list)

            self.script.unload()

            hook_script_code = (hook_jscode_header.format(class_name) +
                                ''.join(_gen_hook_jscode_for_method(class_name, m) for m in method_list) +
                                hook_jscode_footer)

            #print(hook_script_code)

            hook_script = self.process.create_script(hook_script_code)
            hook_script.on('message', self._on_message)
            hook_script.load()

            log.info("Hooked methods of class {0}".format(class_name))
        else:
            log.info("Class {0} does not exist.".format(class_name))

        self.class_counter += 1
        self._hook_next()

def callback_when_finished():
    log.info("Finished hooking classes. Ready... Exit with CTRL-C")

def hook_classes(process, classes, path):
    receiver = Method_List_Receiver(process, classes, path, callback_when_finished)
    receiver.start_hooking()

def main(target_process):

    with open(CONFIG_FILE_NAME) as j:
        config = json.load(j)

    try:
        session = frida.get_usb_device().attach(target_process)
    except frida.ServerNotRunningError:
        try:
            log.error("Please start frida server first")
        except:
            sys.exit(-1)
    except frida.TimedOutError:
        try:
            log.error("Frida timeout...")
        except:
            sys.exit(-1)

    PATH = ""
    if config["settings"]["write_results"]:
        PATH = os.path.join(PATH, "results", sys.argv[1])
        if not os.path.exists(PATH):
            os.makedirs(PATH)

        runnr = len([x for x in os.listdir(PATH) if os.path.isdir(os.path.join(PATH,x))])
        PATH = os.path.join(PATH, "run_" + str(runnr))
        if not os.path.exists(PATH):
            os.makedirs(PATH)

    hook_classes(session, config, PATH)
    sys.stdin.read()

if __name__ == '__main__':
    if len(sys.argv) != 2:
        try:
            log.error("Usage: %s <process name or PID>" % __file__)
        except:
            sys.exit(-1)

    try:
        target_process = int(sys.argv[1])
    except ValueError:
        target_process = sys.argv[1]

    main(target_process)


text:
package org.jadira.usertype.dateandtime.jsr310;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Table;
import javax.time.calendar.ZoneOffset;

import org.jadira.usertype.dateandtime.jsr310.testmodel.ZoneOffsetAsStringHolder;
import org.jadira.usertype.dateandtime.shared.dbunit.DatabaseCapable;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestPersistentZoneOffsetAsString extends DatabaseCapable {

    private static final ZoneOffset[] zoneOffsets = new ZoneOffset[] { ZoneOffset.UTC, ZoneOffset.ofHours(5), ZoneOffset.ofHoursMinutes(11, 30), ZoneOffset.ofHoursMinutesSeconds(5, 40, 45) };

    private static EntityManagerFactory factory;

    @BeforeClass
    public static void setup() {
        factory = Persistence.createEntityManagerFactory("test1");
    }

    @AfterClass
    public static void tearDown() {
        factory.close();
    }

    @Test
    public void testPersist() {

        EntityManager manager = factory.createEntityManager();

        manager.getTransaction().begin();

        for (int i = 0; i < zoneOffsets.length; i++) {

            ZoneOffsetAsStringHolder item = new ZoneOffsetAsStringHolder();
            item.setId(i);
            item.setName("test_" + i);
            item.setZoneOffset(zoneOffsets[i]);

            manager.persist(item);
        }

        manager.flush();

        manager.getTransaction().commit();

        manager.close();

        manager = factory.createEntityManager();

        for (int i = 0; i < zoneOffsets.length; i++) {

            ZoneOffsetAsStringHolder item = manager.find(ZoneOffsetAsStringHolder.class, Long.valueOf(i));

            assertNotNull(item);
            assertEquals(i, item.getId());
            assertEquals("test_" + i, item.getName());
            assertEquals(zoneOffsets[i], item.getZoneOffset());
        }

        verifyDatabaseTable(manager, ZoneOffsetAsStringHolder.class.getAnnotation(Table.class).name());

        manager.close();
    }
}


text:
namespace Egs.ZkooTutorial
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows;
    using System.Windows.Threading;
    using System.Windows.Controls;

    partial class VideoPlayingPage : Page
    {
        public string PageTitle { get; set; }
        public string VideoFileNameWithoutDirectory { get; internal set; }
        bool IsMouseHoveredOnTutorialAppHeaderMenuUserControl { get; set; }

        MainNavigationWindow refToNavigator { get; set; }
        ZkooTutorialModel refToAppModel { get; set; }

        int MouseCursorPositionY { get; set; }
        void UpdateAppHeaderMenuVisibility()
        {
            var newBoolValue = IsMouseHoveredOnTutorialAppHeaderMenuUserControl || (videoPlayingUserControl.IsPlaying == false);
            var newOpacity = newBoolValue ? 1.0 : 0.0;
            if (TutorialAppHeaderMenuUserControl.Opacity != newOpacity) { TutorialAppHeaderMenuUserControl.Opacity = newOpacity; }
        }

        public VideoPlayingPage()
        {
            InitializeComponent();
            PageTitle = "";
            VideoFileNameWithoutDirectory = "";
            MouseCursorPositionY = 200;
            TutorialAppHeaderMenuUserControl.Visibility = Visibility.Visible;
            TutorialAppHeaderMenuUserControl.Opacity = 1.0;
            ReplayPracticeNextButtonsUserControl.Visibility = Visibility.Collapsed;

            ReplayPracticeNextButtonsUserControl.DialogNextButtonUserControl.Visibility = Visibility.Collapsed;
        }

        public void InitializeOnceAtStartup(MainNavigationWindow navigator, ZkooTutorialModel appModel)
        {
            Trace.Assert(navigator != null);
            Trace.Assert(appModel != null);
            refToNavigator = navigator;
            refToAppModel = appModel;

            this.DataContext = refToAppModel;

            ReplayPracticeNextButtonsUserControl.InitializeOnceAtStartup(appModel.TutorialAppHeaderMenu);
            TutorialAppHeaderMenuUserControl.InitializeOnceAtStartup(appModel.TutorialAppHeaderMenu);

            this.PreviewMouseMove += (sender, e) =>
            {
                MouseCursorPositionY = (int)e.GetPosition(this).Y;
                UpdateAppHeaderMenuVisibility();
            };

            TutorialAppHeaderMenuUserControl.MouseEnter += (sender, e) =>
            {
                IsMouseHoveredOnTutorialAppHeaderMenuUserControl = true;
                UpdateAppHeaderMenuVisibility();
            };
            TutorialAppHeaderMenuUserControl.MouseLeave += (sender, e) =>
            {
                IsMouseHoveredOnTutorialAppHeaderMenuUserControl = false;
                UpdateAppHeaderMenuVisibility();
            };

            videoPlayingUserControl.IsPlayingChanged += (sender, e) =>
            {
                UpdateAppHeaderMenuVisibility();
                ReplayPracticeNextButtonsUserControl.Visibility = videoPlayingUserControl.IsPlaying ? Visibility.Collapsed : Visibility.Visible;
            };

            this.Loaded += (sender, e) =>
            {
                // NOTE: This does not change device settings and so on.
                // NOTE: Called from asynchronous Task.Run() called from each Page's Loaded event.
                refToNavigator.Title = this.PageTitle;
                refToNavigator.SetWindowFullScreen();
                refToAppModel.EnableUpdatingCameraViewImageButHideWindow();
                videoPlayingUserControl.SetMediaElementSourceUriByFilePath(Path.Combine(refToAppModel.CurrentResources.TutorialVideoFilesFolderPath, VideoFileNameWithoutDirectory), UriKind.Relative);
                videoPlayingUserControl.Replay();
            };
        }
    }
}


text:
require 'spec_helper'

describe EarlyReview, type: :model do
  before do
    EmailNotifications.stubs(:early_review_submitted).returns(stub(deliver_now: true))
  end

  it_should_trim_attributes EarlyReview, :comments_to_organizers, :comments_to_authors

  describe 'associations' do
    it { is_expected.to belong_to :reviewer }
    it { is_expected.to belong_to :session }
    it { is_expected.to belong_to :recommendation }

    it { is_expected.to belong_to :author_agile_xp_rating }
    it { is_expected.to belong_to :author_proposal_xp_rating }
    it { is_expected.to belong_to :proposal_quality_rating }
    it { is_expected.to belong_to :proposal_relevance_rating }
    it { is_expected.to belong_to :reviewer_confidence_rating }

    it { is_expected.to have_many :review_evaluations }
  end

  describe 'validations' do
    it { is_expected.to validate_presence_of :author_agile_xp_rating_id }
    it { is_expected.to validate_presence_of :author_proposal_xp_rating_id }

    it { is_expected.to validate_presence_of :proposal_quality_rating_id }
    it { is_expected.to validate_presence_of :proposal_relevance_rating_id }

    it { is_expected.to validate_presence_of :reviewer_confidence_rating_id }

    it { is_expected.to validate_presence_of :reviewer_id }
    it { is_expected.to validate_presence_of :session_id }

    it { is_expected.to validate_length_of(:comments_to_authors).is_at_least(150) }

    describe 'uniqueness' do
      before { FactoryBot.create(:early_review) }

      it { is_expected.to validate_uniqueness_of(:reviewer_id).scoped_to(:session_id, :type) }
    end
  end

  describe 'notifications' do
    it 'notifies session author(s) after creation' do
      review = FactoryBot.build(:early_review)
      EarlyReview.send(:public, :notify)

      EmailNotifications.expects(:early_review_submitted).with(review.session).returns(mock(deliver_now: true))

      review.notify
    end
  end
end


text:
namespace chrome_variations {

namespace {

const char* kSuffixesToSetHeadersFor[] = {
  ".android.com",
  ".doubleclick.com",
  ".doubleclick.net",
  ".ggpht.com",
  ".googleadservices.com",
  ".googleapis.com",
  ".googlesyndication.com",
  ".googleusercontent.com",
  ".googlevideo.com",
  ".gstatic.com",
  ".ytimg.com",
};

}  // namespace

VariationsHttpHeaderProvider* VariationsHttpHeaderProvider::GetInstance() {
  return Singleton<VariationsHttpHeaderProvider>::get();
}

void VariationsHttpHeaderProvider::AppendHeaders(
    const GURL& url,
    bool incognito,
    bool uma_enabled,
    net::HttpRequestHeaders* headers) {
  // Note the criteria for attaching Chrome experiment headers:
  // 1. We only transmit to Google owned domains which can evaluate experiments.
  //    1a. These include hosts which have a standard postfix such as:
  //         *.doubleclick.net or *.googlesyndication.com or
  //         exactly www.googleadservices.com or
  //         international TLD domains *.google.<TLD> or *.youtube.<TLD>.
  // 2. Only transmit for non-Incognito profiles.
  // 3. For the X-Chrome-UMA-Enabled bit, only set it if UMA is in fact enabled
  //    for this install of Chrome.
  // 4. For the X-Client-Data header, only include non-empty variation IDs.
  if (incognito || !ShouldAppendHeaders(url))
    return;

  if (uma_enabled)
    headers->SetHeaderIfMissing("X-Chrome-UMA-Enabled", "1");

  // Lazily initialize the header, if not already done, before attempting to
  // transmit it.
  InitVariationIDsCacheIfNeeded();

  std::string variation_ids_header_copy;
  {
    base::AutoLock scoped_lock(lock_);
    variation_ids_header_copy = variation_ids_header_;
  }

  if (!variation_ids_header_copy.empty()) {
    // Note that prior to M33 this header was named X-Chrome-Variations.
    headers->SetHeaderIfMissing("X-Client-Data",
                                variation_ids_header_copy);
  }
}

bool VariationsHttpHeaderProvider::SetDefaultVariationIds(
    const std::string& variation_ids) {
  default_variation_ids_set_.clear();
  default_trigger_id_set_.clear();
  std::vector<std::string> entries;
  base::SplitString(variation_ids, ',', &entries);
  for (std::vector<std::string>::const_iterator it = entries.begin();
       it != entries.end(); ++it) {
    if (it->empty()) {
      default_variation_ids_set_.clear();
      default_trigger_id_set_.clear();
      return false;
    }
    bool trigger_id = StartsWithASCII(*it, "t", true);
    // Remove the "t" prefix if it's there.
    std::string entry = trigger_id ? it->substr(1) : *it;

    int variation_id = 0;
    if (!base::StringToInt(entry, &variation_id)) {
      default_variation_ids_set_.clear();
      default_trigger_id_set_.clear();
      return false;
    }
    if (trigger_id)
      default_trigger_id_set_.insert(variation_id);
    else
      default_variation_ids_set_.insert(variation_id);
  }
  return true;
}

VariationsHttpHeaderProvider::VariationsHttpHeaderProvider()
    : variation_ids_cache_initialized_(false) {
}

VariationsHttpHeaderProvider::~VariationsHttpHeaderProvider() {
}

void VariationsHttpHeaderProvider::OnFieldTrialGroupFinalized(
    const std::string& trial_name,
    const std::string& group_name) {
  VariationID new_id =
      GetGoogleVariationID(GOOGLE_WEB_PROPERTIES, trial_name, group_name);
  VariationID new_trigger_id = GetGoogleVariationID(
      GOOGLE_WEB_PROPERTIES_TRIGGER, trial_name, group_name);
  if (new_id == EMPTY_ID && new_trigger_id == EMPTY_ID)
    return;

  base::AutoLock scoped_lock(lock_);
  if (new_id != EMPTY_ID)
    variation_ids_set_.insert(new_id);
  if (new_trigger_id != EMPTY_ID)
    variation_trigger_ids_set_.insert(new_trigger_id);

  UpdateVariationIDsHeaderValue();
}

void VariationsHttpHeaderProvider::InitVariationIDsCacheIfNeeded() {
  base::AutoLock scoped_lock(lock_);
  if (variation_ids_cache_initialized_)
    return;

  // Register for additional cache updates. This is done first to avoid a race
  // that could cause registered FieldTrials to be missed.
  DCHECK(base::MessageLoop::current());
  base::FieldTrialList::AddObserver(this);

  base::TimeTicks before_time = base::TimeTicks::Now();

  base::FieldTrial::ActiveGroups initial_groups;
  base::FieldTrialList::GetActiveFieldTrialGroups(&initial_groups);
  for (base::FieldTrial::ActiveGroups::const_iterator it =
           initial_groups.begin();
       it != initial_groups.end(); ++it) {
    const VariationID id =
        GetGoogleVariationID(GOOGLE_WEB_PROPERTIES, it->trial_name,
                             it->group_name);
    if (id != EMPTY_ID)
      variation_ids_set_.insert(id);

    const VariationID trigger_id =
        GetGoogleVariationID(GOOGLE_WEB_PROPERTIES_TRIGGER, it->trial_name,
                             it->group_name);
    if (trigger_id != EMPTY_ID)
      variation_trigger_ids_set_.insert(trigger_id);
  }
  UpdateVariationIDsHeaderValue();

  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "Variations.HeaderConstructionTime",
      (base::TimeTicks::Now() - before_time).InMicroseconds(),
      0,
      base::TimeDelta::FromSeconds(1).InMicroseconds(),
      50);

  variation_ids_cache_initialized_ = true;
}

void VariationsHttpHeaderProvider::UpdateVariationIDsHeaderValue() {
  lock_.AssertAcquired();

  // The header value is a serialized protobuffer of Variation IDs which is
  // base64 encoded before transmitting as a string.
  variation_ids_header_.clear();

  if (variation_ids_set_.empty() && default_variation_ids_set_.empty() &&
      variation_trigger_ids_set_.empty() && default_trigger_id_set_.empty()) {
    return;
  }

  // This is the bottleneck for the creation of the header, so validate the size
  // here. Force a hard maximum on the ID count in case the Variations server
  // returns too many IDs and DOSs receiving servers with large requests.
  const size_t total_id_count =
      variation_ids_set_.size() + variation_trigger_ids_set_.size();
  DCHECK_LE(total_id_count, 10U);
  if (total_id_count > 20)
    return;

  // Merge the two sets of experiment ids.
  std::set<VariationID> all_variation_ids_set = default_variation_ids_set_;
  for (std::set<VariationID>::const_iterator it = variation_ids_set_.begin();
       it != variation_ids_set_.end(); ++it) {
    all_variation_ids_set.insert(*it);
  }
  metrics::ChromeVariations proto;
  for (std::set<VariationID>::const_iterator it = all_variation_ids_set.begin();
       it != all_variation_ids_set.end(); ++it) {
    proto.add_variation_id(*it);
  }

  std::set<VariationID> all_trigger_ids_set = default_trigger_id_set_;
  for (std::set<VariationID>::const_iterator it =
           variation_trigger_ids_set_.begin();
       it != variation_trigger_ids_set_.end(); ++it) {
    all_trigger_ids_set.insert(*it);
  }
  for (std::set<VariationID>::const_iterator it = all_trigger_ids_set.begin();
       it != all_trigger_ids_set.end(); ++it) {
    proto.add_trigger_variation_id(*it);
  }

  std::string serialized;
  proto.SerializeToString(&serialized);

  std::string hashed;
  base::Base64Encode(serialized, &hashed);
  // If successful, swap the header value with the new one.
  // Note that the list of IDs and the header could be temporarily out of sync
  // if IDs are added as the header is recreated. The receiving servers are OK
  // with such discrepancies.
  variation_ids_header_ = hashed;
}

// static
bool VariationsHttpHeaderProvider::ShouldAppendHeaders(const GURL& url) {
  if (google_util::IsGoogleDomainUrl(url, google_util::ALLOW_SUBDOMAIN,
                                     google_util::ALLOW_NON_STANDARD_PORTS)) {
    return true;
  }

  if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS())
    return false;

  // Some domains don't have international TLD extensions, so testing for them
  // is very straight forward.
  const std::string host = url.host();
  for (size_t i = 0; i < arraysize(kSuffixesToSetHeadersFor); ++i) {
    if (EndsWith(host, kSuffixesToSetHeadersFor[i], false))
      return true;
  }

  return google_util::IsYoutubeDomainUrl(url, google_util::ALLOW_SUBDOMAIN,
                                         google_util::ALLOW_NON_STANDARD_PORTS);
}

}  // namespace chrome_variations


text:
package com.baidubce.services.tablestorage.model;

/**
 * Represent the request for DeleteRow operation.
 */
public class DeleteRowRequest extends AbstractTableStorageRequest {
    private DeleteRow deleteRow;

    /**
     * Constructs a delete row request with target table name and rowkey.
     *
     * @param tableName The target table name.
     * @param rowkey The target rowkey.
     */
    public DeleteRowRequest(String tableName, String rowkey) {
        super(tableName);
        this.deleteRow = new DeleteRow(rowkey);
    }

    /**
     * Add a cell with column name to this delete row request.
     * @param column The column name of cell.
     * @return This delete row request object.
     */
    public DeleteRowRequest addCell(String column) {
        deleteRow.addCell(column);
        return this;
    }

    /**
     * Convert this request object to json string.
     *
     * @return the json string represent the request object.
     */
    @Override
    public String toJsonString() {
        return deleteRow.toJsonString();
    }
}


text:
#ifndef SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_
#define SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_

#include "webrtc/system_wrappers/interface/atomic32.h"

namespace webrtc {

// This class can be used for instantiating
// reference counted objects.
// int32_t AddRef() and int32_t Release().
// Usage:
// RefCountImpl<T>* implementation = new RefCountImpl<T>(p);
//
// Example:
// class MyInterface {
//  public:
//   virtual void DoSomething() = 0;
//   virtual int32_t AddRef() = 0;
//   virtual int32_t Release() = 0:
//  private:
//   virtual ~MyInterface(){};
// }
// class MyImplementation : public MyInterface {
//  public:
//   virtual DoSomething() { printf("hello"); };
// };
// MyImplementation* CreateMyImplementation() {
//   RefCountImpl<MyImplementation>* implementation =
//       new RefCountImpl<MyImplementation>();
//   return implementation;
// }

template <class T>
class RefCountImpl : public T {
 public:
  RefCountImpl() : ref_count_(0) {}

  template<typename P>
  explicit RefCountImpl(P p) : T(p), ref_count_(0) {}

  template<typename P1, typename P2>
  RefCountImpl(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {}

  template<typename P1, typename P2, typename P3>
  RefCountImpl(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) {}

  template<typename P1, typename P2, typename P3, typename P4>
  RefCountImpl(P1 p1, P2 p2, P3 p3, P4 p4) : T(p1, p2, p3, p4), ref_count_(0) {}

  template<typename P1, typename P2, typename P3, typename P4, typename P5>
  RefCountImpl(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)
      : T(p1, p2, p3, p4, p5), ref_count_(0) {}

  virtual int32_t AddRef() {
    return ++ref_count_;
  }

  virtual int32_t Release() {
    int32_t ref_count;
    ref_count = --ref_count_;
    if (ref_count == 0)
      delete this;
    return ref_count;
  }

 protected:
  Atomic32 ref_count_;
};

}  // namespace webrtc

#endif  // SYSTEM_WRAPPERS_INTERFACE_REF_COUNT_H_


text:
Inline methods to simplify Auto Layout code.

## License

MIT Licensed.

## Credit

All credit goes to @mobitar, this is pretty much a fork of [github.com/mobitar/AutolayoutHelpers](https://github.com/mobitar/AutolayoutHelpers).


text:
package backEnd;

import java.util.List;

import javafx.scene.paint.Color;

public class GameOfLife extends RuleSet {

	private static final String GAME_OF_LIFE = "Game of Life";

	// No extra parameters!

	public GameOfLife() {
		super();

		myDescription = GAME_OF_LIFE;
		myPossibleStates = new State[] { new State("Alive", 0, Color.BLACK,
				null) };
	}

	@Override
	public Patch getNext(Patch patch) {
		List<Patch> neighborhood = getNeighbors(patch);
		Patch newPatch = new Patch(patch);

		int liveNeighbors = countLiveNeighbors(0, neighborhood);

		if (patch.containsCell() && (liveNeighbors < 2 || liveNeighbors > 3)) {
			newPatch.clear();
		}

		if (!patch.containsCell() && liveNeighbors == 3) {
			newPatch.fill(new Cell(myPossibleStates[0]));
		}

		return newPatch;
	}

	public int countLiveNeighbors(int liveOnes, List<Patch> theNeighborhood) {
		for (Patch p : theNeighborhood) {
			if (p.containsCell())
				liveOnes++;
		}
		return liveOnes;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout android:id="@+id/block_time_container"
        android:orientation="vertical"
        android:layout_width="@dimen/schedule_block_time_width"
        android:layout_height="match_parent"
        android:background="@drawable/transparent_background_pattern"
        android:padding="8dp">

        <TextView android:id="@+id/block_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_small"
            android:textColor="@color/body_text_2"
            android:paddingTop="@dimen/text_size_diff_large_small" />

        <TextView android:id="@+id/block_endtime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_small"
            android:textColor="@color/body_text_3"
            android:paddingTop="4dp"/>
    </LinearLayout>

    <LinearLayout android:id="@+id/list_item_middle_container"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView android:id="@+id/block_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="?listPreferredItemPaddingLeft"
            android:layout_marginRight="?listPreferredItemPaddingRight"
            android:paddingTop="8dp"
            style="@style/ListItemTitle" />

        <TextView android:id="@+id/block_subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="?listPreferredItemPaddingLeft"
            android:layout_marginRight="?listPreferredItemPaddingRight"
            android:paddingBottom="8dp"
            style="@style/ListItemSubtitle" />
    </LinearLayout>

</LinearLayout>


text:
package example.service;

import example.repo.Customer325Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer325Service {
	public Customer325Service(Customer325Repository repo) {}
}


text:
		<form data-ng-submit="changeUserPassword()" class="signin form-horizontal" autocomplete="off">
			<fieldset>

					<input type="password" id="currentPassword" name="currentPassword" class="form-control" data-ng-model="passwordDetails.currentPassword" placeholder="{{'cpassword.cp' | translate}}">

					<input type="password" id="newPassword" name="newPassword" class="form-control" data-ng-model="passwordDetails.newPassword" placeholder="{{'cpassword.npw' | translate}}">

					<input type="password" id="verifyPassword" name="verifyPassword" class="form-control" data-ng-model="passwordDetails.verifyPassword" placeholder="{{'cpassword.vpw' | translate}}">

					<button type="submit" class="btn btn-large btn-primary" translate="cpassword.spw"></button>

			</fieldset>
		</form>


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:title="@string/action_settings"/>

    <item
        android:id="@+id/action_about"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:title="@string/action_about"/>

</menu>


text:
<?php

namespace Spatie\Backup\Tasks\Monitor;

use Carbon\Carbon;
use Spatie\Backup\Helpers\Format;
use Spatie\Backup\BackupDestination\BackupDestination;

class BackupDestinationStatus
{
    /** @var \Spatie\Backup\BackupDestination\BackupDestination */
    protected $backupDestination;

    /** @var int */
    protected $maximumAgeOfNewestBackupInDays = 1;

    /** @var int */
    protected $maximumStorageUsageInMegabytes = 5000;

    /** @var string */
    protected $diskName;

    /** @var bool */
    protected $reachable;

    /**
     * @param \Spatie\Backup\BackupDestination\BackupDestination $backupDestination
     * @param string                                             $diskName
     */
    public function __construct(BackupDestination $backupDestination, $diskName)
    {
        $this->backupDestination = $backupDestination;
        $this->diskName = $diskName;

        $this->reachable = $this->backupDestination->isReachable();
    }

    /**
     * @param int $days
     *
     * @return \Spatie\Backup\Tasks\Monitor\BackupDestinationStatus
     */
    public function setMaximumAgeOfNewestBackupInDays($days)
    {
        $this->maximumAgeOfNewestBackupInDays = $days;

        return $this;
    }

    /**
     * @return int
     */
    public function getMaximumAgeOfNewestBackupInDays()
    {
        return $this->maximumAgeOfNewestBackupInDays;
    }

    /**
     * @param int $megabytes
     *
     * @return \Spatie\Backup\Tasks\Monitor\BackupDestinationStatus
     */
    public function setMaximumStorageUsageInMegabytes($megabytes)
    {
        $this->maximumStorageUsageInMegabytes = $megabytes;

        return $this;
    }

    /**
     * @return string
     */
    public function getBackupName()
    {
        return $this->backupDestination->getBackupName();
    }

    /**
     * @deprecated
     *
     * @return string
     */
    public function getFilesystemName()
    {
        return $this->getDiskName();
    }

    /**
     * @return string
     */
    public function getDiskName()
    {
        return $this->diskName;
    }

    /**
     * @return int
     */
    public function getAmountOfBackups()
    {
        return $this->backupDestination->getBackups()->count();
    }

    /**
     * @return \Carbon\Carbon|null
     */
    public function getDateOfNewestBackup()
    {
        $newestBackup = $this->backupDestination->getNewestBackup();

        if (is_null($newestBackup)) {
            return;
        }

        return $newestBackup->date();
    }

    /**
     * @return bool
     */
    public function newestBackupIsToolOld()
    {
        if (! count($this->backupDestination->getBackups())) {
            return true;
        }

        $maximumDate = Carbon::now()->subDays($this->maximumAgeOfNewestBackupInDays);

        return ! $this->backupDestination->isNewestBackupOlderThan($maximumDate);
    }

    /**
     * @return int
     */
    public function getUsedStorage()
    {
        return $this->backupDestination->getUsedStorage();
    }

    /**
     * @return \Exception
     */
    public function getConnectionError()
    {
        return $this->backupDestination->getConnectionError();
    }

    /**
     * @return bool
     */
    public function isReachable()
    {
        return $this->reachable;
    }

    /**
     * @return int
     */
    public function getMaximumAllowedUsageInBytes()
    {
        return $this->maximumStorageUsageInMegabytes * 1024 * 1024;
    }

    /**
     * @return bool
     */
    public function backupUsesTooMuchStorage()
    {
        $maximumInBytes = $this->getMaximumAllowedUsageInBytes();

        if ($maximumInBytes === 0) {
            return false;
        }

        return $this->getUsedStorage() > $maximumInBytes;
    }

    /**
     * @return bool
     */
    public function isHealthy()
    {
        if (! $this->backupDestination->isReachable()) {
            return false;
        }

        if ($this->backupUsesTooMuchStorage()) {
            return false;
        }

        if ($this->newestBackupIsToolOld()) {
            return false;
        }

        return true;
    }

    /**
     * @return string
     */
    public function getHumanReadableAllowedStorage()
    {
        $maximumInBytes = $this->getMaximumAllowedUsageInBytes();

        if ($maximumInBytes === 0) {
            return 'unlimited';
        }

        return Format::getHumanReadableSize($maximumInBytes);
    }

    /**
     * @return string
     */
    public function getHumanReadableUsedStorage()
    {
        return Format::getHumanReadableSize($this->getUsedStorage());
    }
}


text:
package org.gradle.internal.resource.local;

import com.google.common.base.Preconditions;

import java.io.File;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Tracks access to files by touching, i.e. updating the last modified
 * timestamp, files and directory at the supplied depth within the supplied base
 * directory.
 */
public class SingleDepthFileAccessTracker implements FileAccessTracker {

    private final Path baseDir;
    private final int endNameIndex;
    private final int startNameIndex;
    private final FileAccessTimeJournal journal;

    public SingleDepthFileAccessTracker(FileAccessTimeJournal journal, File baseDir, int depth) {
        this.journal = journal;
        Preconditions.checkArgument(depth > 0, "depth must be > 0: %s", depth);
        this.baseDir = baseDir.toPath().toAbsolutePath();
        this.startNameIndex = this.baseDir.getNameCount();
        this.endNameIndex = startNameIndex + depth;
    }

    @Override
    public void markAccessed(File file) {
        markAccessed(toSubPath(file));
    }

    @Override
    public void markAccessed(Collection<File> files) {
        for (Path path : collectSubPaths(files)) {
            markAccessed(path);
        }
    }

    private void markAccessed(Path path) {
        if (path != null) {
            journal.setLastAccessTime(path.toFile(), System.currentTimeMillis());
        }
    }

    private Set<Path> collectSubPaths(Collection<File> files) {
        Set<Path> paths = new HashSet<Path>();
        for (File file : files) {
            paths.add(toSubPath(file));
        }
        return paths;
    }

    private Path toSubPath(File file) {
        Path path = file.toPath().toAbsolutePath();
        if (path.getNameCount() >= endNameIndex && path.startsWith(baseDir)) {
            return baseDir.resolve(path.subpath(startNameIndex, endNameIndex));
        }
        return null;
    }
}


text:
-	[`0.3.0`, `latest` (*Dockerfile*)](https://github.com/nats-io/nats-streaming-docker/blob/1fcbfd456264c5da5888e279d9ea865166eeb3cf/Dockerfile)

For more information about this image and its history, please see [the relevant manifest file (`library/nats-streaming`)](https://github.com/docker-library/official-images/blob/master/library/nats-streaming). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fnats-streaming).

For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/nats-streaming/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/nats-streaming/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info).

# [NATS Streaming](https://nats.io): A high-performance cloud native messaging streaming system.

![logo](https://raw.githubusercontent.com/docker-library/docs/4a2d30cdf4ff4bc6ae915ada7a058db0c908659d/nats-streaming/logo.png)

`nats-streaming` is a high performance streaming server for the NATS Messaging System.

# Example usage

```bash
# Run a NATS Streaning server
# Each server exposes multiple ports
# 4222 is for clients.
# 8222 is an HTTP management port for information reporting.
# use -p or -P as needed.

$ docker run -d nats-streaming

Output that you would get if you had started with `-ti` instead of `d` (for daemon):

[INF] Starting nats-streaming-server[test-cluster] version 0.3.0
[INF] Starting nats-server version 0.9.4
[INF] Listening for client connections on 0.0.0.0:4222
[INF] Server is ready
[INF] STAN: Message store is MEMORY
[INF] STAN: --------- Store Limits ---------
[INF] STAN: Channels:                  100 *
[INF] STAN: -------- channels limits -------
[INF] STAN:   Subscriptions:          1000 *
[INF] STAN:   Messages     :       1000000 *
[INF] STAN:   Bytes        :     976.56 MB *
[INF] STAN:   Age          :     unlimited *
[INF] STAN: --------------------------------

To use a file based store instead, you would run:

$ docker run -d nats-streaming -store file -dir datastore

[INF] Starting nats-streaming-server[test-cluster] version 0.3.0
[INF] Starting nats-server version 0.9.4
[INF] Listening for client connections on 0.0.0.0:4222
[INF] Server is ready
[INF] STAN: Message store is FILE
[INF] STAN: --------- Store Limits ---------
[INF] STAN: Channels:                  100 *
[INF] STAN: -------- channels limits -------
[INF] STAN:   Subscriptions:          1000 *
[INF] STAN:   Messages     :       1000000 *
[INF] STAN:   Bytes        :     976.56 MB *
[INF] STAN:   Age          :     unlimited *
[INF] STAN: --------------------------------

You can also connect to a remote NATS Server running in a docker image.
First, run NATS Server:

$ docker run -d --name=nats-main nats

Now, start the Streaming server and link it to the above docker image:

$ docker run -d --link nats-main nats-streaming -ns nats://nats-main:4222

[INF] Starting nats-streaming-server[test-cluster] version 0.3.0
[INF] Server is ready
[INF] STAN: Message store is MEMORY
[INF] STAN: --------- Store Limits ---------
[INF] STAN: Channels:                  100 *
[INF] STAN: -------- channels limits -------
[INF] STAN:   Subscriptions:          1000 *
[INF] STAN:   Messages     :       1000000 *
[INF] STAN:   Bytes        :     976.56 MB *
[INF] STAN:   Age          :     unlimited *
[INF] STAN: --------------------------------

Notice that the output shows that the NATS Server was not started, as opposed to the first output.

```

# Commandline Options

```bash
Streaming Server Options:
    -cid, --cluster_id  <cluster ID> Cluster ID (default: test-cluster)
    -st,  --store <type>             Store type: MEMORY|FILE (default: MEMORY)
          --dir <directory>          For FILE store type, this is the root directory
    -mc,  --max_channels <number>    Max number of channels (0 for unlimited)
    -msu, --max_subs <number>        Max number of subscriptions per channel (0 for unlimited)
    -mm,  --max_msgs <number>        Max number of messages per channel (0 for unlimited)
    -mb,  --max_bytes <number>       Max messages total size per channel (0 for unlimited)
    -ma,  --max_age <seconds>        Max duration a message can be stored ("0s" for unlimited)
    -ns,  --nats_server <url>        Connect to this external NATS Server (embedded otherwise)
    -sc,  --stan_config <file>       Streaming server configuration file

Streaming Server File Store Options:
    --file_compact_enabled           Enable file compaction
    --file_compact_frag              File fragmentation threshold for compaction
    --file_compact_interval <int>    Minimum interval (in seconds) between file compactions
    --file_compact_min_size <int>    Minimum file size for compaction
    --file_buffer_size <int>         File buffer size (in bytes)
    --file_crc                       Enable file CRC-32 checksum
    --file_crc_poly <int>            Polynomial used to make the table used for CRC-32 checksum
    --file_sync                      Enable File.Sync on Flush
    --file_cache                     Enable messages caching

Streaming Server TLS Options:
    -secure                          Use a TLS connection to the NATS server without
                                     verification; weaker than specifying certificates.
    -tls_client_key                  Client key for the streaming server
    -tls_client_cert                 Client certificate for the streaming server
    -tls_client_cacert               Client certificate CA for the streaming server

Streaming Server Logging Options:
    -SD, --stan_debug                Enable STAN debugging output
    -SV, --stan_trace                Trace the raw STAN protocol
    -SDV                             Debug and trace STAN
    (See additional NATS logging options below)

Embedded NATS Server Options:
    -a, --addr <host>                Bind to host address (default: 0.0.0.0)
    -p, --port <port>                Use port for clients (default: 4222)
    -P, --pid <file>                 File to store PID
    -m, --http_port <port>           Use port for http monitoring
    -ms,--https_port <port>          Use port for https monitoring
    -c, --config <file>              Configuration file

Logging Options:
    -l, --log <file>                 File to redirect log output
    -T, --logtime                    Timestamp log entries (default: true)
    -s, --syslog                     Enable syslog as log method
    -r, --remote_syslog <addr>       Syslog server addr (udp://localhost:514)
    -D, --debug                      Enable debugging output
    -V, --trace                      Trace the raw protocol
    -DV                              Debug and trace

Authorization Options:
        --user <user>                User required for connections
        --pass <password>            Password required for connections
        --auth <token>               Authorization token required for connections

TLS Options:
        --tls                        Enable TLS, do not verify clients (default: false)
        --tlscert <file>             Server certificate file
        --tlskey <file>              Private key for server certificate
        --tlsverify                  Enable TLS, very client certificates
        --tlscacert <file>           Client certificate CA for verification

NATS Clustering Options:
        --routes <rurl-1, rurl-2>    Routes to solicit and connect
        --cluster <cluster-url>      Cluster URL for solicited routes

Common Options:
    -h, --help                       Show this message
    -v, --version                    Show version
        --help_tls                   TLS help.
```

# Configuration

Details on how to configure further the NATS Streaming server can be found [here](https://github.com/nats-io/nats-streaming-server#configuring)

# License

View [license information](https://github.com/nats-io/nats-streaming-server/blob/master/LICENSE) for the software contained in this image.

# Supported Docker versions

This image is officially supported on Docker version 1.12.3.

Support for older versions (down to 1.6) is provided on a best-effort basis.

Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon.

# User Feedback

## Issues

If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/nats-io/nats-streaming-docker/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker).

You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net).

## Contributing

You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can.

Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/nats-io/nats-streaming-docker/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing.

## Documentation

Documentation for this image is stored in the [`nats-streaming/` directory](https://github.com/docker-library/docs/tree/master/nats-streaming) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.


text:
---
uid: SolidEdgePart.ConstructionModel.FaceOffsets
summary:
remarks:
---


text:
package com.iosdevlog.a10intentsending;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {

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

    public void sendTel(View view) {
        Uri number = Uri.parse("tel:15888888888");
        Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
        startActivity(callIntent);
    }

    public void sendMap(View view) {
        // Build the intent
        Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
        Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

        // Verify it resolves
        PackageManager packageManager = getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
        boolean isIntentSafe = activities.size() > 0;

        // Start an activity if it's safe
        if (isIntentSafe) {
            startActivity(mapIntent);
        } else {
            Toast.makeText(MainActivity.this, "No Map Apps Found!", Toast.LENGTH_SHORT).show();
        }

    }

    public void sendWeb(View view) {
        Uri webpage = Uri.parse("http://iosdevlog.com");
        Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
        startActivity(webIntent);
    }

    public void sendEmail(View view) {
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        // The intent does not have a URI, so declare the "text/plain" MIME type
        emailIntent.setType("text/plain");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"iosdevlog@iosdevlog.com"}); // recipients
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));
        // You can also attach multiple items by passing an ArrayList of Uris
        startActivity(emailIntent);
    }

    public void sendCal(View view) {
        Intent calendarIntent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);
        Calendar beginTime = Calendar.getInstance(TimeZone.getDefault());
        beginTime.set(2016, 9, 20, 10, 20, 30);
        Calendar endTime = Calendar.getInstance(TimeZone.getDefault());
        endTime.set(2016, 9, 20, 10, 30, 30);
        calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis());
        calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis());
        calendarIntent.putExtra(CalendarContract.Events.TITLE, "Android Dev Log");
        calendarIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Home");
        startActivity(calendarIntent);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/dragContainer"
    android:background="@color/colorBackground"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.project.quiz.customviews.TextViewRegularFont
        android:textColor="@color/colorText"
        android:visibility="gone"
        android:id="@+id/student_id_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.project.quiz.customviews.TextViewRegularFont
        android:padding="15dp"
        android:text="Student"
        android:gravity="left"
        android:textColor="@color/colorText"
        android:textSize="@dimen/font_size_large"
        android:id="@+id/student_name_field"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
layout: default
---

{{ page.title }}

        {{ content }}


text:
layout: page
title: Helix Purple Entertainment Seminar
date: 2016-05-24
author: Carl Kramer
tags: weekly links, java
status: published
summary: Maecenas volutpat sed metus vel tempus. Curabitur ut sagittis nunc.
banner: images/banner/people.jpg
booking:
  startDate: 08/03/2017
  endDate: 08/06/2017
  ctyhocn: HSBUVHX
  groupCode: HPES
published: true
---
Duis eget egestas nisl, in eleifend ante. Suspendisse elementum, urna non varius ullamcorper, purus libero viverra diam, non tempor mi augue et massa. Donec id ultrices leo. Phasellus pharetra lacinia ex ut vehicula. Nam finibus, ex eu posuere laoreet, nunc lacus ornare mi, at gravida urna velit id ante. Suspendisse elit ante, tincidunt quis felis at, lacinia imperdiet nisi. Curabitur efficitur augue et magna euismod, id blandit libero viverra. Vestibulum volutpat magna et dignissim iaculis. Sed gravida quam semper, accumsan nisi posuere, finibus odio. Nullam lacinia mollis neque in lobortis.

* Sed et metus mollis velit posuere lobortis quis ut diam.

Etiam mattis augue quam, quis sollicitudin lectus dictum vel. Integer tristique dictum tincidunt. Donec ut nisi non ante fringilla vestibulum sit amet pellentesque nibh. Aenean nec mollis nulla, eu tristique nunc. Curabitur sed bibendum nibh, vel iaculis magna. Maecenas ex eros, hendrerit venenatis faucibus at, consectetur quis tortor. In porttitor eget mi id consequat. Nulla ante nisl, laoreet euismod scelerisque non, viverra sed ligula. Sed pulvinar lorem arcu, a euismod nisi tristique in. Suspendisse mauris est, dictum eu risus lacinia, dictum consequat mauris. Quisque vulputate ac odio ut pretium.
Sed tempus condimentum turpis at commodo. In hac habitasse platea dictumst. Integer hendrerit velit ante. Etiam dignissim urna vitae imperdiet pretium. Donec at dolor eleifend, elementum velit eget, semper mi. Sed euismod urna pellentesque mauris elementum, vitae vulputate lorem facilisis. Pellentesque vel velit nulla. Aenean et lectus ac lorem tristique placerat.


text:
import React from 'react';
import { Table } from 'react-bootstrap';

const ReleaseHeader = (props) => {
  const { label, releaseDate, styles } = props;
  return (

          Label
          {label}

          Released
          {releaseDate}

          Styles
          {styles}

  );
};

ReleaseHeader.propTypes = {
  label: React.PropTypes.string.isRequired,
  releaseDate: React.PropTypes.string.isRequired,
  styles: React.PropTypes.string.isRequired,
};

export default ReleaseHeader;


text:
<?php
namespace schmunk42\giiant\generators\module;

use yii\gii\CodeFile;
use yii\helpers\StringHelper;

class Generator extends \yii\gii\generators\module\Generator
{
    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'Giiant Module';
    }

    /**
     * @inheritdoc
     */
    public function requiredTemplates()
    {
        return ['module.php', 'controller.php', 'view.php'];
    }

    /**
     * @inheritdoc
     */
    public function generate()
    {
        $files = [];
        $modulePath = $this->getModulePath();
        $files[] = new CodeFile(
            $modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php',
            $this->render("module.php")
        );
        $files[] = new CodeFile(
            $modulePath . '/controllers/DefaultController.php',
            $this->render("controller.php")
        );
        $files[] = new CodeFile(
            $modulePath . '/views/default/index.php',
            $this->render("view.php")
        );
        $files[] = new CodeFile(
            $modulePath . '/traits/ActiveRecordDbConnectionTrait.php',
            $this->render("db-connection-trait.php")
        );

        return $files;
    }

    /**
     * @return string the controller namespace of the module.
     */
    public function getTraitsNamespace()
    {
        return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')) . '\traits';
    }
}


text:
package io.wcm.handler.url;

import org.apache.sling.api.resource.Resource;
import org.jetbrains.annotations.Nullable;
import org.osgi.annotation.versioning.ProviderType;

/**
 * Detects the site root based on Context-Aware configuration context paths.
 */
@ProviderType
public interface SiteRootDetector {

  /**
   * Returns the absolute path level where the root page of the site is located.
   * This is the context path of the "inner-most" context-aware configuration context.
   * @param contextResource Context resource that is assumed to be inside the site context.
   * @return Root level or -1 if it could not be detected
   */
  int getSiteRootLevel(@Nullable Resource contextResource);

}


text:
namespace gasv1 = ::google::api::servicecontrol::v1;

using ::google::api::servicecontrol::v1::QuotaError;
using ::google::api_manager::utils::Status;
using ::google::protobuf::util::error::Code;

namespace google {
namespace api_manager {
namespace service_control {

namespace {

Status ConvertAllocateQuotaErrorToStatus(gasv1::QuotaError::Code code,
                                         const char* error_detail,
                                         const char* service_name) {
  gasv1::AllocateQuotaResponse response;
  gasv1::QuotaError* quota_error = response.add_allocate_errors();
  QuotaRequestInfo info;
  quota_error->set_code(code);
  quota_error->set_description(error_detail);
  return Proto::ConvertAllocateQuotaResponse(response, service_name);
}

Status ConvertAllocateQuotaErrorToStatus(gasv1::QuotaError::Code code) {
  gasv1::AllocateQuotaResponse response;
  std::string service_name;
  response.add_allocate_errors()->set_code(code);
  return Proto::ConvertAllocateQuotaResponse(response, service_name);
}

}  // namespace

TEST(AllocateQuotaResponseTest,
     AbortedWithInvalidArgumentWhenRespIsKeyInvalid) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::API_KEY_INVALID);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithInvalidArgumentWhenRespIsKeyExpired) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::API_KEY_EXPIRED);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithInvalidArgumentWhenRespIsBlockedWithResourceExausted) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::RESOURCE_EXHAUSTED);
  EXPECT_EQ(Code::RESOURCE_EXHAUSTED, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithInvalidArgumentWhenRespIsBlockedWithProjectSuspended) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::PROJECT_SUSPENDED);
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithServiceNotEnabled) {
  Status result = ConvertAllocateQuotaErrorToStatus(
      QuotaError::SERVICE_NOT_ENABLED,
      "API api_xxxx is not enabled for the project.", "api_xxxx");
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
  EXPECT_EQ(result.message(), "API api_xxxx is not enabled for the project.");
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithBillingNotActivated) {
  Status result = ConvertAllocateQuotaErrorToStatus(
      QuotaError::BILLING_NOT_ACTIVE,
      "API api_xxxx has billing disabled. Please enable it..", "api_xxxx");
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
  EXPECT_EQ(result.message(),
            "API api_xxxx has billing disabled. Please enable it.");
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithIpAddressBlocked) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::IP_ADDRESS_BLOCKED);
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithRefererBlocked) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::REFERER_BLOCKED);
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithClientAppBlocked) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::CLIENT_APP_BLOCKED);
  EXPECT_EQ(Code::PERMISSION_DENIED, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenResponseIsBlockedWithProjectInvalid) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::PROJECT_INVALID);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithProjectDeleted) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::PROJECT_DELETED);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithApiKeyInvalid) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::API_KEY_INVALID);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AbortedWithPermissionDeniedWhenRespIsBlockedWithApiKeyExpiread) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::API_KEY_EXPIRED);
  EXPECT_EQ(Code::INVALID_ARGUMENT, result.code());
}

TEST(AllocateQuotaResponseTest,
     AcceptOKWhenRespIsBlockedWithProjectStatusUnavailable) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::PROJECT_STATUS_UNVAILABLE);
  EXPECT_EQ(Code::OK, result.code());
}

TEST(AllocateQuotaResponseTest,
     AcceptOKWhenRespIsBlockedWithServiceStatusUnavailable) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::SERVICE_STATUS_UNAVAILABLE);
  EXPECT_EQ(Code::OK, result.code());
}

TEST(AllocateQuotaResponseTest,
     AcceptOKWhenRespIsBlockedWithBillingStatusUnavailable) {
  Status result =
      ConvertAllocateQuotaErrorToStatus(QuotaError::BILLING_STATUS_UNAVAILABLE);
  EXPECT_EQ(Code::OK, result.code());
}

TEST(AllocateQuotaResponseTest, FailOpenWhenResponseIsUnknownBillingStatus) {
  EXPECT_TRUE(
      ConvertAllocateQuotaErrorToStatus(QuotaError::BILLING_STATUS_UNAVAILABLE)
          .ok());
}

TEST(AllocateQuotaResponseTest, FailOpenWhenResponseIsUnknownServiceStatus) {
  EXPECT_TRUE(
      ConvertAllocateQuotaErrorToStatus(QuotaError::SERVICE_STATUS_UNAVAILABLE)
          .ok());
}

}  // namespace service_control
}  // namespace api_manager
}  // namespace google


text:
The [package documentation](src/main/java/cucumber/api/guice/package.html) contains detailed instructions for using
Cucumber Guice. In particular be sure to read the migration section if upgrading from earlier versions of Cucumber
Guice.


text:
module CustomClass
=begin
The REST-Interface does not work with "select from SomeClass where a_property like 'pattern%' "

This is rewritten as

  SomeClass.like "name = D*", order: 'asc'

The order-argument is optional, "asc" is the default.
This Primitiv-Version only accepts the wildcards "*" and "%" at the end of the seach-string.
The Wildcard can be omitted.

The method does not accept further arguments.
=end
  def like operation, order: 'asc'
    # remove all spaces and split the resulting word
		case operation
		when Hash
			p,s = operation.keys.first, operation.values.first
		else
			p, s = operation.gsub(/\s+/, "").split("=")
		end
    if ["%","*"].include?(s[-1])
      s.chop!
    end

    query( where: { "#{p}.left(#{s.length})" => s } ,order: { p => order }).execute
  end
end


text:
require 'spec_helper'

describe ActivityStreams::Object::Bookmark do
  its(:recommended_verbs) { should == [:post, :favorite] }

  context 'when invalid attributes given' do
    let(:invalid_attributes) do
      {:target_url => 'http://'}
    end

    it do
      expect { ActivityStreams::Object::Bookmark.new invalid_attributes }.should raise_error ActivityStreams::InvalidAttribute
    end
  end
end


text:
This is an HOWDOI build an msi package from a windows machine using appveyor cloud service.

### Requirements

- a github account
- a github repo
- an appveyor account

### Repo setup

1. Add your repo to appveyor config
2. Generate a new Github API token (Settings->Personal access tokens->Generate new token). Give it authorizations to `repo`.
3. Save the new token!
3. Add a new `appveyor.yml` to the root of your repo
4. Encrypt the token value as an appveyor secure variable (AppVeyor->Dashboard->[Encrypt Data](https://ci.appveyor.com/tools/encrypt))
5. Modify below appveyor template

__appveyor.yml__

```yml
image: Visual Studio 2017
clone_folder: c:\gopath\src\github.com\%APPVEYOR_REPO_NAME%

# trigger build/deploy only on tag
# if false, take care that %APPVEYOR_REPO_TAG_NAME% won t be set on commit
# this will fail the build
skip_non_tags: true

environment:
  GOPATH: c:\gopath
  JFROG_CLI_OFFER_CONFIG: false
  VCS_URL: https://github.com/%APPVEYOR_REPO_NAME%
  BT_KEY:
    secure: yyyy
  CHOCOKEY:
    secure: xxxxx

install:
  # wix setup
  - set PATH=%WIX%\bin;%PATH%
  # go setup
  - set PATH=%GOPATH%\bin;%PATH%
  # glide setup, if your package uses it
  - go get -u github.com/mh-cbon/never-fail
  - go get -u github.com/Masterminds/glide
  # setup go-msi, choose one method
  #
  # method 1: static link
  # - curl -fsSL -o C:\go-msi.msi https://github.com/mh-cbon/go-msi/releases/download/0.0.22/go-msi-amd64.msi
  # - msiexec.exe /i C:\go-msi.msi /quiet
  # - set PATH=C:\Program Files\go-msi\;%PATH% # for some reason, go-msi path needs to be added manually :(...
  #
  # method 2: via gh-api-cli
  # - curl -fsSL -o C:\latest.bat https://raw.githubusercontent.com/mh-cbon/latest/master/latest.bat
  # - cmd /C C:\latest.bat mh-cbon go-msi amd64
  # - set PATH=C:\Program Files\go-msi\;%PATH%
  #
  # method 3: via chocolatey
  - choco install changelog -y
  - choco install go-msi -y
  - glide install

build_script:
  - set GH_APP=%APPVEYOR_PROJECT_NAME%
  - set GH_USER=%APPVEYOR_ACCOUNT_NAME%
  - set VERSION=%APPVEYOR_REPO_TAG_NAME%
  # - set VERSION=1.0.2 # fake it when needed
  - set GOARCH=386
  - go build -o %MYAPP%.exe --ldflags "-X main.VERSION=%VERSION%" main.go
  - .\go-msi.exe make --msi %GH_APP%-%GOARCH%.msi --version %VERSION% --arch %GOARCH%
  - set GOARCH=amd64
  - go build -o %MYAPP%.exe --ldflags "-X main.VERSION=%VERSION%" main.go
  - .\go-msi.exe make --msi %GH_APP%-%GOARCH%.msi --version %VERSION% --arch %GOARCH%

after_deploy:
  # Choco push
  - .\go-msi.exe choco --input %GH_APP%-%GOARCH%.msi --version %VERSION% --changelog-cmd "changelog ghrelease --version %VERSION%"
  - choco push -k="'%CHOCOKEY%'" %GH_APP%.%VERSION%.nupkg
    # Bintray push
  - never-fail jfrog bt pc --user %GH_USER% --key %BT_KEY% --licenses=MIT --vcs-url=https://github.com/%APPVEYOR_REPO_NAME% %GH_USER%/msi/%GH_APP%
  - jfrog bt upload --user %GH_USER% --key %BT_KEY%  --override=true --publish=true %GH_APP%-%GOARCH%-%VERSION%.msi %GH_USER%/msi/%GH_APP%/%VERSION%
  - never-fail jfrog bt pc --user %GH_USER% --key %BT_KEY% --licenses=MIT --vcs-url=https://github.com/%APPVEYOR_REPO_NAME% %GH_USER%/choco/%GH_APP%
  - jfrog bt upload --user %GH_USER% --key %BT_KEY%  --override=true --publish=true %GH_APP%.%VERSION%.nupkg %GH_USER%/choco/%GH_APP%/%VERSION%

# to disable automatic tests
test: off

# need this to deploy assets,
# note that each MUST match only one file
artifacts:
  - path: '*-386.msi'
    name: msi-x86
  - path: '*-amd64.msi'
    name: msi-x64

# deploy section to github releases
deploy:
  - provider: GitHub
    # it should be possible to use a regexp like this /msi.*/,
    # but I could not make it work, let me know if you find a solution
    artifact: msi-x86, msi-x64
    draft: false
    prerelease: false
    description: "Release {APPVEYOR_REPO_TAG_NAME}"
    auth_token:
      # Change this to your encrypted token value
      secure: xxxxx
    on:
      branch:
        - master
        - /v\d\.\d\.\d/
        - /\d\.\d\.\d/
      appveyor_repo_tag: true
```

### Workflow

With this `appveyor.yml` config,
every time you create a tag and push it on the remote,
`msi` files are generated and uploaded to your github release.

`choco` package is generated from the amd64 build,
and uploaded to your choco account.

Both `msi` nad `nupkg` artifacts are uploaded to your bintray repos (/msi/ and /choco/)

[go here](https://ci.appveyor.com/tools/encrypt)
to generate the secure variable containing your `choco` api key and your `bintray` key.

For an easy way to bump,
you can use [gump](https://github.com/mh-cbon/gump),
with a script like this,

```yml
scripts:
  prebump: 666 git fetch --tags
  preversion: |
    philea -s "666 go vet %s" "666 go-fmt-fail %s" \
    && go run main.go -v
  postversion: |
    666 git push && 666 git push --tags \
    && 666 gh-api-cli create-release -n release -o YOURUSER -r YOURREPO --ver !newversion!
```


text:
<?php

namespace common\models\facility;

use common\utilities\DateTimeDbConversion;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "availability".
 *
 * @property integer $id
 * @property integer $room_id
 * @property string $date_from
 * @property string $date_to
 * @property string $description
 *
 * @property Room $room
 */
class Availability extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'availability';
    }

	/**
	 * @return array configuration of behaviors.
	 */
	public function behaviors()
	{
		return [
			'dateTime' => [
				'class' => DateTimeDbConversion::className(),
				'attributes' =>[
					[
						'name' => 'date_from'
					],
					[
						'name' => 'date_to'
					]
				]
			]
		];
	}

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['room_id'], 'integer'],
	        [['date_from', 'date_to'], 'default', 'value' => null],
            [['date_from', 'date_to'], 'required'],
            [['date_from', 'date_to'], 'date', 'format' => 'php:Y-m-d'],
	        ['date_from', 'compare', 'compareValue' => date('Y-m-d', time()+86400), 'operator' => '>='],
	        ['date_to', 'compare', 'compareAttribute' => 'date_from', 'operator' => '>='],
            [['description'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'room_id' => Yii::t('app', 'Room ID'),
            'date_from' => Yii::t('app', 'Date From'),
            'date_to' => Yii::t('app', 'Date To'),
            'description' => Yii::t('app', 'Description'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRoom()
    {
        return $this->hasOne(Room::className(), ['id' => 'room_id']);
    }
}


text:
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_GEOMETRY_FRUSTUM_HPP_
#define OPENMVG_GEOMETRY_FRUSTUM_HPP_

#include "openMVG/geometry/half_space_intersection.hpp"

namespace openMVG {
namespace geometry {

using namespace openMVG::geometry::halfPlane;

/// Define a camera Frustum:
///  - infinite Frustum (4 Half Spaces) (a pyramid)
///  - truncated Frustum (6 Half Spaces) (a truncated pyramid)
///  - This structure is used for testing frustum intersection (see if two cam can share visual content)
struct Frustum
{
  Vec3 cones[5]; // camera centre and the 4 points that define the image plane
  Half_planes planes; // Define infinite frustum planes + 2 optional Near and Far Half Space
  double z_near, z_far;
  std::vector<Vec3> points;

  Frustum() : z_near(-1.), z_far(-1.)  {}

  // Build a frustum from the image size, camera intrinsic and pose
  Frustum(const int w, const int h, const Mat3 & K, const Mat3 & R, const Vec3 & C)
    : z_near(-1.), z_far(-1.)
  {
    const Mat3 Kinv = K.inverse();
    const Mat3 Rt = R.transpose();

    // Definition of the frustum with the supporting points
    cones[0] = C;
    cones[1] = Rt * ((Kinv * Vec3(0,0,1.0))) + C;
    cones[2] = Rt * ((Kinv * Vec3(w,0,1.0))) + C;
    cones[3] = Rt * ((Kinv * Vec3(w,h,1.0))) + C;
    cones[4] = Rt * ((Kinv * Vec3(0,h,1.0))) + C;

    // Definition of the supporting planes
    planes.push_back( Half_plane_p(cones[0], cones[4], cones[1]) );
    planes.push_back( Half_plane_p(cones[0], cones[1], cones[2]) );
    planes.push_back( Half_plane_p(cones[0], cones[2], cones[3]) );
    planes.push_back( Half_plane_p(cones[0], cones[3], cones[4]) );

    // supporting point for drawing is a normalized cone, since infinity cannot be represented
    points = std::vector<Vec3>(&cones[0], &cones[0]+5);
  }

  Frustum(const int w, const int h, const Mat3 & K, const Mat3 & R, const Vec3 & C, const double zNear, const double zFar)
  {
    *this = Frustum(w,h,K,R,C);

    // update near & far planes & clear set points
    z_near = zNear;
    z_far = zFar;
    points.clear();
    assert(zFar > zNear);

    // Add Znear and ZFar half plane using the cam looking direction
    const Vec3 camLookDirection_n = R.row(2).normalized();
    const double d_near = - zNear - camLookDirection_n.dot(C);
    planes.push_back( Half_plane(camLookDirection_n, d_near) );

    const double d_Far = zFar + camLookDirection_n.dot(C);
    planes.push_back( Half_plane(-camLookDirection_n, d_Far) );

    // supporting point are the points defined by the truncated cone
    const Mat3 Kinv = K.inverse();
    const Mat3 Rt = R.transpose();
    points.push_back( Rt * (z_near * (Kinv * Vec3(0,0,1.0))) + C);
    points.push_back( Rt * (z_near * (Kinv * Vec3(w,0,1.0))) + C);
    points.push_back( Rt * (z_near * (Kinv * Vec3(w,h,1.0))) + C);
    points.push_back( Rt * (z_near * (Kinv * Vec3(0,h,1.0))) + C);

    points.push_back( Rt * (z_far * (Kinv * Vec3(0,0,1.0))) + C);
    points.push_back( Rt * (z_far * (Kinv * Vec3(w,0,1.0))) + C);
    points.push_back( Rt * (z_far * (Kinv * Vec3(w,h,1.0))) + C);
    points.push_back( Rt * (z_far * (Kinv * Vec3(0,h,1.0))) + C);
  }

  /// Test if two frustums intersect or not
  bool intersect(const Frustum & f) const
  {
    // Concatenate the Half Planes and see if an intersection exists
    std::vector<Half_plane> vec_planes(planes.size() + f.planes.size());
    std::copy(&planes[0], &planes[0]+planes.size(), &vec_planes[0]);
    std::copy(&f.planes[0], &f.planes[0]+f.planes.size(), &vec_planes[planes.size()]);

    return halfPlane::isNotEmpty(vec_planes);
  }

  /// Return true if the Frustum is an infinite one
  bool isInfinite() const
  {
    return planes.size() == 4;
  }

  /// Return true if the Frustum is truncated
  bool isTruncated() const
  {
    return planes.size() == 6;
  }

  // Return the supporting frustum points (5 for the infinite, 8 for the truncated)
  const std::vector<Vec3> & frustum_points() const
  {
    return points;
  }

}; // struct Frustum

} // namespace geometry
} // namespace openMVG

#endif // OPENMVG_GEOMETRY_FRUSTUM_HPP_


text:
<!DOCTYPE html>

	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta charset="utf-8" />
	<title> Return - GlosoTech </title>
	<meta content="" name="keywords"/>
	<meta id="description" content="" name="description"/>
	<link href="/css/index.css" rel="stylesheet" type="text/css" />
	<link href="/css/main.css" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" type="text/css" href="/css/thickbox/css/thickbox.css"/>

Home

about

· About GLOSO

· Contact Us

· Events

· Trade Shows

Account

· My Profile

· My Order

· Modify Address

· Funds Management

· Returns Management

Terms & Conditions

· Terms & Conditions

· Cross Reference

· Privacy

Products


text:
"""Parse command line arguments and update :attr:`stagpy.conf`."""

from __future__ import annotations
from inspect import isfunction
from types import MappingProxyType
import importlib.resources as imlr
import typing

from loam.cli import Subcmd, CLIManager
import matplotlib.pyplot as plt
import matplotlib.style as mpls

from . import __doc__ as doc_module
from . import conf, ISOLATED
from . import (
    commands, config, field, rprof, time_series, refstate, plates, _styles,
)
from ._helpers import baredoc
from .config import CONFIG_DIR

if typing.TYPE_CHECKING:
    from typing import Any, Optional, List, Callable

def _sub(cmd: Any, *sections: str) -> Subcmd:
    """Build Subcmd instance."""
    cmd_func = cmd if isfunction(cmd) else cmd.cmd
    return Subcmd(baredoc(cmd), *sections, func=cmd_func)

def _bare_cmd() -> None:
    """Print help message when no arguments are given."""
    print(doc_module)
    print('Run `stagpy -h` for usage')

def _load_mplstyle() -> None:
    """Try to load conf.plot.mplstyle matplotlib style."""
    for style in conf.plot.mplstyle:
        style_fname = style + ".mplstyle"
        if not ISOLATED:
            stfile = config.CONFIG_DIR / style_fname
            if stfile.is_file():
                mpls.use(str(stfile))
                continue
        # try packaged version
        if imlr.is_resource(_styles, style_fname):
            with imlr.path(_styles, style_fname) as stfile:
                mpls.use(str(stfile))
                continue
        mpls.use(style)
    if conf.plot.xkcd:
        plt.xkcd()

SUB_CMDS = MappingProxyType({
    'common_': Subcmd(doc_module, 'common', func=_bare_cmd),
    'field': _sub(field, 'core', 'plot', 'scaling'),
    'rprof': _sub(rprof, 'core', 'plot', 'scaling'),
    'time': _sub(time_series, 'core', 'plot', 'scaling'),
    'refstate': _sub(refstate, 'core', 'plot'),
    'plates': _sub(plates, 'core', 'plot', 'scaling'),
    'info': _sub(commands.info_cmd, 'core', 'scaling'),
    'var': _sub(commands.var_cmd),
    'version': _sub(commands.version_cmd),
    'config': _sub(commands.config_cmd),
})

def parse_args(arglist: Optional[List[str]] = None) -> Callable[[], None]:
    """Parse cmd line arguments.

    Update :attr:`stagpy.conf` accordingly.

    Args:
        arglist: the list of cmd line arguments. If set to None, the arguments
            are taken from :attr:`sys.argv`.

    Returns:
        the function implementing the sub command to be executed.
    """
    climan = CLIManager(conf, **SUB_CMDS)

    bash_script = CONFIG_DIR / "bash" / "stagpy.sh"
    bash_script.parent.mkdir(parents=True, exist_ok=True)
    climan.bash_complete(bash_script, "stagpy")
    zsh_script = CONFIG_DIR / "zsh" / "_stagpy.sh"
    zsh_script.parent.mkdir(parents=True, exist_ok=True)
    climan.zsh_complete(zsh_script, "stagpy", sourceable=True)

    cmd_args = climan.parse_args(arglist)
    sub_cmd = cmd_args.loam_sub_name

    if sub_cmd is None:
        return cmd_args.func

    if conf.common.config:
        commands.config_pp(climan.sections_list(sub_cmd))

    _load_mplstyle()

    return cmd_args.func


text:
package xyz.jmullin.drifter.enrich

import com.badlogic.gdx.math.Rectangle
import xyz.jmullin.drifter.VectorHex
import scala.language.implicitConversions

/**
 * Convenience implicits, constructors and type aliases for working with enriched geometry classes.
 */
object RichGeometry {
  // 2d Vectors

  type Vector2 = com.badlogic.gdx.math.Vector2
  type V2 = Vector2
  def V2(xy: Float) = new V2(xy, xy)
  def V2(x: Float, y: Float) = new V2(x, y)

  implicit def enrichVector2(v: V2): RichVector2 = new RichVector2(v)
  implicit def tupleToRichVector2(t: (Float, Float)): V2 = V2(t._1, t._2)

  // 3d Vectors

  type Vector3 = com.badlogic.gdx.math.Vector3
  type V3 = Vector3
  def V3(xyz: Float) = new V3(xyz, xyz, xyz)
  def V3(v: V2, z: Float) = new V3(v.x, v.y, z)
  def V3(x: Float, v: V2) = new V3(x, v.x, v.y)
  def V3(x: Float, y: Float, z: Float) = new V3(x, y, z)

  implicit def enrichVector3(v: V3): RichVector3 = new RichVector3(v)
  implicit def tupleToRichVector3(t: (Float, Float, Float)): V3 = V3(t._1, t._2, t._3)

  // Matrices

  type M3 = com.badlogic.gdx.math.Matrix3
  type M4 = com.badlogic.gdx.math.Matrix4

  // Hex geometry

  type Vh = VectorHex
  def Vh(q: Float, r: Float, s: Float) = VectorHex(q, r, s)
  def Vh(q: Float, s: Float) = VectorHex(q, s)
  def Vho(x: Int, y: Int) = VectorHex(x, y - (x  - (x & 1)) / 2)

  // Other shapes

  type Rect = Rectangle
  def Rect(x: Float, y: Float, width: Float, height: Float) = new Rectangle(x, y, width, height)
  def Rect(v: V2, size: V2) = new Rectangle(v.x, v.y, size.x, size.y)

  implicit def enrichRect(r: Rect): RichRectangle = new RichRectangle(r)
}


text:
Install node.js

Install bower, grunt et coffee-script

    npm install -g bower grunt-cli coffee-script

Install dependencies

    npm install
    bower install

Copy and Configure jade.conf.coffee

    cp jade.conf.default.coffee jade.conf.coffee

Run server and dev tools

    grunt

Open brower

    open http://localhost:3333/


text:
name: Question
about: Create a report to help us improve
title: Question
---

<!--- Provide a general summary of the issue in the Title above -->

## Question

<!--- Provide your detailed question here -->

## Additional context

<!--- Optional: supply any additional context on what you are trying to do -->