text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ManipulationEventArgs.cs" company="Helix 3D Toolkit">
//   http://helixtoolkit.codeplex.com, license: MIT
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace HelixToolkit.Wpf
{
    using System.Windows;

    /// <summary>
    /// Provides data for the manipulation events.
    /// </summary>
    public class ManipulationEventArgs
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ManipulationEventArgs"/> class.
        /// </summary>
        /// <param name="currentPosition">
        /// The current position.
        /// </param>
        public ManipulationEventArgs(Point currentPosition)
        {
            this.CurrentPosition = currentPosition;
        }

        /// <summary>
        /// Gets or sets the current position.
        /// </summary>
        /// <value>The current position.</value>
        public Point CurrentPosition { get; private set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
struct Vector2
{
	Vector2();
	Vector2(float _x, float _y);

	float x = 0.0f;
	float y = 0.0f;

	// Returns a normalized version of the Vector with a magnitude of 1.
	Vector2 Normalized();

	// --- Statics ---

	// Smoothly moves between start and end, depending on percent in Range[0,1].
	static Vector2 Lerp(Vector2 start, Vector2 end, float percent);

	// Smoothly lerps the Vector between start and end.
	static Vector2 Slerp(Vector2 start, Vector2 end, float percent);

	// Dot product of Vector a and Vector b
	static float Dot(Vector2 a, Vector2 b);

	// Returns the Angle between a and b in Degrees.
	static float Angle(Vector2 a, Vector2 b);

	// Overloaded Operands to play with.
	Vector2 &operator+=(const Vector2 &other);
	Vector2 &operator-=(const Vector2 &other);
	Vector2 &operator*=(const Vector2 &other);
	Vector2 &operator*=(const float &other);
};


text:
@class JavaNetInetAddress;
@class JavaxJmdnsJmDNS;
@protocol JavaxJmdnsNetworkTopologyListener;

@interface JavaxJmdnsImplNetworkTopologyEventImpl : JavaxJmdnsNetworkTopologyEvent < NSCopying >

#pragma mark Public

- (instancetype)initWithJavaxJmdnsJmDNS:(JavaxJmdnsJmDNS *)jmDNS
                 withJavaNetInetAddress:(JavaNetInetAddress *)inetAddress;

- (JavaxJmdnsImplNetworkTopologyEventImpl *)java_clone;

- (JavaxJmdnsJmDNS *)getDNS;

- (JavaNetInetAddress *)getInetAddress;

- (NSString *)description;

#pragma mark Package-Private

- (instancetype)initWithJavaxJmdnsNetworkTopologyListener:(id<JavaxJmdnsNetworkTopologyListener>)jmmDNS
                                   withJavaNetInetAddress:(JavaNetInetAddress *)inetAddress;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaxJmdnsImplNetworkTopologyEventImpl)

FOUNDATION_EXPORT void JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsJmDNS_withJavaNetInetAddress_(JavaxJmdnsImplNetworkTopologyEventImpl *self, JavaxJmdnsJmDNS *jmDNS, JavaNetInetAddress *inetAddress);

FOUNDATION_EXPORT JavaxJmdnsImplNetworkTopologyEventImpl *new_JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsJmDNS_withJavaNetInetAddress_(JavaxJmdnsJmDNS *jmDNS, JavaNetInetAddress *inetAddress) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaxJmdnsImplNetworkTopologyEventImpl *create_JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsJmDNS_withJavaNetInetAddress_(JavaxJmdnsJmDNS *jmDNS, JavaNetInetAddress *inetAddress);

FOUNDATION_EXPORT void JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsNetworkTopologyListener_withJavaNetInetAddress_(JavaxJmdnsImplNetworkTopologyEventImpl *self, id<JavaxJmdnsNetworkTopologyListener> jmmDNS, JavaNetInetAddress *inetAddress);

FOUNDATION_EXPORT JavaxJmdnsImplNetworkTopologyEventImpl *new_JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsNetworkTopologyListener_withJavaNetInetAddress_(id<JavaxJmdnsNetworkTopologyListener> jmmDNS, JavaNetInetAddress *inetAddress) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaxJmdnsImplNetworkTopologyEventImpl *create_JavaxJmdnsImplNetworkTopologyEventImpl_initWithJavaxJmdnsNetworkTopologyListener_withJavaNetInetAddress_(id<JavaxJmdnsNetworkTopologyListener> jmmDNS, JavaNetInetAddress *inetAddress);

J2OBJC_TYPE_LITERAL_HEADER(JavaxJmdnsImplNetworkTopologyEventImpl)

#endif

#pragma pop_macro("INCLUDE_ALL_JavaxJmdnsImplNetworkTopologyEventImpl")


text:
<bill session="111" type="h" number="1289" updated="2009-03-07T12:30:45-05:00">
	<status><introduced date="1236056400" datetime="2009-03-03"/></status>

	<introduced date="1236056400" datetime="2009-03-03"/>
	<titles>
		<title type="short" as="introduced">Social Security Fairness for the Terminally Ill Act of 2009</title>
		<title type="official" as="introduced">To amend title II of the Social Security Act to eliminate the five-month waiting period in the disability insurance program, and for other purposes.</title>
	</titles>
	<sponsor id="412227"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1236056400" datetime="2009-03-03"><text>Referred to the House Committee on Ways and Means.</text></action>
	</actions>
	<committees>
		<committee name="House Ways and Means" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
package api

import (
	"encoding/json"
	"net/http"
	"regexp"

	"code.cloudfoundry.org/lager"
	"github.com/tedsuo/rata"

	"github.com/concourse/baggageclaim"
	"github.com/concourse/baggageclaim/volume"
)

func NewHandler(
	logger lager.Logger,
	strategerizer volume.Strategerizer,
	volumeRepo volume.Repository,
	p2pInterfacePattern *regexp.Regexp,
	p2pInterfaceFamily int,
	p2pStreamPort uint16,
) (http.Handler, error) {
	volumeServer := NewVolumeServer(
		logger.Session("volume-server"),
		strategerizer,
		volumeRepo,
	)

	p2pServer := NewP2pServer(
		logger.Session("p2p-server"),
		p2pInterfacePattern,
		p2pInterfaceFamily,
		p2pStreamPort,
	)

	handlers := rata.Handlers{
		baggageclaim.CreateVolume:            http.HandlerFunc(volumeServer.CreateVolume),
		baggageclaim.CreateVolumeAsync:       http.HandlerFunc(volumeServer.CreateVolumeAsync),
		baggageclaim.CreateVolumeAsyncCancel: http.HandlerFunc(volumeServer.CreateVolumeAsyncCancel),
		baggageclaim.CreateVolumeAsyncCheck:  http.HandlerFunc(volumeServer.CreateVolumeAsyncCheck),
		baggageclaim.ListVolumes:             http.HandlerFunc(volumeServer.ListVolumes),
		baggageclaim.GetVolume:               http.HandlerFunc(volumeServer.GetVolume),
		baggageclaim.SetProperty:             http.HandlerFunc(volumeServer.SetProperty),
		baggageclaim.GetPrivileged:           http.HandlerFunc(volumeServer.GetPrivileged),
		baggageclaim.SetPrivileged:           http.HandlerFunc(volumeServer.SetPrivileged),
		baggageclaim.StreamIn:                http.HandlerFunc(volumeServer.StreamIn),
		baggageclaim.StreamOut:               http.HandlerFunc(volumeServer.StreamOut),
		baggageclaim.StreamP2pOut:            http.HandlerFunc(volumeServer.StreamP2pOut),
		baggageclaim.DestroyVolume:           http.HandlerFunc(volumeServer.DestroyVolume),
		baggageclaim.DestroyVolumes:          http.HandlerFunc(volumeServer.DestroyVolumes),

		baggageclaim.GetP2pUrl: http.HandlerFunc(p2pServer.GetP2pUrl),
	}

	return rata.NewRouter(baggageclaim.Routes, handlers)
}

type ErrorResponse struct {
	Message string `json:"error"`
}

func RespondWithError(w http.ResponseWriter, err error, statusCode ...int) {
	var code int

	if len(statusCode) > 0 {
		code = statusCode[0]
	} else {
		code = http.StatusInternalServerError
	}

	w.WriteHeader(code)
	errResponse := ErrorResponse{Message: err.Error()}
	json.NewEncoder(w).Encode(errResponse)
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.execution.scheduler;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.trino.Session;
import io.trino.connector.CatalogName;
import io.trino.execution.NodeTaskMap;
import io.trino.execution.RemoteTask;
import io.trino.metadata.InternalNode;
import io.trino.metadata.Split;
import io.trino.spi.HostAddress;

import javax.inject.Inject;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.airlift.concurrent.MoreFutures.whenAnyCompleteCancelOthers;
import static java.util.Objects.requireNonNull;

public class NodeScheduler
{
    private final NodeSelectorFactory nodeSelectorFactory;

    @Inject
    public NodeScheduler(NodeSelectorFactory nodeSelectorFactory)
    {
        this.nodeSelectorFactory = requireNonNull(nodeSelectorFactory, "nodeSelectorFactory is null");
    }

    public NodeSelector createNodeSelector(Session session, Optional<CatalogName> catalogName)
    {
        return nodeSelectorFactory.createNodeSelector(requireNonNull(session, "session is null"), requireNonNull(catalogName, "catalogName is null"));
    }

    public static List<InternalNode> getAllNodes(NodeMap nodeMap, boolean includeCoordinator)
    {
        return nodeMap.getNodesByHostAndPort().values().stream()
                .filter(node -> includeCoordinator || !nodeMap.getCoordinatorNodeIds().contains(node.getNodeIdentifier()))
                .collect(toImmutableList());
    }

    public static List<InternalNode> selectNodes(int limit, Iterator<InternalNode> candidates)
    {
        checkArgument(limit > 0, "limit must be at least 1");

        List<InternalNode> selected = new ArrayList<>(limit);
        while (selected.size() < limit && candidates.hasNext()) {
            selected.add(candidates.next());
        }

        return selected;
    }

    public static ResettableRandomizedIterator<InternalNode> randomizedNodes(NodeMap nodeMap, boolean includeCoordinator, Set<InternalNode> excludedNodes)
    {
        ImmutableList<InternalNode> nodes = nodeMap.getNodesByHostAndPort().values().stream()
                .filter(node -> includeCoordinator || !nodeMap.getCoordinatorNodeIds().contains(node.getNodeIdentifier()))
                .filter(node -> !excludedNodes.contains(node))
                .collect(toImmutableList());
        return new ResettableRandomizedIterator<>(nodes);
    }

    public static List<InternalNode> selectExactNodes(NodeMap nodeMap, List<HostAddress> hosts, boolean includeCoordinator)
    {
        Set<InternalNode> chosen = new LinkedHashSet<>();
        Set<String> coordinatorIds = nodeMap.getCoordinatorNodeIds();

        for (HostAddress host : hosts) {
            nodeMap.getNodesByHostAndPort().get(host).stream()
                    .filter(node -> includeCoordinator || !coordinatorIds.contains(node.getNodeIdentifier()))
                    .forEach(chosen::add);

            InetAddress address;
            try {
                address = host.toInetAddress();
            }
            catch (UnknownHostException e) {
                // skip hosts that don't resolve
                continue;
            }

            // consider a split with a host without a port as being accessible by all nodes in that host
            if (!host.hasPort()) {
                nodeMap.getNodesByHost().get(address).stream()
                        .filter(node -> includeCoordinator || !coordinatorIds.contains(node.getNodeIdentifier()))
                        .forEach(chosen::add);
            }
        }

        // if the chosen set is empty and the host is the coordinator, force pick the coordinator
        if (chosen.isEmpty() && !includeCoordinator) {
            for (HostAddress host : hosts) {
                // In the code below, before calling `chosen::add`, it could have been checked that
                // `coordinatorIds.contains(node.getNodeIdentifier())`. But checking the condition isn't necessary
                // because every node satisfies it. Otherwise, `chosen` wouldn't have been empty.

                chosen.addAll(nodeMap.getNodesByHostAndPort().get(host));

                InetAddress address;
                try {
                    address = host.toInetAddress();
                }
                catch (UnknownHostException e) {
                    // skip hosts that don't resolve
                    continue;
                }

                // consider a split with a host without a port as being accessible by all nodes in that host
                if (!host.hasPort()) {
                    chosen.addAll(nodeMap.getNodesByHost().get(address));
                }
            }
        }

        return ImmutableList.copyOf(chosen);
    }

    public static SplitPlacementResult selectDistributionNodes(
            NodeMap nodeMap,
            NodeTaskMap nodeTaskMap,
            int maxSplitsPerNode,
            int maxPendingSplitsPerTask,
            int maxUnacknowledgedSplitsPerTask,
            Set<Split> splits,
            List<RemoteTask> existingTasks,
            BucketNodeMap bucketNodeMap)
    {
        Multimap<InternalNode, Split> assignments = HashMultimap.create();
        NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks);

        Set<InternalNode> blockedNodes = new HashSet<>();
        for (Split split : splits) {
            // node placement is forced by the bucket to node map
            InternalNode node = bucketNodeMap.getAssignedNode(split).get();

            // if node is full, don't schedule now, which will push back on the scheduling of splits
            if (assignmentStats.getUnacknowledgedSplitCountForStage(node) < maxUnacknowledgedSplitsPerTask &&
                    (assignmentStats.getTotalSplitCount(node) < maxSplitsPerNode || assignmentStats.getQueuedSplitCountForStage(node) < maxPendingSplitsPerTask)) {
                assignments.put(node, split);
                assignmentStats.addAssignedSplit(node);
            }
            else {
                blockedNodes.add(node);
            }
        }

        ListenableFuture<Void> blocked = toWhenHasSplitQueueSpaceFuture(blockedNodes, existingTasks, calculateLowWatermark(maxPendingSplitsPerTask));
        return new SplitPlacementResult(blocked, ImmutableMultimap.copyOf(assignments));
    }

    public static int calculateLowWatermark(int maxPendingSplitsPerTask)
    {
        return (int) Math.ceil(maxPendingSplitsPerTask / 2.0);
    }

    public static ListenableFuture<Void> toWhenHasSplitQueueSpaceFuture(Set<InternalNode> blockedNodes, List<RemoteTask> existingTasks, int spaceThreshold)
    {
        if (blockedNodes.isEmpty()) {
            return immediateVoidFuture();
        }
        Map<String, RemoteTask> nodeToTaskMap = new HashMap<>();
        for (RemoteTask task : existingTasks) {
            nodeToTaskMap.put(task.getNodeId(), task);
        }
        List<ListenableFuture<Void>> blockedFutures = blockedNodes.stream()
                .map(InternalNode::getNodeIdentifier)
                .map(nodeToTaskMap::get)
                .filter(Objects::nonNull)
                .map(remoteTask -> remoteTask.whenSplitQueueHasSpace(spaceThreshold))
                .collect(toImmutableList());
        if (blockedFutures.isEmpty()) {
            return immediateVoidFuture();
        }
        return asVoid(whenAnyCompleteCancelOthers(blockedFutures));
    }

    public static ListenableFuture<Void> toWhenHasSplitQueueSpaceFuture(List<RemoteTask> existingTasks, int spaceThreshold)
    {
        if (existingTasks.isEmpty()) {
            return immediateVoidFuture();
        }
        List<ListenableFuture<Void>> stateChangeFutures = existingTasks.stream()
                .map(remoteTask -> remoteTask.whenSplitQueueHasSpace(spaceThreshold))
                .collect(toImmutableList());
        return asVoid(whenAnyCompleteCancelOthers(stateChangeFutures));
    }

    private static <T> ListenableFuture<Void> asVoid(ListenableFuture<T> future)
    {
        return Futures.transform(future, v -> null, directExecutor());
    }
}


text:
#include <aws/ce/model/MetricValue.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CostExplorer
{
namespace Model
{

MetricValue::MetricValue() :
    m_amountHasBeenSet(false),
    m_unitHasBeenSet(false)
{
}

MetricValue::MetricValue(JsonView jsonValue) :
    m_amountHasBeenSet(false),
    m_unitHasBeenSet(false)
{
  *this = jsonValue;
}

MetricValue& MetricValue::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Amount"))
  {
    m_amount = jsonValue.GetString("Amount");

    m_amountHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Unit"))
  {
    m_unit = jsonValue.GetString("Unit");

    m_unitHasBeenSet = true;
  }

  return *this;
}

JsonValue MetricValue::Jsonize() const
{
  JsonValue payload;

  if(m_amountHasBeenSet)
  {
   payload.WithString("Amount", m_amount);

  }

  if(m_unitHasBeenSet)
  {
   payload.WithString("Unit", m_unit);

  }

  return payload;
}

} // namespace Model
} // namespace CostExplorer
} // namespace Aws


text:
@interface MainMenuViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *aboutView;

@property (weak, nonatomic) IBOutlet UILabel *versionLabel;
@end


text:
class RdbTrackerFilter < RdbFilter
  def initialize
    super :tracker
  end

  def scope(scope)
    return scope if all?

    scope.where tracker_id: values
  end

  def all?
    values.count == board.trackers.count
  end

  def apply_to_child_issues?
    true
  end

  def default_values
    board.trackers.pluck(:id)
  end

  def update(params)
    return unless (tracker = params[:tracker])

    if tracker == 'all'
      self.values = board.trackers.pluck(:id)
      return
    end

    id = tracker.to_i
    return if board.trackers.where(id: id).empty?

    if params[:only]
      self.value = id
    elsif values.include? id
      values.delete id if values.count > 2
    else
      values << id
    end
  end

  def title
    return I18n.t(:rdb_filter_tracker_all) if all?
    return I18n.t(:rdb_filter_tracker_multiple) if values.count > 1

    board.trackers.find(value).name
  end

  def enabled?(id)
    return true if value == :all

    values.include? id
  end
end


text: Implementation of IETF language tag


text:
import { IContainer } from '../../../../../../../../model/IContainer';
import { Id } from '../../../../../../../../util/id';
import { Key } from '../../../../../../../../util/keycode';
import { SpecmateDataService } from '../../../../../../../data/modules/data-service/services/specmate-data.service';
import { SelectedElementService } from '../../../../../../side/modules/selected-element/services/selected-element.service';
import { ClipboardService } from '../../services/clipboard-service';
import { MultiselectionService } from '../../services/multiselection.service';
import { GraphTransformer } from '../../util/graph-transformer';
import { IDragAndDropTool } from '../IDragAndDropTool';
import { IKeyboardTool } from '../IKeyboardTool';
import { ToolBase } from '../tool-base';

export class SelectTool extends ToolBase implements IKeyboardTool, IDragAndDropTool {
    public icon = 'mouse-pointer';
    public color = 'primary';
    public cursor = 'default';
    public name = 'tools.select';
    public selectedElements: any[] = [];
    public done = false;

    public sticky = false;

    private static originType: string;

    public activate() {
        this.selectedElements = [];
    }

    public deactivate() {
        this.selectedElements = [];
    }

    public click(event: MouseEvent, zoom: number): Promise<void> {
        return Promise.resolve();
    }

    private setSelection(element: IContainer): void {
        this.selectedElements = [element];
        this.selectedElementService.selectedElements = this.selectedElements;
    }

    public select(element: IContainer, evt: MouseEvent): Promise<void> {
        if (evt.shiftKey) {
            if (!('x' in element && 'y' in element)) {
                // If the user selects an ISpecmatePositionableModelObject the selection is already handled by DraggableElementBase
                this.selectedElementService.toggleSelection([element]);
            }
        } else {
            if (this.selectedElementService.isSelected(element)) {
                return Promise.resolve();
            }
            this.setSelection(element);
        }

        let blur = (<HTMLElement>document.activeElement).blur;
        if (blur) {
            (<HTMLElement>document.activeElement).blur();
        }
        return Promise.resolve();
    }

    public mouseDown(event: MouseEvent, zoom: number): Promise<void> {
        this.rect.mouseDown(event, zoom);
        return Promise.resolve();
    }

    public mouseDrag(event: MouseEvent, zoom: number): Promise<void> {
        this.rect.mouseMove(event, zoom);
        return Promise.resolve();
    }

    public mouseUp(event: MouseEvent, zoom: number): Promise<void> {
        return this.rect.mouseUp(event, zoom);
    }

    private cancelEvent(evt: KeyboardEvent) {
        evt.preventDefault();
        evt.stopPropagation();
    }

    // Keyboard Shortcuts
    public keydown(evt: KeyboardEvent): Promise<void> {
        let ctrl = evt.ctrlKey || evt.metaKey;

        if (ctrl && evt.key === 'c') {
            // Copy
            this.cancelEvent(evt);
            return this.copySelection();
        }

        if (ctrl && evt.key === 'v') {
            // Paste
            this.cancelEvent(evt);
            return this.pasteSelection();
        }

        if (ctrl && evt.key === 'x') {
            // Cut
            this.cancelEvent(evt);
            return this.cutSelection();
        }

        if (evt.keyCode === Key.BACKSPACE) {
            // Delete
            this.cancelEvent(evt);
            return this.deleteSelection();
        }
        return Promise.resolve();
    }

    private async copySelection(): Promise<void> {
        // Copy Selection
        SelectTool.originType = this.model.className;
        let graphTransformer = new GraphTransformer(this.dataService, this.selectedElementService, this.model);
        let sel = this.selectedElementService.selectedElements.slice();
        this.clipboardService.clipboard = await graphTransformer.cloneSubgraph(sel, Id.uuid, false);
        return Promise.resolve();
    }

    private cutSelection(): Promise<void> {
        return this.copySelection().then(() => this.deleteSelection());
    }

    private async pasteSelection(): Promise<void> {
        if (!SelectTool.originType || !this.clipboardService.hasClipboard()) {
            // Nothing to paste
            return Promise.resolve();
        }

        let graphTransformer = new GraphTransformer(this.dataService, this.selectedElementService, this.model);
        let compoundId: string = Id.uuid;
        // Check Compatible Origin
        if (this.model.className !== SelectTool.originType) {
            return Promise.resolve();
        }

        let newSelection = await graphTransformer.cloneSubgraph(this.clipboardService.clipboard, compoundId, true);
        this.selectedElementService.selectedElements = newSelection;
        return Promise.resolve();
    }

    private async deleteSelection(): Promise<void> {
        let compoundId: string = Id.uuid;
        let graphTransformer = new GraphTransformer(this.dataService, this.selectedElementService, this.model);
        let selection = this.selectedElementService.selectedElements.slice();
        await graphTransformer.deleteAll(selection, compoundId);
        return Promise.resolve();
    }

    constructor(protected selectedElementService: SelectedElementService, private dataService: SpecmateDataService,
                private rect: MultiselectionService, private clipboardService: ClipboardService, private model: IContainer) {
        super(selectedElementService);
    }
}


text:
package org.jersey2.jaxbcontext.example;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

/**
 * 不使用注解返回xml
 * @author welcome
 *
 */

@Path("/employee")
@Consumes(MediaType.APPLICATION_XML)//Accept 接受值类型
@Produces(MediaType.APPLICATION_XML)//ContentType 返回值类型
public class EmployeeRestService {

	@Path("/v1")
	@GET
	public List<JAXBElement<Employee>> getEmployees(){
		List<JAXBElement<Employee>> employees = new ArrayList<JAXBElement<Employee>>();
		Employee employee;
		Department department;
		JAXBElement<Employee> element;
		for (int i = 1; i <= 100; i++) {
			department = new Department(i,"department"+i);
			employee = new Employee(i,"employee"+i,department);
			element = new JAXBElement<Employee>(new QName("employee"), Employee.class, employee);
			employees.add(element);
		}
		return employees;
	}

	@Path("{id}")
	@GET
	public JAXBElement<Employee> getEmployee(@PathParam("id")int id){
		Department department = new Department(id,"研发部");
		Employee employee = new Employee(id,"scott",department);
		return new JAXBElement<Employee>(new QName("employee"), Employee.class, employee);
	}

	@POST
	public JAXBElement<Employee> saveEmployee(JAXBElement<Employee> employee){
		return employee;
	}

	@PUT
	public JAXBElement<Employee> updateEmployee(JAXBElement<Employee> employee){
		Employee value = employee.getValue();
		value.setEname("乔布斯");
		value.getDepartment().setDeptname("apple");
		return new JAXBElement<Employee>(new QName("employee"), Employee.class, value);
	}

	@DELETE
	@Path("{id}")
	public JAXBElement<Employee> deleteEmployee(@PathParam("id")int id){
		Department department = new Department(id,"研发部");
		Employee employee = new Employee(id,"scott",department);
		return new JAXBElement<Employee>(new QName("employee"), Employee.class, employee);
	}
}


text:
import Ember from 'ember';

/**
  The `DS.Transform` class is used to serialize and deserialize model
  attributes when they are saved or loaded from an
  adapter. Subclassing `DS.Transform` is useful for creating custom
  attributes. All subclasses of `DS.Transform` must implement a
  `serialize` and a `deserialize` method.

  Example

  ```app/transforms/temperature.js
  import DS from 'ember-data';

  // Converts centigrade in the JSON to fahrenheit in the app
  export default DS.Transform.extend({
    deserialize: function(serialized, options) {
      return (serialized *  1.8) + 32;
    },
    serialize: function(deserialized, options) {
      return (deserialized - 32) / 1.8;
    }
  });
  ```

  The options passed into the `DS.attr` function when the attribute is
  declared on the model is also available in the transform.

  ```app/models/post.js
  export default DS.Model.extend({
    title: DS.attr('string'),
    markdown: DS.attr('markdown', {
      markdown: {
        gfm: false,
        sanitize: true
      }
    })
  });
  ```

  ```app/transforms/markdown.js
  export default DS.Transform.extend({
    serialize: function (deserialized, options) {
      return deserialized.raw;
    },

    deserialize: function (serialized, options) {
      var markdownOptions = options.markdown || {};

      return marked(serialized, markdownOptions);
    }
  });
  ```

  Usage

  ```app/models/requirement.js
  import DS from 'ember-data';

  export default DS.Model.extend({
    name: DS.attr('string'),
    temperature: DS.attr('temperature')
  });
  ```

  @class Transform
  @namespace DS
 */
export default Ember.Object.extend({
  /**
    When given a deserialized value from a record attribute this
    method must return the serialized value.

    Example

    ```javascript
    serialize: function(deserialized, options) {
      return Ember.isEmpty(deserialized) ? null : Number(deserialized);
    }
    ```

    @method serialize
    @param deserialized The deserialized value
    @param options hash of options passed to `DS.attr`
    @return The serialized value
  */
  serialize: null,

  /**
    When given a serialize value from a JSON object this method must
    return the deserialized value for the record attribute.

    Example

    ```javascript
    deserialize: function(serialized, options) {
      return empty(serialized) ? null : Number(serialized);
    }
    ```

    @method deserialize
    @param serialized The serialized value
    @param options hash of options passed to `DS.attr`
    @return The deserialized value
  */
  deserialize: null
});


text:
package de.codesourcery.jasm16.ide.ui.views;

public interface IViewStateListener
{
    public void viewVisible();

    public void viewHidden();
}


text:
var __ = require('underscore'),
    Backbone = require('backbone');

module.exports = window.Backbone.Model.extend({
  defaults: {
    status: 0,
    contract_type: "",
    vendor: "",
    description: "",
    title: "",
    order_id: "",
    timestamp: 0,
    btc_total: 0,
    thumbnail_hash: "",
    btAve: "", //set by view
    cCode: "" //set by view
  },

  parse: function(response){
    "use strict";
    if(response.cCode != 'BTC'){
      response.displayPrice = new Intl.NumberFormat(window.lang, {
        style: 'currency',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
        currency: response.cCode
      }).format(response.btc_total*response.btAve);
    } else {
      response.displayPrice = response.btc_total.toFixed(4) + " BTC";
    }

    return response;
  }
});


text:
require 'lettuce-android/version'
require 'lettuce-android/operations'
require 'lettuce-android/abase'


text:
int euidaccess(const char *filename, int amode)
{
	return faccessat(AT_FDCWD, filename, amode, AT_EACCESS);
}

weak_alias(euidaccess, eaccess);


text:
UPGRADE FROM 4.1 to 4.2
=======================

BrowserKit
----------

 * The `Client::submit()` method will have a new `$serverParameters` argument in version 5.0, not defining it is deprecated.

Cache
-----

 * Deprecated `CacheItem::getPreviousTags()`, use `CacheItem::getMetadata()` instead.

Config
------

 * Deprecated constructing a `TreeBuilder` without passing root node information.
 * Deprecated `FileLoaderLoadException`, use `LoaderLoadException` instead.

Console
-------

 * Deprecated passing a command as a string to `ProcessHelper::run()`,
   pass the command as an array of arguments instead.

   Before:
   ```php
   $processHelper->run($output, 'ls -l');
   ```

   After:
   ```php
   $processHelper->run($output, array('ls', '-l'));

   // alternatively, when a shell wrapper is required
   $processHelper->run($output, Process::fromShellCommandline('ls -l'));
   ```

DoctrineBridge
--------------

 * The `lazy` attribute on `doctrine.event_listener` tags was removed.
   Listeners are now lazy by default. So any `lazy` attributes can safely be removed from those tags.

DomCrawler
----------

 * The `Crawler::children()` method will have a new `$selector` argument in version 5.0, not defining it is deprecated.

Finder
------

 * The `Finder::sortByName()` method will have a new `$useNaturalSort` argument in version 5.0, not defining it is deprecated.

Form
----

 * The `scale` option of the `IntegerType` is deprecated.
 * The `$scale` argument of the `IntegerToLocalizedStringTransformer` is deprecated.

 * Deprecated calling `FormRenderer::searchAndRenderBlock` for fields which were already rendered.
   Instead of expecting such calls to return empty strings, check if the field has already been rendered.

   Before:
   ```twig
   {% for field in fieldsWithPotentialDuplicates %}
      {{ form_widget(field) }}
   {% endfor %}
   ```

   After:
   ```twig
   {% for field in fieldsWithPotentialDuplicates if not field.rendered %}
      {{ form_widget(field) }}
   {% endfor %}
   ```

HttpFoundation
--------------

 * The default value of the "$secure" and "$samesite" arguments of Cookie's constructor
   will respectively change from "false" to "null" and from "null" to "lax" in Symfony
   5.0, you should define their values explicitly or use "Cookie::create()" instead.

FrameworkBundle
---------------

 * The `framework.router.utf8` configuration option has been added. If your app's charset
   is UTF-8 (see kernel's `getCharset()` method), it is recommended to set it to `true`:
   this will generate 404s for non-UTF-8 URLs, which are incompatible with you app anyway,
   and will allow dumping optimized routers and using Unicode classes in requirements.
 * Added support for the SameSite attribute for session cookies. It is highly recommended to set this setting (`framework.session.cookie_samesite`) to `lax` for increased security against CSRF attacks.
 * The `Controller` class has been deprecated, use `AbstractController` instead.
 * The Messenger encoder/decoder configuration has been changed for a unified Messenger serializer configuration.

   Before:
   ```yaml
   framework:
       messenger:
           encoder: your_encoder_service_id
           decoder: your_decoder_service_id
   ```

   After:
   ```yaml
   framework:
       messenger:
           serializer:
               id: your_messenger_service_id
   ```
 * The `ContainerAwareCommand` class has been deprecated, use `Symfony\Component\Console\Command\Command`
   with dependency injection instead.
 * The `--env` console option and its "-e" shortcut have been deprecated,
   set the "APP_ENV" environment variable instead.
 * The `--no-debug` console option has been deprecated,
   set the "APP_DEBUG" environment variable to "0" instead.

Messenger
---------

 * `EnvelopeItemInterface` doesn't extend `Serializable` anymore
 * The `handle` method of the `Symfony\Component\Messenger\Middleware\ValidationMiddleware` and `Symfony\Component\Messenger\Asynchronous\Middleware\SendMessageMiddleware` middlewares now requires an `Envelope` object to be given (because they implement the `EnvelopeAwareInterface`). When using these middleware with the provided `MessageBus`, you will not have to do anything. If you use the middlewares any other way, you can use `Envelope::wrap($message)` to create an envelope for your message.
 * `MessageSubscriberInterface::getHandledMessages()` return value has changed. The value of an array item
   needs to be an associative array or the method name.

   Before:
   ```php
   return [
      [FirstMessage::class, 0],
      [SecondMessage::class, -10],
   ];
   ```

   After:
   ```php
   yield FirstMessage::class => ['priority' => 0];
   yield SecondMessage::class => ['priority => -10];
   ```

   Before:
   ```php
   return [
       SecondMessage::class => ['secondMessageMethod', 20],
   ];
   ```

   After:
   ```php
   yield SecondMessage::class => [
       'method' => 'secondMessageMethod',
       'priority' => 20,
   ];
   ```
 * The `EncoderInterface` and `DecoderInterface` interfaces have been replaced by a unified `Symfony\Component\Messenger\Transport\Serialization\SerializerInterface`.
   Each interface method have been merged untouched into the `Serializer` interface, so you can simply merge your two implementations together and implement the new interface.

Monolog
-------

 * The methods `DebugProcessor::getLogs()`, `DebugProcessor::countErrors()`, `Logger::getLogs()` and `Logger::countErrors()` will have a new `$request` argument in version 5.0, not defining it is deprecated.

Process
-------

 * Deprecated the `Process::setCommandline()` and the `PhpProcess::setPhpBinary()` methods.
 * Deprecated passing commands as strings when creating a `Process` instance.

   Before:
   ```php
   $process = new Process('ls -l');
   ```

   After:
   ```php
   $process = new Process(array('ls', '-l'));

   // alternatively, when a shell wrapper is required
   $process = Process::fromShellCommandline('ls -l');
   ```

Security
--------

 * Using the `has_role()` function in security expressions is deprecated, use the `is_granted()` function instead.
 * Not returning an array of 3 elements from `FirewallMapInterface::getListeners()` is deprecated, the 3rd element
   must be an instance of `LogoutListener` or `null`.
 * Passing custom class names to the
   `Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver` to define
   custom anonymous and remember me token classes is deprecated. To
   use custom tokens, extend the existing `Symfony\Component\Security\Core\Authentication\Token\AnonymousToken`
   or `Symfony\Component\Security\Core\Authentication\Token\RememberMeToken`.
 * Accessing the user object that is not an instance of `UserInterface` from `Security::getUser()` is deprecated.
 * `SimpleAuthenticatorInterface`, `SimpleFormAuthenticatorInterface`, `SimplePreAuthenticatorInterface`,
   `SimpleAuthenticationProvider`, `SimpleAuthenticationHandler`, `SimpleFormAuthenticationListener` and
   `SimplePreAuthenticationListener` have been deprecated. Use Guard instead.

SecurityBundle
--------------

 * Passing a `FirewallConfig` instance as 3rd argument to the `FirewallContext` constructor is deprecated,
   pass a `LogoutListener` instance instead.
 * Using the `security.authentication.trust_resolver.anonymous_class` and
   `security.authentication.trust_resolver.rememberme_class` parameters to define
   the token classes is deprecated. To use
   custom tokens extend the existing AnonymousToken and RememberMeToken.
 * The `simple_form` and `simple_preauth` authentication listeners have been deprecated,
   use Guard instead.
 * The `SimpleFormFactory` and `SimplePreAuthenticationFactory` classes have been deprecated,
   use Guard instead.

Serializer
----------

 * Relying on the default value (false) of the "as_collection" option is deprecated.
   You should set it to false explicitly instead as true will be the default value in 5.0.
 * The `AbstractNormalizer::handleCircularReference()` method will have two new `$format` and `$context` arguments in version 5.0, not defining them is deprecated.

Translation
-----------

 * The `TranslatorInterface` has been deprecated in favor of `Symfony\Contracts\Translation\TranslatorInterface`
 * The `MessageSelector`, `Interval` and `PluralizationRules` classes have been deprecated, use `IdentityTranslator` instead
 * The `Translator::getFallbackLocales()` and `TranslationDataCollector::getFallbackLocales()` method have been marked as internal

Validator
---------

 * The component is now decoupled from `symfony/translation` and uses `Symfony\Contracts\Translation\TranslatorInterface` instead
 * The `ValidatorBuilderInterface` has been deprecated and `ValidatorBuilder` made final
 * Deprecated validating instances of `\DateTimeInterface` in `DateTimeValidator`, `DateValidator` and `TimeValidator`. Use `Type` instead or remove the constraint if the underlying model is type hinted to `\DateTimeInterface` already.
 * Using the `Bic`, `Country`, `Currency`, `Language` and `Locale` constraints without `symfony/intl` is deprecated
 * Using the `Email` constraint without `egulias/email-validator` is deprecated
 * Using the `Expression` constraint without `symfony/expression-language` is deprecated


text:
from google.appengine.ext import db

class PersonModel(db.Model):
    firstname = db.StringProperty()
    lastname = db.StringProperty()
    username = db.StringProperty()
    email = db.StringProperty()
    password = db.StringProperty()

class RefProductCategoriesModel(db.Model):
    name = db.StringProperty()
    description = db.StringProperty()

class CompanyModel(db.Model):
    name = db.StringProperty()
    description = db.StringProperty()

class CompanyBrandsModel(db.Model):
    company = db.ReferenceProperty(
        CompanyModel,
        required=True,
        collection_name='company_brand'
    )
    name = db.StringProperty()

class ProductModel(db.Model):
    brand = db.ReferenceProperty(
        CompanyBrandsModel,
        required=True,
        collection_name='brand'
    )
    category = db.ReferenceProperty(
        RefProductCategoriesModel,
        required=True,
        collection_name='product_category'
    )
    price = db.IntegerProperty()
    description = db.StringProperty()

class ManufacturerModel(db.Model):
    details = db.StringProperty()

class ProductManufacturersModel(db.Model):
    product = db.ReferenceProperty(ProductModel, collection_name='manufacturers')
    manufacturer = db.ReferenceProperty(ManufacturerModel, collection_name='products')

class RefPhoneNumbersTypesModel(db.Model):
    name = db.StringProperty()
    description = db.StringProperty()

class PhoneNumbersModel(db.Model):
    manufacturer = db.ReferenceProperty(
        ManufacturerModel,
        required=True,
        collection_name='manufacturer_phone'
    )
    type = db.ReferenceProperty(
        RefPhoneNumbersTypesModel,
        required=True,
        collection_name='phone_type'
    )
    phone = db.StringProperty()


text:
package com.dataart.spreadsheetanalytics.engine;

import java.util.List;

import javax.cache.Cache;
import javax.cache.Caching;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dataart.spreadsheetanalytics.api.engine.DataSourceHub;
import com.dataart.spreadsheetanalytics.api.engine.datasource.DataSource;
import com.dataart.spreadsheetanalytics.api.engine.datasource.DataSourceQuery;
import com.dataart.spreadsheetanalytics.api.model.IDataSet;

/**
 * {@link DataSourceHub} implementation based on {@link Cache}.
 */
public class CacheBasedDataSourceHub implements DataSourceHub {
    private static final Logger log = LoggerFactory.getLogger(CacheBasedDataSourceHub.class);

    public static final String DATA_SOURCE_CACHE_NAME = "dataSourceCache";

    protected Cache<Object, DataSource> dataSourceCache = Caching.getCache(DATA_SOURCE_CACHE_NAME, Object.class, DataSource.class);

    @Override
    public IDataSet executeQuery(String dataSourceName, DataSourceQuery query, List<Object> params) throws Exception {
        log.debug("Execute data query for DataSource: {} and Query: {}", dataSourceName, query);

        DataSource ds = this.get(dataSourceName);

        if (ds == null) {
            log.error(String.format("DataSource with name %s is not found.", dataSourceName));
            throw new CalculationEngineException(String.format("DataSource with name %s is not found.", dataSourceName));
        }

        return ds.executeQuery(query, params);
    }

    @Override
    public void add(DataSource sqlDataSource) {
        this.dataSourceCache.put(sqlDataSource.getName() == null ? "" : sqlDataSource.getName(), sqlDataSource);
        log.debug("Added DataSource with name {}", sqlDataSource.getName());
    }

    @Override
    public void remove(DataSource dataSource) {
        if (dataSource == null) { return; }
        this.dataSourceCache.remove(dataSource.getName() == null ? "" : dataSource.getName());
    }

    @Override
    public void remove(String dataSourceName) {
        this.dataSourceCache.remove(dataSourceName == null ? "" : dataSourceName);
    }

    @Override
    public DataSource get(String dataSourceName) {
        return this.dataSourceCache.get(dataSourceName == null ? "" : dataSourceName);
    }

    public void setDataSourceCache(Cache<Object, DataSource> cache) { this.dataSourceCache = cache; }
}


text:
module.exports = function ({ $lookup }) {
    return {
        object: function () {
            return function ($buffer, $start) {
                let object = {
                    value: 0
                }

                object.value =
                    $buffer[$start++] |
                    $buffer[$start++] << 8

                return object
            }
        } ()
    }
}


text:
Voici un apercu de votre sélection

Cépages

                  {{preview[0].variety}}

Appellation

                  {{preview[0].appellation}}

{{preview[0].display_name}}

{{preview[0].region}} -  {{preview[0].vintage}}

En savoir plus

Cépages

                  {{preview[1].variety}}

Appellation

                  {{preview[1].appellation}}

{{preview[1].display_name}}

{{preview[1].region}} -  {{preview[1].vintage}}

En savoir plus

Cépages

                  {{preview[2].variety}}

Appellation

                  {{preview[2].appellation}}

{{preview[2].display_name}}

{{preview[2].region}} -  {{preview[2].vintage}}

En savoir plus

Recevez une sélection de 6 bouteilles différentes
 revue par notre oenologue pour 69 €

        <button class="button btn-square" ng-click="order('Vinibar')">Je veux 6 bouteilles choisies pour moi</button>

Découvrez la gamme Vinify
 avec ces 3 bouteilles pour 39 €

        <button class="button btn-square-o" ng-click="order('Découverte')">Je teste ces 3 bouteilles</button>


text:
package org.apache.eagle.security.userprofile;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigRenderOptions;
import org.apache.eagle.dataproc.impl.storm.kafka.KafkaSourcedSpoutProvider;
import org.apache.eagle.dataproc.util.ConfigOptionParser;
import org.apache.eagle.datastream.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class UserProfileDetectionStreamMain {
    private final static Logger LOG = LoggerFactory.getLogger(UserProfileDetectionStreamMain.class);

    public static void main(String[] args) throws Exception{
        Config config = new ConfigOptionParser().load(args);

        LOG.info("Config class: " + config.getClass().getCanonicalName());

        if(LOG.isDebugEnabled()) LOG.debug("Config content:"+config.root().render(ConfigRenderOptions.concise()));

        StormExecutionEnvironment env = ExecutionEnvironmentFactory.getStorm(config);
        env.newSource(new KafkaSourcedSpoutProvider().getSpout(config)).renameOutputFields(1).withName("kafkaMsgConsumer")
                .flatMap(new AuditLogTransformer()).withName("transformer")     // [user,map]
                .groupBy(Arrays.asList(0))                                      // group by [user]
                .flatMap(new UserProfileAggregatorExecutor()).withName("aggregator")
                .alertWithConsumer(Arrays.asList(UserProfileDetectionConstants.USER_ACTIVITY_AGGREGATION_STREAM),
                        UserProfileDetectionConstants.USER_PROFILE_ANOMALY_DETECTION_EXECUTOR); // alert
                ;
        env.execute();
    }

    private static class AuditLogTransformer extends JavaStormStreamExecutor2<String,Map<String,Object>> {
        @Override
        public void prepareConfig(Config config) {}

        @Override
        public void init() {}

        @Override
        public void flatMap(List<Object> input, Collector<Tuple2<String, Map<String, Object>>> collector) {
            Map<String, Object> auditLog = (Map<String, Object>) input.get(0);
            collector.collect(new Tuple2<>((String)auditLog.get("user"),auditLog));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:paddingBottom="7dp"
              android:paddingTop="7dp">

    <TextView
        android:id="@+id/header_text"
        style="@style/TextAppearance.AppCompat.Large"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?colorAccent"
        android:padding="7dp"
        android:text="@string/app_name"
        android:textColor="?android:textColorPrimaryInverse"/>

</LinearLayout>


text:
package com.jetbrains.python.inspections;

import com.jetbrains.python.fixtures.PyInspectionTestCase;
import com.jetbrains.python.psi.LanguageLevel;
import org.jetbrains.annotations.NotNull;

/**
 * User : catherine
 */
public class PyOldStyleClassInspectionTest extends PyInspectionTestCase {

  public void testSlot() {
    doTest();
  }

  public void testGetattr() {
    doTest();
  }

  public void testSuper() {
    doTest();
  }

  public void testSuper30() {
    runWithLanguageLevel(LanguageLevel.PYTHON30, this::doTest);
  }

  @NotNull
  @Override
  protected Class<? extends PyInspection> getInspectionClass() {
    return PyOldStyleClassesInspection.class;
  }

  @Override
  protected boolean isLowerCaseTestFile() {
    return false;
  }
}


text:
module: "@wq/map-gl"
---

# VectorTile

@wq/map-gl's `<VectorTile/>` [overlay component][overlay] displays one or more vector tile sources and layers.  It is similar to the [VectorTile basemap component][VectorTile-basemap], but can be added and removed without changing the base style.

## Source

This basemap type is only supported by [@wq/map-gl].

 * [VectorTile.js (@wq/map-gl)][mapgl-src]
 * [VectorTile.native.js (@wq/map-gl)][mapgl-native-src]
 * [VectorTile.expo.js (@wq/map-gl)][mapgl-expo-src]

[overlay]: ./index.md
[VectorTile-basemap]: ../basemaps/VectorTile.md
[@wq/map-gl]: ../@wq/map-gl.md

[mapgl-src]: https://github.com/wq/wq.app/blob/main/packages/map-gl/src/overlays/VectorTile.js
[mapgl-native-src]: https://github.com/wq/wq.app/blob/main/packages/map-gl/src/overlays/VectorTile.native.js
[mapgl-expo-src]: https://github.com/wq/wq.app/blob/main/packages/map-gl/src/overlays/VectorTile.expo.js


text:
*This image includes haproxy built with debug symbols and SLZ instead of zlib*

Dynamic haproxy configuration using consul packed into a Docker container that weighs 28MB.

<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc/generate-toc again -->
**Table of Contents**

- [haproxy-consul](#haproxy-consul)
- [Overview](#overview)
    - [How it works](#how-it-works)
    - [Building](#building)
    - [Running](#running)
        - [Modes](#modes)
            - [consul Configuration](#consul-configuration)
            - [Marathon Configuration](#marathon-configuration)
        - [Usage](#usage)
    - [Options](#options)
        - [SSL Termination](#ssl-termination)
- [License](#license)

<!-- markdown-toc end -->

# Overview

This project combines [Alpine Linux](https://www.alpinelinux.org), [consul template](https://github.com/hashicorp/consul-template), and [haproxy](http://haproxy.org)
to create a proxy that forwards traffic to apps registered in Marathon and forwarded with [marathon-consul](https://github.com/CiscoCloud/marathon-consul).

## How it works

First, you must set up a wildcard dns (using something like CloudFlare or [xip.io](http://xip.io)). This means that if your domain is `example.com`, any request to  a `<name>.example.com` will resolve to the IP of your haproxy container.

Inside the haproxy container, a header match is used to map `<application>.example.com` to the service registered in consul under `application`.

## Building

```
docker build -t haproxy .
```

## Running

### Modes

haproxy-consul can run in two different modes: forwarding either consul services
(the default) or Marathon apps. This behavior is controlled by the
`HAPROXY_MODE` variable, which should be set to `consul` or
`marathon`.

#### Reload configuration

It's possible to reload the HA proxy configuration without restarting the container itself.
`docker exec -it <container_id> bash reload.sh`

#### consul Configuration

When `HAPROXY_MODE` is set to `consul`, haproxy-consul uses consul service names
to set subdomains. No other configuration is required.

#### Marathon Configuration

When `HAPROXY_MODE` is set to `marathon`, haproxy-consul assumes that there will
be app information in the `marathon` prefix of the Consul KV store. It was
written to work with the information provided by
[marathon-consul](https://github.com/CiscoCloud/marathon-consul).

By default, haproxy will forward all Marathon-assigned ports. So if you specify
that your application should own port 10000 in the "ports" member of the app
JSON, haproxy will open port 10000 to direct traffic to your app. This works
with auto-assigned ports (ports set to 0), as well. This is all automatic, you
don't need to think about it other than to pull the ports from Marathon.

However, if you want HTTP load balancing using the host header, you need a
specify the following labels on your app:

```
{
    "id": "hello-rails",
    "cmd": "cd hello && bundle install && bundle exec unicorn -p $PORT",
    "mem": 100,
    "cpus": 1.0,
    "instances": 1,
    "uris": [
        "http://downloads.mesosphere.com/tutorials/RailsHello.tgz"
    ],
    "env": {
        "RAILS_ENV": "production"
    },
    "ports": [10000],
    "labels": {
        "HAPROXY_HTTP": "true",
        "HTTP_PORT_IDX_0_NAME": "hello_rails",
    }
}
```

In this example (available at [`examples/rails.json`](examples/rails.json)), the
hello-rails application is assigned port 10000. This is different from the
service or host port of the app; it is a global value that Marathon tracks. This
means that haproxy-consul will forward all TCP traffic to port 10000 to the app
workers.

When `HAPROXY_HTTP` is set to true and `HTTP_PORT_IDX_0_NAME` is set to a
DNS-valid name Haproxy will forward all HTTP traffic with the host header (the
name specified plus [`HAPROXY_DOMAIN`](#options)) to the app workers. This
extends to as many ports as you'd care to give it in the form
`HTTP_PORT_IDX_{port_number}_NAME`.

This particular app results in something like the following haproxy
configuration:

```
global
    maxconn 256
    debug

defaults
    mode tcp
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

# HTTP services
frontend www
    mode http
    bind *:80

    # files ACLs
    acl host_hello_rails hdr(host) -i hello_rails.haproxy.service.consul
    use_backend hello_rails_backend if host_hello_rails

# files backends
backend hello_rails_backend
    mode http
    server 1.2.3.4:49165 # TASK_RUNNING

# TCP services
listen hello-rails_10000
    mode tcp
    bind *:10000
    server task_id 1.2.3.4:41965 # TASK_RUNNING
```

### Usage

If you don't want to configure wildcard dns, you can use xip.io. In this example, we are going to assume that the IP of your server is `180.19.20.21`, then all domains in `180.19.20.21.xip.io` will forward to your host.

Start the container as follows:

```
docker run --net=host --name=haproxy -d -e HAPROXY_DOMAIN=180.19.20.21.xip.io asteris/haproxy-consul
```

If you have wildcard DNS set up for your company (say at `*.mycompany.com`) use the following:

```
docker run --net=host --name=haproxy -d -e HAPROXY_DOMAIN=mycompany.com asteris/haproxy-consul
```

Now that it is set up, connect to an app:

```
curl -L http://myapp.mycompany.com
```

Or if you do not have a wildcard DNS:

```
curl -L http://myapp.180.19.20.21.xip.io
```

## Options

If you want to override the config and template files, mount a volume and set the `CONSUL_CONFIG` environment variable before launch. In docker this can be accomplished with the `-e` option:

```
docker run -v /host/config:/my_config -e CONSUL_CONFIG=/my_config -net=host --name=haproxy -d -e HAPROXY_DOMAIN=mycompany.com asteris/haproxy-consul
```

If you need to have a root CA added so you can connect to Consul over SSL, mount
a directory containing your root CA at `/usr/local/share/ca-certificates/`.

Configure using the following environment variables:

Variable | Description | Default
---------|-------------|---------
`HAPROXY_DOMAIN` | The domain to match against | `haproxy.service.consul` (for `app.haproxy.service.consul`).
`HAPROXY_MODE` | forward consul service or Marathon apps | `consul` (`marathon` also available, as described [above](#modes))
`HAPROXY_USESSL` | Enable the SSL frontend (see [below](#ssl-termination)) | `false`
`HAPROXY_STATS` | Enable Statistics UI on port 1936 (see [below](#ssl-termination)) | `false`
`HAPROXY_STATS_TITLE` | Change Statistics Title (see [below](#ssl-termination)) | `false`
`HAPROXY_STATS_URI` | Change Statistics URI (see [below](#ssl-termination)) | `false`

consul-template variables:

Variable | Description | Default
---------|-------------|---------
`CONSUL_TEMPLATE` | Location of consul-template bin | `/usr/local/bin/consul-template`
`CONSUL_CONNECT`  | The consul connection | `consul.service.consul:8500`
`CONSUL_CONFIG`   | File/directory for consul-template config | `/consul-template/config.d`
`CONSUL_LOGLEVEL` | Valid values are "debug", "info", "warn", and "err". | `debug`
`CONSUL_TOKEN`    | The [Consul API token](http://www.consul.io/docs/internals/acl.html) |

consul KV variables:

Variable | Description | Default
---------|-------------|---------
`service/haproxy/maxconn` | maximum connections | 256
`service/haproxy/timeouts/connect` | connect timeout | 5000ms
`service/haproxy/timeouts/client` | client timeout | 50000ms
`service/haproxy/timeouts/server` | server timeout | 50000ms

### SSL Termination

If you wish to configure HAproxy to terminate incoming SSL connections, you must set the environment variable `HAPROXY_USESSL=true`, and mount your SSL certificate at `/haproxy/ssl.crt` - this file should contain both the SSL certificate and the private key to use (with no passphrase), in PEM format. You should also include any intermediate certificates in this bundle.

If you do not provide an SSL certificate at container runtime, a self-signed certificate will be generated for the value of `*.HAPROXY_DOMAIN`.

For example:
```
docker run -v /etc/ssl/wildcard.example.com.pem:/haproxy/ssl.crt -e HAPROXY_USESSL=true -e HAPROXY_DOMAIN=example.com --net=host --name=haproxy haproxy-consul
```

You can also force that all incoming connections are redirected to HTTPS, by setting `HAPROXY_USESSL=force`.

SSL termination is currently only available in 'consul' mode.

# License

Released under an Apache 2.0 License. See LICENSE


text:
  Se pueden usar comodines como 'module/dist/**/*.zip'. Echa un vistazo al

    atributo @includes de la etiqueta fileset de Ant

  para conocer el formato exacto. El directorio base es
  el workspace
  .


text:
import {Component} from '@angular/core';

@Component({
  selector: 'myprocesses',
  styles: [],
  template: `<router-outlet></router-outlet>`
})
export class MyProcesses {

  constructor() {
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Pull</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//NadineLaCuisine.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//NadineLaCuisine.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://NadineLaCuisine.github.io/2015/09/17/Pull.html" />

    <meta property="og:site_name" content="Awesome Title" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Pull" />
    <meta property="og:description" content="Clic pour voir la photo nadine Over..." />
    <meta property="og:url" content="https://NadineLaCuisine.github.io/2015/09/17/Pull.html" />
    <meta property="article:published_time" content="2015-09-16T22:00:00.000Z" />
    <meta property="article:modified_time" content="2015-09-18T00:24:15.420Z" />
    <meta property="article:tag" content="Mode" />
    <meta property="article:tag" content="Robe" />
    <meta property="article:tag" content="Pull" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Pull" />
    <meta name="twitter:description" content="Clic pour voir la photo nadine Over..." />
    <meta name="twitter:url" content="https://NadineLaCuisine.github.io/2015/09/17/Pull.html" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Awesome Title" href="https://NadineLaCuisine.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

Pull

                <time class="post-date" datetime="2015-09-17">17 September 2015</time>  on Mode,  Robe,  Pull

Clic pour voir la photo nadine

Over

                's Picture

Read more posts by this author.

Share this post

                    Twitter

                    Facebook

                    Google+

Awesome Title © 2015

Proudly published with HubPress


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Rdio -> Spotify</title>
    <link rel="stylesheet" type="text/css" href="./app/dist/styles.css">

    <input type="file" id="csv-upload">


text:
<?php
include 'functions/advertisement_functions.php';
require_once 'conf/smarty-conf.php';
include 'functions/admin_functions.php';

if ($_REQUEST['job']=="login"){

	$login=$_POST['login'];
	$passcode=$_POST['password'];

	if (check_admin_login($login, $passcode)==1){

		$user_info=get_admin_info($login);
		$_SESSION['admin_login']=1;
		$_SESSION['user_name']=$login;
		$_SESSION['user_id']=$user_info['id'];

		$smarty->assign('page',"Login");
		$smarty->display('admin/admin_index.tpl');
	}

	else {

		$smarty->assign('error',"Incorrect Login Details!");
		$smarty->display('admin/login.tpl');
	}

}

elseif ($_REQUEST['job']=="logout"){

	unset($_SESSION['admin_login']);
	unset($_SESSION['user_name']);
	unset($_SESSION['user_id']);

	$smarty->display('admin/login.tpl');

}

else{
	$smarty->display('admin/login.tpl');
}