text:
package io.pravega.client.connection.impl;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import io.pravega.client.ClientConfig;
import io.pravega.client.connection.impl.FlowHandler.KeepAliveTask;
import io.pravega.common.ObjectClosedException;
import io.pravega.shared.metrics.ClientMetricKeys;
import io.pravega.shared.metrics.MetricNotifier;
import io.pravega.shared.protocol.netty.Append;
import io.pravega.shared.protocol.netty.ConnectionFailedException;
import io.pravega.shared.protocol.netty.FailingReplyProcessor;
import io.pravega.shared.protocol.netty.PravegaNodeUri;
import io.pravega.shared.protocol.netty.Reply;
import io.pravega.shared.protocol.netty.ReplyProcessor;
import io.pravega.shared.protocol.netty.WireCommands;
import io.pravega.shared.protocol.netty.WireCommands.KeepAlive;
import io.pravega.test.common.InlineExecutor;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.Cleanup;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import static io.pravega.test.common.AssertExtensions.assertThrows;
import static java.lang.String.valueOf;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class FlowHandlerTest {

    @Rule
    public Timeout globalTimeout = Timeout.seconds(15);

    private Flow flow;
    private FlowHandler flowHandler;
    @Mock
    private ReplyProcessor processor;
    @Mock
    private Append appendCmd;
    @Mock
    private ByteBuf buffer;
    @Mock
    private ConnectionFactory connectionFactory;
    @Mock
    private ClientConnection connection;
    private ScheduledExecutorService loop;
    @Mock
    private ChannelFuture completedFuture;
    @Mock
    private ChannelPromise promise;

    @BeforeClass
    public static void beforeClass() {
        System.setProperty("pravega.client.netty.channel.timeout.millis", valueOf(SECONDS.toMillis(5)));
    }

    @Before
    public void setUp() throws Exception {
        flow = new Flow(10, 0);
        loop = new InlineExecutor();
        appendCmd = new Append("segment0", UUID.randomUUID(), 2, 1, buffer, 10L, flow.asLong());

        when(connectionFactory.establishConnection(any(PravegaNodeUri.class), any(ReplyProcessor.class)))
            .thenReturn(CompletableFuture.completedFuture(connection));
        when(connectionFactory.getInternalExecutor()).thenReturn(loop);

        ClientConfig clientConfig = ClientConfig.builder().build();
        PravegaNodeUri pravegaNodeUri = new PravegaNodeUri("testConnection", 0);
        flowHandler = FlowHandler.openConnection(pravegaNodeUri, new TestMetricNotifier(), connectionFactory).join();
    }

    @After
    public void tearDown() {
        loop.shutdown();
    }

    @Test
    public void sendNormal() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        clientConnection.send(appendCmd);
    }

    @Test(expected = ConnectionFailedException.class)
    public void sendError() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        Mockito.doThrow(new ConnectionFailedException()).when(connection).send(appendCmd);
        clientConnection.send(appendCmd);
    }

    @Test
    public void sendErrorUnRegistered() throws Exception {
        AtomicBoolean dropped = new AtomicBoolean(false);
        ReplyProcessor rp = new FailingReplyProcessor() {
            @Override
            public void processingFailure(Exception error) {
                //nothing
            }

            @Override
            public void connectionDropped() {
                dropped.set(true);
            }
        };
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, rp);
        //any send after channelUnregistered should throw a ConnectionFailedException.
        flowHandler.connectionDropped();
        assertTrue(dropped.get());
    }

    @Test(expected = IllegalArgumentException.class)
    public void createDuplicateSession() throws Exception {
        Flow flow = new Flow(10, 0);
        ClientConnection connection1 = flowHandler.createFlow(flow, processor);
        connection1.send(appendCmd);
        // Creating a flow with the same flow id.
        flowHandler.createFlow(flow, processor);
    }

    @Test
    public void testCloseSession() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        clientConnection.send(appendCmd);
        clientConnection.close();
        assertEquals(0, flowHandler.getFlowIdReplyProcessorMap().size());
    }

    @Test
    public void testCloseSessionHandler() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        WireCommands.GetSegmentAttribute cmd = new WireCommands.GetSegmentAttribute(flow.asLong(), "seg", UUID.randomUUID(), "");
        clientConnection.send(cmd);
        flowHandler.close();
        // verify that the Channel.close is invoked.
        Mockito.verify(connection, times(1)).close();
        assertThrows(ObjectClosedException.class, () -> flowHandler.createFlow(flow, processor));
        assertThrows(ObjectClosedException.class, () -> flowHandler.createConnectionWithFlowDisabled(processor));
    }

    @Test
    public void testCreateConnectionWithSessionDisabled() throws Exception {
        flow = new Flow(0, 10);
        ClientConnection connection = flowHandler.createConnectionWithFlowDisabled(processor);
        connection.send(new Append("segment0", UUID.randomUUID(), 2, 1, buffer, 10L, flow.asLong()));
        assertThrows(IllegalStateException.class, () -> flowHandler.createFlow(flow, processor));
    }

    @Test
    public void testChannelUnregistered() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        clientConnection.send(appendCmd);
        //simulate a connection dropped
        flowHandler.connectionDropped();
        assertTrue(flowHandler.isClosed());
    }

    @Test
    public void testHelloPassed() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        InOrder order = inOrder(connection);
        order.verify(connection).send(any(WireCommands.Hello.class));
        order.verifyNoMoreInteractions();
    }

    @Test
    public void testChannelReadDataAppended() throws Exception {
        @Cleanup
        ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
        WireCommands.DataAppended dataAppendedCmd = new WireCommands.DataAppended(flow.asLong(), UUID.randomUUID(), 2, 1, 0);
        InOrder order = inOrder(processor);
        flowHandler.process(dataAppendedCmd);
        order.verify(processor, times(1)).process(dataAppendedCmd);
    }

    @Test
    public void testHelloWithErrorReplyProcessor() throws Exception {
        ReplyProcessor errorProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(new Flow(11, 0), errorProcessor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(flow, processor);
        doAnswer((Answer<Void>) invocation -> {
            throw new RuntimeException("Reply processor error");
        }).when(errorProcessor).hello(any(WireCommands.Hello.class));

        final WireCommands.Hello msg = new WireCommands.Hello(5, 4);
        flowHandler.process(msg);
        verify(processor).hello(msg);
        verify(errorProcessor).hello(msg);
    }

    @Test
    public void testKeepAlive() {
        final WireCommands.KeepAlive msg = new WireCommands.KeepAlive();
        flowHandler.process(msg);
        // ensure none of the Replyprocessors are bothered with this msg.
        verifyNoInteractions(processor);
    }

    @Test
    public void testProcessWithErrorReplyProcessor() throws Exception {
        @Cleanup
        ClientConnection connection = flowHandler.createFlow(flow, processor);
        doAnswer((Answer<Void>) invocation -> {
            throw new RuntimeException("ReplyProcessorError");
        }).when(processor).process(any(Reply.class));

        WireCommands.DataAppended msg = new WireCommands.DataAppended(flow.asLong(), UUID.randomUUID(), 2, 1, 0);
        flowHandler.process(msg);
        verify(processor).process(msg);
        verify(processor).processingFailure(any(RuntimeException.class));
    }

    @Test
    public void testExceptionCaughtWithErrorReplyProcessor() throws Exception {
        ReplyProcessor errorProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(new Flow(11, 0), errorProcessor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(flow, processor);
        doAnswer((Answer<Void>) invocation -> {
            throw new RuntimeException("Reply processor error");
        }).when(errorProcessor).processingFailure(any(ConnectionFailedException.class));

        flowHandler.processingFailure(new IOException("netty error"));
        verify(processor).processingFailure(any(ConnectionFailedException.class));
        verify(errorProcessor).processingFailure(any(ConnectionFailedException.class));
    }

    @Test
    public void testChannelUnregisteredWithErrorReplyProcessor() throws Exception {
        ReplyProcessor errorProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(new Flow(11, 0), errorProcessor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(flow, processor);
        doAnswer((Answer<Void>) invocation -> {
            throw new RuntimeException("Reply processor error");
        }).when(errorProcessor).connectionDropped();

        flowHandler.connectionDropped();
        verify(processor).connectionDropped();
        verify(errorProcessor).connectionDropped();
    }

    @Test
    public void keepAliveFailureTest() throws Exception {
        ReplyProcessor replyProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(flow, processor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(new Flow(11, 0), replyProcessor);
        KeepAliveTask keepAlive = flowHandler.getKeepAliveTask();
        keepAlive.run();

        // simulate a KeepAlive connection failure.
        keepAlive.handleError(new RuntimeException("Induced error"));

        // ensure all the reply processors are informed immediately of the channel being closed due to KeepAlive Failure.
        verify(processor).connectionDropped();
        verify(replyProcessor).connectionDropped();
    }

    @Test
    public void keepAliveWriteFailureTest() throws Exception {
        ReplyProcessor replyProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(flow, processor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(new Flow(11, 0), replyProcessor);

        KeepAliveTask keepAlive = flowHandler.getKeepAliveTask();
        Mockito.doThrow(new RuntimeException("Induced error")).when(connection).send(any(KeepAlive.class));
        keepAlive.run();

        // ensure all the reply processors are informed immediately of the channel being closed due to KeepAlive Failure.
        verify(processor).connectionDropped();
        verify(replyProcessor).connectionDropped();
    }

    @Test
    public void keepAliveTimeoutTest() throws Exception {
        ReplyProcessor replyProcessor = mock(ReplyProcessor.class);
        @Cleanup
        ClientConnection connection1 = flowHandler.createFlow(flow, processor);
        @Cleanup
        ClientConnection connection2 = flowHandler.createFlow(new Flow(11, 0), replyProcessor);
        KeepAliveTask keepAlive = flowHandler.getKeepAliveTask();
        Mockito.doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                keepAlive.run();  //Triggers a timeout.
                return null;
            }
        }).when(connection).send(any(KeepAlive.class));
        keepAlive.run();

        // ensure all the reply processors are informed immediately of the channel being closed due to KeepAlive Failure.
        verify(processor).connectionDropped();
        verify(replyProcessor).connectionDropped();
    }

    /**
     * Added a mock MetricNotifier different from the default one to exercise reporting metrics from client side.
     */
    static class TestMetricNotifier implements MetricNotifier {
        @Override
        public void updateSuccessMetric(ClientMetricKeys metricKey, String[] metricTags, long value) {
            NO_OP_METRIC_NOTIFIER.updateSuccessMetric(metricKey, metricTags, value);
            assertNotNull(metricKey);
        }

        @Override
        public void updateFailureMetric(ClientMetricKeys metricKey, String[] metricTags, long value) {
            NO_OP_METRIC_NOTIFIER.updateFailureMetric(metricKey, metricTags, value);
            assertNotNull(metricKey);
        }

        @Override
        public void close() {
            NO_OP_METRIC_NOTIFIER.close();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using GroupDocs.Annotation.Options;

namespace GroupDocs.Annotation.Examples.CSharp.AdvancedUsage.Saving
{
    /// <summary>
    /// This example demonstrates saving result document as document given to create annotator class
    /// </summary>
    class SavingAsInputFromFilePathWithOptions
    {
        public static void Run()
        {
            string outputPath = Path.Combine(Constants.GetOutputDirectoryPath(), "result" + Path.GetExtension(Constants.INPUT));

            using (Annotator annotator = new Annotator(Constants.INPUT))
            {
                annotator.Save(new SaveOptions { Version = Guid.NewGuid().ToString() });
            }
            Console.WriteLine($"\nDocument saved successfully.\nCheck output in {outputPath}.");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = {
    aString: 'a string',
    anEmptyString: '',
    aNumber: 123,
    notANumber: NaN,
    aBoolean: true,
    aFalseBoolean: false,
    anObject: {foo: 'bar'},
    anEmptyObject: {},
    aStrObject: new String(),
    aNumObject: new Number(),
    anArray: [undefined, 'one', 2],
    anEmptyArray: [],
    anArgsObject: (function(){return arguments;})('one', 2),
    aFunction: function(){},
    aDate: new Date(),
    aRegExp: / /i,
    aNull: null,
    anUndefined: void 0
};


text:
from openprocurement.api.utils import update_logging_context
from openprocurement.api.validation import validate_json_data, validate_data
from openprocurement.relocation.api.models import Transfer

def validate_transfer_data(request):
    update_logging_context(request, {'transfer_id': '__new__'})
    data = validate_json_data(request)
    if data is None:
        return
    model = Transfer
    return validate_data(request, model, data=data)

def validate_ownership_data(request):
    if request.errors:
        # do not run validation if some errors are already detected
        return
    data = validate_json_data(request)

    for field in ['id', 'transfer']:
        if not data.get(field):
            request.errors.add('body', field, 'This field is required.'.format(field))
    if request.errors:
        request.errors.status = 422
        return
    request.validated['ownership_data'] = data

def validate_accreditation_level(request, tender, level_name):
    level = getattr(type(tender), level_name)
    if not request.check_accreditation(level):
        request.errors.add('procurementMethodType', 'accreditation', 'Broker Accreditation level does not permit ownership change')
        request.errors.status = 403
        return

    if tender.get('mode', None) is None and request.check_accreditation('t'):
        request.errors.add('procurementMethodType', 'mode', 'Broker Accreditation level does not permit ownership change')
        request.errors.status = 403
        return

def validate_tender_accreditation_level(request):
    validate_accreditation_level(request, request.validated['tender'], 'create_accreditation')

def validate_bid_accreditation_level(request):
    validate_accreditation_level(request, request.validated['tender'], 'edit_accreditation')

def validate_contract_accreditation_level(request):
    validate_accreditation_level(request, request.validated['contract'], 'create_accreditation')

validate_complaint_accreditation_level = validate_bid_accreditation_level


text:
package net.sf.webdav.methods;

import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.webdav.IMethodExecutor;
import net.sf.webdav.ITransaction;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.exceptions.LockFailedException;
import net.sf.webdav.fromcatalina.URLEncoder;
import net.sf.webdav.fromcatalina.XMLWriter;
import net.sf.webdav.locking.IResourceLocks;
import net.sf.webdav.locking.LockedObject;

public abstract class AbstractMethod implements IMethodExecutor {

  private static final ThreadLocal<DateFormat> thLastmodifiedDateFormat = new ThreadLocal<DateFormat>();
  private static final ThreadLocal<DateFormat> thCreationDateFormat = new ThreadLocal<DateFormat>();
  private static final ThreadLocal<DateFormat> thLocalDateFormat = new ThreadLocal<DateFormat>();

  /**
   * Array containing the safe characters set.
   */
  protected static URLEncoder URL_ENCODER;

  /**
   * Default depth is infite.
   */
  protected static final int INFINITY = 3;

  /**
   * Simple date format for the creation date ISO 8601 representation (partial).
   */
  protected static final String CREATION_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

  /**
   * Simple date format for the last modified date. (RFC 822 updated by RFC
   * 1123)
   */
  protected static final String LAST_MODIFIED_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z";

  protected static final String LOCAL_DATE_FORMAT = "dd/MM/yy' 'HH:mm:ss";

  static {
    /**
     * GMT timezone - all HTTP dates are on GMT
     */
    URL_ENCODER = new URLEncoder();
    URL_ENCODER.addSafeCharacter('-');
    URL_ENCODER.addSafeCharacter('_');
    URL_ENCODER.addSafeCharacter('.');
    URL_ENCODER.addSafeCharacter('*');
    URL_ENCODER.addSafeCharacter('/');
  }

  /**
   * size of the io-buffer
   */
  protected static int BUF_SIZE = 65536;

  /**
   * Default lock timeout value.
   */
  protected static final int DEFAULT_TIMEOUT = 3600;

  /**
   * Maximum lock timeout.
   */
  protected static final int MAX_TIMEOUT = 604800;

  /**
   * Boolean value to temporary lock resources (for method locks)
   */
  protected static final boolean TEMPORARY = true;

  /**
   * Timeout for temporary locks
   */
  protected static final int TEMP_TIMEOUT = 10;

  public static String lastModifiedDateFormat(final Date date) {
    DateFormat df = thLastmodifiedDateFormat.get();
    if (df == null) {
      df = new SimpleDateFormat(LAST_MODIFIED_DATE_FORMAT, Locale.US);
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      thLastmodifiedDateFormat.set(df);
    }
    return df.format(date);
  }

  public static String creationDateFormat(final Date date) {
    DateFormat df = thCreationDateFormat.get();
    if (df == null) {
      df = new SimpleDateFormat(CREATION_DATE_FORMAT);
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      thCreationDateFormat.set(df);
    }
    return df.format(date);
  }

  public static String getLocalDateFormat(final Date date, final Locale loc) {
    DateFormat df = thLocalDateFormat.get();
    if (df == null) {
      df = new SimpleDateFormat(LOCAL_DATE_FORMAT, loc);
    }
    return df.format(date);
  }

  /**
   * Return the relative path associated with this servlet.
   *
   * @param request
   *          The servlet request we are processing
   */
  protected String getRelativePath(HttpServletRequest request) {
    // Are we being processed by a RequestDispatcher.include()?
    if (request.getAttribute("javax.servlet.include.request_uri") != null) {
      String result = (String) request.getAttribute("javax.servlet.include.path_info");
      // if (result == null)
      // result = (String) request
      // .getAttribute("javax.servlet.include.servlet_path");
      if ((result == null) || (result.equals("")))
        result = "/";
      return (result);
    }

    // No, extract the desired path directly from the request
    String result = request.getPathInfo();
    // if (result == null) {
    // result = request.getServletPath();
    // }
    if ((result == null) || (result.equals(""))) {
      result = "/";
    }
    return (result);
  }

  /**
   * creates the parent path from the given path by removing the last '/' and
   * everything after that
   *
   * @param path
   *          the path
   * @return parent path
   */
  protected String getParentPath(String path) {
    int slash = path.lastIndexOf('/');
    if (slash != -1) {
      return path.substring(0, slash);
    }
    return null;
  }

  /**
   * removes a / at the end of the path string, if present
   *
   * @param path
   *          the path
   * @return the path without trailing /
   */
  protected String getCleanPath(String path) {
    if (path.endsWith("/") && path.length() > 1)
      path = path.substring(0, path.length() - 1);
    return path;
  }

  /**
   * Return JAXP document builder instance.
   */
  protected DocumentBuilder getDocumentBuilder() throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
      documentBuilderFactory = DocumentBuilderFactory.newInstance();
      documentBuilderFactory.setNamespaceAware(true);
      documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new ServletException("jaxp failed");
    }
    return documentBuilder;
  }

  /**
   * reads the depth header from the request and returns it as a int
   *
   * @param req
   * @return the depth from the depth header
   */
  protected int getDepth(HttpServletRequest req) {
    int depth = INFINITY;
    String depthStr = req.getHeader("Depth");
    if (depthStr != null) {
      if (depthStr.equals("0")) {
        depth = 0;
      } else if (depthStr.equals("1")) {
        depth = 1;
      }
    }
    return depth;
  }

  /**
   * URL rewriter.
   *
   * @param path
   *          Path which has to be rewiten
   * @return the rewritten path
   */
  protected String rewriteUrl(String path) {
    return URL_ENCODER.encode(path);
  }

  /**
   * Get the ETag associated with a file.
   *
   * @param StoredObject
   *          StoredObject to get resourceLength, lastModified and a hashCode of
   *          StoredObject
   * @return the ETag
   */
  protected String getETag(StoredObject so) {

    String resourceLength = "";
    String lastModified = "";

    if (so != null && so.isResource()) {
      resourceLength = Long.valueOf(so.getResourceLength()).toString();
      lastModified = Long.valueOf(so.getLastModified().getTime()).toString();
    }

    return "W/\"" + resourceLength + "-" + lastModified + "\"";

  }

  protected String[] getLockIdFromIfHeader(HttpServletRequest req) {
    String[] ids = new String[2];
    String id = req.getHeader("If");
    if (id != null && !id.equals("")) {
      if (id.indexOf(">)") == id.lastIndexOf(">)")) {
        id = id.substring(id.indexOf("(<"), id.indexOf(">)"));
        if (id.indexOf("locktoken:") != -1) {
          id = id.substring(id.indexOf(':') + 1);
        }
        ids[0] = id;
      } else {
        String firstId = id.substring(id.indexOf("(<"), id.indexOf(">)"));
        if (firstId.indexOf("locktoken:") != -1) {
          firstId = firstId.substring(firstId.indexOf(':') + 1);
        }
        ids[0] = firstId;
        String secondId = id.substring(id.lastIndexOf("(<"), id.lastIndexOf(">)"));
        if (secondId.indexOf("locktoken:") != -1) {
          secondId = secondId.substring(secondId.indexOf(':') + 1);
        }
        ids[1] = secondId;
      }
    } else {
      ids = null;
    }
    return ids;
  }

  protected String getLockIdFromLockTokenHeader(HttpServletRequest req) {
    String id = req.getHeader("Lock-Token");
    if (id != null) {
      id = id.substring(id.indexOf(":") + 1, id.indexOf(">"));
    }
    return id;
  }

  /**
   * Checks if locks on resources at the given path exists and if so checks the
   * If-Header to make sure the If-Header corresponds to the locked resource.
   * Returning true if no lock exists or the If-Header is corresponding to the
   * locked resource
   *
   * @param req
   *          Servlet request
   * @param resp
   *          Servlet response
   * @param resourceLocks
   * @param path
   *          path to the resource
   * @param errorList
   *          List of error to be displayed
   * @return true if no lock on a resource with the given path exists or if the
   *         If-Header corresponds to the locked resource
   * @throws IOException
   * @throws LockFailedException
   */
  protected boolean checkLocks(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp, IResourceLocks resourceLocks, String path) throws IOException, LockFailedException {

    LockedObject loByPath = resourceLocks.getLockedObjectByPath(transaction, path);
    if (loByPath != null) {

      if (loByPath.isShared())
        return true;

      // the resource is locked
      String[] lockTokens = getLockIdFromIfHeader(req);
      String lockToken = null;
      if (lockTokens != null)
        lockToken = lockTokens[0];
      else {
        return false;
      }
      if (lockToken != null) {
        LockedObject loByIf = resourceLocks.getLockedObjectByID(transaction, lockToken);
        if (loByIf == null) {
          // no locked resource to the given lockToken
          return false;
        }
        if (!loByIf.equals(loByPath)) {
          loByIf = null;
          return false;
        }
        loByIf = null;
      }

    }
    loByPath = null;
    return true;
  }

  /**
   * Send a multistatus element containing a complete error report to the
   * client. If the errorList contains only one error, send the error directly
   * without wrapping it in a multistatus message.
   *
   * @param req
   *          Servlet request
   * @param resp
   *          Servlet response
   * @param errorList
   *          List of error to be displayed
   */
  protected void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String, Integer> errorList) throws IOException {

    if (errorList.size() == 1) {
      int code = errorList.elements().nextElement();
      if (WebdavStatus.getStatusText(code) != "") {
        resp.sendError(code, WebdavStatus.getStatusText(code));
      } else {
        resp.sendError(code);
      }
    } else {
      resp.setStatus(WebdavStatus.SC_MULTI_STATUS);

      String absoluteUri = req.getRequestURI();
      // String relativePath = getRelativePath(req);

      HashMap<String, String> namespaces = new HashMap<String, String>();
      namespaces.put("DAV:", "D");

      XMLWriter generatedXML = new XMLWriter(namespaces);
      generatedXML.writeXMLHeader();

      generatedXML.writeElement("DAV::multistatus", XMLWriter.OPENING);

      Enumeration<String> pathList = errorList.keys();
      while (pathList.hasMoreElements()) {

        String errorPath = (String) pathList.nextElement();
        int errorCode = ((Integer) errorList.get(errorPath)).intValue();

        generatedXML.writeElement("DAV::response", XMLWriter.OPENING);

        generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
        String toAppend = null;
        if (absoluteUri.endsWith(errorPath)) {
          toAppend = absoluteUri;

        } else if (absoluteUri.contains(errorPath)) {

          int endIndex = absoluteUri.indexOf(errorPath) + errorPath.length();
          toAppend = absoluteUri.substring(0, endIndex);
        }
        if (!toAppend.startsWith("/") && !toAppend.startsWith("http:"))
          toAppend = "/" + toAppend;
        generatedXML.writeText(errorPath);
        generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
        generatedXML.writeElement("DAV::status", XMLWriter.OPENING);
        generatedXML.writeText("HTTP/1.1 " + errorCode + " " + WebdavStatus.getStatusText(errorCode));
        generatedXML.writeElement("DAV::status", XMLWriter.CLOSING);

        generatedXML.writeElement("DAV::response", XMLWriter.CLOSING);

      }

      generatedXML.writeElement("DAV::multistatus", XMLWriter.CLOSING);

      Writer writer = resp.getWriter();
      writer.write(generatedXML.toString());
      writer.close();
    }
  }

}


text:
package ru.job4j.chat;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {
    private final File file;

    public WriteToFile(File file) {
        this.file = file;
    }

    public void appendString(String message) throws IOException {
        try (FileWriter writer = new FileWriter(file, true)) {
            writer.write(message);
        }
    }

    public String getPath() {
        return this.file.getPath();
    }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m141123_200938_create_permis_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%permission}}', [
            'id' => Schema::TYPE_PK,
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'descript' => Schema::TYPE_TEXT . ' NOT NULL',
            'operation' => Schema::TYPE_TEXT . ' NOT NULL',
            'status' => Schema::TYPE_STRING,
        ], $tableOptions);

    }

    public function down()
    {
        $this->dropTable('{{%permission}}');
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactIconBase = require('react-icon-base');

var _reactIconBase2 = _interopRequireDefault(_reactIconBase);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var MdBrandingWatermark = function MdBrandingWatermark(props) {
    return _react2.default.createElement(
        _reactIconBase2.default,
        _extends({ viewBox: '0 0 40 40' }, props),
        _react2.default.createElement(
            'g',
            null,
            _react2.default.createElement('path', { d: 'm35 31.6v-10h-15v10h15z m0-26.6c1.8 0 3.4 1.6 3.4 3.4v23.2c0 1.8-1.6 3.4-3.4 3.4h-30c-1.8 0-3.4-1.6-3.4-3.4v-23.2c0-1.8 1.6-3.4 3.4-3.4h30z' })
        )
    );
};

exports.default = MdBrandingWatermark;
module.exports = exports['default'];


text:
/*
 * Key point: recursive solution, in-place, preorder
 */

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {

        recursiveWorker(root);

    }

    public TreeNode recursiveWorker(TreeNode root){
        if(root == null || (root.left == null && root.right == null))
            return root;

        //last node of flatted left-subtree
        TreeNode leftEnd = recursiveWorker(root.left);

        //last node of flatted right-subtree
        TreeNode rightEnd = recursiveWorker(root.right);

        //connect left subtree and right subtree
        if(leftEnd != null){
            leftEnd.right = root.right;
            root.right = root.left;
            root.left = null;
        }

        //return the last node after we connect left and right subtree
        if(rightEnd != null)
            return rightEnd;
        else
            return leftEnd;
    }
}


text:
var CacheGroupsController = function() {
};

CacheGroupsController.$inject = [];
module.exports = CacheGroupsController;


text:
Boost.Process
=============

Idea
----

* Thin OS wrapper for process "management"
* Supports Windows + POSIX
* Long history ... (since 2006)

Features
--------

* Multiple interface styles for process creation
* Synchronous and asynchronous I/O with stdin/stdout/stderr
    * Integrates nicely with Boost.ASIO
* `char` + `wchar_t` support (even mixed usage)

Concepts
--------

* Pipes: consist of 2 directed channels (stdin, stdout, stderr)
* Processes: PID, exit code
    * only "hard" termination supported, since this is the only portable way
* Environment: map of variables

Simple examples
---------------

```cpp
int result = std::system("g++ main.cpp"); // "standard" C++

// Boost.Process
namespace bp = boost::process;
int result = bp::system("g++ main.cpp");
// better:
int result = bp::system("/usr/bin/g++", "main.cpp");
// using paths:
boost::filesystem::path p = "/usr/bin/g++";
int result = bp::system(p, "main.cpp");
// alternative: search $PATH / %PATH%
// (handles .exe/.bat/... properly on Windows)
boost::filesystem::path p = bp::search_path("g++");
int result = bp::system(p, "main.cpp");
```

About 'system'
--------------

![](danger - shell injection.jpg)

More examples
-------------

```cpp
// spawn & detach
bp::spawn(bp::search_path("chrome"), "www.boost.org");

// interact with a child process
bp::child c(bp::search_path("g++"), "main.cpp");

while (c.running())
    do_some_stuff();

c.wait(); // wait for the process to exit
// alternatives: wait_for(delay), wait_until(time)
int result = c.exit_code();
```

Interface styles
----------------

```cpp
using namespace boost::process;

// cmd style
system("grep -c false /etc/passwd");
system(cmd="grep -c false /etc/passwd");

// exe-/args-
system("grep", "-c", "false", "/etc/passwd");
system(exe="grep", args={"-c", "false", "/etc/passwd"});

// Both styles can also be mixed in some cases.
system("gcc", "-c", args+={"main.cpp"});
```

(Synchronous) I/O example
-------------------------

```cpp
bp::opstream in;
bp::ipstream out;

bp::child c("c++filt", bp::std_out > out, bp::std_in < in);

in << "_ZN5boost7process8tutorialE" << endl;
std::string value;
out >> value;

c.terminate();
```

Connecting processes with pipes
-------------------------------

```cpp
bp::pipe p; bp::ipstream is;
std::vector<std::string> outline;

// same pipe for output and input to connect both processes
bp::child nm(bp::search_path("nm"), file,  bp::std_out > p);
bp::child filt("c++filt", bp::std_in < p, bp::std_out > is);

std::string line;
// when nm finishes the pipe closes and c++filt exits
while (filt.running() && std::getline(is, line))
    outline.push_back(line);

nm.wait(); filt.wait();
```

Good to know
------------

* Error handling: pass an `std::error_code` or catch `std::system_error`
* `bp::child`: kills the process in the destructor if not detached
* Waiting for a process to end and for its output simultaneously is a pain...

Asynchronous I/O
----------------

* integrates with Boost.ASIO
* can be used with futures

## ASIO example

```cpp
boost::asio::io_service ios;
std::vector<char> buf(4096);

bp::async_pipe ap(ios);

bp::child c(bp::search_path("g++"), "main.cpp",
            bp::std_out > ap);

boost::asio::async_read(ap, boost::asio::buffer(buf),
        [](const boost::system::error_code &ec,
           std::size_t size){});

ios.run();
int result = c.exit_code();
```

## Simplified ASIO example

```cpp
boost::asio::io_service ios;
std::vector<char> buf(4096);

bp::child c(bp::search_path("g++"), "main.cpp",
            bp::std_out > boost::asio::buffer(buf), ios);

ios.run();
int result = c.exit_code();
```

## Using futures

```cpp
boost::asio::boost::asio::io_service ios;
std::future<std::string> data;

bp::child c("g++", "main.cpp",
            bp::std_in.close(),
            bp::std_out > bp::null,
            bp::std_err > data,
            ios);

ios.run(); // will block until the compiler is finished

auto err = data.get();
```

Process groups
--------------

Children can be grouped for easier management. Groups can be polled/terminated as a single entity.

Example:

```cpp
bp::group g;
bp::spawn("foo", g);
bp::spawn("bar", g);

do_something();

g.wait();
```

Environment
-----------

```cpp
auto env = boost::this_process::environment();
// add a variable to the current environment
env["VALUE_1"] = "foo";

// create a copy for the new process
bp::environment newEnv = env;
// append two values to a variable in the new env
newEnv["VALUE_2"] += {"bar1", "bar2"};

// launch a process with `env_`
bp::system("stuff", newEnv);
```

More convenient:

```cpp
bp::system("stuff", bp::env["VALUE_1"]="foo",
           bp::env["VALUE_2"]+={"bar1", "bar2"});
```

Extensions
----------

Different handlers are called during execution:

* `on_setup`: Invoked before the process is launched.
* `on_error`: Invoked on error (on the parent).
* `on_success`: Invoked after successful launch of the child.

Extensions
----------

Additional handlers for POSIX:

* `on_fork_error`: Invoked on the parent if `fork()` failed.
* `on_exec_error`: Invoked on the child(!) if `execve()` failed.
* `on_exec_setup`: Invoked on the child(!) after successful `fork()`.
    * great for changing permissions/umask/...

Extensions - Windows/all
------------------------

![](windows_exec_ok.svg)
![](windows_exec_err.svg)

Extensions - POSIX only
-----------------------

![](posix_exec_ok.svg)
![](posix_exec_err.svg)
![](posix_fork_err.svg)


text:
namespace faint{ class Command; }

namespace faint{

class MergeCondition{
  // Specifies conditions for merging all commands in two
  // CommandBunches, and for appending a single command to an existing
  // CommandBunch.
public:
  virtual ~MergeCondition() = default;

  // True if the command should be appended to the list of commands in
  // the command bunch with this merge condition.
  virtual bool ShouldAppend(const Command&) const = 0;
  virtual void NotifyAppended() = 0;

  // True if the command bunch should assume the name of the
  // merged command bunch or appended command.
  virtual bool AssumeName() const = 0;

  // True if all commands should be merged.
  virtual bool Satisfied(const MergeCondition&) = 0;
  bool Unsatisfied(const MergeCondition& other);
};

using MergeConditionPtr = std::unique_ptr<MergeCondition>;

} // namespace

#endif


text:
"""This script was used to check the outputs of the Mathematica script pk.math.  More specifically,
it takes the output power spectra, tells GalSim to generate a random shear field according to the
power spectra, computes the shear correlation function xi_+, and compares it to the original one
given above to ensure that they are consistent.
"""
import numpy as np
import matplotlib.pyplot as plt
import galsim
import subprocess
import os
import sys

def run_corr2_ascii(x,y,e1,e2,min_sep,max_sep,nbins):
    """This is a simple utility to run corr2 (the two-point correlation function code) on an ascii
    file."""
    f = open('temp.cat','w')
    for (i,j), value in np.ndenumerate(x):
        xij = value
        yij = y[i,j]
        g1ij = e1[i,j]
        g2ij = e2[i,j]
        f.write('%e  %e  %e  %e\n'%(xij,yij,g1ij,g2ij))
    f.close()
    subprocess.Popen(['corr2','corr2.params',
                      'min_sep=%f'%min_sep,'max_sep=%f'%max_sep,'nbins=%f'%nbins]).wait()
    results = np.loadtxt('temp.e2')
    os.remove('temp.cat')
    os.remove('temp.e2')
    return results

fig = plt.figure()
ax = fig.add_subplot(111)
# Define values for theta_0, the scale length in the atmospheric PSF correlation function (which had
# been pre-determined for mathematica calculations and used to make filenames, meaning this part of
# the code can't be changed without changing those other pieces of code and rerunning Mathematica).
min_theta0 = 360.  # 0.1 degree
max_theta0 = 7200. # 2 degrees
ntheta0 = 11
theta0 = np.logspace(np.log10(min_theta0),np.log10(max_theta0),ntheta0)

# Loop over the values of theta_0, read in the P(k) from the precomputed files, and plot.
for t0 in theta0:
    strval = str(int(round(t0)))
    infile = 'pk_math/Pk'+strval+'.dat'
    pk_dat = np.loadtxt(infile).transpose()
    k = pk_dat[0]
    pk = 1.e-4*2.*np.pi*pk_dat[1] # Put in the proper normalization here.
    ax.plot(k, pk, label='theta0='+strval)
# And just for fun, let's plot a cosmological shear power spectrum as well.  For that, we have to
# convert the iCosmo outputs to arcsec instead of radians.
pk_file = '../ps/tables/cosmo-fid.zmed1.00.out'
pk_data = np.loadtxt(pk_file).transpose()
rad_to_arcsec = 3600.*180./np.pi
k_arcsec = pk_data[0]/rad_to_arcsec
pk_arcsec = pk_data[1]*(rad_to_arcsec**2)
ax.plot(k_arcsec, pk_arcsec, label='<gg>, z=1')
# Note some of the interesting scales.
ell_20 = 20./rad_to_arcsec
ell_2000 = 2000./rad_to_arcsec
ax.plot((ell_20, ell_20), (1.e-6,1.e5))
ax.plot((ell_2000, ell_2000), (1.e-6,1.e5))
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('k [1/arcsec]')
ax.set_ylabel('P(k) [arcsec^2]')
plt.legend()
print "Saving plot to file"
plt.savefig('diagnostics/test_pk_math.jpg')
# The outputs are quite interesting: for the lowest k (or ell) in the range probed by our grid, the
# atmospheric PSF anisotropy power spectrum is above the cosmological one.  However, for the highest
# k the situation is reversed, and the cosmological shear power spectrum is higher.  This is roughly
# what we expect, but it's good to confirm.

# Next we want to explicitly check what happens when we use GalSim to draw shears according to those
# power spectra.  So we start by setting up our grid (using GREAT3 standard values for the sub-grids
# used for PSF determination for ground-based simulations, i.e., 2x2 degrees), since that determines
# the values of k that we actually care about.  We want to oversample the grid in order to not screw
# up the shear power on small scales.  And, we want to subsample so as to be able to offset our
# grids and include small-scale power (probably by 10, but for now, 5).
oversample = 20
subsample = 5
ngrid = 20*oversample*subsample
theta_deg = 2.*oversample
theta_arcsec = theta_deg*3600
dtheta_arcsec = theta_arcsec / ngrid
# Set up the k values corresponding to this grid.
k_min = 2.*np.pi / theta_arcsec
k_max = np.sqrt(2.)*np.pi/dtheta_arcsec
# The shear generation is expensive, so let's not do it every time, particularly if I just want to
# mess with the P(k) calculation.
do_shear = True
# Also we'll make an option to just use some of the grid, to save time.
use_subgrid = True
if do_shear:
    for t0 in theta0:
        print "Getting shears using GalSim for theta0=",t0
        strval = str(int(round(t0)))
        infile = 'pk_math/Pk'+strval+'.dat'
        pk_dat = np.loadtxt(infile).transpose()
        k = pk_dat[0]
        pk = 1.e-4*2.*np.pi*pk_dat[1] # put in the normalization here

        tab_pk = galsim.LookupTable(k, 0.5*pk, x_log=True, f_log=True)
        # Take the outputs and run corr2 to check that the outputs correspond to inputs.  Use 0.5*P
        # but give that to both P_E and P_B.
        ps = galsim.PowerSpectrum(tab_pk, tab_pk, units=galsim.arcsec)

        # Note, typically the buildGrid() method returns shear, not distortion e.  For nearly round
        # things, e~2*shear.  But for the atmospheric PSF stuff, I gave the code amplitudes
        # corresponding to some ellipticity variance, so the results should correspond to e1/e2 in
        # amplitude as well.  The alternative approach would have been to use shear variances
        # (factor of 4 lower) and then to take the e that come out and multiply by 2.  This seemed
        # silly so I didn't do it.  However, it does mean that the kappa fluctuations are too high
        # by a factor of 4, so I must reduce them.
        e1, e2, kappa = ps.buildGrid(grid_spacing=dtheta_arcsec,
                                     ngrid=ngrid,
                                     get_convergence=True)
        kappa /= 4.
        grid_range = (dtheta_arcsec) * np.arange(ngrid)
        x, y = np.meshgrid(grid_range, grid_range)
        if not use_subgrid:
            results = run_corr2_ascii(x,y,e1,e2,dtheta_arcsec,np.sqrt(2)*dtheta_arcsec*ngrid,ngrid)
            theta_corr2 = results[:,1]
            xip_corr2 = results[:,2]
            xim_corr2 = results[:,3]
        else:
            n_iter = 0
            for x_ind in range(oversample):
                x_start = x_ind*ngrid/(oversample)
                x_end = (x_ind+1)*ngrid/(oversample)
                for y_ind in range(oversample):
                    print "  Subsample ",n_iter
                    y_start = y_ind*ngrid/(oversample)
                    y_end = (y_ind+1)*ngrid/(oversample)
                    e1_sub = e1[x_start:x_end, y_start:y_end]
                    e2_sub = e2[x_start:x_end, y_start:y_end]
                    x_sub = x[x_start:x_end, y_start:y_end]
                    y_sub = y[x_start:x_end, y_start:y_end]
                    results = run_corr2_ascii(x_sub,y_sub,e1_sub,e2_sub,dtheta_arcsec,np.sqrt(2)*dtheta_arcsec*ngrid/oversample,ngrid/(oversample))
                    if n_iter == 0:
                        theta_corr2 = results[:,1]
                        xip_corr2 = results[:,2]
                        xim_corr2 = results[:,3]
                    else:
                        xip_corr2 += results[:,2]
                        xim_corr2 += results[:,3]
                    n_iter += 1
            xip_corr2 /= oversample**2
            xim_corr2 /= oversample**2

        print "Plotting ellipticity correlation function."
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(theta_corr2, xip_corr2, label='observed xi+')
        ax.plot(theta_corr2, xim_corr2, label='observed xi-')
        theory = 1.e-4/(1+theta_corr2/t0)
        ax.plot(theta_corr2, 1.e-4/(1+theta_corr2/t0), label='input xi+')
        ratio = xip_corr2/theory
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlabel('theta [arcsec]')
        ax.set_ylabel('xi')
        ax.set_title('theta0='+strval)
        plt.legend(loc=3)
        print "Saving plot to file"
        plt.savefig('diagnostics/test_pk_math_xi_'+strval+'.jpg')

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(theta_corr2, ratio)
        plt.ylim((0.5,1.5))
        ax.set_xscale('log')
        ax.set_xlabel('theta [arcsec]')
        ax.set_ylabel('observed/theory xi_+')
        plt.savefig('diagnostics/test_pk_math_xi_'+strval+'_ratio.jpg')


text:
OSC application orchestration

[![Compose](https://www.docker.com/sites/default/files/Compose.png)](https://www.docker.com/products/docker-compose)

## Log management

[![2017-01-27_083558.png](https://s24.postimg.org/ie9aaon5h/2017_01_27_083558.png)](https://postimg.org/image/kvl1hy71t/)

## Load balancer

[![HAProxy](http://www.haproxy.org/img/logo-med.png)](http://www.haproxy.org/)

HAProxy provides us with round-robin load balancing, receives the web request and routes it to the web service.

We can scale the stack to 'n' web instances/containers conected to log manager. Then web request are received by the HAPoxy and routed ound-robin to all 'n' of the web instances. All these instances ar also linked to the log management system.

```
$ docker-compose scale web=3
```


text:
using System;
using System.Numerics;

class BinaryToDecimal
{
    static void Main()

    {
        BigInteger binary = BigInteger.Parse(Console.ReadLine());

        BigInteger rem = 0;
        BigInteger powStatic = 0;
        BigInteger powDynamic = -1;
        BigInteger toDecimal = 0;

        BigInteger i = -1;

        while (binary > 0)
        {
            rem = binary % 10;
            binary = binary / 10;
            powDynamic++;

            for (int DONTNEED = -1; i < powDynamic; i++) // 2^n
            {
                if (2 * powDynamic == 0)
                {
                    powStatic++;
                    continue;
                }

                powStatic *= 2;
            }

            toDecimal += rem * powStatic;

        }

        Console.WriteLine(toDecimal);

    }
}


text:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';
// RxJS
import 'rxjs';
// Other vendors for example jQuery, Lodash or Bootstrap
// You can import js, ts, css, sass, ...

import 'jquery/dist/jquery.min';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-material-design/dist/css/bootstrap-material-design.min.css';
import 'bootstrap-material-design/dist/css/ripples.min.css';


text:
<?php

namespace Mouf\Controllers\Composer;

use Mouf\Composer\ChunckedUtils;

use Mouf\Html\Utils\WebLibraryManager\WebLibrary;

use Mouf\Composer\OnPackageFoundInterface;

use Mouf\Composer\ComposerService;

use Mouf\MoufManager;

use Mouf\Html\HtmlElement\HtmlBlock;

use Mouf\MoufPackage;
use Mouf\Mvc\Splash\Controllers\Controller;
use Mouf\Html\Template\TemplateInterface;

use Composer\Package\PackageInterface;

/**
 * The controller managing the list of composer packages included in the project.
 *
 * @Component
 */
class InstalledPackagesController extends Controller implements OnPackageFoundInterface {

	public $selfedit;

	/**
	 * The active MoufManager to be edited/viewed
	 *
	 * @var MoufManager
	 */
	public $moufManager;

	/**
	 * The template used by the main page for mouf.
	 *
	 * @Property
	 * @Compulsory
	 * @var TemplateInterface
	 */
	public $template;

	/**
	 * The content block the template will be writting into.
	 *
	 * @Property
	 * @Compulsory
	 * @var HtmlBlock
	 */
	public $contentBlock;

	/**
	 *
	 * @var array<PackageInterface>
	 */
	protected $packageList;

	/**
	 * View the list of all installed composer packages.
	 *
	 * @URL composer/view
	 */
	public function index($selfedit = "false") {
		$this->selfedit = $selfedit;

		if ($selfedit == "true") {
			$this->moufManager = MoufManager::getMoufManager();
		} else {
			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
		}

		$composerService = new ComposerService($this->selfedit == "true", false);

		$this->packageList = $composerService->getLocalPackages();

		$this->contentBlock->addFile(ROOT_PATH."src-dev/views/composer/index.php", $this);
		$this->template->toHtml();
	}

	/**
	 * Searches the packages and returns a list of matching packages.
	 *
	 * @URL composer/search
	 * @param string $text
	 */
	public function search($text) {
		$composerService = new ComposerService(false, true);

		ChunckedUtils::init();

		$msg = "";
		ChunckedUtils::writeChunk($msg);

		$msg = "";
		ChunckedUtils::writeChunk($msg);

		$composerService->searchPackages($text, $this);

		$msg = "";
		ChunckedUtils::writeChunk($msg);

		ChunckedUtils::close();
	}

	public function onPackageFound(PackageInterface $package, $score) {
		//$html = $this->getHtmlForPackage($package);
		$packageArr = array();
		$packageArr['prettyName'] = $package->getPrettyName();
		$packageArr['prettyVersion'] = $package->getPrettyVersion();
		$packageArr['name'] = $package->getName();
		$packageArr['version'] = $package->getVersion();
		$packageArr['homePage'] = $package->getHomepage();
		$packageArr['description'] = $package->getDescription();
		$extra = $package->getExtra();
		if (isset($extra['mouf']['logo'])) {
			$packageArr['logo'] = ROOT_URL."vendor".$package->getName()."/".$extra['mouf']['logo'];
		}

		$msg = "";
		ChunckedUtils::writeChunk($msg);
	}

	public function getHtmlForPackage(PackageInterface $package) {
		$version = $package->getPrettyVersion();
		$html = '

';
		$extra = $package->getExtra();
		if (isset($extra['mouf']['logo'])) {
			$html .= 'getName()."/".$extra['mouf']['logo'].'">';
		}
		$html .= '

				'.$package->getPrettyName().' (version '.$version.')

Homepage: getHomepage().'">'.$package->getHomepage().'

'.$package->getDescription().'
';
		if ($package->getName() != "__root__") {
			$html .= '
				<form action="uninstall" method="post">
					<input type="hidden" name="name" value="'.$package->getName().'" />
					<button>Uninstall</button>
				<form>';
		}
		$html .= '

';
		return $html;
	}

	protected $name;
	protected $version;

	/**
	 * Triggers the installation of the composer package passed in parameter.
	 * This will actually display a screen with an iframe that will do the real install process.
	 *
	 * @Post
	 * @URL composer/install
	 * @param string $name
	 * @param string $version
	 * @param string $selfedit
	 */
	public function install($name, $version, $selfedit = "false") {
		$this->selfedit = $selfedit;
		$this->name = $name;
		$this->version = $version;

		if ($selfedit == "true") {
			$this->moufManager = MoufManager::getMoufManager();
		} else {
			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
		}

		$this->contentBlock->addFile(ROOT_PATH."src-dev/views/composer/install.php", $this);
		$this->template->toHtml();
	}

	/**
	 * Actually performs the package installation.
	 *
	 * @URL composer/doInstall
	 * @param string $name
	 * @param string $version
	 * @param string $selfedit
	 */
	public function doInstall($name, $version, $selfedit = "false") {
		$this->selfedit = $selfedit;

		if ($selfedit == "true") {
			$this->moufManager = MoufManager::getMoufManager();
		} else {
			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
		}

		$composerService = new ComposerService($this->selfedit == "true", true);

		ChunckedUtils::init();

		$msg = "";
		ChunckedUtils::writeChunk($msg);

		$composerService->install($name, $version);

		ChunckedUtils::close();
	}

	/**
	 * Triggers the removal of the composer package passed in parameter.
	 * This will actually display a screen with an iframe that will do the real uninstall process.
	 *
	 * @Post
	 * @URL composer/uninstall
	 * @param string $name
	 * @param string $selfedit
	 */
	public function uninstall($name, $selfedit = "false") {
		$this->selfedit = $selfedit;
		$this->name = $name;

		if ($selfedit == "true") {
			$this->moufManager = MoufManager::getMoufManager();
		} else {
			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
		}

		$this->contentBlock->addFile(ROOT_PATH."src-dev/views/composer/uninstall.php", $this);
		$this->template->toHtml();
	}

	/**
	 * Actually performs the package removal.
	 *
	 * @URL composer/doUninstall
	 * @param string $name
	 * @param string $selfedit
	 */
	public function doUninstall($name, $selfedit = "false") {
		$this->selfedit = $selfedit;

		if ($selfedit == "true") {
			$this->moufManager = MoufManager::getMoufManager();
		} else {
			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
		}

		$composerService = new ComposerService($this->selfedit == "true", true);

		ChunckedUtils::init();

		$msg = "";
		ChunckedUtils::writeChunk($msg);

		$composerService->uninstall($name);

		ChunckedUtils::close();
	}
}


text:
package org.keycloak.testsuite.pages;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

/**
 * @author Stian Thorgersen
 */
public class TermsAndConditionsPage extends AbstractPage {

    @FindBy(id = "kc-accept")
    private WebElement submitButton;

    @FindBy(id = "kc-decline")
    private WebElement cancelButton;

    public boolean isCurrent() {
        return PageUtils.getPageTitle(driver).equals("Terms and Conditions");
    }

    public void acceptTerms() {
        submitButton.click();
    }
    public void declineTerms() {
        cancelButton.click();
    }

    @Override
    public void open() {
        throw new UnsupportedOperationException();
    }

}


text:
import { Animation } from '../animations/animation';
import { Menu, MenuType as IMenuType } from './menu.interface';
import { MenuController } from './menu-controller';
import { Platform } from '../platform/platform';

/**
 * @hidden
 * Menu Type
 * Base class which is extended by the various types. Each
 * type will provide their own animations for open and close
 * and registers itself with Menu.
 */
export class MenuType implements IMenuType {

  ani: Animation;
  isOpening: boolean;

  constructor(plt: Platform) {
    this.ani = new Animation(plt);
    this.ani
      .easing('cubic-bezier(0.0, 0.0, 0.2, 1)')
      .easingReverse('cubic-bezier(0.4, 0.0, 0.6, 1)')
      .duration(280);
  }

  setOpen(shouldOpen: boolean, animated: boolean, done: Function) {
    const ani = this.ani
      .onFinish(done, true, true)
      .reverse(!shouldOpen);

    if (animated) {
      ani.play();
    } else {
      ani.syncPlay();
    }
  }

  setProgressStart(isOpen: boolean) {
    this.isOpening = !isOpen;

    // the cloned animation should not use an easing curve during seek
    this.ani
      .reverse(isOpen)
      .progressStart();
  }

  setProgessStep(stepValue: number) {
    // adjust progress value depending if it opening or closing
    this.ani.progressStep(stepValue);
  }

  setProgressEnd(shouldComplete: boolean, currentStepValue: number, velocity: number, done: Function) {
    let isOpen = (this.isOpening && shouldComplete);
    if (!this.isOpening && !shouldComplete) {
      isOpen = true;
    }
    const ani = this.ani;
    ani.onFinish(() => {
      this.isOpening = false;
      done(isOpen);
    }, true);

    const factor = 1 - Math.min(Math.abs(velocity) / 4, 0.7);
    const dur = ani.getDuration() * factor;

    ani.progressEnd(shouldComplete, currentStepValue, dur);
  }

  destroy() {
    this.ani.destroy();
    this.ani = null;
  }

}


text:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { WalletComponent } from './wallet.component';

describe('WalletComponent', () => {
  let component: WalletComponent;
  let fixture: ComponentFixture<WalletComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ WalletComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(WalletComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
<?php

 namespace ElephantIO\Exception;

 use RuntimeException;

 class UnsupportedTransportException extends RuntimeException
 {
     public function __construct($transport, \Exception $previous = null)
     {
         parent::__construct(sprintf('This server does not support the %s transport, aborting', $transport), 0, $previous);
     }
 }


text:
require 'spec_helper'

describe 'Jasmine command line tool' do
  before :each do
    temp_dir_before
    Dir::chdir @tmp
  end

  after :each do
    temp_dir_after
  end

  describe '.init' do
    describe 'without a Gemfile' do
      it 'should create files on init' do
        output = capture_stdout { Jasmine::CommandLineTool.new.process ['init'] }
        output.should =~ /Jasmine has been installed\./

        File.exists?(File.join(@tmp, 'spec/javascripts/helpers/.gitkeep')).should == true
        File.exists?(File.join(@tmp, 'spec/javascripts/support/jasmine.yml')).should == true
        File.exists?(File.join(@tmp, 'Rakefile')).should == true
        ci_output = `rake --trace jasmine:ci`
        ci_output.should =~ (/0 specs, 0 failures/)
      end

      it 'should create a new Rakefile if it does not exist' do
        output = capture_stdout { Jasmine::CommandLineTool.new.process ["init"] }
        output.should =~ /Jasmine has been installed\./
        File.read(File.join(@tmp, 'Rakefile')).should include('jasmine.rake')
      end

      it "should append to an existing Rakefile" do
        FileUtils.cp("#{@old_dir}/spec/fixture/Rakefile", @tmp)
        output = capture_stdout { Jasmine::CommandLineTool.new.process ["init"] }
        output.should =~ /Jasmine has been installed\./
        File.read(File.join(@tmp, 'Rakefile')).should include('jasmine_flunk')
      end
    end

    describe 'with a Gemfile containing Rails' do
      before :each do
        open(File.join(@tmp, "Gemfile"), 'w') do |f|
          f.puts "rails"
        end
      end

      it 'should warn the user' do
        output = capture_stdout {
          expect {
            Jasmine::CommandLineTool.new.process ['init']
          }.to raise_error SystemExit
        }
        output.should =~ /attempting to run jasmine init in a Rails project/

        Dir.entries(@tmp).sort.should == [".", "..", "Gemfile"]
      end

      it 'should allow the user to override the warning' do
        output = capture_stdout {
          expect {
            Jasmine::CommandLineTool.new.process ['init', '--force']
          }.not_to raise_error
        }
        output.should =~ /Jasmine has been installed\./

        File.exists?(File.join(@tmp, 'spec/javascripts/helpers/.gitkeep')).should == true
        File.exists?(File.join(@tmp, 'spec/javascripts/support/jasmine.yml')).should == true
      end
    end

    describe 'with a Gemfile not containing Rails' do
      before :each do
        open(File.join(@tmp, "Gemfile"), 'w') do |f|
          f.puts "sqlite3"
        end
      end

      it 'should perform normally' do
        output = capture_stdout {
          expect {
            Jasmine::CommandLineTool.new.process ['init']
          }.not_to raise_error
        }
        output.should =~ /Jasmine has been installed\./

        File.exists?(File.join(@tmp, 'spec/javascripts/helpers/.gitkeep')).should == true
        File.exists?(File.join(@tmp, 'spec/javascripts/support/jasmine.yml')).should == true
      end
    end
  end

  it 'should install the examples' do
    output = capture_stdout { Jasmine::CommandLineTool.new.process ['examples'] }
    output.should =~ /Jasmine has installed some examples\./
    File.exists?(File.join(@tmp, 'public/javascripts/jasmine_examples/Player.js')).should == true
    File.exists?(File.join(@tmp, 'public/javascripts/jasmine_examples/Song.js')).should == true
    File.exists?(File.join(@tmp, 'spec/javascripts/jasmine_examples/PlayerSpec.js')).should == true
    File.exists?(File.join(@tmp, 'spec/javascripts/helpers/jasmine_examples/SpecHelper.js')).should == true

    capture_stdout { Jasmine::CommandLineTool.new.process ['init'] }
    ci_output = `rake --trace jasmine:ci`
    ci_output.should =~ (/[1-9]\d* specs, 0 failures/)
  end

  it 'should include license info' do
    output = capture_stdout { Jasmine::CommandLineTool.new.process ['license'] }
    output.should =~ /Copyright/
  end

  it 'should copy boot.js' do
    output = capture_stdout { Jasmine::CommandLineTool.new.process ['copy_boot_js'] }
    output.should =~ /Jasmine has copied an example boot.js to spec\/javascripts\/support/

    File.exists?(File.join(@tmp, 'spec/javascripts/support/boot.js')).should == true
  end

  it 'should not overwrite an existing boot.js' do
    capture_stdout { Jasmine::CommandLineTool.new.process ['copy_boot_js'] }
    output = capture_stdout { Jasmine::CommandLineTool.new.process ['copy_boot_js'] }

    output.should =~ /already exists/
  end
end


text: require_relative './railtie' if defined?(Rails)


text:
Cloud Monitoring Exporter Example
=================================

These examples show how to use OpenTelemetry to send metrics data to Cloud Monitoring.

Basic Example
-------------

To use this exporter you first need to:
    * `Create a Google Cloud project <https://console.cloud.google.com/projectcreate>`_.
    * Enable the Cloud Monitoring API (aka Stackdriver Monitoring API) in the project `here <https://console.cloud.google.com/apis/library?q=cloud_monitoring>`_.
    * Enable `Default Application Credentials <https://developers.google.com/identity/protocols/application-default-credentials>`_.

* Installation

.. code-block:: sh

    pip install opentelemetry-exporter-gcp-monitoring \
        opentelemetry-api \
        opentelemetry-sdk

* Run example code

.. literalinclude:: basic_metrics.py
    :language: python
    :lines: 1-

Viewing Output
--------------------------

After running the example:
    * Go to the `Cloud Monitoring Metrics Explorer page <https://console.cloud.google.com/monitoring/metrics-explorer>`_.
    * In "Select a Metric" enter "workload.googleapis.com/request_counter".
    * You can filter by labels and change the graphical output here as well.

Troubleshooting
--------------------------

``One or more points were written more frequently than the maximum sampling period configured for the metric``
##############################################################################################################

Currently, Cloud Monitoring allows one write every 5 seconds for any unique tuple (metric_name, metric_label_value_1, metric_label_value_2, ...). The exporter should rate limit on its own but issues arise if:

    * You are restarting the server more than once every 5 seconds.
    * You have a multiple exporters (possibly on different threads) writing to the same tuple.

For both cases, you can pass ``add_unique_identifier=True`` to the CloudMonitoringMetricsExporter constructor. This adds a UUID label_value, making the tuple unique again. For the first case, you can also choose to just wait longer than 5 seconds between restarts.


text:
package org.androidtransfuse.util.matcher;

import com.google.common.collect.ImmutableSet;
import org.androidtransfuse.adapter.ASTAnnotation;

import java.util.Collection;

/**
 * Matches a collection of annotations exactly to the given set of annotations.  This matches both the type
 * of the annotation and the contained parameters.
 *
 * @author John Ericksen
 */
public class ASTAnnotationMatcher implements Matcher<Collection<ASTAnnotation>> {

    private final ImmutableSet<ASTAnnotation> annotation;

    public ASTAnnotationMatcher(ImmutableSet<ASTAnnotation> annotation) {
        this.annotation = annotation;
    }

    @Override
    public boolean matches(Collection<ASTAnnotation> input) {

        if(input.size() != annotation.size()){
            return false;
        }

        for (ASTAnnotation astAnnotation : annotation) {
            boolean found = false;
            for (ASTAnnotation inputAnnotations : input) {
                if(annotationsEquals(astAnnotation, inputAnnotations)){
                    found = true;
                }
            }
            if(!found){
                return false;
            }
        }

        return true;
    }

    private boolean annotationsEquals(ASTAnnotation astAnnotation, ASTAnnotation inputAnnotations) {
        if(!astAnnotation.getASTType().equals(inputAnnotations.getASTType())){
            return false;
        }

        for (String propertyName : astAnnotation.getPropertyNames()) {

            Object annotationProperty = astAnnotation.getProperty(propertyName, Object.class);
            Object inputProperty = inputAnnotations.getProperty(propertyName, Object.class);

            if(!annotationProperty.equals(inputProperty)){
                return false;
            }
        }

        return true;
    }
}


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

package com.google.gerrit.extensions.client;

import java.util.EnumSet;

/** Output options available when using {@code /groups/} RPCs. */
public enum ListGroupsOption {
  /** Return information on the direct group members. */
  MEMBERS(0),

  /** Return information on the directly included groups. */
  INCLUDES(1);

  private final int value;

  ListGroupsOption(int v) {
    this.value = v;
  }

  public int getValue() {
    return value;
  }

  public static EnumSet<ListGroupsOption> fromBits(int v) {
    EnumSet<ListGroupsOption> r = EnumSet.noneOf(ListGroupsOption.class);
    for (ListGroupsOption o : ListGroupsOption.values()) {
      if ((v & (1 << o.value)) != 0) {
        r.add(o);
        v &= ~(1 << o.value);
      }
      if (v == 0) {
        return r;
      }
    }
    if (v != 0) {
      throw new IllegalArgumentException("unknown " + Integer.toHexString(v));
    }
    return r;
  }

  public static int toBits(EnumSet<ListGroupsOption> set) {
    int r = 0;
    for (ListGroupsOption o : set) {
      r |= 1 << o.value;
    }
    return r;
  }
}


text:
import json
from unittest import mock

import pytest

from pgctl import __version__
from pgctl import telemetry

@pytest.fixture
def mock_clog():
    with mock.patch.object(telemetry, '_clog_configured', True):
        with mock.patch.object(telemetry, 'clog') as fake_clog:
            yield fake_clog

def test_event_context():
    context = telemetry._event_context()
    assert context['time'].startswith('20')
    assert context['version'] == __version__

def test_emit_event(mock_clog):
    telemetry.emit_event('my_event', {'attr1': 'value1', 'attr2': 'value2'})
    call, = mock_clog.mock_calls
    _, args, _ = call

    assert args[0] == 'tmp_pgctl_events'
    payload = json.loads(args[1])
    assert payload['attributes'] == {
        'attr1': 'value1',
        'attr2': 'value2',
    }
    assert payload['event'] == 'my_event'

    # Just spot-checking some of the auto-injected context variables.
    assert 'version' in payload
    assert 'time' in payload


text:
function parse1(n: number=) { }

//// [jsdocParseErrorsInTypescript.js]
// parse error (blocks grammar errors from checker)
function parse1(n) {
    if (n === void 0) { n = ; }
}


text:
import { RouterEventType } from '../../../event/router';

export function focus(
  type: RouterEventType,
  document: Document,
): void {
  switch (type) {
    case RouterEventType.Click:
    case RouterEventType.Submit:
      return void [...document.querySelectorAll<HTMLElement>('[autofocus]')]
        .slice(-1)
        .filter(el =>
          el.closest('html') === window.document.documentElement &&
          el !== document.activeElement)
        .forEach(el =>
          void el.focus());
    case RouterEventType.Popstate:
      return;
    default:
      throw new TypeError(type);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DentistSpace.Common
{
    public static class  Class1
    {
    }
}


text:
"""Regexp-based split and replace using the obsolete regex module.

This module is only for backward compatibility.  These operations
are now provided by the new regular expression module, "re".

sub(pat, repl, str):        replace first occurrence of pattern in string
gsub(pat, repl, str):       replace all occurrences of pattern in string
split(str, pat, maxsplit):  split string using pattern as delimiter
splitx(str, pat, maxsplit): split string using pattern as delimiter plus
                            return delimiters
"""

import warnings
warnings.warn("the regsub module is deprecated; please use re.sub()",
              DeprecationWarning)

# Ignore further deprecation warnings about this module
warnings.filterwarnings("ignore", "", DeprecationWarning, __name__)

import regex

__all__ = ["sub","gsub","split","splitx","capwords"]

# Replace first occurrence of pattern pat in string str by replacement
# repl.  If the pattern isn't found, the string is returned unchanged.
# The replacement may contain references \digit to subpatterns and
# escaped backslashes.  The pattern may be a string or an already
# compiled pattern.

def sub(pat, repl, str):
    prog = compile(pat)
    if prog.search(str) >= 0:
        regs = prog.regs
        a, b = regs[0]
        str = str[:a] + expand(repl, regs, str) + str[b:]
    return str

# Replace all (non-overlapping) occurrences of pattern pat in string
# str by replacement repl.  The same rules as for sub() apply.
# Empty matches for the pattern are replaced only when not adjacent to
# a previous match, so e.g. gsub('', '-', 'abc') returns '-a-b-c-'.

def gsub(pat, repl, str):
    prog = compile(pat)
    new = ''
    start = 0
    first = 1
    while prog.search(str, start) >= 0:
        regs = prog.regs
        a, b = regs[0]
        if a == b == start and not first:
            if start >= len(str) or prog.search(str, start+1) < 0:
                break
            regs = prog.regs
            a, b = regs[0]
        new = new + str[start:a] + expand(repl, regs, str)
        start = b
        first = 0
    new = new + str[start:]
    return new

# Split string str in fields separated by delimiters matching pattern
# pat.  Only non-empty matches for the pattern are considered, so e.g.
# split('abc', '') returns ['abc'].
# The optional 3rd argument sets the number of splits that are performed.

def split(str, pat, maxsplit = 0):
    return intsplit(str, pat, maxsplit, 0)

# Split string str in fields separated by delimiters matching pattern
# pat.  Only non-empty matches for the pattern are considered, so e.g.
# split('abc', '') returns ['abc']. The delimiters are also included
# in the list.
# The optional 3rd argument sets the number of splits that are performed.

def splitx(str, pat, maxsplit = 0):
    return intsplit(str, pat, maxsplit, 1)

# Internal function used to implement split() and splitx().

def intsplit(str, pat, maxsplit, retain):
    prog = compile(pat)
    res = []
    start = next = 0
    splitcount = 0
    while prog.search(str, next) >= 0:
        regs = prog.regs
        a, b = regs[0]
        if a == b:
            next = next + 1
            if next >= len(str):
                break
        else:
            res.append(str[start:a])
            if retain:
                res.append(str[a:b])
            start = next = b
            splitcount = splitcount + 1
            if (maxsplit and (splitcount >= maxsplit)):
                break
    res.append(str[start:])
    return res

# Capitalize words split using a pattern

def capwords(str, pat='[^a-zA-Z0-9_]+'):
    words = splitx(str, pat)
    for i in range(0, len(words), 2):
        words[i] = words[i].capitalize()
    return "".join(words)

# Internal subroutines:
# compile(pat): compile a pattern, caching already compiled patterns
# expand(repl, regs, str): expand \digit escapes in replacement string

# Manage a cache of compiled regular expressions.
#
# If the pattern is a string a compiled version of it is returned.  If
# the pattern has been used before we return an already compiled
# version from the cache; otherwise we compile it now and save the
# compiled version in the cache, along with the syntax it was compiled
# with.  Instead of a string, a compiled regular expression can also
# be passed.

cache = {}

def compile(pat):
    if type(pat) != type(''):
        return pat              # Assume it is a compiled regex
    key = (pat, regex.get_syntax())
    if key in cache:
        prog = cache[key]       # Get it from the cache
    else:
        prog = cache[key] = regex.compile(pat)
    return prog

def clear_cache():
    global cache
    cache = {}

# Expand \digit in the replacement.
# Each occurrence of \digit is replaced by the substring of str
# indicated by regs[digit].  To include a literal \ in the
# replacement, double it; other \ escapes are left unchanged (i.e.
# the \ and the following character are both copied).

def expand(repl, regs, str):
    if '\\' not in repl:
        return repl
    new = ''
    i = 0
    ord0 = ord('0')
    while i < len(repl):
        c = repl[i]; i = i+1
        if c != '\\' or i >= len(repl):
            new = new + c
        else:
            c = repl[i]; i = i+1
            if '0' <= c <= '9':
                a, b = regs[ord(c)-ord0]
                new = new + str[a:b]
            elif c == '\\':
                new = new + c
            else:
                new = new + '\\' + c
    return new

# Test program, reads sequences "pat repl str" from stdin.
# Optional argument specifies pattern used to split lines.

def test():
    import sys
    if sys.argv[1:]:
        delpat = sys.argv[1]
    else:
        delpat = '[ \t\n]+'
    while 1:
        if sys.stdin.isatty(): sys.stderr.write('--> ')
        line = sys.stdin.readline()
        if not line: break
        if line[-1] == '\n': line = line[:-1]
        fields = split(line, delpat)
        if len(fields) != 3:
            print 'Sorry, not three fields'
            print 'split:', `fields`
            continue
        [pat, repl, str] = split(line, delpat)
        print 'sub :', `sub(pat, repl, str)`
        print 'gsub:', `gsub(pat, repl, str)`


text:
============
Rally v0.5.0
============

Information
-----------

+------------------+-----------------------+
| Commits          |        **175**        |
+------------------+-----------------------+
| Bug fixes        |        **19**         |
+------------------+-----------------------+
| Dev cycle        |      **93 days**      |
+------------------+-----------------------+
| Release date     |     **7/20/2016**     |
+------------------+-----------------------+

Details
-------

This release took much more time than we expected, but we have a lot of
reasons for such delay and if you look at our change-log, you will understand
them.:)

Here is a quick introduction:

* To make our releases as much as possible stable, we added upper limits for
  each of our requirements;
* A lot of deprecated lines of code were removed, so be careful;
* Statistics trends for given tasks were introduced;
* Support for tempest plugins was added;
* Several new pages at docs.

Specs & Feature Requests
~~~~~~~~~~~~~~~~~~~~~~~~

* `[Introduced && implemented] Introduce class-based scenario implementation <https://github.com/openstack/rally/blob/0.5.0/doc/specs/implemented/class-based-scenarios.rst>`_

* `[Introduced] Rally Task Validation refactoring <https://github.com/openstack/rally/blob/0.5.0/doc/specs/in-progress/pluggable_validators.rst>`_

* `[Introduced] Scaling & Refactoring Rally DB <https://github.com/openstack/rally/blob/0.5.0/doc/specs/in-progress/db_refactoring.rst>`_

* `[Introduced] SLA Performance degradation plugin <https://github.com/openstack/rally/blob/0.5.0/doc/specs/in-progress/sla_pd_plugin.rst>`_

Logging
~~~~~~~

* disable urllib3 warnings only if the library provide them

Database
~~~~~~~~

[doesn't require migration]
Transform DB layer to return dicts, not SQLAlchemy models

Rally Deployment
~~~~~~~~~~~~~~~~

* Support single-AZ deployment

  This supports the case where OpenStack is deployed with a single AZ for both
  controller(s) and compute(s), and not all hosts in the AZ that contains an
  instance are guaranteed to have the nova-compute service.

* Extend creation from environment with several new vars

  - OS_ENDPOINT_TYPE/OS_INTERFACE
  - OS_USER_DOMAIN_NAME
  - OS_PROJECT_DOMAIN_NAME

* Improve devstack plugin for Keystone V3

Rally Task
~~~~~~~~~~

*NEW!!* Statistics trends for given tasks.

Rally Verify
~~~~~~~~~~~~

* Remove '--tempest-config' arg from 'reinstall' command

  .. warning:: Using `--tempest-config` is became an error from this release.
      Use `rally verify genconfig` cmd for all config related stuff.

* Don't install Tempest when `rally verify start`

  .. warning:: Use should use `rally verify install` cmd to install tempest now

* Add ability to setup version of Tempest to install

  `CLI argument to setup version <http://rally.readthedocs.io/en/0.5.0/cli/cli_reference.html#verify-install-version>`_

* Configure 'aodh' service in 'service_available' section

* Check existence of Tempest-tree in `rally verify discover` cmd

* Make Tempest work with auth url which doesn't include keystone version

  Tempest needs /v2.0 and /v3 at the end of URLs. Actually, we can't fix
  Tempest, so we extend our configuration module with workaround which allow
  to specify auth_url without version in rally deployment config.

* Use default list of plugins for sahara

* Move tempest related options of rally configuration to separate section.

* *NEW!!* Support for tempest plugins.

  `CLI argument to install them <http://rally.readthedocs.io/en/0.5.0/cli/cli_reference.html#verify-installplugin>`_

Plugins
~~~~~~~

In this release we are happy to introduce new entity - plugins Base classes

We have a lot of base plugin entities: Context, Scenario, SLA and etc.
Sometimes plugins of different bases can have equal names(i.e ceilometer
OSClient and ceilometer Context). It is normal and we should allow such
conflicts. To support such cases we introduced new entity - plugin base.
Statements of plugin bases:
 - Each plugin base is unique entity;
 - Names of plugin bases can't conflict with each other;
 - Names of two or more plugins in one plugin base can't conflict with each
   other(in case of same namespace).
 - Names of two or more plugins in different plugin base can conflict

Current list of plugin bases:
 - rally.task.context.Context
 - rally.task.scenario.Scenario
 - rally.task.types.ResourceType
 - rally.task.exporter.TaskExporter
 - rally.task.processing.charts.Chart
 - rally.task.runner.ScenarioRunner
 - rally.task.sla.SLA
 - rally.deployment.serverprovider.provider.ProviderFactory
 - rally.deployment.engine.Engine
 - rally.osclients.OSClient

**OSClients**

* *NEW!!* Support for Senlin client

* *NEW!!* Support for Gnocchi client

* *NEW!!* Support for Magnum client

* *NEW!!* Support for Watcher client

* Transmit endpoint_type to saharaclient

**Scenarios**:

* *NEW!!*:

 - `Authenticate.validate_ceilometer <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#authenticate-validate-ceilometer-scenario>`_
 - `CinderVolumes.create_volume_from_snapshot <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#cindervolumes-create-volume-from-snapshot>`_
 - `CinderVolumes.create_volume_and_clone <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#cindervolumes-create-volume-and-clone>`_
 - `NovaFlavors.create_and_list_flavor_access <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#novaflavors-create-and-list-flavor-access-scenario>`_
 - `NovaFlavors.create_flavor <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#novaflavors-create-flavor-scenario>`_
 - `NovaServers.boot_and_update_server <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#novaservers-boot-and-update-server>`_
 - `NovaServers.boot_server_from_volume_snapshot <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#novaservers-boot-server-from-volume-snapshot>`_

* [Sahara] Add configs to MapR plugin

* Extend CinderVolumes.create_and_upload_volume_to_image with "image" argument

  `Plugin Reference <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#cindervolumes-create-and-upload-volume-to-image-scenario>`_

* Deprecate Dummy.dummy_with_scenario_output scenario in favor of Dummy.dummy_output

  .. warning:: Dummy.dummy_with_scenario_output scenario will be removed after
      several releases

  `Deprecated Plugin Reference <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#dummy-dummy-with-scenario-output-scenario>`_
  `New Plugin Reference <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#dummy-dummy-output-scenario>`_

* Extend CinderVolumes.create_volume_and_clone with nested_level

  Add nested_level argument for nested cloning volume to new volume

  `Plugin Reference <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#cindervolumes-create-volume-and-clone>`_

* Extend CinderVolumes.create_nested_snapshots_and_attach_volume

  Two new arguments were added: create_volume_kwargs and create_snapshot_kwargs

  .. warning:: All arguments related to snapshot creation should be transmitted
        only via create_snapshot_kwargs.

  `Plugin Reference <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#cindervolumes-create-nested-snapshots-and-attach-volume>`_

* Introduce new style of scenarios - class based.

  `Spec Reference <https://github.com/openstack/rally/blob/0.5.0/doc/specs/implemented/class-based-scenarios.rst>`_

* Improve report for VMTasks.boot_runcommand_delete

* [Sahara] Added 5.5.0 version for cdh-plugin and 1.6.0 version for spark

* Extend boot_server_from_volume_and_delete, boot_server_from_volume,
  boot_server_from_volume_and_live_migrate, boot_server_from_volume_snapshot
  scenarios of NovaServers class with "volume_type" parameter.

**Contexts**:

* *NEW!!*:

  - `Cinder volume_types <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#volume-types-context>`_
  - `Murano environments <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#murano-environments-context>`_
  - `Heat dataplane <http://rally.readthedocs.io/en/0.5.0/plugin/plugin_reference.html#heat-dataplane-context>`_

* Use Broker Pattern in Keystone roles context

* Use immutable types for locking context configuration

  Since context configuration passed to Context.__init__() was a mutable type
  (dict or list), sometimes we had unexpected changes done by unpredictable
  code (for example, in wrappers).

* Add possibility to balance usage of users

  For the moment all users for tasks were taken randomly and there was no way
  to balance them between tasks. It may be very useful when we have difference
  between first usage of tenant/user and all consecutive. In this case we get
  different load results.

  Therefore, "users" context was extended with new config option
  'user_choice_method' that defines approach for picking up users.

  Two values are available:
  - random
  - round_robin

  Default one is compatible with old approach - "random".

* Make sahara_image and custom_image contexts glance v2 compatible

* Extend servers context with "nics" parameter

* Extend network context with "dns_nameservers" parameter

* Extend volume context with "volume_type" parameter

**Cleanup**:

* Mark several cleanup resources as tenant_resource

  Nova servers and security groups are tenant related resources, but resource
  decorator missed that fact which makes cleanup tries to delete one resources
  several times.

* Turn off redundant nova servers cleanup for NovaFlavors.list_flavors scenario

* Add neutron cleanup for NeutronSecurityGroup.create_and_delete_security_groups

**Exporter**:

Rename task-exporter "file-exporter" to "file".

.. warning:: "file-exporter" is deprecated and will be removed in further
    releases.

**Types**:

Remove deprecated types.

.. warning:: you should use rally.task.types.convert instead of
    rally.task.types.set decorator

**Validators**

* Add a required_api_version validator
* Add validators for scenario arguments

**Utils**:

Use glance wrapper where appropriate to support compatibility between V1 and V2

Bug fixes
~~~~~~~~~

**19 bugs were fixed**:

* Wrong arguments order of Keystone wrapper in case of V2 and V3

* AttributeError while disabling urllib3 warnings on old installations

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1573650>`_

* install_rally.sh script is failed while obtaining setuptools

* "-inf" load duration in case of wrong runner plugin and failed start of
  contexts

* Strange input task in the report

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1570328>`_

* Wrong behaviour of boot_server_from_volume scenarios in case of booting
  server from image.

  The arg of image must be None, when booting server from volume. Otherwise
  still boot server from image.

  Affected scenarios:
    NovaServers.boot_server_from_volume
    NovaServers.boot_server_from_volume_and_delete
    NovaServers.boot_server_from_volume_and_resize
    NovaServers.boot_server_from_volume_and_live_migrate

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1578556>`_

* Weak validation of json schema of RPS runner

  JSON Schema of RPS runner doesn't have "required" field. It means that
  users are able to pass wrong configs and we will have runtime error while
  running task.

* Rally doesn't take cacert setting while creating keystone session

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1577360>`_

* Heat scenarios fail when API uses TLS

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1585456>`_

* Example in comment of context manila_share_networks wrong

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1587164>`_

* There is no way to get UUID of a verification after it is created by
  "rally verify start" or "rally verify import_results" when --no-use is set

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1587034>`_

* Exposed ssh timeout and interval in vm scenario

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1587728>`_

* Ceilometer scenario doesn't require "ceilometer" ctx

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1557642>`_

* "servers" context requires setting network id for multiple possible networks
  found.

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1592292>`_

* nested_level data type incorrect in create_nested_snapshots_and_attach_volume

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1594656>`_

* Rally cleanup servers raises exception

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1584104>`_

* Stopping server is redundant before cold-migrating server

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1594730>`_

* existing_users context doesn't work in case of Keystone v3

* Whether validates flavor's disk or not depends on booting type of the instance

  `Launchpad bug-report <https://bugs.launchpad.net/rally/+bug/1596756>`_

Documentation
~~~~~~~~~~~~~

* Re-use openstack theme for building docs outside rtd.

  `Rally Docs at docs.openstack.org <http://docs.openstack.org/developer/rally/>`_

* Add page for Verification component

  `RTD page <http://rally.readthedocs.io/en/0.5.0/tutorial/step_10_verifying_cloud_via_tempest.html>`_

* Add glossary page

  `RTD page <http://rally.readthedocs.io/en/0.5.0/tutorial/glossary.html>`_

* Adjust docs reference to "KeystoneBasic.authenticate" scenario

  `RTD page <http://rally.readthedocs.io/en/0.5.0/tutorial/step_6_aborting_load_generation_on_sla_failure.html>`_

Thanks
~~~~~~

 2 Everybody!


text:
.class Lcom/android/internal/app/ExternalMediaFormatActivity$1;
.super Landroid/content/BroadcastReceiver;
.source "ExternalMediaFormatActivity.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/app/ExternalMediaFormatActivity;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/app/ExternalMediaFormatActivity;

# direct methods
.method constructor <init>(Lcom/android/internal/app/ExternalMediaFormatActivity;)V
    .locals 0
    .parameter

    .prologue
    .line 48
    iput-object p1, p0, Lcom/android/internal/app/ExternalMediaFormatActivity$1;->this$0:Lcom/android/internal/app/ExternalMediaFormatActivity;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 5
    .parameter "context"
    .parameter "intent"

    .prologue
    .line 51
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    .line 52
    .local v0, action:Ljava/lang/String;
    invoke-virtual {p2}, Landroid/content/Intent;->getData()Landroid/net/Uri;

    move-result-object v2

    invoke-virtual {v2}, Landroid/net/Uri;->getPath()Ljava/lang/String;

    move-result-object v1

    .line 53
    .local v1, path:Ljava/lang/String;
    const-string v2, "ExternalMediaFormatActivity"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "got action "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, ", path = "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 55
    iget-object v2, p0, Lcom/android/internal/app/ExternalMediaFormatActivity$1;->this$0:Lcom/android/internal/app/ExternalMediaFormatActivity;

    #getter for: Lcom/android/internal/app/ExternalMediaFormatActivity;->mPath:Ljava/lang/String;
    invoke-static {v2}, Lcom/android/internal/app/ExternalMediaFormatActivity;->access$000(Lcom/android/internal/app/ExternalMediaFormatActivity;)Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_1

    .line 56
    const-string v2, "android.intent.action.MEDIA_REMOVED"

    if-eq v0, v2, :cond_0

    const-string v2, "android.intent.action.MEDIA_CHECKING"

    if-eq v0, v2, :cond_0

    const-string v2, "android.intent.action.MEDIA_MOUNTED"

    if-eq v0, v2, :cond_0

    const-string v2, "android.intent.action.MEDIA_SHARED"

    if-ne v0, v2, :cond_1

    .line 60
    :cond_0
    iget-object v2, p0, Lcom/android/internal/app/ExternalMediaFormatActivity$1;->this$0:Lcom/android/internal/app/ExternalMediaFormatActivity;

    invoke-virtual {v2}, Lcom/android/internal/app/ExternalMediaFormatActivity;->finish()V

    .line 63
    :cond_1
    return-void
.end method


text:
<!DOCTYPE html>

<title>File_deleteFile_onerror_invalid_cb</title>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Gams, Kleine Kryptogamenflora von Mitteleuropa - Die Blätter- und Baupilze (Agaricales und Gastromycetes) 2b: 37 (1953)

#### Original name
Hygrophorus nitiosus A. Blytt, 1905

### Remarks
null


text:
class StakesController < ApplicationController
  before_action :set_stake, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user,
                :must_have_person_if_logged_in,
                :must_be_active,
                :check_authorization

  # GET /stakes
  # GET /stakes.json
  def index
    @stakes = Stake.includes(:wards).order(:name)
  end

  # GET /stakes/1
  # GET /stakes/1.json
  def show
  end

  # GET /stakes/new
  def new
    @stake = Stake.new
  end

  # GET /stakes/1/edit
  def edit
  end

  # POST /stakes
  # POST /stakes.json
  def create
    @stake = Stake.new(stake_params)

    respond_to do |format|
      if @stake.save
        format.html { redirect_to @stake, notice: 'Estaca criada com sucesso.' }
        format.json { render :show, status: :created, location: @stake }
      else
        format.html { render :new }
        format.json { render json: @stake.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /stakes/1
  # PATCH/PUT /stakes/1.json
  def update
    respond_to do |format|
      if @stake.update(stake_params)
        format.html { redirect_to @stake, notice: 'Estaca atualizada com sucesso.' }
        format.json { render :show, status: :ok, location: @stake }
      else
        format.html { render :edit }
        format.json { render json: @stake.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /stakes/1
  # DELETE /stakes/1.json
  def destroy
    @stake.destroy
    respond_to do |format|
      format.html { redirect_to stakes_url, notice: 'Estaca removida com sucesso.' }
      format.json { head :no_content }
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_stake
    @stake = Stake.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def stake_params
    params.require(:stake).permit(:name, :region_id)
  end

  # Verifica se usuario logado tem permissao para acessar a controller
  def check_authorization
    permitted = [:admin]
    fail User::NotAuthorized unless permitted.include? current_user.profile.to_sym
  end
end


text:
package com.mdataset.service.api

import com.ecfront.ez.framework.core.EZManager
import com.ecfront.ez.framework.core.test.BasicSpec
import com.mdataset.service.api.export.query.SocketAPI

class MockStartupSpec extends BasicSpec {

  before {
    EZManager.start()
    MdsContext.apiExchangeMaster.registerResp()
    MdsContext.apiExchangeMaster.unRegisterResp()
    SocketAPI.listening(MdsContext.socketPort, MdsContext.socketHost)
  }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Bombax sordidum R.E.Schult.

### Remarks
null