text:
package org.kie.workbench.common.dmn.client.editors.expressions.types.function;

import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.HasExpression;
import org.kie.workbench.common.dmn.api.definition.HasName;
import org.kie.workbench.common.dmn.api.definition.v1_1.Decision;
import org.kie.workbench.common.dmn.api.definition.v1_1.Expression;
import org.kie.workbench.common.dmn.api.definition.v1_1.FunctionDefinition;
import org.kie.workbench.common.dmn.api.definition.v1_1.InformationItem;
import org.kie.workbench.common.dmn.api.definition.v1_1.LiteralExpression;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.client.commands.expressions.types.function.AddParameterCommand;
import org.kie.workbench.common.dmn.client.commands.expressions.types.function.SetKindCommand;
import org.kie.workbench.common.dmn.client.commands.general.SetCellValueCommand;
import org.kie.workbench.common.dmn.client.editors.expressions.types.ExpressionEditorDefinition;
import org.kie.workbench.common.dmn.client.editors.expressions.types.ExpressionEditorDefinitions;
import org.kie.workbench.common.dmn.client.editors.expressions.types.ExpressionType;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionCellValue;
import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionEditorColumn;
import org.kie.workbench.common.dmn.client.events.ExpressionEditorSelectedEvent;
import org.kie.workbench.common.dmn.client.widgets.grid.BaseExpressionGrid;
import org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridData;
import org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple;
import org.kie.workbench.common.dmn.client.widgets.layer.DMNGridLayer;
import org.kie.workbench.common.dmn.client.widgets.panel.DMNGridPanel;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridData;
import org.uberfire.ext.wires.core.grids.client.widget.dnd.GridWidgetDnDHandlersState;
import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.layer.impl.GridLayerRedrawManager;
import org.uberfire.mocks.EventSourceMock;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

@RunWith(LienzoMockitoTestRunner.class)
public class FunctionGridTest {

    @Mock
    private DMNGridPanel gridPanel;

    @Mock
    private DMNGridLayer gridLayer;

    @Mock
    private SessionManager sessionManager;

    @Mock
    private SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;

    @Mock
    private ClientSession session;

    @Mock
    private AbstractCanvasHandler canvasHandler;

    @Mock
    private Supplier<ExpressionEditorDefinitions> expressionEditorDefinitionsSupplier;

    @Mock
    private Supplier<ExpressionEditorDefinitions> supplementaryEditorDefinitionsSupplier;

    @Mock
    private EventSourceMock<ExpressionEditorSelectedEvent> editorSelectedEvent;

    @Mock
    private ManagedInstance<FunctionGridControls> controlsProvider;

    @Mock
    private FunctionGridControls controls;

    @Mock
    private GridCellTuple parent;

    @Mock
    private HasExpression hasExpression;

    @Mock
    private ExpressionEditorDefinition literalExpressionEditorDefinition;

    @Mock
    private BaseExpressionGrid literalExpressionEditor;

    private LiteralExpression literalExpression = new LiteralExpression();

    @Mock
    private ExpressionEditorDefinition supplementaryLiteralExpressionEditorDefinition;

    @Mock
    private GridWidget supplementaryLiteralExpressionEditor;

    private LiteralExpression supplementaryLiteralExpression = new LiteralExpression();

    @Mock
    private GridWidgetDnDHandlersState dndHandlersState;

    @Captor
    private ArgumentCaptor<Optional<Expression>> expressionCaptor;

    @Captor
    private ArgumentCaptor<Optional<BaseExpressionGrid>> gridWidgetCaptor;

    @Captor
    private ArgumentCaptor<GridLayerRedrawManager.PrioritizedCommand> redrawCaptor;

    private Optional<FunctionDefinition> expression;

    private FunctionGrid grid;

    @Before
    @SuppressWarnings("unchecked")
    public void setup() {
        final FunctionEditorDefinition definition = new FunctionEditorDefinition(gridPanel,
                                                                                gridLayer,
                                                                                sessionManager,
                                                                                sessionCommandManager,
                                                                                expressionEditorDefinitionsSupplier,
                                                                                supplementaryEditorDefinitionsSupplier,
                                                                                editorSelectedEvent,
                                                                                controlsProvider);

        expression = definition.getModelClass();
        expression.get().getFormalParameter().add(new InformationItem() {{
            setName(new Name("p0"));
        }});

        final ExpressionEditorDefinitions expressionEditorDefinitions = new ExpressionEditorDefinitions();
        expressionEditorDefinitions.add((ExpressionEditorDefinition) definition);
        expressionEditorDefinitions.add(literalExpressionEditorDefinition);
        expressionEditorDefinitions.add(supplementaryLiteralExpressionEditorDefinition);

        final Decision decision = new Decision();
        decision.setName(new Name("name"));
        final Optional<HasName> hasName = Optional.of(decision);

        doReturn(controls).when(controlsProvider).get();
        doReturn(expressionEditorDefinitions).when(expressionEditorDefinitionsSupplier).get();
        doReturn(expressionEditorDefinitions).when(supplementaryEditorDefinitionsSupplier).get();

        doReturn(ExpressionType.LITERAL_EXPRESSION).when(literalExpressionEditorDefinition).getType();
        doReturn(Optional.of(literalExpression)).when(literalExpressionEditorDefinition).getModelClass();
        doReturn(Optional.of(literalExpressionEditor)).when(literalExpressionEditorDefinition).getEditor(any(GridCellTuple.class),
                                                                                any(HasExpression.class),
                                                                                any(Optional.class),
                                                                                any(Optional.class),
                                                                                anyBoolean());

        doReturn(Optional.of(supplementaryLiteralExpression)).when(supplementaryLiteralExpressionEditorDefinition).getModelClass();
        doReturn(Optional.of(supplementaryLiteralExpressionEditor)).when(supplementaryLiteralExpressionEditorDefinition).getEditor(any(GridCellTuple.class),
                                                                                any(HasExpression.class),
                                                                                any(Optional.class),
                                                                                any(Optional.class),
                                                                                anyBoolean());
        final GridData uiLiteralExpressionModel = new BaseGridData();
        doReturn(uiLiteralExpressionModel).when(literalExpressionEditor).getModel();

        doReturn(session).when(sessionManager).getCurrentSession();
        doReturn(canvasHandler).when(session).getCanvasHandler();

        this.grid = spy((FunctionGrid) definition.getEditor(parent,
                                                            hasExpression,
                                                            expression,
                                                            hasName,
                                                            false).get());
    }

    @Test
    public void testInitialSetupFromDefinition() {
        final GridData uiModel = grid.getModel();
        assertTrue(uiModel instanceof DMNGridData);

        assertEquals(1,
                     uiModel.getColumnCount());
        assertTrue(uiModel.getColumns().get(0) instanceof ExpressionEditorColumn);

        assertEquals(1,
                     uiModel.getRowCount());

        assertTrue(uiModel.getCell(0, 0).getValue() instanceof ExpressionCellValue);
        final ExpressionCellValue dcv = (ExpressionCellValue) uiModel.getCell(0, 0).getValue();
        assertEquals(literalExpressionEditor,
                     dcv.getValue().get());
    }

    @Test
    public void testGetEditorControls() {
        grid.getEditorControls();

        verify(controls).initSelectedKind(eq(FunctionDefinition.Kind.FEEL));
        verify(controls).enableKind(eq(true));
        verify(controls).initSelectedExpressionType(eq(ExpressionType.LITERAL_EXPRESSION));
        verify(controls).enableExpressionType(eq(true));
    }

    @Test
    public void testColumnMetaData() {
        final GridColumn<?> column = grid.getModel().getColumns().get(0);
        final List<GridColumn.HeaderMetaData> header = column.getHeaderMetaData();

        assertEquals(2,
                     header.size());
        assertTrue(header.get(0) instanceof FunctionColumnNameHeaderMetaData);
        assertTrue(header.get(1) instanceof FunctionColumnParametersHeaderMetaData);

        final FunctionColumnNameHeaderMetaData md1 = (FunctionColumnNameHeaderMetaData) header.get(0);
        final FunctionColumnParametersHeaderMetaData md2 = (FunctionColumnParametersHeaderMetaData) header.get(1);

        assertEquals("name",
                     md1.getTitle());
        assertEquals("F",
                     md2.getExpressionLanguageTitle());
        assertEquals("(p0)",
                     md2.getFormalParametersTitle());
    }

    @Test
    public void testAddFormalParameter() {
        grid.addFormalParameter();

        verify(sessionCommandManager).execute(any(AbstractCanvasHandler.class),
                                              any(AddParameterCommand.class));
    }

    @Test
    public void testSetKindFEEL() {
        grid.setKind(FunctionDefinition.Kind.FEEL);

        assertSetKind(FunctionDefinition.Kind.FEEL,
                      literalExpression,
                      literalExpressionEditor);
    }

    @Test
    public void testSetKindJava() {
        doReturn(ExpressionType.FUNCTION_JAVA).when(supplementaryLiteralExpressionEditorDefinition).getType();

        grid.setKind(FunctionDefinition.Kind.JAVA);

        assertSetKind(FunctionDefinition.Kind.JAVA,
                      supplementaryLiteralExpression,
                      supplementaryLiteralExpressionEditor);
    }

    @Test
    public void testSetKindPMML() {
        doReturn(ExpressionType.FUNCTION_PMML).when(supplementaryLiteralExpressionEditorDefinition).getType();

        grid.setKind(FunctionDefinition.Kind.PMML);

        assertSetKind(FunctionDefinition.Kind.PMML,
                      supplementaryLiteralExpression,
                      supplementaryLiteralExpressionEditor);
    }

    private void assertSetKind(final FunctionDefinition.Kind expectedKind,
                               final Expression expectedExpression,
                               final GridWidget expectedEditor) {
        verify(grid).doSetKind(eq(expectedKind),
                               eq(expression.get()),
                               expressionCaptor.capture(),
                               gridWidgetCaptor.capture());
        assertEquals(expectedExpression,
                     expressionCaptor.getValue().get());
        assertEquals(expectedEditor,
                     gridWidgetCaptor.getValue().get());

        verify(sessionCommandManager).execute(any(AbstractCanvasHandler.class),
                                              any(SetKindCommand.class));
    }

    @Test
    public void testSetExpressionType() {
        grid.setExpressionType(ExpressionType.LITERAL_EXPRESSION);

        verify(sessionCommandManager).execute(any(AbstractCanvasHandler.class),
                                              any(SetCellValueCommand.class));
    }

    @Test
    public void testSynchroniseViewWhenExpressionEditorChanged() {
        grid.synchroniseViewWhenExpressionEditorChanged(Optional.of(literalExpressionEditor));

        verify(parent).onResize();
        verify(gridPanel).refreshScrollPosition();
        verify(gridPanel).updatePanelSize();
        verify(gridLayer).batch(redrawCaptor.capture());
        verify(grid).getEditorControls();

        final GridLayerRedrawManager.PrioritizedCommand command = redrawCaptor.getValue();
        command.execute();

        verify(gridLayer).draw();
        verify(gridLayer).select(eq(literalExpressionEditor));
    }
}


text:
module CSVPort

  class Junction

    attr_accessor :passer
    attr_accessor :receiver
    attr_accessor :passer_port
    attr_accessor :receiver_port

    def initialize(passer, receiver, opts={})
      @passer = passer
      @receiver = receiver
      @passer_port = (opts[:passer_port] or :default)
      @receiver_port = (opts[:receiver_port] or :default)
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Question2AnswerMigrater.Models
{
    using Microsoft.AspNet.Identity.EntityFramework;

    public class User : IdentityUser
    {
        public string Email { get; set; }
    }
}


text:
require 'net/http'

module Wiziq
  class HttpUtil
    attr_reader:request_url,:params_hash
    def initialize(request_url)
      @request_url = request_url
      @params_hash ||= {}
    end

    def add_params(params={})
      @params_hash = @params_hash.merge! params
    end

    def add_param(key,value)
      @params_hash = @params_hash.merge! Hash[key,value]
    end

    def send_http_request
      uri = URI.parse(@request_url)
      res = nil
      req = Net::HTTP::Post.new(uri.request_uri)
      req.set_form_data(@params_hash, '&')
      http = Net::HTTP.new(uri.host, uri.port)
      res = http.start { |htt| htt.request(req)  }
      case res
      when Net::HTTPSuccess, Net::HTTPRedirection
       r = res.body
       Rails::logger.debug "response xml is #{ r }"
       r
      else
        res.error!
      end
    end
  end
end


text:
'use strict'

import { useEffect, useState } from 'react'
import PropTypes from 'prop-types'

function DelayRender ({ children, visible, startDelay = 200, stopDelay = 1000 }) {
  const [render1, setRender1] = useState(false)
  const [render2, setRender2] = useState(false)

  useEffect(() => {
    const id = setTimeout(() => setRender1(visible), visible ? startDelay : 0)
    return () => clearTimeout(id)
  }, [visible, startDelay])

  useEffect(() => {
    const id = setTimeout(() => setRender2(render1), render1 ? 0 : stopDelay)
    return () => clearTimeout(id)
  }, [render1, stopDelay])

  return render2 ? children : null
}

DelayRender.propTypes = {
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
  visible: PropTypes.bool,
  startDelay: PropTypes.number,
  stopDelay: PropTypes.number
}

export default DelayRender


text:
import React, { PropTypes } from "react";
import { connectToStores } from "fluxible-addons-react";

import Thumbnail from "../components/Thumbnail";

if (process.env.BROWSER) {
  require("../style/ThumbnailCollection.scss");
}

@connectToStores(["FeaturedStore"], (context) => {
  const ids = context.getStore("FeaturedStore").getFeaturedPhotos();
  const photos = context.getStore("PhotoStore").getMultiple(ids);
  return {
    photos: photos
  };
})
class FeaturedPage extends React.Component {

  static propTypes = {
    photos: PropTypes.array.isRequired
  }

  render() {
    const { photos } = this.props;
    return (

          {
            photos.map(photo =>
              <Thumbnail key={ photo.id } size="small" photo={ photo } />
            )
          }

    );
  }

}

export default FeaturedPage;


text:
 Container Monitor {{ containerId }}

       Container List

       Detail

Monitor


text:
package brooklyn.launcher;

public enum PersistMode {
    DISABLED,
    AUTO,
    REBIND,
    CLEAN;
}


text:
title: About Kubernetes egress
description: Learn about Kubernetes egress!
---

>  This guide provides optional background education, including
> education that is not specific to {{site.prodname}}.
{: .alert .alert-info}

In this guide you will learn:
- What is Kubernetes egress?
- Why should you restrict egress traffic and how can you do it?
- What is "NAT outgoing" and when is it used?
- What is an egress gateway, and why might you want to use one?

### What is Kubernetes egress?

In this guide we are using the term Kubernetes egress to describe connections being made from pods to anything outside of the cluster.

In contrast to ingress traffic, where Kubernetes has the [Ingress]({{site.baseurl}}/about/about-kubernetes-ingress)
resource type to help manage the traffic, there is no Kubernetes Egress resource. Instead, how the egress traffic is
handled at a networking level is determined by the Kubernetes network implementation / CNI plugin being used by the
cluster. In addition, if a service mesh is being used, this can add egress behaviors on top of those the
network implementation provides.

There are three areas of behavior worth understanding for egress traffic, so you can choose a networking and/or service
mesh setup that best suits your needs:
- Restricting egress traffic
- Outgoing NAT behavior
- Egress gateways

### Restricting egress traffic

It's a common security requirement and best practice to restrict outgoing connections from the cluster. This is normally
achieved using [Network Policy]({{site.baseurl}}/about/about-network-policy) to define egress rules for each
microservice, often in conjunction with a [default deny]({{site.baseurl}}/about/about-network-policy#default-deny)
policy that ensures outgoing connections are denied by default, until a policy is defined to explicitly allow specific
traffic.

One limitation when using Kubernetes Network Policy to restrict access to specific external resources, is that the external
resources need to be specified as IP addresses (or IP address ranges) within the policy rules. If the IP addresses
associated with an external resource change, then every policy that referenced those IP addresses needs to be updated with
the new IP addresses. This limitation can be circumvented using Calico [Network
Sets]({{site.baseurl}}/security/external-ips-policy), or Calico Enterprise's support for [domain
names]({{site.baseurl}}/security/calico-enterprise/egress-access-controls) in policy rules.

In addition to using network policy, service meshes typically allow you to configure which external services each pod
can access. In the case of Istio, {{site.prodname}} can be integrated to enforce network policy at the service mesh
layer, including [L5-7 rules]({{site.baseurl}}/security/http-methods), as another alternative to using IP addresses in rules. To
learn more about the benefits of this kind of approach, read our [Adopt a zero trust network model for security
]({{site.baseurl}}/security/adopt-zero-trust) guide.

Note in addition to everything mentioned so far, perimeter firewalls can also be used to restrict outgoing connections,
for example to allow connections only to particular external IP address ranges, or external services. However, since
perimeter firewalls typically cannot distinguish individual pods, the rules apply equally to all pods in the cluster.
This provides some defense in depth, but cannot replace the requirement for network policy.

### NAT outgoing

Network Address Translation ({% include open-new-window.html text='NAT'
url='https://en.wikipedia.org/wiki/Network_address_translation' %}) is the process of mapping an IP address in a packet
to a different IP address as the packet passes through the device performing the NAT. Depending on the use case, NAT can
apply to the source or destination IP address, or to both addresses.

In the context of Kubernetes egress, NAT is used to allow pods to connect to services outside of the cluster if the pods
have IP addresses that are not routable outside of the cluster (for example, if the pod network is an overlay).

For example, if a pod in an overlay network attempts to connect to an IP address outside of the cluster, then the
node hosting the pod uses SNAT (Source Network Address Translation) to map the non-routable source IP address of the
packet to the node's IP address before forwarding on the packet.  The node then maps response packets coming in the
opposite direction back to the original pod IP address, so packets flow end-to-end in both directions, with neither
pod or external service being aware the mapping is happening.

In most clusters this NAT behavior is configured statically across the whole of the cluster. When using
{{site.prodname}}, the NAT behavior can be configured at a more granular level for particular address ranges using [IP
pools]({{site.baseurl}}/reference/resources/ippool). This effectively allows the scope of "non-routable" to be more
tightly defined than just "inside the cluster vs outside the cluster", which can be useful in some enterprise deployment
scenarios.

### Egress gateways

Another approach to Kubernetes egress is to route all outbound connections via one or more egress gateways. The gateways
SNAT (Source Network Address Translation) the connections so the external service being connected to sees the connection
as coming from the egress gateway. The main use case is to improve security, either with the egress gateway performing a
direct security role in terms of what connections it allows, or in conjunction with perimeter firewalls (or other
external entities). For example, so that perimeter firewalls see the connections coming from well known IP
addresses (the egress gateways) rather than from dynamic pod IP addresses they don't understand.

Egress gateways are not a native concept in Kubernetes itself, but are implemented by some Kubernetes network
implementations and some service meshes. For example, Calico Enterprise provides egress gateway functionality, plus the
ability to map namespaces (or even individual pods) to specific egress gateways. Perimeter firewalls (or other external
security entities) can then effectively provide per namespace security controls, even though they do not have visibility
to dynamic pod IP addresses.

As an alternative approach to egress gateways, {{site.prodname}} allows you to control pod IP address ranges based on
namespace, or node, or even at the individual pod level. Assuming no outgoing NAT is required, this provides a very
simple way for perimeter firewalls (or other external security entities) to integrate with Kubernetes for both ingress
and egress traffic. (Note that this approach relies on having enough address space available to sensibly assign IP
address ranges, for example to each namespace, so it can lead to IP address range exhaustion challenges for large scale
deployments. In these scenarios, using egress gateways is likely to be a better option.)

### Above and beyond

- [Adopt a zero trust network model for security]({{site.baseurl}}/security/adopt-zero-trust)
- [Use external IPs or networks rules in policy]({{site.baseurl}}/security/external-ips-policy)
- [Enforce network policy using Istio]({{site.baseurl}}/security/app-layer-policy)
- [Use HTTP methods and paths in policy rules]({{site.baseurl}}/security/http-methods)
- [Restrict a pod to use an IP address in a specific range]({{site.baseurl}}/networking/legacy-firewalls)
- [Assign IP addresses based on topology]({{site.baseurl}}/networking/assign-ip-addresses-topology)
- {% include enterprise_icon.html %}[Advanced egress access controls]({{site.baseurl}}/security/calico-enterprise/egress-access-controls)


text:
package server

import (
	"time"

	. "github.com/pingcap/check"
	"github.com/pingcap/tidb"
)

type TidbTestSuite struct {
	tidbdrv *TiDBDriver
	server  *Server
}

var _ = Suite(new(TidbTestSuite))

func (ts *TidbTestSuite) SetUpSuite(c *C) {
	store, err := tidb.NewStore("memory:///tmp/tidb")
	c.Assert(err, IsNil)
	ts.tidbdrv = NewTiDBDriver(store)
	cfg := &Config{
		Addr:     ":4001",
		LogLevel: "debug",
	}
	server, err := NewServer(cfg, ts.tidbdrv)
	c.Assert(err, IsNil)
	ts.server = server
	go ts.server.Run()
	time.Sleep(time.Millisecond * 100)
}

func (ts *TidbTestSuite) TearDownSuite(c *C) {
	ts.server.Close()
}

func (ts *TidbTestSuite) TestRegression(c *C) {
	if regression {
		runTestRegression(c)
	}
}

func (ts *TidbTestSuite) TestUint64(c *C) {
	runTestPrepareResultFieldType(c)
}

func (ts *TidbTestSuite) TestSpecialType(c *C) {
	runTestSpecialType(c)
}

func (ts *TidbTestSuite) TestPreparedString(c *C) {
	runTestPreparedString(c)
}

func (ts *TidbTestSuite) TestConcurrentUpdate(c *C) {
	runTestConcurrentUpdate(c)
}

func (ts *TidbTestSuite) TestAuth(c *C) {
	runTestAuth(c)
}

func (ts *TidbTestSuite) TestIssues(c *C) {
	runTestIssues(c)
}


text:
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
	[ActionCategory(ActionCategory.Lights)]
	[Tooltip("Sets the Flare effect used by a Light.")]
	public class SetLightFlare : FsmStateAction
	{
		[RequiredField]
		[CheckForComponent(typeof(Light))]
		public FsmOwnerDefault gameObject;
		public Flare lightFlare;

		public override void Reset()
		{
			gameObject = null;
			lightFlare = null;
		}

		public override void OnEnter()
		{
			DoSetLightRange();
			Finish();
		}

		void DoSetLightRange()
		{
			GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);
			if (go == null) return;

			Light light = go.light;
			if (light == null)
			{
				LogError("Missing Light Component!");
				return;
			}

			light.flare = lightFlare;
		}
	}
}


text:
#ifndef CCB_NEB_HOST_GROUP_MEMBER_HH
#define CCB_NEB_HOST_GROUP_MEMBER_HH

#include "com/centreon/broker/io/event_info.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/mapping/entry.hh"
#include "com/centreon/broker/namespace.hh"
#include "com/centreon/broker/neb/group_member.hh"
#include "com/centreon/broker/neb/internal.hh"

CCB_BEGIN()

namespace neb {
/**
 *  @class host_group_member host_group_member.hh
 * "com/centreon/broker/neb/host_group_member.hh"
 *  @brief Member of a host group.
 *
 *  Base class defining that an host is part of a host group.
 *
 *  @see host
 *  @see host_group
 */
class host_group_member : public group_member {
 public:
  host_group_member();
  host_group_member(host_group_member const& other);
  virtual ~host_group_member();
  host_group_member& operator=(host_group_member const& other);
  constexpr static uint32_t static_type() {
    return io::events::data_type<io::events::neb,
                                 neb::de_host_group_member>::value;
  }

  static mapping::entry const entries[];
  static io::event_info::event_operations const operations;
};
}  // namespace neb

CCB_END()

#endif  // !CCB_NEB_HOST_GROUP_MEMBER_HH


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

<title>Uses of Class generics.AlreadyCarryingException</title>
<meta name="date" content="2016-09-20">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
generics.AlreadyCarryingException

Packages that use AlreadyCarryingException

Package
Description

generics

Uses of AlreadyCarryingException in generics

Methods in generics that throw AlreadyCarryingException

Modifier and Type
Method and Description

void
Collector.giveTo(Collector<? super T> collector)

Give to a object in collector to the other collector.

static void
Collector.main(java.lang.String[] args)

void
Collector.take(T object)

Take a object

void
CollectorTest.testcollectObjectExceptionTest()

void
CollectorTest.testcollectObjectTest()

void
CollectorTest.testObjectDropped()

void
CollectorTest.testObjectGiveToOtherCollection()

void
CollectorTest.testObjectRemoveAfterGive()

void
CollectorTest.testWithNoObjectCarried()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
var util = require('util');
var format = util.format;
var EventEmitter = require('events').EventEmitter;
var defaultListener = require('./defaultListener');
var version = '2.2.0';
var pattern = new RegExp(/^at (([^ ]+) )?(\(?([^:]+)*:([0-9]+)*:([0-9]+)*\)?)?$/g);
var slice = Array.prototype.slice;
var globalEventName = 'message';
var loglevels = ['log', 'info', 'warn', 'error'];
var proxies = ['dir', 'time', 'timeEnd', 'trace', 'assert'];
var times = {};
var emptyStack = {object:null, path:null, line:null, char:null};
var prevTime = {};

function parseStackLine(line) {
    var match, stack = [];
    while (match = pattern.exec(line)) {
        stack.push({ object:match[2] || null, path:match[4] || null, line:match[5] || null, char:match[6] || null });
    }
    return stack[0] || emptyStack;
}

function getTrace() {
    return parseStackLine(getTraceLine());
}

function getTraceLine() {
    var err = new Error;
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack.split("\n"), i = 0, l = stack.length, line;
    for (l; l > i; l--) {
        line = (stack[l] || "").trim();
        if (line.match(/\(\/|\\.+\)/)) return line;
    }
}

function getDiff(label) {
    var curr = new Date(),
        diff = curr - (prevTime[label] || curr);
    prevTime[label] = curr;
    return diff;
}

function Konsole(label) {
    EventEmitter.call(this);
    this._label = label || "";
    this._processType = (process.env.NODE_WORKER_ID ? 'worker' : 'master');
}
util.inherits(Konsole, EventEmitter);

loglevels.forEach(function (funcName) {
    Konsole.prototype[funcName] = function () {
        var args = slice.call(arguments) || [], level = funcName;
        this.emit(globalEventName, level, args);
        this.emit(level, args);
    }
});
proxies.forEach(function (funcName) {
    Konsole.prototype[funcName] = function () {
        return console[funcName].apply(console, arguments);
    }
});

Konsole.prototype.write = function () {
    process.stdout.write(format.apply(this, arguments) + '\n');
}
Konsole.prototype.format = function () {
    return format.apply(this, arguments);
}
Konsole.prototype.relay = function () {
    var that = this, origins = slice.call(arguments);
    origins.forEach(function (origin) {
        that.listeners(globalEventName).forEach(function (listener) {
            origin.on(globalEventName, listener);
        });
    });
}
Konsole.prototype.version = version;
Konsole.prototype.addDefaultListener = function () {
    this.on(globalEventName, defaultListener);
}
Konsole.prototype.__defineGetter__('trace', function () {
    return getTrace.call(this);
});
Konsole.prototype.__defineGetter__('diff', function () {
    return getDiff.apply(this, [this.label]);
});
Konsole.prototype.__defineGetter__('processType', function () {
    return this._processType;
});
Konsole.prototype.__defineGetter__('pid', function () {
    return process.pid;
});
Konsole.prototype.__defineGetter__('label', function () {
    return this._label || "";
});
Konsole.prototype.time = function (label) {
    times[label] = Date.now();
};
Konsole.prototype.timeEnd = function (label) {
    var duration = Date.now() - times[label];
    this.log('%s: %dms', label, duration);
};
module.exports = Konsole;


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var app = express();

////
// DATABASE
////
var db = monk('localhost:27017/kanban');

// interceptor / filter
app.use(function(req,res,next) {
    req.db = db;
    next();
});

////
// SETUP
////
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

////
// WEB ROUTES
////
var routes = require('./routes/w/families');
app.use('/w/families', routes);

routes = require('./routes/w/clients');
app.use('/w/clients', routes);

routes = require('./routes/w/projects');
app.use('/w/projects', routes);

routes = require('./routes/w/boards');
app.use('/w/boards', routes);

routes = require('./routes/w/columns');
app.use('/w/columns', routes);

routes = require('./routes/w/cards');
app.use('/w/cards', routes);

routes = require('./routes/w/comments');
app.use('/w/comments', routes);

////
// REST ROUTES
////
routes = require('./routes/columns');
app.use('/columns', routes);

routes = require('./routes/cards');
app.use('/cards', routes);

////
// CATCHALL ROUTES
////
routes = require('./routes/index');
app.use('/', routes);

////
// ERROR HANDLING
////

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
	// http://stackoverflow.com/questions/5276892/expressjs-how-to-output-pretty-html
	app.locals.pretty = true;
	// development error handler - will print stacktrace
	app.use(function(err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: err
		});
	});
}
else {
	// production error handler - no stacktraces leaked to user
	app.use(function(err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: {}
		});
	});
}

module.exports = app;


text:
"""
This module provides functionality that allows users to interact with container
filesystems (e.g., reading, writing, and deleting files).
"""
__all__ = ['FileManager']

import os
import logging
import tempfile

import chardet

from .bug import BugManager
from .container import ContainerManager
from ..core.container import Container

logger = logging.getLogger(__name__)  # type: logging.Logger
logger.setLevel(logging.DEBUG)

class FileManager(object):
    def __init__(self,
                 mgr_bug: BugManager,
                 mgr_ctr: ContainerManager
                 ) -> None:
        self.__mgr_bug = mgr_bug
        self.__mgr_ctr = mgr_ctr

    def _resolve_path(self, container: Container, filepath: str) -> str:
        """
        Ensures that relative paths are transformed into absolute paths.
        """
        bug = self.__mgr_bug[container.bug]
        filepath_orig = filepath

        if not os.path.isabs(filepath):
            filepath = os.path.join(bug.source_dir, filepath)
            logger.debug("converted relative path to absolute path: %s -> %s",
                         filepath_orig, filepath)

        return filepath

    def read(self, container: Container, filepath: str) -> str:
        """
        Reads the contents of a given file belonging to a container.
        """
        logger.debug("reading contents of file [%s] inside container [%s]",
                     filepath, container.id)
        filepath_orig = filepath
        filepath = self._resolve_path(container, filepath)

        # TODO what if the file doesn't exist?
        # TODO what if we encounter a permissions problem?

        # copy the contents the file to a temporary file on the host machine
        # TODO ensure correct permissions
        (_, fn_host) = tempfile.mkstemp(suffix='.bugzoo')
        try:
            # TODO we can probably move 'copy_from' to this manager
            self.__mgr_ctr.copy_from(container, filepath, fn_host)
            with open(fn_host, 'rb') as fh:
                blob = fh.read()
        finally:
            os.remove(fn_host)

        # detect encoding
        logger.debug("detecting encoding for file [%s] in container [%s]",
                     filepath_orig, container.id)
        chardet_res = chardet.detect(blob)
        encoding = chardet_res['encoding']
        confidence = chardet_res['confidence']
        logger.debug("detected encoding of file [%s] in container [%s]: %s (%.3f confidence)",  # noqa: pycodestyle
                     filepath_orig, container.id, encoding, confidence)

        # if no encoding is detected, return an empty file
        if encoding is None:
            return ''

        # decode file
        logger.debug("decoding file [%s] in container [%s]",
                     filepath_orig, container.id)
        try:
            contents = blob.decode(encoding)
        except UnicodeDecodeError:
            logger.exception("failed to decode contents of file [%s] in container [%s]",  # noqa: pycodestyle
                             filepath_orig, container.id)
            raise
        logger.debug("decoded file [%s] in container [%s]",
                     filepath_orig, container.id)

        logger.debug("read contents of file [%s] inside container [%s]",
                     filepath_orig, container.id)
        return contents

    def delete(self,
               container: Container,
               filepath: str,
               force: bool = False
               ) -> None:
        raise NotImplementedError

    def write(self,
              container: Container,
              filepath: str,
              contents: str
              ) -> str:
        """
        Reads the contents of a given file belonging to a container.
        """
        logger.debug("writing to file [%s] inside container [%s]",
                     filepath, container.id)
        filepath = self._resolve_path(container, filepath)

        # write the file contents to a temporary file on the host before
        # copying that file to the container
        (_, fn_host) = tempfile.mkstemp(suffix='.bugzoo')
        try:
            with open(fn_host, 'w') as fh:
                fh.write(contents)
            self.__mgr_ctr.copy_to(container, fn_host, filepath)
        finally:
            os.remove(fn_host)

        logger.debug("wrote to file [%s] inside container [%s]",
                     filepath, container.id)


text:
// Copyright 2015-2022 Bret Jordan, All rights reserved.
//
// Use of this source code is governed by an Apache 2.0 license that can be
// found in the LICENSE file in the root of the source tree.

package threatactor

import (
	"github.com/freetaxii/libstix2/objects"
)

// ----------------------------------------------------------------------
// Define Object Type
// ----------------------------------------------------------------------

/*
ThreatActor - This type implements the STIX 2 Threat Actor SDO and defines
all of the properties and methods needed to create and work with this object.
All of the methods not defined local to this type are inherited from the
individual properties.
*/
type ThreatActor struct {
	objects.CommonObjectProperties
	objects.NameProperty
	objects.DescriptionProperty
	ThreatActorTypes []string `json:"threat_actor_types,omitempty"`
	objects.AliasesProperty
	objects.SeenProperties
	objects.RolesProperty
	objects.GoalsProperty
	Sophistication string `json:"sophistication,omitempty"`
	objects.ResourceLevelProperty
	objects.MotivationProperties
	PersonalMotivations []string `json:"personal_motivations,omitempty"`
}

/*
GetPropertyList - This method will return a list of all of the properties that
are unique to this object. This is used by the custom UnmarshalJSON for this
object. It is defined here in this file to make it easy to keep in sync.
*/
func (o *ThreatActor) GetPropertyList() []string {
	return []string{"name", "description", "threat_actor_types", "aliases", "first_seen", "last_seen", "roles", "goals", "sophistication", "resource_level", "primary_motivation", "secondary_motivations", "personal_motivations"}
}

// ----------------------------------------------------------------------
// Initialization Functions
// ----------------------------------------------------------------------

/*
New - This function will create a new STIX Threat Actor object and return it
as a pointer. It will also initialize the object by setting all of the basic
properties.
*/
func New() *ThreatActor {
	var obj ThreatActor
	obj.InitSDO("threat-actor")
	return &obj
}


text:
import {Component, Input, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import { FormControl } from '@angular/forms';
import { takeWhile, skip, distinctUntilChanged, debounceTime } from 'rxjs/operators';

@Component({
  selector: 'ngd-theme-block',
  styleUrls: ['./theme-block.component.scss'],
  templateUrl: './theme-block.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NgdThemeComponent implements OnInit, OnDestroy {
  searchControl = new FormControl();

  private alive: boolean = true;

  properties = [];
  filtered = [];
  themeName = '';
  parentThemeName = '';

  @Input('block')
  set _block(block: any) {
    this.themeName = block.source.name;
    this.parentThemeName = block.source.parent;

    this.filtered = this.properties = Object.entries(block.source.data)
      .map(([key, data]: [string, any]) => {
        const propertyValue = data.value;
        return {
          name: key,
          value: Array.isArray(propertyValue) ? propertyValue.join(' ') : propertyValue,
          parents: data.parents,
        };
    });
  }

  constructor(private cd: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(skip(1), distinctUntilChanged(), debounceTime(300), takeWhile(() => this.alive))
      .subscribe((value: string) => {
        this.filtered = this.properties
          .filter(({ name }) => name.toLowerCase().includes(value.toLowerCase()));
        this.cd.detectChanges();
      });
  }

  trackByFn(index, item) {
    return item.name;
  }

  ngOnDestroy() {
    this.alive = false;
  }
}


text:
package io.rong.app.activity;

import android.os.Bundle;

/**
 * Created by Bob on 15/6/18.
 */
public class RongCloudActivtiy extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

}


text:
import subprocess
import shlex

from tests import DEBUG

def call_process(cmd):
    try:
        from subprocess import DEVNULL
    except ImportError:
        import os
        DEVNULL = open(os.devnull, 'wb')
    if DEBUG:
        out = None
        close_fds = False
    else:
        out = DEVNULL
        close_fds = True

    args = shlex.split(cmd)
    return subprocess.call(args, stdout=out, stderr=out, close_fds=close_fds)


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.mfreitas.twister"
      android:versionCode="46"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".twisterActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation"
                  android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>


text:
package pojos;

import java.util.ArrayList;

public class LectureDashboard {

		private Course course;
		private int lectureID;
		private ArrayList<Announcement> announcements;
		private int enrolledStudentCount = 0;
		private int gradeCount = 0;

		public LectureDashboard(Course course, int lectureID, ArrayList<Announcement> anouncments, int enrolledStudentCount, int gradeCount) {
			this.course = course;
			this.lectureID = lectureID;
			this.announcements = anouncments;
			this.enrolledStudentCount = enrolledStudentCount;
			this.gradeCount = gradeCount;
		}

		public int getLectureID() {
			return lectureID;
		}
		public ArrayList<Announcement> getAnnouncements() {
			return announcements;
		}
		public int getEnrolledStudentCount() {
			return enrolledStudentCount;
		}
		public int getGradeCount() {
			return gradeCount;
		}

		public Course getCourse() {
			return course;
		}

}


text:
describe('Options -> Preferences', function () {
  const urlInvalid = 's://test'
  const messageInvalid = '"missingLeadingBracket": true}'

  beforeEach(() => {
    cy.mockChromeStorageAndVisit('/#options')
    cy.get('#optionsPreferencesAnchor').click()
    cy.get('#optionsPreferences').should('be.visible')
  })

  it('clicking "i" icon should show and hide popover', function() {
    // Prevent Saving Invalid URL
    cy.log('Prevent Saving Invalid URL')
    cy.get('[data-test=popover-save-url]').click()
    cy.get('[data-title="Prevent Saving Invalid URL"]').should('have.attr', 'aria-describedby')
    cy.get('[data-test=popover-save-url]').click()
    cy.get('[data-title="Prevent Saving Invalid URL"]').should('not.have.attr', 'aria-describedby')

    // Prevent Using Invalid URL
    cy.log('Prevent Using Invalid URL')
    cy.get('[data-test=popover-use-url]').click()
    cy.get('[data-title="Prevent Using Invalid URL"]').should('have.attr', 'aria-describedby')
    cy.get('[data-test=popover-use-url]').click()
    cy.get('[data-title="Prevent Using Invalid URL"]').should('not.have.attr', 'aria-describedby')

    // Prevent Saving Message Body with Invalid JSON
    cy.log('Prevent Saving Message Body with Invalid JSON')
    cy.get('[data-test=popover-save-message]').click()
    cy.get('[data-title="Prevent Saving Message Body with Invalid JSON"]').should('have.attr', 'aria-describedby')
    cy.get('[data-test=popover-save-message]').click()
    cy.get('[data-title="Prevent Saving Message Body with Invalid JSON"]').should('not.have.attr', 'aria-describedby')

    // Prevent Using Message Body with Invalid JSON
    cy.log('Prevent Using Message Body with Invalid JSON')
    cy.get('[data-test=popover-use-message]').click()
    cy.get('[data-title="Prevent Using Message Body with Invalid JSON"]').should('have.attr', 'aria-describedby')
    cy.get('[data-test=popover-use-message]').click()
    cy.get('[data-title="Prevent Using Message Body with Invalid JSON"]').should('not.have.attr', 'aria-describedby')
  })

  it('prevent saving an invalid URL in the Options section', function () {
    cy.get('#preferencesOptionsUrlCheckbox').then((checkbox) => {
      if (!checkbox.prop('checked')) {
        cy.get('#preferencesOptionsUrlSlider').click()
      }
    })
    cy.get('#preferencesOptionsUrlCheckbox').should('be.checked')
    cy.get('#optionsUrlsAnchor').click()
    cy.get('#optionsUrlsAnchor').click()
    cy.get('#optionsUrls').should('be.visible')
    cy.get('#optionsUrlInput')
      .clear()
      .type(urlInvalid)
    cy.fixture('optionsDefaults').then((input) => {
      input.optionsUrlInputValue = urlInvalid
      input.optionsUrlInvalidWarningVisible = ''
      input.optionsUrlSaveButtonDisabled = ''
      cy.checkOptionsUrls(input)
    })
  })

  it('allow saving an invalid URL in the Options section', function () {
    cy.get('#preferencesOptionsUrlCheckbox').then((checkbox) => {
      if (checkbox.prop('checked')) {
        cy.get('#preferencesOptionsUrlSlider').click()
      }
    })
    cy.get('#preferencesOptionsUrlCheckbox').should('not.be.checked')
    cy.get('#optionsUrlsAnchor').click()
    cy.get('#optionsUrlsAnchor').click()
    cy.get('#optionsUrls').should('be.visible')
    cy.get('#optionsUrlInput')
      .clear()
      .type(urlInvalid)
    cy.fixture('optionsDefaults').then((input) => {
      input.optionsUrlInputValue = urlInvalid
      input.optionsUrlInvalidWarningVisible = ''
      input.optionsUrlSaveButtonDisabled = 'not.'
      cy.checkOptionsUrls(input)
    })
  })

  it('prevent saving an invalid message body in the Options section', function () {
    const name = 'name'
    cy.get('#preferencesOptionsMessageCheckbox').then((checkbox) => {
      if (!checkbox.prop('checked')) {
        cy.get('#preferencesOptionsMessageSlider').click()
      }
    })
    cy.get('#preferencesOptionsMessageCheckbox').should('be.checked')
    cy.get('#optionsMessagesAnchor').click()
    cy.get('#optionsMessagesAnchor').click()
    cy.get('#optionsMessages').should('be.visible')
    cy.get('#optionsMessageNameInput')
      .clear()
      .type(name)
    cy.get('#optionsMessageTextarea')
      .clear()
      .type(messageInvalid)
    cy.fixture('optionsDefaults').then((input) => {
      input.optionsMessageNameInputValue = name
      input.optionsMessageTextareaValue = messageInvalid
      input.optionsMessageJsonInvalidWarningVisible = ''
      input.optionsMessageSaveButtonDisabled = ''
      cy.checkOptionsMessages(input)
    })
  })

  it('allow saving an invalid message body in the Options section', function () {
    const name = 'name'
    cy.get('#preferencesOptionsMessageCheckbox').then((checkbox) => {
      if (checkbox.prop('checked')) {
        cy.get('#preferencesOptionsMessageSlider').click()
      }
    })
    cy.get('#preferencesOptionsMessageCheckbox').should('not.be.checked')
    cy.get('#optionsMessagesAnchor').click()
    cy.get('#optionsMessagesAnchor').click()
    cy.get('#optionsMessages').should('be.visible')
    cy.get('#optionsMessageNameInput')
      .clear()
      .type(name)
    cy.get('#optionsMessageTextarea')
      .clear()
      .type(messageInvalid)
    cy.fixture('optionsDefaults').then((input) => {
      input.optionsMessageNameInputValue = name
      input.optionsMessageTextareaValue = messageInvalid
      input.optionsMessageJsonInvalidWarningVisible = ''
      input.optionsMessageSaveButtonDisabled = 'not.'
      cy.checkOptionsMessages(input)
    })
  })

  it('prevent using an invalid URL in the Client section', function () {
    cy.get('#preferencesClientUrlCheckbox').then((checkbox) => {
      if (!checkbox.prop('checked')) {
        cy.get('#preferencesClientUrlSlider').click()
      }
    })
    cy.get('#preferencesClientUrlCheckbox').should('be.checked')
    cy.get('#clientAnchor').click()
    cy.get('#clientAnchor').click()
    cy.get('#client').should('be.visible')
    cy.get('#urlInput')
      .clear()
      .type(urlInvalid)
    cy.fixture('clientDefaults').then((input) => {
      input.urlInputValue = urlInvalid
      input.urlInvalidWarningVisible = ''
      input.connectButtonDisabled = ''
      cy.checkClient(input)
    })
  })

  it('allow using an invalid URL in the Client section', function () {
    cy.get('#preferencesClientUrlCheckbox').then((checkbox) => {
      if (checkbox.prop('checked')) {
        cy.get('#preferencesClientUrlSlider').click()
      }
    })
    cy.get('#preferencesClientUrlCheckbox').should('not.be.checked')
    cy.get('#clientAnchor').click()
    cy.get('#clientAnchor').click()
    cy.get('#client').should('be.visible')
    cy.get('#urlInput')
      .clear()
      .type(urlInvalid)
    cy.fixture('clientDefaults').then((input) => {
      input.urlInputValue = urlInvalid
      input.urlInvalidWarningVisible = ''
      input.connectButtonDisabled = 'not.'
      cy.checkClient(input)
    })
  })

  it('prevent using an invalid message body in the Client section', function () {
    cy.get('#preferencesClientMessageCheckbox').then((checkbox) => {
      if (!checkbox.prop('checked')) {
        cy.get('#preferencesClientMessageSlider').click()
      }
    })
    cy.get('#preferencesClientMessageCheckbox').should('be.checked')
    cy.get('#clientAnchor').click()
    cy.get('#clientAnchor').click()
    cy.get('#client').should('be.visible')
    cy.get('#messageTextarea')
      .clear()
      .type(messageInvalid)
    cy.fixture('clientDefaults').then((input) => {
      input.messageTextareaValue = messageInvalid
      input.messageJsonInvalidWarningVisible = ''
      input.messageSendButtonDisabled = ''
      cy.checkClient(input)
    })
  })

  it('allow using an invalid message body in the Client section', function () {
    cy.get('#preferencesClientMessageCheckbox').then((checkbox) => {
      if (checkbox.prop('checked')) {
        cy.get('#preferencesClientMessageSlider').click()
      }
    })
    cy.get('#preferencesClientMessageCheckbox').should('not.be.checked')
    cy.get('#clientAnchor').click()
    cy.get('#clientAnchor').click()
    cy.get('#client').should('be.visible')
    cy.get('#messageTextarea')
      .clear()
      .type(messageInvalid)
    cy.fixture('clientDefaults').then((input) => {
      input.messageTextareaValue = messageInvalid
      input.messageJsonInvalidWarningVisible = ''
      input.messageSendButtonDisabled = 'not.'
      cy.checkClient(input)
    })
  })
})


text:
namespace {

#define SEPARATOR "======== output separator ========"

const char kAllCommands[] = "shell:"
    "getprop ro.product.model\n"
    "echo " SEPARATOR "\n"
    "dumpsys window policy\n"
    "echo " SEPARATOR "\n"
    "ps\n"
    "echo " SEPARATOR "\n"
    "cat /proc/net/unix\n"
    "echo " SEPARATOR "\n"
    "dumpsys user\n";

const char kSeparator[] = SEPARATOR;

#undef SEPARATOR

const char kScreenSizePrefix[] = "mStable=";
const char kUserInfoPrefix[] = "UserInfo{";

const char kDevToolsSocketSuffix[] = "_devtools_remote";

const char kChromeDefaultName[] = "Chrome";
const char kChromeDefaultSocket[] = "chrome_devtools_remote";

const char kWebViewSocketPrefix[] = "webview_devtools_remote";
const char kWebViewNameTemplate[] = "WebView in %s";

struct BrowserDescriptor {
  const char* package;
  const char* socket;
  const char* display_name;
};

const BrowserDescriptor kBrowserDescriptors[] = {
  {
    "com.google.android.apps.chrome",
    kChromeDefaultSocket,
    "Chromium"
  },
  {
    "com.chrome.canary",
    kChromeDefaultSocket,
    "Chrome Canary"
  },
  {
    "com.chrome.dev",
    kChromeDefaultSocket,
    "Chrome Dev"
  },
  {
    "com.chrome.beta",
    kChromeDefaultSocket,
    "Chrome Beta"
  },
  {
    "com.android.chrome",
    kChromeDefaultSocket,
    kChromeDefaultName
  },
  {
    "com.chrome.work",
    kChromeDefaultSocket,
    "Work Chrome"
  },
  {
    "org.chromium.android_webview.shell",
    "webview_devtools_remote",
    "WebView Test Shell"
  },
  {
    "org.chromium.content_shell_apk",
    "content_shell_devtools_remote",
    "Content Shell"
  },
  {
    "org.chromium.chrome",
    kChromeDefaultSocket,
    "Chromium"
  },
};

const BrowserDescriptor* FindBrowserDescriptor(const std::string& package) {
  size_t count = arraysize(kBrowserDescriptors);
  for (size_t i = 0; i < count; i++) {
    if (kBrowserDescriptors[i].package == package)
      return &kBrowserDescriptors[i];
  }
  return nullptr;
}

bool BrowserCompare(const AndroidDeviceManager::BrowserInfo& a,
                    const AndroidDeviceManager::BrowserInfo& b) {
  size_t count = arraysize(kBrowserDescriptors);
  for (size_t i = 0; i < count; i++) {
    bool isA = kBrowserDescriptors[i].display_name == a.display_name;
    bool isB = kBrowserDescriptors[i].display_name == b.display_name;
    if (isA != isB)
      return isA;
    if (isA && isB)
      break;
  }
  return a.socket_name < b.socket_name;
}

using StringMap = std::map<std::string, std::string>;

void MapProcessesToPackages(const std::string& response,
                            StringMap* pid_to_package,
                            StringMap* pid_to_user) {
  // Parse 'ps' output which on Android looks like this:
  //
  // USER PID PPID VSIZE RSS WCHAN PC ? NAME
  //
  for (const base::StringPiece& line :
       base::SplitStringPiece(response, "\n", base::KEEP_WHITESPACE,
                              base::SPLIT_WANT_NONEMPTY)) {
    std::vector<std::string> fields =
        base::SplitString(line, " \r", base::KEEP_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);
    if (fields.size() < 9)
      continue;
    std::string pid = fields[1];
    (*pid_to_package)[pid] = fields[8];
    (*pid_to_user)[pid] = fields[0];
  }
}

StringMap MapSocketsToProcesses(const std::string& response) {
  // Parse 'cat /proc/net/unix' output which on Android looks like this:
  //
  // Num       RefCount Protocol Flags    Type St Inode Path
  // 00000000: 00000002 00000000 00010000 0001 01 331813 /dev/socket/zygote
  // 00000000: 00000002 00000000 00010000 0001 01 358606 @xxx_devtools_remote
  // 00000000: 00000002 00000000 00010000 0001 01 347300 @yyy_devtools_remote
  //
  // We need to find records with paths starting from '@' (abstract socket)
  // and containing the channel pattern ("_devtools_remote").
  StringMap socket_to_pid;
  for (const base::StringPiece& line :
       base::SplitStringPiece(response, "\n", base::KEEP_WHITESPACE,
                              base::SPLIT_WANT_NONEMPTY)) {
    std::vector<std::string> fields =
        base::SplitString(line, " \r", base::KEEP_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);
    if (fields.size() < 8)
      continue;
    if (fields[3] != "00010000" || fields[5] != "01")
      continue;
    std::string path_field = fields[7];
    if (path_field.size() < 1 || path_field[0] != '@')
      continue;
    size_t socket_name_pos = path_field.find(kDevToolsSocketSuffix);
    if (socket_name_pos == std::string::npos)
      continue;

    std::string socket = path_field.substr(1);

    std::string pid;
    size_t socket_name_end = socket_name_pos + strlen(kDevToolsSocketSuffix);
    if (socket_name_end < path_field.size() &&
        path_field[socket_name_end] == '_') {
      pid = path_field.substr(socket_name_end + 1);
    }
    socket_to_pid[socket] = pid;
  }
  return socket_to_pid;
}

gfx::Size ParseScreenSize(base::StringPiece str) {
  std::vector<base::StringPiece> pairs =
      base::SplitStringPiece(str, "-", base::KEEP_WHITESPACE,
                             base::SPLIT_WANT_NONEMPTY);
  if (pairs.size() != 2)
    return gfx::Size();

  int width;
  int height;
  std::vector<base::StringPiece> numbers =
      base::SplitStringPiece(pairs[1].substr(1, pairs[1].size() - 2), ",",
                             base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  if (numbers.size() != 2 ||
      !base::StringToInt(numbers[0], &width) ||
      !base::StringToInt(numbers[1], &height))
    return gfx::Size();

  return gfx::Size(width, height);
}

gfx::Size ParseWindowPolicyResponse(const std::string& response) {
  for (const base::StringPiece& line :
      base::SplitStringPiece(response, "\r", base::KEEP_WHITESPACE,
                             base::SPLIT_WANT_NONEMPTY)) {
    size_t pos = line.find(kScreenSizePrefix);
    if (pos != base::StringPiece::npos) {
      return ParseScreenSize(
          line.substr(pos + strlen(kScreenSizePrefix)));
    }
  }
  return gfx::Size();
}

StringMap MapIdsToUsers(const std::string& response) {
  // Parse 'dumpsys user' output which looks like this:
  // Users:
  //   UserInfo{0:Test User:13} serialNo=0
  //     Created: <unknown>
  //     Last logged in: +17m18s871ms ago
  //   UserInfo{10:User with : (colon):10} serialNo=10
  //     Created: +3d4h35m1s139ms ago
  //     Last logged in: +17m26s287ms ago
  StringMap id_to_username;
  for (const base::StringPiece& line :
       base::SplitStringPiece(response, "\r", base::KEEP_WHITESPACE,
                              base::SPLIT_WANT_NONEMPTY)) {
    size_t pos = line.find(kUserInfoPrefix);
    if (pos != std::string::npos) {
      base::StringPiece fields = line.substr(pos + strlen(kUserInfoPrefix));
      size_t first_pos = fields.find_first_of(":");
      size_t last_pos = fields.find_last_of(":");
      if (first_pos != std::string::npos && last_pos != std::string::npos) {
        std::string id = fields.substr(0, first_pos).as_string();
        std::string name = fields.substr(first_pos + 1,
                                         last_pos - first_pos - 1).as_string();
        id_to_username[id] = name;
      }
    }
  }
  return id_to_username;
}

std::string GetUserName(const std::string& unix_user,
                        const StringMap id_to_username) {
  // Parse username as returned by ps which looks like 'u0_a31'
  // where '0' is user id and '31' is app id.
  if (!unix_user.empty() && unix_user[0] == 'u') {
    size_t pos = unix_user.find('_');
    if (pos != std::string::npos) {
      StringMap::const_iterator it =
          id_to_username.find(unix_user.substr(1, pos - 1));
      if (it != id_to_username.end())
        return it->second;
    }
  }
  return std::string();
}

AndroidDeviceManager::BrowserInfo::Type
GetBrowserType(const std::string& socket) {
  if (socket.find(kChromeDefaultSocket) == 0)
    return AndroidDeviceManager::BrowserInfo::kTypeChrome;

  if (socket.find(kWebViewSocketPrefix) == 0)
    return AndroidDeviceManager::BrowserInfo::kTypeWebView;

  return AndroidDeviceManager::BrowserInfo::kTypeOther;
}

void ReceivedResponse(const AndroidDeviceManager::DeviceInfoCallback& callback,
                      int result,
                      const std::string& response) {
  AndroidDeviceManager::DeviceInfo device_info;
  if (result < 0) {
    callback.Run(device_info);
    return;
  }
  std::vector<std::string> outputs;
  base::SplitStringUsingSubstr(response, kSeparator, &outputs);
  if (outputs.size() != 5) {
    callback.Run(device_info);
    return;
  }
  device_info.connected = true;
  device_info.model = outputs[0];
  device_info.screen_size = ParseWindowPolicyResponse(outputs[1]);
  StringMap pid_to_package;
  StringMap pid_to_user;
  MapProcessesToPackages(outputs[2], &pid_to_package, &pid_to_user);
  StringMap socket_to_pid = MapSocketsToProcesses(outputs[3]);
  StringMap id_to_username = MapIdsToUsers(outputs[4]);
  std::set<std::string> used_pids;
  for (const auto& pair : socket_to_pid)
    used_pids.insert(pair.second);

  for (const auto& pair : pid_to_package) {
    std::string pid = pair.first;
    std::string package = pair.second;
    if (used_pids.find(pid) == used_pids.end()) {
      const BrowserDescriptor* descriptor = FindBrowserDescriptor(package);
      if (descriptor)
        socket_to_pid[descriptor->socket] = pid;
    }
  }

  for (const auto& pair : socket_to_pid) {
    std::string socket = pair.first;
    std::string pid = pair.second;
    std::string package;
    StringMap::iterator pit = pid_to_package.find(pid);
    if (pit != pid_to_package.end())
      package = pit->second;

    AndroidDeviceManager::BrowserInfo browser_info;
    browser_info.socket_name = socket;
    browser_info.type = GetBrowserType(socket);
    browser_info.display_name =
        AndroidDeviceManager::GetBrowserName(socket, package);

    StringMap::iterator uit = pid_to_user.find(pid);
    if (uit != pid_to_user.end())
      browser_info.user = GetUserName(uit->second, id_to_username);

    device_info.browser_info.push_back(browser_info);
  }
  std::sort(device_info.browser_info.begin(),
            device_info.browser_info.end(),
            &BrowserCompare);
  callback.Run(device_info);
}

}  // namespace

// static
std::string AndroidDeviceManager::GetBrowserName(const std::string& socket,
                                                 const std::string& package) {
  if (package.empty()) {
    // Derive a fallback display name from the socket name.
    std::string name = socket.substr(0, socket.find(kDevToolsSocketSuffix));
    name[0] = base::ToUpperASCII(name[0]);
    return name;
  }

  const BrowserDescriptor* descriptor = FindBrowserDescriptor(package);
  if (descriptor)
    return descriptor->display_name;

  if (GetBrowserType(socket) ==
      AndroidDeviceManager::BrowserInfo::kTypeWebView)
    return base::StringPrintf(kWebViewNameTemplate, package.c_str());

  return package;
}

// static
void AndroidDeviceManager::QueryDeviceInfo(
    const RunCommandCallback& command_callback,
    const DeviceInfoCallback& callback) {
  command_callback.Run(
      kAllCommands,
      base::Bind(&ReceivedResponse, callback));
}


text:
require 'spec_helper'
require 'periods/constants'
require 'initialized_by_single_date'

describe HalfyearlyPeriod do

  let(:subject) { described_class.for("1.1.2015") }

  it_behaves_like "Initialized by single date" do
    let(:period) { described_class.for(Date.new(2015,6,25)) }
  end

  describe "#next" do
    it "returns next period" do
      expect(described_class.for('25.06.2015').next).to eq described_class.for('25.12.2015')
      expect(described_class.for('01.07.2015').next).to eq described_class.for('01.01.2016')
    end
  end

  describe "#previous" do
    it "returns previous period" do
      expect(described_class.for('25.06.2015').previous).to eq described_class.for('25.12.2014')
      expect(described_class.for('01.07.2015').previous).to eq described_class.for('01.01.2015')
    end
  end

  describe "#days" do
    it "returns days of period" do
      expect(described_class.for("01.01.2015").days).to eq 181
      expect(described_class.for("25.06.2015").days).to eq 183
      expect(described_class.for("01.01.2016").days).to eq 182
      expect(described_class.for("01.03.2016").days).to eq 184
    end
  end

  describe "#include?" do
    let(:period) { described_class.for('25.06.2015') }

    context "date included" do
      it "returns true" do
        expect(period.include?('25.06.2015')).to be_truthy
        expect(period.include?('24.12.2015')).to be_truthy
      end
    end

    context "date not included" do
      it "returns false" do
        expect(period.include?('24.06.2015')).to be_falsey
        expect(period.include?('25.12.2015')).to be_falsey
      end
    end

    context "period included" do
      it "returns true" do
        expect(period.include?(Period.new('25.06.2015', '24.12.2015'))).to be_truthy
        expect(period.include?(Period.new('26.06.2015', '24.12.2015'))).to be_truthy
        expect(period.include?(Period.new('25.06.2015', '23.12.2015'))).to be_truthy
      end
    end

    context "period not included" do
      it "returns false" do
        expect(period.include?(Period.new('24.06.2015', '24.12.2015'))).to be_falsey
        expect(period.include?(Period.new('25.06.2015', '25.12.2015'))).to be_falsey
      end
    end
  end
end


text:
@font-face {
  font-family: 'IM Fell English SC';
  font-style: normal;
  font-weight: 400;
  src: local('IM FELL English SC'), local('IM_FELL_English_SC'), url(http://themes.googleusercontent.com/static/fonts/imfellenglishsc/v3/h3Tn6yWfw4b5qaLD1RWvz9gX5f6-V0DImePmAcKHNfQ.ttf) format('truetype');
}

h1, h2, h3 {
   font-family: 'IM Fell English SC', serif;
}

/* Inputs */
.charsheet label {
    display: inline-block;
    width: 75px;
    text-align: right;
    padding-bottom: 2px;
    margin-top: 14px;
    margin-left: 20px;
}

.charsheet input {
    display: inline-block;
    width: 155px;
    margin-bottom: 2px;
}

.charsheet {
    background-color: white;
}

.charsheet select {
    width: 42px;
}

select {
    margin-bottom: 2px;
}

span.sheet-skill-name {
    font-size: 14px;
    font-weight: bold;
    line-height: 29px;
}

span.sheet-background {
    font-size: 14px;
    font-weight: bold;
    line-height: 29px;
    display: block;
}

span.sheet-skill-panel {
    font-size: 14px;
    font-weight: bold;
    line-height: 32px;
    color:#787878;
}

span.sheet-skill-combat {
    font-size: 14px;
    font-weight: bold;
    line-height: 26px;
}

div.sheet-row { margin-bottom: 2px; }

/*Checkboxes*/
input[type="checkbox"]
{
    position: left;
    opacity: 100;
    width:15px;
    cursor: pointer;
    z-index: 1;
    margin-top: -1px;
}

/*Sheet Tabs*/
div.sheet-tab-content { display: none; }

input.sheet-tab1:checked ~ div.sheet-tab1,
input.sheet-tab2:checked ~ div.sheet-tab2,
input.sheet-tab3:checked ~ div.sheet-tab3,
input.sheet-tab4:checked ~ div.sheet-tab4,
input.sheet-tab5:checked ~ div.sheet-tab5,
input.sheet-tab6:checked ~ div.sheet-tab6 {
    display: block;
}

input.sheet-tab
{
    width: 121px;
    height: 20px;
    position: relative;
    top: 5px;
    margin: 4px;
    cursor: pointer;
    z-index: 1;
    font-family: 'IM Fell English SC', serif;
}

input.sheet-tab::before
{
    content: attr(title);
    border: solid 2px #E8E8E8;
    text-align: center;
    display: inline-block;
    background: #FFFFFF;
    width: 121px;
    height: 20px;
    font-size: 14px;
    font-weight: bold;
}

input.sheet-tab:checked::before
{
    background: #dcdcdc;
    background: -moz-linear-gradient(to top, #fcfcfc, #F0F0F0, #fcfcfc);
    background: -webkit-linear-gradient(to top, #fcfcfc, #F0F0F0, #fcfcfc);
    background: -ms-linear-gradient(to top, #fcfcfc, #F0F0F0, #fcfcfc);
    background: -o-linear-gradient(to top, #fcfcfc, #F0F0F0, #fcfcfc);
    background: linear-gradient(to top, #fcfcfc, #F0F0F0, #fcfcfc);
    border-color: #C0C0C0;
}

div.sheet-tab-content
{
    border: 0px solid #a8a8a8;
    border-top-color: #000;
    margin: 2px 0 0 5px;
    padding: 5px;
}
/*end Sheet Tabs*/

/*Hiding Sections*/
.charsheet .sheet-togglepanel {
    width: 95%;
    vertical-align:top;
    border: 1px
    solid black;
    background-color:#F0F0F0;
    padding-top: 6px;
    padding-bottom: 2px;
    padding-left: 6px;
    padding-right: 6px;
}

input.sheet-arrow {
    margin-top: 3px;
    float: left;
}

div.sheet-togglepanel {
    display: none;
}

input.sheet-arrow:checked ~ div.sheet-togglepanel {
    display: block;
}

.sheet-newtoggel {
    border-left: 4px solid;
    color:#787878;
    padding: 8px 8px 8px 8px;
    background: #F0F0F0;
    width: 95%;
    vertical-align: top;
}

.sheet-details-togglepanel {
    text-align: justify;
    text-justify: inter-word;
    display: none;
}

input.sheet-arrow:checked ~ .sheet-details-togglepanel { display: block; }
/*end Hiding Sections*/


text:
Test for timecop_strtotime
--SKIPIF--
<?php
$required_func = array("timecop_freeze", "timecop_strtotime");
include(__DIR__."/tests-skipcheck.inc.php");
--INI--
date.timezone=America/Los_Angeles
timecop.func_override=0
--FILE--
<?php
timecop_freeze(new DateTime("2012-02-29"));
var_dump(date("Y-m-d", timecop_strtotime("+1 month")));
--EXPECT--
string(10) "2012-03-29"


text:
var Schema = {
  update: function(request) {

  },
  _version: function(request) {
    // console.log(`[schema.js][_version] parameter:`, request);
    if (typeof request['requestUrl'] == 'string'
      && typeof request['requestMethod'] == 'string'
      && typeof request['requestBody'] == 'string')
    {
      return "v1001";
    }
    if (request.version && request.version == 1 && request.data)
    {
      return 'v3' + ('' + request.version).padStart(3, "0");
    }
    if(typeof request == 'object' && !request.version)
    {
      for(let key in request)
      {
        if (typeof request[key]['method'] != 'undefined'
            && typeof request[key]['url'] != 'undefined'
            && typeof request[key]['body'] != 'undefined' )
        {
          return "v2001";
        }
      }
    }
    return "unkown";
  },
  _v1001: function(data, tags) {
    var request = {
      "method": data.requestMethod,
      "url": data.requestUrl,
      "body": data.requestBody,
      "tags": Array.isArray(tags) ? tags : [],
      "created_at": new Date(),
      "updated_at": new Date(),
    };

    if (Array.isArray(data.headers))
    {
      var headers = [];
      for (var i = 0; i < data.headers.length; i = i + 2) {
        headers.push({ "name": data.headers[i], "value": data.headers[i + 1] });
      }
      request.headers = headers;
    }
    return request;
  },
  _v2001: function(request, tags) {
    var tags = Array.isArray(tags) ? tags : [];
    request.tags = Array.isArray(request.tags) ? [...new Set([...request.tags, ...tags])] : tags;
    if (typeof request.overrideMimeType != 'undefined') {
      delete request.overrideMimeType;
    }
    // console.log(`[schema.js][_v2001]: processing request.`, request);
    if (request.headers) {
      if (request.headers.length > 0) {
        var headers = [];
        for(let i = 0; i < request.headers.length; i++)
        {
          var header  = request.headers[i];
          var name = value = '';
          if (Array.isArray(header))
          {
            name = header[0];
            value = header[1];
          }
          else
          {
            name = header['name'];
            value = header['value'];
          }
          // basic authentication
          if(name.toLowerCase() == 'authorization' && value.toLowerCase().indexOf('basic ') == 0)
          {
            var credentials = header[1].substr(6);
            // console.log(`[schema.js][_v2001]: credentials.`, credentials);
            credentials = Base64.decode(credentials);
            // console.log(`[schema.js][_v2001]: credentials.`, credentials);
            var username = credentials.substr(0, credentials.indexOf(':'));
            var password = credentials.substr(credentials.indexOf(':') + 1);
            request.authentication = {
              'mode': 'basic',
              'data': {
                'username': username,
                'password': password
              }
            };
            continue;
            // console.log(`[schema.js][_v2001]: authentication.`, request);
          }

          // oauth authentication
          if (request.oauth && name.toLowerCase() == 'authorization' && value.toLowerCase().indexOf('oauth ') == 0)
          {
            continue;
          }

          // oauth2 authentication
          if (request.oauth2 && name.toLowerCase() == 'authorization' && value.toLowerCase().indexOf('oauth2 ') == 0) {
            continue;
          }

          headers.push({ "name": name, "value": value });
        }
        request.headers = headers;
      }
      else {
        delete request.headers;
      }
    }

    // if the request uses OAuth 1.0 authentication
    if(request.oauth)
    {
      var authentication = {'mode': 'oauth10'};
      var secrets = request.oauth.oauth_secrets;
      secrets = JSON.parse(secrets);
      var data = {};
      data['consumer_key'] = secrets.consumer_key;
      data['shared_secret'] = secrets.consumer_secret;
      data['access_token'] = secrets.access_token;
      data['access_secret'] = secrets.access_secret;
      var params = request.oauth.oauth_parameters;
      params = JSON.parse(params);
      data['oauth_version'] = params.oauth_version;
      data['oauth_signature_method'] = params.params;
      data['oauth_nonce'] = true;
      data['oauth_timestamp'] = true;
      data['parameter_transmission'] = "header";
      data['auto_refresh'] = request.oauth.auto_refresh == 'no' ? false : true;
      authentication.data = data;
      request.authentication = authentication;
      delete request.oauth;
      // TODO remove authorization header
    }

    // if the request uses OAuth 2.0 authentication
    if (request.oauth2) {
      var authentication = { 'mode': 'oauth20' };
      var authorize = request.oauth2.authorize;
      var data = {};
      data['client_id'] = authorize.client_id;
      data['client_secret'] = authorize.client_secret;
      data['grant_type'] = authorize.response_type == 'code' ? 'authorization_code' : 'client_credentials';
      data['request_method'] = authorize.token_method ? authorize.token_method.toLowerCase() : 'post';
      data['authorization_endpoint'] = authorize.authorization_endpoint;
      data['redirect_endpoint'] = authorize.redirection_endpoint;
      data['token_endpoint'] = authorize.token_endpoint;
      data['scope'] = authorize.scope;
      data['state'] = authorize.state == '' ? true : '';
      if (request.oauth2.tokens)
      {
        var tokens = request.oauth2.tokens;
        data.result = {};
        data.result['access_token'] = tokens.access_token;
        data.result['refresh_token'] = tokens.refresh_token;
        data.result['expires_in'] = 3600;
        data.result['timestamp'] = 1515554247;
        data.result['token_type'] = 'Bearer';
      }
      authentication.data = data;
      request.authentication = authentication;
      delete request.oauth2;
    }
    request.created_at = new Date();
    request.updated_at = new Date();
    return request;
  },
  _v3001: function(request, tags)
  {
    return this._v2001(request, tags);
  }
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = Schema;
}
else {
  if (typeof define === 'function' && define.amd) {
    define([], function () {
      return Schema;
    });
  }
  else {
    window.Schema = Schema;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace vgcpTowerDefense.GameObjects
{

    //The DrawableGameObject defines a set of variables and functions that can define a basic game object such as a tower, enemy mob, projectile, etc
    public class DrawableGameObject
    {

        protected Texture2D TextureCurrent; /*The current texture to be drawn of this object*/
        public Vector2 Position;            /*The position on the viewport in which this object will be drawn. Centered on Top Left of object*/
        public Vector2 Velocity;            /*The magnitude and direction the object moves each update*/
        public bool IsActive;               /*Flag, update with update each update if true, will not update if false*/
        public float Rotation;              /*Describes the rotation to be applied to object's draw*/
        public float AngularVelocity;       /* The magnitude and direction that the object's rotation changes each update*/
        public float Scale;                 /*The amount the object's graphic and hit box are scaled.*/
        public Color Color { get; set; }
        public String IdentifierString;     /* String Identifier used to provide unique ID's to different instances of the same gameObject
                                             class*/

        //This is the class constructor, notice that is a function that is call the same thing as the
        //class name, which in this game is "GameObject". It is automatically called whenever you create an instance of this class.
        //This mechanism allows us to set up default values of it's variables.

        /// <summary>
        /// Constructor. Initializes the the object to default values the moment it is instantiated.
        /// </summary>
        /// <param name="loadedTexture"></param>

        public DrawableGameObject(Texture2D loadedTexture)
        {

            Position = new Vector2(0, 0);
            Velocity = new Vector2(0, 0);

            Scale = 1f;
            Rotation = 0f;
            Position = Vector2.Zero;
            Velocity = Vector2.Zero;
            IsActive = false;
            Color = Color.White;
            TextureCurrent = loadedTexture;
        }

        //Public Functions. These funcations can be called "outside" the class. They provide an interface with which to interact with the class.
        public Vector2 GetCenter()
        {
            if (TextureCurrent == null)
            {
                throw new Exception("A gameObject tried to do texture operations without a texture defined");
            }

            return new Vector2(this.Position.X + ((this.TextureCurrent.Width * this.Scale) / 2),
                this.Position.Y + ((this.TextureCurrent.Width * this.Scale) / 2));
        }

        /// <summary>
        /// Returns the offset the represents the distance between the center of the object and the "origin" of the object. The origin of the object is the point
        /// which the object rotates about.
        /// </summary>
        /// <returns></returns>
        public Vector2 GetOriginOffset()
        {
            if (TextureCurrent == null)
            {
                throw new Exception("A gameObject tried to do texture operations without a texture defined");
            }

            return new Vector2( (this.TextureCurrent.Width * this.Scale) / 2, (this.TextureCurrent.Height * this.Scale) / 2);
        }

        public virtual Rectangle GetBoundingRectangle()
        {
            Rectangle BoundingRec = new Rectangle(
                (int)(this.Position.X - this.TextureCurrent.Width * this.Scale / 2),
                (int)(this.Position.Y - this.TextureCurrent.Height * this.Scale / 2),
                (int)(this.TextureCurrent.Width * this.Scale),
                (int)(this.TextureCurrent.Height * this.Scale));

            return BoundingRec;

        }

        //draws the game object with default texture
        public virtual void Draw(SpriteBatch spriteBatch)
        {
            if (IsActive)
            {
                //spriteBatch.Draw(CurrentTexture, Position, Color.White);
                spriteBatch.Draw(TextureCurrent, Position, null, Color, Rotation, this.GetOriginOffset(), Scale, SpriteEffects.None, 1);

            }
        }

        //draws game object with specified texture
        public virtual void Draw(SpriteBatch spriteBatch, Texture2D texture)
        {
            if (IsActive)
            {
                //spriteBatch.Draw(texture, this.GetCenter(), Color.White);
                spriteBatch.Draw(texture, Position, null, Color, Rotation, this.GetOriginOffset(), Scale, SpriteEffects.None, 1);

            }
        }

        //by adding the objects velocity to it's position every update cycle, we can make the object "move".
        public virtual void Update(GameTime gameTime)
        {
            if (IsActive)
            {
                this.Position += Velocity;
                this.Rotation += AngularVelocity;

            }
        }

    }
}


text:
package org.bouncycastle.crypto.agreement.kdf;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.crypto.DerivationParameters;

public class DHKDFParameters
    implements DerivationParameters
{
    private ASN1ObjectIdentifier algorithm;
    private int keySize;
    private byte[] z;
    private byte[] extraInfo;

    public DHKDFParameters(
        DERObjectIdentifier algorithm,
        int keySize,
        byte[] z)
    {
        this(algorithm, keySize, z, null);
    }

    public DHKDFParameters(
        DERObjectIdentifier algorithm,
        int keySize,
        byte[] z,
        byte[] extraInfo)
    {
        this.algorithm = new ASN1ObjectIdentifier(algorithm.getId());
        this.keySize = keySize;
        this.z = z;
        this.extraInfo = extraInfo;
    }

    public ASN1ObjectIdentifier getAlgorithm()
    {
        return algorithm;
    }

    public int getKeySize()
    {
        return keySize;
    }

    public byte[] getZ()
    {
        return z;
    }

    public byte[] getExtraInfo()
    {
        return extraInfo;
    }
}


text:
/**
 * Module dependencies.
 */
var express = require('express')
	, routes = require('./routes')
	, http = require('http')
	, path = require('path')
	, querystring = require('querystring')
	, fs = require('fs')
	, FileFeeder = require('./services/FileFeeder')
	, properties = require('./properties')
	, logger = require('../shared/logging/Logger').getLogger('client')
	, _ = require('underscore')
	;

var app = express(),
	fileFeeder = new FileFeeder
	;

app.configure(function(){
  app.set('port', properties.FILE_FEEDER_PORT || process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

// app.get('/', routes.index);

app.all('/heartbeat', function(req, res, next) {

	logger.debug("heartbeat: ", req.body);
	res.send(200, "OK");

});

app.post('/musicstream', function(req, res, next) {

	logger.debug('stream requested');

	var audioReq = _.clone(req.body);

	if (audioReq.filepath) {

		res.on('close', function() {
			logger.info('\n+++client connection was terminated');
		});

		var localFilePath = audioReq.filepath;
		var stat = fs.statSync(localFilePath);

		res.writeHead(200, {
			'Content-Type' : 'audio/mpeg',
			'Content-Length' : stat.size
		});

		var readStream = fs.createReadStream(localFilePath);
		fileFeeder.pipeStreamer(readStream, res);

	}
	else {
		res.send(400, 'No filepath field set');
	}

});

http.createServer(app).listen(app.get('port'), function(){
	logger.info("Client streamer listening on port " + app.get('port'));
});


text:
The NBT Editor is an easy to use NBT editor.
The NBT file format is used by minecraft to store
the data of the worlds.

The project can be build via ANT (build.xml).
The following jars are generated:

-   *nbt*

    A command line version to generate readable nbt representations.
    In combination with the source package this jar can be
    imported in other projects to use the nbt api.

-   *nbt_edit*

    The visual nbt editor.

-   *nbt_map*

    A minecraft anvil map viewer and editor.
    Better run with -Xmx2g or more for larger maps.

    NOTE THAT ALL CHANGES TO A MAP IN THIS VIEW ARE PERMANENT!

    So you better should backup your world before loading it
    in this editor. Edit the world by choosing a brush and
    right click on the map. The slider can be used to set the radius.

-   *ultrahc.jar*

    Converts a world to a ultra hardcore world. The root folder
    of the world must be provided as an argument. This program
    generates a border for the map and allows to reset the spawn
    to a position outside of the area, position players ready to fight,
    and ensures that the game type for all players is survival.

-   *nbt_src*

    A zip file containing the sources of this project.

### The NBT format

The content of a NBT file is a gzipped stream of
byte data. The following grammar is a complete
description of the format:

    RECORD := END | REAL_RECORD

    REAL_RECORD := BYTE | SHORT | INT | LONG | FLOAT | DOUBLE
                 | BYTE_ARRAY | STRING | LIST | COMPOUND | INT_ARRAY

    END := 0

    BYTE := 1 NAME RAW_BYTE

    SHORT := 2 NAME RAW_SHORT

    INT := 3 NAME RAW_INT

    LONG := 4 NAME RAW_LONG

    FLOAT := 5 NAME RAW_FLOAT

    DOUBLE := 6 NAME RAW_DOUBLE

    BYTE_ARRAY := 7 NAME RAW_BYTE_ARRAY

    STRING := 8 NAME RAW_STRING

    LIST := 9 NAME RAW_LIST

    COMPOUND := 10 NAME RAW_COMPOUND

    INT_ARRAY := 11 NAME RAW_INT_ARRAY

    NAME := RAW_STRING

    RAW_BYTE := <signed byte>

    RAW_SHORT := <big endian signed short>

    RAW_INT := <big endian signed integer>

    RAW_LONG := <big endian signed long>

    RAW_FLOAT := <big endian IEEE 754-2008 float>

    RAW_DOUBLE := <big endian IEEE 754-2008 double>

    RAW_BYTE_ARRAY := RAW_INT <byte array with length given by integer>

    RAW_STRING := RAW_SHORT <utf8 string with length given by short>

    RAW_LIST := [0-10] RAW_INT ITEM
    // type of item given by byte and length given by integer
    ITEM := RAW_ITEM (ITEM |)

    RAW_ITEM := RAW_BYTE | RAW_SHORT | RAW_INT | RAW_LONG | RAW_FLOAT
              | RAW_DOUBLE | RAW_BYTE_ARRAY | RAW_STRING | RAW_LIST | RAW_COMPOUND

    // names within a compound must be unique
    RAW_COMPOUND := REAL_RECORD RAW_COMPOUND | END

    RAW_INT_ARRAY := RAW_INT <int array with length given by integer>

The start symbol is RECORD and all numeric symbols stand for
the byte representation.

### NBT API

This project also provides an api to manipulate nbt files.
With the classes `nbt.read.NBTReader` and `nbt.write.NBTWriter`
streams or files containing nbt content can be read and written.
The class `nbt.record.NBTRecord` is the main class for nbt content.

Another way of using the api is the class `nbt.world.World`. It
provides an interface to manipulate worlds. For the most things
this works without the explicit use of NBTRecords and provides easy
to use methods to manipulate settings of the world or the maps.