text:
package org.springframework.jms.core;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.NamingException;

import junit.framework.TestCase;
import org.easymock.MockControl;

import org.springframework.jms.JmsException;
import org.springframework.jms.support.JmsUtils;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.jms.support.destination.JndiDestinationResolver;
import org.springframework.jndi.JndiTemplate;

/**
 * Unit tests for the JmsTemplate implemented using JMS 1.1.
 * @author Andre Biryukov
 * @author Mark Pollack
 */
public class JmsTemplateTests extends TestCase {

	private Context mockJndiContext;
	private MockControl mockJndiControl;

	private MockControl connectionFactoryControl;
	private ConnectionFactory mockConnectionFactory;

	private MockControl connectionControl;
	private Connection mockConnection;

	private MockControl sessionControl;
	private Session mockSession;

	private MockControl queueControl;
	private Queue mockQueue;

	private int deliveryMode = DeliveryMode.PERSISTENT;
	private int priority = 9;
	private int timeToLive = 10000;

	/**
	 * Create the mock objects for testing.
	 */
	protected void setUp() throws Exception {
		mockJndiControl = MockControl.createControl(Context.class);
		mockJndiContext = (Context) this.mockJndiControl.getMock();

		createMockforDestination();

		mockJndiContext.close();
		mockJndiControl.replay();
	}

	private void createMockforDestination()
			throws JMSException, NamingException {
		connectionFactoryControl =
				MockControl.createControl(ConnectionFactory.class);
		mockConnectionFactory =
				(ConnectionFactory) connectionFactoryControl.getMock();

		connectionControl = MockControl.createControl(Connection.class);
		mockConnection = (Connection) connectionControl.getMock();

		sessionControl = MockControl.createControl(Session.class);
		mockSession = (Session) sessionControl.getMock();

		queueControl = MockControl.createControl(Queue.class);
		mockQueue = (Queue) queueControl.getMock();

		mockConnectionFactory.createConnection();
		connectionFactoryControl.setReturnValue(mockConnection);
		connectionFactoryControl.replay();

		//TODO tests with TX=true
		mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		connectionControl.setReturnValue(mockSession);
		mockSession.getTransacted();
		sessionControl.setReturnValue(false);

		mockJndiContext.lookup("testDestination");
		mockJndiControl.setReturnValue(mockQueue);
	}

	public void testExceptionStackTrace() {
		JMSException jmsEx = new JMSException("could not connect");
		Exception innerEx = new Exception("host not found");
		jmsEx.setLinkedException(innerEx);
		JmsException springJmsEx = JmsUtils.convertJmsAccessException(jmsEx);
		StringWriter sw = new StringWriter();
		PrintWriter out = new PrintWriter(sw);
		springJmsEx.printStackTrace(out);
		String trace = sw.toString();
		//System.out.println("trace = " + trace);
		assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0);

	}

	public void testProducerCallback() throws Exception {
		JmsTemplate sender = new JmsTemplate();
		sender.setConnectionFactory(mockConnectionFactory);
		setJndiTemplate(sender);

		MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
		MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();

		mockSession.createProducer(null);
		sessionControl.setReturnValue(mockMessageProducer);

		mockMessageProducer.getPriority();
		messageProducerControl.setReturnValue(4);

		messageProducerControl.replay();

		mockSession.close();
		sessionControl.setVoidCallable(1);

		mockConnection.close();
		connectionControl.setVoidCallable(1);

		sessionControl.replay();
		connectionControl.replay();

		sender.execute(new ProducerCallback() {
			public Object doInJms(Session session, MessageProducer msgProducer) throws JMSException {
				boolean b = session.getTransacted();
				int i = msgProducer.getPriority();
				return null;
			}
		});

		connectionFactoryControl.verify();
		connectionControl.verify();
		sessionControl.verify();
	}

	/**
	 * Test the method execute(SessionCallback action).
	 */
	public void testSessionCallback() throws Exception {
		JmsTemplate sender = new JmsTemplate();
		sender.setConnectionFactory(mockConnectionFactory);
		setJndiTemplate(sender);

		mockSession.close();
		sessionControl.setVoidCallable(1);

		mockConnection.close();
		connectionControl.setVoidCallable(1);

		sessionControl.replay();
		connectionControl.replay();

		sender.execute(new SessionCallback() {
			public Object doInJms(Session session) throws JMSException {
				boolean b = session.getTransacted();
				return null;
			}
		});

		connectionFactoryControl.verify();
		connectionControl.verify();
		sessionControl.verify();
	}

	/**
	 * Test sending to a destination using the method
	 * send(Destination d, MessageCreator messageCreator)
	 */
	public void testSendDestination() throws Exception {
		doTestSendDestination(true, true, false);
	}

	/**
	 * Test sending to a destination using the method
	 * send(Destination d, MessageCreator messageCreator) using QOS parameters.
	 */
	public void testSendDestinationWithQOS() throws Exception {
		doTestSendDestination(false, true, false);
	}

	/**
	 * Test seding to a destination using the method
	 * send(String d, MessageCreator messageCreator)
	 */
	public void testSendStringDestination() throws Exception {
		doTestSendDestination(true, false, false);
	}

	/**
	 * Test sending to a destination using the method
	 * send(String d, MessageCreator messageCreator) using QOS parameters.
	 */
	public void testSendStringDestinationWithQOS() throws Exception {
		doTestSendDestination(false, false, false);
	}

	/**
	 * Test sending to the default destination.
	 */
	public void testSendDefaultDestination() throws Exception {
		doTestSendDestination(true, true, true);
	}

	/**
	 * Test sending to the default destination using explicit QOS parameters.
	 */
	public void testSendDefaultDestinationWithQOS() throws Exception {
		doTestSendDestination(false, true, true);
	}

	/**
	 * Common method for testing a send method that uses the MessageCreator
	 * callback but with different QOS options.
	 * @param ignoreQOS test using default QOS options.
	 */
	private void doTestSendDestination(boolean ignoreQOS, boolean explicitDestination,
			boolean useDefaultDestination) throws Exception {

		JmsTemplate sender = new JmsTemplate();
		sender.setConnectionFactory(mockConnectionFactory);
		setJndiTemplate(sender);
		if (useDefaultDestination) {
			sender.setDefaultDestination(mockQueue);
		}

		MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
		MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();

		MockControl messageControl = MockControl.createControl(TextMessage.class);
		TextMessage mockMessage = (TextMessage) messageControl.getMock();

		mockSession.close();
		sessionControl.setVoidCallable(1);

		mockConnection.close();
		connectionControl.setVoidCallable(1);

		mockSession.createProducer(mockQueue);
		sessionControl.setReturnValue(mockMessageProducer);
		mockSession.createTextMessage("just testing");
		sessionControl.setReturnValue(mockMessage);

		sessionControl.replay();
		connectionControl.replay();

		if (ignoreQOS) {
			mockMessageProducer.send(mockMessage);
		}
		else {
			sender.setExplicitQosEnabled(true);
			sender.setDeliveryMode(deliveryMode);
			sender.setPriority(priority);
			sender.setTimeToLive(timeToLive);
			mockMessageProducer.send(mockMessage, deliveryMode, priority, timeToLive);
		}

		messageProducerControl.replay();

		if (useDefaultDestination) {
			sender.send(new MessageCreator() {
				public Message createMessage(Session session) throws JMSException {
					return session.createTextMessage("just testing");
				}
			});
		}
		else {
			if (explicitDestination) {
				sender.send(mockQueue, new MessageCreator() {
					public Message createMessage(Session session)
							throws JMSException {
						return session.createTextMessage("just testing");
					}
				});
			}
			else {
				sender.send("testDestination", new MessageCreator() {
					public Message createMessage(Session session)
							throws JMSException {
						return session.createTextMessage("just testing");
					}
				});
			}
		}

		connectionFactoryControl.verify();
		connectionControl.verify();
		messageProducerControl.verify();

		sessionControl.verify();

	}

	public void testConverter() throws Exception {
		JmsTemplate sender = new JmsTemplate();
		sender.setConnectionFactory(mockConnectionFactory);
		setJndiTemplate(sender);
		sender.setMessageConverter(new SimpleMessageConverter());
		String s = "Hello world";

		MockControl messageProducerControl = MockControl.createControl(MessageProducer.class);
		MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock();

		MockControl messageControl = MockControl.createControl(TextMessage.class);
		TextMessage mockMessage = (TextMessage) messageControl.getMock();

		mockSession.close();
		sessionControl.setVoidCallable(1);

		mockConnection.close();
		connectionControl.setVoidCallable(1);

		mockSession.createProducer(mockQueue);
		sessionControl.setReturnValue(mockMessageProducer);
		mockSession.createTextMessage("Hello world");
		sessionControl.setReturnValue(mockMessage);

		sessionControl.replay();
		connectionControl.replay();

		mockMessageProducer.send(mockMessage);

		messageProducerControl.replay();

		sender.convertAndSend(mockQueue, s);

		connectionFactoryControl.verify();
		connectionControl.verify();
		messageProducerControl.verify();

		sessionControl.verify();
	}

	public void testReceiveDefaultDestination() throws Exception {
		doTestReceive(false, true, false, false);
	}

	public void testReceiveDestination() throws Exception {
		doTestReceive(true, false, false, false);
	}

	public void testReceiveDestinationWithClientAcknowledge() throws Exception {
		doTestReceive(true, false, false, true);
	}

	public void testReceiveStringDestination() throws Exception {
		doTestReceive(false, false, false, false);
	}

	public void testReceiveAndConvertDefaultDestination() throws Exception {
		doTestReceive(false, true, true, false);
	}

	public void testReceiveAndConvertStringDestination() throws Exception {
		doTestReceive(false, false, true, false);
	}

	public void testReceiveAndConvertDestination() throws Exception {
		doTestReceive(true, false, true, false);
	}

	private void doTestReceive(boolean explicitDestination, boolean useDefaultDestination,
			boolean testConverter, boolean clientAcknowledge) throws Exception {

		JmsTemplate sender = new JmsTemplate();
		sender.setConnectionFactory(mockConnectionFactory);
		setJndiTemplate(sender);

		if (useDefaultDestination) {
			sender.setDefaultDestination(mockQueue);
		}

		mockConnection.start();
		connectionControl.setVoidCallable(1);
		mockConnection.close();
		connectionControl.setVoidCallable(1);

		MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class);
		MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock();

		mockSession.createConsumer(mockQueue);
		sessionControl.setReturnValue(mockMessageConsumer);
		mockSession.getAcknowledgeMode();
		if (clientAcknowledge) {
			sessionControl.setReturnValue(Session.CLIENT_ACKNOWLEDGE);
		}
		else {
			sessionControl.setReturnValue(Session.AUTO_ACKNOWLEDGE);
		}
		mockSession.close();
		sessionControl.setVoidCallable(1);

		MockControl messageControl = MockControl.createControl(TextMessage.class);
		TextMessage mockMessage = (TextMessage) messageControl.getMock();

		if (testConverter) {
			mockMessage.getText();
			messageControl.setReturnValue("Hello World!");
		}
		if (clientAcknowledge) {
			mockMessage.acknowledge();
			messageControl.setVoidCallable(1);
		}

		sessionControl.replay();
		connectionControl.replay();
		messageControl.replay();

		mockMessageConsumer.receive();
		messageConsumerControl.setReturnValue(mockMessage);
		mockMessageConsumer.close();
		messageConsumerControl.setVoidCallable(1);
		messageConsumerControl.replay();

		Message m = null;
		String textFromMessage = null;
		if (useDefaultDestination) {
			if (testConverter) {
				textFromMessage = (String) sender.receiveAndConvert();
			}
			else {
				m = sender.receive();
			}
		}
		else {
			if (explicitDestination) {
				if (testConverter) {
					textFromMessage = (String) sender.receiveAndConvert(mockQueue);
				}
				else {
					m = sender.receive(mockQueue);
				}
			}
			else {
				if (testConverter) {
					textFromMessage = (String) sender.receiveAndConvert("testDestination");
				}
				else {
					m = sender.receive("testDestination");
				}
			}
		}

		connectionFactoryControl.verify();
		connectionControl.verify();
		sessionControl.verify();
		messageConsumerControl.verify();
		messageControl.verify();

		if (testConverter) {
			assertEquals("Message Text should be equal", "Hello World!", textFromMessage);
		}
		else {
			assertEquals("Messages should refer to the same object", m, mockMessage);
		}
	}

	private void setJndiTemplate(JmsTemplate sender) {
		JndiDestinationResolver destMan = new JndiDestinationResolver();
		destMan.setJndiTemplate(new JndiTemplate() {
			protected Context createInitialContext() throws NamingException {
				return mockJndiContext;
			}
		});
		sender.setDestinationResolver(destMan);
	}

}


text:
package org.redisson.config;

/**
 *
 * @author Nikita Koksharov
 *
 */
public enum SslProvider {

    /**
     * Use JDK default implementation to handle SSL connection
     */
    JDK,

    /**
     * Use OpenSSL-based implementation to handle SSL connection.
     * netty-tcnative lib is required to be in classpath.
     */
    OPENSSL

}

redpajama_set_name: RedPajamaGithub


text:
package io.undertow.servlet.test.listener.request.async;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author Stuart Douglas
 */
public class AsyncServlet extends HttpServlet {

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        req.startAsync();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                req.getAsyncContext().dispatch("/message");
            }
        });
        t.start();
    }
}


text:
package ai.subut.kurjun.subutai;

import com.google.inject.AbstractModule;

import ai.subut.kurjun.subutai.service.SubutaiTemplateParser;

/**
 * Guice module to initialize Subutai template parser bindings.
 *
 */
public class SubutaiTemplateParserModule extends AbstractModule
{

    @Override
    protected void configure()
    {
        bind( SubutaiTemplateParser.class ).to( SubutaiTemplateParserImpl.class );
    }

}


text:
package com.simplechat.shared.commands;

/**
 * Created by lampt on 6/24/2017.
 */
public interface AbstractCommandBuilder {
    String build();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;

namespace TableDriver
{
	/**
	 * Row encapsulates low-level sql operations on entity instances
	 */
	public class Row
	{
		// retrieve objects by single field comparison
		// TODO: should this be a generic method? Then we can return List<T> directly
		public static List<object> GetByField( Type in_type, string in_field, string in_value ) {
			DbConfig config = new DbConfig();
			string qualifiedTableName = SqlUtil.WriteQualifiedName( config.Schema, in_type.Name );
			string qualifiedFieldName = SqlUtil.WriteQualifiedName( in_field );
			string sqlString = "select * from " + qualifiedTableName + " where " + qualifiedFieldName + " = '" + in_value + "'";
			IDataReader rdr = DbUtil.ExecuteReader( ConnectionFactory.GetConnection( new DbConfig() ), sqlString );

			List<object> retval = new List<object>();
			while( rdr.Read() ) {
				object obj = Activator.CreateInstance( in_type );
				PopulateObjectFromReader( obj, rdr );
				retval.Add( obj );
			}
			return retval;
		}

		private static void PopulateObjectFromReader( object obj, IDataReader reader ) {
			PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties( obj );
			for( int i = 0; i < descriptors.Count; i++ ) {
				object value = reader[ descriptors[ i ].Name ];
				descriptors[ i ].SetValue( obj, value );
			}
		}

		// TODO: only works with string datatypes
		public static void Insert( object obj ) {
			DbConfig config = new DbConfig();
			string tableName = obj.GetType().Name;
			string schemaName = config.Schema;
			string fields = SqlUtil.BuildFieldNames( obj );
			string values = SqlUtil.BuildFieldValues( obj );

			/*
			PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties( obj );
			for( int i = 0; i < descriptors.Count; i++ ) {
				Console.WriteLine( descriptors[ i ].Name + ": " + descriptors[i].GetValue( obj ).ToString() );
				fields += "[" + descriptors[i].Name + "]";
				values += "'" + descriptors[ i ].GetValue( obj ) + "'";
				if( i < descriptors.Count - 1 ) {
					fields += ",";
					values += ",";
				}
			}
			*/
			string qualifiedTableName = SqlUtil.WriteQualifiedName( schemaName, tableName );
			string sqlString = "insert into " + qualifiedTableName +
				" ( " + fields +
				" ) values ( " + values + " ) ";
			Console.WriteLine( sqlString );

			IDbConnection conn = ConnectionFactory.GetConnection( new DbConfig() );
			using( conn ) {
				IDataReader rdr = DbUtil.ExecuteReader( conn, sqlString );
				rdr.Close();
			}
		}
	} // class
} // namespace


text:
title: 009 - Apache Pulsar Connector
description: Jet source and sink for Apache Pulsar.
---

*Since*: Contrib Module

## Summary

Apache Pulsar connector enables Jet to ingest data from Pulsar topics
into Jet pipelines and publish messages to Pulsar topics.

It uses the Pulsar client library to read and publish messages from/to a
Pulsar topic. Pulsar client library provides two different ways of
reading messages from a topic. They are namely Consumer API and Reader
API that have major differences. Pulsar connectors have benefits of both
Consumer API and Reader API.

Besides, this Pulsar client library has an API called the Producer API.
The Pulsar connector enables users to use the Pulsar topic as a sink in
Jet pipelines.

## Implementation Details

In the implementation of the Apache Pulsar sources, both Consumer API
and Reader API are used. Each API is advantageous in different aspects
compared to one another.

By using the Consumer API, the distributed source is created without
dealing with the partition mapping - it is handled below this
abstraction level. But, since this API does not return the cursor for
the last consumed message, it is incapable of assuring fault-tolerance.
This issue will be discussed in the upcoming section.

As opposed to Consumer API, the Reader API helps us to build a source
that consumes through a Pulsar topic with an **exactly-once guarantee**
if the remaining sections of the pipeline also assure this.

### The Source using Consumer API

Pulsar provides an abstraction called Consumer API that is based on a
topic subscription. An application that subscribes to the topic can
consume messages from the first unacknowledged message for this
subscription.

The Consumer API has the 4 main operations listed below:

1. Subscribe to a topic.
2. Start to consume from the first unacknowledged message.
3. Consume messages
4. Send an acknowledgment to the broker.

#### Subscription Mode

A subscription determines how messages are delivered to consumers, and
it is identified by its subscription-name. There are three available
subscription modes in Pulsar: exclusive, shared, and failover. In the
Pulsar source connector using Consumer API abstraction, the shared or
round-robin mode is used. The shared subscription allows multiple
consumers to attach to the same subscription. The messages belong to the
subscribed topic are delivered in a round-robin distribution across
consumers, and any given message is delivered to only one consumer. When
a consumer disconnects, all the messages that were sent to it and not
acknowledged will be rescheduled for sending to the remaining consumers.
This subscription mode allows consuming messages in a distributed
manner. However, this distributed manner prevents the order of messages
from being preserved. Please see Pulsar's documentation for information
on other subscription options.

#### Message Receive Policy

Consumer API provides 4 different policies (2 for single or batch x 2
for sync or async) for receiving messages from the broker. These are

1. Blocking Single Receive
2. Async Single Receive
3. Blocking Batch Receive (Our choice)
4. Async Batch Receive

Since `SourceBuilder.SourceBuffer` and
`SourceBuilder.TimestampedSourceBuffer` are not thread-safe, it would
require extra care when async policies were chosen. Therefore, handling
the result of the async calls should not be performed by creating new
threads. This requirement conflicts with the usual practice of async
processing. That is why I did not prefer async policies.

We prefer to use batch receive assuming that it is better in
performance. The batch receiving of Pulsar consumer assures that "the
batch receive will be completed as long as anyone of the conditions(has
enough number of messages, has enough of the size of messages in terms
of bytes and number, wait for a timeout) is met". As the default batch
receive policy, we set timeout to 1000 ms and max number of messages to
512 messages. Since the batch receive policy of the consumer is more
likely to change, a separate builder setter is created for it.

#### Consumer API's acknowledgment mechanism

As a default, Pulsar Broker deletes a message from the topic provided
that all subscriptions for this topic acknowledge this message. By
changing the broker configurations, these fully-acknowledged messages
can continue to persist.

With a consumer, the application resume consuming from the first
unacknowledged message. It resembles the cursor mechanism but it hinders
some tricky conditions that can result in message loss. In order to
support fault-tolerance, the rollback mechanism should be able to
perform properly in case of failure. However, the acknowledgment
mechanism of Consumer API has no rollback mechanism.

#### Consumer API cannot support Fault-tolerance

At the first trial of mine, between two snapshotting times, I stored the
consumed messages ids in a list. Then, I tried to acknowledge the list
of messages at the snapshot time (by assuming the job does not fail at
snapshot time). But if the job fails during the snapshot, there is no
way to rollback these acknowledgments.  As a result, after the restart
of the job, the job loses these acknowledged messages. If the Consumer
API had a commit mechanism, it could guarantee exactly-once processing.

To avoid these complications, you could remove acknowledgment logic
entirely. But, this would introduce another short come: all of the
messages would be stored permanently unless any eviction mechanism
exists. For the continuous processes, this may cause excessive storage
usage.

Note that: The Pulsar consumer source does not fail fast in the scenario
that when the job reading Pulsar topic using the Pulsar consumer source
is running and Pulsar broker is closed, the job doesn't fail, it just
prints log at warn level. The reason for this is that the Pulsar Client
tries to reconnect to the broker with exponential backoff in this case,
and while doing this, we cannot notice the connection issue because it
only prints logs without throwing an exception.

#### The decision on Acknowledgement Design on Jet Connector

It should be determined when the messages are acknowledged or whether
should be acknowledged at all. The current implementation of the Pulsar
Consumer source acknowledges messages whenever it consumes them. It
should be noted that this implementation prevents at-least-once logic
let alone exactly-once.

This issue with existence and timing of acknowledgment should be
discussed further.

#### Summary of the Design Choices

The design choices regarding the usage of Consumer API are listed below:

1. Shared subscription mode is preferred.
2. Receive messages in a synchronous batch manner.
3. Immediately send acknowledgments to a Pulsar broker after consuming
   a batch of messages.

### The Source using Reader API

The Reader API is a lower-level API of the Pulsar. It does not have any
subscription mode or so. A user can simply read from a topic by telling
the Reader API from which message it should read onwards. The Reader API
provides us the `MessageId` of the earliest or latest message. You can use
one of these as the starting point for message reading. Or, the user can
declare the exact starting position by giving `MessageId` between these two
ends.  That being said, the current implementation of the source using
Reader API overwrites any user-specified preference on the starting
point and just reads from the earliest message onwards.

The implementation might require enhancements in order not to ignore the
user's preference on the starting point of reading messages.

#### Fault-tolerance support

Since Reader API enables us to start reading from a specified message,
the source using Reader API can provide exactly-once processing. In
Pulsar source using Reader API, the `MessageId` of the latest read message
is stored in the snapshot. In case of failure, the job restarts from the
latest snapshot and reads from the stored `MessageId`.

For further information about Reader API visit its
[documentation](https://pulsar.apache.org/docs/en/concepts-clients/#reader-interface).

Note that: The Pulsar reader source does not fail fast in the scenario
that when the job reading Pulsar topic using the Pulsar reader source is
running and Pulsar broker is closed, the job doesn't fail, it just
prints logs at warn level. The reason for this is that the Pulsar Client
tries to reconnect to the broker with exponential backoff in this case,
and while doing this, we cannot notice the connection issue because it
only prints logs without throwing an exception.

## The Sink

Pulsar has Producer API to publish messages to the topics.

Producer API provides 4 different options for sending messages to
brokers:

1. Sync Single Publish
2. Async Single Publish (Our choice)
3. Sync Batch Publish
4. Async Batch Publish

The builder pattern is used when constructing a Pulsar Sink. The
constructor of the builder, `PulsarSinkBuilder`, consists of the required
fields for Sink. The other optional fields can be added with setter
functions as well. At the sink, the messages are sent in an asynchronous
manner. This async sending has a retry mechanism, the max retry count is
set to 10.

### Fault-tolerance support on Sink

Pulsar does not provide a commit mechanism as a messaging system (they
want very low-latency). It has a deduplication mechanism to provide
exactly-once processing. After enabling the deduplication, the Pulsar
brokers remove the duplicate messages. It detects duplicates by looking
into the `SequenceId` field of messages which is added at publish-time.
Since the order of processing items cannot be guaranteed to be preserved
in Jet pipelines,  we cannot assign the same `SequenceId` to the same
message after a job restart.  The wrong assignments of `SequenceId` lead
to loss of messages, we cannot benefit from this deduplication
mechanism.

For more information about Pulsar producers
[look](https://pulsar.apache.org/docs/en/concepts-messaging/#producers).

## Common Properties of Sources and Sink

Both the source and sink creation APIs of the Pulsar connector implement
the builder pattern. We get the required parameters in the constructor
and other parameters in the setters. Configuration values are set to
default values and these default values can be changed using setters. We
have shown basic usage in all of the usage examples we provided, if you
want to change the values of optional parameters, you can use the setter
methods of the builder.
Both creating sources or sink of the Pulsar requires some kind of
projection functions from the user as a required parameter. These
functions are used to transform the data format with respect to the data
transfer direction. In the case of the source, we need to convert the
received Pulsar message to a Jet-compatible serializable data, that is,
emitting items. The Jet sources use `Event Time` of the Pulsar message
object as a timestamp, if it exists. Otherwise, its `Publish Time` is
used as a timestamp which always presents.

In turn, converting the processed items to the Pulsar message form is
required at the sink.

Additionally, Pulsar has a mechanism for type-safety called Schema.
Normally Pulsar allows messaging without schema, but we preferred to
impose schema usage while creating the sources and sink. It should be
noted that not using any schema is almost equivalent to using
Schema.BYTE in practice.

## Testing Details

The `PulsarTestSupport extends JetTestSupport` is formed to provide a
Pulsar container, Pulsar clients, 'source and sink setup functions' for
tests.

Various integration tests were to test the Pulsar connector. To test the
sources, firstly, a Pulsar container is initiated. Then, through some
client that is created in `PulsarTestSupport` for the purpose of testing
(external to Jet), some sequence of messages are published into a
pre-defined topic. After that, by using the Pulsar source,  we run a job
that reads from that topic. As the last step of the job,  we collect the
items and check whether all of the messages are read. To test the Pulsar
sink, we perform the steps above in reverse order.

To check fault tolerance support of PulsarReader source, distributed
node failure recovery is simulated. Two Jet instances are created and
the job is submitted to them. Once we make sure at least one snapshot is
created for the job, we enforce the job to restart by killing one of the
Jet instances and check if it manages not to lose or duplicate any
messages.

## Future Improvements

### Make the Source using Reader API Distributed

- The current version of the source using Reader API does not support
  distributed processing. It can be enabled by adding a custom partition
  mapping mechanism to it.

### Exactly-once at the sink

- If a mechanism for ordering processing items add to the Jet pipelines,
  then the exactly-once processing semantics can be achieved on the
  Pulsar sink

## Code Samples

### Pulsar Reader Source

Example code for Pulsar Reader Source can be found in this
[tutorial](../tutorials/pulsar.md).

### Pulsar Consumer Source

The program below creates a job that connects the local Pulsar cluster
located at `localhost:6650`(default address) and then consumes messages
from the pulsar topic, `hazelcast-demo-topic`,

```java
package com.hazelcast.jet.contrib.pulsar;

import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.StreamSource;
import org.apache.pulsar.client.api.BatchReceivePolicy;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PulsarConsumerDemo {

    public static void main(String[] args) {
        JetInstance jet = Jet.bootstrappedInstance();
        final StreamSource<Integer> pulsarConsumerSource = PulsarSources.pulsarConsumerBuilder(
                "hazelcast-demo-topic",
                () -> PulsarClient.builder().serviceUrl("pulsar://localhost:6650").build(),
                () -> Schema.INT32,
                Message::getValue).build();
        Pipeline pipeline = Pipeline.create();
        pipeline.readFrom(pulsarConsumerSource)
                .withoutTimestamps()
                .writeTo(Sinks.logger());
        jet.newJob(pipeline).join();
    }
}
```

The created source above uses default client configurations, you can
change them by using builder methods.

### Pulsar Sink

The program below creates a job that connects the local Pulsar cluster
located at `localhost:6650`(default address) and then publishes messages
to the pulsar topic, `hazelcast-demo-topic`,

```java
package com.hazelcast.jet.contrib.pulsar;

import com.hazelcast.function.FunctionEx;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;

import com.hazelcast.jet.config.JobConfig;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sink;

import com.hazelcast.jet.pipeline.test.TestSources;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.Schema;

import java.util.HashMap;
import java.util.Map;

public class PulsarProducerDemo {
    public static void main(String[] args) {
        JetInstance jet = Jet.bootstrappedInstance();
        Pipeline p = Pipeline.create();
        Sink<Integer> pulsarSink = PulsarSinks.builder(
                "hazelcast-demo-topic",
                () -> PulsarClient.builder()
                                  .serviceUrl("pulsar://localhost:6650")
                                  .build(),
                () -> Schema.INT32,
                FunctionEx.identity()).build();
        p.readFrom(TestSources.itemStream(15))
         .withoutTimestamps()
         .map(x -> (int) x.sequence())
         .writeTo(pulsarSink);

        JobConfig jobConfig = new JobConfig();
        jobConfig.setName("hazelcast-pulsar-producer");
        jet.newJob(p, jobConfig).join();
    }
}
```


text:
<!doctype html>

	<title>Scrubbing</title>
	<link href="../polymer-animation/polymer-animation.html" rel="import">
	<link href="polymer-scrub.html" rel="import">

	<polymer-element name="scrub-demo" attributes="scale scrubType snapPoints">
		<template>

			scale: <input id="scale" value="{{scale}}">
			scrubType: <input id="scrubType" value="{{scrubType}}">
			snapThreshold: <input id="snapThreshold" value="{{snapThreshold}}">

⊥

			<polymer-animation id="anim" target="{{$.c2}}" duration="3" fillMode="both">
				<polymer-animation-keyframe>
					<polymer-animation-prop name="transform" value="translate(0px, 0px) rotate(0deg)"></polymer-animation-prop>
					<polymer-animation-prop name="opacity" value="1"></polymer-animation-prop>
				</polymer-animation-keyframe>
				<polymer-animation-keyframe>
					<polymer-animation-prop name="transform" value="translate(200px, 0px) rotate(360deg)"></polymer-animation-prop>
					<polymer-animation-prop name="opacity" value="1"></polymer-animation-prop>
				</polymer-animation-keyframe>
				<polymer-animation-keyframe>
					<polymer-animation-prop name="transform" value="translate(400px, 0px) rotate(720deg)"></polymer-animation-prop>
					<polymer-animation-prop name="opacity" value="0.5"></polymer-animation-prop>
				</polymer-animation-keyframe>
				<polymer-animation-keyframe>
					<polymer-animation-prop name="transform" value="translate(600px, 0px) rotate(1080deg)"></polymer-animation-prop>
					<polymer-animation-prop name="opacity" value="1"></polymer-animation-prop>
				</polymer-animation-keyframe>
				<polymer-animation-keyframe>
					<polymer-animation-prop name="transform" value="translate(800px, 0px) rotate(1440deg)"></polymer-animation-prop>
					<polymer-animation-prop name="opacity" value="1"></polymer-animation-prop>
				</polymer-animation-keyframe>
			</polymer-animation>
			<polymer-scrub target="{{$.c}}" animation="{{$.anim.animation}}" scale="{{scale}}" scrubType="{{scrubType}}" snapPoints="{{snapPoints}}" snapThreshold="{{snapThreshold}}"></polymer-scrub>
		</template>

	</polymer-element>
	<scrub-demo></scrub-demo>


text:
layout:     post
title:      "模仿锤子阅读的下拉刷新"
subtitle:   ""
date:       2016-09-12 14:00:00
author:     "steven"
catalog:    true
tags:
    - IOS
---

模仿锤子阅读的下拉刷新效果

Demo:
---

![image]({{ site.baseurl }}/img/post/refresh_header.gif)

Usage:
---

```Swift
//oc
_scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
DxRefreshView *refreshHeader = [[DxRefreshView alloc] init];
refreshHeader.color = [UIColor blueColor];
refreshHeader.actionHandler = ^{
     //刷新数据
};
_scrollView.refreshHeader = refreshHeader;

//swift
let refreshHeader:DxRefreshView = DxRefreshView();
refreshHeader.color = UIColor.blue;
refreshHeader.actionHandler = {
    //刷新数据
};
tableView.setRefreshHeader(refreshHeader: refreshHeader);
```

刷新完成之后:

```Swift
//oc
[_scrollView.refreshHeader endRefreshing];
//swift
scrollView.endRefreshing();
```

不通过下拉触发,直接开始刷新:

```Swift
//oc
[_scrollView.refreshHeader beginRefreshing];
//swift
scrollView.beginRefreshing();
```

Source
---

>[Swift 3](https://github.com/StevenDXC/DxRefreshView)

>[Objective-c](https://github.com/StevenDXC/DxRefreshView_OC)


text:
import unittest, sys
from lxml.tests.common_imports import make_doctest, doctest
import lxml.html

def test_suite():
    suite = unittest.TestSuite()
    if sys.version_info >= (2,4):
        suite.addTests([make_doctest('test_basic.txt')])
    suite.addTests([doctest.DocTestSuite(lxml.html)])
    return suite

if __name__ == '__main__':
    unittest.main()


text:
"""
_views_test_

"""
import mock
import unittest

from cloudant.views import Code, View, DesignDocument
from cloudant.index import Index
from cloudant.document import Document

class CodeTests(unittest.TestCase):
    """tests for cloudant.views.Code, not much to test here yet..."""
    def test_code(self):
        """test instantiation/manipulation"""
        c = Code("function(doc){emit(doc._id, 1)}")

class ViewTests(unittest.TestCase):
    """tests for View class"""
    def setUp(self):
        self.map_func = "function(doc){emit(doc._id, 1)}"
        self.reduce_func = "_sum"

    def test_view_class(self):
        """test various methods of instantiation and properties"""
        ddoc = DesignDocument(mock.Mock(), "_design/tests")
        view1 = View(ddoc, "view1", map_func=self.map_func, reduce_func=self.reduce_func)
        view2 = View(ddoc, "view2", map_func=self.map_func)
        view3 = View(ddoc, "view1", map_func=Code(self.map_func), reduce_func=Code(self.reduce_func))
        view4 = View(ddoc, "view1", map_func=Code(self.map_func))

        self.assertEqual(view1.map, Code(self.map_func))
        self.assertEqual(view1.reduce, Code(self.reduce_func))
        self.assertEqual(view2.map, Code(self.map_func))
        self.assertEqual(view2.reduce, None)
        self.assertEqual(view3.map, Code(self.map_func))
        self.assertEqual(view3.reduce, Code(self.reduce_func))
        self.assertEqual(view4.map, Code(self.map_func))
        self.assertEqual(view4.reduce, None)

        view5 = View(ddoc, "view5")
        self.assertEqual(view5.map, None)
        self.assertEqual(view5.reduce, None)
        view5.map = self.map_func
        self.assertEqual(view5.map, Code(self.map_func))
        view5.reduce = self.reduce_func
        self.assertEqual(view5.reduce, Code(self.reduce_func))

    def test_view_access(self):
        """
        _test_view_access_

        Test accessing the data via the view

        """
        db = mock.Mock()
        db._database_name = 'unittest'
        ddoc = DesignDocument(db, "_design/tests")
        ddoc._database_host = "https://bob.cloudant.com"
        view1 = View(ddoc, "view1", map_func=self.map_func)

        self.assertEqual(
            view1.url,
            "https://bob.cloudant.com/unittest/_design/tests/_view/view1"
        )

    def test_view_context(self):
        db = mock.Mock()
        db._database_name = 'unittest'
        ddoc = DesignDocument(db, "_design/tests")
        ddoc._database_host = "https://bob.cloudant.com"
        view1 = View(ddoc, "view1", map_func=self.map_func)

        with view1.custom_index() as v:
            self.failUnless(isinstance(v, Index))

class DesignDocTests(unittest.TestCase):
    """
    tests for design doc object

    """
    @mock.patch.object(Document, 'fetch')
    def test_design_doc(self, mock_fetch):
        """test overridden methods work as expected"""
        mock_database = mock.Mock()
        ddoc = DesignDocument(mock_database, '_design/unittest')
        ddoc['views'] = {
            'view1' : {'map': "MAP", 'reduce': 'REDUCE'}
        }
        ddoc.fetch()

        self.failUnless(mock_fetch.called)
        views = [ x for _,x in ddoc.iterviews() ]
        self.assertEqual(len(views), 1)
        view = views[0]
        self.failUnless('view1' in view)
        self.assertEqual(view['view1']['map'], 'MAP')
        self.assertEqual(view['view1']['reduce'], 'REDUCE')
        self.failUnless('view1' in ddoc.views)

    def test_ddoc_add_view(self):
        mock_database = mock.Mock()
        with mock.patch('cloudant.views.DesignDocument.save') as mock_save:
            ddoc = DesignDocument(mock_database, '_design/unittest')
            ddoc['views'] = {
                'view1': {'map': "MAP", 'reduce': 'REDUCE'}
            }
            ddoc.add_view('view2', "MAP2")
            self.failUnless('view2' in ddoc['views'])
            self.assertEqual(ddoc['views']['view2'].map, 'MAP2')
            self.assertEqual(ddoc['views']['view2'].reduce, None)
            self.failUnless(mock_save.called)

    def test_list_views(self):
        mock_database = mock.Mock()
        ddoc = DesignDocument(mock_database, '_design/unittest')
        ddoc['views'] = {
            'view1': {'map': "MAP", 'reduce': 'REDUCE'},
            'view2': {'map': "MAP", 'reduce': 'REDUCE'},
        }
        self.assertEqual(ddoc.list_views(), ['view1', 'view2'])

if __name__ == '__main__':
    unittest.main()


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Getting started with Stratis – up and running)
[#]: via: (https://fedoramagazine.org/getting-started-with-stratis-up-and-running/)
[#]: author: (Gordon Keegan https://fedoramagazine.org/author/gmkeegan/)

Getting started with Stratis – up and running
======

![][1]

[Photo][2] by [Jeremy Lapak][3] on [Unsplash][4]

When adding storage to a Linux server, system administrators often use commands like _pvcreate_, _vgcreate_, _lvcreate_, and _mkfs_ to integrate the new storage into the system. [Stratis][5] is a command-line tool designed to make managing storage much simpler. It creates, modifies, and destroys pools of storage. It also allocates and deallocates filesystems from the storage pools.

Instead of an entirely in-kernel approach like ZFS or Btrfs, Stratis uses a hybrid approach with components in both user space and kernel land. It builds on existing block device managers like device mapper and existing filesystems like XFS. Monitoring and control is performed by a user space daemon.

Stratis tries to avoid some ZFS characteristics like restrictions on adding new hard drives or replacing existing drives with bigger ones. One of its main design goals is to achieve a positive command-line experience.

### Install Stratis

Begin by installing the required packages. Several Python-related dependencies will be automatically pulled in. The _stratisd_ package provides the _stratisd_ daemon which creates, manages, and monitors local storage pools. The _stratis-cli_ package provides the _stratis_ command along with several Python libraries.

```
# yum install -y stratisd stratis-cli
```

Next, enable the _stratisd_ service.

```
# systemctl enable --now stratisd
```

Note that the "enable –now" syntax shown above both permanently enables and immediately starts the service.

After determining what disks/block devices are present and available, the three basic steps to using Stratis are:

  1. Create a pool of the desired disks.
  2. Create a filesystem in the pool.
  3. Mount the filesystem.

In the following example, four virtual disks are available in a virtual machine. Be sure not to use the root/system disk (/dev/vda in this example)!

```
# sfdisk -s
/dev/vda:  31457280
/dev/vdb:   5242880
/dev/vdc:   5242880
/dev/vdd:   5242880
/dev/vde:   5242880
total:  52428800 blocks
```

### Create a storage pool using Stratis

```
# stratis pool create testpool /dev/vdb /dev/vdc
# stratis pool list
Name Total Physical Size  Total Physical Used
testpool   10 GiB         56 MiB
```

After creating the pool, check the status of its block devices:

```
# stratis blockdev list
Pool Name   Device Node Physical Size   State  Tier
testpool    /dev/vdb            5 GiB  In-use  Data
testpool    /dev/vdc            5 GiB  In-use  Data
```

### Create a filesystem using Stratis

Next, create a filesystem. As mentioned earlier, Stratis uses the existing DM (device mapper) and XFS filesystem technologies to create thinly-provisioned filesystems. By building on these existing technologies, large filesystems can be created and it is possible to add physical storage as storage needs grow.

```
# stratis fs create testpool testfs
# stratis fs list
Pool Name  Name   Used     Created                                 Device                    UUID
testpool   testfs 546 MiB  Apr 18 2020 09:15 /stratis/testpool/testfs  095fb4891a5743d0a589217071ff71dc
```

Note that "fs" in the example above can optionally be written out as "filesystem".

### Mount the filesystem

Next, create a mount point and mount the filesystem.

```
# mkdir /testdir
# mount /stratis/testpool/testfs /testdir
# df -h | egrep 'stratis|Filesystem'
Filesystem                                 Size  Used Avail Use% Mounted on
/dev/mapper/stratis-1-3e8e[truncated]71dc  1.0T  7.2G 1017G   1% /testdir
```

The actual space used by a filesystem is shown using the _stratis fs list_ command demonstrated previously. Notice how the _testdir_ filesystem has a virtual size of **1.0T**. If the data in a filesystem approaches its virtual size, and there is available space in the storage pool, Stratis will automatically grow the filesystem. Note that beginning with Fedora 34, the form of device path will be _/dev/stratis/<pool-name>/<filesystem-name>_.

### Add the filesystem to fstab

To configure automatic mounting of the filesystem at boot time, run following commands:

```
# UUID=`lsblk -n -o uuid /stratis/testpool/testfs`
# echo "UUID=${UUID} /testdir xfs defaults 0 0" >> /etc/fstab
```

After updating fstab, verify that the entry is correct by unmounting and mounting the filesystem:

```
# umount /testdir
# mount /testdir
# df -h | egrep 'stratis|Filesystem'
Filesystem                                 Size  Used Avail Use% Mounted on
/dev/mapper/stratis-1-3e8e[truncated]71dc  1.0T  7.2G 1017G   1% /testdir
```

### Adding cache devices with Stratis

Suppose _/dev/vdd_ is an available SSD (solid state disk). To configure it as a cache device and check its status, use the following commands:

```
# stratis pool add-cache testpool  /dev/vdd
# stratis blockdev
Pool Name   Device Node Physical Size  State    Tier
testpool    /dev/vdb            5 GiB  In-use   Data
testpool    /dev/vdc            5 GiB  In-use   Data
testpool    /dev/vdd            5 GiB  In-use   Cache
```

### Growing the storage pool

Suppose the _testfs_ filesystem is close to using all the storage capacity of _testpool_. You could add an additional disk/block device to the pool with commands similar to the following:

```
# stratis pool add-data testpool /dev/vde
# stratis blockdev
Pool Name  Device Node Physical Size   State    Tier
testpool   /dev/vdb            5 GiB   In-use   Data
testpool   /dev/vdc            5 GiB   In-use   Data
testpool   /dev/vdd            5 GiB   In-use   Cache
testpool   /dev/vde            5 GiB   In-use   Data
```

After adding the device, verify that the pool shows the added capacity:

```
# stratis pool
Name      Total Physical Size   Total Physical Used
testpool               15 GiB               606 MiB
```

### Conclusion

Stratis is a tool designed to make managing storage much simpler. Creating a filesystem with enterprise functionalities like thin-provisioning, snapshots, volume management, and caching can be accomplished quickly and easily with just a few basic commands.

See also [Getting Started with Stratis Encryption][6].

--------------------------------------------------------------------------------

via: https://fedoramagazine.org/getting-started-with-stratis-up-and-running/

作者:[Gordon Keegan][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://fedoramagazine.org/author/gmkeegan/
[b]: https://github.com/lujun9972
[1]: https://fedoramagazine.org/wp-content/uploads/2020/11/stratis-up-and-running-816x345.jpg
[2]: https://unsplash.com/photos/CVvFVQ_-oUg
[3]: https://unsplash.com/@jeremy_justin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText
[4]: https://unsplash.com/s/photos/runner?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText
[5]: https://stratis-storage.github.io/
[6]: https://fedoramagazine.org/getting-started-with-stratis-encryption/


text:
import React, {Component} from 'react'
import CustToolbarAndroid from './compent/CustToolbarAndroid'
import {
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableNativeFeedback,
    View
} from 'react-native';

import ToastCustomAndroid from './CustDemo'

export default class ReactAndroidInteractiveDemo extends Component {
    state={
        back:"",
        wode:"ceshi"
    }
    _onPressButton=()=>{

    }
    render() {
        return (
            <View>
                <CustToolbarAndroid title="自定义弹出Toast消息" {...this.props} />

                <TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackground()}>
                    <View style={{flex:1,height:100, backgroundColor:"#FFE5D7",alignItems: "center",justifyContent:"center",margin:5}}><Text>Button</Text></View>
                    </TouchableNativeFeedback>

                <CustomButton
                    text="点击自定义Toast方法"
                    onPress={()=>ToastCustomAndroid.toast("我是ToastCustomAndroid弹出消息")}
                />
                <CustomButton
                    text="点击测试封装方法"
                    onPress={()=>ToastCustomAndroid.measureLayout((msg) => {
                    console.log(msg);
                  },
                   (x, y, width, height) => {
                        this.setState({
                            back:x + '坐标,' + y + '坐标,' + width + '宽,' + height+'高'
                        })
                       console.log( this.state)
                  })}
                />
                <CustomButton
                    text={this.state.back}
                    onPress={()=>ToastCustomAndroid.toast("我是ToastCustomAndroid弹出消息")}
                />
            </View>
        );
    }
}

class CustomButton extends React.Component {
    render() {
        return (
            <TouchableHighlight
                style={styles.button}
                underlayColor="#a5a5a5"
                onPress={this.props.onPress}>
                <Text style={styles.buttonText}>{this.props.text}</Text>
            </TouchableHighlight>
        );
    }
}
//onPress={()=>NativeModules.ToastCustomAndroid.show("我是ToastCustomAndroid弹出消息",NativeModules.ToastCustomAndroid.SHORT)}

const styles = StyleSheet.create({
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    button: {
        margin:5,
        backgroundColor: 'white',
        padding: 15,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#cdcdcd',
    },
});


text:
namespace content {

NoTransportImageTransportFactory::NoTransportImageTransportFactory(
    ui::ContextFactory* context_factory)
    : context_factory_(context_factory) {}

NoTransportImageTransportFactory::~NoTransportImageTransportFactory() {}

ui::ContextFactory* NoTransportImageTransportFactory::AsContextFactory() {
  return context_factory_.get();
}

gfx::GLSurfaceHandle
NoTransportImageTransportFactory::CreateSharedSurfaceHandle() {
  return gfx::GLSurfaceHandle();
}

void NoTransportImageTransportFactory::DestroySharedSurfaceHandle(
    gfx::GLSurfaceHandle surface) {}

scoped_refptr<ui::Texture>
NoTransportImageTransportFactory::CreateTransportClient(
    float device_scale_factor) {
  return NULL;
}

scoped_refptr<ui::Texture> NoTransportImageTransportFactory::CreateOwnedTexture(
    const gfx::Size& size,
    float device_scale_factor,
    unsigned int texture_id) {
  return NULL;
}

GLHelper* NoTransportImageTransportFactory::GetGLHelper() { return NULL; }

uint32 NoTransportImageTransportFactory::InsertSyncPoint() { return 0; }

void NoTransportImageTransportFactory::WaitSyncPoint(uint32 sync_point) {}

// We don't generate lost context events, so we don't need to keep track of
// observers
void NoTransportImageTransportFactory::AddObserver(
    ImageTransportFactoryObserver* observer) {}

void NoTransportImageTransportFactory::RemoveObserver(
    ImageTransportFactoryObserver* observer) {}

}  // namespace content


text:
<title>
It's our right to protest
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Seattle police settle with anti-WTO demonstrators

It's our right to protest

February 20, 2004 | Page 4

Dear Socialist Worker,

The chaos in the streets at protests against the World Trade Organization (WTO) in Seattle in December 1999 shook the world. The media and the city of Seattle were quick to lay the blame on "crazy anarchists" and "rioting protesters."

But the truth was that the vast majority of violence came from the cops of Seattle, who went completely out of control. The police aggressively herded people into a blocked-off area. They used pepper spray and tear gas indiscriminately on hundreds of people. Over the course of the weekend, 600 people were arrested. Many of them were kept in jail for three to five days.

The brutal methods used by the Seattle police during the WTO protests set the standard for police forces across the country. Since 1999, pepper spray, teargas, rubber bullets and mass arrests have been used against demonstrations across the country.

After the Seattle protests, it seemed to many activists like the police were "untouchable." But global justice activists won an important victory recently when the city of Seattle agreed to pay $250,000 to more than 150 people arrested during the WTO protests. A federal judge had declared that the Seattle police had no probable cause for the arrests and called their record-keeping "atrocious," because of their use of photocopied arrest warrants and a signature on warrants from a policeman who admitted that he had not made any of the arrests.

After the decision, the city agreed to settle the class-action lawsuit in order to avoid a full trial. This payment represents an admission of wrongdoing by the city and its police force.

But the settlement presents challenges for activists, too. By settling out of court, the city did not have to officially accept liability for its mistakes and has been able to avoid a public trial and further legal actions. No police officer, or the city officials who approved of their Gestapo tactics, has had to face any criminal charges.

The amount of money--about $1,500 per person after lawyers' fees--is not nearly enough restitution for people who were locked up for days "until the WTO was over." The length of time it took for the city to pay up is also a problem.

While some important decisions may go our way, the "injustice" system is overwhelmingly biased towards protecting the police. More pressure from outside the courts is needed to hold them truly accountable, and to protect our basic rights of freedom of speech and assembly.

Ellie Fingerman, Seattle

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
package sfc.placement

import play.api.libs.json.JsString

/**
 * @author noel.yap@gmail.com
 */
object VertexOrientation extends Enumeration {
  type VertexOrientation = Value

  val Top = Value
  val TopRight = Value
  val BottomRight = Value
  val Bottom = Value
  val BottomLeft = Value
  val TopLeft = Value

  class OrientationValue(orientation: Value) {
    def toJson = JsString(orientation.toString)
    def before = VertexOrientation((orientation.id + maxId - 1) % maxId)
    def after = VertexOrientation((orientation.id + 1) % maxId)
    def to(to: VertexOrientation): List[VertexOrientation] = {
      val ids: List[Int] = if (orientation.id > to.id) {
        (orientation.id until VertexOrientation.maxId).toList ::: (0 to to.id).toList
      } else {
        (orientation.id to to.id).toList
      }

      ids map {
        VertexOrientation(_)
      }
    }
  }

  implicit def value2OrientationValue(orientation: Value) = new OrientationValue(orientation)
}


text:
<Record>
<Term>Duchenne Muscular Dystrophy</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Muscular Dystrophies</ParentTerm>
<ParentTerm>Genetic Diseases, X-Linked</ParentTerm>
<ClassificationPath>Congenital, Hereditary, and Neonatal Diseases and Abnormalities/Genetic Diseases, Inborn/Muscular Dystrophies/Muscular Dystrophy, Duchenne</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Neuromuscular Diseases/Muscular Diseases/Muscular Disorders, Atrophic/Muscular Dystrophies/Muscular Dystrophy, Duchenne</ClassificationPath>
<ClassificationPath>Congenital, Hereditary, and Neonatal Diseases and Abnormalities/Genetic Diseases, Inborn/Genetic Diseases, X-Linked/Muscular Dystrophy, Duchenne</ClassificationPath>
<ClassificationPath>Musculoskeletal Diseases/Muscular Diseases/Muscular Disorders, Atrophic/Muscular Dystrophies/Muscular Dystrophy, Duchenne</ClassificationPath>
<BroaderTerm>Genetic Diseases, Inborn</BroaderTerm>
<BroaderTerm>Muscular Dystrophies</BroaderTerm>
<BroaderTerm>Musculoskeletal Diseases</BroaderTerm>
<BroaderTerm>Muscular Diseases</BroaderTerm>
<BroaderTerm>Congenital, Hereditary, and Neonatal Diseases and Abnormalities</BroaderTerm>
<BroaderTerm>Genetic Diseases, X-Linked</BroaderTerm>
<BroaderTerm>Muscular Dystrophy, Duchenne</BroaderTerm>
<BroaderTerm>Muscular Disorders, Atrophic</BroaderTerm>
<BroaderTerm>Neuromuscular Diseases</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<Synonym>Pseudohypertrophic Muscular Dystrophies</Synonym>
<Synonym>Pseudohypertrophic Childhood Muscular Dystrophy</Synonym>
<Synonym>Duchenne-Type Progressive Muscular Dystrophy</Synonym>
<Synonym>Duchenne Muscular Dystrophy</Synonym>
<Synonym>Duchenne Type Progressive Muscular Dystrophy</Synonym>
<Synonym>Childhood Pseudohypertrophic Muscular Dystrophy</Synonym>
<Synonym>Pseudohypertrophic Muscular Dystrophy</Synonym>
<Synonym>Becker Muscular Dystrophy</Synonym>
<Description>An X-linked recessive muscle disease caused by an inability to synthesize DYSTROPHIN, which is involved with maintaining the integrity of the sarcolemma. Muscle fibers undergo a process that features degeneration and regeneration. Clinical manifestations include proximal weakness in the first few years of life, pseudohypertrophy, cardiomyopathy (see MYOCARDIAL DISEASES), and an increased incidence of impaired mentation. Becker muscular dystrophy is a closely related condition featuring a later onset of disease (usually adolescence) and a slowly progressive course. (Adams et al., Principles of Neurology, 6th ed, p1415)</Description>
<Source>MeSH</Source>
</Record>


text:
<?hh // strict

function send_email(string $to, string $subject, :x:base $content, ?string $from = null) : void {
	(new beatbox\mailer\Outbound($to, $subject, $content, $from))->send();
}


text:
interface Colors {
    lower: string;
    upper: string;
}

interface Label {
    index: number,
    label?: string,
    align?: string;
}

interface SliderOptions {
    slider?: JQuery;
    colors?: Colors;
    labels?: boolean|Array<Label|number>;
    value?: number;
    max?: number;
    min?: number;
    step?: number;
    ticks?: number[]|boolean;
    title?: boolean;
    thumbWidth?: number;
    onInit?: (slider: Slider) => void;
    onSlide?: (slider: Slider) => void;
    onChange?: (slider: Slider) => void;
    onDestroy?: () => void;
    disabled?: boolean;
}

interface ParsedSliderOptions {
    colors: Colors;
    labels: Label[];
    value: number;
    max: number;
    min: number;
    step: number;
    ticks: number[];
    thumbWidth: number;
    onInit: (slider: Slider) => void;
    onSlide: (slider: Slider) => void;
    onChange: (slider: Slider) => void;
    onDestroy: () => void;
}

interface JQuery {
    slider(opts?: SliderOptions|string|number): JQuery;
}


text:
require 'rails_helper'

RSpec.describe Ticket, type: :model do
  it { is_expected.to belong_to(:user) }
  it { is_expected.to belong_to(:status) }
  it { is_expected.to have_many(:messages).dependent(:destroy) }

  it { is_expected.to validate_presence_of :subject }
  it { is_expected.to validate_presence_of :customer_name }
  it { is_expected.to validate_presence_of :customer_email }

  describe '::with_status' do
    let!(:status1) { create :status, name: 'Waiting for Staff Response' }
    let!(:status2) { create :status, name: 'On Hold' }
    let!(:ticket1) { create :ticket, :without_validations, status: status1, reference_number: 'A1' }
    let!(:ticket2) { create :ticket, :without_validations, status: status1, reference_number: 'A2' }
    let!(:ticket3) { create :ticket, :without_validations, status: status2, reference_number: 'B1' }

    specify do
      expect(described_class.with_status('Invalid')).to  contain_exactly(ticket1, ticket2, ticket3)
      expect(described_class.with_status('On Hold')).to  contain_exactly(ticket3)
    end
  end

  describe '::with_reference_number' do
    let!(:status1) { create :status, name: 'Waiting for Staff Response' }
    let!(:status2) { create :status, name: 'On Hold' }
    let!(:ticket1) { create :ticket, :without_validations, status: status1, reference_number: 'A1' }
    let!(:ticket2) { create :ticket, :without_validations, status: status1, reference_number: 'A2' }
    let!(:ticket3) { create :ticket, :without_validations, status: status2, reference_number: 'B1' }

    specify do
      expect(described_class.with_reference_number('Invalid')).to be_empty
      expect(described_class.with_reference_number('A1')).to contain_exactly(ticket1)
      expect(described_class.with_reference_number('B1')).to contain_exactly(ticket3)
    end
  end

  describe '::with_subject' do
    let!(:status1) { create :status, name: 'Waiting for Staff Response' }
    let!(:status2) { create :status, name: 'On Hold' }
    let!(:ticket1) { create :ticket, :without_validations, status: status1, subject: 'A1 S' }
    let!(:ticket2) { create :ticket, :without_validations, status: status1, subject: 'A2' }
    let!(:ticket3) { create :ticket, :without_validations, status: status2, subject: 'B1' }

    specify do
      expect(described_class.with_subject('Invalid')).to be_empty
      expect(described_class.with_subject('A')).to contain_exactly(ticket1, ticket2)
      expect(described_class.with_subject('B1')).to contain_exactly(ticket3)
    end
  end

  describe '::search_by_params' do
    let(:ticket_with_status)           { double :ticket_with_status }
    let(:ticket_with_reference_number) { double :ticket_with_reference_number }
    let(:ticket_with_subject)          { double :ticket_with_subject }
    let(:params) do
      { status: double(:status), reference_number: double(:reference_number), subject: double(:subject) }
    end

    before do
      allow(described_class).to receive(:with_status) { ticket_with_status }
      allow(ticket_with_status).to receive(:with_reference_number) { ticket_with_reference_number }
      allow(ticket_with_reference_number).to receive(:with_subject) { ticket_with_subject }
    end

    it {expect(described_class.search_by_params(params)).to eq  ticket_with_subject}
  end
end


text:
/* Basic console example (esp_console_repl API)

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <string.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_console.h"
#include "esp_vfs_dev.h"
#include "esp_vfs_fat.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "cmd_system.h"
#include "cmd_wifi.h"
#include "cmd_nvs.h"

static const char* TAG = "example";
#define PROMPT_STR CONFIG_IDF_TARGET

/* Console command history can be stored to and loaded from a file.
 * The easiest way to do this is to use FATFS filesystem on top of
 * wear_levelling library.
 */
#if CONFIG_CONSOLE_STORE_HISTORY

#define MOUNT_PATH "/data"
#define HISTORY_PATH MOUNT_PATH "/history.txt"

static void initialize_filesystem(void)
{
    static wl_handle_t wl_handle;
    const esp_vfs_fat_mount_config_t mount_config = {
            .max_files = 4,
            .format_if_mount_failed = true
    };
    esp_err_t err = esp_vfs_fat_spiflash_mount_rw_wl(MOUNT_PATH, "storage", &mount_config, &wl_handle);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
        return;
    }
}
#endif // CONFIG_STORE_HISTORY

static void initialize_nvs(void)
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK( nvs_flash_erase() );
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);
}

void app_main(void)
{
    esp_console_repl_t *repl = NULL;
    esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
    /* Prompt to be printed before each line.
     * This can be customized, made dynamic, etc.
     */
    repl_config.prompt = PROMPT_STR ">";
    repl_config.max_cmdline_length = CONFIG_CONSOLE_MAX_COMMAND_LINE_LENGTH;

    initialize_nvs();

#if CONFIG_CONSOLE_STORE_HISTORY
    initialize_filesystem();
    repl_config.history_save_path = HISTORY_PATH;
    ESP_LOGI(TAG, "Command history enabled");
#else
    ESP_LOGI(TAG, "Command history disabled");
#endif

    /* Register commands */
    esp_console_register_help_command();
    register_system();
    register_wifi();
    register_nvs();

#if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) || defined(CONFIG_ESP_CONSOLE_UART_CUSTOM)
    esp_console_dev_uart_config_t hw_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_console_new_repl_uart(&hw_config, &repl_config, &repl));

#elif defined(CONFIG_ESP_CONSOLE_USB_CDC)
    esp_console_dev_usb_cdc_config_t hw_config = ESP_CONSOLE_DEV_CDC_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_console_new_repl_usb_cdc(&hw_config, &repl_config, &repl));

#elif defined(CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG)
    esp_console_dev_usb_serial_jtag_config_t hw_config = ESP_CONSOLE_DEV_USB_SERIAL_JTAG_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_console_new_repl_usb_serial_jtag(&hw_config, &repl_config, &repl));

#else
#error Unsupported console type
#endif

    ESP_ERROR_CHECK(esp_console_start_repl(repl));
}


text:
from __future__ import unicode_literals

from django.utils.translation import ugettext as _

from ..utils.emails import umanage_send_email

def send_change_forgot_username_email(to_user,
                                      markdown_template='umanage/emails/forgot_username.md',
                                      **kwargs):
    """Sends an email to a user letting them know their username."""
    return umanage_send_email(
        to_user=to_user,
        subject=_('The Username You Requested'),
        markdown_template=markdown_template,
        **kwargs)


text:
/**
 * Class definition for a MicroBit Device Firmware Update loader.
 *
 * This is actually just a frontend to a memory resident nordic DFU loader.
 *
 * We rely on the BLE standard pairing processes to provide encryption and authentication.
 * We assume any device that is paied with the micro:bit is authorized to reprogram the device.
 *
 */
#include "MicroBitConfig.h"
#include "MicroBitDFUService.h"
#include "ble/UUID.h"
#include "MicroBitConfig.h"

#if !defined(__arm)
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif

/*
 * The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ
 * If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL)
 * The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this
 * as a compatability option, but does not support the options used...
 */
extern "C" {
#include "dfu_app_handler.h"
}

/*
 * Return to our predefined compiler settings.
 */
#if !defined(__arm)
#pragma GCC diagnostic pop
#endif

/**
  * Constructor.
  * Initialise the Device Firmware Update service.
  * @param _ble The instance of a BLE device that we're running on.
  */
MicroBitDFUService::MicroBitDFUService(BLEDevice &_ble) :
    ble(_ble)
{
    // Opcodes can be issued here to control the MicroBitDFU Service, as defined above.
    GattCharacteristic  microBitDFUServiceControlCharacteristic(MicroBitDFUServiceControlCharacteristicUUID, &controlByte, 0, sizeof(uint8_t),
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE);

    controlByte = 0x00;

    // Set default security requirements
    microBitDFUServiceControlCharacteristic.requireSecurity(SecurityManager::MICROBIT_BLE_SECURITY_LEVEL);

    GattCharacteristic *characteristics[] = {&microBitDFUServiceControlCharacteristic};
    GattService         service(MicroBitDFUServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *));

    ble.addService(service);

    microBitDFUServiceControlCharacteristicHandle = microBitDFUServiceControlCharacteristic.getValueHandle();

    ble.gattServer().write(microBitDFUServiceControlCharacteristicHandle, &controlByte, sizeof(uint8_t));
    ble.gattServer().onDataWritten(this, &MicroBitDFUService::onDataWritten);
}

/**
  * Callback. Invoked when any of our attributes are written via BLE.
  */
void MicroBitDFUService::onDataWritten(const GattWriteCallbackParams *params)
{
    if (params->handle == microBitDFUServiceControlCharacteristicHandle)
    {
        if(params->len > 0 && params->data[0] == MICROBIT_DFU_OPCODE_START_DFU)
        {
            // TODO: Raise a SYSTEM event here.
            //uBit.display.stopAnimation();
            //uBit.display.clear();

#if CONFIG_ENABLED(MICROBIT_DBG)
            printf("  ACTIVATING BOOTLOADER.\n");
#endif

            // Perform an explicit disconnection to assist our peer to reconnect to the DFU service
            ble.disconnect(Gap::REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF);

            wait_ms(1000);

            // Call bootloader_start implicitly trough a event handler call
            // it is a work around for bootloader_start not being public in sdk 8.1
            ble_dfu_t p_dfu;
            ble_dfu_evt_t p_evt;

            p_dfu.conn_handle = params->connHandle;
            p_evt.ble_dfu_evt_type = BLE_DFU_START;

            dfu_app_on_dfu_evt(&p_dfu, &p_evt);
        }
    }
}

/**
  * UUID definitions for BLE Services and Characteristics.
  */
const uint8_t              MicroBitDFUServiceUUID[] = {
    0xe9,0x5d,0x93,0xb0,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};

const uint8_t              MicroBitDFUServiceControlCharacteristicUUID[] = {
    0xe9,0x5d,0x93,0xb1,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/power_source_coordinatorLayout"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/power_source" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/activity_powersource_layout" />

    <View
        android:id="@+id/shadow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:alpha="0"/>

    <include layout="@layout/bottom_sheet_powersource" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
@extends('layouts.masterLayout')

@section('html_title', 'Help & About')

@section('page_content')

Getting Help with SeAT only sorry >:)

            <button class="btn btn-primary btn-sm"></button>
            <button class="btn btn-primary btn-sm" data-widget="remove"></button>

If you are totally stuck, have feature ideas etc, use the following channels to get into contact!

SeAT the SeAT Project

Documentation for install & upgrade guides

EVE-O Forum Post for general information and help

Github Issues for SeAT specific errors

@qu1ckkkk on twitter for general crap, oh and SeAT announcements

qu1ckkkk ingame Character

Version Information

            <button class="btn btn-primary btn-sm"></button>
            <button class="btn btn-primary btn-sm" data-widget="remove"></button>

          @if ($versions_behind > 0)

              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
              Hmm... Your install of SeAT is {{ $versions_behind }} version(s) behind! You should consider upgrading :)

              You are running version {{ \Config::get('seat.version') }} and version {{ $release_data[0]->tag_name }} is available.

            @if (is_array($release_data))

              @foreach (array_slice($release_data, 0, $versions_behind) as $release)

 {{ $release->name }}

                      Released: {{ Carbon\Carbon::parse($release->published_at)->diffForHumans() }} by {{ $release->author->login }}
                      Upgrade Guide

{{ $release->body }}

              @endforeach

            @else
              Unable to get realease information. Github could not be successfully reached.
            @endif

          @else

              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
              You are running version {{ \Config::get('seat.version') }} of SeAT which is the latest.

          @endif

@stop


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Backgrounds;
using OpenTK;
using osu.Framework.Localisation;
using osu.Game.Screens.Menu;

namespace osu.Game.Screens.Play
{
    public class PlayerLoader : OsuScreen
    {
        private Player player;

        private BeatmapMetadataDisplay info;

        private bool showOverlays = true;
        public override bool ShowOverlays => showOverlays;

        public override bool AllowBeatmapRulesetChange => false;

        protected override BackgroundScreen CreateBackground() => new BackgroundScreenBeatmap(Beatmap);

        public PlayerLoader(Player player)
        {
            this.player = player;

            player.RestartRequested = () =>
            {
                showOverlays = false;
                ValidForResume = true;
            };
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Add(info = new BeatmapMetadataDisplay(Beatmap)
            {
                Alpha = 0,
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
            });

            LoadComponentAsync(player);
        }

        protected override void OnResuming(Screen last)
        {
            base.OnResuming(last);

            contentIn();

            //we will only be resumed if the player has requested a re-run (see ValidForResume setting above)
            LoadComponentAsync(player = new Player
            {
                RestartCount = player.RestartCount + 1,
                RestartRequested = player.RestartRequested,
            });

            this.Delay(400).Schedule(pushWhenLoaded);
        }

        private void contentIn()
        {
            Content.ScaleTo(1, 650, Easing.OutQuint);
            Content.FadeInFromZero(400);
        }

        private void contentOut()
        {
            Content.ScaleTo(0.7f, 300, Easing.InQuint);
            Content.FadeOut(250);
        }

        protected override void OnEntering(Screen last)
        {
            base.OnEntering(last);

            Background.FadeTo(0.4f, 250);

            Content.ScaleTo(0.7f);

            contentIn();

            info.Delay(750).FadeIn(500);
            this.Delay(2150).Schedule(pushWhenLoaded);
        }

        protected override void LogoArriving(OsuLogo logo, bool resuming)
        {
            base.LogoArriving(logo, resuming);

            logo.RelativePositionAxes = Axes.Both;

            logo.ScaleTo(new Vector2(0.15f), 300, Easing.In);
            logo.MoveTo(new Vector2(0.5f), 300, Easing.In);
            logo.FadeIn(350);

            logo.Delay(resuming ? 0 : 500).MoveToOffset(new Vector2(0, -0.24f), 500, Easing.InOutExpo);
        }

        private void pushWhenLoaded()
        {
            if (player.LoadState != LoadState.Ready)
            {
                Schedule(pushWhenLoaded);
                return;
            }

            contentOut();

            this.Delay(250).Schedule(() =>
            {
                if (!IsCurrentScreen) return;

                if (!Push(player))
                    Exit();
                else
                {
                    //By default, we want to load the player and never be returned to.
                    //Note that this may change if the player we load requested a re-run.
                    ValidForResume = false;
                }
            });
        }

        protected override bool OnExiting(Screen next)
        {
            Content.ScaleTo(0.7f, 150, Easing.InQuint);
            this.FadeOut(150);

            return base.OnExiting(next);
        }

        private class BeatmapMetadataDisplay : Container
        {
            private class MetadataLine : Container
            {
                public MetadataLine(string left, string right)
                {
                    AutoSizeAxes = Axes.Both;
                    Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Anchor = Anchor.TopCentre,
                            Origin = Anchor.TopRight,
                            Margin = new MarginPadding { Right = 5 },
                            Colour = OsuColour.Gray(0.5f),
                            Text = left,
                        },
                        new OsuSpriteText
                        {
                            Anchor = Anchor.TopCentre,
                            Origin = Anchor.TopLeft,
                            Margin = new MarginPadding { Left = 5 },
                            Text = string.IsNullOrEmpty(right) ? @"-" : right,
                        }
                    };
                }
            }

            private readonly WorkingBeatmap beatmap;

            public BeatmapMetadataDisplay(WorkingBeatmap beatmap)
            {
                this.beatmap = beatmap;
            }

            [BackgroundDependencyLoader]
            private void load(LocalisationEngine localisation)
            {
                var metadata = beatmap?.BeatmapInfo?.Metadata ?? new BeatmapMetadata();

                AutoSizeAxes = Axes.Both;
                Children = new Drawable[]
                {
                    new FillFlowContainer
                    {
                        AutoSizeAxes = Axes.Both,
                        Origin = Anchor.TopCentre,
                        Anchor = Anchor.TopCentre,
                        Direction = FillDirection.Vertical,
                        Children = new Drawable[]
                        {
                            new OsuSpriteText
                            {
                                Current = localisation.GetUnicodePreference(metadata.TitleUnicode, metadata.Title),
                                TextSize = 36,
                                Font = @"Exo2.0-MediumItalic",
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                            },
                            new OsuSpriteText
                            {
                                Current = localisation.GetUnicodePreference(metadata.ArtistUnicode, metadata.Artist),
                                TextSize = 26,
                                Font = @"Exo2.0-MediumItalic",
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                            },
                            new Container
                            {
                                Size = new Vector2(300, 60),
                                Margin = new MarginPadding(10),
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                                CornerRadius = 10,
                                Masking = true,
                                Children = new[]
                                {
                                    new Sprite
                                    {
                                        RelativeSizeAxes = Axes.Both,
                                        Texture = beatmap?.Background,
                                        Origin = Anchor.Centre,
                                        Anchor = Anchor.Centre,
                                        FillMode = FillMode.Fill,
                                    },
                                }
                            },
                            new OsuSpriteText
                            {
                                Text = beatmap?.BeatmapInfo?.Version,
                                TextSize = 26,
                                Font = @"Exo2.0-MediumItalic",
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                                Margin = new MarginPadding
                                {
                                    Bottom = 40
                                },
                            },
                            new MetadataLine("Source", metadata.Source)
                            {
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                            },
                            new MetadataLine("Composer", string.Empty)
                            {
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                            },
                            new MetadataLine("Mapper", metadata.Author.Username)
                            {
                                Origin = Anchor.TopCentre,
                                Anchor = Anchor.TopCentre,
                            },
                        },
                    }
                };
            }
        }
    }
}


text:
<?php

defined('APPLICATION_DIR') OR exit();

class CustomAccessRightApi extends CustomAccessRightController
{
    var $module = 'customaccessright';
    var $type = 'api';

	function searchAction() {
	    AclApi::checkPermission('customaccessright', 'list');

		$keyword = isset($_REQUEST['keyword'])? $_REQUEST['keyword'] : '';

		$model = new CustomAccessRightModel();

		$model->selectAdd();
		$model->selectAdd('ID, VALID_FROM');

		if (!empty($keyword)) {
			$model->whereAdd("VALID_FROM LIKE '%$keyword%'");
		}

        $model->orderBy('VALID_FROM');
        $model->limit(10);

		$model->find();

		$rows = array();
		while ($model->fetch()) {
			$rows[] = $model->VALID_FROM;
		}

		echo json_encode($rows);
	}

    function listAction() {
	    AclApi::checkPermission('customaccessright', 'list');

        if (isset($_REQUEST['page'])) {
            $this->updatePageNumber($_REQUEST['page']);
        }

        if (!isset($_REQUEST['limit'])) {
            $_REQUEST['limit'] = '*';
        }

        $this->updatePageSize($_REQUEST['limit']);

        $this->updatePageNumber(1);

        if (isset($_REQUEST['sort'])) {
            $this->updateOrderBy(strtoupper($_REQUEST['sort']));
        }

        $orderby = $this->getRealOrderBy();
        $limit = $this->getPageSize();
        $page = $this->getPageNumber();

        $items = $this->getList($_REQUEST, array(), $orderby, $limit, $page, $pagination);

	    $result = array(
	        'success' => true,
	        'items' => $this->model_sanitize($items),
	        'pagination' => $pagination
	    );

		$this->json_response($result);
	}

    function saveAction() {
        AclApi::checkPermission('customaccessright', 'edit');

        $this->checkform($errors);

        if (!empty($errors)) {
            $this->json_response(array('success' => false, 'message' => $errors[0]));
        } else {
            $model = $this->saveform();

            $this->json_response(array('success' => true, 'data' => $this->model_sanitize($model)));
        }
    }

    function deleteAction() {
        AclApi::checkPermission('customaccessright', 'delete');

	    list($id) = explode('/', $_REQUEST['args']);

		$model = new CustomAccessRightModel();
		$model->UUID = $id;

		$model->delete();

		$this->json_response($id);
	}

    function viewAction() {
	    AclApi::checkPermission('customaccessright', 'view');

		@list($id) = explode('/', $_REQUEST['args']);

        $model = new CustomAccessRightModel();

        if (!empty($id)) {
            $filters = array('UUID' => $id);
        } else {
            $filters = FilterHelper::getProperFilters($model, $_REQUEST);
        }

        $this->applyFilters($filters, $model);

        $model->find();

        if ($model->fetch()) {
            $this->json_response(array('success' => true, 'data' => $this->model_sanitize($model), 'title' => $model->VALID_FROM));
        } else {
            $this->json_response(array('success' => false));
        }
	}

    function updateAction() {
	    AclApi::checkPermission('customaccessright', 'edit');

 		@list($id, $col, $val) = explode('/', $_REQUEST['args']);

		if (empty($id)) {
		    echo json_encode(array('success' => false, 'message' => 'Parameter missing'));

		    return;
        }

        if (!empty($col)) {
            $_REQUEST[$col] = $val;
        }

		$model = new CustomAccessRightModel();
		$model->UUID = $id;

        $updatable = false;

		foreach($_REQUEST as $key => $value) {
		    if (property_exists($model, $key) && strtoupper($key) != 'ID') {
		        $updatable = true;

    		    $value = $this->field_sanitize($key, $value);

                if (is_array($value)) {
                    $model->$key = implode(',', $value);
                } else {
                    $model->$key = trim($value);
                }
            }
		}

		if (!$updatable) {
		    echo json_encode(array('success' => false, 'message' => 'Parameter missing'));

		    return;
        }

        $this->save(array($model));

        echo json_encode(array('success' => true, 'message' => ''));
	}
}


text:
namespace v8 {
namespace internal {

void IncrementalMarkingJob::Start(Heap* heap) {
  DCHECK(!heap->incremental_marking()->IsStopped());
  ScheduleTask(heap);
}

void IncrementalMarkingJob::NotifyTask() { task_pending_ = false; }

void IncrementalMarkingJob::ScheduleTask(Heap* heap) {
  if (!task_pending_) {
    v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(heap->isolate());
    task_pending_ = true;
    auto task = new Task(heap->isolate(), this);
    V8::GetCurrentPlatform()->CallOnForegroundThread(isolate, task);
  }
}

void IncrementalMarkingJob::Task::Step(Heap* heap) {
  const int kIncrementalMarkingDelayMs = 1;
  double deadline =
      heap->MonotonicallyIncreasingTimeInMs() + kIncrementalMarkingDelayMs;
  heap->incremental_marking()->AdvanceIncrementalMarking(
      deadline, i::IncrementalMarking::NO_GC_VIA_STACK_GUARD,
      i::IncrementalMarking::FORCE_COMPLETION, i::StepOrigin::kTask);
  heap->FinalizeIncrementalMarkingIfComplete(
      GarbageCollectionReason::kFinalizeMarkingViaTask);
}

void IncrementalMarkingJob::Task::RunInternal() {
  VMState<GC> state(isolate());
  RuntimeCallTimerScope runtime_timer(
      isolate(), &RuntimeCallStats::GC_IncrementalMarkingJob);

  Heap* heap = isolate()->heap();
  job_->NotifyTask();
  IncrementalMarking* incremental_marking = heap->incremental_marking();
  if (incremental_marking->IsStopped()) {
    if (heap->IncrementalMarkingLimitReached() !=
        Heap::IncrementalMarkingLimit::kNoLimit) {
      heap->StartIncrementalMarking(Heap::kNoGCFlags,
                                    GarbageCollectionReason::kIdleTask,
                                    kNoGCCallbackFlags);
    }
  }
  if (!incremental_marking->IsStopped()) {
    Step(heap);
    if (!incremental_marking->IsStopped()) {
      job_->ScheduleTask(heap);
    }
  }
}

}  // namespace internal
}  // namespace v8