text:
package com.qumasoft.qvcslib;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class implements a file level merge. It requires 3 input files, and one output file. The 3 input files consist of a common ancestor file, and two descendants of that common
 * ancestor file. Basically, it diffs descendant 1 against the common ancestor, then diffs descendant 2 against the common ancestor, and then merges the resulting edit scripts
 * produced by those two diffs. It then applies the merged edit script against the common ancestor to produce a merged result. If there are no collisions between the two diffs,
 * then the resulting merged output will contain the merged edits of the two descendants. If there are collisions, then the merge will fail.
 *
 * @author Jim Voris
 */
public final class FileMerge implements QVCSOperation {
    // Create our logger object
    private static final Logger LOGGER = LoggerFactory.getLogger(FileMerge.class);
    private String[] args;
    private String baseFileName;
    private String firstDescendentName;
    private String secondDescendentName;
    private String outputFileName;
    private Map<String, EditInfo> editScript = null;
    private long insertedBytesCount = 0L;
    private static final int ARGUMENT_COUNT = 4;
    private static final int BASE_FILENAME_ARG_INDEX = 0;
    private static final int FIRST_DESCENDENT_FILENAME_ARG_INDEX = 1;
    private static final int SECOND_DESCENDENT_FILENAME_ARG_INDEX = 2;
    private static final int OUTPUT_FILENAME_ARG_INDEX = 3;
    private static final int COMPARE_FILES_ARG_COUNT = 3;

    /**
     * Default constructor.
     */
    public FileMerge() {
    }

    /**
     * File merge constructor with arguments.
     * @param arguments a String[] with the arguments: base file name; first descendent file name; second descendent file name; output file name.
     */
    public FileMerge(final String[] arguments) {
        this.args = arguments;
    }

    @Override
    public boolean execute(String[] arguments) throws QVCSOperationException {
        this.args = arguments;
        copyArguments();
        return execute();
    }

    private void copyArguments() {
        baseFileName = args[BASE_FILENAME_ARG_INDEX];
        firstDescendentName = args[FIRST_DESCENDENT_FILENAME_ARG_INDEX];
        secondDescendentName = args[SECOND_DESCENDENT_FILENAME_ARG_INDEX];
        outputFileName = args[OUTPUT_FILENAME_ARG_INDEX];
    }

    /**
     * Merge the two descendent files of the base file into a single output file.
     *
     * @param baseName the common ancestor of the two descendent files.
     * @param firstDescFileName the filename of the first descendent file.
     * @param secondDescFileName the filename of the second descendent file.
     * @param outputName the filename of the output file that we create.
     * @return true if the merge succeeds. false if the merge fails.
     * @throws com.qumasoft.qvcslib.QVCSOperationException for validation or other QVCS related problems.
     */
    public boolean mergeFiles(final String baseName, final String firstDescFileName, final String secondDescFileName, final String outputName)
            throws QVCSOperationException {
        String[] localArgs = new String[ARGUMENT_COUNT];
        localArgs[BASE_FILENAME_ARG_INDEX] = baseName;
        localArgs[FIRST_DESCENDENT_FILENAME_ARG_INDEX] = firstDescFileName;
        localArgs[SECOND_DESCENDENT_FILENAME_ARG_INDEX] = secondDescFileName;
        localArgs[OUTPUT_FILENAME_ARG_INDEX] = outputName;
        return execute(localArgs);
    }

    @Override
    public boolean execute() throws QVCSOperationException {
        boolean retVal;

        try {
            // Make sure we have the arguments that we need.
            validateArguments();

            // Make a new empty merged edit script.
            editScript = new TreeMap<>();

            // Compare the first descendent to the base file.
            String[] firstCompareArgs = new String[COMPARE_FILES_ARG_COUNT];
            firstCompareArgs[0] = baseFileName;
            firstCompareArgs[1] = firstDescendentName;
            File firstCompareOutputTempFile = File.createTempFile("QVCS", ".tmp");
            firstCompareOutputTempFile.deleteOnExit();
            firstCompareArgs[2] = firstCompareOutputTempFile.getCanonicalPath();

            LOGGER.info("Comparing [" + baseFileName + "] to [" + firstDescendentName + "]");
            CompareFilesWithApacheDiff firstCompareFilesOperator = new CompareFilesWithApacheDiff(firstCompareArgs);
            if (!firstCompareFilesOperator.execute()) {
                throw new QVCSOperationException("Failed to compare [" + baseFileName + "] to file revision [" + firstDescendentName + "]");
            }

            // Compare the second descendent to the base file.
            String[] secondCompareArgs = new String[COMPARE_FILES_ARG_COUNT];
            secondCompareArgs[0] = baseFileName;
            secondCompareArgs[1] = secondDescendentName;
            File secondCompareOutputTempFile = File.createTempFile("QVCS", ".tmp");
            secondCompareOutputTempFile.deleteOnExit();
            secondCompareArgs[2] = secondCompareOutputTempFile.getCanonicalPath();

            LOGGER.info("Comparing [" + baseFileName + "] to [" + secondDescendentName + "]");
            CompareFilesWithApacheDiff secondCompareFilesOperator = new CompareFilesWithApacheDiff(secondCompareArgs);
            if (!secondCompareFilesOperator.execute()) {
                throw new QVCSOperationException("Failed to compare [" + baseFileName + "] to file revision [" + secondDescendentName + "]");
            }

            // Merge the two edit scripts into a single merged edit script (contained in
            // the m_EditScript instance variable.
            mergeEditScripts(firstCompareOutputTempFile, secondCompareOutputTempFile);

            // Apply the edits. We'll get here if and only if there are no
            // overlaps.
            applyEdits();
            retVal = true;
        } catch (IOException e) {
            LOGGER.warn(e.getLocalizedMessage(), e);
            retVal = false;
        }

        return retVal;
    }

    /**
     * Walk the list of edits and apply them to the the base file.
     */
    private void applyEdits() throws IOException, QVCSOperationException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        File baseFile = new File(baseFileName);
        byte[] originalData = new byte[(int) baseFile.length()];

        byte[] editedBuffer = new byte[(int) getInsertedBytesCount() + originalData.length]; // It can't be any bigger than this.
        int inIndex = 0;
        int outIndex = 0;
        int deletedBytesCount;
        int localInsertedBytesCount;
        int bytesTillChange = 0;
        EditInfo editInfo = null;

        try {
            fileInputStream = new FileInputStream(baseFile);
            fileInputStream.read(originalData);

            Iterator<EditInfo> it = editScript.values().iterator();
            while (it.hasNext()) {
                editInfo = it.next();
                bytesTillChange = (int) editInfo.getSeekPosition() - inIndex;
                System.arraycopy(originalData, inIndex, editedBuffer, outIndex, bytesTillChange);

                inIndex += bytesTillChange;
                outIndex += bytesTillChange;

                deletedBytesCount = (int) editInfo.getDeletedBytesCount();
                localInsertedBytesCount = (int) editInfo.getInsertedBytesCount();

                switch (editInfo.getEditType()) {
                    case CompareFilesEditInformation.QVCS_EDIT_DELETE:
                        /*
                         * Delete input.
                         * Just skip over deleted bytes.
                         */
                        inIndex += deletedBytesCount;
                        break;
                    case CompareFilesEditInformation.QVCS_EDIT_INSERT:
                        /*
                         * Insert edit lines
                         */
                        System.arraycopy(editInfo.getInsertedBytes(), 0, editedBuffer, outIndex, localInsertedBytesCount);
                        outIndex += localInsertedBytesCount;
                        break;
                    case CompareFilesEditInformation.QVCS_EDIT_REPLACE:
                        /*
                         * Replace input line with edit line
                         * First skip over the bytes to be replaced, then copy the replacing bytes from the edit file to the output file.
                         */
                        inIndex += deletedBytesCount;
                        System.arraycopy(editInfo.getInsertedBytes(), 0, editedBuffer, outIndex, localInsertedBytesCount);
                        outIndex += localInsertedBytesCount;
                        break;
                    default:
                        continue;
                }
            }

            // Copy the rest of the input "file" to the output "file".
            int remainingBytes = originalData.length - inIndex;
            if (remainingBytes > 0) {
                System.arraycopy(originalData, inIndex, editedBuffer, outIndex, remainingBytes);
                outIndex += remainingBytes;
            }

            // Write the result to the output file.
            File outputFile = new File(outputFileName);
            fileOutputStream = new FileOutputStream(outputFile);
            fileOutputStream.write(editedBuffer, 0, outIndex);
        } catch (IOException e) {
            LOGGER.warn(e.getLocalizedMessage(), e);
            if (editInfo != null) {
                LOGGER.warn(" editInfo.seekPosition: " + editInfo.getSeekPosition() + " originalData.length: " + originalData.length + " inIndex: " + inIndex
                        + " editedBuffer.length: "
                        + editedBuffer.length + " outIndex: " + outIndex + " bytesTillChange: " + bytesTillChange);
            }
            throw new QVCSOperationException("Internal error!! Failed to apply edits in FileMerge.");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                LOGGER.warn(e.getLocalizedMessage(), e);
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }
    }

    private String getEditRecordType(FileMerge.EditInfo editInfo) {
        String editInfoType;

        switch (editInfo.getEditType()) {
            case CompareFilesEditInformation.QVCS_EDIT_DELETE:
                /*
                * Delete input
                */
                editInfoType = "DELETE";
                break;
            case CompareFilesEditInformation.QVCS_EDIT_INSERT:
                /*
                 * Insert edit lines
                 */
                editInfoType = "INSERT";
                break;
            case CompareFilesEditInformation.QVCS_EDIT_REPLACE:
                /*
                 * Replace input line with edit line
                 */
                editInfoType = "REPLACE";
                break;
            default:
                editInfoType = "UNKNOWN";
                break;
        }

        return editInfoType;
    }

    private void mergeEditScripts(File firstCompareOutputTempFile, File secondCompareOutputTempFile) throws QVCSOperationException {
        addFileToEditScript(firstCompareOutputTempFile, 1);
        addFileToEditScript(secondCompareOutputTempFile, 2);

        // Check for overlap.
        long lastEditEndingPosition = 0L;
        EditInfo lastEditInfo = null;
        Iterator<EditInfo> it = editScript.values().iterator();
        while (it.hasNext()) {
            EditInfo editInfo = it.next();
            if (editInfo.getSeekPosition() <= lastEditEndingPosition) {
                String overlapMessage;
                if (lastEditInfo != null) {
                    overlapMessage = "Overlap detected between " + getEditRecordType(lastEditInfo) + " edit record from file " + lastEditInfo.getFileIndex() + " at location "
                            + lastEditInfo.getSeekPosition() + " with length " + lastEditInfo.getEditLength()
                            + " and " + getEditRecordType(editInfo) + " edit record from file " + editInfo.getFileIndex() + " at location " + editInfo.getSeekPosition()
                            + " with length " + editInfo.getEditLength();
                } else {
                    overlapMessage = "Overlap detected at " + editInfo.getFileIndex();
                }
                throw new QVCSOperationException(overlapMessage);
            }
            lastEditEndingPosition = editInfo.getSeekPosition() + editInfo.getEditLength();
            lastEditInfo = editInfo;
            insertedBytesCount += editInfo.getInsertedBytesCount();
        }
    }

    private void addFileToEditScript(File editScriptToAdd, int fileIndex) throws QVCSOperationException {
        try {
            byte[] fileData = new byte[(int) editScriptToAdd.length()];
            try (FileInputStream fileInputStream = new FileInputStream(editScriptToAdd)) {
                fileInputStream.read(fileData);
            }
            DataInputStream editStream = new DataInputStream(new ByteArrayInputStream(fileData));
            CompareFilesEditInformation cfei = new CompareFilesEditInformation();

            // Skip over the header bytes that are a prefix at the beginning of the
            // edit script.
            byte[] headerBytesToSkip = new byte[CompareFilesEditHeader.getEditHeaderSize()];
            editStream.read(headerBytesToSkip);

            while (editStream.available() > 0) {
                byte[] insertBuffer = null;

                cfei.read(editStream);
                if ((cfei.getEditType() == CompareFilesEditInformation.QVCS_EDIT_INSERT)
                        || (cfei.getEditType() == CompareFilesEditInformation.QVCS_EDIT_REPLACE)) {
                    insertBuffer = new byte[(int) cfei.getInsertedBytesCount()];
                    editStream.read(insertBuffer);
                }

                EditInfo editInfo = new EditInfo(cfei.getSeekPosition(),
                        fileIndex,
                        cfei.getEditType(),
                        cfei.getDeletedBytesCount(),
                        cfei.getInsertedBytesCount(),
                        insertBuffer);
                editScript.put(String.format("%015d,%d", cfei.getSeekPosition(), fileIndex), editInfo);
            }
        } catch (IOException e) {
            LOGGER.warn(e.getLocalizedMessage(), e);
            throw new QVCSOperationException(e.getLocalizedMessage());
        }
    }

    /**
     * Validate the arguments needed for a file merge. We need 4 arguments:
 the base file name
 the file name of the first descendant.
 the file name of the 2nd
     * descendant.
 the file name of the output file.... i.e. the file that will contained the merged result.

     *
     * @throws com.qumasoft.operations.QVCSOperationException
     */
    private void validateArguments() throws QVCSOperationException {
        if (args == null) {
            throw new QVCSOperationException("No arguments specified.");
        } else {
            if (args.length != ARGUMENT_COUNT) {
                throw new QVCSOperationException("You must specify 4 separate file names.");
            } else {
                baseFileName = args[BASE_FILENAME_ARG_INDEX];
                firstDescendentName = args[FIRST_DESCENDENT_FILENAME_ARG_INDEX];
                secondDescendentName = args[SECOND_DESCENDENT_FILENAME_ARG_INDEX];
                outputFileName = args[OUTPUT_FILENAME_ARG_INDEX];

                // Verify that each input file exists.
                checkThatFileExists(baseFileName, "Base file");
                checkThatFileExists(firstDescendentName, "First descendent");
                checkThatFileExists(secondDescendentName, "Second descendent");
            }
        }
    }

    private void checkThatFileExists(final String fileName, final String fileUsedAs) throws QVCSOperationException {
        File file = new File(fileName);
        if (!file.exists()) {
            throw new QVCSOperationException(fileUsedAs + " '" + baseFileName + "' is missing.");
        } else {
            // File exists. Make sure we can read it...
            if (!file.canRead()) {
                throw new QVCSOperationException("Don't have rights to read " + fileUsedAs + " : '" + fileName + "'.");
            }
        }
    }

    private long getInsertedBytesCount() {
        return insertedBytesCount;
    }

    static class EditInfo {

        private final long seekPosition;
        /**
         * Track which file this edit info is associated with
         */
        private final int fileIndex;
        private final short editType;
        private final long deletedBytesCount;
        private final long insertedBytesCount;
        private final byte[] insertedBytes;

        EditInfo(long seekPos, int fileIdx, int editTyp, long deletedBytesCnt, long insertedBytesCnt, byte[] insrtedBytes) {
            this.seekPosition = seekPos;
            this.fileIndex = fileIdx;
            this.editType = (short) editTyp;
            this.deletedBytesCount = deletedBytesCnt;
            this.insertedBytesCount = insertedBytesCnt;
            this.insertedBytes = insrtedBytes;
        }

        public long getSeekPosition() {
            return seekPosition;
        }

        /**
         * Return the file index -- i.e. which file this edit info instance is associated with.
         *
         * @return the file index for this instance. The value should be a 1 or a 2.
         */
        public int getFileIndex() {
            return fileIndex;
        }

        public short getEditType() {
            return editType;
        }

        public long getDeletedBytesCount() {
            return deletedBytesCount;
        }

        public long getInsertedBytesCount() {
            return insertedBytesCount;
        }

        public byte[] getInsertedBytes() {
            return insertedBytes;
        }

        /**
         * Figure out how many bytes this edit record affects in base file... i.e. how far into the file from the current position will these changes occur. This is useful for
         * detecting overlap.
         *
         * @return the number of bytes that this edit will affect in the base file.
         * @throws com.qumasoft.operations.QVCSOperationException this should never get thrown. If it does, it is an internal error -- we are seeing an edit script that is corrupt.
         */
        private long getEditLength() throws QVCSOperationException {
            long editLength = -1L;
            switch (editType) {
                case CompareFilesEditInformation.QVCS_EDIT_DELETE:
                    editLength = getDeletedBytesCount();
                    break;
                case CompareFilesEditInformation.QVCS_EDIT_INSERT:
                    editLength = getInsertedBytesCount();
                    break;
                case CompareFilesEditInformation.QVCS_EDIT_REPLACE:
                    if (getDeletedBytesCount() > getInsertedBytesCount()) {
                        editLength = getDeletedBytesCount();
                    } else {
                        editLength = getInsertedBytesCount();
                    }
                    break;
                default:
                    throw new QVCSOperationException("Internal error. Unknown edit type in FileMerge.java");
            }
            return editLength;
        }
    }

}


text:
package com.DroneSimulator;

/**
 * Represents the results of a trial.
 * @author Lars Bokkers
 *
 */
public class TrialResults
{
	// The trial for which this class holds the results.
	private TrialParameters trialParams;

	// Whether the cursor hit the target.
	private boolean isHit;

	// The time that expired during the trial.
	private double timeExpired; // In seconds.

	public TrialResults(){
	}

	public double getTimeRequired() {
		return timeExpired;
	}

	public void setTimeRequired(double timeRequired) {
		this.timeExpired = timeRequired;
	}

	public boolean isHit() {
		return isHit;
	}

	public void setHit(boolean isHit) {
		this.isHit = isHit;
	}

	public TrialParameters getSimulationDetails() {
		return trialParams;
	}

	public void setSimulationDetails(TrialParameters simulationDetails) {
		this.trialParams = simulationDetails;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
class User_model extends CI_Model {

    public $id;
    public $name;
    public $email;
    public $password;
    public $telephone;
    public $address;
    public $ip;
    public $admin = 0;
    public $date;

    private $table = 'users';

    public function __construct()
    {
        parent::__construct();
    }

    public function get_user()
    {
        $user_id = $this->session->userdata('user_id');

        if (!empty($user_id)) {
            $query = $this->db->get_where($this->table, ['id' => $user_id]);

            $data = $query->result();

            return end($data);
        } else {
            return false;
        }
    }

    public function get_data_by_id($id)
    {
        $query = $this->db->get_where($this->table, ['id' => $id]);

        $data = $query->result();

        return end($data);
    }

    public function get_admin()
    {
        if (!empty($_POST)) {
            $query = $this->db->get_where($this->table, ['admin' => 1, 'email' => $_POST['email'], 'password' => sha1($_POST['password'])]);

            $data = $query->result();

            return end($data);
        } else {
            return false;
        }
    }

    public function login()
    {
        $query = $this->db->get_where($this->table, ['email' => $_POST['email'], 'password' => sha1($_POST['password'])]);
        $result = $query->result();

        if (!empty($result)) {
            $this->session->set_userdata('user_id', end($result)->id);
        }
    }

    public function register()
    {
        $query = $this->db->get_where($this->table, ['email' => $_POST['email']]);
        $result = $query->result();

        if (!empty($result)) {
            return false;
        } else {
            $this->name             = $_POST['name'];
            $this->email            = $_POST['email'];
            $this->password         = sha1($_POST['password']);
            $this->telephone        = $_POST['telephone'];
            $this->address          = $_POST['address'];
            $this->ip               = $this->input->ip_address();

            $user = $this->db->insert($this->table, $this);

            $this->session->set_userdata('user_id', $user->id);

            return true;
        }
    }
}


text:
"use strict";

const Funnel = require('broccoli-funnel');
const findLib = require('./find-lib');

module.exports = function funnelLib(name) {

  let libPath, options;
  if (arguments.length > 2) {
    libPath = arguments[1];
    options = arguments[2];
  } else {
    options = arguments[1];
  }

  return new Funnel(findLib(name, libPath), options);
};


text:
package sdk.jassinaturas.clients;

import java.util.List;

import sdk.jassinaturas.clients.attributes.Customer;
import sdk.jassinaturas.communicators.CustomerCommunicator;

public class CustomerClient {

    private CustomerCommunicator customerCommunicator;

    public CustomerClient() {
    }

    public CustomerClient(final CustomerCommunicator customerCommunicator) {
        this.customerCommunicator = customerCommunicator;
    }

    public Customer create(final Customer toBeCreated) {

        if (shouldCreateVault(toBeCreated)) {
            Customer customer = customerCommunicator.createWithCreditCard(toBeCreated);
            return customer;
        } else {
            Customer customer = customerCommunicator.createWithoutCreditCard(toBeCreated);
            return customer;
        }

    }

    public List<Customer> list() {
        Customer customers = customerCommunicator.list();
        return customers.getCustomers();
    }

    public boolean shouldCreateVault(final Customer toBeCreated) {
        if (toBeCreated.getBillingInfo() == null) {
            return false;
        }

        return true;
    }

    public Customer show(final Customer customer) {
        Customer updatedCustomer = customerCommunicator.show(customer.getCode());
        return updatedCustomer;
    }

    public Customer show(final String code) {
        Customer plan = customerCommunicator.show(code);
        return plan;
    }

    public Customer update(final Customer toBeUpdated) {
        Customer customer = customerCommunicator.update(toBeUpdated.getCode(), toBeUpdated);
        return customer;
    }

    public Customer updateVault(final Customer toBeUpdated) {
        Customer customer = customerCommunicator.updateCreditCard(toBeUpdated.getCode(), toBeUpdated.getBillingInfo());
        return customer;
    }

}


text:
package br.com.cantinhoinc.sqlquerybuilder.builder;

public class Condition {

    private String left;

    private String right;

    private String operator;

    public static Condition make(
            String left,
            String operator,
            String right) {
        Condition condition = new Condition();
        condition.setLeft(left);
        condition.setOperator(operator);
        condition.setRight(right);
        return condition;
    }

    private Condition() {
    }

    public String getLeft() {
        return left;
    }

    public void setLeft(String left) {
        this.left = left;
    }

    public String getRight() {
        return right;
    }

    public void setRight(String right) {
        this.right = right;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String value() {
        return left + operator + right;
    }
}


text:
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include "WebKitDOMTestActiveDOMObject.h"

#include "DOMObjectCache.h"
#include "ExceptionCode.h"
#include "JSMainThreadExecState.h"
#include "TestActiveDOMObject.h"
#include "WebKitDOMBinding.h"
#include "gobject/ConvertToUTF8String.h"
#include "webkit/WebKitDOMNode.h"
#include "webkit/WebKitDOMNodePrivate.h"
#include "webkit/WebKitDOMTestActiveDOMObjectPrivate.h"
#include "webkitdefines.h"
#include "webkitglobalsprivate.h"
#include "webkitmarshal.h"
#include <glib-object.h>
#include <wtf/GetPtr.h>
#include <wtf/RefPtr.h>

namespace WebKit {

WebKitDOMTestActiveDOMObject* kit(WebCore::TestActiveDOMObject* obj)
{
    g_return_val_if_fail(obj, 0);

    if (gpointer ret = DOMObjectCache::get(obj))
        return static_cast<WebKitDOMTestActiveDOMObject*>(ret);

    return static_cast<WebKitDOMTestActiveDOMObject*>(DOMObjectCache::put(obj, WebKit::wrapTestActiveDOMObject(obj)));
}

WebCore::TestActiveDOMObject* core(WebKitDOMTestActiveDOMObject* request)
{
    g_return_val_if_fail(request, 0);

    WebCore::TestActiveDOMObject* coreObject = static_cast<WebCore::TestActiveDOMObject*>(WEBKIT_DOM_OBJECT(request)->coreObject);
    g_return_val_if_fail(coreObject, 0);

    return coreObject;
}

WebKitDOMTestActiveDOMObject* wrapTestActiveDOMObject(WebCore::TestActiveDOMObject* coreObject)
{
    g_return_val_if_fail(coreObject, 0);

    // We call ref() rather than using a C++ smart pointer because we can't store a C++ object
    // in a C-allocated GObject structure. See the finalize() code for the matching deref().
    coreObject->ref();

    return WEBKIT_DOM_TEST_ACTIVE_DOM_OBJECT(g_object_new(WEBKIT_TYPE_DOM_TEST_ACTIVE_DOM_OBJECT, "core-object", coreObject, NULL));
}

} // namespace WebKit

G_DEFINE_TYPE(WebKitDOMTestActiveDOMObject, webkit_dom_test_active_dom_object, WEBKIT_TYPE_DOM_OBJECT)

enum {
    PROP_0,
    PROP_EXCITING_ATTR,
};

static void webkit_dom_test_active_dom_object_finalize(GObject* object)
{

    WebKitDOMObject* domObject = WEBKIT_DOM_OBJECT(object);

    if (domObject->coreObject) {
        WebCore::TestActiveDOMObject* coreObject = static_cast<WebCore::TestActiveDOMObject*>(domObject->coreObject);

        WebKit::DOMObjectCache::forget(coreObject);
        coreObject->deref();

        domObject->coreObject = 0;
    }

    G_OBJECT_CLASS(webkit_dom_test_active_dom_object_parent_class)->finalize(object);
}

static void webkit_dom_test_active_dom_object_set_property(GObject* object, guint propertyId, const GValue* value, GParamSpec* pspec)
{
    WebCore::JSMainThreadNullState state;
    switch (propertyId) {
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
        break;
    }
}

static void webkit_dom_test_active_dom_object_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec)
{
    WebCore::JSMainThreadNullState state;

    WebKitDOMTestActiveDOMObject* self = WEBKIT_DOM_TEST_ACTIVE_DOM_OBJECT(object);
    WebCore::TestActiveDOMObject* coreSelf = WebKit::core(self);

    switch (propertyId) {
    case PROP_EXCITING_ATTR: {
        g_value_set_long(value, coreSelf->excitingAttr());
        break;
    }
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
        break;
    }
}

static void webkit_dom_test_active_dom_object_constructed(GObject* object)
{

    if (G_OBJECT_CLASS(webkit_dom_test_active_dom_object_parent_class)->constructed)
        G_OBJECT_CLASS(webkit_dom_test_active_dom_object_parent_class)->constructed(object);
}

static void webkit_dom_test_active_dom_object_class_init(WebKitDOMTestActiveDOMObjectClass* requestClass)
{
    GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass);
    gobjectClass->finalize = webkit_dom_test_active_dom_object_finalize;
    gobjectClass->set_property = webkit_dom_test_active_dom_object_set_property;
    gobjectClass->get_property = webkit_dom_test_active_dom_object_get_property;
    gobjectClass->constructed = webkit_dom_test_active_dom_object_constructed;

    g_object_class_install_property(gobjectClass,
                                    PROP_EXCITING_ATTR,
                                    g_param_spec_long("exciting-attr", /* name */
                                                           "test_active_dom_object_exciting-attr", /* short description */
                                                           "read-only  glong TestActiveDOMObject.exciting-attr", /* longer - could do with some extra doc stuff here */
                                                           G_MINLONG, /* min */
G_MAXLONG, /* max */
0, /* default */
                                                           WEBKIT_PARAM_READABLE));

}

static void webkit_dom_test_active_dom_object_init(WebKitDOMTestActiveDOMObject* request)
{
}

void
webkit_dom_test_active_dom_object_exciting_function(WebKitDOMTestActiveDOMObject* self, WebKitDOMNode* nextChild)
{
    g_return_if_fail(self);
    WebCore::JSMainThreadNullState state;
    WebCore::TestActiveDOMObject* item = WebKit::core(self);
    g_return_if_fail(nextChild);
    WebCore::Node* convertedNextChild = 0;
    if (nextChild) {
        convertedNextChild = WebKit::core(nextChild);
        g_return_if_fail(convertedNextChild);
    }
    item->excitingFunction(convertedNextChild);
}

void
webkit_dom_test_active_dom_object_post_message(WebKitDOMTestActiveDOMObject* self, const gchar* message)
{
    g_return_if_fail(self);
    WebCore::JSMainThreadNullState state;
    WebCore::TestActiveDOMObject* item = WebKit::core(self);
    g_return_if_fail(message);
    WTF::String convertedMessage = WTF::String::fromUTF8(message);
    item->postMessage(convertedMessage);
}

glong
webkit_dom_test_active_dom_object_get_exciting_attr(WebKitDOMTestActiveDOMObject* self)
{
    g_return_val_if_fail(self, 0);
    WebCore::JSMainThreadNullState state;
    WebCore::TestActiveDOMObject* item = WebKit::core(self);
    glong result = item->excitingAttr();
    return result;
}


text:
module GithubTools
  module Configuration
    extend self

    def token
      token = `git config githubtools.token`.strip
      token = create_token if token.empty?
      token
    end

    def create_token
      print 'Username:'
      username = gets.strip
      print 'Password (never saved):'
      password = STDIN.noecho(&:gets).strip
      client = Octokit::Client.new(:login => username, :password => password)
      response = client.create_authorization(
        :scopes => [:repo],
        :note => 'github_tools',
        :note_url =>'https://github.com/ivantsepp/github_tools')
      token = response[:token]
      save_token(token)
      token
    end

    def save_token(token)
      `git config --global githubtools.token #{token}`
    end

    def remote
      url = `git config --get remote.origin.url`.strip
      url = 'ssh://' + url if url.include?('@')
      url.gsub!('.git', '')
      Octokit::Repository.from_url(url)
    end

  end
end


text:
package elastic

// MinAggregation is a single-value metrics aggregation that keeps track and
// returns the minimum value among numeric values extracted from the
// aggregated documents. These values can be extracted either from
// specific numeric fields in the documents, or be generated by a
// provided script.
// See: https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-aggregations-metrics-min-aggregation.html
type MinAggregation struct {
	field           string
	script          *Script
	format          string
	subAggregations map[string]Aggregation
	meta            map[string]interface{}
}

func NewMinAggregation() *MinAggregation {
	return &MinAggregation{
		subAggregations: make(map[string]Aggregation),
	}
}

func (a *MinAggregation) Field(field string) *MinAggregation {
	a.field = field
	return a
}

func (a *MinAggregation) Script(script *Script) *MinAggregation {
	a.script = script
	return a
}

func (a *MinAggregation) Format(format string) *MinAggregation {
	a.format = format
	return a
}

func (a *MinAggregation) SubAggregation(name string, subAggregation Aggregation) *MinAggregation {
	a.subAggregations[name] = subAggregation
	return a
}

// Meta sets the meta data to be included in the aggregation response.
func (a *MinAggregation) Meta(metaData map[string]interface{}) *MinAggregation {
	a.meta = metaData
	return a
}

func (a *MinAggregation) Source() (interface{}, error) {
	// Example:
	//	{
	//    "aggs" : {
	//      "min_price" : { "min" : { "field" : "price" } }
	//    }
	//	}
	// This method returns only the { "min" : { "field" : "price" } } part.

	source := make(map[string]interface{})
	opts := make(map[string]interface{})
	source["min"] = opts

	// ValuesSourceAggregationBuilder
	if a.field != "" {
		opts["field"] = a.field
	}
	if a.script != nil {
		src, err := a.script.Source()
		if err != nil {
			return nil, err
		}
		opts["script"] = src
	}
	if a.format != "" {
		opts["format"] = a.format
	}

	// AggregationBuilder (SubAggregations)
	if len(a.subAggregations) > 0 {
		aggsMap := make(map[string]interface{})
		source["aggregations"] = aggsMap
		for name, aggregate := range a.subAggregations {
			src, err := aggregate.Source()
			if err != nil {
				return nil, err
			}
			aggsMap[name] = src
		}
	}

	// Add Meta data if available
	if len(a.meta) > 0 {
		source["meta"] = a.meta
	}

	return source, nil
}


text:
package com.intuit.karate.debug;

import com.intuit.karate.Json;
import com.intuit.karate.core.ScenarioRuntime;
import com.intuit.karate.core.Variable;

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

/**
 *
 * @author pthomas3
 */
public class SourceBreakpoints {

    public final String name;
    public final String path;
    public final List<Breakpoint> breakpoints;
    public final boolean sourceModified;

    public boolean isBreakpoint(int line, ScenarioRuntime context) {
        if (breakpoints == null || breakpoints.isEmpty()) {
            return false;
        }
        for (Breakpoint b : breakpoints) {
            if (b.line == line) {
                if (b.condition == null) {
                    return true;
                } else {
                    Variable evalCondition = context.engine.evalKarateExpression(b.condition);
                    if (evalCondition != null && evalCondition.type != Variable.Type.BOOLEAN) {
                        // if the condition is not a boolean then what are you doing trying to use it as a condition?
                        return true;
                    }

                    return evalCondition != null && evalCondition.isTrue();
                }
            }
        }
        return false;
    }

    public SourceBreakpoints(Map<String, Object> map) {
        Json json = Json.of(map);
        name = json.get("source.name");
        path = json.get("source.path");
        List<Map<String, Object>> list = json.get("breakpoints");
        breakpoints = new ArrayList(list.size());
        for (Map<String, Object> bm : list) {
            breakpoints.add(new Breakpoint(bm));
        }
        sourceModified = json.get("sourceModified");
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[name: ").append(name);
        sb.append(", path: ").append(path);
        sb.append(", breakpoints: ").append(breakpoints);
        sb.append(", sourceModified: ").append(sourceModified);
        sb.append("]");
        return sb.toString();
    }

}


text:
using LinFx.Extensions.Modularity;
using Microsoft.AspNetCore.Builder;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ModuleExtensions
    {
        [Obsolete]
        public static IApplicationBuilder UseModules(this IApplicationBuilder app)
        {
            var moduleInitializers = app.ApplicationServices.GetServices<IModuleInitializer>();
            foreach (var moduleInitializer in moduleInitializers)
            {
                moduleInitializer.Configure(app, null);
            }
            return app;
        }
    }
}


text:
SYNONYM

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

#### Published in
Führ. Pilzk. (Zwickau) 132 (1871)

#### Original name
Agaricus nudus Bull., 1790

### Remarks
null


text:
Learn about
[null safety and safe calls](http://kotlinlang.org/docs/reference/null-safety.html)
in Kotlin and rewrite the following Java code so that it only has one `if` expression:

```java
public void sendMessageToClient(
    @Nullable Client client,
    @Nullable String message,
    @NotNull Mailer mailer
) {
    if (client == null || message == null) return;

    PersonalInfo personalInfo = client.getPersonalInfo();
    if (personalInfo == null) return;

    String email = personalInfo.getEmail();
    if (email == null) return;

    mailer.sendMessage(email, message);
}
```


text: 1. detect android device params


text:
package com.stanleyidesis.quotograph.api.drawing;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v7.graphics.Palette;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.stanleyidesis.quotograph.BuildConfig;
import com.stanleyidesis.quotograph.LWQApplication;
import com.stanleyidesis.quotograph.LWQPreferences;
import com.stanleyidesis.quotograph.R;
import com.stanleyidesis.quotograph.RemoteConfigConst;
import com.stanleyidesis.quotograph.api.Callback;
import com.stanleyidesis.quotograph.api.controller.LWQWallpaperController;
import com.stanleyidesis.quotograph.api.controller.LWQWallpaperControllerHelper;
import com.stanleyidesis.quotograph.ui.UIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class LWQDrawScript {

    static ExecutorService executorService;
    static SparseArray<Palette> paletteCache;
    static final int TEXT_ALPHA = 0xE5FFFFFF;
    static final int STROKE_ALPHA = 0xF2FFFFFF;
    static int swatchIndex;
    static RenderScript renderScript;
    static Bitmap cachedBlur;
    static int cachedBlurLevel;

    static {
        executorService = Executors.newSingleThreadScheduledExecutor();
        paletteCache = new SparseArray<>();
    }

    Palette palette;
    int drawRequests = 0;

    /**
     * @return a Canvas, ready to draw
     */
    protected abstract Canvas reserveCanvas();

    /**
     * Release the canvas when ready
     * @param canvas
     */
    protected abstract void releaseCanvas(Canvas canvas);

    /**
     * @return a Rect that represents the full Surface size
     */
    protected abstract Rect surfaceRect();

    public void changeSwatch() {
        swatchIndex++;
        final List<Palette.Swatch> swatches = palette.getSwatches();
        if (swatchIndex >= swatches.size()) {
            swatchIndex = 0;
        }
        final Palette.Swatch chosenSwatch = swatches.get(swatchIndex);
        if (!BuildConfig.DEBUG) {
            return;
        }
        if (chosenSwatch == palette.getMutedSwatch()) {
            Toast.makeText(LWQApplication.get(), "Muted Swatch", Toast.LENGTH_LONG).show();
        } else if (chosenSwatch == palette.getVibrantSwatch()) {
            Toast.makeText(LWQApplication.get(), "Vibrant Swatch", Toast.LENGTH_LONG).show();
        } else if (chosenSwatch == palette.getDarkMutedSwatch()) {
            Toast.makeText(LWQApplication.get(), "Dark Muted Swatch", Toast.LENGTH_LONG).show();
        } else if (chosenSwatch == palette.getDarkVibrantSwatch()) {
            Toast.makeText(LWQApplication.get(), "Dark Vibrant Swatch", Toast.LENGTH_LONG).show();
        } else if (chosenSwatch == palette.getLightMutedSwatch()) {
            Toast.makeText(LWQApplication.get(), "Light Muted Swatch", Toast.LENGTH_LONG).show();
        } else if (chosenSwatch == palette.getLightVibrantSwatch()) {
            Toast.makeText(LWQApplication.get(), "Light Vibrant Swatch", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(LWQApplication.get(), "Unknown Swatch", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Notifies the Draw script that a brand new image is coming in
     */
    public void clearCache() {
        paletteCache.clear();
        if (cachedBlur != null) cachedBlur.recycle();
        cachedBlur = null;
        cachedBlurLevel = 0;
        renderScript = null;
    }

    public void requestDraw(final Callback<Boolean> callback) {
        increaseDrawRequests();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (getDrawRequests() == 0) {
                        return;
                    }
                    resetDrawRequests();
                    if (!LWQWallpaperControllerHelper.get().activeWallpaperLoaded()) {
                        LWQWallpaperControllerHelper.get().retrieveActiveWallpaper();
                        return;
                    }
                    draw();
                    if (callback != null) {
                        callback.onSuccess(true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void requestDraw() {
        requestDraw(null);
    }

    private void draw() {
        final LWQWallpaperController wallpaperController =
                LWQWallpaperControllerHelper.get();
        final Bitmap backgroundImage = wallpaperController.getBackgroundImage();
        if (backgroundImage == null) {
            return;
        }
        // Get screen size
        final Point realScreenSize = UIUtils.getRealScreenSize();
        final int screenWidth = realScreenSize.x;
        final int screenHeight = realScreenSize.y;
        final Rect surfaceFrame = surfaceRect();

        palette = paletteCache.get(backgroundImage.hashCode());
        if (palette == null) {
            LWQDrawScript.paletteCache.clear();
            palette = Palette.from(backgroundImage).generate();
            LWQDrawScript.paletteCache.put(backgroundImage.hashCode(), palette);
            LWQDrawScript.swatchIndex = 0;
        }

        final Canvas canvas = reserveCanvas();
        canvas.save();
        try {
            final int blurPreference = LWQPreferences.getBlurPreference();
            final int dimPreference = LWQPreferences.getDimPreference();
            // Blur or choose the raw background image
            Bitmap toDraw = null;
            if (cachedBlurLevel == blurPreference && cachedBlur != null) {
                toDraw = cachedBlur;
            } else {
                toDraw = blurPreference > 0.5f ? generateBlurredBitmap(blurPreference, backgroundImage) : backgroundImage;
                cachedBlur = blurPreference > 0.5f ? toDraw : null;
                cachedBlurLevel = blurPreference;
            }
            drawBitmap(canvas, screenWidth, surfaceFrame, toDraw);
            drawDimmer(canvas, dimPreference);
            drawText(canvas, screenWidth, screenHeight);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            canvas.restore();
            releaseCanvas(canvas);
        }
    }

    /**
     * Draws the quote and author text
     *
     * @param canvas
     * @param screenWidth
     * @param screenHeight
     * @return the rect surrounding both the quote and author
     */
    private Rect drawText(Canvas canvas, int screenWidth, int screenHeight) {
        Context context = LWQApplication.get();
        final LWQWallpaperController wallpaperController = LWQWallpaperControllerHelper.get();

        final Palette.Swatch swatch = getSwatch();
        int quoteColor = swatch.getRgb();
        int authorColor = swatch.getRgb();
        int quoteStrokeColor = swatch.getTitleTextColor();

        // Load Typeface
        Typeface quoteTypeFace = wallpaperController.getTypeface();

        // Setup Quote text
        TextPaint quoteTextPaint = new TextPaint();
        quoteTextPaint.setTextAlign(Paint.Align.LEFT);
        quoteTextPaint.setColor(quoteColor & TEXT_ALPHA);
        quoteTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
        quoteTextPaint.setTypeface(quoteTypeFace);
        quoteTextPaint.setTextSize(145f);
        quoteTextPaint.setStyle(Paint.Style.FILL);

        // Setup Author Text
        TextPaint authorTextPaint = new TextPaint(quoteTextPaint);
        authorTextPaint.setTextSize(100f);
        authorTextPaint.setTextAlign(Paint.Align.RIGHT);
        authorTextPaint.setColor(authorColor & TEXT_ALPHA);
        authorTextPaint.setTypeface(quoteTypeFace);
        String author = "";
        if (wallpaperController.getAuthor() != null && !wallpaperController.getAuthor().isEmpty()) {
            author = wallpaperController.getAuthor();
        }
        String quote = "";
        if (wallpaperController.getQuote() != null && !wallpaperController.getQuote().isEmpty()) {
            quote = wallpaperController.getQuote();
        }

        // Find the ending index of each word
        // We use this data to determine whether a line-break occurs in our StaticLayout
        List<Integer> endIndeces = new ArrayList<>();
        String[] words = quote.split("\\s+");
        if (words.length > 0) {
            int runningIndex = 0;
            for (int i = 0; i < words.length; i++) {
                int nextEndCap = quote.indexOf(words[i], runningIndex) + words[i].length() - 1;
                runningIndex = nextEndCap;
                endIndeces.add(nextEndCap);
            }
        } else {
            endIndeces.add(quote.length() - 1);
        }

        final int horizontalPadding = (int) (screenWidth * .07);
        final int verticalPadding = (int) (screenHeight * .2);
        final Rect drawingArea = new Rect(horizontalPadding, verticalPadding,
                screenWidth - horizontalPadding, screenHeight - verticalPadding);

        StaticLayout quoteLayout = new StaticLayout(quote.toUpperCase(), quoteTextPaint,
                drawingArea.width(), Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
        StaticLayout authorLayout = new StaticLayout(author, authorTextPaint,
                drawingArea.width(), Layout.Alignment.ALIGN_NORMAL, 1, 0, true);

        // Correct the quote and author height, if necessary
        quoteLayout = correctFontSize(quoteLayout, drawingArea.height() - authorLayout.getHeight(), endIndeces);
        authorLayout = correctFontSize(authorLayout, Integer.MAX_VALUE, null);
        if (authorLayout.getPaint().getTextSize() > quoteLayout.getPaint().getTextSize()) {
            TextPaint paint = authorLayout.getPaint();
            paint.setTextSize(quoteLayout.getPaint().getTextSize());
            authorLayout = new StaticLayout(authorLayout.getText(), paint,
                    authorLayout.getWidth(), authorLayout.getAlignment(), authorLayout.getSpacingMultiplier(),
                    authorLayout.getSpacingAdd(), true);
        }

        // Draw the quote centered vertically
        int centerQuoteOffset = (int)(.5 * (drawingArea.height() - quoteLayout.getHeight()));
        canvas.translate(drawingArea.left, drawingArea.top + centerQuoteOffset);
        quoteLayout.draw(canvas);
        strokeText(quoteLayout, quoteStrokeColor & STROKE_ALPHA, 3f, canvas);

        canvas.translate(drawingArea.width(), quoteLayout.getHeight() + (authorLayout.getHeight() / 4));
        authorLayout.draw(canvas);
        strokeText(authorLayout, quoteStrokeColor & STROKE_ALPHA, 3f, canvas);

        // Re-set the x/y translation
        canvas.setMatrix(null);

        // Crop the rect to quote and author
        drawingArea.top += centerQuoteOffset;
        drawingArea.bottom = drawingArea.top + quoteLayout.getHeight()
                + (int) (1.25 * authorLayout.getHeight());
        return drawingArea;
    }

    private void drawDimmer(Canvas canvas, int dimPreference) {
        if (dimPreference > 0) {
            int alpha = (int) Math.floor(255f * (dimPreference / 100f));
            canvas.drawColor(Color.argb(alpha, 0, 0, 0));
        }
    }

    private void drawBitmap(Canvas canvas, int screenWidth, Rect surfaceFrame, Bitmap bitmapToDraw) {
        Paint bitmapPaint = new Paint();
        bitmapPaint.setAntiAlias(true);
        bitmapPaint.setFilterBitmap(true);
        bitmapPaint.setDither(true);

        float scaleY = (float) surfaceFrame.height() / (float) bitmapToDraw.getHeight();
        float scaleX = (float) surfaceFrame.width() / (float) bitmapToDraw.getWidth();
        float finalScale = Math.max(scaleX, scaleY);

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.postScale(finalScale, finalScale);

        // Adjust center
        final int bitmapFinalWidth = (int)((float) bitmapToDraw.getWidth() * finalScale);
        if (bitmapFinalWidth <= screenWidth) {
            canvas.drawBitmap(bitmapToDraw, scaleMatrix, bitmapPaint);
            return;
        }
        final float dx = -0.5f * (bitmapFinalWidth - screenWidth);
        canvas.translate(dx, 0);
        canvas.drawBitmap(bitmapToDraw, scaleMatrix, bitmapPaint);
        canvas.translate(-dx, 0);
    }

    /**
     * For now, disabled. Scrapping Issue #148
     * @param canvas
     * @param screenWidth
     * @param screenHeight
     * @param quoteAndAuthorRect
     */
    void drawWatermark(Canvas canvas, int screenWidth, int screenHeight, Rect quoteAndAuthorRect) {
        if (!LWQPreferences.isWatermarkEnabled()) {
            return;
        }
        Bitmap icon = BitmapFactory.decodeResource(LWQApplication.get().getResources(),
                R.mipmap.ic_launcher);
        // Let's make the icon no more than 10% of the screen size at most
        float maxPixelHeight = ((float) Math.max(screenWidth, screenHeight)) * .1f;
        float scale = maxPixelHeight / (float) icon.getHeight();
        Matrix scaleMatrix = new Matrix();
        scaleMatrix.postScale(scale, scale);
        Paint iconPaint = new Paint();
        iconPaint.setAntiAlias(true);
        iconPaint.setFilterBitmap(true);
        iconPaint.setDither(true);
        iconPaint.setAlpha(100);
        canvas.translate(quoteAndAuthorRect.left, screenHeight - maxPixelHeight);
        canvas.drawBitmap(icon, scaleMatrix, iconPaint);
    }

    private StaticLayout correctFontSize(StaticLayout staticLayout, int maxHeight, List<Integer> endOfWordIndices) {
        final TextPaint textPaint = staticLayout.getPaint();
        boolean heightFixed = false;
        while (!heightFixed) {
            textPaint.setTextSize(textPaint.getTextSize() * .99f);
            staticLayout = new StaticLayout(staticLayout.getText(), textPaint,
                    staticLayout.getWidth(), staticLayout.getAlignment(), staticLayout.getSpacingMultiplier(),
                    staticLayout.getSpacingAdd(), true);

            // Check end of word indices for cut-off
            // This essentially acts as a 'break on white space' function
            boolean noCutOffs = true;
            if (endOfWordIndices != null) {
                for (int i = 0; i < staticLayout.getLineCount() && noCutOffs; i++) {
                    // -1 because it goes one past the last visible character
                    int lineVisibleEnd = staticLayout.getLineVisibleEnd(i) - 1;
                    // Check if the end to each line is the end of a word or quote
                    noCutOffs = noCutOffs && endOfWordIndices.contains(lineVisibleEnd);
                }
            }
            heightFixed = staticLayout.getHeight() <= maxHeight && noCutOffs;
        }
        return staticLayout;
    }

    private void strokeText(StaticLayout staticLayout, int color, float width, Canvas canvas) {
        TextPaint strokePaint = new TextPaint(staticLayout.getPaint());
        strokePaint.setColor(color);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(width);
        strokePaint.setStrokeJoin(Paint.Join.MITER);
        strokePaint.setStrokeCap(Paint.Cap.BUTT);
        StaticLayout strokeLayout = new StaticLayout(staticLayout.getText(), strokePaint,
                staticLayout.getWidth(), staticLayout.getAlignment(), staticLayout.getSpacingMultiplier(),
                staticLayout.getSpacingAdd(), true);
        strokeLayout.draw(canvas);
    }

    /**
     * This approach uses StackBlurring by Mario Klingemann as long as the device is running
     * an old OS or the Firebase config says so.
     *
     * Leaving the Firebase config in there in case a flurry of OOM errors results.
     *
     * @param blurRadius
     * @param backgroundImage
     * @return
     */
    private Bitmap generateBlurredBitmap(int blurRadius, Bitmap backgroundImage) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN
                || FirebaseRemoteConfig.getInstance().getBoolean(RemoteConfigConst.STACK_BLURRING)) {
            return stackBlur(backgroundImage, 1.0f, blurRadius);
        } else {
            return blurBitmap(backgroundImage, blurRadius);
        }
    }

    private Bitmap blurBitmap(Bitmap original, float radius) {
        Allocation overlayAllocation = null;
        Allocation outAllocation = null;
        ScriptIntrinsicBlur blur = null;
        Bitmap result = null;
        try {
            if (renderScript == null) {
                renderScript = RenderScript.create(LWQApplication.get());
            }
            overlayAllocation = Allocation.createFromBitmap(renderScript, original);
            outAllocation = Allocation.createTyped(renderScript, overlayAllocation.getType());
            result = Bitmap.createBitmap(original.getWidth(), original.getHeight(), original.getConfig());
            blur = ScriptIntrinsicBlur.create(renderScript, overlayAllocation.getElement());
            blur.setInput(overlayAllocation);
            blur.setRadius(radius);
            blur.forEach(outAllocation);
            outAllocation.copyTo(result);
        } finally {
            if (renderScript != null) {
                renderScript.destroy();
            }
            if (overlayAllocation != null) {
                overlayAllocation.destroy();
            }
            if (outAllocation != null) {
                outAllocation.destroy();
            }
            if (blur != null) {
                blur.destroy();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                RenderScript.releaseAllContexts();
            }
        }
        return result;
    }

    /**
     * Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>
     */
    public Bitmap stackBlur(Bitmap sentBitmap, float scale, int radius) {

        int width = Math.round(sentBitmap.getWidth() * scale);
        int height = Math.round(sentBitmap.getHeight() * scale);
        sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        Log.e("pix", w + " " + h + " " + pix.length);
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = ( 0xff000000 & pix[yi] ) | ( dv[rsum] << 16 ) | ( dv[gsum] << 8 ) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        Log.e("pix", w + " " + h + " " + pix.length);
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }

    private Palette.Swatch getSwatch() {
        return palette.getSwatches().get(swatchIndex);
    }

    private synchronized void increaseDrawRequests() {
        drawRequests++;
    }

    private synchronized void resetDrawRequests() {
        drawRequests = 0;
    }

    private synchronized int getDrawRequests() {
        return drawRequests;
    }
}


text:
#include <Uefi.h>

#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/QNCAccessLib.h>

/**
  The user Entry Point for Application. The user code starts with this function
  as the real entry point for the application.

  @param[in] ImageHandle    The firmware allocated handle for the EFI image.
  @param[in] SystemTable    A pointer to the EFI System Table.

  @retval EFI_SUCCESS       The entry point is executed successfully.
  @retval other             Some error occurs when executing this entry point.

**/
EFI_STATUS
EFIAPI
UefiMain (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  //
  // Set 'B_CFG_STICKY_RW_FORCE_RECOVERY' sticky bit so we know we need to do a recovery following warm reset
  //
  QNCAltPortWrite (
    QUARK_SCSS_SOC_UNIT_SB_PORT_ID,
    QUARK_SCSS_SOC_UNIT_CFG_STICKY_RW,
    QNCAltPortRead (QUARK_SCSS_SOC_UNIT_SB_PORT_ID, QUARK_SCSS_SOC_UNIT_CFG_STICKY_RW) | B_CFG_STICKY_RW_FORCE_RECOVERY
    );

  //
  // Do a warm reset
  //
  gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL);

  return EFI_SUCCESS;
}


text:
"""Illustrates a mixin which provides a generic association
using a single target table and a single association table,
referred to by all parent tables.  The association table
contains a "discriminator" column which determines what type of
parent object associates to each particular row in the association
table.

SQLAlchemy's single-table-inheritance feature is used
to target different association types.

This configuration attempts to simulate a so-called "generic foreign key"
as closely as possible without actually foregoing the use of real
foreign keys.   Unlike table-per-related and table-per-association,
it uses a fixed number of tables to serve any number of potential parent
objects, but is also slightly more complex.

"""
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import as_declarative
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session

@as_declarative()
class Base:
    """Base class which provides automated table name
    and surrogate primary key column.

    """

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    id = Column(Integer, primary_key=True)

class AddressAssociation(Base):
    """Associates a collection of Address objects
    with a particular parent.

    """

    __tablename__ = "address_association"

    discriminator = Column(String)
    """Refers to the type of parent."""

    __mapper_args__ = {"polymorphic_on": discriminator}

class Address(Base):
    """The Address class.

    This represents all address records in a
    single table.

    """

    association_id = Column(Integer, ForeignKey("address_association.id"))
    street = Column(String)
    city = Column(String)
    zip = Column(String)
    association = relationship("AddressAssociation", backref="addresses")

    parent = association_proxy("association", "parent")

    def __repr__(self):
        return "%s(street=%r, city=%r, zip=%r)" % (
            self.__class__.__name__,
            self.street,
            self.city,
            self.zip,
        )

class HasAddresses:
    """HasAddresses mixin, creates a relationship to
    the address_association table for each parent.

    """

    @declared_attr
    def address_association_id(cls):
        return Column(Integer, ForeignKey("address_association.id"))

    @declared_attr
    def address_association(cls):
        name = cls.__name__
        discriminator = name.lower()

        assoc_cls = type(
            "%sAddressAssociation" % name,
            (AddressAssociation,),
            dict(
                __tablename__=None,
                __mapper_args__={"polymorphic_identity": discriminator},
            ),
        )

        cls.addresses = association_proxy(
            "address_association",
            "addresses",
            creator=lambda addresses: assoc_cls(addresses=addresses),
        )
        return relationship(
            assoc_cls, backref=backref("parent", uselist=False)
        )

class Customer(HasAddresses, Base):
    name = Column(String)

class Supplier(HasAddresses, Base):
    company_name = Column(String)

engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)

session = Session(engine)

session.add_all(
    [
        Customer(
            name="customer 1",
            addresses=[
                Address(
                    street="123 anywhere street", city="New York", zip="10110"
                ),
                Address(
                    street="40 main street", city="San Francisco", zip="95732"
                ),
            ],
        ),
        Supplier(
            company_name="Ace Hammers",
            addresses=[
                Address(street="2569 west elm", city="Detroit", zip="56785")
            ],
        ),
    ]
)

session.commit()

for customer in session.query(Customer):
    for address in customer.addresses:
        print(address)
        print(address.parent)


text:
<?php

namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest;

use OCP\AppFramework\Http;
use OCP\Lock\ILockingProvider;

/**
 * Class DownloadTest
 *
 * @group DB
 *
 * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest
 */
class DownloadTest extends RequestTest {
	public function testDownload() {
		$user = $this->getUniqueID();
		$view = $this->setupUser($user, 'pass');

		$view->file_put_contents('foo.txt', 'bar');

		$response = $this->request($view, $user, 'pass', 'GET', '/foo.txt');
		$this->assertEquals(Http::STATUS_OK, $response->getStatus());
		$this->assertEquals(\stream_get_contents($response->getBody()), 'bar');
	}

	/**
	 */
	public function testDownloadWriteLocked() {
		$this->expectException(\OCA\DAV\Connector\Sabre\Exception\FileLocked::class);

		$user = $this->getUniqueID();
		$view = $this->setupUser($user, 'pass');

		$view->file_put_contents('foo.txt', 'bar');

		$view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE);

		$this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd');
	}

	public function testDownloadReadLocked() {
		$user = $this->getUniqueID();
		$view = $this->setupUser($user, 'pass');

		$view->file_put_contents('foo.txt', 'bar');

		$view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED);

		$response = $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd');
		$this->assertEquals(Http::STATUS_OK, $response->getStatus());
		$this->assertEquals(\stream_get_contents($response->getBody()), 'bar');
	}
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<go-plugin id="generic-artifactory" version="1">
<about>
    <name>Generic Artifactory poller plugin</name>
    <version>0.1.0</version>
    <target-go-version>14.1</target-go-version>
    <description>Plugin that polls an Artifactory repository</description>
    <vendor>
        <name>Deyan Varchev</name>
        <url>http://some_url/to/repository/README.md</url>
    </vendor>
</about>
</go-plugin>


text:
enum ContentRestriction {
  CONTENT_RESTRICTION_COPY  = 1 << 0,
  CONTENT_RESTRICTION_CUT   = 1 << 1,
  CONTENT_RESTRICTION_PASTE = 1 << 2,
  CONTENT_RESTRICTION_PRINT = 1 << 3,
  CONTENT_RESTRICTION_SAVE  = 1 << 4
};

#endif  // CHROME_COMMON_CONTENT_RESTRICTION_H_


text:
import re

from .operations import And, Or

class Clause(object):

    def __init__(self):
        super(Clause, self).__init__()

    def __call__(self, value):
        return False

    def _and(self, *clauses):
        return And(*([self] + list(clauses)))

    def _or(self, *clauses):
        return Or(*([self] + list(clauses)))

    def __str__(self):
        return '<always fails>'

    def __repr__(self):
        return str(self)

class typ(Clause):

    def __init__(self, t):
        super(typ, self).__init__()
        self._type = t

    def __call__(self, value):
        return type(value) == self._type

    def __str__(self):
        return "<type {}.{}>".format(self._type.__module__, self._type.__name__)

class typ_or_none(typ):

    def __call__(self, value):
        return value is None or super(typ_or_none, self).__call__(value)

    def __str__(self):
        return "<type {}.{} or None>".format(self._type.__module__, self._type.__name__)

class inst(typ):

    def __call__(self, value):
        return isinstance(value, self._type)

    def __str__(self):
        return "<instance of {}.{}>".format(self._type.__module__, self._type.__name__)

class inst_or_none(inst):

    def __call__(self, value):
        return value is None or super(inst_or_none, self).__call__(value)

    def __str__(self):
        return "<instance of {}.{} or None>".format(self._type.__module__, self._type.__name__)

class at_least(Clause):
    def __init__(self, value, inclusive=True):
        super(at_least, self).__init__()
        self.value = value
        self.inclusive = inclusive

    def __call__(self, value):
        if self.inclusive:
            return value >= self.value
        else:
            return value > self.value

    def __str__(self):
        return "<at least {} ({})>".format(self.value, 'inclusive' if self.inclusive else 'exclusive')

class at_most(Clause):
    def __init__(self, value, inclusive=True):
        super(at_most, self).__init__()
        self.value = value
        self.inclusive = inclusive

    def __call__(self, value):
        if self.inclusive:
            return value <= self.value
        else:
            return value < self.value

    def __str__(self):
        return "<at most {} ({})>".format(self.value, 'inclusive' if self.inclusive else 'exclusive')

class between(Clause):

    def __init__(self, lower, upper, lower_inc=True, upper_inc=False):
        super(between, self).__init__()
        self.lower = lower
        self.upper = upper
        self.lower_inc = lower_inc
        self.upper_inc = upper_inc

    def __call__(self, value):
        if self.lower_inc:
            if value < self.lower:
                return False
        elif value <= self.lower:
            return False

        if self.upper_inc:
            if value > self.upper:
                return False
        elif value >= self.upper:
            return False

        return True

    def __str__(self):
        return "<in range {}{}..{}{}>".format(
            '[' if self.lower_inc else '(',
            self.lower,
            self.upper,
            ']' if self.upper_inc else ')'
        )

class len_between(between):

    def __call__(self, value):
        return super(len_between, self).__call__(len(value))

    def __str__(self):
        return "<length in range {}{}..{}{}>".format(
            '[' if self.lower_inc else '(',
            self.lower,
            self.upper,
            ']' if self.upper_inc else ')'
        )

class regex(Clause):

    def __init__(self, r, entire_string=True, flags=0):
        super(regex, self).__init__()

        if entire_string:
            if not r.startswith('^'):
                r = '^' + r
            if not r.endswith('$') and not r.endswith('\\$'):
                r = r + '$'
        self.regex_string = r
        self.reg = re.compile(r, flags=flags)

    def __call__(self, value):
        return self.reg.match(value) is not None

    def __str__(self):
        return "<regex match '{}'>".format(self.regex_string)

class list_of(Clause):

    def __init__(self, clause):
        super(list_of, self).__init__()

        if not callable(clause):
            raise TypeError('Clause must be callable')

        self._clause = clause

    def __call__(self, value):
        if type(value) == list:
            for l in value:
                if not self._clause(l):
                    return False
            return True
        return False

    def __str__(self):
        return "<list of {!s}>".format(self._clause)

class dict_of(Clause):

    def __init__(self, clause1, clause2):
        super(dict_of, self).__init__()

        if not callable(clause1):
            raise TypeError('Clause 1 must be callable')

        if not callable(clause2):
            raise TypeError('Clause 2 must be callable')

        self._clause1 = clause1
        self._clause2 = clause2

    def __call__(self, value):
        if type(value) == dict:
            for k, v in value.items():
                if not self._clause1(k) or not self._clause2(v):
                    return False
            return True
        return False

    def __str__(self):
        return "<dict of {!s} -> {!s}>".format(self._clause1, self._clause2)

class list_of_typ(list_of):
    def __init__(self, t):
        super(list_of_typ, self).__init__(typ(t))

class list_of_inst(list_of):
    def __init__(self, t):
        super(list_of_inst, self).__init__(inst(t))

class dict_of_typ(dict_of):
    def __init__(self, t1, t2):
        super(dict_of_typ, self).__init__(typ(t1), typ(t2))

class dict_of_inst(dict_of):
    def __init__(self, t1, t2):
        super(dict_of_inst, self).__init__(inst(t1), inst(t2))


text:
package net.coderland.server.api.model.response;

import net.coderland.server.core.model.pojo.Stock;

import java.util.List;

/**
 * Author: zhangxin
 * Date:   15-12-24
 */
public class StockResponse {
    private Integer total;
    private Long since;
    private Long util;
    private List<Stock> data;

    public StockResponse() {
    }

    public StockResponse(Integer total, Long since, Long util, List<Stock> data) {
        this.total = total;
        this.since = since;
        this.util = util;
        this.data = data;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Long getSince() {
        return since;
    }

    public void setSince(Long since) {
        this.since = since;
    }

    public Long getUtil() {
        return util;
    }

    public void setUtil(Long util) {
        this.util = util;
    }

    public List<Stock> getData() {
        return data;
    }

    public void setData(List<Stock> data) {
        this.data = data;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <!--
  * Copyright 2010-2013, Sikuli.org
  * Released under the MIT License.
  *
  * RaiMan 2013
  -->

  <parent>
    <groupId>org.sikuli</groupId>
    <artifactId>SikuliX-Project</artifactId>
    <version>1.1.0</version>
    <relativePath>../</relativePath>
  </parent>

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.sikuli</groupId>
  <artifactId>SikuliX-Natives</artifactId>
  <version>1.1.0</version>

  <dependencies>
      <!-- for FileManager to load native libs -->
      <dependency>
          <groupId>org.sikuli</groupId>
          <artifactId>SikuliX-Basics</artifactId>
          <version>1.1.0</version>
      </dependency>
  </dependencies>

  <build>
    <defaultGoal>clean install</defaultGoal>
  </build>
</project>


text:
using namespace dcmtk::log4cplus;
using namespace dcmtk::log4cplus::helpers;

//////////////////////////////////////////////////////////////////////////////
// SocketBuffer ctors and dtor
//////////////////////////////////////////////////////////////////////////////

SocketBuffer::SocketBuffer(size_t maxsize_)
: maxsize(maxsize_),
  size(0),
  pos(0),
  buffer(new char[maxsize_])
{
}

SocketBuffer::SocketBuffer(const SocketBuffer& rhs)
    : LogLogUser ()
{
    copy(rhs);
}

SocketBuffer::~SocketBuffer()
{
    delete [] buffer;
}

SocketBuffer&
SocketBuffer::operator=(const SocketBuffer& rhs)
{
    if(&rhs != this) {
        delete buffer;
        copy(rhs);
    }

    return *this;
}

void
SocketBuffer::copy(const SocketBuffer& r)
{
    SocketBuffer& rhs = OFconst_cast(SocketBuffer&, r);
    maxsize = rhs.maxsize;
    size = rhs.size;
    pos = rhs.pos;
    buffer = rhs.buffer;

    rhs.maxsize = 0;
    rhs.size = 0;
    rhs.pos = 0;
    rhs.buffer = 0;
}

//////////////////////////////////////////////////////////////////////////////
// SocketBuffer methods
//////////////////////////////////////////////////////////////////////////////

unsigned char
SocketBuffer::readByte()
{
    if(pos >= maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readByte()- end of buffer reached"));
        return 0;
    }
    else if((pos + sizeof(unsigned char)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readByte()- Attempt to read beyond end of buffer"));
        return 0;
    }

    unsigned char ret = *(OFreinterpret_cast(unsigned char*, &buffer[pos]));
    pos += sizeof(unsigned char);

    return ret;
}

unsigned short
SocketBuffer::readShort()
{
    if(pos >= maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readShort()- end of buffer reached"));
        return 0;
    }
    else if((pos + sizeof(unsigned short)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readShort()- Attempt to read beyond end of buffer"));
        return 0;
    }

    unsigned short ret;
    memcpy(&ret, buffer + pos, sizeof(ret));
    ret = ntohs(ret);
    pos += sizeof(unsigned short);

    return ret;
}

unsigned int
SocketBuffer::readInt()
{
    if(pos >= maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readInt()- end of buffer reached"));
        return 0;
    }
    else if((pos + sizeof(unsigned int)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readInt()- Attempt to read beyond end of buffer"));
        return 0;
    }

    unsigned int ret;
    memcpy (&ret, buffer + pos, sizeof(ret));
    ret = ntohl(ret);
    pos += sizeof(unsigned int);

    return ret;
}

tstring
SocketBuffer::readString(unsigned char sizeOfChar)
{
    size_t strlen = readInt();
    size_t bufferLen = strlen * sizeOfChar;

    if(strlen == 0) {
        return tstring();
    }
    if(pos > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readString()- end of buffer reached"));
        return tstring();
    }

    if((pos + bufferLen) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readString()- Attempt to read beyond end of buffer"));
        bufferLen = (maxsize - 1) - pos;
        strlen = bufferLen / sizeOfChar;
    }

    if(sizeOfChar == 1) {
        tstring ret(&buffer[pos], strlen);
        pos += strlen;
        return ret;
    }
    else if(sizeOfChar == 2) {
        tstring ret;
        for(tstring::size_type i=0; i<strlen; ++i) {
            unsigned short tmp = readShort();
            ret += OFstatic_cast(char, tmp < 256 ? tmp : ' ');
        }
        return ret;
    }
    else {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::readString()- Invalid sizeOfChar!!!!"));
    }

    return tstring();
}

void
SocketBuffer::appendByte(unsigned char val)
{
    if((pos + sizeof(unsigned char)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendByte()- Attempt to write beyond end of buffer"));
        return;
    }

    *(OFreinterpret_cast(unsigned char*, &buffer[pos])) = val;
    pos += sizeof(unsigned char);
    size = pos;
}

void
SocketBuffer::appendShort(unsigned short val)
{
    if((pos + sizeof(unsigned short)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendShort()- Attempt to write beyond end of buffer"));
        return;
    }

    unsigned short s = htons(val);
    memcpy(buffer + pos, &s, sizeof (s));
    pos += sizeof(s);
    size = pos;
}

void
SocketBuffer::appendInt(unsigned int val)
{
    if((pos + sizeof(unsigned int)) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendInt()- Attempt to write beyond end of buffer"));
        return;
    }

    int i = htonl(val);
    memcpy(buffer + pos, &i, sizeof (i));
    pos += sizeof(i);
    size = pos;
}

void
SocketBuffer::appendSize_t(size_t val)
{
    if ((pos + sizeof(unsigned)) > maxsize)
    {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendInt(size_t)- ")
            DCMTK_LOG4CPLUS_TEXT("Attempt to write beyond end of buffer"));
        return;
    }
    //if (val > (STD_NAMESPACE numeric_limits<unsigned>::max) ())
    // htonl expects a 32 bit value
    if (val > UINT_MAX)
    {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendInt(size_t)-")
            DCMTK_LOG4CPLUS_TEXT(" Attempt to write value greater than")
            DCMTK_LOG4CPLUS_TEXT(" STD_NAMESPACE numeric_limits<unsigned>::max"));
        return;
    }

    unsigned st = htonl(OFstatic_cast(unsigned, val));
    memcpy(buffer + pos, &st, sizeof(st));
    pos += sizeof(st);
    size = pos;
}

void
SocketBuffer::appendString(const tstring& str)
{
    size_t strlen = str.length();

    if((pos + sizeof(unsigned int) + strlen) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendString()- Attempt to write beyond end of buffer"));
        return;
    }

    appendInt(OFstatic_cast(unsigned, strlen));
    memcpy(&buffer[pos], str.data(), strlen);
    pos += strlen;
    size = pos;
}

void
SocketBuffer::appendBuffer(const SocketBuffer& buf)
{
    if((pos + buf.getSize()) > maxsize) {
        getLogLog().error(DCMTK_LOG4CPLUS_TEXT("SocketBuffer::appendBuffer()- Attempt to write beyond end of buffer"));
        return;
    }

    memcpy(&buffer[pos], buf.buffer, buf.getSize());
    pos += buf.getSize();
    size = pos;
}


text:
var magnitudes;
// an array for depth
var depths;
// an array for lat & long
var latitudes, longitudes;

// minimum and maximum values for magnitude and depth
var magnitudeMin, magnitudeMax;
var depthMin, depthMax;

// table as the data set
var table;

// my leaflet.js map
var mymap;

function preload() {
  //my table is comma separated value "csv"
  //and has a header specifying the columns labels
  table = loadTable("assets/significant_month_simple.csv", "csv", "header");
}

function setup() {
  // LEAFLET CODE
  // create your own map
  mymap = L.map('mapid').setView([51.505, -0.09], 2);

  // get the tiles you need. Don't have to touch this
  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
      'CC-BY-SA, ' +
      'Imagery © Mapbox',
    id: 'mapbox.streets'
  }).addTo(mymap);

  drawDataPoints();
}

function drawDataPoints(){
  strokeWeight(5);
  stroke(255,0,0);

  // get the two arrays of interest: depth and magnitude
  depths = table.getColumn("depth");
  magnitudes = table.getColumn("mag");
  latitudes = table.getColumn("latitude");
  longitudes = table.getColumn("longitude");

  // println(longitudes);

  // get minimum and maximum values for both
  magnitudeMin = 0.0;
  magnitudeMax = getColumnMax("mag");

  depthMin = 0.0;
  depthMax = getColumnMax("depth");

  // cycle through array
  for(var i=0; i<depths.length; i++){
    var circle = L.circle([latitudes[i], longitudes[i]], {
      color: 'red',
      fillColor: '#f03',
      fillOpacity: 0.5,
      radius: magnitudes[i] * 40000
    }).addTo(mymap);
}
}

// get the maximum value within a column
function getColumnMax(columnName){
  var col = table.getColumn(columnName);
  // m is the maximum value
  // purposefully start this very low
  var m = 0.0;
  for(var i =0; i< col.length; i++){
    // each value within the column
    // that is higher than m replaces the previous value
    if(float(col[i])>m){
      m = float(col[i]);
    }
  }
  // after going through all rows, return the max value
  return m;
}


text: google-site-verification: google011698e3df631b84.html


text:
<?php

namespace Untitled\Middleware;

use Slim\Middleware;

class HttpAuthentication extends Middleware
{
	public function call()
	{
		$request = $this->app->request();
		$response = $this->app->response();
		$authUser = $request->headers('PHP_AUTH_USER');
		$authPass = $request->headers('PHP_AUTH_PW');

		// If a username is passed in, verify that it is valid.
		if (!empty($authUser)) {

			global $em;
			$identity = $em->getRepository('\Users\Entity\Application')->find($authUser);

			if ($identity) {
				$this->next->call();
			}
		}

		if (!$identity) {
			$response->status(401);
			$response->header('WWW-Authenticate', 'Basic realm="Authentication required."');
		}
	}
}


text:
const int ACE_UNKNOWN_ERROR = -1;
const int ACE_SUCCESS = 0;
const int ACE_ERR_WRONG_NUMBER_OF_ARGUMENTS = 1;
const int ACE_ERR_NO_SOURCE_DIR = 2;
const int ACE_ERR_NO_TARGET_DIR = 3;


text:
package com.yattatech.dbtc.activity.async;

import twitter4j.auth.RequestToken;
import android.content.Intent;
import android.os.AsyncTask;
import com.yattatech.dbtc.Constants;
import com.yattatech.dbtc.R;
import com.yattatech.dbtc.activity.GenericFragmentActivity;
import com.yattatech.dbtc.activity.TwitterAuthenticatorScreen;
import com.yattatech.dbtc.activity.TwitterWriteScreen;
import com.yattatech.dbtc.log.Debug;
import com.yattatech.dbtc.util.TwitterUtil;

/**
 * AsyncTask responsible for loging into Twitter
 *
 * @author Adriano Braga Alencar (adrianobragaalencar@gmail.com)
 *
 */
public final class TwitterAuthAsyncTask extends AsyncTask<Void, Void, Integer> {

	private static final String TAG            = "TwitterAuthAsyncTask";
	private static final Integer NO_CONNECTION = Integer.valueOf(0);
	private static final Integer FAILED        = Integer.valueOf(1);
	private static final Integer SUCCESS       = Integer.valueOf(2);
	private final GenericFragmentActivity mActivity;

	public TwitterAuthAsyncTask(GenericFragmentActivity activity) {
		mActivity = activity;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Integer doInBackground(Void... params) {
		Integer result = SUCCESS;
		try {
			if (!mActivity.isConnected()) {
				result = NO_CONNECTION;
			} else if (GenericFragmentActivity.FACADE.isTwitterLogged()) {
				mActivity.startNewActivity(TwitterWriteScreen.class);
			} else {
				TwitterUtil.invalidRequestToken();
				final RequestToken requestToken = TwitterUtil.getRequestToken();
				final String authUrl            = requestToken.getAuthorizationURL();
				final Intent intent             = new Intent(mActivity, TwitterAuthenticatorScreen.class);
				intent.putExtra(Constants.TWITTER_URL,           authUrl);
				intent.putExtra(Constants.TWITTER_REQUEST_TOKEN, requestToken);
				mActivity.startActivityForResult(intent, Constants.TWITTER_SUCCCESS);
			}
		} catch (Exception e) {
			Debug.e(TAG, "Failed:", e);
			result = FAILED;
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(Integer result) {
		if (result == NO_CONNECTION) {
			mActivity.showMessage(R.string.lab_no_connection);
		} else if (result == FAILED) {
			mActivity.showMessage(R.string.lab_twitter_unknow);
		} else {
			Debug.d(TAG, "TwitterAuthAsyncTask success");
		}
	}
}


text:
import { EnvConfig } from '../../../../../tools/env/env-config.interface';

export const Config: EnvConfig = JSON.parse('<%= ENV_CONFIG %>');


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

namespace ExceptionAnalyzer
{
    /// <summary>
    /// Detects `catch` blocks that swallow an exception.
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public sealed class GenericCatchBlockAnalyzer : DiagnosticAnalyzer
    {
        // Catch is not empty, `catch` or `catch(Exception)` and some return statement exists. Add hint!
        // show hint on the return itself
        public const string DiagnosticId = "EA002";
        internal const string Title = "Swallow exceptions considered harmful";
        internal const string MessageFormat = "Catching everything considered harmful!\r\n Are you not curious at all about exception type?";
        internal const string Category = "CodeSmell";

        internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

        public override void Initialize(AnalysisContext context)
        {
            context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.CatchClause);
        }

        // Called when Roslyn encounters a catch clause.
        private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
        {
            var catchBlock = context.Node as CatchClauseSyntax;

            // Current analyzer is interested in "catch {}" blocks without exception declarations
            if (catchBlock == null || catchBlock.Declaration != null)
            {
                return;
            }

            StatementSyntax syntax = catchBlock.Block;
            var controlFlow = context.SemanticModel.AnalyzeControlFlow(syntax);

            // Warn if end block is reachable or there is a return statement
            if (controlFlow.EndPointIsReachable || controlFlow.ReturnStatements.Length != 0)
            {
                // Block is empty, create and report diagnostic warning.
                var diagnostic = Diagnostic.Create(Rule, catchBlock.CatchKeyword.GetLocation());
                context.ReportDiagnostic(diagnostic);
            }
        }
    }
}


text:
module Gws::StaffRecord::Yearly
  extend ActiveSupport::Concern
  extend SS::Translation

  included do
    field :year_code, type: String
    field :year_name, type: String

    belongs_to :year, class_name: 'Gws::StaffRecord::Year'

    permit_params :year_id

    validates :year_id, presence: true
    validates :year_code, presence: true
    validates :year_name, presence: true

    before_validation :set_year_name, if: -> { year_id.present? && year_id_changed? }
  end

  def year_options
    Gws::StaffRecord::Year.site(@cur_site || site).
      map { |c| [c.name_with_code, c.id] }
  end

  private

  def set_year_name
    item = Gws::StaffRecord::Year.where(site_id: site_id, id: year_id).first
    self.year_code = item ? item.code : nil
    self.year_name = item ? item.name : nil
  end
end


text:
package org.apache.jena.testing_framework;

import org.apache.jena.graph.impl.TripleStore;

/**
 * Creates the graph for testing
 *
 */
public interface ITripleStoreProducer {

	/**
	 * Returns a TripleStore to take part in the test. Must be overridden in a
	 * subclass.
	 *
	 * @return The TripleStore implementation to test.
	 */
	public abstract TripleStore newTripleStore();
}


text:
const mocks = require('../mocks/mocks');
const mockPackageFactory = require('../mocks/mockPackage');
const Dgeni = require('dgeni');
const gitDataFactory = require('./gitData');

describe("gitData", () => {
  let gitData, mockPackage;

  beforeEach(() => {
    mockPackage = mockPackageFactory()
      .factory(gitDataFactory);

    const dgeni = new Dgeni([mockPackage]);

    const injector = dgeni.configureInjector();
    gitData = injector.get('gitData');

  });

  describe("version", () => {
    it("should be set to currentVersion of versionInfo", () => {
      expect(gitData.version).toEqual(mocks.versionInfo.currentVersion);
    });
  });

  describe("versions", () => {
    it("should be set to previousVersions of versionInfo", () => {
      expect(gitData.versions).toEqual(mocks.versionInfo.previousVersions);
    });
  });

  describe("info", () => {
    it("should be set to gitRepoInfo of versionInfo", () => {
      expect(gitData.info).toEqual(mocks.versionInfo.gitRepoInfo);
    });
  });
});


text:
/*
 * Project Euler problem #36
 *
 *
 * The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
 *
 * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
 *
 * (Please note that the palindromic number, in either base, may not include leading zeros.)
 *
 */

#include <iostream>
#include <bitset>
#include <vector>

typedef std::vector<unsigned char> DigitVector;
static unsigned int buildPalindrome(const DigitVector &base, int halfWidth, int oddLength)
{
    int num = base[0];
    size_t middleDigit = halfWidth + oddLength - 1;
    for (int i = 1; i <= middleDigit; ++i)
    {
        num *= 10;
        num += base[i];
    }

    for (int i = 0; i < halfWidth; ++i)
    {
        num *= 10;
        num += base[middleDigit - i - oddLength];
    }

    return num;
}
static bool updatePalindromeBase(DigitVector &base)
{
    size_t index = base.size();
    for (DigitVector::reverse_iterator it = base.rbegin(); it != base.rend(); ++it)
    {
        --index;
        if (*it < 9)
        {
            *it += 1 + (index == 0); // skip even for maximum digit
            return true;
        }

        *it = 0;
    }
    return false;
}

int isBinaryPalindrome(unsigned int value)
{
    size_t bitLength = sizeof(value) * 8;
    for (; bitLength != 0 && !(value >> (bitLength - 1)); --bitLength);

    for (size_t i = 0; i < (bitLength / 2); ++i)
    {
        int h = value >> (bitLength - i - 1);
        int l = value >> i;
        bool equal = ((h ^ l) & 1) == 0;
        if (!equal)
        {
            return false;
        }
    }
    return true;
}

unsigned int getBiPalindromesSum(unsigned int length)
{
    int halfWidth = length / 2;
    int oddLength = (length & 1);

    DigitVector base;
    base.reserve(halfWidth + oddLength);
    base.push_back(1);
    base.resize(base.capacity(), 0);

    unsigned int sum = 0;
    bool hasNext = true;
    do
    {
        unsigned int num = buildPalindrome(base, halfWidth, oddLength);

        if (isBinaryPalindrome(num))
        {
            sum += num;
            std::cout << num << " b"
                      << std::bitset<sizeof(num) * 8>(num) << std::endl;
        }

        hasNext = updatePalindromeBase(base);
    }
    while (hasNext);

    return sum;
}

int main(int, const char *[])
{
    unsigned int result = 0;
    for (int palindromLength = 1;  palindromLength < 7; ++palindromLength)
    {
        std::cout << "Length: " << palindromLength << std::endl;
        result += getBiPalindromesSum(palindromLength);
    }
    std::cout << std::endl << "result: " << result << std::endl;
    return 0;
}