text:
package org.littleshoot.proxy;

import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongArray;

import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class HttpFilterTest {
    private Server webServer;
    private HttpProxyServer proxyServer;
    private int webServerPort;

    @Before
    public void setUp() throws Exception {
        webServer = new Server(0);
        webServer.start();
        webServerPort = TestUtils.findLocalHttpPort(webServer);
    }

    @After
    public void tearDown() throws Exception {
        try {
            if (webServer != null) {
                webServer.stop();
            }
        } finally {
            if (proxyServer != null) {
                proxyServer.stop();
            }
        }
    }

    /**
     * Sets up the HttpProxyServer instance for a test. This method initializes the proxyServer and proxyPort method variables, and should
     * be called before making any requests through the proxy server.
     *
     * The proxy cannot be created in an @Before method because the filtersSource must be initialized by each test before the proxy is
     * created.
     *
     * @param filtersSource HTTP filters source
     */
    private void setUpHttpProxyServer(HttpFiltersSource filtersSource) {
        this.proxyServer = DefaultHttpProxyServer.bootstrap()
                .withPort(0)
                .withFiltersSource(filtersSource)
                .start();

        final InetSocketAddress isa = new InetSocketAddress("127.0.0.1", proxyServer.getListenAddress().getPort());
        while (true) {
            final Socket sock = new Socket();
            try {
                sock.connect(isa);
                break;
            } catch (final IOException e) {
                // Keep trying.
            } finally {
                IOUtils.closeQuietly(sock);
            }

            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted while verifying proxy is connectable");
            }
        }
    }

    @Test
    public void testFiltering() throws Exception {
        final AtomicInteger shouldFilterCalls = new AtomicInteger(0);
        final AtomicInteger filterResponseCalls = new AtomicInteger(0);
        final AtomicInteger fullHttpRequestsReceived = new AtomicInteger(0);
        final AtomicInteger fullHttpResponsesReceived = new AtomicInteger(0);
        final Queue<HttpRequest> associatedRequests =
                new LinkedList<HttpRequest>();

        final AtomicInteger requestCount = new AtomicInteger(0);
        final AtomicLongArray proxyToServerRequestSendingNanos = new AtomicLongArray(new long[] { -1, -1, -1, -1, -1 });
        final AtomicLongArray proxyToServerRequestSentNanos = new AtomicLongArray(new long[] { -1, -1, -1,-1, -1 });
        final AtomicLongArray serverToProxyResponseReceivingNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray serverToProxyResponseReceivedNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray proxyToServerConnectionQueuedNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray proxyToServerResolutionStartedNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray proxyToServerResolutionSucceededNanos = new AtomicLongArray(new long[] { -1,-1, -1, -1, -1 });
        final AtomicLongArray proxyToServerConnectionStartedNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray proxyToServerConnectionSSLHandshakeStartedNanos = new AtomicLongArray(new long[] {-1, -1, -1, -1, -1 });
        final AtomicLongArray proxyToServerConnectionFailedNanos = new AtomicLongArray(new long[] { -1, -1,-1, -1, -1 });
        final AtomicLongArray proxyToServerConnectionSucceededNanos = new AtomicLongArray(new long[] { -1,-1, -1, -1, -1 });

        final String url1 = "http://localhost:" + webServerPort + "/";
        final String url2 = "http://localhost:" + webServerPort + "/testing";
        final String url3 = "http://localhost:" + webServerPort + "/testing2";
        final String url4 = "http://localhost:" + webServerPort + "/testing3";
        final String url5 = "http://localhost:" + webServerPort + "/testing4";
        final HttpFiltersSource filtersSource = new HttpFiltersSourceAdapter() {
            public HttpFilters filterRequest(HttpRequest originalRequest) {
                shouldFilterCalls.incrementAndGet();
                associatedRequests.add(originalRequest);

                return new HttpFiltersAdapter(originalRequest) {
                    @Override
                    public HttpResponse clientToProxyRequest(
                            HttpObject httpObject) {
                        fullHttpRequestsReceived.incrementAndGet();
                        if (httpObject instanceof HttpRequest) {
                            HttpRequest httpRequest = (HttpRequest) httpObject;
                            if (httpRequest.getUri().equals(url2)) {
                                return new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1,
                                        HttpResponseStatus.FORBIDDEN);
                            }
                        }
                        return null;
                    }

                    @Override
                    public HttpResponse proxyToServerRequest(
                            HttpObject httpObject) {
                        if (httpObject instanceof HttpRequest) {
                            HttpRequest httpRequest = (HttpRequest) httpObject;
                            if (httpRequest.getUri().equals("/testing2")) {
                                return new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1,
                                        HttpResponseStatus.FORBIDDEN);
                            }
                        }
                        return null;
                    }

                    @Override
                    public void proxyToServerRequestSending() {
                        proxyToServerRequestSendingNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void proxyToServerRequestSent() {
                        proxyToServerRequestSentNanos.set(requestCount.get(), now());
                    }

                    public HttpObject serverToProxyResponse(
                            HttpObject httpObject) {
                        if (originalRequest.getUri().contains("testing3")) {
                            return new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.FORBIDDEN);
                        }
                        filterResponseCalls.incrementAndGet();
                        if (httpObject instanceof FullHttpResponse) {
                            fullHttpResponsesReceived.incrementAndGet();
                        }
                        if (httpObject instanceof HttpResponse) {
                            ((HttpResponse) httpObject).headers().set(
                                    "Header-Pre", "1");
                        }
                        return httpObject;
                    }

                    @Override
                    public void serverToProxyResponseReceiving() {
                        serverToProxyResponseReceivingNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void serverToProxyResponseReceived() {
                        serverToProxyResponseReceivedNanos.set(requestCount.get(), now());
                    }

                    public HttpObject proxyToClientResponse(
                            HttpObject httpObject) {
                        if (originalRequest.getUri().contains("testing4")) {
                            return new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.FORBIDDEN);
                        }
                        if (httpObject instanceof HttpResponse) {
                            ((HttpResponse) httpObject).headers().set(
                                    "Header-Post", "2");
                        }
                        return httpObject;
                    }

                    @Override
                    public void proxyToServerConnectionQueued() {
                        proxyToServerConnectionQueuedNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public InetSocketAddress proxyToServerResolutionStarted(
                            String resolvingServerHostAndPort) {
                        proxyToServerResolutionStartedNanos.set(requestCount.get(), now());
                        return super.proxyToServerResolutionStarted(resolvingServerHostAndPort);
                    }

                    @Override
                    public void proxyToServerResolutionSucceeded(
                            String serverHostAndPort,
                            InetSocketAddress resolvedRemoteAddress) {
                        proxyToServerResolutionSucceededNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void proxyToServerConnectionStarted() {
                        proxyToServerConnectionStartedNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void proxyToServerConnectionSSLHandshakeStarted() {
                        proxyToServerConnectionSSLHandshakeStartedNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void proxyToServerConnectionFailed() {
                        proxyToServerConnectionFailedNanos.set(requestCount.get(), now());
                    }

                    @Override
                    public void proxyToServerConnectionSucceeded() {
                        proxyToServerConnectionSucceededNanos.set(requestCount.get(), now());
                    }

                };
            }

            public int getMaximumRequestBufferSizeInBytes() {
                return 1024 * 1024;
            }

            public int getMaximumResponseBufferSizeInBytes() {
                return 1024 * 1024;
            }
        };

        setUpHttpProxyServer(filtersSource);

        org.apache.http.HttpResponse response1 = getResponse(url1);
        // sleep for a short amount of time, to allow the filter methods to be invoked
        Thread.sleep(500);
        assertEquals(
                "Response should have included the custom header from our pre filter",
                "1", response1.getFirstHeader("Header-Pre").getValue());
        assertEquals(
                "Response should have included the custom header from our post filter",
                "2", response1.getFirstHeader("Header-Post").getValue());

        assertEquals(1, associatedRequests.size());
        assertEquals(1, shouldFilterCalls.get());
        assertEquals(1, fullHttpRequestsReceived.get());
        assertEquals(1, fullHttpResponsesReceived.get());
        assertEquals(1, filterResponseCalls.get());

        int i = requestCount.get();
        assertThat(proxyToServerConnectionQueuedNanos.get(i), lessThan(proxyToServerResolutionStartedNanos.get(i)));
        assertThat(proxyToServerResolutionStartedNanos.get(i), lessThan(proxyToServerResolutionSucceededNanos.get(i)));
        assertThat(proxyToServerResolutionSucceededNanos.get(i), lessThan(proxyToServerConnectionStartedNanos.get(i)));
        assertEquals(-1, proxyToServerConnectionSSLHandshakeStartedNanos.get(i));
        assertEquals(-1, proxyToServerConnectionFailedNanos.get(i));
        assertThat(proxyToServerConnectionStartedNanos.get(i), lessThan(proxyToServerConnectionSucceededNanos.get(i)));
        assertThat(proxyToServerConnectionSucceededNanos.get(i), lessThan(proxyToServerRequestSendingNanos.get(i)));
        assertThat(proxyToServerRequestSendingNanos.get(i), lessThan(proxyToServerRequestSentNanos.get(i)));
        assertThat(proxyToServerRequestSentNanos.get(i), lessThan(serverToProxyResponseReceivingNanos.get(i)));
        assertThat(serverToProxyResponseReceivingNanos.get(i), lessThan(serverToProxyResponseReceivedNanos.get(i)));

        // We just open a second connection here since reusing the original
        // connection is inconsistent.
        requestCount.incrementAndGet();
        org.apache.http.HttpResponse response2 = getResponse(url2);
        Thread.sleep(500);

        assertEquals(403, response2.getStatusLine().getStatusCode());

        assertEquals(2, associatedRequests.size());
        assertEquals(2, shouldFilterCalls.get());
        assertEquals(2, fullHttpRequestsReceived.get());
        assertEquals(1, fullHttpResponsesReceived.get());
        assertEquals(1, filterResponseCalls.get());

        requestCount.incrementAndGet();
        org.apache.http.HttpResponse response3 = getResponse(url3);
        Thread.sleep(500);

        assertEquals(403, response3.getStatusLine().getStatusCode());

        assertEquals(3, associatedRequests.size());
        assertEquals(3, shouldFilterCalls.get());
        assertEquals(3, fullHttpRequestsReceived.get());
        assertEquals(1, fullHttpResponsesReceived.get());
        assertEquals(1, filterResponseCalls.get());

        i = requestCount.get();
        assertThat(proxyToServerConnectionQueuedNanos.get(i), lessThan(proxyToServerResolutionStartedNanos.get(i)));
        assertThat(proxyToServerResolutionStartedNanos.get(i), lessThan(proxyToServerResolutionSucceededNanos.get(i)));
        assertEquals(-1, proxyToServerConnectionStartedNanos.get(i));
        assertEquals(-1, proxyToServerConnectionSSLHandshakeStartedNanos.get(i));
        assertEquals(-1, proxyToServerConnectionFailedNanos.get(i));
        assertEquals(-1, proxyToServerConnectionSucceededNanos.get(i));
        assertEquals(-1, proxyToServerRequestSendingNanos.get(i));
        assertEquals(-1, proxyToServerRequestSentNanos.get(i));
        assertEquals(-1, serverToProxyResponseReceivingNanos.get(i));
        assertEquals(-1, serverToProxyResponseReceivedNanos.get(i));

        final HttpRequest first = associatedRequests.remove();
        final HttpRequest second = associatedRequests.remove();
        final HttpRequest third = associatedRequests.remove();

        // Make sure the requests in the filter calls were the requests they
        // actually should have been.
        assertEquals(url1, first.getUri());
        assertEquals(url2, second.getUri());
        assertEquals(url3, third.getUri());

        requestCount.incrementAndGet();
        org.apache.http.HttpResponse response4 = getResponse(url4);
        Thread.sleep(500);

        i = requestCount.get();
        assertThat(proxyToServerConnectionQueuedNanos.get(i), lessThan(proxyToServerResolutionStartedNanos.get(i)));
        assertThat(proxyToServerResolutionStartedNanos.get(i), lessThan(proxyToServerResolutionSucceededNanos.get(i)));
        assertThat(proxyToServerResolutionSucceededNanos.get(i), lessThan(proxyToServerConnectionStartedNanos.get(i)));
        assertEquals(-1, proxyToServerConnectionSSLHandshakeStartedNanos.get(i));
        assertEquals(-1, proxyToServerConnectionFailedNanos.get(i));
        assertThat(proxyToServerConnectionStartedNanos.get(i), lessThan(proxyToServerConnectionSucceededNanos.get(i)));
        assertThat(proxyToServerConnectionSucceededNanos.get(i), lessThan(proxyToServerRequestSendingNanos.get(i)));
        assertThat(proxyToServerRequestSendingNanos.get(i), lessThan(proxyToServerRequestSentNanos.get(i)));
        assertThat(proxyToServerRequestSentNanos.get(i), lessThan(serverToProxyResponseReceivingNanos.get(i)));
        assertThat(serverToProxyResponseReceivingNanos.get(i), lessThan(serverToProxyResponseReceivedNanos.get(i)));

        requestCount.incrementAndGet();
        org.apache.http.HttpResponse response5 = getResponse(url5);

        assertEquals(403, response4.getStatusLine().getStatusCode());
        assertEquals(403, response5.getStatusLine().getStatusCode());
    }

    @Test
    public void testResolutionStartedFilterReturnsUnresolvedAddress() throws Exception {
        final AtomicBoolean resolutionSucceeded = new AtomicBoolean(false);

        HttpFiltersSource filtersSource = new HttpFiltersSourceAdapter() {
            @Override
            public HttpFilters filterRequest(HttpRequest originalRequest) {
                return new HttpFiltersAdapter(originalRequest) {
                    @Override
                    public InetSocketAddress proxyToServerResolutionStarted(String resolvingServerHostAndPort) {
                        return InetSocketAddress.createUnresolved("localhost", webServerPort);
                    }

                    @Override
                    public void proxyToServerResolutionSucceeded(String serverHostAndPort, InetSocketAddress resolvedRemoteAddress) {
                        assertFalse("expected to receive a resolved InetSocketAddress", resolvedRemoteAddress.isUnresolved());
                        resolutionSucceeded.set(true);
                    }
                };
            }
        };

        setUpHttpProxyServer(filtersSource);

        getResponse("http://localhost:" + webServerPort + "/");

        assertTrue("proxyToServerResolutionSucceeded method was not called", resolutionSucceeded.get());
    }

    @Test
    public void testRequestSentInvokedAfterLastHttpContentSent() throws Exception {
        final AtomicBoolean lastHttpContentProcessed = new AtomicBoolean(false);
        final AtomicBoolean requestSentCallbackInvoked = new AtomicBoolean(false);

        HttpFiltersSource filtersSource = new HttpFiltersSourceAdapter() {
            @Override
            public HttpFilters filterRequest(HttpRequest originalRequest) {
                return new HttpFiltersAdapter(originalRequest) {
                    @Override
                    public HttpResponse proxyToServerRequest(HttpObject httpObject) {
                        if (httpObject instanceof LastHttpContent) {
                            assertFalse("requestSentCallback should not be invoked until the LastHttpContent is processed", requestSentCallbackInvoked.get());

                            lastHttpContentProcessed.set(true);
                        }

                        return null;
                    }

                    @Override
                    public void proxyToServerRequestSent() {
                        // proxyToServerRequestSent should only be invoked after the entire request, including payload, has been sent to the server
                        assertTrue("proxyToServerRequestSent callback invoked before LastHttpContent was received from the client and sent to the server", lastHttpContentProcessed.get());

                        requestSentCallbackInvoked.set(true);
                    }
                };
            }
        };

        setUpHttpProxyServer(filtersSource);

        // test with a POST request with a payload. post a large amount of data, to force chunked content.
        postToServer("http://localhost:" + webServerPort + "/", 50000);

        assertTrue("proxyToServerRequest callback was not invoked for LastHttpContent for chunked POST", lastHttpContentProcessed.get());
        assertTrue("proxyToServerRequestSent callback was not invoked for chunked POST", requestSentCallbackInvoked.get());

        // test with a non-payload-bearing GET request.
        lastHttpContentProcessed.set(false);
        requestSentCallbackInvoked.set(false);

        getResponse("http://localhost:" + webServerPort + "/");
        Thread.sleep(500);

        assertTrue("proxyToServerRequest callback was not invoked for LastHttpContent for GET", lastHttpContentProcessed.get());
        assertTrue("proxyToServerRequestSent callback was not invoked for GET", requestSentCallbackInvoked.get());
    }

    private DefaultHttpClient getDefaultHttpClient() {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpHost proxy = new HttpHost("127.0.0.1", proxyServer.getListenAddress().getPort(), "http");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        return httpClient;
    }

    private org.apache.http.HttpResponse getResponse(final String url)
            throws Exception {
        final DefaultHttpClient http = getDefaultHttpClient();

        final HttpGet get = new HttpGet(url);

        return getHttpResponse(http, get);
    }

    private org.apache.http.HttpResponse postToServer(String url, int postSizeInBytes) throws Exception {
        DefaultHttpClient httpClient = getDefaultHttpClient();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < postSizeInBytes; i++) {
            sb.append('q');
        }

        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(sb.toString()));

        return getHttpResponse(httpClient, post);
    }

    private org.apache.http.HttpResponse getHttpResponse(DefaultHttpClient httpClient, HttpUriRequest get) throws IOException {
        final org.apache.http.HttpResponse hr = httpClient.execute(get);
        final HttpEntity responseEntity = hr.getEntity();
        EntityUtils.consume(responseEntity);
        httpClient.getConnectionManager().shutdown();
        return hr;
    }

    private long now() {
        // using nanoseconds instead of milliseconds, since it is extremely unlikely that any two callbacks would be invoked in the same nanosecond,
        // even on very fast hardware
        return System.nanoTime();
    }
}


text:
layout: post
title: New Site
categories: tech
author: Austen Lamacraft
---

My web pages are in serious need of an overhaul. In the past I've built my sites using [RapidWeaver](https://www.realmacsoftware.com/rapidweaver/), but it was never particularly future proof: something always needed updating.

Now I'm switching to [Jekyll](https://jekyllrb.com), which I used for the first time over the summer. Relative to a WYSIWYG editor it's a bit more work, but you feel like you know what's going on under the bonnet. There's a large ecosystem, lots of [themes](http://themes.jekyllrc.org), free hosting on [GitHub Pages](https://pages.github.com). The ease of writing in Markdown and rendering mathematics with [MathJax](https://www.mathjax.org) is wonderful.

$$
\int f(x)\,dx
$$

See?

It would be great to integrate this with [Symplectic](https://symplectic.admin.cam.ac.uk) and / or [ORCID](http://orcid.org) to get an automatically updated publication list. Let's see.

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.remote;

import com.google.devtools.remoteexecution.v1test.Digest;
import java.io.IOException;

/**
 * An exception to indicate cache misses.
 * TODO(olaola): have a class of checked RemoteCacheExceptions.
 */
public final class CacheNotFoundException extends IOException {
  private final Digest missingDigest;

  CacheNotFoundException(Digest missingDigest) {
    super("Missing digest: " + missingDigest);
    this.missingDigest = missingDigest;
  }

  public Digest getMissingDigest() {
    return missingDigest;
  }
}


text:
package com.zaita.aliyounes.gsbvc2017.network.apis;

/**
 * Created by Elie Ohanian on 8/29/2017.
 */

public class InvoiceNetworkCalls {
}


text:
package com.handywedge.workflow;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import com.handywedge.db.FWConnection;
import com.handywedge.db.FWConnectionManager;
import com.handywedge.db.FWPreparedStatement;
import com.handywedge.db.FWResultSet;
import com.handywedge.db.FWTransactional;

@ApplicationScoped
public class FWWFService {

  @Inject
  private FWConnectionManager cm;

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFStatus getStatus(String wfId) throws SQLException {
    FWConnection con = cm.getConnection();
    FWWFStatus status = null;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wfid.status_code AS status_code, sm.status_name AS status_name FROM fw_wf_id_management wfid"
            + " INNER JOIN fw_status_master AS sm ON wfid.status_code = sm.status"
            + " WHERE wfid.wf_id = ?")) {
      ps.setString(1, wfId);
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          status = new FWWFStatus();
          status.setStatus(rs.getString("status_code"));
          status.setStatusName(rs.getString("status_name"));
        }
        return status;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public int insertWFIDManagement(FWWFIDManagement wfIdManagement) throws SQLException {
    FWConnection con = cm.getConnection();
    try (FWPreparedStatement ps = con.prepareStatement(
        "INSERT INTO fw_wf_id_management (wf_id, status_code, create_date, update_date) VALUES(?, ?, ?, ?)")) {
      int idx = 1;
      ps.setString(idx++, wfIdManagement.getWfId());
      ps.setString(idx++, wfIdManagement.getStatusCode());
      ps.setTimestamp(idx++, wfIdManagement.getCreateDate());
      ps.setTimestamp(idx++, wfIdManagement.getUpdateDate());
      return ps.executeUpdate();
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public int updateWFIDManagement(FWWFIDManagement wfIdManagement) throws SQLException {
    FWConnection con = cm.getConnection();
    try (FWPreparedStatement ps = con.prepareStatement(
        "UPDATE fw_wf_id_management SET status_code = ?, update_date = ? WHERE wf_id = ?")) {
      int idx = 1;
      ps.setString(idx++, wfIdManagement.getStatusCode());
      ps.setTimestamp(idx++, wfIdManagement.getUpdateDate());
      ps.setString(idx++, wfIdManagement.getWfId());
      return ps.executeUpdate();
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFAction getRollbackAction(String wfId)
      throws SQLException {
    FWConnection con = cm.getConnection();
    FWWFAction action = null;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wfpm_pre.status_code AS pre_status_code, sm1.status_name AS pre_status_name, wfpm_pos.status_code AS post_status_code, sm2.status_name AS post_status_name FROM"
            + " (SELECT wf_id, max(wf_ser_no) AS wf_ser_no from fw_wf_progress_management WHERE wf_id = ? GROUP BY wf_id) AS st_base1"
            + " INNER JOIN (SELECT wf_id, wf_ser_no, row_number() over (order by wf_ser_no desc) AS odr from fw_wf_progress_management WHERE wf_id = ?) AS st_base2 ON st_base1.wf_id = st_base2.wf_id AND st_base2.odr = 2"
            + " INNER JOIN fw_wf_progress_management AS wfpm_pre ON st_base1.wf_id = wfpm_pre.wf_id AND st_base1.wf_ser_no = wfpm_pre.wf_ser_no"
            + " INNER JOIN fw_wf_progress_management AS wfpm_pos ON st_base2.wf_id = wfpm_pos.wf_id AND st_base2.wf_ser_no = wfpm_pos.wf_ser_no"
            + " INNER JOIN fw_status_master AS sm1 ON wfpm_pre.status_code = sm1.status"
            + " INNER JOIN fw_status_master AS sm2 ON wfpm_pos.status_code = sm2.status")) {
      int idx = 1;
      ps.setString(idx++, wfId);
      ps.setString(idx++, wfId);
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          action = new FWWFAction();
          action.setPreStatus(rs.getString("pre_status_code"));
          action.setPreStatusName(rs.getString("pre_status_name"));
          action.setPostStatus(rs.getString("post_status_code"));
          action.setPostStatusName(rs.getString("post_status_name"));
        }
        return action;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public List<FWWFAction> getActions(String status, String role) throws SQLException {
    FWConnection con = cm.getConnection();
    List<FWWFAction> actions = new ArrayList<>();
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wfrt.action_code AS action_code, wfrt.action AS action, wfrt.pre_status AS pre_status, sm1.status_name AS pre_status_name, wfrt.post_status AS post_status, sm2.status_name AS status_name, CASE WHEN wfrt2.pre_status IS NULL THEN 'true' ELSE 'false' END AS last_action_bool FROM fw_wf_rote AS wfrt"
            + " INNER JOIN fw_role_action AS ra ON wfrt.action_code = ra.action_code"
            + " LEFT JOIN fw_status_master AS sm1 ON wfrt.pre_status = sm1.status"
            + " LEFT JOIN fw_status_master AS sm2 ON wfrt.post_status = sm2.status"
            + " LEFT JOIN (SELECT pre_status FROM fw_wf_rote GROUP BY pre_status) AS wfrt2 ON wfrt.post_status = wfrt2.pre_status"
            + " WHERE wfrt.pre_status = ? AND ra.role = ?"
            + " ORDER BY wfrt.action_code ASC")) {
      int idx = 1;
      ps.setString(idx++, status);
      ps.setString(idx++, role);
      try (FWResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
          FWWFAction action = new FWWFAction();
          action.setActionCode(rs.getString("action_code"));
          action.setAction(rs.getString("action"));
          action.setPreStatus(rs.getString("pre_status"));
          action.setPreStatusName(rs.getString("pre_status_name"));
          action.setPostStatus(rs.getString("post_status"));
          action.setPostStatusName(rs.getString("status_name"));
          action.setLastAction(Boolean.valueOf(rs.getString("last_action_bool")));
          actions.add(action);
        }
        return actions;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFAction getAction(String actionCode, String role)
      throws SQLException {
    FWConnection con = cm.getConnection();
    FWWFAction action = null;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wfrt.action_code AS action_code, wfrt.action AS action, wfrt.pre_status AS pre_status, sm1.status_name AS pre_status_name, wfrt.post_status AS post_status, sm2.status_name AS status_name, CASE WHEN wfrt2.pre_status IS NULL THEN 'true' ELSE 'false' END AS last_action_bool FROM fw_wf_rote AS wfrt"
            + " INNER JOIN fw_role_action AS ra ON wfrt.action_code = ra.action_code"
            + " LEFT JOIN fw_status_master AS sm1 ON wfrt.pre_status = sm1.status"
            + " LEFT JOIN fw_status_master AS sm2 ON wfrt.post_status = sm2.status"
            + " LEFT JOIN (SELECT pre_status FROM fw_wf_rote GROUP BY pre_status) AS wfrt2 ON wfrt.post_status = wfrt2.pre_status"
            + " WHERE ra.role = ? AND wfrt.action_code = ?")) {
      int idx = 1;
      ps.setString(idx++, role);
      ps.setString(idx++, actionCode);
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          action = new FWWFAction();
          action.setActionCode(rs.getString("action_code"));
          action.setAction(rs.getString("action"));
          action.setPreStatus(rs.getString("pre_status"));
          action.setPreStatusName(rs.getString("pre_status_name"));
          action.setPostStatus(rs.getString("post_status"));
          action.setPostStatusName(rs.getString("status_name"));
          action.setLastAction(Boolean.valueOf(rs.getString("last_action_bool")));
        }
        return action;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFAction getAction(String actionCode, String status, String role)
      throws SQLException {
    FWConnection con = cm.getConnection();
    FWWFAction action = null;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wfrt.action_code AS action_code, wfrt.action AS action, wfrt.pre_status AS pre_status, sm1.status_name AS pre_status_name, wfrt.post_status AS post_status, sm2.status_name AS status_name, CASE WHEN wfrt2.pre_status IS NULL THEN 'true' ELSE 'false' END AS last_action_bool FROM fw_wf_rote AS wfrt"
            + " INNER JOIN fw_role_action AS ra ON wfrt.action_code = ra.action_code"
            + " LEFT JOIN fw_status_master AS sm1 ON wfrt.pre_status = sm1.status"
            + " LEFT JOIN fw_status_master AS sm2 ON wfrt.post_status = sm2.status"
            + " LEFT JOIN (SELECT pre_status FROM fw_wf_rote GROUP BY pre_status) AS wfrt2 ON wfrt.post_status = wfrt2.pre_status"
            + " WHERE wfrt.pre_status = ? AND ra.role = ? AND wfrt.action_code = ?")) {
      int idx = 1;
      ps.setString(idx++, status);
      ps.setString(idx++, role);
      ps.setString(idx++, actionCode);
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          action = new FWWFAction();
          action.setActionCode(rs.getString("action_code"));
          action.setAction(rs.getString("action"));
          action.setPreStatus(rs.getString("pre_status"));
          action.setPreStatusName(rs.getString("pre_status_name"));
          action.setPostStatus(rs.getString("post_status"));
          action.setPostStatusName(rs.getString("status_name"));
          action.setLastAction(Boolean.valueOf(rs.getString("last_action_bool")));
        }
        return action;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFLog insertWFLog(FWWFLog wfLog) throws SQLException {
    FWConnection con = cm.getConnection();
    // 履歴最大値取得
    int wfSerNo = 1;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT MAX(wf_ser_no) AS max_wf_ser_no FROM fw_wf_log"
            + " WHERE wf_id = ?")) {
      ps.setString(1, wfLog.getWfId());
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          wfSerNo = rs.getInt("max_wf_ser_no") + 1;
        }
      }
    }
    // 履歴登録処理
    try (FWPreparedStatement ps = con.prepareStatement(
        "INSERT INTO fw_wf_log (wf_id, wf_ser_no, action_date, action_owner, action_code, status_code, description) VALUES(?, ?, ?, ?, ?, ?, ?)")) {
      int idx = 1;
      ps.setString(idx++, wfLog.getWfId());
      ps.setInt(idx++, wfSerNo);
      ps.setTimestamp(idx++, wfLog.getActionDate());
      ps.setString(idx++, wfLog.getActionOwner());
      ps.setString(idx++, wfLog.getActionCode());
      ps.setString(idx++, wfLog.getStatusCode());
      ps.setString(idx++, wfLog.getDescription());
      ps.executeUpdate();
    }
    // 最新ログ取得
    return getWFLog(wfLog.getWfId(), wfSerNo);
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public FWWFLog getWFLog(String wfId, int wfSerNo) throws SQLException {
    FWConnection con = cm.getConnection();
    FWWFLog wfLog = null;
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wflg.wf_id AS wf_id, wflg.wf_ser_no AS wf_ser_no, wflg.action_date AS action_date, wflg.action_owner AS action_owner, ur.name AS action_owner_name, wflg.action_code AS action_code, wfrt.action AS action, wflg.status_code AS status_code, sm.status_name AS status_name, wflg.description AS description FROM fw_wf_log AS wflg"
            + " LEFT JOIN fw_user AS ur ON wflg.action_owner = ur.id"
            + " LEFT JOIN fw_wf_rote AS wfrt ON wflg.action_code = wfrt.action_code"
            + " LEFT JOIN fw_status_master AS sm ON wflg.status_code = sm.status"
            + " WHERE wflg.wf_id = ? AND wflg.wf_ser_no = ?")) {
      int idx = 1;
      ps.setString(idx++, wfId);
      ps.setInt(idx++, wfSerNo);
      try (FWResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          wfLog = new FWWFLog();
          wfLog.setWfId(rs.getString("wf_id"));
          wfLog.setWfSerNo(rs.getInt("wf_ser_no"));
          wfLog.setActionDate(rs.getTimestamp("action_date"));
          wfLog.setActionOwner(rs.getString("action_owner"));
          wfLog.setActionOwnerName(rs.getString("action_owner_name"));
          wfLog.setActionCode(rs.getString("action_code"));
          wfLog.setActionName(rs.getString("action"));
          wfLog.setStatusCode(rs.getString("status_code"));
          wfLog.setStatusName(rs.getString("status_name"));
          wfLog.setDescription(rs.getString("description"));
        }
        return wfLog;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public List<FWWFLog> getWFLogs(String wfId) throws SQLException {
    FWConnection con = cm.getConnection();
    List<FWWFLog> logs = new ArrayList<>();
    try (FWPreparedStatement ps = con.prepareStatement(
        "SELECT wflg.wf_id AS wf_id, wflg.wf_ser_no AS wf_ser_no, wflg.action_date AS action_date, wflg.action_owner AS action_owner, ur.name AS action_owner_name, wflg.action_code AS action_code, wfrt.action AS action, wflg.status_code AS status_code, sm.status_name AS status_name, wflg.description AS description FROM fw_wf_log AS wflg"
            + " LEFT JOIN fw_user AS ur ON wflg.action_owner = ur.id"
            + " LEFT JOIN fw_wf_rote AS wfrt ON wflg.action_code = wfrt.action_code"
            + " LEFT JOIN fw_status_master AS sm ON wflg.status_code = sm.status"
            + " WHERE wflg.wf_id = ?"
            + " ORDER BY wflg.wf_ser_no ASC")) {
      ps.setString(1, wfId);
      try (FWResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
          FWWFLog wfLog = new FWWFLog();
          wfLog.setWfId(rs.getString("wf_id"));
          wfLog.setWfSerNo(rs.getInt("wf_ser_no"));
          wfLog.setActionDate(rs.getTimestamp("action_date"));
          wfLog.setActionOwner(rs.getString("action_owner"));
          wfLog.setActionOwnerName(rs.getString("action_owner_name"));
          wfLog.setActionCode(rs.getString("action_code"));
          wfLog.setActionName(rs.getString("action"));
          wfLog.setStatusCode(rs.getString("status_code"));
          wfLog.setStatusName(rs.getString("status_name"));
          wfLog.setDescription(rs.getString("description"));
          logs.add(wfLog);
        }
        return logs;
      }
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public int insertWFProgressManagement(FWWFProgressManagement wfProgressManagement) throws SQLException {
    FWConnection con = cm.getConnection();
    try (FWPreparedStatement ps = con.prepareStatement(
        "INSERT INTO fw_wf_progress_management (wf_id, wf_ser_no, action_code, status_code, create_date) VALUES(?, ?, ?, ?, ?)")) {
      int idx = 1;
      ps.setString(idx++, wfProgressManagement.getWfId());
      ps.setInt(idx++, wfProgressManagement.getWfSerNo());
      ps.setString(idx++, wfProgressManagement.getActionCode());
      ps.setString(idx++, wfProgressManagement.getStatusCode());
      ps.setTimestamp(idx++, wfProgressManagement.getCreateDate());
      return ps.executeUpdate();
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public int deleteLastWFProgressManagement(String wfId) throws SQLException {
    FWConnection con = cm.getConnection();
    // 進捗管理TBLの最終レコード削除
    try (FWPreparedStatement ps = con.prepareStatement(
        "DELETE FROM fw_wf_progress_management"
            + " WHERE wf_id = ? AND wf_ser_no = (SELECT max(wf_ser_no) from fw_wf_progress_management WHERE wf_id = ?)")) {
      int idx = 1;
      ps.setString(idx++, wfId);
      ps.setString(idx++, wfId);
      return ps.executeUpdate();
    }
  }

  @FWTransactional(dataSourceName = "jdbc/fw")
  public int deleteWFProgressManagement(String wfId) throws SQLException {
    FWConnection con = cm.getConnection();
    // 進捗管理TBLの全レコード削除
    try (FWPreparedStatement ps = con.prepareStatement(
        "DELETE FROM fw_wf_progress_management"
            + " WHERE wf_id = ?")) {
      ps.setString(1, wfId);
      return ps.executeUpdate();
    }
  }
}


text:
#include "local_mapper_viewer.h"
#include "qevent.h"
#include <cstring>
#include "gl_helpers/opengl_primitives.h"

namespace fps_mapper{
  using namespace std;
  using namespace Eigen;
  using namespace GLHelpers;

  LocalMapperViewer::LocalMapperViewer(LocalMapTrigger* t) {
    _trigger = t;
    _tracker = t->tracker();
    _trigger->setLocalMaps(&nodes);
    _trigger->setLocalMapsRelations(&relations);
    _modelTainted = true;
    _local_map_trajectory = _trigger->nodes();
  }

  void LocalMapperViewer::draw(){
    if (!_tracker->currentModel() || !_tracker->referenceModel() )
      return;

    glPushAttrib(GL_COLOR);
    glPushMatrix();
    glMultMatrix( _tracker->globalT() );

    glPushMatrix();
    glScalef(0.2, 0.2, 0.2);
    GLHelpers::drawReferenceSystem();
    glPopMatrix();

   /// draw the current after applying the epsilon T from aligner
    glPushMatrix();
    glMultMatrix(_tracker->aligner().T().inverse() );
    if (_tracker->currentModel()){
      glColor3f(0.3, 0.3, 0.8);
      _tracker->currentModel()->draw();
    }
    glPopMatrix();

    glPushMatrix();
    glMultMatrix(_tracker->lastCamera()->offset());
    float pyrH = 0.1;
    float pyrW = 0.05;
    drawPyramidWireframe(/*pyrH = */ 0.1, /*pyrW = */ 0.05);
    glPopMatrix();

    /// draw the reference
    if (_tracker->referenceModel()){
      glColor3f(0.5, 0.5, 0.5);
      _tracker->referenceModel()->draw();
    }

    glPopMatrix();
    glPopAttrib();

    TrajectoryViewer::draw();

    glPushAttrib(GL_COLOR);
    if (_local_map_trajectory) {
      for (MapNodeList::iterator it = _local_map_trajectory->begin(); it!=_local_map_trajectory->end();
	   it++)
	(*it)->draw();
    }
    glPopAttrib();
  }

}


text:
package org.flywaydb.core.internal.sqlscript;

import lombok.Getter;
import org.flywaydb.core.internal.jdbc.JdbcTemplate;
import org.flywaydb.core.internal.jdbc.Results;

/**
 * A sql statement from a script that can be executed at once against a database.
 */
public class ParsedSqlStatement implements SqlStatement {
    @Getter
    private final int pos;
    @Getter
    private final int line;
    @Getter
    private final int col;
    @Getter(onMethod = @__(@Override))
    private final String sql;

    /**
     * The delimiter of the statement.
     */
    private final Delimiter delimiter;

    private final boolean canExecuteInTransaction;

    public ParsedSqlStatement(int pos, int line, int col, String sql, Delimiter delimiter,
                              boolean canExecuteInTransaction

                             ) {
        this.pos = pos;
        this.line = line;
        this.col = col;
        this.sql = sql;
        this.delimiter = delimiter;
        this.canExecuteInTransaction = canExecuteInTransaction;

    }

    @Override
    public final int getLineNumber() {
        return line;
    }

    @Override
    public String getDelimiter() {
        return delimiter.toString();
    }

    @Override
    public boolean canExecuteInTransaction() {
        return canExecuteInTransaction;
    }

    @Override
    public Results execute(JdbcTemplate jdbcTemplate

                          ) {
        return jdbcTemplate.executeStatement(sql);
    }
}


text:
<?php

namespace tontineBundle\Repository;

use Doctrine\ORM\QueryBuilder;

/**
 * BaseRepository
 *
 */
class BaseRepository extends \Doctrine\ORM\EntityRepository
{
    private $relationsToLoad = array();

    /**
     * @param mixed $relations
     */
    public function with($relations)
    {
        if (is_string($relations)) {
            $relations = func_get_args();
        }

        foreach ($relations as $relation) {

            if ($this->_class->hasAssociation($relation)) {

                $this->relationsToLoad[] = $relation;
            }
        }

        return $this;
    }

    public function __call($method, $args)
    {
        if (strpos($method, 'with') === 0) {

            $relation = lcfirst(substr($method, '4'));
            return $this->with($relation);
        }
    }

    /**
     * Find entity by id
     *
     * @param mixed $id
     *
     * @return null|object
     */
    public function find($id)
    {
        if (count($this->relationsToLoad) == 0) {
            return parent::find($id);
        }

        $queryBuilder = $this->getQueryBuilder();

        $this->applyRelations($queryBuilder);

        $queryBuilder->andWhere($this->getPropertyName('id') . ' = :id');
        $queryBuilder->setParameter('id', intval($id));

        $this->resetRelationToLoad();

        return $queryBuilder->getQuery()->getOneOrNullResult();
    }

    /**
     * Find all entities
     *
     * @return array
     */
    public function findAll()
    {
        if (count($this->relationsToLoad) == 0) {
            return parent::findAll();
        }

        $queryBuilder = $this->getQueryBuilder();

        $this->applyRelations($queryBuilder);

        $this->resetRelationToLoad();

        return $queryBuilder->getQuery()->getResult();
    }

    /**
     * Find one entity by $criteria
     *
     * @param array $criteria
     *
     * @return null|object
     */
    public function findOneBy(array $criteria = array())
    {
        if (count($this->relationsToLoad) == 0) {
            return parent::findOneBy($criteria);
        }

        $queryBuilder = $this->getQueryBuilder();

        $this->applyRelations($queryBuilder);
        $this->applyCriteria($queryBuilder, $criteria);

        $this->resetRelationToLoad();

        return $queryBuilder->getQuery()->getOneOrNullResult();
    }

    /**
     * @param array $criteria
     * @param array $orderBy
     * @param int   $limit
     * @param int   $offset
     *
     * @return array
     */
    public function findBy(array $criteria = array(), array $orderBy = null, $limit = null, $offset = null)
    {
        /*if (count($this->relationsToLoad) == 0) {
            return parent::findBy($criteria, $orderBy, $limit, $offset);
        }*/

        $queryBuilder = $this->getQueryBuilder();

        $this->applyRelations($queryBuilder);
        $this->applyCriteria($queryBuilder, $criteria);
        $orderBy != null and $this->applyOrderBy($queryBuilder, $orderBy);

        if (null !== $limit) {
            $queryBuilder->setMaxResults($limit);
        }

        if (null !== $offset) {
            $queryBuilder->setFirstResult($offset);
        }

        $this->resetRelationToLoad();

        return $queryBuilder->getQuery()->getResult();
    }

    /**
     * @param  array  $criteria
     *
     * @return integer
     */
    public function count(array $criteria = array())
    {
        $queryBuilder = $this->getQueryBuilder();
        $this->applyCriteria($queryBuilder, $criteria);

        $queryBuilder->select('COUNT('. $this->getAlias() .')');

        return $queryBuilder
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function sum($field, array $criteria = array())
    {
        $queryBuilder = $this->getQueryBuilder();
        $this->applyCriteria($queryBuilder, $criteria);

        $queryBuilder->select(sprintf("SUM(%s.%s)", $this->getAlias(), $field));

        return $queryBuilder
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * @return QueryBuilder
     */
    protected function getQueryBuilder()
    {
        return $this->createQueryBuilder($this->getAlias());
    }

    /**
     * @param QueryBuilder
     */
    protected function applyRelations(QueryBuilder $queryBuilder)
    {
        foreach ($this->relationsToLoad as $relation) {
            $queryBuilder->leftJoin($this->getPropertyName($relation), $relation);
            $queryBuilder->addSelect($relation);
        }
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param array        $criteria
     */
    protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = array())
    {
        foreach ($criteria as $property => $value) {

            if (is_integer($property) && is_array($value) && count($value) == 3) {

                list($property, $operator, $val) = $value;
                $name = $this->getPropertyName($property);

                switch ($operator) {

                    case 'like':
                        $parameter = str_replace('.', '_', $property);
                        $queryBuilder
                            ->andWhere(sprintf("%s LIKE :%s", $name, $parameter))
                            ->setParameter($parameter, '%'. $val .'%');
                        break;
                    default:
                        $parameter = str_replace('.', '_', $property);
                        $queryBuilder
                            ->andWhere(sprintf("%s %s :%s", $name, $operator, $parameter))
                            ->setParameter($parameter, $val);
                        break;
                }

            } else {

                $name = $this->getPropertyName($property);

                if ($value === null) {

                    $queryBuilder->andWhere($queryBuilder->expr()->isNull($name));

                } elseif (is_array($value)) {

                    $queryBuilder->andWhere($queryBuilder->expr()->in($name, $value));

                } elseif ($value !== '') {

                    $parameter = str_replace('.', '_', $property);
                    $queryBuilder
                        ->andWhere($queryBuilder->expr()->eq($name, ':'.$parameter))
                        ->setParameter($parameter, $value)
                    ;
                }
            }
        }
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param array        $orderBy
     */
    protected function applyOrderBy(QueryBuilder $queryBuilder, array $orderBy = array())
    {
        foreach ($orderBy as $property => $order) {

            if (!empty($order)) {

                $queryBuilder->addOrderBy($this->getPropertyName($property), $order);
            }
        }
    }

    /**
     * @param string $name
     *
     * @return string
     */
    protected function getPropertyName($name)
    {
        if (strpos($name, '.') === false) {
            return $this->getAlias().'.'.$name;
        }

        return $name;
    }

    /**
     * @return string
     */
    protected function getAlias()
    {
        return $this->getEntityName();
    }

    protected function resetRelationToLoad()
    {
        $this->relationsToLoad = array();
    }
}


text:
package com.amazonaws.services.autoscalingplans.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.autoscalingplans.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * GetScalingPlanResourceForecastDataRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetScalingPlanResourceForecastDataRequestMarshaller {

    private static final MarshallingInfo<String> SCALINGPLANNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ScalingPlanName").build();
    private static final MarshallingInfo<Long> SCALINGPLANVERSION_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ScalingPlanVersion").build();
    private static final MarshallingInfo<String> SERVICENAMESPACE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServiceNamespace").build();
    private static final MarshallingInfo<String> RESOURCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceId").build();
    private static final MarshallingInfo<String> SCALABLEDIMENSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ScalableDimension").build();
    private static final MarshallingInfo<String> FORECASTDATATYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ForecastDataType").build();
    private static final MarshallingInfo<java.util.Date> STARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StartTime").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<java.util.Date> ENDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EndTime").timestampFormat("unixTimestamp").build();

    private static final GetScalingPlanResourceForecastDataRequestMarshaller instance = new GetScalingPlanResourceForecastDataRequestMarshaller();

    public static GetScalingPlanResourceForecastDataRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(GetScalingPlanResourceForecastDataRequest getScalingPlanResourceForecastDataRequest, ProtocolMarshaller protocolMarshaller) {

        if (getScalingPlanResourceForecastDataRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getScalingPlanName(), SCALINGPLANNAME_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getScalingPlanVersion(), SCALINGPLANVERSION_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getServiceNamespace(), SERVICENAMESPACE_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getResourceId(), RESOURCEID_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getScalableDimension(), SCALABLEDIMENSION_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getForecastDataType(), FORECASTDATATYPE_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(getScalingPlanResourceForecastDataRequest.getEndTime(), ENDTIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
@interface HLSubjectGroup : NSObject {

	NSMutableDictionary* _subjectDictionary;
	//@property (nonatomic, retain) NSMutableDictionary* subjectDictionary;
	//@synthesize subjectDictionary = _subjectDictionary;

}

-(NSEnumerator*)subjectEnumerator;

-(int)count;

-(bool)containsUsername:(NSString*)username;
-(HLSubject*)subjectForUsername:(NSString*)username;

-(void)addSubject:(HLSubject*)subject;

-(void)removeSubjectWithUsername:(NSString*)username;
-(void)removeSubject:(HLSubject*)subject;

@end


text:
require "spec_helper"

RSpec.describe "Case: La Poste typos", type: :feature do
  %w[
    john.doe@lapost.net
    john.doe@laposte.com
    john.doe@laposte.fr
    john.doe@laposte.ne
    john.doe@laposte.ner
    john.doe@lapostr.net
    john.doe@lapostz.net
    john.doe@lapote.net
    john.doe@lappste.net
  ].each do |kase|
    it "proposes a hint for `#{kase}`" do
      response = EmailInquire.validate(kase)
      expect(response).to have_attributes({
        replacement: "john.doe@laposte.net",
        status: :hint,
      })
    end
  end
end


text:
namespace blink {

class V8TestInterfaceGarbageCollected {
public:
    static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*);
    static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
    static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*);
    static TestInterfaceGarbageCollected* toImpl(v8::Local<v8::Object> object)
    {
        return blink::toScriptWrappable(object)->toImpl<TestInterfaceGarbageCollected>();
    }
    static TestInterfaceGarbageCollected* toImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
    static const WrapperTypeInfo wrapperTypeInfo;
    static void refObject(ScriptWrappable*);
    static void derefObject(ScriptWrappable*);
    template<typename VisitorDispatcher>
    static void trace(VisitorDispatcher visitor, ScriptWrappable* scriptWrappable)
    {
        visitor->trace(scriptWrappable->toImpl<TestInterfaceGarbageCollected>());
    }
    static void constructorCallback(const v8::FunctionCallbackInfo<v8::Value>&);
    static const int eventListenerCacheIndex = v8DefaultWrapperInternalFieldCount + 0;
    static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 1;
    static void installConditionallyEnabledProperties(v8::Local<v8::Object>, v8::Isolate*) { }
    static void installConditionallyEnabledMethods(v8::Local<v8::Object>, v8::Isolate*) { }
};

} // namespace blink

#endif // V8TestInterfaceGarbageCollected_h


text:
from __future__ import unicode_literals

import time
import json
from io import BytesIO

import pytest
import tabun_api as api
from tabun_api.compat import text, binary

from testutil import UserTest, load_file, form_intercept, set_mock, user, assert_data

@pytest.mark.parametrize("url,data_file,rev", [
    ('/blog/132085.html', '132085_comments.json', False),
    (None, 'comments.json', True)
])
def test_get_comments(user, url, data_file, rev):
    comments_data = json.loads(load_file(data_file, template=False).decode('utf-8'))
    if url:
        comments = user.get_comments(url)
    else:
        comments = user.get_comments()

    assert list(sorted(comments.keys(), reverse=rev)) == [x['comment_id'] for x in comments_data]

    for data in comments_data:
        comment = comments[data['comment_id']]
        assert data['comment_id'] == comment.comment_id
        assert_data(comment, data)

def test_get_comments_types_ok(user):
    comments = user.get_comments()
    comments.update(user.get_comments('/blog/132085.html'))
    for comment_id, comment in comments.items():
        assert isinstance(comment_id, int)
        assert comment.blog is None or isinstance(comment.blog, text)
        if comment.deleted:
            assert comment.author is None
            assert comment.raw_body is None
            assert comment.vote_total is None
        else:
            assert isinstance(comment.author, text)
            assert isinstance(comment.raw_body, text)
            assert isinstance(comment.vote_total, int)

def test_add_comment_ok(form_intercept, set_mock, user):
    set_mock({'/blog/ajaxaddcomment/': (None, {'data': b'{"sCommentId": 1, "sMsgTitle": "", "sMsg": "", "bStateError": false}'})})
    @form_intercept('/blog/ajaxaddcomment/')
    def add_comment(data, headers):
        assert headers.get('content-type', '').startswith(b'multipart/form-data; boundary=-')

        assert data.get('security_ls_key') == [b'0123456789abcdef0123456789abcdef']
        assert data.get('cmt_target_id') in ([b'1'], [b'2'])
        assert data.get('comment_text') == ['тест'.encode('utf-8')]
        assert data.get('reply') == ([b'0'] if data['cmt_target_id'][0] == b'1' else [b'1'])

    assert user.comment(1, 'тест') == 1
    assert user.comment(1, 'тест', reply=0) == 1

def test_add_comment_fail(set_mock, user):
    err = "Текст комментария должен быть от 2 до 3000 символов и не содержать разного рода каку"
    set_mock({'/blog/ajaxaddcomment/': (None, {'data': ('{"sMsgTitle": "Ошибка", "sMsg": "%s", "bStateError": true}' % err).encode('utf-8')})})
    with pytest.raises(api.TabunResultError) as excinfo:
        user.comment(1, '')
    assert excinfo.value.message == err

def test_edit_comment_ok(form_intercept, set_mock, user):
    set_mock({'/ajax/comment/edit/': (
        None,
        {'data': '{"newText": "тест2", "notice": null, "sMsgTitle": null, "sMsg": "Комментарий изменён", "bStateError": false}'.encode('utf-8')},
    )})

    @form_intercept('/ajax/comment/edit/')
    def edit_comment(data, headers):
        assert headers.get('content-type', '').startswith(b'multipart/form-data; boundary=-')

        assert data.get('security_ls_key') == [b'0123456789abcdef0123456789abcdef']
        assert data.get('idComment') == [b'777']
        assert data.get('newText') == ['тест2'.encode('utf-8')]
        assert data.get('setLock') == [b'0']

    assert user.edit_comment(777, 'тест2') == ('тест2', 'Комментарий изменён', None)

def test_edit_comment_error(form_intercept, set_mock, user):
    set_mock({'/ajax/comment/edit/': (
        None,
        {'data': '{"newText": "тест", "notice": null, "sMsgTitle": "Ошибка доступа", "sMsg": "Вы не можете изменять чужой комментарий, срок редактирования которого истёк", "bStateError": true}'.encode('utf-8')},
    )})

    @form_intercept('/ajax/comment/edit/')
    def edit_comment(data, headers):
        assert headers.get('content-type', '').startswith(b'multipart/form-data; boundary=-')

        assert data.get('security_ls_key') == [b'0123456789abcdef0123456789abcdef']
        assert data.get('idComment') == [b'777']
        assert data.get('newText') == ['тест2'.encode('utf-8')]
        assert data.get('setLock') == [b'0']

    with pytest.raises(api.TabunResultError) as excinfo:
        user.edit_comment(777, 'тест2')

    assert excinfo.value.message == 'Вы не можете изменять чужой комментарий, срок редактирования которого истёк'
    assert excinfo.value.data.get('newText') == 'тест'

# Тесты hashsum гарантируют обратную совместимость, так что лучше их не трогать

def test_comments_hashsum_default(user):
    c = list(sorted(user.get_comments().items()))
    assert c[0][0] == 9445361
    assert c[0][1].hashsum() == '21e86981a1eb1110c55f8f59c6b7e684'
    assert c[1][0] == 9445595
    assert c[1][1].hashsum() == 'c8c7a9621120fc5f9f1f10caa2941ec0'

def test_comments_hashsum_part(user):
    c = list(sorted(user.get_comments().items()))
    assert c[0][0] == 9445361
    assert c[0][1].hashsum(('body',)) == '5768f420c77973975c835ba44e8bd285'
    assert c[1][0] == 9445595
    assert c[1][1].hashsum(('body',)) == 'be8d648dd8bb53a957b0bd861dfb548f'

    # Потому что смешивать \n и \r\n в файлах так же, как и на сайте, очень геморройно
    c[1][1].raw_body = c[1][1].raw_body.replace('\n', '\r\n')
    assert c[1][1].hashsum(('body',)) == '10b2ae8cd48a8e9bc86bf5138ebfa18d'


text:
<Record>
<Term>Female Orgasmic Disorder</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Female Non-Neoplastic Reproductive System Disorder</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Disorder by Site/Reproductive System Disorder/Non-Neoplastic Reproductive System Disorder/Female Non-Neoplastic Reproductive System Disorder/Female Orgasmic Disorder</ClassificationPath>
<BroaderTerm>Female Non-Neoplastic Reproductive System Disorder</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Female Orgasmic Disorder</BroaderTerm>
<BroaderTerm>Disorder by Site</BroaderTerm>
<BroaderTerm>Non-Neoplastic Reproductive System Disorder</BroaderTerm>
<BroaderTerm>Reproductive System Disorder</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<Synonym>Female Orgasmic Disorder</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
function complainEmails()
{
    var email = document.getElementById('email').value;
    var re_email = document.getElementById('re_email').value;
    return (email === re_email);
}

function showErrMsg()
{
    var errBoxDisplay = 'block';
    var errBox = document.getElementById('divergent_email');
    errBox.style.display = errBoxDisplay;
}

function submitHandler()
{
    if (this.status && complainEmails())
    {
        this.submit();
    }
    else if (this.status)
    {
        showErrMsg();
    }
    return false;
}

function onloadHandler()
{
    var fields =
    {
        'email': 'email',
        're_email': 'email',
        'first_name': 'text',
        'last_name': 'text',
        'password': 'pass'
    };

    var val = new ValidateForm(fields);

    var form = document.getElementById('reg_form');
    form.__proto__ = val;
    form.onsubmit = submitHandler;
}

window.onload = onloadHandler;


text:
/**
 * @module UI
 */
/// <reference path="./uiPlugin.ts"/>
module UI {

  export var hawtioFilter = _module.directive("hawtioFilter", [() => {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      templateUrl: UI.templatePath + 'filter.html',
      scope: {
        placeholder: '@',
        cssClass: '@',
        saveAs: '@?',
        ngModel: '='
      },
      controller: ["$scope", "localStorage", "$location", "$element", ($scope, localStorage, $location, $element) => {

        $scope.getClass = () => {
          var answer = [];
          if (!Core.isBlank($scope.cssClass)) {
            answer.push($scope.cssClass);
          }
          if (!Core.isBlank($scope.ngModel)) {
            answer.push("has-text");
          }
          return answer.join(' ');
        };

        // sync with local storage and the location bar, maybe could refactor this into a helper function
        if (!Core.isBlank($scope.saveAs)) {
          if ($scope.saveAs in localStorage) {
            var val = localStorage[$scope.saveAs];
            if (!Core.isBlank(val)) {
              $scope.ngModel = val;
            } else {
              $scope.ngModel = '';
            }
          } else {
            $scope.ngModel = '';
          }
          /*
           // input loses focus when we muck with the search, at least on firefox
          var search = $location.search();
          if ($scope.saveAs in search) {
            $scope.ngModel = search[$scope.saveAs];
          }
          */

          var updateFunc = () => {
            localStorage[$scope.saveAs] = $scope.ngModel;
            // input loses focus when we do this
            //$location.search($scope.saveAs, $scope.ngModel);
          };
          $scope.$watch('ngModel', updateFunc);
        }
      }]
    };
  }]);

}


text:
import unittest

from metrics import timeline_interaction_record
from telemetry.core.timeline import async_slice

class ParseTests(unittest.TestCase):
  def testParse(self):
    self.assertTrue(timeline_interaction_record.IsTimelineInteractionRecord(
        'Interaction.Foo'))
    self.assertTrue(timeline_interaction_record.IsTimelineInteractionRecord(
        'Interaction.Foo/Bar'))
    self.assertFalse(timeline_interaction_record.IsTimelineInteractionRecord(
        'SomethingRandom'))

  def CreateRecord(self, event_name):
    s = async_slice.AsyncSlice(
      'cat', event_name,
      timestamp=1, duration=2)
    return timeline_interaction_record.TimelineInteractionRecord.FromEvent(s)

  def testCreate(self):
    r = self.CreateRecord('Interaction.LogicalName')
    self.assertEquals('LogicalName', r.logical_name)
    self.assertEquals(False, r.is_smooth)
    self.assertEquals(False, r.is_loading_resources)

    r = self.CreateRecord('Interaction.LogicalName/is_smooth')
    self.assertEquals('LogicalName', r.logical_name)
    self.assertEquals(True, r.is_smooth)
    self.assertEquals(False, r.is_loading_resources)

    r = self.CreateRecord('Interaction.LogicalNameWith/Slash/is_smooth')
    self.assertEquals('LogicalNameWith/Slash', r.logical_name)
    self.assertEquals(True, r.is_smooth)
    self.assertEquals(False, r.is_loading_resources)

    r = self.CreateRecord(
        'Interaction.LogicalNameWith/Slash/is_smooth,is_loading_resources')
    self.assertEquals('LogicalNameWith/Slash', r.logical_name)
    self.assertEquals(True, r.is_smooth)
    self.assertEquals(True, r.is_loading_resources)


text:
@interface ZBFireworkViewController : UIViewController
{

}

@end


text:
<?php
namespace FormAl\Elements;

use FormAl\ElementBase;
use FormAl\Utilities\HtmlBuilder;

/**
 * Class Button
 *
 * @package FormAl\Elements
 */
class Button extends ElementBase
{
    /** @var string */
    private $labelname = "";
    /** @var string */
    private $location = "";
    /** @var string */
    public $text = "";

    /**
     * @param string $text
     *
     * @return $this
     */
    public function label($text)
    {
        $this->labelname = $text;

        return $this;
    }

    /**
     * @return string
     */
    public function getLabel()
    {
        return $this->labelname;
    }

    /**
     * @param string $location
     *
     * @return $this
     */
    public function location($location)
    {
        $this->location = $location;

        return $this;
    }

    /**
     * @param string $text
     */
    public function setText($text)
    {
        $this->text = $text;
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function render()
    {
        $element = new HtmlBuilder('a.form-control.btn.btn-default');
        $element->attr('name', md5($this->getName()))
            ->attr('href', $this->location)
            ->attr('style', "max-width: 400px;")
            ->addText($this->text);

        if ($this->isDisabled()) {
            $element->attr('disabled', true);
        }

        return $element->render();
    }
}


text:
/* automatically generated by rust-bindgen */

pub const FPS_UPPER_LIMIT: u32 = 200;
pub const FPS_LOWER_LIMIT: u32 = 1;
pub const FPS_DEFAULT: u32 = 30;
pub type __uint32_t = libc::c_uint;
pub type Uint32 = u32;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct FPSmanager {
    pub framecount: Uint32,
    pub rateticks: f32,
    pub baseticks: Uint32,
    pub lastticks: Uint32,
    pub rate: Uint32,
}
#[test]
fn bindgen_test_layout_FPSmanager() {
    assert_eq!(
        ::core::mem::size_of::<FPSmanager>(),
        20usize,
        concat!("Size of: ", stringify!(FPSmanager))
    );
    assert_eq!(
        ::core::mem::align_of::<FPSmanager>(),
        4usize,
        concat!("Alignment of ", stringify!(FPSmanager))
    );
    assert_eq!(
        unsafe { &(*(::core::ptr::null::<FPSmanager>())).framecount as *const _ as usize },
        0usize,
        concat!(
            "Offset of field: ",
            stringify!(FPSmanager),
            "::",
            stringify!(framecount)
        )
    );
    assert_eq!(
        unsafe { &(*(::core::ptr::null::<FPSmanager>())).rateticks as *const _ as usize },
        4usize,
        concat!(
            "Offset of field: ",
            stringify!(FPSmanager),
            "::",
            stringify!(rateticks)
        )
    );
    assert_eq!(
        unsafe { &(*(::core::ptr::null::<FPSmanager>())).baseticks as *const _ as usize },
        8usize,
        concat!(
            "Offset of field: ",
            stringify!(FPSmanager),
            "::",
            stringify!(baseticks)
        )
    );
    assert_eq!(
        unsafe { &(*(::core::ptr::null::<FPSmanager>())).lastticks as *const _ as usize },
        12usize,
        concat!(
            "Offset of field: ",
            stringify!(FPSmanager),
            "::",
            stringify!(lastticks)
        )
    );
    assert_eq!(
        unsafe { &(*(::core::ptr::null::<FPSmanager>())).rate as *const _ as usize },
        16usize,
        concat!(
            "Offset of field: ",
            stringify!(FPSmanager),
            "::",
            stringify!(rate)
        )
    );
}
extern "C" {
    pub fn SDL_initFramerate(manager: *mut FPSmanager);
}
extern "C" {
    pub fn SDL_setFramerate(manager: *mut FPSmanager, rate: Uint32) -> libc::c_int;
}
extern "C" {
    pub fn SDL_getFramerate(manager: *mut FPSmanager) -> libc::c_int;
}
extern "C" {
    pub fn SDL_getFramecount(manager: *mut FPSmanager) -> libc::c_int;
}
extern "C" {
    pub fn SDL_framerateDelay(manager: *mut FPSmanager) -> Uint32;
}


text:
<?php

namespace ONGR\ElasticsearchDSL\Aggregation;

/**
 * Class representing Avg Aggregation.
 */
class AvgAggregation extends StatsAggregation
{
    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'avg';
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>tesseract: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

tesseract
    4.00.00dev

file_in_zip_read_info_s Member List

This is the complete list of members for file_in_zip_read_info_s, including all inherited members.

byte_before_the_zipfile	file_in_zip_read_info_s

compression_method	file_in_zip_read_info_s

crc32	file_in_zip_read_info_s

crc32_wait	file_in_zip_read_info_s

filestream	file_in_zip_read_info_s

offset_local_extrafield	file_in_zip_read_info_s

pos_in_zipfile	file_in_zip_read_info_s

pos_local_extrafield	file_in_zip_read_info_s

raw	file_in_zip_read_info_s

read_buffer	file_in_zip_read_info_s

rest_read_compressed	file_in_zip_read_info_s

rest_read_uncompressed	file_in_zip_read_info_s

size_local_extrafield	file_in_zip_read_info_s

stream	file_in_zip_read_info_s

stream_initialised	file_in_zip_read_info_s

z_filefunc	file_in_zip_read_info_s

Generated on Sat May 20 2017 22:15:28 for tesseract by

     1.8.13


text:
layout: page
title: "Steven Elliot Glaser"
comments: true
description: "blanks"
keywords: "Steven Elliot Glaser,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: GEOL 1030

#### GEOL 1030: Introduction to Geology Laboratory 1

**Terms taught**: Fall 2010, Fall 2010

**Instructor rating**: 5.56

**Standard deviation in instructor rating**: 0.19

**Average grade** (4.0 scale): 3.19

**Standard deviation in grades** (4.0 scale): 0.01

**Average workload** (raw): 1.78

**Standard deviation in workload** (raw): 0.03


text:
'use strict';

/**@type {ModdedBattleScriptsData} */
let BattleScripts = {
	init() {
		for (let i in this.data.Items) {
			if (!this.data.Items[i].megaStone) continue;
			this.modData('Items', i).onTakeItem = false;
			let id = toID(this.data.Items[i].megaStone);
			this.modData('FormatsData', id).isNonstandard = null;
		}
	},
	canMegaEvo(pokemon) {
		if (pokemon.template.isMega) return null;

		const item = pokemon.getItem();
		if (item.megaStone) {
			if (item.megaStone === pokemon.species) return null;
			return item.megaStone;
		} else {
			return null;
		}
	},
	runMegaEvo(pokemon) {
		if (pokemon.template.isMega) return false;

		/**@type {Template} */
		// @ts-ignore
		const template = this.getMixedTemplate(pokemon.m.originalSpecies, pokemon.canMegaEvo);
		const side = pokemon.side;

		// Pokémon affected by Sky Drop cannot Mega Evolve. Enforce it here for now.
		for (const foeActive of side.foe.active) {
			if (foeActive.volatiles['skydrop'] && foeActive.volatiles['skydrop'].source === pokemon) {
				return false;
			}
		}

		// Do we have a proper sprite for it?
		// @ts-ignore assert non-null pokemon.canMegaEvo
		if (this.dex.getTemplate(pokemon.canMegaEvo).baseSpecies === pokemon.m.originalSpecies) {
			pokemon.formeChange(template, pokemon.getItem(), true);
		} else {
			let oTemplate = this.dex.getTemplate(pokemon.m.originalSpecies);
			// @ts-ignore
			let oMegaTemplate = this.dex.getTemplate(template.originalMega);
			pokemon.formeChange(template, pokemon.getItem(), true);
			this.add('-start', pokemon, oMegaTemplate.requiredItem, '[silent]');
			if (oTemplate.types.length !== pokemon.template.types.length || oTemplate.types[1] !== pokemon.template.types[1]) {
				this.add('-start', pokemon, 'typechange', pokemon.template.types.join('/'), '[silent]');
			}
		}

		pokemon.canMegaEvo = null;
		return true;
	},
	getMixedTemplate(originalSpecies, megaSpecies) {
		let originalTemplate = this.dex.getTemplate(originalSpecies);
		let megaTemplate = this.dex.getTemplate(megaSpecies);
		if (originalTemplate.baseSpecies === megaTemplate.baseSpecies) return megaTemplate;
		// @ts-ignore
		let deltas = this.getMegaDeltas(megaTemplate);
		// @ts-ignore
		let template = this.doGetMixedTemplate(originalTemplate, deltas);
		return template;
	},
	getMegaDeltas(megaTemplate) {
		let baseTemplate = this.dex.getTemplate(megaTemplate.baseSpecies);
		/**@type {{ability: string, baseStats: {[k: string]: number}, weighthg: number, originalMega: string, requiredItem: string | undefined, type?: string, isMega?: boolean}} */
		let deltas = {
			ability: megaTemplate.abilities['0'],
			baseStats: {},
			weighthg: megaTemplate.weighthg - baseTemplate.weighthg,
			originalMega: megaTemplate.species,
			requiredItem: megaTemplate.requiredItem,
		};
		for (let statId in megaTemplate.baseStats) {
			// @ts-ignore
			deltas.baseStats[statId] = megaTemplate.baseStats[statId] - baseTemplate.baseStats[statId];
		}
		if (megaTemplate.types.length > baseTemplate.types.length) {
			deltas.type = megaTemplate.types[1];
		} else if (megaTemplate.types.length < baseTemplate.types.length) {
			deltas.type = 'mono';
		} else if (megaTemplate.types[1] !== baseTemplate.types[1]) {
			deltas.type = megaTemplate.types[1];
		}
		if (megaTemplate.isMega) deltas.isMega = true;
		return deltas;
	},
	doGetMixedTemplate(templateOrTemplateName, deltas) {
		if (!deltas) throw new TypeError("Must specify deltas!");
		let template = this.dex.deepClone(this.dex.getTemplate(templateOrTemplateName));
		template.abilities = {'0': deltas.ability};
		if (template.types[0] === deltas.type) {
			template.types = [deltas.type];
		} else if (deltas.type === 'mono') {
			template.types = [template.types[0]];
		} else if (deltas.type) {
			template.types = [template.types[0], deltas.type];
		}
		let baseStats = template.baseStats;
		for (let statName in baseStats) {
			baseStats[statName] = this.dex.clampIntRange(baseStats[statName] + deltas.baseStats[statName], 1, 255);
		}
		template.weighthg = Math.max(1, template.weighthg + deltas.weighthg);
		template.originalMega = deltas.originalMega;
		template.requiredItem = deltas.requiredItem;
		if (deltas.isMega) template.isMega = true;
		return template;
	},
};

exports.BattleScripts = BattleScripts;


text:
package tec.uom.client.fitbit.model.units;

import javax.measure.Unit;
import javax.measure.quantity.Volume;

import tec.units.ri.unit.Units;
import tec.units.ri.unit.MetricPrefix;
import systems.uom.common.US;

public enum VolumeUnits {
    ML(MetricPrefix.MILLI(Units.LITRE)),
    FL_OZ(US.FLUID_OUNCE),
    CUP(US.CUP);

    Unit<Volume> unitRepresentation;

    VolumeUnits(Unit<Volume> unitRepresentation) {
        this.unitRepresentation = unitRepresentation;
    }

    public Unit<Volume> getUnitRepresentation() {
        return unitRepresentation;
    }
}


text:
from webkitpy.layout_tests.models import test_expectations

from webkitpy.common.net import resultsjsonparser

TestExpectations = test_expectations.TestExpectations
TestExpectationParser = test_expectations.TestExpectationParser

class BuildBotPrinter(object):
    # This output is parsed by buildbots and must only be changed in coordination with buildbot scripts (see webkit.org's
    # Tools/BuildSlaveSupport/build.webkit.org-config/master.cfg: RunWebKitTests._parseNewRunWebKitTestsOutput
    # and chromium.org's buildbot/master.chromium/scripts/master/log_parser/webkit_test_command.py).

    def __init__(self, stream, debug_logging):
        self.stream = stream
        self.debug_logging = debug_logging

    def print_results(self, run_details):
        if self.debug_logging:
            self.print_run_results(run_details.initial_results)
        self.print_unexpected_results(run_details.summarized_full_results, run_details.enabled_pixel_tests_in_retry)

    def _print(self, msg):
        self.stream.write(msg + '\n')

    def print_run_results(self, run_results):
        failed = run_results.total_failures
        total = run_results.total
        passed = total - failed - run_results.remaining
        percent_passed = 0.0
        if total > 0:
            percent_passed = float(passed) * 100 / total

        self._print("=> Results: %d/%d tests passed (%.1f%%)" % (passed, total, percent_passed))
        self._print("")
        self._print_run_results_entry(run_results, test_expectations.NOW, "Tests to be fixed")

        self._print("")
        # FIXME: We should be skipping anything marked WONTFIX, so we shouldn't bother logging these stats.
        self._print_run_results_entry(run_results, test_expectations.WONTFIX,
            "Tests that will only be fixed if they crash (WONTFIX)")
        self._print("")

    def _print_run_results_entry(self, run_results, timeline, heading):
        total = len(run_results.tests_by_timeline[timeline])
        not_passing = (total -
            len(run_results.tests_by_expectation[test_expectations.PASS] &
                run_results.tests_by_timeline[timeline]))
        self._print("=> %s (%d):" % (heading, not_passing))

        for result in TestExpectations.EXPECTATION_ORDER:
            if result in (test_expectations.PASS, test_expectations.SKIP):
                continue
            results = (run_results.tests_by_expectation[result] & run_results.tests_by_timeline[timeline])
            desc = TestExpectations.EXPECTATION_DESCRIPTIONS[result]
            if not_passing and len(results):
                pct = len(results) * 100.0 / not_passing
                self._print("  %5d %-24s (%4.1f%%)" % (len(results), desc, pct))

    def print_unexpected_results(self, summarized_results, enabled_pixel_tests_in_retry=False):
        passes = {}
        flaky = {}
        regressions = {}

        def add_to_dict_of_lists(dict, key, value):
            dict.setdefault(key, []).append(value)

        def add_result(test, results, passes=passes, flaky=flaky, regressions=regressions):
            actual = results['actual'].split(" ")
            expected = results['expected'].split(" ")

            if 'is_unexpected' not in results or not results['is_unexpected']:
                # Don't print anything for tests that ran as expected.
                return

            if actual == ['PASS']:
                if 'CRASH' in expected:
                    add_to_dict_of_lists(passes, 'Expected to crash, but passed', test)
                elif 'TIMEOUT' in expected:
                    add_to_dict_of_lists(passes, 'Expected to timeout, but passed', test)
                else:
                    add_to_dict_of_lists(passes, 'Expected to fail, but passed', test)
            elif enabled_pixel_tests_in_retry and actual == ['TEXT', 'IMAGE+TEXT']:
                add_to_dict_of_lists(regressions, actual[0], test)
            elif len(actual) > 1:
                # We group flaky tests by the first actual result we got.
                add_to_dict_of_lists(flaky, actual[0], test)
            else:
                add_to_dict_of_lists(regressions, results['actual'], test)

        resultsjsonparser.for_each_test(summarized_results['tests'], add_result)

        if len(passes) or len(flaky) or len(regressions):
            self._print("")
        if len(passes):
            for key, tests in passes.iteritems():
                self._print("%s: (%d)" % (key, len(tests)))
                tests.sort()
                for test in tests:
                    self._print("  %s" % test)
                self._print("")
            self._print("")

        if len(flaky):
            descriptions = TestExpectations.EXPECTATION_DESCRIPTIONS
            for key, tests in flaky.iteritems():
                result = TestExpectations.EXPECTATIONS[key.lower()]
                self._print("Unexpected flakiness: %s (%d)" % (descriptions[result], len(tests)))
                tests.sort()

                for test in tests:
                    result = resultsjsonparser.result_for_test(summarized_results['tests'], test)
                    actual = result['actual'].split(" ")
                    expected = result['expected'].split(" ")
                    result = TestExpectations.EXPECTATIONS[key.lower()]
                    # FIXME: clean this up once the old syntax is gone
                    new_expectations_list = [TestExpectationParser._inverted_expectation_tokens[exp] for exp in list(set(actual) | set(expected))]
                    self._print("  %s [ %s ]" % (test, " ".join(new_expectations_list)))
                self._print("")
            self._print("")

        if len(regressions):
            descriptions = TestExpectations.EXPECTATION_DESCRIPTIONS
            for key, tests in regressions.iteritems():
                result = TestExpectations.EXPECTATIONS[key.lower()]
                self._print("Regressions: Unexpected %s (%d)" % (descriptions[result], len(tests)))
                tests.sort()
                for test in tests:
                    self._print("  %s [ %s ]" % (test, TestExpectationParser._inverted_expectation_tokens[key]))
                self._print("")

        if len(summarized_results['tests']) and self.debug_logging:
            self._print("%s" % ("-" * 78))


text:
package com.microsoft.windowsazure.core.pipeline;

import com.microsoft.windowsazure.core.pipeline.PipelineHelpers;
import com.microsoft.windowsazure.core.utils.AccessConditionHeader;
import static org.junit.Assert.*;

import org.junit.Test;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;

public class PipelineHelpersTest {
    @Test
    public void addOptionalSourceAccessConditionHeaderSuccess()
            throws Exception {
        // Arrange
        Client client = Client.create();
        WebResource webResource = client.resource("http://www.microsoft.com");
        Builder builder = webResource.header("ms-version", "1.0");
        AccessConditionHeader accessCondition = AccessConditionHeader
                .ifMatch("thisIsAETag");

        // Act
        Builder resultBuilder = PipelineHelpers
                .addOptionalSourceAccessConditionHeader(builder,
                        accessCondition);

        // Assert
        assertNotNull(resultBuilder);

    }
}