text:
package org.xnio.http;

import static org.xnio.IoUtils.safeClose;
import static org.xnio._private.Messages.msg;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.xnio.ChannelExceptionHandler;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.FutureResult;
import org.xnio.IoFuture;
import org.xnio.OptionMap;
import org.xnio.Pooled;
import org.xnio.StreamConnection;
import org.xnio.XnioWorker;
import org.xnio.channels.BoundChannel;
import org.xnio.conduits.ConduitStreamSinkChannel;
import org.xnio.ssl.SslConnection;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.conduits.PushBackStreamSourceConduit;
import org.xnio.conduits.StreamSourceConduit;
import org.xnio.ssl.XnioSsl;

/**
 * Simple HTTP client that can perform a HTTP upgrade. This is not a general purpose HTTP
 * client, all it can do is upgrade a HTTP
 *
 * @author Stuart Douglas
 */
public class HttpUpgrade {

    /**
     * Perform a HTTP upgrade that results in a SSL secured connection. This method should be used if the target endpoint is using https
     *
     * @param worker           The worker
     * @param ssl              The XnioSsl instance
     * @param bindAddress      The bind address
     * @param uri              The URI to connect to
     * @param headers          Any additional headers to include in the upgrade request. This must include an Upgrade header that specifies the type of upgrade being performed
     * @param openListener     The open listener that is invoked once the HTTP upgrade is done
     * @param bindListener     The bind listener that is invoked when the socket is bound
     * @param optionMap        The option map for the connection
     * @param handshakeChecker A handshake checker that can be supplied to verify that the server returned a valid response to the upgrade request
     * @return An IoFuture of the connection
     */
    public static IoFuture<SslConnection> performUpgrade(final XnioWorker worker, XnioSsl ssl, InetSocketAddress bindAddress, URI uri, final Map<String, String> headers, ChannelListener<? super SslConnection> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap, HandshakeChecker handshakeChecker) {
        return new HttpUpgradeState<SslConnection>(worker, ssl, bindAddress, uri, headers, openListener, bindListener, optionMap, handshakeChecker).doUpgrade();
    }

    /**
     * Connects to the target server using HTTP upgrade.
     *
     * @param worker           The worker
     * @param bindAddress      The bind address
     * @param uri              The URI to connect to
     * @param headers          Any additional headers to include in the upgrade request. This must include an Upgrade header that specifies the type of upgrade being performed
     * @param openListener     The open listener that is invoked once the HTTP upgrade is done
     * @param bindListener     The bind listener that is invoked when the socket is bound
     * @param optionMap        The option map for the connection
     * @param handshakeChecker A handshake checker that can be supplied to verify that the server returned a valid response to the upgrade request
     * @return An IoFuture of the connection
     */
    public static IoFuture<StreamConnection> performUpgrade(final XnioWorker worker, InetSocketAddress bindAddress, URI uri, final Map<String, String> headers, ChannelListener<? super StreamConnection> openListener, ChannelListener<? super BoundChannel> bindListener, OptionMap optionMap, HandshakeChecker handshakeChecker) {
        return new HttpUpgradeState<StreamConnection>(worker, null, bindAddress, uri, headers, openListener, bindListener, optionMap, handshakeChecker).doUpgrade();
    }

    /**
     * Performs a HTTP upgrade on an existing connection.
     *
     * @param connection       The existing connection to upgrade
     * @param uri              The URI to connect to
     * @param headers          Any additional headers to include in the upgrade request. This must include an Upgrade header that specifies the type of upgrade being performed
     * @param openListener     The open listener that is invoked once the HTTP upgrade is done
     * @param handshakeChecker A handshake checker that can be supplied to verify that the server returned a valid response to the upgrade request
     * @return An IoFuture of the connection
     */
    public static <T extends StreamConnection> IoFuture<T> performUpgrade(final T connection, URI uri, final Map<String, String> headers, ChannelListener<? super StreamConnection> openListener, HandshakeChecker handshakeChecker) {
        return new HttpUpgradeState<T>(connection, uri, headers, openListener, handshakeChecker).upgradeExistingConnection();
    }

    private HttpUpgrade() {

    }

    private static class HttpUpgradeState<T extends StreamConnection> {

        private final XnioWorker worker;
        private final XnioSsl ssl;
        private final InetSocketAddress bindAddress;
        private final URI uri;
        private final Map<String, String> headers;
        private final ChannelListener<? super T> openListener;
        private final ChannelListener<? super BoundChannel> bindListener;
        private final OptionMap optionMap;
        private final HandshakeChecker handshakeChecker;
        private final FutureResult<T> future = new FutureResult<T>();
        private T connection;

        private HttpUpgradeState(final XnioWorker worker, final XnioSsl ssl, final InetSocketAddress bindAddress, final URI uri, final Map<String, String> headers, final ChannelListener<? super T> openListener, final ChannelListener<? super BoundChannel> bindListener, final OptionMap optionMap, final HandshakeChecker handshakeChecker) {
            this.worker = worker;
            this.ssl = ssl;
            this.bindAddress = bindAddress;
            this.uri = uri;
            this.headers = headers;
            this.openListener = openListener;
            this.bindListener = bindListener;
            this.optionMap = optionMap;
            this.handshakeChecker = handshakeChecker;
        }

        public HttpUpgradeState(final T connection, final URI uri, final Map<String, String> headers, final ChannelListener<? super StreamConnection> openListener, final HandshakeChecker handshakeChecker) {
            this.worker = connection.getWorker();
            this.ssl = null;
            this.bindAddress = null;
            this.uri = uri;
            this.headers = headers;
            this.openListener = openListener;
            this.bindListener = null;
            this.optionMap = OptionMap.EMPTY;
            this.handshakeChecker = handshakeChecker;
            this.connection = connection;
        }

        private IoFuture<T> doUpgrade() {
            InetSocketAddress address = new InetSocketAddress(uri.getHost(), uri.getPort());

            final ChannelListener<StreamConnection> connectListener = new ConnectionOpenListener();
            final String scheme = uri.getScheme();
            if (scheme.equals("http")) {
                if (bindAddress == null) {
                    worker.openStreamConnection(address, connectListener, bindListener, optionMap).addNotifier(new FailureNotifier(), null);
                } else {
                    worker.openStreamConnection(bindAddress, address, connectListener, bindListener, optionMap).addNotifier(new FailureNotifier(), null);
                }
            } else if (scheme.equals("https")) {
                if (ssl == null) {
                    throw msg.missingSslProvider();
                }
                if (bindAddress == null) {
                    ssl.openSslConnection(worker, address, connectListener, bindListener, optionMap).addNotifier(new FailureNotifier(), null);
                } else {
                    ssl.openSslConnection(worker, bindAddress, address, connectListener, bindListener, optionMap).addNotifier(new FailureNotifier(), null);
                }
            } else {
                throw msg.invalidURLScheme(scheme);
            }
            return future.getIoFuture();
        }

        private String buildHttpRequest() {

            final StringBuilder builder = new StringBuilder();
            builder.append("GET ");
            builder.append(uri.getPath().isEmpty() ? "/" : uri.getPath());
            builder.append(" HTTP/1.1\r\n");
            final Set<String> seen = new HashSet<String>();
            for (Map.Entry<String, String> header : headers.entrySet()) {
                builder.append(header.getKey());
                builder.append(": ");
                builder.append(header.getValue());
                builder.append("\r\n");
                seen.add(header.getKey().toLowerCase(Locale.ENGLISH));
            }
            if (!seen.contains("host")) {
                builder.append("Host: ");
                builder.append(getHost());
                builder.append("\r\n");
            }
            if (!seen.contains("connection")) {
                builder.append("Connection: upgrade\r\n");
            }
            if (!seen.contains("upgrade")) {
                throw new IllegalArgumentException("Upgrade: header was not supplied in header arguments");
            }
            builder.append("\r\n");
            return builder.toString();
        }

        private String getHost() {
            String scheme = uri.getScheme();
            int port = uri.getPort();

            if (port < 0 || "http".equals(scheme) && port == 80 || "https".equals(scheme) && port == 443) {
                // No port or default port.
                return uri.getHost();
            }

            return uri.getHost() + ":" + port;
        }

        public IoFuture<T> upgradeExistingConnection() {
            final ChannelListener<StreamConnection> connectListener = new ConnectionOpenListener();
            connectListener.handleEvent(connection);
            return future.getIoFuture();
        }

        private class ConnectionOpenListener implements ChannelListener<StreamConnection> {
            @Override
            public void handleEvent(final StreamConnection channel) {
                connection = (T) channel;
                final ByteBuffer buffer = ByteBuffer.wrap(buildHttpRequest().getBytes());
                int r;
                do {
                    try {
                        r = channel.getSinkChannel().write(buffer);
                        if (r == 0) {
                            channel.getSinkChannel().getWriteSetter().set(new StringWriteListener(buffer));
                            channel.getSinkChannel().resumeWrites();
                            return;
                        }
                    } catch (IOException e) {
                        safeClose(channel);
                        future.setException(e);
                        return;
                    }
                } while (buffer.hasRemaining());
                flushUpgradeChannel();
            }
        }

        private void flushUpgradeChannel() {
            try {
                if(!connection.getSinkChannel().flush()) {

                    connection.getSinkChannel().getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
                        @Override
                        public void handleEvent(StreamSinkChannel channel) {
                            channel.suspendWrites();
                            new UpgradeResultListener().handleEvent(connection.getSourceChannel());
                        }
                    }, new ChannelExceptionHandler<StreamSinkChannel>() {
                        @Override
                        public void handleException(StreamSinkChannel channel, IOException exception) {
                            safeClose(channel);
                            future.setException(exception);
                        }
                    }));
                    connection.getSinkChannel().resumeWrites();
                    return;
                }
            } catch (IOException e) {
                safeClose(connection);
                future.setException(e);
                return;
            }
            new UpgradeResultListener().handleEvent(connection.getSourceChannel());
        }

        private final class StringWriteListener implements ChannelListener<StreamSinkChannel> {

            final ByteBuffer buffer;

            private StringWriteListener(final ByteBuffer buffer) {
                this.buffer = buffer;
            }

            @Override
            public void handleEvent(final StreamSinkChannel channel) {
                int r;
                do {
                    try {
                        r = channel.write(buffer);
                        if (r == 0) {
                            return;
                        }
                    } catch (IOException e) {
                        safeClose(channel);
                        future.setException(e);
                        return;
                    }
                } while (buffer.hasRemaining());
                channel.suspendWrites();
                flushUpgradeChannel();
            }
        }

        private final class UpgradeResultListener implements ChannelListener<StreamSourceChannel> {

            private final HttpUpgradeParser parser = new HttpUpgradeParser();
            private ByteBuffer buffer = ByteBuffer.allocate(1024);

            @Override
            public void handleEvent(final StreamSourceChannel channel) {
                int r;
                do {
                    try {
                        buffer.compact();
                        r = channel.read(buffer);
                        if (r == 0) {
                            channel.getReadSetter().set(this);
                            channel.resumeReads();
                            return;
                        } else if (r == -1) {
                            throw msg.connectionClosedEarly();
                        }
                        buffer.flip();
                        parser.parse(buffer);
                    } catch (IOException e) {
                        safeClose(channel);
                        future.setException(e);
                        return;
                    }

                } while (!parser.isComplete());
                channel.suspendReads();

                if (buffer.hasRemaining()) {
                    StreamSourceConduit orig = connection.getSourceChannel().getConduit();
                    PushBackStreamSourceConduit pushBack = new PushBackStreamSourceConduit(orig);
                    pushBack.pushBack(new Pooled<ByteBuffer>() {
                        @Override
                        public void discard() {
                            buffer = null;
                        }

                        @Override
                        public void free() {
                            buffer = null;
                        }

                        @Override
                        public ByteBuffer getResource() throws IllegalStateException {
                            return buffer;
                        }

                        @Override
                        public void close() {
                            free();
                        }
                    });
                    connection.getSourceChannel().setConduit(pushBack);
                }

                //ok, we have a response
                if (parser.getResponseCode() == 101) { // Switching Protocols
                    handleUpgrade(parser);
                } else if (parser.getResponseCode() == 301 || // Moved Permanently
                        parser.getResponseCode() == 302 || // Found
                        parser.getResponseCode() == 303 || // See Other
                        parser.getResponseCode() == 307 || // Temporary Redirect
                        parser.getResponseCode() == 308) { // Permanent Redirect
                    handleRedirect(parser, channel);
                } else {
                    future.setException(new IOException("Invalid response code " + parser.getResponseCode()));
                }
            }
        }

        private void handleUpgrade(final HttpUpgradeParser parser) {
            final String contentLength = parser.getHeaders().get("content-length");
            if (contentLength != null) {
                if (!"0".equals(contentLength)) {
                    future.setException(new IOException("Upgrade responses must have a content length of zero."));
                    return;
                }
            }
            final String transferCoding = parser.getHeaders().get("transfer-encoding");
            if (transferCoding != null) {
                future.setException(new IOException("Upgrade responses cannot have a transfer coding"));
                return;
            }

            if (handshakeChecker != null) {
                try {
                    handshakeChecker.checkHandshake(parser.getHeaders());
                } catch (IOException e) {
                    safeClose(connection);
                    future.setException(e);
                    return;
                }
            }
            future.setResult(connection);
            ChannelListeners.invokeChannelListener(connection, openListener);
        }

        private void handleRedirect(final HttpUpgradeParser parser, final StreamSourceChannel channel) {
            safeClose(channel);
            future.setException(new RedirectException(msg.redirect(), parser.getResponseCode(), parser.getHeaders().get("location")));
        }

        private class FailureNotifier extends IoFuture.HandlingNotifier<StreamConnection, Object> {
            @Override
            public void handleFailed(IOException exception, Object attachment) {
                future.setException(exception);
            }

            @Override
            public void handleCancelled(Object attachment) {
                future.setCancelled();
            }
        }
    }
}


text:
require File.dirname(__FILE__) + '/../../../spec_helper'

describe "/links/edit.html.haml" do
  include Admin::LinksHelper

  before do
    @link = mock_model(Link)
    @link.stub!(:url).and_return("MyString")
    @link.stub!(:title).and_return("MyString")
    assigns[:link] = @link
  end

  it "should render edit form" do
    render "/admin/links/edit.html.haml"

    response.should have_tag("form[action=#{admin_link_path(@link)}][method=post]") do
      with_tag('input#link_url[name=?]', "link[url]")
      with_tag('input#link_title[name=?]', "link[title]")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
import base64
import json
import websocket

class WebsocketClient(object):
    def __init__(self, url, username=None, password=None, headers={}, enable_trace=False,
                 timeout=60):
        """Simple Web socket client for wrapanapi

       Args:
           url: String with the hostname or IP address of the server with port
            (e.g. 'ws://10.11.12.13:8080/hawkular/command-gateway/ui/ws')
           username: username for basic auth (optional)
           password: password for basic auth
           headers: When you want to pass specified header use this
           enable_trace: Enable trace on web socket client
           timeout: receive timeout in seconds
       """
        self.url = url
        self.username = username
        self.password = password
        self.headers = headers
        self.enable_trace = enable_trace
        self.timeout = timeout
        self.ws = None

    def connect(self):
        """connects with the initialized detail"""
        if self.ws and self.ws.connected:
            return self.ws
        else:
            websocket.enableTrace(self.enable_trace)
            if self.username:
                base64_creds = base64.b64encode("{}:{}".format(self.username, self.password))
                self.headers.update({"Authorization": "Basic {}".format(base64_creds)})
            self.ws = websocket.create_connection(self.url, header=self.headers)
            self.ws.settimeout(self.timeout)

    @property
    def connected(self):
        """Returns True if client connected with server"""
        if self.ws and self.ws.connected:
            return True
        return False

    def close(self):
        """Close the current connection"""
        if self.ws and self.ws.connected:
            self.ws.close()

    def _check_connection(self, make_connection=True):
        """Check client connected with server

        Args:
            make_connection: by default True. Creates connection if not connected
        """
        if self.connected:
            return
        elif make_connection:
            self.connect()
            if self.connected:
                return
        raise RuntimeError("WS client not connected!")

    def send(self, payload, binary_stream=False):
        """Send payload to server
        Args:
            payload: payload, string or binary
            binary_stream: dafault False. Set this True when you send binary payload
        """
        self._check_connection()
        if binary_stream:
            self.ws.send_binary(payload=payload)
        else:
            self.ws.send(payload=payload)

    def receive(self):
        """Returns available message on received queue. If there is no message.
         waits till timeout"""
        self._check_connection()
        return self.ws.recv()

class HawkularWebsocketClient(WebsocketClient):
    """This client extended from normal websocket client. designed to hawkular specific"""
    def __init__(self, url, username=None, password=None, headers={}, enable_trace=False,
                 timeout=60):
        """Creates hawkular web socket client. for arguments refer 'WebsocketClient'"""
        super(HawkularWebsocketClient, self).__init__(url=url, username=username, password=password,
                                                      headers=headers, enable_trace=enable_trace,
                                                      timeout=timeout)
        self.session_id = None

    def connect(self):
        """Create connection with hawkular web socket server"""
        super(HawkularWebsocketClient, self).connect()
        response = self.hwk_receive()
        if 'WelcomeResponse' in response:
            self.session_id = response['WelcomeResponse']['sessionId']
            return response['WelcomeResponse']
        else:
            raise RuntimeWarning("Key 'WelcomeResponse' not found on response: {}".format(response))
            return response

    def hwk_receive(self):
        """parse recevied message and returns as dictionary value"""
        payload = self.receive()
        data = payload.split('=', 1)
        if len(data) != 2:
            raise IndentationError("Unknown payload format! {}".format(payload))
        response = {data[0]: json.loads(data[1])}
        if 'GenericErrorResponse' in response:
            raise Exception("Hawkular server sent failure message: {}"
                            .format(response['GenericErrorResponse']))
        return response

    def hwk_invoke_operation(self, payload, operation_name="ExecuteOperation", binary_content=None,
                             binary_file_location=None, wait_for_response=True):
        """Runs hawkular specific operations
        Args:
            payload: payload to server. only string
            operation_name: requested operation. default: ExecuteOperation
            binary_content: binary content
            binary_file_location: binary content file name. Will be changed as binary content
            wait_for_response: When executing a command, wait for the response. default: True

        """
        _payload = "{}Request={}".format(operation_name, json.dumps(payload))
        if binary_file_location:
            binary_content = open(binary_file_location, 'rb').read()
        if binary_content:
            self.send(_payload + binary_content, binary_stream=True)
        else:
            self.send(_payload, binary_stream=False)
        if wait_for_response:
            responses = []
            response = self.hwk_receive()
            responses.append(response)
            if "GenericSuccessResponse" in response:
                responses.append(self.hwk_receive())
            return responses


text:
package swarm

import (
	"fmt"
	"testing"

	docker_types "github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/swarm"
	mock_client "github.com/docker/infrakit/pkg/mock/docker/docker/client"
	"github.com/docker/infrakit/pkg/spi/group"
	"github.com/docker/infrakit/pkg/spi/instance"
	"github.com/docker/infrakit/pkg/types"
	"github.com/docker/infrakit/pkg/util/docker"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/require"
)

func TestManagerDrain(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	selfAddr := "10.20.100.1"
	self := instance.LogicalID(selfAddr)
	managerStop := make(chan struct{})

	client := mock_client.NewMockAPIClientCloser(ctrl)

	flavorImpl := NewManagerFlavor(scp, func(Spec) (docker.APIClientCloser, error) {
		return client, nil
	}, templ(DefaultManagerInitScriptTemplate), managerStop)

	swarmInfo := swarm.Swarm{
		ClusterInfo: swarm.ClusterInfo{
			ID: "ClusterUUID",
			Meta: swarm.Meta{
				Version: swarm.Version{Index: uint64(9999)},
			},
		},
		JoinTokens: swarm.JoinTokens{
			Manager: "ManagerToken",
			Worker:  "WorkerToken",
		},
	}

	client.EXPECT().Close().AnyTimes()
	client.EXPECT().SwarmInspect(gomock.Any()).Return(swarmInfo, nil).AnyTimes()
	client.EXPECT().Info(gomock.Any()).Return(infoResponse, nil).AnyTimes()

	flavorProperties := types.AnyString("")
	index := group.Index{Group: group.ID("group"), Sequence: 0}
	id := self

	// manager self info
	nodeInfo := swarm.Node{ManagerStatus: &swarm.ManagerStatus{Addr: selfAddr}}
	client.EXPECT().NodeInspectWithRaw(gomock.Any(), nodeID).Return(nodeInfo, nil, nil)

	details, err := flavorImpl.Prepare(flavorProperties,
		instance.Spec{Tags: map[string]string{"a": "b"}, LogicalID: &id},
		group.AllocationMethod{LogicalIDs: []instance.LogicalID{id}},
		index)
	require.NoError(t, err)

	link := types.NewLinkFromMap(details.Tags)
	associationID := link.Value()
	associationTag := link.Label()

	filter, err := filters.FromParam(fmt.Sprintf(`{"label": {"%s=%s": true}}`, associationTag, associationID))
	require.NoError(t, err)

	// Do a drain
	swarmNodeID := "swarm-id-1"
	swarmNodeVersion := swarm.Version{Index: uint64(1234)}
	client.EXPECT().NodeList(gomock.Any(),
		docker_types.NodeListOptions{Filters: filter}).Return(
		[]swarm.Node{
			{ID: swarmNodeID},
		},
		nil)
	client.EXPECT().NodeInspectWithRaw(gomock.Any(), swarmNodeID).Return(
		swarm.Node{
			ID:   swarmNodeID,
			Spec: swarm.NodeSpec{Role: swarm.NodeRoleManager},
			Meta: swarm.Meta{Version: swarmNodeVersion},
		},
		nil,
		nil,
	)
	// Should be changed to a woker
	client.EXPECT().NodeUpdate(gomock.Any(), swarmNodeID, swarmNodeVersion, swarm.NodeSpec{Role: swarm.NodeRoleWorker}).Return(nil)

	err = flavorImpl.Drain(flavorProperties,
		instance.Description{
			LogicalID: &id,
			Tags:      map[string]string{associationTag: associationID},
		})
	require.NoError(t, err)

	close(managerStop)
}

func TestManagerDrainNotInSwarm(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	selfAddr := "10.20.100.2"
	self := instance.LogicalID(selfAddr)
	managerStop := make(chan struct{})

	client := mock_client.NewMockAPIClientCloser(ctrl)

	flavorImpl := NewManagerFlavor(scp, func(Spec) (docker.APIClientCloser, error) {
		return client, nil
	}, templ(DefaultManagerInitScriptTemplate), managerStop)

	swarmInfo := swarm.Swarm{
		ClusterInfo: swarm.ClusterInfo{
			ID: "ClusterUUID",
			Meta: swarm.Meta{
				Version: swarm.Version{Index: uint64(9999)},
			},
		},
		JoinTokens: swarm.JoinTokens{
			Manager: "ManagerToken",
			Worker:  "WorkerToken",
		},
	}

	client.EXPECT().Close().AnyTimes()
	client.EXPECT().SwarmInspect(gomock.Any()).Return(swarmInfo, nil).AnyTimes()
	client.EXPECT().Info(gomock.Any()).Return(infoResponse, nil).AnyTimes()

	flavorProperties := types.AnyString("")
	index := group.Index{Group: group.ID("group"), Sequence: 0}
	id := self

	// manager self info
	nodeInfo := swarm.Node{ManagerStatus: &swarm.ManagerStatus{Addr: selfAddr}}
	client.EXPECT().NodeInspectWithRaw(gomock.Any(), nodeID).Return(nodeInfo, nil, nil)

	details, err := flavorImpl.Prepare(flavorProperties,
		instance.Spec{Tags: map[string]string{"a": "b"}, LogicalID: &id},
		group.AllocationMethod{LogicalIDs: []instance.LogicalID{id}},
		index)
	require.NoError(t, err)

	link := types.NewLinkFromMap(details.Tags)
	associationID := link.Value()
	associationTag := link.Label()

	filter, err := filters.FromParam(fmt.Sprintf(`{"label": {"%s=%s": true}}`, associationTag, associationID))
	require.NoError(t, err)

	// Do a drain, no nodes returned
	client.EXPECT().NodeList(gomock.Any(),
		docker_types.NodeListOptions{Filters: filter}).Return(
		[]swarm.Node{},
		nil)
	err = flavorImpl.Drain(flavorProperties,
		instance.Description{
			LogicalID: &id,
			Tags:      map[string]string{associationTag: associationID},
		})
	require.NoError(t, err)

	close(managerStop)
}

func TestManagerDrainNotManager(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	selfAddr := "10.20.100.2"
	self := instance.LogicalID(selfAddr)
	managerStop := make(chan struct{})

	client := mock_client.NewMockAPIClientCloser(ctrl)

	flavorImpl := NewManagerFlavor(scp, func(Spec) (docker.APIClientCloser, error) {
		return client, nil
	}, templ(DefaultManagerInitScriptTemplate), managerStop)

	swarmInfo := swarm.Swarm{
		ClusterInfo: swarm.ClusterInfo{
			ID: "ClusterUUID",
			Meta: swarm.Meta{
				Version: swarm.Version{Index: uint64(9999)},
			},
		},
		JoinTokens: swarm.JoinTokens{
			Manager: "ManagerToken",
			Worker:  "WorkerToken",
		},
	}

	client.EXPECT().Close().AnyTimes()
	client.EXPECT().SwarmInspect(gomock.Any()).Return(swarmInfo, nil).AnyTimes()
	client.EXPECT().Info(gomock.Any()).Return(infoResponse, nil).AnyTimes()

	flavorProperties := types.AnyString("")
	index := group.Index{Group: group.ID("group"), Sequence: 0}
	id := self

	// manager self info
	nodeInfo := swarm.Node{ManagerStatus: &swarm.ManagerStatus{Addr: selfAddr}}
	client.EXPECT().NodeInspectWithRaw(gomock.Any(), nodeID).Return(nodeInfo, nil, nil)

	details, err := flavorImpl.Prepare(flavorProperties,
		instance.Spec{Tags: map[string]string{"a": "b"}, LogicalID: &id},
		group.AllocationMethod{LogicalIDs: []instance.LogicalID{id}},
		index)
	require.NoError(t, err)

	link := types.NewLinkFromMap(details.Tags)
	associationID := link.Value()
	associationTag := link.Label()

	filter, err := filters.FromParam(fmt.Sprintf(`{"label": {"%s=%s": true}}`, associationTag, associationID))
	require.NoError(t, err)

	// Do a drain, the node should not be changed
	swarmNodeID := "swarm-id-1"
	swarmNodeVersion := swarm.Version{Index: uint64(1234)}
	client.EXPECT().NodeList(gomock.Any(),
		docker_types.NodeListOptions{Filters: filter}).Return(
		[]swarm.Node{
			{ID: swarmNodeID},
		},
		nil)
	client.EXPECT().NodeInspectWithRaw(gomock.Any(), swarmNodeID).Return(
		swarm.Node{
			ID:   swarmNodeID,
			Spec: swarm.NodeSpec{Role: swarm.NodeRoleWorker},
			Meta: swarm.Meta{Version: swarmNodeVersion},
		},
		nil,
		nil,
	)

	err = flavorImpl.Drain(flavorProperties,
		instance.Description{
			LogicalID: &id,
			Tags:      map[string]string{associationTag: associationID},
		})
	require.NoError(t, err)

	close(managerStop)
}


text:
package com.hellodev.lightme.util;

import java.util.Calendar;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.hellodev.lightme.FlashApp;
import com.hellodev.lightme.R;
import com.meizu.mstore.license.ILicensingService;
import com.meizu.mstore.license.LicenseCheckHelper;
import com.meizu.mstore.license.LicenseResult;

public class MLisenseMangaer {
	private final static String TAG = "MLisenseMangaer";

	public final static int STATE_UNKNOWN = 0;
	public final static int STATE_PURCHASED = 1;
	public final static int STATE_TRYING = 2;
	public final static int STATE_EXPIRED = 3;

	public final static int EXPIRE_DAYS = 3;
	public final static String APK_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCB4xYVRA7w13J6dBWA+oERVDRnefb8J5N7zeD3e6JfExk76F59YRDbmDVPL+ztwwboy+R3RSQKIHM/DYymqAHnbq4m/tKXCS6BcL9MeH6Cc2xas2dNNfzOjDrb/5oqvzHI+0TPX3gU2ZML3Udsw4Q+QT+jYOgLbMYfbps3OZne5QIDAQAB/wJQnyPGfR72CNv5zR+qA4qjxSMBUSQh55awBgR4Jrwd3G+6/yH540pB/oP+GsTp0Sof/dEFaR85968aEhBGRcnpEl9OITISZRwMp654/LD6kzdsjMBjfPXiYRSLjygcbG//gOVxZbnmU2Nz5pnuFvav8wIDAQAB";

	private Context mContext;
	// 服务的实例对象
	private ILicensingService mLicensingService = null;
	private OnLisenseStateChangeListener mListener;

	public MLisenseMangaer() {
		// for local check
		this(null);
	}

	public MLisenseMangaer(OnLisenseStateChangeListener listener) {
		mListener = listener;
		mContext = FlashApp.getContext();
	}

	// 服务绑定的回调,可用于判断服务是否绑定成功
	private ServiceConnection mLicenseConnection = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			if (mListener != null)
				mListener.onRemoteServiceDisconnected();
			mLicensingService = null;
		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.v(TAG, "服务绑定成功,获取服务实例");
			mLicensingService = ILicensingService.Stub.asInterface(service);
			if (mListener != null)
				mListener.onRemoteServiceConnected();
		}
	};

	public void bindRemoteService() {
		if (mLicensingService == null) {
			// 绑定服务
			Intent serviceIntent = new Intent();
			serviceIntent.setAction(ILicensingService.class.getName());
			mContext.bindService(serviceIntent, mLicenseConnection,
					Context.BIND_AUTO_CREATE);
		} else {
			if (mListener != null)
				mListener.onRemoteServiceConnected();
		}
	}

	public void unbindRemoteService() {
		// 如果服务已经绑定,在退出时需要反绑服务
		if (mLicensingService != null) {
			mContext.unbindService(mLicenseConnection);
		}
	}

	// doCheck()方法演示了如何使用license服务来验证授权是否合法
	public int doRemoteCheck() {

		// 该第三方应用的包名,可使用getApplication().getPackageName()获取本应用包名
		final String packageName = mContext.getPackageName();

		// 保存服务验证的结果值
		LicenseResult result = null;
		int lisenseState = STATE_UNKNOWN;
		if (mLicensingService != null) {
			try {
				// 调用服务接口进行验证,获取返回的结果值
				// FIXME 为什么有的时候为空
				result = mLicensingService.checkLicense(packageName);
			} catch (RemoteException e) {
				Log.e(TAG, "获取证书失败");
				// 作为UNKNOWN来处理,这种异常不需要显示错误
				lisenseState = STATE_TRYING;
			}

			if (result != null
					&& result.getResponseCode() == LicenseResult.RESPONSE_CODE_SUCCESS) {
				// license验证服务验证通过,需要接着对服务返回的结果再次进行校验(使用自己的公钥进行验证)
				boolean bSuccess = LicenseCheckHelper.checkResult(
						APK_PUBLIC_KEY, result);

				if (bSuccess
						&& result.getPurchaseType() == LicenseResult.PURCHASE_TYPE_NORMAL) {
					// 验证成功,并且为正式版本
					lisenseState = STATE_PURCHASED;

					// FIXME 获取子产品
				} else if (result.getPurchaseType() == LicenseResult.PURCHASE_TYPE_TRIAL) {
					// 验证成功,是试用版本
					// 该方法返回license文件的生成日期(注:该日期的值只精确到天,即时分秒为随机值)
					Calendar beginCal = result.getStartDate();
					// Log.v("", "试用开始的日期为: " + beginCal.get(Calendar.YEAR) +
					// "年"
					// + (beginCal.get(Calendar.MONTH) + 1) + "月"
					// + beginCal.get(Calendar.DAY_OF_MONTH) + "日");
					/**
					 * 以下是可供参考的过期判断
					 */
					// 你自己定义的过期天数
					final int expireDays = 3;
					// 获取当前日期
					Calendar nowCal = Calendar.getInstance();
					// 求剩余的天数
					long dif = nowCal.getTimeInMillis()
							- beginCal.getTimeInMillis();
					int passDay = (int) (dif / (24 * 60 * 60 * 1000));
					int left = expireDays - passDay;
					if (left > 0) {
						// 未过期
						Log.v(TAG, "未过期");
						lisenseState = STATE_TRYING;
					} else {
						// 过期
						Log.e(TAG, "过期");
						lisenseState = STATE_EXPIRED;
					}
					// FIXME 获取子产品
				} else {
					// 验证不成功或者版本类型不对,可按试用版处理
					// FIXME 状态一定要对,作为UNKNOWN来处理
					lisenseState = STATE_TRYING;
					Log.e(TAG, "license验证不通过");
				}
			} else {
				// license验证服务验证不通过
				lisenseState = STATE_UNKNOWN;// 用友盟来统计?
				if (result!= null && result.getResponseCode() == LicenseResult.RESPONSE_CODE_NO_LICENSE_FILE) {
					// 不存在与应用对应的license文件
					Log.e(TAG, "无对应的license文件");
				} else {
					// license文件无效
					Log.e(TAG, "license文件无效");
				}
			}
		}
		MPreferenceManager.getInstance().setLocalLisenseState(lisenseState);
		return lisenseState;
	}

	public static String getLisenseInfo(int lisenseState) {
		Resources resource = FlashApp.getContext().getResources();
		String lisenseInfo;
		switch (lisenseState) {
		case STATE_TRYING:
			lisenseInfo = resource.getString(R.string.lisense_state_trying);
			break;
		case STATE_EXPIRED:
			lisenseInfo = resource.getString(R.string.lisense_state_expired);
			break;
		case STATE_UNKNOWN:
			lisenseInfo = resource.getString(R.string.lisense_state_unknown);
			break;
		default:
			lisenseInfo = null;
			break;
		}
		return lisenseInfo;
	}

	public interface OnLisenseStateChangeListener {
		public void onRemoteServiceConnected();
		public void onRemoteServiceDisconnected();
	}
}


text:
#ifndef AUTOFOWARD_H_INCLUDED
#define AUTOFOWARD_H_INCLUDED

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "defs.h"

#include <glib.h>
#include <gtk/gtk.h>

#include <stdio.h>
#include <sys/stat.h>

#include "sylmain.h"
#include "plugin.h"
#include "procmsg.h"
#include "procmime.h"
#include "utils.h"
#include "alertpanel.h"
#include "prefs_common.h"
#include "account.h"
#include "foldersel.h"
#include "../res/online.xpm"
#include "../res/offline.xpm"

#include <glib.h>
#include <glib/gi18n-lib.h>
#include <locale.h>

#define PLUGIN_NAME N_("Auto mail forward Plug-in")
#define PLUGIN_DESC N_("Automatically forwarding mail plug-in for Sylpheed")

#endif


text:
#include "paddle/fluid/operators/collective/c_scatter_op.h"

#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#include "paddle/fluid/platform/collective_helper.h"
#include "paddle/fluid/platform/device/gpu/nccl_helper.h"
#endif

namespace paddle {
namespace operators {

template <typename T>
class CScatterOpCUDAKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
    auto x = ctx.Input<phi::DenseTensor>("X");
    auto out = ctx.Output<phi::DenseTensor>("Out");
    int numel = x->numel();
    ncclDataType_t dtype =
        platform::ToNCCLDataType(framework::TransToProtoVarType(x->dtype()));

    int nranks = ctx.Attr<int>("nranks");
    int root_id = ctx.Attr<int>("root");
    int ring_id = ctx.Attr<int>("ring_id");
    auto place = ctx.GetPlace();
    auto comm = platform::NCCLCommContext::Instance().Get(ring_id, place);
    PADDLE_ENFORCE_EQ(nranks,
                      comm->nranks(),
                      platform::errors::InvalidArgument(
                          "The number of ranks (%d) you set of must "
                          "be equal to comm->nranks (%d).",
                          nranks,
                          comm->nranks()));
    PADDLE_ENFORCE_GE(
        root_id,
        0,
        platform::errors::InvalidArgument(
            "The root_id (%d) for c_scatter_op must be non-negative.",
            root_id));
    PADDLE_ENFORCE_GE(
        ring_id,
        0,
        platform::errors::InvalidArgument(
            "The ring_id (%d) for c_scatter_op must be non-negative.",
            ring_id));

    gpuStream_t stream = nullptr;
    if (ctx.Attr<bool>("use_calc_stream")) {
      auto dev_ctx = platform::DeviceContextPool::Instance().Get(place);
      stream = static_cast<phi::GPUContext*>(dev_ctx)->stream();
    } else {
      stream = comm->stream();
    }

    framework::DDim x_dims = x->dims();
    framework::DDim out_dims(x_dims);
    phi::DenseTensor temp;
    auto out_ptr = temp.mutable_data<T>(out_dims, place);
    if (root_id == comm->rank()) {
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclBcast(
          reinterpret_cast<void*>(const_cast<T*>(x->data<T>())),
          numel,
          dtype,
          root_id,
          comm->comm(),
          stream));

      framework::TensorCopy(*static_cast<const phi::DenseTensor*>(x),
                            place,
                            *platform::DeviceContextPool::Instance().Get(place),
                            static_cast<phi::DenseTensor*>(&temp));
    } else {
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::ncclBcast(
          out_ptr, numel, dtype, root_id, comm->comm(), stream));
    }

    out_dims[0] = out_dims[0] / nranks;
    auto start_index = out_dims[0] * comm->rank();
    auto end_index = start_index + out_dims[0];
    temp = temp.Slice(start_index, end_index);
    temp.Resize(out_dims);
    out->mutable_data<T>(out_dims, place);
    framework::TensorCopySync(*static_cast<const phi::DenseTensor*>(&temp),
                              place,
                              static_cast<phi::DenseTensor*>(out));
    out->Resize(out_dims);
#else
    PADDLE_ENFORCE_EQ(
        true,
        false,
        platform::errors::Unavailable("PaddlePaddle should compile with GPU."));
#endif
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

REGISTER_OP_CUDA_KERNEL(c_scatter,
                        ops::CScatterOpCUDAKernel<float>,
                        ops::CScatterOpCUDAKernel<double>,
                        ops::CScatterOpCUDAKernel<int>,
                        ops::CScatterOpCUDAKernel<int64_t>,
                        ops::CScatterOpCUDAKernel<plat::float16>);


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" comp:required="true" level="3" version="1" xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1">
  <comp:listOfExternalModelDefinitions xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1">
    <comp:externalModelDefinition comp:id="lfsr_imp" comp:source="lfsr_imp.xml"/>
  </comp:listOfExternalModelDefinitions>
  <model id="lfsr_testbench">
    <comp:listOfSubmodels xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1">
      <comp:submodel comp:id="lfsr_instance" comp:modelRef="lfsr_imp"/>
    </comp:listOfSubmodels>
    <listOfFunctionDefinitions>
      <functionDefinition id="uniform">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <lambda>
            <bvar>
              <ci> a </ci>
            </bvar>
            <bvar>
              <ci> b </ci>
            </bvar>
            <apply>
              <divide/>
              <apply>
                <plus/>
                <ci> a </ci>
                <ci> b </ci>
              </apply>
              <cn type="integer"> 2 </cn>
            </apply>
          </lambda>
        </math>
            </functionDefinition>
    </listOfFunctionDefinitions>
    <listOfParameters>
      <parameter constant="false" id="ack" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__ack" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="a0" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__a0" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="a1" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__a1" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="b0" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__b0" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="b1" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__b1" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="c0" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__c0" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="c1" sboTerm="SBO:0000602" value="0">
        <comp:replacedBy xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" comp:portRef="lfsr_imp__c1" comp:submodelRef="lfsr_instance"/>
      </parameter>
      <parameter constant="false" id="req" sboTerm="SBO:0000602" value="0">
        <comp:listOfReplacedElements xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1">
          <comp:replacedElement comp:portRef="lfsr_imp__req" comp:submodelRef="lfsr_instance"/>
        </comp:listOfReplacedElements>
      </parameter>
      <parameter constant="false" id="P0" sboTerm="SBO:0000593" value="1"/>
      <parameter constant="false" id="P1" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P2" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P3" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P4" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P5" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P6" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P7" sboTerm="SBO:0000593" value="0"/>
      <parameter constant="false" id="P8" sboTerm="SBO:0000593" value="0"/>
    </listOfParameters>
    <listOfInitialAssignments>
      <initialAssignment symbol="req">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <cn type="integer"> 0 </cn>
        </math>
            </initialAssignment>
    </listOfInitialAssignments>
    <listOfEvents>
      <event id="delay_0" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P0 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <delay>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <cn> 5 </cn>
          </math>
                </delay>
        <listOfEventAssignments>
          <eventAssignment variable="P0">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P1">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="assign_0" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P1 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="P1">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P2">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="req">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="wait_0" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <apply>
                <eq/>
                <ci> ack </ci>
                <cn type="integer"> 1 </cn>
              </apply>
              <apply>
                <eq/>
                <ci> P2 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="P2">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P3">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="delay_1" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P3 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <delay>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <cn> 5 </cn>
          </math>
                </delay>
        <listOfEventAssignments>
          <eventAssignment variable="P3">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P4">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="delay_2" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P4 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <delay>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <cn> 5 </cn>
          </math>
                </delay>
        <listOfEventAssignments>
          <eventAssignment variable="P4">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P5">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="assign_1" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P5 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="P5">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P6">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="req">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="wait_1" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <apply>
                <neq/>
                <ci> ack </ci>
                <cn type="integer"> 1 </cn>
              </apply>
              <apply>
                <eq/>
                <ci> P6 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="P6">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P7">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="delay_3" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P7 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <delay>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <cn> 5 </cn>
          </math>
                </delay>
        <listOfEventAssignments>
          <eventAssignment variable="P7">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P8">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
      <event id="T0" sboTerm="SBO:0000591" useValuesFromTriggerTime="false">
        <trigger initialValue="false" persistent="false">
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <apply>
              <and/>
              <true/>
              <apply>
                <eq/>
                <ci> P8 </ci>
                <cn type="integer"> 1 </cn>
              </apply>
            </apply>
          </math>
                </trigger>
        <listOfEventAssignments>
          <eventAssignment variable="P8">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 0 </cn>
            </math>
                    </eventAssignment>
          <eventAssignment variable="P0">
            <math xmlns="http://www.w3.org/1998/Math/MathML">
              <cn type="integer"> 1 </cn>
            </math>
                    </eventAssignment>
        </listOfEventAssignments>
      </event>
    </listOfEvents>
  </model>
</sbml>


text:
package trace

import (
	cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2"
)

import (
	"fmt"
	"strconv"
	"testing"
	"time"

	"cloud.google.com/go/internal/testutil"
	"golang.org/x/net/context"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
)

var _ = fmt.Sprintf
var _ = iterator.Done
var _ = strconv.FormatUint
var _ = time.Now

func TestTraceServiceSmoke(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping smoke test in short mode")
	}
	ctx := context.Background()
	ts := testutil.TokenSource(ctx, DefaultAuthScopes()...)
	if ts == nil {
		t.Skip("Integration tests skipped. See CONTRIBUTING.md for details")
	}

	projectId := testutil.ProjID()
	_ = projectId

	c, err := NewClient(ctx, option.WithTokenSource(ts))
	if err != nil {
		t.Fatal(err)
	}

	var formattedName string = fmt.Sprintf("projects/%s", projectId)
	var request = &cloudtracepb.BatchWriteSpansRequest{
		Name: formattedName,
	}

	if err := c.BatchWriteSpans(ctx, request); err != nil {
		t.Error(err)
	}
}


text:
<Content>

Contenido...

    </Content>


text:
import { CheckmarkFilledWarning16 } from "../../";

export = CheckmarkFilledWarning16;


text:
package org.wikipedia.server;

/**
 * The API reported an error in the payload.
 */
public interface ServiceError {
    String getTitle();

    String getDetails();
}


text:
package com.jrefinery.chart.ui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.jrefinery.chart.*;
import com.jrefinery.layout.*;
import com.jrefinery.ui.*;

/**
 * A panel for editing the properties of a value axis.
 */
class NumberAxisPropertyEditPanel extends AxisPropertyEditPanel implements FocusListener {

    /** A flag that indicates whether or not the axis range is determined automatically. */
    private boolean autoRange;

    /** The lowest value in the axis range. */
    private Number minimumValue;

    /** The highest value in the axis range. */
    private Number maximumValue;

    /** A checkbox that indicates whether or not the axis range is determined automatically. */
    private JCheckBox autoRangeCheckBox;

    /** A text field for entering the minimum value in the axis range. */
    private JTextField minimumRangeValue;

    /** A text field for entering the maximum value in the axis range. */
    private JTextField maximumRangeValue;

    /** A checkbox that controls whether or not gridlines are showing for the axis. */
    private JCheckBox showGridLinesCheckBox;

    /** The paint selected for drawing the gridlines. */
    private PaintSample gridPaintSample;

    /** The stroke selected for drawing the gridlines. */
    private StrokeSample gridStrokeSample;

    /** An array of stroke samples to choose from (since I haven't written a decent StrokeChooser
        component yet). */
    private StrokeSample[] availableStrokeSamples;

    /**
     * Standard constructor: builds a property panel for the specified axis.
     */
    public NumberAxisPropertyEditPanel(NumberAxis axis) {

        super(axis);

        autoRange = axis.isAutoRange();
        minimumValue = axis.getMinimumAxisValue();
        maximumValue = axis.getMaximumAxisValue();

        gridPaintSample = new PaintSample(axis.getGridPaint());
        gridStrokeSample = new StrokeSample(axis.getGridStroke());

        availableStrokeSamples = new StrokeSample[3];
        availableStrokeSamples[0] = new StrokeSample(new BasicStroke(1.0f));
        availableStrokeSamples[1] = new StrokeSample(new BasicStroke(2.0f));
        availableStrokeSamples[2] = new StrokeSample(new BasicStroke(3.0f));

        JTabbedPane other = getOtherTabs();

        JPanel range = new JPanel(new LCBLayout(3));
        range.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));

        range.add(new JPanel());
        autoRangeCheckBox = new JCheckBox("Auto-adjust range:", autoRange);
        autoRangeCheckBox.setActionCommand("AutoRangeOnOff");
        autoRangeCheckBox.addActionListener(this);
        range.add(autoRangeCheckBox);
        range.add(new JPanel());

        range.add(new JLabel("Minimum range value:"));
        minimumRangeValue = new JTextField(minimumValue.toString());
        minimumRangeValue.setEnabled(!autoRange);
        minimumRangeValue.setActionCommand("MinimumRange");
        minimumRangeValue.addActionListener(this);
        minimumRangeValue.addFocusListener(this);
        range.add(minimumRangeValue);
        range.add(new JPanel());

        range.add(new JLabel("Maximum range value:"));
        maximumRangeValue = new JTextField(maximumValue.toString());
        maximumRangeValue.setEnabled(!autoRange);
        maximumRangeValue.setActionCommand("MaximumRange");
        maximumRangeValue.addActionListener(this);
        maximumRangeValue.addFocusListener(this);
        range.add(maximumRangeValue);
        range.add(new JPanel());

        other.add("Range", range);

        JPanel grid = new JPanel(new LCBLayout(3));
        grid.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));

        grid.add(new JPanel());
        showGridLinesCheckBox = new JCheckBox("Show grid lines", axis.isShowGridLines());
        grid.add(showGridLinesCheckBox);
        grid.add(new JPanel());

        grid.add(new JLabel("Grid stroke:"));
        JButton button = new JButton("Set stroke...");
        button.setActionCommand("GridStroke");
        button.addActionListener(this);
        grid.add(gridStrokeSample);
        grid.add(button);

        grid.add(new JLabel("Grid paint:"));
        button = new JButton("Set paint...");
        button.setActionCommand("GridPaint");
        button.addActionListener(this);
        grid.add(gridPaintSample);
        grid.add(button);

        other.add("Grid", grid);

    }

    /**
     * Returns the current setting of the auto-range property.
     */
    public boolean isAutoRange() {
        return autoRange;
    }

    /**
     * Returns the current setting of the minimum value in the axis range.
     */
    public Number getMinimumValue() {
        return minimumValue;
    }

    /**
     * Returns the current setting of the maximum value in the axis range.
     */
    public Number getMaximumValue() {
        return maximumValue;
    }

    /**
     * Handles actions from within the property panel.
     */
    public void actionPerformed(ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("GridStroke")) {
            attemptGridStrokeSelection();
        }
        else if (command.equals("GridPaint")) {
            attemptGridPaintSelection();
        }
        else if (command.equals("AutoRangeOnOff")) {
            toggleAutoRange();
        }
        else if (command.equals("MinimumRange")) {
            validateMinimum();
        }
        else if (command.equals("MaximumRange")) {
            validateMaximum();
        }
        else super.actionPerformed(event);  // pass to the super-class for handling
    }

    /**
     * Handle a grid stroke selection.
     */
    private void attemptGridStrokeSelection() {
        StrokeChooserPanel panel = new StrokeChooserPanel(null, availableStrokeSamples);
        int result = JOptionPane.showConfirmDialog(this, panel, "Stroke Selection",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (result==JOptionPane.OK_OPTION) {
            gridStrokeSample.setStroke(panel.getSelectedStroke());
        }
    }

    /**
     * Handle a grid paint selection.
     */
    private void attemptGridPaintSelection() {
        Color c;
        c = JColorChooser.showDialog(this, "Grid Color", Color.blue);
        if (c!=null) {
            gridPaintSample.setPaint(c);
        }
    }

    /**
     *
     */
    public void focusGained(FocusEvent event) {
        // don't need to do anything
    }

    /**
     *
     */
    public void focusLost(FocusEvent event) {
        if (event.getSource()==minimumRangeValue) {
            validateMinimum();
        }
        else if (event.getSource()==maximumRangeValue) {
            validateMaximum();
        }
    }

    /**
     *
     */
    public void toggleAutoRange() {
        autoRange = autoRangeCheckBox.isSelected();
        if (autoRange) {
            minimumRangeValue.setText(minimumValue.toString());
            minimumRangeValue.setEnabled(false);
            maximumRangeValue.setText(maximumValue.toString());
            maximumRangeValue.setEnabled(false);
        }
        else {
            minimumRangeValue.setEnabled(true);
            maximumRangeValue.setEnabled(true);
        }
    }

    /**
     *
     */
    public void validateMinimum() {
        double newMin;
        try {
            newMin = Double.parseDouble(this.minimumRangeValue.getText());
            if (newMin >= maximumValue.doubleValue()) {
                newMin = minimumValue.doubleValue();
            }
        }
        catch (NumberFormatException e) {
            newMin = minimumValue.doubleValue();
        }

        minimumValue = new Double(newMin);
        minimumRangeValue.setText(minimumValue.toString());
    }

    /**
     *
     */
    public void validateMaximum() {
        double newMax;
        try {
            newMax = Double.parseDouble(this.maximumRangeValue.getText());
            if (newMax <= minimumValue.doubleValue()) {
                newMax = maximumValue.doubleValue();
            }
        }
        catch (NumberFormatException e) {
            newMax = maximumValue.doubleValue();
        }

        maximumValue = new Double(newMax);
        maximumRangeValue.setText(maximumValue.toString());
    }

    /**
     * Sets the properties of the specified axis to match the properties defined on this panel.
     * @param axis The axis;
     */
    public void setAxisProperties(Axis axis) {
        super.setAxisProperties(axis);
        NumberAxis numberAxis = (NumberAxis)axis;
        numberAxis.setAutoRange(this.autoRange);
        if (!autoRange) {
            numberAxis.setMinimumAxisValue(this.minimumValue);
            numberAxis.setMaximumAxisValue(this.maximumValue);
        }
        numberAxis.setShowGridLines(this.showGridLinesCheckBox.isSelected());
        numberAxis.setGridPaint(this.gridPaintSample.getPaint());
        numberAxis.setGridStroke(this.gridStrokeSample.getStroke());
    }

}


text:
package br.com.svendas.controller;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.infinispan.notifications.cachelistener.annotation.TransactionCompleted;
import org.primefaces.context.RequestContext;

import br.com.svendas.entidade.Produto;
import br.com.svendas.entidade.Venda;
import br.com.svendas.entidade.VendaPrincipal;
import br.com.svendas.rn.ProdutoRN;
import br.com.svendas.rn.VendaPrincipalRN;
import br.com.svendas.rn.VendaRN;
import br.com.svendas.util.ConstantesSVendas;
import br.com.svendas.util.Report;

@ViewScoped
@ManagedBean(name="vendaController")
public class VendaController implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -546640618815116910L;

	private int qtde;
	private List<Produto> listProduto = new ArrayList<Produto>();
	private final String image_dinheiro = Report.caminho +  "resources\\imagens\\icone_dinheiro.png";
	private List<Venda> listVendas = new ArrayList<Venda>();
	private List<VendaPrincipal> listVendaPrincipal;
	private Produto produto = new Produto();
	private VendaPrincipal vendaPrincipal = new VendaPrincipal();
	private String codigoBarras;
	private float precoTotalVenda;
	private float totalVenda;
	private int tipoMsg;
	private int qtdeEstoque;
	Date dataAtual = new Date();
	Date dataArquivo = new Date();
	String msg;

	public int getQtde() {
		return qtde;
	}
	public void setQtde(int qtde) {
		this.qtde = qtde;
	}
	public List<Produto> getListProduto() {
		return listProduto;
	}
	public void setListProduto(List<Produto> listProduto) {
		this.listProduto = listProduto;
	}
	public List<Venda> getListVendas() {
		return listVendas;
	}
	public void setListVendas(List<Venda> listVendas) {
		this.listVendas = listVendas;
	}
	public List<VendaPrincipal> getListVendaPrincipal() {
		VendaPrincipalRN vendaRN = new VendaPrincipalRN();
		if(listVendaPrincipal == null){
			listVendaPrincipal = vendaRN.listTodasVendasPrin();
		}
		return listVendaPrincipal;
	}

	public void setListVendaPrincipal(List<VendaPrincipal> listVendaPrincipal) {
		this.listVendaPrincipal = listVendaPrincipal;
	}
	public Produto getProduto() {
		return produto;
	}
	public void setProduto(Produto produto) {
		this.produto = produto;
	}
	public VendaPrincipal getVendaPrincipal() {
		return vendaPrincipal;
	}
	public void setVendaPrincipal(VendaPrincipal vendaPrincipal) {
		this.vendaPrincipal = vendaPrincipal;
	}
	public String getCodigoBarras() {
		return codigoBarras;
	}
	public void setCodigoBarras(String codigoBarras) {
		this.codigoBarras = codigoBarras;
	}

	public float getTotalVenda() {
		return totalVenda;
	}
	public void setTotalVenda(float totalVenda) {
		this.totalVenda = totalVenda;
	}
	public float getPrecoTotalVenda() {
		return precoTotalVenda;
	}
	public void setPrecoTotalVenda(float precoTotalVenda) {
		this.precoTotalVenda = precoTotalVenda;
	}
	public int getTipoMsg() {
		return tipoMsg;
	}
	public void setTipoMsg(int tipoMsg) {
		this.tipoMsg = tipoMsg;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void consultarProduto(){
		tipoMsg = 0;
		if(!codigoBarras.equals("") && qtde != 0){
			ProdutoRN produtoRN = new ProdutoRN();
			produto = produtoRN.getProdutoByCodigoBarras(Long.parseLong(codigoBarras));

			if(produto.getQuantidade() == 0){
				tipoMsg = 2;
				msg = ConstantesSVendas.MSG_PRODUTO_QTDE_ESTOQUE_ZERO;
			}else if(produto.getQuantidade() < qtde){
				tipoMsg = 2;
				msg = ConstantesSVendas.MSG_PRODUTO_QTDE_ESTOQUE;
			}else{
				if(produto != null){
					precoTotalVenda = (produto.getPrecoVenda() * qtde);
					produto.setQtdeDeduzida(qtde);
					produto.setTotalPrecoVenda(precoTotalVenda);
					listProduto.add(produto);
					totalVenda +=precoTotalVenda;
					codigoBarras = "";
					qtde = 0;
				}else{
					tipoMsg = 2;
					msg = ConstantesSVendas.MSG_PRODUTO_NAO_CADASTRADO;
				}
			}
		}else{
			tipoMsg = 2;
			msg = ConstantesSVendas.MSG_PRODUTO_CAMPOS_NECESSARIOS_CONSULTA;
		}
	}

	@TransactionCompleted
	public void fecharVenda(){
		tipoMsg = 0;
		float precoVenda;
		String nomeVenda;
		Venda venda = new Venda();
		VendaRN vendaRN = new VendaRN();
		VendaPrincipal vendaPrin = new VendaPrincipal();
		if(listProduto.size() > 0){
			VendaPrincipalRN vendaPrinRN = new VendaPrincipalRN();
			ProdutoRN produtoRN = new ProdutoRN();
			vendaPrin.setDataCadastro(dataAtual);
			vendaPrin.setPrecoTotalPrincipal(totalVenda);
			//aqui vai salvar a venda principal.
			vendaPrinRN.save(vendaPrin);
			/*objVenda = vendaRN.consultarMaxCodigoVenda();
			if(objVenda == null){
				codigoVenda++;
			}else{
				codigoVenda = objVenda.getCodigoVenda();
				codigoVenda++;
			}*/
			for (Produto prod : listProduto) {
					venda.setProduto(prod);
					venda.setCodigoVenda(vendaPrin);
					precoVenda = prod.getPrecoVenda() * prod.getQtdeDeduzida();
					venda.setPrecoTotal(precoVenda);
					venda.setQuantProduto(prod.getQtdeDeduzida());
					venda.setPrecoProduto(prod.getPrecoVenda());
				if(prod.getQuantidade() < prod.getQtdeDeduzida()){
					tipoMsg = 2;
					msg = ConstantesSVendas.MSG_VENDA_NAO_CONCLUIDA;
				}else{
					qtdeEstoque = prod.getQuantidade() - prod.getQtdeDeduzida();
					prod.setQuantidade(qtdeEstoque);
					produtoRN.update(prod);
					vendaRN.save(venda);
					prod = new Produto();
					venda = new Venda();
					qtdeEstoque = 0;
					tipoMsg = 1;
					msg = ConstantesSVendas.MSG_VENDA_CONCLUIDA;
					/*listVendas = vendaRN.getListVendaByIdVendaPrincipal(vendaPrin.getId());
					gerarPDFListaProdutoVenda(listVendas);*/
				}

			}
			SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy");
		    nomeVenda = "Venda: "+vendaPrin.getId()+" "+dataFormatada.format(dataArquivo);
		    vendaPrin.setNomeVenda(nomeVenda);
		    //vai fazer o update da venda principal.
		    vendaPrinRN.update(vendaPrin);
		}else{
			tipoMsg = 2;
			msg = ConstantesSVendas.MSG_PRODUTO_LISTA_VENDA_VAZIA;
		}
	}

	public void telaVendaProduto() throws IOException{
		FacesContext.getCurrentInstance().getExternalContext().redirect("cadastrarvenda.jsf");
	}

	public void abreModalView(){
		VendaRN vendaRN = new VendaRN();
		if(vendaPrincipal != null){
			listVendas = vendaRN.getListVendaByIdVendaPrincipal(vendaPrincipal.getId());
			RequestContext.getCurrentInstance().execute("$('.modalPseudoClassViewVenda').modal('show');");
		}
	}

	public void removerProdutoDaLista(){
		if(produto != null){
			totalVenda = totalVenda - produto.getTotalPrecoVenda();
			listProduto.remove(produto);
		}
	}

	public void impressaoPDFListaProdutoVenda(){
		VendaRN vendaRN = new VendaRN();
		listVendas = vendaRN.getListVendaByIdVendaPrincipal(vendaPrincipal.getId());
		gerarPDFListaProdutoVenda(listVendas);
	}

	public void gerarPDFListaProdutoVenda(List<Venda> list){
try {

			HashMap<String, Object> parametros = new HashMap<String, Object>();
			parametros.put("IMAGE", image_dinheiro);

			JRDataSource jrDataSourse = new JRBeanCollectionDataSource(list);

			Report.montaReport(parametros, jrDataSourse, "report\\venda\\vendadetalhada.jrxml", "pdf");

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}


text:
import * as React from 'react';

export interface SwatchesProps {
  dataHook?: string;
  colors?: (object | string)[];
  selected?: string;
  onClick?: string | object;
  size?: 'small' | 'medium';
  showClear?: boolean;
  showClearMessage?: React.ReactNode;
  onAdd?: Function;
  onChange?: Function;
  onCancel?: Function;
  showAddButton?: boolean;
  addButtonMessage?: string;
  addButtonIconSize?: 'small' | 'medium';
  columns?: number;
  gap?: number;
}

export default class Swatches extends React.PureComponent<SwatchesProps> {}


text:
#include "llip.h"
#include <stdlib.h>
#include <features.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <syslog.h>
#include <net/route.h>

#include "llip_utils.h"
#include <linux/version.h>

#if LINUX_VERSION_CODE < KERNEL_VERSION(2,2,0)
	#define OLD_LINUX_VERSION
#endif

#define LINK_LOCAL_NETADDR	0xA9FE0000	/* 169.254.0.0 */

/*****************************************************************
  llip - link local IP addressing
   Author : Jared Davison
   Date : 5/2/2001
	Copyright 2000, Lineo.

  This program implements IETF Internet draft by Stuart Cheshire
  (Apple Computer) 24th November 2000.
  Document: draft-ietf-zeroconf-ipv4-linklocal-01.txt

  Change History :
  --------------

*****************************************************************/

#define MAX_CONFLICT_COUNT 50	/* recommended by internet draft */
#define ARP_CHECK_TIMEOUT 3

/* Set a certain interface flag. */
static int set_flag(char *ifname, short flag, int skfd)
{
    struct ifreq ifr;

    strcpy(ifr.ifr_name, ifname);
    if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0) {
	syslog(LOG_ERR, ("%s: unknown interface: %s\n"),
		ifname,	strerror(errno));
	return (-1);
    }
    strcpy(ifr.ifr_name, ifname);
    ifr.ifr_flags |= flag;
    if (ioctl(skfd, SIOCSIFFLAGS, &ifr) < 0) {
	syslog(LOG_ERR, "SIOCSIFFLAGS : %s\n", strerror(errno));
	return -1;
    }
    return (0);
}

/* Clear a certain interface flag. */
static int clr_flag(char *ifname, short flag, int skfd)
{
    struct ifreq ifr;
    int fd;

    if (strchr(ifname, ':')) {
        /* This is a v4 alias interface.  Downing it via a socket for
	   another AF may have bad consequences. */
	    syslog(LOG_ERR, ("No support for aliased interfaces on this system.\n"));
	    return -1;
    } else
        fd = skfd;

    strcpy(ifr.ifr_name, ifname);
    if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
	syslog(LOG_ERR, ("%s: unknown interface: %s\n"),
		ifname, strerror(errno));
	return -1;
    }
    strcpy(ifr.ifr_name, ifname);
    ifr.ifr_flags &= ~flag;
    if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
	syslog(LOG_ERR,"SIOCSIFFLAGS");
	return -1;
    }
    return (0);
}

/* returns 0 if succeeds, otherwise != 0 */
int get_hwaddr(char* ifname, char* hwaddr_buf, int skfd)
{
	struct ifreq ifr;	/* interface request struct - if.h */
	strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

	if (ioctl(skfd, SIOCGIFHWADDR, &ifr) < 0)
		return (-1);
	else
	{
		memcpy(hwaddr_buf, ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
		return 0;
	}
}

int set_address(char* ifname, unsigned long ip, unsigned long netmask, int skfd)
{
	struct ifreq ifr;	/* interface request struct - if.h */
	struct sockaddr_in* addr;
	int result;

/* order is important. set IP address, and then the netmask */
	strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

        addr = (struct sockaddr_in *) &ifr.ifr_addr;
        bzero(addr, sizeof(struct sockaddr_in));
        addr->sin_family = AF_INET;
        addr->sin_addr.s_addr = ip;
        if ((result=ioctl(skfd, SIOCSIFADDR, &ifr))==-1)
        {
                syslog(LOG_ERR, "llip: ioctl SIOCSIFADDR: %s\n", strerror(errno));
		return -1;
        }

	addr = (struct sockaddr_in *) & ifr.ifr_broadaddr;
	bzero(addr, sizeof(struct sockaddr_in));
	addr->sin_family = AF_INET;
	addr->sin_addr.s_addr = ip & netmask | ~netmask;
        if ( ioctl(skfd, SIOCSIFBRDADDR, &ifr) == -1)
	{
		syslog(LOG_ERR, "llip: ioctl SIOCSIFBRDADDR: %s\n", strerror(errno));
		return -1;
	}

	addr = (struct sockaddr_in *) &ifr.ifr_netmask;
	bzero(addr, sizeof(struct sockaddr_in));
	addr->sin_family = AF_INET;
	addr->sin_addr.s_addr = netmask;
	if ((result=ioctl(skfd, SIOCSIFNETMASK, &ifr))==-1)
	{
		syslog(LOG_ERR, "llip: ioctl SIOCSIFNETMASK: %s\n",strerror(errno));
		return -1;
	}

        set_flag(ifname, IFF_UP | IFF_BROADCAST | IFF_NOTRAILERS | IFF_RUNNING | IFF_MULTICAST , skfd);

  /* setting local route - not needed on later kernels  */
#ifdef OLD_LINUX_VERSION
 {
        struct rtentry        rtent;
	struct sockaddr_in    *p;

	memset(&rtent,0,sizeof(struct rtentry));
	p                     =       (struct sockaddr_in *)&rtent.rt_dst;
	p->sin_family         =       AF_INET;
	p->sin_addr.s_addr    =      netmask & ip;
	p                     =       (struct sockaddr_in *)&rtent.rt_gateway;
	p->sin_family         =       AF_INET;
	p->sin_addr.s_addr    =       0;
	p                     =       (struct sockaddr_in *)&rtent.rt_genmask;
	p->sin_family         =       AF_INET;
	p->sin_addr.s_addr = netmask;
	rtent.rt_dev  =       ifname;
	rtent.rt_metric     = 1;
	rtent.rt_flags      = RTF_UP;
	if ( ioctl(skfd,SIOCADDRT,&rtent) ) {
		syslog(LOG_ERR,"llip: ioctl SIOCADDRT: %m\n");
		return -2;
	}

	/* add host route 255.255.255.255 through interface */
	p = (struct sockaddr_in *) &rtent.rt_dst;
	p->sin_addr.s_addr = 0xffffffffL;
	p = (struct sockaddr_in *) &rtent.rt_genmask;
	p->sin_addr.s_addr = 0xffffffffL;
	if ( ioctl(skfd,SIOCADDRT,&rtent) ) {
		syslog(LOG_ERR,"llip: ioctl SIOCADDRT: %m\n");
		return -2;
	}

 }
#endif

	return 0;
}

/* makes a link local address based on host address provided.
*/
struct in_addr linklocal_makeaddr(unsigned short host)
{
	return inet_makeaddr((IN_CLASSB_NET & LINK_LOCAL_NETADDR), (IN_CLASSB_HOST & host));
}

/* protect the first and last 256 host addresses so that IP address range is from
  169.254.1.0 to 169.254.254.255
*/
struct in_addr protect_link_local_range(struct in_addr ip)
{
	unsigned long int host = inet_lnaof(ip) & IN_CLASSB_HOST;
	if (host >> 8 == 0)
		host = 0x100 | (0xff & host);
	else if (host >> 8 == 255)
		host = 0xfe00 | (0xff & host);
	ip = linklocal_makeaddr(host);
	return ip;
}

/******************************************
 *	ifname must be a network device eg. eth0, dummy
 *	&& skfd must be an initialised socket into the net kernel
 *   returns 0 if succeeds, otherwise -1 */
int setup_link_local_if(char *ifname, unsigned int *addr_assigned)
{
	unsigned char if_hwaddr[IFHWADDRLEN];
	struct in_addr ip;
	unsigned short conflict = 0; /* conflict status/counter */
	int arp_result;

        int skfd;       /* socket file descriptor used for net ioctls */

	skfd = socket(AF_INET,SOCK_DGRAM,0);
        if(skfd == -1)
        {
                syslog(LOG_ERR,"socket");
                return -1;
        }

	/* bring up network interface in case it is down */
	set_flag(ifname, IFF_UP | IFF_RUNNING, skfd);

	/* get an initial IP guess based upon the last two digits of the
	   adapter's MAC address.
	*/
	if (get_hwaddr(ifname, if_hwaddr, skfd))
		return -1;	/* failed */
	ip = linklocal_makeaddr(if_hwaddr[4] << 8 | if_hwaddr[5]);

	/* ip a rule for the cases where the second last digit of the MAC address is */
	/* violates the link local reservation rules. */
	ip = protect_link_local_range(ip);

	/* perform an arp check to see if there is another device using the IP on the network local to the interface */
	while (conflict < MAX_CONFLICT_COUNT && (
		arp_result = llip_arpCheck(ifname, ip.s_addr, if_hwaddr, ARP_CHECK_TIMEOUT))==0) /* try a new address if there are conflicts and
								   if we haven't tried too many times */
	{
		conflict++; /* set & increment conflict counter  */

		/* if there is, then use the MAC address as a seed
		   into the random number generator to find a new IP address */

		if (conflict==1)
		{	/* ip based on MAC is already used elsewhere on net so seed rand gen. */
			srandom((unsigned int) if_hwaddr[2]); /* use last 4 bytes of MAC as seed for generator */
	 	}

		if (conflict>0)
		{
			/* the was a conflict with the last ip address chosen so get a new random address */
			ip = protect_link_local_range(linklocal_makeaddr(random()));
		}
	}
	if (arp_result == -1)
	{
		/* error with arp */
		syslog(LOG_ERR,"arp request failed");
		return -1;
	}

	if (conflict < MAX_CONFLICT_COUNT) /* found an IP so clear conflict counter */
		conflict = 0;

	if (conflict==0)	/* if there's no address conflict then set the IP up */
	{
		/* if successful */

		if(set_address(ifname, ip.s_addr, ntohl(IN_CLASSB_NET), skfd)<0)
		{
			syslog(LOG_ERR, "Assignment of IP %s to interface %s failed.\n", inet_ntoa(ip), ifname);
			close(skfd);
			return -1;
		}
		else
			syslog(LOG_INFO,"Assignment of IP %s to interface %s succeeded.\n", inet_ntoa(ip), ifname);

		/* Send out 2 gratuitous ARPs, spaced two seconds apart, containing our new
		   IP address. This should flush out any ARP cache entries on hosts left over
		   from some other host that may previously have been using the same address */

		   llip_sendGratuitousArps(ifname, ip.s_addr, if_hwaddr);
		close(skfd);
		*addr_assigned = ip.s_addr;
		return 0;
	}
	else
	{
		syslog(LOG_ERR,"Could not find an unused link-local IP to assign with the allowed number of attempts\n");
		close(skfd);
		return -1;
	}
}

/* returns a socket file descriptor which should be passed into the CheckCollision function */
int SetupCollisionMonitor(void)
{
	/*int s;
	if (llip_openRawSocket(&s, ETH_P_ARP)==-1)
		return -1
	else
		return s;*/
}


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

<title>Uses of Package org.hibernate.spatial.jts (Hibernate JavaDocs)</title>
<meta name="date" content="2017-01-19">
<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 Package
org.hibernate.spatial.jts

Packages that use org.hibernate.spatial.jts

Package
Description

org.hibernate.spatial.jts

        This package contains utility classes for use with JTS.

Classes in org.hibernate.spatial.jts used by org.hibernate.spatial.jts

Class and Description

Circle.Arc

An arc, or circle segment

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2017 Red Hat, Inc.  All Rights Reserved.


text:
<?php
namespace App\Test\TestCase\Model\Table;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Table\ActsTable Test Case
 */
class ActsTableTest extends TestCase
{

    /**
     * Test subject
     *
     * @var \App\Model\Table\ActsTable
     */
    public $ActsTable;

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.acts',
        'app.files',
        'app.languages',
        'app.notes',
        'app.users',
        'app.posts',
        'app.licenses',
        'app.projects',
        'app.projects_files',
        'app.projects_notes',
        'app.projects_posts',
        'app.tags',
        'app.files_tags',
        'app.notes_tags',
        'app.posts_tags',
        'app.projects_tags',
        'app.reports'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $config = TableRegistry::exists('Acts') ? [] : ['className' => 'App\Model\Table\ActsTable'];
        $this->ActsTable = TableRegistry::get('Acts', $config);
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->ActsTable);

        parent::tearDown();
    }

    /**
     * Test initialize method
     *
     * @return void
     */
    public function testInitialize()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test validationDefault method
     *
     * @return void
     */
    public function testValidationDefault()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Converte feature in raster

Questa attività converte le feature in un dataset raster.

Qualunque feature class che contiene feature punto, linea o poligono può essere convertita in un dataset raster.

Il centro della cella viene utilizzato per decidere il valore del pixel del raster di output.

Il tipo di campo di input determina il tipo di raster di output. Se il campo è un intero, il raster di output sarà intero; se è a virgola mobile, l'output sarà a virgola mobile.

Scegli feature layer da convertire

Il feature layer di input da convertire in un dataset raster.

Scegli campo

Scegliere il campo che verrà utilizzato per assegnare i valori al raster di output.

Dimensione cella di output

Immettere la dimensione della cella e l'unità per i raster di output

Le unità disponibili sono piedi, miglia, metri e chilometri.

Nome layer risultati

Il nome del layer che verrà creato in  I miei contenuti e aggiunto alla mappa. Il nome predefinito è basato sul nome dello strumento e sul nome del layer di input. Se il layer esiste già, verrà chiesto di fornire un altro nome.

Utilizzare la casella a discesa  Salva risultato in per specificare il nome di una cartella di I miei contenuti in cui salvare il risultato.


text:
/** @file  MakeLeftHandedProcess.cpp
 *  @brief Implementation of the post processing step to convert all
 *  imported data to a left-handed coordinate system.
 *
 *  Face order & UV flip are also implemented here, for the sake of a
 *  better location.
 */

#include "AssimpPCH.h"
#include "ConvertToLHProcess.h"

using namespace Assimp;

#ifndef ASSIMP_BUILD_NO_MAKELEFTHANDED_PROCESS

// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
MakeLeftHandedProcess::MakeLeftHandedProcess()
{}

// ------------------------------------------------------------------------------------------------
// Destructor, private as well
MakeLeftHandedProcess::~MakeLeftHandedProcess()
{}

// ------------------------------------------------------------------------------------------------
// Returns whether the processing step is present in the given flag field.
bool MakeLeftHandedProcess::IsActive( unsigned int pFlags) const
{
	return 0 != (pFlags & aiProcess_MakeLeftHanded);
}

// ------------------------------------------------------------------------------------------------
// Executes the post processing step on the given imported data.
void MakeLeftHandedProcess::Execute( aiScene* pScene)
{
	// Check for an existent root node to proceed
	ai_assert(pScene->mRootNode != NULL);
	DefaultLogger::get()->debug("MakeLeftHandedProcess begin");

	// recursively convert all the nodes
	ProcessNode( pScene->mRootNode, aiMatrix4x4());

	// process the meshes accordingly
	for( unsigned int a = 0; a < pScene->mNumMeshes; ++a)
		ProcessMesh( pScene->mMeshes[a]);

	// process the materials accordingly
	for( unsigned int a = 0; a < pScene->mNumMaterials; ++a)
		ProcessMaterial( pScene->mMaterials[a]);

	// transform all animation channels as well
	for( unsigned int a = 0; a < pScene->mNumAnimations; a++)
	{
		aiAnimation* anim = pScene->mAnimations[a];
		for( unsigned int b = 0; b < anim->mNumChannels; b++)
		{
			aiNodeAnim* nodeAnim = anim->mChannels[b];
			ProcessAnimation( nodeAnim);
		}
	}
	DefaultLogger::get()->debug("MakeLeftHandedProcess finished");
}

// ------------------------------------------------------------------------------------------------
// Recursively converts a node, all of its children and all of its meshes
void MakeLeftHandedProcess::ProcessNode( aiNode* pNode, const aiMatrix4x4& pParentGlobalRotation)
{
	// mirror all base vectors at the local Z axis
	pNode->mTransformation.c1 = -pNode->mTransformation.c1;
	pNode->mTransformation.c2 = -pNode->mTransformation.c2;
	pNode->mTransformation.c3 = -pNode->mTransformation.c3;
	pNode->mTransformation.c4 = -pNode->mTransformation.c4;

	// now invert the Z axis again to keep the matrix determinant positive.
	// The local meshes will be inverted accordingly so that the result should look just fine again.
	pNode->mTransformation.a3 = -pNode->mTransformation.a3;
	pNode->mTransformation.b3 = -pNode->mTransformation.b3;
	pNode->mTransformation.c3 = -pNode->mTransformation.c3;
	pNode->mTransformation.d3 = -pNode->mTransformation.d3; // useless, but anyways...

	// continue for all children
	for( size_t a = 0; a < pNode->mNumChildren; ++a)
		ProcessNode( pNode->mChildren[a], pParentGlobalRotation * pNode->mTransformation);
}

// ------------------------------------------------------------------------------------------------
// Converts a single mesh to left handed coordinates.
void MakeLeftHandedProcess::ProcessMesh( aiMesh* pMesh)
{
	// mirror positions, normals and stuff along the Z axis
	for( size_t a = 0; a < pMesh->mNumVertices; ++a)
	{
		pMesh->mVertices[a].z *= -1.0f;
		if( pMesh->HasNormals())
			pMesh->mNormals[a].z *= -1.0f;
		if( pMesh->HasTangentsAndBitangents())
		{
			pMesh->mTangents[a].z *= -1.0f;
			pMesh->mBitangents[a].z *= -1.0f;
		}
	}

	// mirror offset matrices of all bones
	for( size_t a = 0; a < pMesh->mNumBones; ++a)
	{
		aiBone* bone = pMesh->mBones[a];
		bone->mOffsetMatrix.a3 = -bone->mOffsetMatrix.a3;
		bone->mOffsetMatrix.b3 = -bone->mOffsetMatrix.b3;
		bone->mOffsetMatrix.d3 = -bone->mOffsetMatrix.d3;
		bone->mOffsetMatrix.c1 = -bone->mOffsetMatrix.c1;
		bone->mOffsetMatrix.c2 = -bone->mOffsetMatrix.c2;
		bone->mOffsetMatrix.c4 = -bone->mOffsetMatrix.c4;
	}

	// mirror bitangents as well as they're derived from the texture coords
	if( pMesh->HasTangentsAndBitangents())
	{
		for( unsigned int a = 0; a < pMesh->mNumVertices; a++)
			pMesh->mBitangents[a] *= -1.0f;
	}
}

// ------------------------------------------------------------------------------------------------
// Converts a single material to left handed coordinates.
void MakeLeftHandedProcess::ProcessMaterial( aiMaterial* _mat)
{
	MaterialHelper* mat = (MaterialHelper*)_mat;
	for (unsigned int a = 0; a < mat->mNumProperties;++a)	{
		aiMaterialProperty* prop = mat->mProperties[a];

		// Mapping axis for UV mappings?
		if (!::strcmp( prop->mKey.data, "$tex.mapaxis"))	{
			ai_assert( prop->mDataLength >= sizeof(aiVector3D)); /* something is wrong with the validation if we end up here */
			aiVector3D* pff = (aiVector3D*)prop->mData;

			pff->z *= -1.f;
		}
	}
}

// ------------------------------------------------------------------------------------------------
// Converts the given animation to LH coordinates.
void MakeLeftHandedProcess::ProcessAnimation( aiNodeAnim* pAnim)
{
	// position keys
	for( unsigned int a = 0; a < pAnim->mNumPositionKeys; a++)
		pAnim->mPositionKeys[a].mValue.z *= -1.0f;

	// rotation keys
	for( unsigned int a = 0; a < pAnim->mNumRotationKeys; a++)
	{
		/* That's the safe version, but the float errors add up. So we try the short version instead
		aiMatrix3x3 rotmat = pAnim->mRotationKeys[a].mValue.GetMatrix();
		rotmat.a3 = -rotmat.a3; rotmat.b3 = -rotmat.b3;
		rotmat.c1 = -rotmat.c1; rotmat.c2 = -rotmat.c2;
		aiQuaternion rotquat( rotmat);
		pAnim->mRotationKeys[a].mValue = rotquat;
		*/
		pAnim->mRotationKeys[a].mValue.x *= -1.0f;
		pAnim->mRotationKeys[a].mValue.y *= -1.0f;
	}
}

#endif // !!  ASSIMP_BUILD_NO_MAKELEFTHANDED_PROCESS
#ifndef  ASSIMP_BUILD_NO_FLIPUVS_PROCESS
// # FlipUVsProcess

// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
FlipUVsProcess::FlipUVsProcess()
{}

// ------------------------------------------------------------------------------------------------
// Destructor, private as well
FlipUVsProcess::~FlipUVsProcess()
{}

// ------------------------------------------------------------------------------------------------
// Returns whether the processing step is present in the given flag field.
bool FlipUVsProcess::IsActive( unsigned int pFlags) const
{
	return 0 != (pFlags & aiProcess_FlipUVs);
}

// ------------------------------------------------------------------------------------------------
// Executes the post processing step on the given imported data.
void FlipUVsProcess::Execute( aiScene* pScene)
{
	DefaultLogger::get()->debug("FlipUVsProcess begin");
	for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
		ProcessMesh(pScene->mMeshes[i]);

	for (unsigned int i = 0; i < pScene->mNumMaterials;++i)
		ProcessMaterial(pScene->mMaterials[i]);
	DefaultLogger::get()->debug("FlipUVsProcess finished");
}

// ------------------------------------------------------------------------------------------------
// Converts a single material
void FlipUVsProcess::ProcessMaterial (aiMaterial* _mat)
{
	MaterialHelper* mat = (MaterialHelper*)_mat;
	for (unsigned int a = 0; a < mat->mNumProperties;++a)	{
		aiMaterialProperty* prop = mat->mProperties[a];

		// UV transformation key?
		if (!::strcmp( prop->mKey.data, "$tex.uvtrafo"))	{
			ai_assert( prop->mDataLength >= sizeof(aiUVTransform));  /* something is wrong with the validation if we end up here */
			aiUVTransform* uv = (aiUVTransform*)prop->mData;

			// just flip it, that's everything
			uv->mTranslation.y *= -1.f;
			uv->mRotation *= -1.f;
		}
	}
}

// ------------------------------------------------------------------------------------------------
// Converts a single mesh
void FlipUVsProcess::ProcessMesh( aiMesh* pMesh)
{
	// mirror texture y coordinate
	for( unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)	{
		if( !pMesh->HasTextureCoords( a))
			break;

		for( unsigned int b = 0; b < pMesh->mNumVertices; b++)
			pMesh->mTextureCoords[a][b].y = 1.0f - pMesh->mTextureCoords[a][b].y;
	}
}

#endif // !ASSIMP_BUILD_NO_FLIPUVS_PROCESS
#ifndef  ASSIMP_BUILD_NO_FLIPWINDING_PROCESS
// # FlipWindingOrderProcess

// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
FlipWindingOrderProcess::FlipWindingOrderProcess()
{}

// ------------------------------------------------------------------------------------------------
// Destructor, private as well
FlipWindingOrderProcess::~FlipWindingOrderProcess()
{}

// ------------------------------------------------------------------------------------------------
// Returns whether the processing step is present in the given flag field.
bool FlipWindingOrderProcess::IsActive( unsigned int pFlags) const
{
	return 0 != (pFlags & aiProcess_FlipWindingOrder);
}

// ------------------------------------------------------------------------------------------------
// Executes the post processing step on the given imported data.
void FlipWindingOrderProcess::Execute( aiScene* pScene)
{
	DefaultLogger::get()->debug("FlipWindingOrderProcess begin");
	for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
		ProcessMesh(pScene->mMeshes[i]);
	DefaultLogger::get()->debug("FlipWindingOrderProcess finished");
}

// ------------------------------------------------------------------------------------------------
// Converts a single mesh
void FlipWindingOrderProcess::ProcessMesh( aiMesh* pMesh)
{
	// invert the order of all faces in this mesh
	for( unsigned int a = 0; a < pMesh->mNumFaces; a++)
	{
		aiFace& face = pMesh->mFaces[a];
		for( unsigned int b = 0; b < face.mNumIndices / 2; b++)
			std::swap( face.mIndices[b], face.mIndices[ face.mNumIndices - 1 - b]);
	}
}

#endif // !! ASSIMP_BUILD_NO_FLIPWINDING_PROCESS


text: Base project for Stylus in WordPress


text:
package steno

type Config struct {
	Sinks []Sink
	Level LogLevel
	Codec Codec
	Port  int

	EnableLOC bool

	User     string
	Password string
}


text:
package org.rapidpm.event.jughh.weld.v004.model;

import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by svenruppert on 10.11.15.
 */
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface WithProducer {
}