text:
package org.gradle.api.internal.tasks.compile;

import org.gradle.api.AntBuilder;
import org.gradle.api.internal.file.DefaultTemporaryFileProvider;
import org.gradle.api.internal.file.TemporaryFileProvider;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.tasks.compile.daemon.CompilerDaemonManager;
import org.gradle.api.internal.tasks.compile.daemon.DaemonJavaCompiler;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.compile.CompileOptions;
import org.gradle.internal.Factory;

import java.io.File;
import java.io.Serializable;

public class DefaultJavaCompilerFactory implements JavaCompilerFactory {
    private final static Logger LOGGER = Logging.getLogger(DefaultJavaCompilerFactory.class);

    private final ProjectInternal project;
    private final Factory<AntBuilder> antBuilderFactory;
    private final JavaCompilerFactory inProcessCompilerFactory;
    private final CompilerDaemonManager compilerDaemonManager;
    private boolean jointCompilation;

    public DefaultJavaCompilerFactory(ProjectInternal project, Factory<AntBuilder> antBuilderFactory, JavaCompilerFactory inProcessCompilerFactory, CompilerDaemonManager compilerDaemonManager){
        this.project = project;
        this.antBuilderFactory = antBuilderFactory;
        this.inProcessCompilerFactory = inProcessCompilerFactory;
        this.compilerDaemonManager = compilerDaemonManager;
    }

    /**
     * If true, the Java compiler to be created is used for joint compilation
     * together with another language's compiler in the compiler daemon.
     * In that case, the other language's normalizing and daemon compilers should be used.
     */
    public void setJointCompilation(boolean flag) {
        jointCompilation = flag;
    }

    public Compiler<JavaCompileSpec> create(CompileOptions options) {
        fallBackToAntIfNecessary(options);

        if (options.isUseAnt()) {
            return new AntJavaCompiler(antBuilderFactory);
        }

        Compiler<JavaCompileSpec> result = createTargetCompiler(options);
        if (!jointCompilation) {
            result = new NormalizingJavaCompiler(result);
        }
        return result;
    }

    private void fallBackToAntIfNecessary(CompileOptions options) {
        if (options.isUseAnt()) { return; }

        if (options.getCompiler() != null) {
            LOGGER.warn("Falling back to Ant javac task ('CompileOptions.useAnt = true') because 'CompileOptions.compiler' is set.");
            options.setUseAnt(true);
        }
    }

    private Compiler<JavaCompileSpec> createTargetCompiler(CompileOptions options) {
        if (options.isFork() && options.getForkOptions().getExecutable() != null) {
            return new CommandLineJavaCompiler(createSerializableTempFileProvider(), project.getProjectDir());
        }

        Compiler<JavaCompileSpec> compiler = inProcessCompilerFactory.create(options);
        if (options.isFork() && !jointCompilation) {
            return new DaemonJavaCompiler(project, compiler, compilerDaemonManager);
        }

        return compiler;
    }

    private TemporaryFileProvider createSerializableTempFileProvider() {
        return new DefaultTemporaryFileProvider(new FileFactory(project.getBuildDir()));
    }

    private static class FileFactory implements Factory<File>, Serializable {
        private final File file;

        private FileFactory(File file) {
            this.file = file;
        }

        public File create() {
            return file;
        }
    }
}


text:
package com.focusit.jsflight.player.scenario;

import com.focusit.jsflight.player.cli.config.IConfig;
import com.focusit.jsflight.player.configurations.CommonConfiguration;
import com.focusit.jsflight.player.configurations.Configuration;
import com.focusit.jsflight.player.configurations.ScriptsConfiguration;
import com.focusit.jsflight.player.constants.EventConstants;
import com.focusit.jsflight.player.constants.EventType;
import com.focusit.jsflight.player.input.EventsParser;
import com.focusit.jsflight.player.input.FileInput;
import com.focusit.jsflight.player.script.PlayerScriptProcessor;
import com.focusit.jsflight.script.player.PlayerContext;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Recorded scenario encapsulation: parses file, plays the scenario by step, modifies the scenario, saves to a disk.
 *
 * @author Denis V. Kirpichenkov
 */
public class UserScenario
{
    private static final Logger LOG = LoggerFactory.getLogger(UserScenario.class);

    private static final Set<String> ALLOWED_EVENT_TYPES = new HashSet<>(
            Arrays.asList(EventType.CLICK, EventType.KEY_PRESS, EventType.KEY_UP, EventType.KEY_DOWN,
                    EventType.SCROLL_EMULATION, EventType.MOUSE_WHEEL, EventType.MOUSE_DOWN, EventType.SCRIPT));
    private static final ConcurrentHashMap<String, JSONObject> lastEvents = new ConcurrentHashMap<>();
    private volatile int position = 0;
    private List<JSONObject> events = new ArrayList<>();
    private String preProcessScenarioScript;
    private PlayerContext context = new PlayerContext();
    private Configuration configuration = new Configuration();

    public static String getTagForEvent(JSONObject event)
    {
        return event.has(EventConstants.TAG) ? event.getString(EventConstants.TAG) : "null";
    }

    public static String getTargetForEvent(JSONObject event)
    {
        if (event.has(EventConstants.SECOND_TARGET)
                && !StringUtils.isBlank(event.getString(EventConstants.SECOND_TARGET)))
        {
            return event.getString(EventConstants.SECOND_TARGET);
        }
        if (!event.has(EventConstants.FIRST_TARGET))
        {
            return "";
        }
        JSONArray array = event.getJSONArray(EventConstants.FIRST_TARGET);
        if (array.isNull(0))
        {
            return "";
        }

        return array.getJSONObject(0).getString("getxp");
    }

    public void initFromConfig(IConfig config)
    {
        CommonConfiguration commonConfiguration = getConfiguration().getCommonConfiguration();
        commonConfiguration.setPathToBrowserExecutable(config.getPathToBrowserExecutable());
        commonConfiguration.setMakeShots(config.shouldMakeScreenshots());
        commonConfiguration
                .setAsyncRequestsCompletedTimeoutInSeconds(config.getAsyncRequestsCompletedTimeoutInSeconds());
        commonConfiguration.setProxyHost(config.getProxyHost());
        commonConfiguration.setProxyPort(config.getProxyPort());
        commonConfiguration.setScreenshotsDirectory(config.getScreenshotsDirectory());
        commonConfiguration.setBrowserType(config.getBrowserType());
        commonConfiguration.setUseRandomChars(config.shouldUseRandomChars());
        commonConfiguration.setFormOrDialogXpath(config.getKeepBrowserXpath());
        commonConfiguration.setUiShownTimeoutSeconds(config.getUiShownTimeoutInSeconds());
        commonConfiguration.setIntervalBetweenUiChecksMs(config.getIntervalBetweenUiChecksInMs());
        commonConfiguration.setTargetBaseUrl(config.getTargetBaseUrl());
        commonConfiguration.setMaxRequestsPerScenario(config.getMaximumCountOfRequestPerJMeterScenario());
        commonConfiguration.setShouldCloseWebDriversOnError(config.shouldCloseWebDriversOnError());

        ScriptsConfiguration scriptsConfiguration = getConfiguration().getScriptsConfiguration();
        scriptsConfiguration.setUrlReplacementScript(readFile(config.getPathToUrlReplacementScript()));
        scriptsConfiguration.setConditionalWaitScript(readFile(config.getPathToConditionalWaitScript()));
        scriptsConfiguration.setDuplicationHandlerScript(readFile(config.getPathToDuplicateHandlerScript()));
        scriptsConfiguration.setElementLookupScript(readFile(config.getPathToElementLookupScript()));
        scriptsConfiguration.setIsBrowserHaveErrorScript(readFile(config.getPathToIsBrowserHaveErrorScript()));
        scriptsConfiguration.setIsSelectElementScript(readFile(config.getPathToIsSelectElementScript()));
        scriptsConfiguration.setIsUiShownScript(readFile(config.getPathToIsUiShownScript()));
        scriptsConfiguration.setScenarioProcessorScript(readFile(config.getPathToJmeterScenarioProcessorScript()));
        scriptsConfiguration.setStepProcessorScript(readFile(config.getPathToJmeterStepProcessorScript()));
        scriptsConfiguration.setScriptEventHandlerScript(readFile(config.getPathToScriptEventHandlerScript()));
        scriptsConfiguration.setShouldSkipKeyboardScript(readFile(config.getPathToShouldSkipKeyboardScript()));
        scriptsConfiguration
                .setIsAsyncRequestsCompletedScript(readFile(config.getPathToIsAsyncRequestsCompletedScript()));

        getConfiguration().getWebConfiguration().setSelectXpath(config.getSelectXpath());

        setPreProcessScenarioScript(readFile(config.getPathToPreProcessorScript()));

        getConfiguration().loadDefaults();
    }

    @Nullable
    private String readFile(@Nullable String path)
    {
        if (path == null)
        {
            LOG.warn("The path was null");
            return null;
        }
        try
        {
            return new String(Files.readAllBytes(Paths.get(path.trim())), StandardCharsets.UTF_8);
        }
        catch (Throwable e)
        {
            LOG.error("Tried to read file {}, but exception occurred", path);
            LOG.error(e.getMessage(), e);
            return null;
        }
    }

    public void checkStep(int position)
    {
        LOG.warn("checkStep method invoked, but wasn't implemented");
    }

    public void copyStep(int position)
    {
        String event = events.get(position).toString();
        JSONObject clone = new JSONObject(event);
        events.add(position, clone);
    }

    public void deleteStep(int position)
    {
        events.remove(position);
    }

    public Configuration getConfiguration()
    {
        return configuration;
    }

    public void setConfiguration(Configuration configuration)
    {
        this.configuration = configuration;
    }

    public PlayerContext getContext()
    {
        return context;
    }

    public int getPosition()
    {
        return position;
    }

    public void setPosition(int position)
    {
        this.position = position;
    }

    @Nullable
    public JSONObject getPrevEvent(JSONObject event)
    {
        return lastEvents.get(getTagForEvent(event));
    }

    public void resetPrevEvent(JSONObject event)
    {
        lastEvents.remove(getTagForEvent(event));
    }

    public String getScenarioFilename()
    {
        return "";
    }

    public JSONObject getStepAt(int position)
    {
        return events.get(position);
    }

    public int getStepsCount()
    {
        return events.size();
    }

    public static boolean isEventBad(JSONObject event)
    {
        return !isEventOfType(event, EventType.SCRIPT) && isFieldOfEventIsNull(event, EventConstants.TARGET);
    }

    private static boolean isFieldOfEventIsNull(JSONObject event, String filedName)
    {
        return !event.has(filedName) || event.get(filedName) == null || event.get(filedName) == JSONObject.NULL;
    }

    private static boolean isEventOfType(JSONObject event, String type)
    {
        return type.equalsIgnoreCase(event.getString(EventConstants.TYPE));
    }

    public static boolean isEventIgnored(JSONObject event)
    {
        return !ALLOWED_EVENT_TYPES.contains(event.getString(EventConstants.TYPE));
    }

    public boolean isStepDuplicates(String script, JSONObject event)
    {
        JSONObject prev = getPrevEvent(event);

        return prev != null && new PlayerScriptProcessor(this).executeDuplicateHandlerScript(script, event, prev);

    }

    public void moveToNextStep()
    {
        setPosition(Math.min(getPosition() + 1, getStepsCount()));
    }

    public void parse(String filename) throws IOException
    {
        events.clear();
        events.addAll(EventsParser.parse(FileInput.getContent(filename)));
        context.reset();
    }

    public void parseNextLine(String filename) throws IOException
    {
        events.clear();
        List<JSONObject> result = EventsParser.parse(FileInput.getLineContent(filename));
        if (result != null)
        {
            events.addAll(result);
        }
    }

    public long getEventsDuration()
    {
        return getStepAt(Math.max(0, getStepsCount() - 1)).getBigDecimal(EventConstants.TIMESTAMP).longValue()
                - getStepAt(0).getBigDecimal(EventConstants.TIMESTAMP).longValue();
    }

    public void preProcessScenario()
    {
        if (!StringUtils.isBlank(preProcessScenarioScript))
        {
            new PlayerScriptProcessor(this).preProcessScenario(preProcessScenarioScript, events);
        }
    }

    public void moveToPreviousStep()
    {
        setPosition(Math.max(0, getPosition() - 1));
    }

    public void rewind()
    {
        context.reset();
        setPosition(0);
    }

    public void runPostProcessor(String script)
    {
        PlayerScriptProcessor engine = new PlayerScriptProcessor(this);
        engine.testPostProcess(script, events);
    }

    public void saveScenario(String filename) throws IOException
    {
        FileInput.saveEvents(events, filename);
    }

    public void setPreProcessScenarioScript(String preProcessScenarioScript)
    {
        this.preProcessScenarioScript = preProcessScenarioScript;
    }

    public void skip()
    {
        setPosition(getPosition() + 1);
    }

    public void updateEvent(JSONObject event)
    {
        lastEvents.put(getTagForEvent(event), event);
    }

    public void updateStep(int position, JSONObject event)
    {
        events.set(position, event);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {
  DEBUGGING,
  IS_DEV,
} from '@ncigdc/utils/constants';

type TConsoleDebug = (log: string) => void;

const consoleDebug: TConsoleDebug = log => {
  if (IS_DEV || DEBUGGING) {
    console.log(log);
  }
};

export default consoleDebug;


text:
package uk.ac.imperial.doc.pctmc.syntax;

import org.antlr.runtime.IntStream;
import org.antlr.runtime.RecognitionException;

@SuppressWarnings("serial")
public class CustomRecognitionException extends RecognitionException {
	private String message;

	public CustomRecognitionException(IntStream input, String message) {
		super(input);
		this.message = message;
	}

	public String getMessage() {
		return message;
	}
}


text:
package org.redisson;

import java.util.Collection;

import org.redisson.client.RedisClient;

/**
 *
 * @author Nikita Koksharov
 *
 */
public interface ScanResult<R> {

    void setRedisClient(RedisClient addr);

    RedisClient getRedisClient();

    long getPos();

    Collection<R> getValues();

}


text:
package ru.icc.cells.lod.ann;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }

    public static void test () {
        System.out.println( "It'a beaver time!");
    };
}


text:
#ifndef DAISELABS_THREAD_QUEUE_H
#define DAISELABS_THREAD_QUEUE_H

#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <queue>
#include <utility>

namespace daiselabs {
namespace thread {

template<typename T>
class queue {
public:
    typedef std::shared_ptr<T> item_ptr_type;

    queue(const queue&) = delete;
    queue &operator=(const queue &) = delete;

    queue() : closed_(false), cond_(), mutex_(), queue_() {}
    ~queue() = default;

    void put(item_ptr_type item, bool notify_all = false) {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            queue_.emplace(item);
        }

        if (notify_all) {
            cond_.notify_all();
        } else {
            cond_.notify_one();
        }
    }

    item_ptr_type get(int timeout_millis) {
        std::unique_lock<std::mutex> lock(mutex_);
        if (timeout_millis <= 0) {
            cond_.wait(lock, [this]{ return (closed_ || !queue_.empty()); });
        } else {
            // wait_for returns false when timed out
            if (cond_.wait_for(lock, std::chrono::milliseconds(timeout_millis), [this]{ return (closed_ || !queue_.empty()); }) == false) {
                return nullptr;
            }
        }

        if (closed_) {
            return nullptr;
        }

        auto item = queue_.front();
        queue_.pop();
        return item;
    }

    bool is_closed() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return closed_;
    }

    void close() {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            closed_ = true;
        }

        cond_.notify_all();
    }
private:
    bool closed_;
    std::condition_variable cond_;
    mutable std::mutex mutex_;
    std::queue<item_ptr_type> queue_;
};

} /* namespace thread */
} /* namespace daiselabs */

#endif /* DAISELABS_THREAD_QUEUE_H */


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from os import path

README = path.abspath(path.join(path.dirname(__file__), 'README.rst'))

setup(
      name='python-zeromq-log',
      version='0.0.1',
      description='ZeroMQ pub/sub logging handler for python',
      long_description=open(README).read(),
      author='Richard Bucker',
      author_email='richard@bucker.net',
      url='https://github.com/rbucker881/python-zeromq-log',
      packages=['zeromqlog'],
      license='MIT',
      install_requires=['pyzmq','simplejson']
)


text:
package gov.nasa.ensemble.core.plan.editor.view.template.operations;

import gov.nasa.ensemble.core.model.plan.CommonMember;
import gov.nasa.ensemble.core.model.plan.DiffIdGenerator;
import gov.nasa.ensemble.core.model.plan.EPlan;
import gov.nasa.ensemble.core.model.plan.EPlanChild;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.PlanPackage;
import gov.nasa.ensemble.core.plan.editor.view.template.TemplatePlanUtils;
import gov.nasa.ensemble.emf.transaction.TransactionUtils;

import java.util.ArrayList;
import java.util.Collection;

public class TemplatePlanDuplicateOperation extends TemplatePlanOperation {

	/** Passed into the constructor. A collection of plan elements to be duplicated. */
	private Collection<EPlanElement> elementsToDuplicate;

	/** The duplicate of the collection passed into the constructor. Initially empty, and filled by execute(). */
	private Collection<EPlanElement> duplicates;

	/**
	 * Decorate by storing the list of elements to duplicate.
	 * @param label an immutable string label that can be fetched; may be null
	 * @param templatePlan stored and gettable, but otherwise ignored
	 * @param elementsToDuplicate a list of plan elements to duplicate; may be empty but must not be null
	 */
	public TemplatePlanDuplicateOperation(String label, EPlan templatePlan, Collection<EPlanElement> elementsToDuplicate) {
		super(label, templatePlan);
		this.elementsToDuplicate = elementsToDuplicate;
		duplicates = new ArrayList<EPlanElement>();
	}

	/**
	 * Execute the duplicate operation. For each plan element in the list passed into the constructor, make a
	 * copy and give prefix "copy of" to the original's name. Change the DiffId of the common member. Add
	 * the plan element to the list of duplicates. If successful, the template plan is flagged as dirty.
	 * Note: there is no check that elementsToDuplicate is not null.
	 */
	@Override
	public void execute() throws Throwable {
		for(EPlanElement element: elementsToDuplicate) {
			final EPlanElement copy = TemplatePlanUtils.getCopy(element, false);
			final Object currentName = copy.eGet(PlanPackage.Literals.EPLAN_ELEMENT__NAME);
			TransactionUtils.writing(getTemplatePlan(), new Runnable() {
				@Override
				public void run() {
					copy.eSet(PlanPackage.Literals.EPLAN_ELEMENT__NAME, "copy of " + currentName);
					CommonMember commonMember = copy.getMember(CommonMember.class);
					// give the new activity a unique template id
					DiffIdGenerator instance = DiffIdGenerator.getInstance();
					String generatedDiffId = instance.generateDiffId(copy.eClass());
					commonMember.setDiffID(generatedDiffId);
					maybeAddToPlan(copy);
					duplicates.add(copy);
				}

			});
		}
	}

	protected void maybeAddToPlan(final EPlanElement copy) {
		getTemplatePlan().getChildren().add((EPlanChild)copy);
		needsSave = true;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return null;
	}

	public Collection<EPlanElement> getDuplicates() {
		return this.duplicates;
	}
}


text:
/*
 * File:   ContactDialog.h
 * Author: ckarner
 *
 * Created on October 27, 2015, 1:30 PM
 */

#ifndef CONTACTDIALOG_H
#define	CONTACTDIALOG_H

#include <QDialog>
#include "Contact.h"
#include <QLineEdit>
#include <QString>

class ContactDialog : public QDialog {
    Q_OBJECT
public:
    ContactDialog(const QString title, Contact* c, QWidget* parent);
private:
    Contact* c;
    QLineEdit* txtFirstName;
    QLineEdit* txtLastName;
    QLineEdit* txtMailAddress;

    void buildGui();

private slots:
    void onAccept();
};

#endif	/* CONTACTDIALOG_H */


text:
from Pyro5.api import expose, Daemon

@expose
class Thingy(object):
    def message(self, arg):
        print("Message received:", arg)
        return "Roger!"

with Daemon(unixsocket="\0example_unix.sock") as d:   # notice the 0-byte at the start
    uri = d.register(Thingy, "example.unixsock")
    print("Server running, uri=", uri)
    string_uri = str(uri)
    print("Actually, the uri contains a 0-byte, make sure you copy the part between the quotes to the client:")
    print(repr(string_uri))
    d.requestLoop()


text:
using System.Windows;
using System.Windows.Forms;
using BrightstarDB.Polaris.Properties;
using BrightstarDB.Polaris.ViewModel;
using UserControl = System.Windows.Controls.UserControl;

namespace BrightstarDB.Polaris.Views
{
    /// <summary>
    /// Interaction logic for ImportView.xaml
    /// </summary>
    public partial class ImportView : UserControl
    {
        public ImportView()
        {
            InitializeComponent();
        }

        private void HandleFileSelectorClick(object sender, RoutedEventArgs e)
        {
            var filterIndex = Settings.Default.ImportFilter;
            var fileDlg = new OpenFileDialog
                              {
                                  CheckFileExists = true,
                                  CheckPathExists = true,
                                  Filter = Strings.FileSelectorOptions,
                                  FilterIndex = filterIndex
                              };
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                var importModel = DataContext as ImportViewModel;
                if (importModel != null)
                {
                    importModel.ImportFileName = fileDlg.FileName;
                }
                if (fileDlg.FilterIndex != filterIndex)
                {
                    Settings.Default.ImportFilter = fileDlg.FilterIndex;
                    Settings.Default.Save();
                }
            }
        }
    }
}


text:
set -o errexit
set -o nounset
set -o pipefail

. /etc/sysconfig/heat-params

if [ "$TLS_DISABLED" == "True" ]; then
  exit 0
fi

cert_ip=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
sans="IP:${cert_ip},IP:${KUBE_API_PUBLIC_ADDRESS},IP:${KUBE_API_PRIVATE_ADDRESS},IP:127.0.0.1"
MASTER_HOSTNAME=${MASTER_HOSTNAME:-}
if [[ -n "${MASTER_HOSTNAME}" ]]; then
  sans="${sans},DNS:${MASTER_HOSTNAME}"
fi

cert_dir=/srv/kubernetes
cert_conf_dir=${cert_dir}/conf
cert_group=root

mkdir -p "$cert_dir"
mkdir -p "$cert_conf_dir"

CA_CERT=$cert_dir/ca.crt
SERVER_CERT=$cert_dir/server.crt
SERVER_CSR=$cert_dir/server.csr
SERVER_KEY=$cert_dir/server.key

#Get a token by user credentials and trust
auth_json=$(cat << EOF
{
    "auth": {
        "identity": {
            "methods": [
                "password"
            ],
            "password": {
                "user": {
                    "id": "$TRUSTEE_USER_ID",
                    "password": "$TRUSTEE_PASSWORD"
                }
            }
        },
        "scope": {
            "OS-TRUST:trust": {
                "id": "$TRUST_ID"
            }
        }
    }
}
EOF
)

#trust is introduced in Keystone v3 version
AUTH_URL=${AUTH_URL/v2.0/v3}
USER_TOKEN=`curl -s -i -X POST -H "Content-Type: application/json" -d "$auth_json" \
                 $AUTH_URL/auth/tokens | grep X-Subject-Token | awk '{print $2}'`

# Get CA certificate for this bay
curl -X GET \
  -H "X-Auth-Token: $USER_TOKEN" \
  $MAGNUM_URL/certificates/$BAY_UUID | python -c 'import sys, json; print json.load(sys.stdin)["pem"]' > ${CA_CERT}

# Create config for server's csr
cat > ${cert_conf_dir}/server.conf <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions     = req_ext
prompt = no
[req_distinguished_name]
CN = kubernetes.invalid
[req_ext]
subjectAltName = ${sans}
extendedKeyUsage = clientAuth,serverAuth
EOF

# Generate server's private key and csr
openssl genrsa -out "${SERVER_KEY}" 4096
chmod 400 "${SERVER_KEY}"
openssl req -new -days 1000 \
        -key "${SERVER_KEY}" \
        -out "${SERVER_CSR}" \
        -reqexts req_ext \
        -config "${cert_conf_dir}/server.conf"

# Send csr to Magnum to have it signed
csr_req=$(python -c "import json; fp = open('${SERVER_CSR}'); print json.dumps({'bay_uuid': '$BAY_UUID', 'csr': fp.read()}); fp.close()")
curl -X POST \
    -H "X-Auth-Token: $USER_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$csr_req" \
    $MAGNUM_URL/certificates | python -c 'import sys, json; print json.load(sys.stdin)["pem"]' > ${SERVER_CERT}

chmod 500 "${cert_dir}"
chown -R kube:kube "${cert_dir}"


text:
package fr.ritaly.dungeonmaster.actuator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.Validate;

import fr.ritaly.dungeonmaster.Temporizer;

/**
 * A simple {@link Actuator} used to trigger a {@link Triggerable}.
 *
 * @author Francois RITALY
 */
public class SimpleActuator implements Actuator {

	/**
	 * A {@link Temporizer} used to delay the triggering of a {@link Triggerable}.
	 */
	private final Temporizer temporizer;

	/**
	 * The triggering action to be triggered.
	 */
	private final TriggerAction action;

	/**
	 * The list of {@link Triggerable} to be triggered.
	 */
	private final List<Triggerable> targets;

	/**
	 * The actuator's label.
	 */
	private final String label;

	/**
	 * The maximal number of clock ticks before triggering the {@link Triggerable}
	 * .
	 */
	private final int max;

	public SimpleActuator(int count, TriggerAction action, Triggerable... targets) {
		Validate.isTrue(count > 0, "The given tick count <" + count + "> must be positive");
		Validate.notNull(action, "The given trigger action is null");
		Validate.notNull(targets, "The given array is null");
		Validate.isTrue(targets.length > 0, "The given array is empty");

		final StringBuilder builder = new StringBuilder(512);

		boolean first = true;
		for (Triggerable triggerable : targets) {
			if (!first) {
				builder.append(",");
			} else {
				first = false;
			}

			builder.append(triggerable);
		}

		this.label = "Actuator[" + builder + "]";
		this.temporizer = new Temporizer(label, count);
		this.action = action;
		this.targets = Arrays.asList(targets);
		this.max = count;
	}

	public SimpleActuator(SimpleActuator actuator) {
		Validate.notNull(actuator, "The given actuator is null");

		this.action = actuator.action;
		this.label = actuator.label;
		this.max = actuator.max;
		this.temporizer = new Temporizer(label, max);
		this.targets = new ArrayList<Triggerable>(actuator.targets);
	}

	@Override
	public boolean clockTicked() {
		if (temporizer.trigger()) {
			// Trigger each target
			for (Triggerable triggerable : targets) {
				triggerable.trigger(action);
			}

			return false;
		}

		return true;
	}

	@Override
	public String getLabel() {
		return label;
	}

	@Override
	public Object clone() {
		return new SimpleActuator(this);
	}

	@Override
	public String toString() {
		return getLabel();
	}
}


text:
require "google/cloud/speech/v2"

##
# Example demonstrating basic usage of
# Google::Cloud::Speech::V2::Speech::Client#create_recognizer
#
def create_recognizer
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Speech::V2::Speech::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Speech::V2::CreateRecognizerRequest.new

  # Call the create_recognizer method.
  result = client.create_recognizer request

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "Error!"
  end
end
# [END speech_v2_generated_Speech_CreateRecognizer_sync]


text:
using Xamarin.Forms;
using System;
using System.ComponentModel;

namespace CupWorks.Forms.Fluent
{
    public static class SwitchCellExtension
    {
        public static TSelf ChangeOn<TSelf>(this TSelf self, bool on) where TSelf : SwitchCell
        {
            self.On = on;
            return self;
        }

        public static TSelf ChangeSwitchCellText<TSelf>(this TSelf self, string text) where TSelf : SwitchCell
        {
            self.Text = text;
            return self;
        }

        public static TSelf HandleOnChanged<TSelf>(this TSelf self, EventHandler<ToggledEventArgs> onChanged) where TSelf : SwitchCell
        {
            self.OnChanged += onChanged;
            return self;
        }

        public static TSelf HandleSwitchCellTapped<TSelf>(this TSelf self, EventHandler tapped) where TSelf : SwitchCell
        {
            self.Tapped += tapped;
            return self;
        }

        public static TSelf HandleSwitchCellAppearing<TSelf>(this TSelf self, EventHandler appearing) where TSelf : SwitchCell
        {
            self.Appearing += appearing;
            return self;
        }

        public static TSelf HandleSwitchCellDisappearing<TSelf>(this TSelf self, EventHandler disappearing) where TSelf : SwitchCell
        {
            self.Disappearing += disappearing;
            return self;
        }

        public static TSelf HandleSwitchCellChildAdded<TSelf>(this TSelf self, EventHandler<ElementEventArgs> childAdded) where TSelf : SwitchCell
        {
            self.ChildAdded += childAdded;
            return self;
        }

        public static TSelf HandleSwitchCellChildRemoved<TSelf>(this TSelf self, EventHandler<ElementEventArgs> childRemoved) where TSelf : SwitchCell
        {
            self.ChildRemoved += childRemoved;
            return self;
        }

        public static TSelf HandleSwitchCellDescendantAdded<TSelf>(this TSelf self, EventHandler<ElementEventArgs> descendantAdded) where TSelf : SwitchCell
        {
            self.DescendantAdded += descendantAdded;
            return self;
        }

        public static TSelf HandleSwitchCellDescendantRemoved<TSelf>(this TSelf self, EventHandler<ElementEventArgs> descendantRemoved) where TSelf : SwitchCell
        {
            self.DescendantRemoved += descendantRemoved;
            return self;
        }

        public static TSelf HandleSwitchCellPropertyChanging<TSelf>(this TSelf self, PropertyChangingEventHandler propertyChanging) where TSelf : SwitchCell
        {
            self.PropertyChanging += propertyChanging;
            return self;
        }

        public static TSelf HandleSwitchCellPropertyChanged<TSelf>(this TSelf self, PropertyChangedEventHandler propertyChanged) where TSelf : SwitchCell
        {
            self.PropertyChanged += propertyChanged;
            return self;
        }

        public static TSelf HandleSwitchCellBindingContextChanged<TSelf>(this TSelf self, EventHandler bindingContextChanged) where TSelf : SwitchCell
        {
            self.BindingContextChanged += bindingContextChanged;
            return self;
        }
    }
}


text:
require 'logstasher/custom_fields'

describe LogStasher::CustomFields do
  describe '#add' do
    before(:each) { LogStasher::CustomFields.add(:test, :test2) }
    after(:each) { LogStasher::CustomFields.custom_fields = [] }
    it 'returns the stored var in current thread' do
      expect(Thread.current[:logstasher_custom_fields]).to eq [:test, :test2]
    end
  end
end


text:
@rem  This file was contributed by Ralf Junker, and touched up by
@rem  Daniel Richard G. Test 10 added by Philip H.
@rem  Philip H also changed test 3 to use "wintest" files.
@rem
@rem  MS Windows batch file to run pcretest on testfiles with the correct
@rem  options.
@rem
@rem  Output is written to a newly created subfolder named "testdata".

setlocal

if [%srcdir%]==[]   set srcdir=.
if [%pcretest%]==[] set pcretest=pcretest

if not exist testout md testout

%pcretest% -q      %srcdir%\testdata\testinput1 > testout\testoutput1
%pcretest% -q      %srcdir%\testdata\testinput2 > testout\testoutput2
@rem %pcretest% -q      %srcdir%\testdata\testinput3 > testout\testoutput3
%pcretest% -q      %srcdir%\testdata\wintestinput3 > testout\wintestoutput3
%pcretest% -q      %srcdir%\testdata\testinput4 > testout\testoutput4
%pcretest% -q      %srcdir%\testdata\testinput5 > testout\testoutput5
%pcretest% -q      %srcdir%\testdata\testinput6 > testout\testoutput6
%pcretest% -q -dfa %srcdir%\testdata\testinput7 > testout\testoutput7
%pcretest% -q -dfa %srcdir%\testdata\testinput8 > testout\testoutput8
%pcretest% -q -dfa %srcdir%\testdata\testinput9 > testout\testoutput9
%pcretest% -q      %srcdir%\testdata\testinput10 > testout\testoutput10

fc /n %srcdir%\testdata\testoutput1 testout\testoutput1
fc /n %srcdir%\testdata\testoutput2 testout\testoutput2
rem fc /n %srcdir%\testdata\testoutput3 testout\testoutput3
fc /n %srcdir%\testdata\wintestoutput3 testout\wintestoutput3
fc /n %srcdir%\testdata\testoutput4 testout\testoutput4
fc /n %srcdir%\testdata\testoutput5 testout\testoutput5
fc /n %srcdir%\testdata\testoutput6 testout\testoutput6
fc /n %srcdir%\testdata\testoutput7 testout\testoutput7
fc /n %srcdir%\testdata\testoutput8 testout\testoutput8
fc /n %srcdir%\testdata\testoutput9 testout\testoutput9
fc /n %srcdir%\testdata\testoutput10 testout\testoutput10


text:
@interface WXOImageBubbleChatView : YWBaseBubbleChatView<YWBaseBubbleChatViewInf>

- (void)setProgressViewHidden:(BOOL)aHidden;
- (void)setProgress:(CGFloat)aProgress;

@property (nonatomic, strong) UIImageView *msgImageView;
@property (nonatomic, assign) BOOL showMask;

@end


text:
/*
	*************************

	Logarithmic Scale Tests

	*************************

*/
describe("Slider with logarithmic scale tests", function() {

	var testSlider;

	it("Should properly position the slider", function() {
		testSlider = $("#testSlider1").slider({
			min: 0,
			max: 10000,
			scale: 'logarithmic',
			value: 100 // This should be at 50%
		});

		var expectedPostition = 210 / 2 + 'px';

		var handle = $("#testSlider1").siblings('div.slider').find('.min-slider-handle');
		expect(handle.css('left')).toBe(expectedPostition);
	});

	it("Should properly position the tick marks", function() {
		testSlider = $("#testSlider1").slider({
			min: 0,
			max: 100,
			scale: 'logarithmic',
			ticks: [0,10,20,50,100]
		});

		// Position expected for the '10' tick
		var expectedTickOnePosition = 210 / 2 + 'px'; //should be at 50%

		var handle = $("#testSlider1").siblings('div.slider').find(".slider-tick").eq(1);
		expect(handle.css('left')).toBe(expectedTickOnePosition);
	});

	it("Should use step size when navigating the keyboard", function() {
		testSlider = $("#testSlider1").slider({
			min: 0,
			max: 10000,
			scale: 'logarithmic',
			value: 100,
			step: 5
		});

		// Focus on handle1
		var handle1 = $("#testSlider1").siblings('div.slider:first').find('.slider-handle');
		handle1.focus();

		// Create keyboard event
		var keyboardEvent = document.createEvent("Events");
		keyboardEvent.initEvent("keydown", true, true);

		var keyPresses = 0;
		handle1.on("keydown", function() {
			keyPresses++;
			var value = $("#testSlider1").slider('getValue');
			expect(value).toBe(100 + keyPresses*5);
		});

		keyboardEvent.keyCode = keyboardEvent.which = 39; // RIGHT
		for (var i = 0; i < 5; i++) {
			handle1[0].dispatchEvent(keyboardEvent);
		}
	});

	afterEach(function() {
	    if(testSlider) {
	      testSlider.slider('destroy');
	      testSlider = null;
	    }
  	});
});


text:
/* jshint onevar: false,  smarttabs: true */
/* global tb_show, tb_pathToImage, ajaxurl, tb_init, tb_remove */
/* global myblogsResponse, publicizeConnTestStart:true, publicizeConnTestComplete:true, publicizeConnRefreshClick:true */

var showOptionsPage;

jQuery( function( $ ) {

	showOptionsPage = function( service, nonce, connection, blogId ) {
		tb_show( null, null, null );
		$('body').append( '

' );
		$('#TB_load').show();

		var query = '';
		if ( connection ) {
			query += '&connection=' + encodeURIComponent( connection );
		}
		if ( 'undefined' !== typeof( blogId ) && blogId ) {
			query += '&blog_id=' + Number( blogId );
		}

		$.post( ajaxurl, 'action=publicize_' + service + '_options_page&_wpnonce=' + nonce + query, function( response ) {
			$('#TB_load').remove();

			try {
				var obj = jQuery.parseJSON( response );
				if ( obj && 'object' === typeof( obj ) ) {
					if ( obj.hasOwnProperty( 'fb_redirect' ) ) {
						location.href = obj.fb_redirect + '&redirect_uri=' + encodeURIComponent( location.href );
						return;
					}
				}
			} catch (err) {
				// Do nothing and move on
			}

			if ( response ) {
				var blogID = $( 'input[name=wpas_ajax_blog_id]' ).val();

				var message = $( '

' ).append( response );
				message.append( '' );
				$('#wpas-message').html( message );

				tb_init( 'a.new-thickbox' );
				$('#wpas-click-' + blogID).click();

				var tb_height = parseInt( $('#TB_ajaxContent').css('height'), 10 );
				var content_height = $('#thickbox-content').height();
				if ( content_height < tb_height ) {
					var new_height = content_height + 15;
					$('#TB_ajaxContent').css( 'height', new_height );

					var new_margin = parseInt( $('#TB_window').css( 'margin-top'), 10 ) + (tb_height - new_height) / 2 + 'px';
					$('#TB_window').css( 'margin-top',  new_margin);
				}

				$('.save-options').unbind('click').click( function() {
					var sel = $( 'input[name=\'option\']:checked' );
					var global = $( 'input[name=\'global\']:checked' );

					var connection = $(this).data('connection');
					var token = encodeURIComponent( sel.val() );
					var id = encodeURIComponent( sel.attr( 'id' ) );
					var type = encodeURIComponent( sel.attr( 'data-type' ) );
					var nonce = $(this).attr('rel');
					var global_conn = 'off';
					var global_nonce = '';

					if ( global.length ) {
						global_conn = 'on';
						global_nonce = global.val();
					}

					$.post( ajaxurl, 'action=publicize_'+ service + '_options_save&connection=' + connection + '&selected_id=' + id + '&token=' + token + '&type=' + type + '&_wpnonce=' + nonce + '&global=' + global_conn + '&global_nonce=' + global_nonce, function( /*response*/ ) {
						var frameNonce;
						tb_remove();
						frameNonce = document.location.search.match( /frame-nonce=([^&]+)/ );
						if ( /inside-newdash=1/.test( document.location.search ) && frameNonce ) {
							document.location = 'options-general.php?page=sharing&inside-newdash=1&frame-nonce' + frameNonce[1];
						} else {
							top.location = 'options-general.php?page=sharing';
						}
					} );

				} );
			}

		}, 'html' );
	};

	$( 'body' ).append( '

' );

	$( '.wpas-posts' ).change( function() {
		var inputs = $(this).parents( 'td:first' ).find( ':input' );
		var _this = this;
		var blogID = inputs.filter( '[name=wpas_ajax_blog_id]' ).val();

		$( '#waiting_' + blogID ).show();
		$.post( ajaxurl, inputs.serialize() + '&action=wpas_post', function( response ) { myblogsResponse.call( _this, blogID, response ); }, 'html' );
	} );

	$( '.options' ).unbind('click').bind( 'click', function(e) {
		e.preventDefault();
		e.stopPropagation();

		var service = $(this).attr('class').replace( 'options ', '' );

		var blogId = null;
		if ( 'undefined' !== typeof( $(this).attr('id') ) ) {
			blogId = parseInt( $(this).attr('id').replace( 'options-', '' ), 10 );
		}

		var nonce = $(this).attr('href').replace( '#nonce=', '' );
		var connection = $(this).data( 'connection' );
		showOptionsPage.call( this, service, nonce, connection, blogId );
	});

	/**
	  * Kicks off tests for all connections
	  */
	publicizeConnTestStart = function() {
		$( '.pub-connection-test' )
			.addClass( 'test-in-progress' );
		$.post( ajaxurl, { action: 'test_publicize_conns' }, publicizeConnTestComplete );
	};

	publicizeConnRefreshClick = function( event ) {
		event.preventDefault();
		var popupURL = event.currentTarget.href;
		var popupTitle = event.currentTarget.title;
		// open a popup window
		// when it is closed, kick off the tests again
		var popupWin = window.open( popupURL, popupTitle, '' );
		var popupWinTimer= window.setInterval( function() {
			if ( popupWin.closed !== false ) {
				window.clearInterval( popupWinTimer );
				publicizeConnTestStart();
			}
		}, 500 );
	};

	publicizeConnTestComplete = function( response ) {
		$( '.pub-connection-test' ).removeClass( 'test-in-progress' );

		$.each( response.data, function( index, testResult ) {
			// find the li for this connection
			var testSelector = '#pub-connection-test-' + testResult.connectionID;
			if ( testResult.connectionTestPassed ) {
				$( testSelector )
					.addClass( 'test-passed' )
					.html( '' )
					.removeClass( 'test-failed' );
			} else {
				$( testSelector )
					.addClass( 'test-failed' )
					.html( '
' + testResult.connectionTestMessage + '
' )
					.removeClass( 'test-passed' );

				if ( testResult.userCanRefresh ) {
					$( testSelector )
						.append( '
' );
					$( '', {
						'class'  : 'pub-refresh-button button',
						'title'  : testResult.refreshText,
						'href'   : testResult.refreshURL,
						'text'   : testResult.refreshText,
						'target' : '_refresh_' + testResult.serviceName
					} )
						.appendTo( testSelector )
						.click( publicizeConnRefreshClick );
				}
			}
		} );
	};

	$( document ).ready( function() {
		// If we have at least one .pub-connection-test div present, kick off the connection test
		if ( $( '.pub-connection-test' ).length ) {
			publicizeConnTestStart();
		}
	} );

} );


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SSS_Library;

namespace SSS_Windows_Forms.Forms.Coordinator
{
    public partial class AssignTutor : Form
    {
        private IS2G10_DBSSSDataSet.GROUPDataTable _groups;
        private IS2G10_DBSSSDataSet.TUTORDataTable _tutors;

        public AssignTutor(int coordinatorId)
        {
            InitializeComponent();
            this.TopLevel = false;
            this.AutoScroll = true;
            this.Hide();

            button1.Enabled = false;
            listView2.Enabled = false;
            listView1.View = View.Details;
            listView2.View = View.Details;

            PopulateData();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void PopulateData()
        {
            _groups = groupTableAdapter1.GetData();
            _tutors = tutorTableAdapter1.GetData();
        }
    }
}


text:
Rails asset gem

## Installation

**Step 1**

Load in your Gemfile

    gem 'layout_test', :git => 'git@github.com:cmu/layout_test.git'

**Step 2**

    Run 'bundle install'

**Step 3**

Require in your CSS manifest (e.g. application.css)

    *= require layout
    *= require typo

Require in your JS manifest (e.g. application.js)

    //= require alert


text:
package edu.nyu.classes.nyugrades.impl;

import edu.nyu.classes.nyugrades.api.DBService;
import edu.nyu.classes.nyugrades.api.NYUGradesSessionService;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Set;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.tool.api.Session;

public class NYUGradesSessionServiceImpl implements NYUGradesSessionService
{
    int SESSION_TIMEOUT_SECONDS = 600;
    private DBService db;

    public void init()
    {
        db = (DBService) ComponentManager.get("edu.nyu.classes.nyugrades.api.DBService");
    }

    private String mintSessionId()
    {
        byte[] b = new byte[32];

        try {
            SecureRandom.getInstance("SHA1PRNG").nextBytes(b);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Couldn't generate a session ID", e);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            sb.append(String.format("%02x", b[i]));
        }

        return sb.toString();
    }

    private int now()
    {
        return (int) ((new java.util.Date()).getTime() / 1000);
    }

    public void expireSessions()
    {
        db.executeUpdate("DELETE FROM nyu_t_grades_ws_session WHERE last_used < ?",
                         now() - SESSION_TIMEOUT_SECONDS);
    }

    public boolean checkSession(String sessionId)
    {
        expireSessions();

        int updateCount = db.executeUpdate("UPDATE nyu_t_grades_ws_session SET last_used = ? WHERE sessionid = ?",
                                           now(),
                                           sessionId);

        return updateCount > 0;
    }

    public String createSession(String username)
    {
        String sessionId = mintSessionId();

        db.executeUpdate("INSERT INTO nyu_t_grades_ws_session (sessionid, username, last_used) values (?, ?, ?)",
                         sessionId,
                         username,
                         now());

        return sessionId;
    }

    public void deleteSession(String sessionId)
    {
        db.executeUpdate("DELETE FROM nyu_t_grades_ws_session WHERE sessionid = ?",
                         sessionId);
    }
}


text:
#include "includes.h"

#ifndef _WIN32

ULONG
VmAuthsvcAllocateStringW(
    PCWSTR pwszSrc,
    PWSTR* ppwszDst
    )
{
    ULONG ulError = 0;

    if (!pwszSrc || !ppwszDst)
    {
        ulError = ERROR_INVALID_PARAMETER;
    }
    else
    {
        ulError = LwNtStatusToWin32Error(
                        LwRtlWC16StringDuplicate(ppwszDst, pwszSrc));
    }

    return ulError;
}

ULONG
VmAuthsvcAllocateStringWFromA(
    PCSTR pszSrc,
    PWSTR* ppwszDst
    )
{
    ULONG ulError = 0;

    if (!pszSrc || !ppwszDst)
    {
        ulError = ERROR_INVALID_PARAMETER;
    }
    else
    {
        ulError = LwNtStatusToWin32Error(
                        LwRtlWC16StringAllocateFromCString(ppwszDst, pszSrc));
    }

    return ulError;
}

ULONG
VmAuthsvcAllocateStringAFromW(
    PCWSTR pwszSrc,
    PSTR*  ppszDst
    )
{
    ULONG ulError = 0;

    if (!pwszSrc || !ppszDst)
    {
        ulError = ERROR_INVALID_PARAMETER;
    }
    else
    {
        ulError = LwNtStatusToWin32Error(
                        LwRtlCStringAllocateFromWC16String(ppszDst, pwszSrc));
    }

    return ulError;
}

ULONG
VmAuthsvcAllocateStringPrintfV(
    PSTR*   ppszStr,
    PCSTR   pszFormat,
    va_list argList
    )
{
    ULONG ulError = 0;

    if (!ppszStr || !pszFormat)
    {
        ulError = ERROR_INVALID_PARAMETER;
    }
    else
    {
        ulError = LwNtStatusToWin32Error(
                        LwRtlCStringAllocatePrintfV(
                                ppszStr,
                                pszFormat,
                                argList));
    }

    return ulError;
}

ULONG
VmAuthsvcAllocateStringPrintf(
    OUT PSTR* ppszString,
    IN PCSTR pszFormat,
    IN ...
    )
{
    DWORD dwError = 0;
    va_list args;

    va_start(args, pszFormat);
    dwError = VmAuthsvcAllocateStringPrintfV(ppszString, pszFormat, args);
    va_end(args);

    return dwError;
}

ULONG
VmAuthsvcGetStringLengthW(
    PCWSTR  pwszStr,
    PSIZE_T pLength
    )
{
    ULONG ulError = 0;

    if (!pwszStr || !pLength)
    {
        ulError = ERROR_INVALID_PARAMETER;
    }
    else
    {
        *pLength = LwRtlWC16StringNumChars(pwszStr);
    }

    return ulError;
}

ULONG
VmAuthsvcStringCompareA(
    PCSTR pszStr1,
    PCSTR pszStr2,
    BOOLEAN bIsCaseSensitive
    )
{
    return LwRtlCStringCompare(pszStr1, pszStr2, bIsCaseSensitive);
}

ULONG
VmAuthsvcStringNCompareA(
    PCSTR pszStr1,
    PCSTR pszStr2,
    size_t n,
    BOOLEAN bIsCaseSensitive
    )
{
    if( bIsCaseSensitive != FALSE )
    {
        return strncmp(pszStr1, pszStr2, n) ;
    }
    else
    {
        return strncasecmp(pszStr1, pszStr2, n) ;
    }
}

SIZE_T
VmAuthsvcStringLenA(
    PCSTR pszStr
)
{
    return strlen(pszStr);
}

PSTR
VmAuthsvcStringChrA(
   PCSTR str,
   int c
)
{
    return strchr( str, c );
}

PSTR
VmAuthsvcStringRChrA(
   PCSTR str,
   int c
)
{
    return strrchr(str, c);
}

PSTR
VmAuthsvcStringTokA(
   PSTR strToken,
   PCSTR strDelimit,
   PSTR* context
)
{
    return strtok_r( strToken, strDelimit, context );
}

PSTR
VmAuthsvcStringStrA(
   PCSTR str,
   PCSTR strSearch
)
{
    return strstr( str, strSearch );
}

DWORD
VmAuthsvcStringCpyA(
   PSTR strDestination,
   size_t numberOfElements,
   PCSTR strSource
)
{
    DWORD dwError = 0;
    size_t count = 0;

    if (!strDestination || !strSource)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    count = strlen(strSource) + 1;
    if (count > numberOfElements)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    strncpy(strDestination, strSource, count);

error:

    return dwError;
}

DWORD
VmAuthsvcStringNCpyA(
   PSTR strDestination,
   size_t numberOfElements,
   PCSTR strSource,
   size_t count
)
{
    DWORD dwError = 0;

    if (!strDestination || !strSource)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    if (count > numberOfElements)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    strncpy(strDestination, strSource, count);

error:

    return dwError;
}

DWORD
VmAuthsvcStringCatA(
   PSTR strDestination,
   size_t numberOfElements,
   PCSTR strSource
)
{
    DWORD dwError = 0;
    size_t count = 0;
    size_t cchSource = 0;

    if (!strDestination || !strSource)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    cchSource = strlen(strSource);
    count = strlen(strDestination) + cchSource + 1;
    if (count > numberOfElements)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    strncat(strDestination, strSource, cchSource + 1);

error:

    return dwError;
}

int64_t
VmAuthsvcStringToLA(
   PCSTR nptr,
   PSTR* endptr,
   int base
)
{
    return strtol( nptr, endptr, base );
}

int VmAuthsvcStringToIA(
   PCSTR pStr
)
{
    return atoi( pStr );
}

DWORD
VmAuthsvcStringErrorA(
   PSTR buffer,
   size_t numberOfElements,
   int errnum
)
{
    return VmAuthsvcStringNCpyA(
        buffer, numberOfElements, strerror(errnum), numberOfElements - 1 );
}

PSTR
VmAuthsvcCaselessStrStrA(
    PCSTR pszStr1,
    PCSTR pszStr2
    )
{
    PSTR pszPosStr1 = NULL;
    size_t sStr2Len = 0;

    if (IsNullOrEmptyString(pszStr1) || IsNullOrEmptyString(pszStr2))
        return NULL;

    pszPosStr1 = (PSTR)pszStr1;
    sStr2Len = strlen(pszStr2);

    do
    {
        if (!strncasecmp(pszPosStr1, pszStr2, sStr2Len))
        {
            return pszPosStr1;
        }
    }while (*(++pszPosStr1));

    return NULL;
}

DWORD
VmAuthsvcStringPrintFA(
    PSTR pDestination,
    size_t destinationSize,
    PCSTR pszFormat,
    ...
)
{
    DWORD dwError = ERROR_SUCCESS;
    BOOLEAN bVaStarted = FALSE;
    va_list args;

    va_start(args, pszFormat);
    bVaStarted = TRUE;

    if (!pDestination)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    if (vsnprintf(pDestination, destinationSize, pszFormat, args ) < 0)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

error:
    if(bVaStarted != FALSE)
    {
        va_end(args);
    }

    return dwError;
}

DWORD
VmAuthsvcStringNPrintFA(
    PSTR pDestination,
    size_t destinationSize,
    size_t maxSize,
    PCSTR pszFormat,
    ...
)
{
    DWORD dwError = ERROR_SUCCESS;
    BOOLEAN bVaStarted = FALSE;
    va_list args;

    va_start(args, pszFormat);
    bVaStarted = TRUE;

    if (!pDestination || maxSize > destinationSize)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

    if ( vsnprintf(
             pDestination, maxSize, pszFormat, args ) < 0 )
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMAUTHSVC_ERROR(dwError);
    }

error:

    if(bVaStarted != FALSE)
    {
        va_end(args);
    }

    return dwError;
}

#endif //#ifndef _WIN32


text:
package io.sipstack.transaction.event.impl;

import io.sipstack.transaction.Transaction;
import io.sipstack.transaction.event.TransactionEvent;

/**
 * @author jonas@jonasborjesson.com
 */
public class TransactionEventImpl implements TransactionEvent {
    final Transaction transaction;

    public TransactionEventImpl(final Transaction transaction) {
        this.transaction = transaction;
    }

    @Override
    public Transaction transaction() {
        return transaction;
    }
}


text:
Agora, vamos adicionar uma lista de alugueres ao template index. Sabemos que os alugueres não vão ser estáticos, visto que eventualmente os utilizadores vão poder adicionar, atualizar e apagar. Por esta razão, precisaremos de um modelo *rentals* para guardar a informação sobre os alugueres. Para manter as coisas simples no início, usaremos um array hard-coded com objetos JavaScript. Mais tarde, passaremos a usar Ember Data, uma biblioteca para gerir robustamente os dados na nossa aplicação.

Aqui está como a nossa homepage parecerá quando acabarmos:

![super rentals homepage with rentals list](../../images/models/super-rentals-index-with-list.png)

In Ember, route handlers are responsible for loading model data. Let's open `app/routes/rentals.js` and add our hard-coded data as the return value of the `model` hook:

```app/routes/rentals.js import Ember from 'ember';

let rentals = [{ id: 'grand-old-mansion', title: 'Grand Old Mansion', owner: 'Veruca Salt', city: 'San Francisco', type: 'Estate', bedrooms: 15, image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg' }, { id: 'urban-living', title: 'Urban Living', owner: 'Mike TV', city: 'Seattle', type: 'Condo', bedrooms: 1, image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg' }, { id: 'downtown-charm', title: 'Downtown Charm', owner: 'Violet Beauregarde', city: 'Portland', type: 'Apartment', bedrooms: 3, image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg' }];

export default Ember.Route.extend({ model() { return rentals; } });

    <br />Here, we are using the ES6 shorthand method definition syntax: `model()` is the same as writing `model: function()`.

    The `model` function acts as a **hook**, meaning that Ember will call it for us during different times in our app.
    The model hook we've added to our `rentals` route handler will be called when a user enters the `rentals` route.

    The `model` hook returns our _rentals_ array and passes it to our `rentals` template as the `model` property.

    Agora, mudemos para o nosso template.
    Podemos usar os dados do modelo para mostrar uma lista de alugueres.
    Aqui, usaremos outro helper Handlebars comum chamado `{{each}}`.
    This helper will let us loop through each of the objects in our model:

    ```app/templates/rentals.hbs{+13,+14,+15,+16,+17,+18,+19,+20,+21,+22,+23,+24,+25,+26,+27,+28,+29}

Welcome!

        We hope you find exactly what you're looking for in a place to stay.

Browse our listings, or use the search box below to narrow your search.

      {{#link-to 'about' class="button"}}
        About Us
      {{/link-to}}

    {{#each model as |rental|}}

{{rental.title}}

          Owner: {{rental.owner}}

          Type: {{rental.type}}

          Location: {{rental.city}}

          Number of bedrooms: {{rental.bedrooms}}

    {{/each}}

Neste template, iteramos cada objecto no modelo e chamamos-lhe *rental*. Por cada <0>rental</0> criamos uma listagem com informações relacionadas com a propriedade.

Now that we are listing rentals, our acceptance test validating that rentals display should show passing:

![list rentals test passing](../../images/model-hook/passing-list-rentals-tests.png)


text:
#include <benchmark/benchmark.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <streambuf>

#ifdef _MSC_VER
#include <direct.h>
#else
#include <unistd.h>
#endif

#include "SimpleConverter.hpp"
#include "TestUtilsUTF8.hpp"

namespace opencc {

SimpleConverter* Initialize(const std::string& config_name) {
  chdir(PROJECT_BINARY_DIR "/data");
  const std::string config_dir = CMAKE_SOURCE_DIR "/data/config/";
  const std::string config_path = config_dir + config_name + ".json";
  return new SimpleConverter(config_path);
}

void Convert(const SimpleConverter* converter, const std::string& text) {
  converter->Convert(text);
}

std::string ReadText(const std::string& filename) {
  const std::string benchmark_data_dir = CMAKE_SOURCE_DIR "/test/benchmark/";
  const std::string data_path = benchmark_data_dir + filename;
  std::ifstream stream(data_path);
  return std::string((std::istreambuf_iterator<char>(stream)),
                     std::istreambuf_iterator<char>());
}

static void BM_Initialization(benchmark::State& state,
                              std::string config_name) {
  for (auto _ : state) {
    const SimpleConverter* converter = Initialize(config_name);
    // Do not count the destruction time.
    state.PauseTiming();
    delete converter;
    state.ResumeTiming();
  }
}
BENCHMARK_CAPTURE(BM_Initialization, hk2s, "hk2s")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, hk2t, "hk2t")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, jp2t, "jp2t")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, s2hk, "s2hk")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, s2t, "s2t")->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, s2tw, "s2tw")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, s2twp, "s2twp")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, t2hk, "t2hk")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, t2jp, "t2jp")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, t2s, "t2s")->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, tw2s, "tw2s")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, tw2sp, "tw2sp")
    ->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Initialization, tw2t, "tw2t")
    ->Unit(benchmark::kMillisecond);

static void BM_Convert2M(benchmark::State& state) {
  const std::string config_name = "s2t";
  const std::string text = ReadText("zuozhuan.txt");
  const std::unique_ptr<SimpleConverter> converter(Initialize(config_name));
  for (auto _ : state) {
    Convert(converter.get(), text);
  }
}
BENCHMARK(BM_Convert2M)->Unit(benchmark::kMillisecond);

static void BM_Convert(benchmark::State& state, int iteration) {
  std::ostringstream os;
  for (int i = 0; i < iteration; i++) {
    os << "Open Chinese Convert 開放中文轉換" << i << std::endl;
  }
  const std::string text = os.str();
  const std::string config_name = "s2t";
  const std::unique_ptr<SimpleConverter> converter(Initialize(config_name));
  for (auto _ : state) {
    Convert(converter.get(), text);
  }
}
BENCHMARK_CAPTURE(BM_Convert, 100, 100)->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Convert, 1000, 1000)->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Convert, 10000, 10000)->Unit(benchmark::kMillisecond);
BENCHMARK_CAPTURE(BM_Convert, 100000, 100000)->Unit(benchmark::kMillisecond);

} // namespace opencc

BENCHMARK_MAIN();


text:
package xyz.meunier.wav2pzx.generaldecoder;

import com.google.common.collect.ImmutableList;
import javafx.util.Pair;
import xyz.meunier.wav2pzx.pulselist.PulseList;

import java.util.List;
import java.util.Optional;
import java.util.logging.Level;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.logging.Logger.getLogger;
import static xyz.meunier.wav2pzx.generaldecoder.LoaderState.INITIAL;

/**
 * LoaderContextImpl represents the extrinsic state of the tape processing state
 * machine. The data extracted from the source file will be stored here and
 *
 * @author Fredrick Meunier
 */
class LoaderContextImpl implements LoaderContext {

    private final long resolution;
    private int nextIndex;
    private int firstIndexOfBlock;
    private int lastIndexOfBlock;

    private int currentLevel;

    private TapeBlockListBuilder tapeBlockListBuilder = new TapeBlockListBuilder();

    private long currentPulse;
    private int pilotPulseCount;
    private ImmutableList<Long> pulseLengths;
    private int firstPulseLevel;

    /**
     * Builder method to construct a series of PZXBlocks that represents the data
     * in the supplied PulseList.
     *
     * @param pulseList the tape data to analyse
     * @return the analysed tape image
     * @throws NullPointerException if pulseList was null
     */
    static List<TapeBlock> buildTapeBlockList(PulseList pulseList) {
        checkNotNull(pulseList, "pulseList was null");
        final LoaderContextImpl context = new LoaderContextImpl(pulseList);

        LoaderState state = INITIAL;

        while (context.hasNextPulse()) {
            context.getNextPulse();
            state = state.nextState(context);
        }

        // Terminate the tape
        state.endLoader(context);

        getLogger(LoaderContextImpl.class.getName()).log(Level.FINE, context.toString());

        return context.getTapeBlockList();
    }

    void getNextPulse() {
        currentPulse = pulseLengths.get(nextIndex++);
        currentLevel = invertPulseLevel(currentLevel);
    }

    private boolean hasNextPulse() {
        return nextIndex < pulseLengths.size();
    }

    @Override
    public long getResolution() {
        return resolution;
    }

    @Override
    public void completeDataBlock() {
        completeBlock(BlockType.DATA);
    }

    private PulseList buildPulseList() {
        return new PulseList(pulseLengths.subList(firstIndexOfBlock, lastIndexOfBlock), firstPulseLevel, resolution);
    }

    @Override
    public void completeUnknownPulseBlock() {
        completeBlock(BlockType.UNKNOWN);
    }

    @Override
    public void completePilotPulseBlock() {
        completeBlock(BlockType.PILOT);
    }

    private void completeBlock(BlockType blockType) {
        if (firstIndexOfBlock >= lastIndexOfBlock) {
            tapeBlockListBuilder.add(null);
            return;
        }
        tapeBlockListBuilder.add(new Pair<>(blockType, buildPulseList()));
        firstIndexOfBlock = lastIndexOfBlock;
        resetBlock();
    }

    @Override
    public void addPilotPulse() {
        lastIndexOfBlock++;
        pilotPulseCount++;
    }

    @Override
    public void addUnclassifiedPulse() {
        lastIndexOfBlock++;
    }

    @Override
    public void revertCurrentBlock() {
        final Optional<Pair<BlockType, PulseList>> lastTapeBlock = tapeBlockListBuilder.removeLastBlock();

        getLogger(LoaderContextImpl.class.getName()).log(Level.FINE, "reverting block: " + lastTapeBlock.toString() + "\n");

        // In this case, popping off the last not present block will have done the job
        if (!lastTapeBlock.isPresent()) return;

        PulseList lastBlock = lastTapeBlock.get().getValue();
        // Preserve any pulses from the last block
        firstIndexOfBlock -= lastBlock.getPulseLengths().size();

        // If the last block was null this block has the same first pulse level that would have had
        resetBlock(lastBlock.getFirstPulseLevel()); // FIXME: Will have lost pilot count if it was present in the last block
    }

    @Override
    public int getNumPilotPulses() {
        return pilotPulseCount;
    }

    @Override
    public boolean isaPilotCandidate() {
        return LoaderContext.isaPilotCandidate(currentPulse);
    }

    @Override
    public boolean isTooLongToBeAPilot() {
        return currentPulse > MAX_PILOT_LENGTH;
    }

    @Override
    public boolean isaDataCandidate() {
        return currentPulse < MIN_PILOT_LENGTH;
    }

    @Override
    public boolean isaCandidateTailPulse() {
        return currentPulse <= LoaderContext.MAX_TAIL_PULSE;
    }

    @Override
    public boolean isCurrentAndNextPulseTooLongToBeADataCandidate() {
        // Any two adjacent data pulses must be less than DATA_TOTAL_MAX
        long nextPulse = hasNextPulse() ? pulseLengths.get(this.nextIndex) : 0L;
        return (currentPulse + nextPulse) > DATA_TOTAL_MAX;
    }

    @Override
    public boolean isaMinimumNumberOfPilotPulses() {
        return pilotPulseCount >= MIN_PILOT_COUNT;
    }

    LoaderContextImpl(PulseList pulseList) {
        checkNotNull(pulseList, "pulseList cannot be null");
        this.currentLevel = invertPulseLevel(pulseList.getFirstPulseLevel()); // will be inverted when first pulse is retrieved
        this.resolution = pulseList.getResolution();
        pulseLengths = pulseList.getPulseLengths();
        nextIndex = 0;
        firstIndexOfBlock = 0;
        lastIndexOfBlock = 0;
        resetBlock(pulseList.getFirstPulseLevel());
    }

    List<TapeBlock> getTapeBlockList() {
        return tapeBlockListBuilder.build();
    }

    private int invertPulseLevel(int level) {
        return level == 0 ? 1 : 0;
    }

    private void resetBlock() {
        resetBlock(currentLevel);
    }

    private void resetBlock(int firstPulseLevel) {
        this.firstPulseLevel = firstPulseLevel;
        pilotPulseCount = 0;
    }

    @Override
    public String toString() {
        return "LoaderContextImpl{" +
                "resolution=" + resolution +
                ", nextIndex=" + nextIndex +
                ", firstIndexOfBlock=" + firstIndexOfBlock +
                ", lastIndexOfBlock=" + lastIndexOfBlock +
                ", currentLevel=" + currentLevel +
                ", tapeBlockListBuilder=" + tapeBlockListBuilder +
                ", currentPulse=" + currentPulse +
                ", pilotPulseCount=" + pilotPulseCount +
                ", firstPulseLevel=" + firstPulseLevel +
                '}';
    }
}


text:
package net.ypresto.timbertreeutils;

import android.util.Log;

class LogMessageHelper {
    public static String format(int priority, String tag, String message) {
        String messageWithTag = tag != null ? "[" + tag + "] " + message : message;
        return prefixForPriority(priority) + messageWithTag;
    }

    public static String prefixForPriority(int priority) {
        switch (priority) {
            case Log.VERBOSE:
                return "[VERBOSE] ";
            case Log.DEBUG:
                return "[DEBUG] ";
            case Log.INFO:
                return "[INFO] ";
            case Log.WARN:
                return "[WARN] ";
            case Log.ERROR:
                return "[ERROR] ";
            case Log.ASSERT:
                return "[ASSERT] ";
            default:
                return "[UNKNOWN(" + priority + ")] ";
        }
    }
}


text:
import React from 'react';
import ItemButton from './items/button';
import ItemLink from './items/link';
import ItemSeparator from './items/separator';

export default React.createClass({
	render: function() {
		var Itype = ItemButton;
		var validItems = {
			'button': ItemButton,
			'link': ItemLink,
			'separator': ItemSeparator
		};
		var liClass = 'toolbar-custom custom-item';

		if (this.props.data.custom) {
			var title = this.props.data.title ? this.props.data.title : '';

			if (typeof this.props.data.liClass != 'undefined' && this.props.data.liClass) {
				liClass += ' ' + this.props.data.liClass;
			}

			return
{this.props.data.custom}
;
		}

		if (typeof validItems[this.props.data.type] != 'undefined') {
			Itype = validItems[this.props.data.type];
		}

		if (typeof this.props.data.type == 'function') {
			Itype = this.props.data.type;
		}

		return <Itype data={this.props.data}/>;
	}
});


text:
package com.espirit.moddev.cli.results.imports;

import de.espirit.common.util.Pair;
import de.espirit.firstspirit.store.access.nexport.ExportInfo;
import de.espirit.firstspirit.store.access.nexport.ExportStatus;
import de.espirit.firstspirit.store.access.nexport.io.ExportInfoFileHandle;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

/**
 * ImportInfo for entity types. This class <b>may</b> be included in newer versions of FirstSpirit.
 * Currently, this class is only a wrapper of the already existing ExportInfo.
 */
public abstract class ImportInfoImpl implements ExportInfo {

    private final Type _type;
    private final ExportStatus _status;

    ImportInfoImpl(final Type type, final ExportStatus status) {
        _type = type;
        _status = status;
    }

    @Override
    public final Type getType() {
        return _type;
    }

    @Override
    public final ExportStatus getStatus() {
        return _status;
    }

    @Override
    public final Set<ExportInfoFileHandle> getCreatedFileHandles() {
        return Collections.emptySet();
    }

    @Override
    public final Set<ExportInfoFileHandle> getUpdatedFileHandles() {
        return Collections.emptySet();
    }

    @Override
    public final Set<ExportInfoFileHandle> getDeletedFileHandles() {
        return Collections.emptySet();
    }

    @Override
    public final Collection<Pair<ExportInfoFileHandle, ExportInfoFileHandle>> getMovedFileHandles() {
        return Collections.emptySet();
    }
}


text:
import os
import smtplib
from functools import wraps
from flask import jsonify, request, current_app
from functools import wraps
from flask import request, Response

from email.mime.text import MIMEText
MAILGUN_SMTP_LOGIN = os.getenv('MAILGUN_SMTP_LOGIN')
MAILGUN_SMTP_PASSWORD = os.getenv('MAILGUN_SMTP_PASSWORD')

def send_email(subject, body, to):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = "spaceprobes@samples.mailgun.org"
    msg['To'] = to
    s = smtplib.SMTP('smtp.mailgun.org', 587)
    s.login(MAILGUN_SMTP_LOGIN, MAILGUN_SMTP_PASSWORD)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()
    print "email sent"

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == os.environ['ADMIN_USER'] and password == os.environ['ADMIN_PASS']

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

def safe_float(s, range, default=False):
    try:
        f = float(s)
    except:
        return default

    if f > range[1]:
        return default
    if f < range[0]:
        return default

    return f

# json endpoint decorator
def json(func):
    """Returning a object gets JSONified"""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        return jsonify(func(*args, **kwargs)[0]), func(*args, **kwargs)[1]
    return decorated_function

# from farazdagi on github
#   https://gist.github.com/1089923
def jsonp(func):
    """Wraps JSONified output for JSONP requests."""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs)[0].data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype), func(*args, **kwargs)[1]
        else:
            return func(*args, **kwargs)
    return decorated_function

# from aisipos on github
#   https://gist.github.com/aisipos/1094140
def support_jsonp(f):
    """Wraps JSONified output for JSONP"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            content = str(callback) + '(' + str(f(*args,**kwargs).data) + ')'
            return current_app.response_class(content, mimetype='application/javascript')
        else:
            return f(*args, **kwargs)
    return decorated_function


text:
This solution provides an automated, serverless way to redact sensitive data from PDF files using Google Cloud Services like [Data Loss Prevention (DLP)](https://cloud.google.com/dlp), [Cloud Workflows](https://cloud.google.com/workflows), and [Cloud Run](https://cloud.google.com/run).

## Solution Architecture Diagram
The image below describes the solution architecture of the pdf redaction process.

![Architecture Diagram](./architecture-diagram.png)

## Workflow Steps
The workflow consists of the following steps:
1. The user uploads a PDF file to a GCS bucket
1. A Cloud Function is triggered
1. The Function starts a Workflow to orchestrate the PDF file redaction. The workflow consists of the following steps:
    - Split the PDF into single pages, convert pages into images, and store them in a working bucket
    - Redact each image using DLP Image Redact API
    - Assemble back the PDF file from the list of redacted images and store it on GCS (output bucket)
    - Write redacted quotes (findings) to BigQuery

# Deploy PDF Redaction app
The `terraform` folder contains the code needed to deploy the PDF Redaction application.

## What resources are created?
Main resources:
- Workflow
- CloudRun services for each component with its service accounts and permissions
  1. `pdf-spliter` - Split PDF into single-page image files
  1. `dlp-runner` - Runs each page file through DLP to redact sensitive information
  1. `pdf-merger` - Assembles back the pages into a single PDF
  1. `findings-writer` - Writes findings into BigQuery
- Cloud Storage buckets
  - *Input Bucket* - bucket where the original file is stored
  - *Working Bucket* - a working bucket in which all temp files will be stored as throughout the different workflow stages
  - *Output Bucket* - bucket where the redacted file is stored
- DLP template where InfoTypes and rules are specified. You can modify the `dlp.tf` file to specify your own INFO_TYPES and Rule Sets (refer to [terraform documentation for dlp templates](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/data_loss_prevention_inspect_template))
- BigQuery dataset and table where findings will be written

## How to deploy?
The following steps should be executed in Cloud Shell in the Google Cloud Console.

### 1. Create a project and enable billing
Follow the steps in [this guide](https://cloud.google.com/resource-manager/docs/creating-managing-projects).

### 2. Get the code
Clone this github repository go to the root of the repository.

```
git clone https://github.com/GoogleCloudPlatform/dlp-pdf-redaction
cd dlp-pdf-redaction
```

### 3. Build images for Cloud Run
You will first need to build the docker images for each microservice.

```
PROJECT_ID=[YOUR_PROJECT_ID]
gcloud services enable cloudbuild.googleapis.com containerregistry.googleapis.com --project $PROJECT_ID
gcloud builds submit --config ./build-app-images.yaml --project $PROJECT_ID
```
Note: If you receive a pop-up for permissions, you can authorize gcloud to request your credentials an make a GCP API call.

The above command will build 4 docker images and push them into Google Container Registry (GCR). Run the following command and confirm that the images are present in GCR.

```
gcloud container images list --project $PROJECT_ID
```

### 4. Deploy the infrastructure using Terraform

This terraform deployment requires the following variables.

- project_id            = "YOUR_PROJECT_ID"
- region                = "YOUR_REGION_REGION"
- wf_region             = "YOUR_WORKFLOW_REGION"

From the root folder of this repo, run the following commands:
```
export TF_VAR_project_id=$PROJECT_ID
terraform -chdir=terraform init
terraform -chdir=terraform apply -auto-approve
```

**Note:** Region and Workflow region both default to `us-central1`. If you wish to deploy the resources in a different region, specify the `region` and the `wf_region` variables (ie. using `TF_VAR_region` and `TF_VAR_wf_region`). Cloud Workflows is only available in specific regions, for more information check the [documentation](https://cloud.google.com/workflows/docs/locations).

### 5. Take note of Terraform Outputs

Once terraform finishes provisioning all resources, you will see its outputs. Please take note of `input_bucket` and `output_bucket` buckets. Files uploaded to the `input_bucket` bucket will be automatically processed and the redacted files will be written to the `output_bucket` bucket.
If you missed the outputs from the firs run, you can list the outputs by running

```
terraform -chdir=terraform output
```

### 6. Test

Use the command below to upload the test file into the `input_bucket`. After a few seconds, you should see a redacted PDF file in the `output_bucket`.
```
gsutil cp ./test_file.pdf [INPUT_BUCKET_FROM_OUTPUT e.g. gs://pdf-input-bucket-xxxx]
```

If you are curious about the behind the scenes, try:
- Checkout the Redacted file in the `output_bucket`.

  ```
  gsutil ls [OUTPUT_BUCKET_FROM_OUTPUT e.g. gs://pdf-output-bucket-xxxx]
  ```

- Download the redacted pdf file, open it with your preferred pdf reader, and search for text in the PDF file.
- Looking into [Cloud Workflows](https://console.cloud.google.com/workflows) in the GCP web console. You will see that a workflow execution was triggered when you uploaded the file to GCS.
- Explore the `pdf_redaction_xxxx` dataset in BigQuery and check out the metadata that was inserted into the `findings` table.


text:
package com.haulmont.restapi.auth;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * Represents CUBA anonymous REST API authentication
 */
public class CubaAnonymousAuthenticationToken extends AbstractAuthenticationToken {

    protected Object principal;

    public CubaAnonymousAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }
}


text:
require 'test_helper'

class RcrashRubyTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, RcrashRuby
  end
end


text:
<?php
class Form_Field_image extends Form_Field_upload {
}


text:
bool
is_finite(double d)
{ return (d != std::numeric_limits<double>::infinity()) && (-d != std::numeric_limits<double>::infinity()); }

int main()
{

  double zero = 0;
  double inf = 1. / zero;
  double nan = zero*inf;
  bool b = true;
  b = b && !is_finite(inf);

  (void) nan; // stop warning

  if (!b)
    return -1;
  return 0;
}


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.au.Common;

namespace OpenADK.Library.au.School{

/// A ResourceReportLineList
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
[Serializable]
public class ResourceReportLineList : SifList<ResourceReportLine>
{
	///
	/// Creates an instance of a ResourceReportLineList
	///
	public ResourceReportLineList() : base ( SchoolDTD.RESOURCEREPORTLINELIST ){}

	///
	/// Constructor that accepts values for all mandatory fields
	///
	///<param name="resourceReportLine">A ResourceReportLine</param>
	///
	public ResourceReportLineList( ResourceReportLine resourceReportLine ) : base( SchoolDTD.RESOURCEREPORTLINELIST )
	{
		this.SafeAddChild( SchoolDTD.RESOURCEREPORTLINELIST_RESOURCEREPORTLINE, resourceReportLine );
	}

	///
	/// Constructor used by the .Net Serialization formatter
	///
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected ResourceReportLineList( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	///
	/// Gets the metadata fields that make up the key of this object
	///
	/// <value>
	/// an array of metadata fields that make up the object's key
	/// </value>
	public  IElementDef[] KeyFields {
		get { return new IElementDef[] { SchoolDTD.RESOURCEREPORTLINELIST_RESOURCEREPORTLINE }; }
	}

	///Adds the value of the <c><ResourceReportLine></c> element.
	/// <param name="StartDate">A StartDate</param>
	/// <param name="CurrentCost">A CurrentCost</param>
	/// <param name="ReportRow">A ReportRow</param>
	///<remarks>
	/// <para>This form of <c>setResourceReportLine</c> is provided as a convenience method
	/// that is functionally equivalent to the method <c>AddResourceReportLine</c></para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.5</para>
	/// </remarks>
	public void AddResourceReportLine( DateTime? StartDate, MonetaryAmount CurrentCost, string ReportRow ) {
		AddChild( SchoolDTD.RESOURCEREPORTLINELIST_RESOURCEREPORTLINE, new ResourceReportLine( StartDate, CurrentCost, ReportRow ) );
	}

}}


text:
package org.apache.rya.indexing;

import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;

/**
 * A set of URIs used in GeoSPARQL
 */
public class GeoConstants {
    public static final String NS_GEO = "http://www.opengis.net/ont/geosparql#";
    public static final String NS_GEOF = "http://www.opengis.net/def/function/geosparql/";

    public static final URI XMLSCHEMA_OGC_WKT = new URIImpl(NS_GEO + "wktLiteral");
    public static final URI GEO_AS_WKT = new URIImpl(NS_GEO + "asWKT");

    public static final URI XMLSCHEMA_OGC_GML = new URIImpl(NS_GEO + "gmlLiteral");
    public static final URI GEO_AS_GML = new URIImpl(NS_GEO + "asGML");

    public static final URI GEO_SF_EQUALS = new URIImpl(NS_GEOF + "sfEquals");
    public static final URI GEO_SF_DISJOINT = new URIImpl(NS_GEOF + "sfDisjoint");
    public static final URI GEO_SF_INTERSECTS = new URIImpl(NS_GEOF + "sfIntersects");
    public static final URI GEO_SF_TOUCHES = new URIImpl(NS_GEOF + "sfTouches");
    public static final URI GEO_SF_CROSSES = new URIImpl(NS_GEOF + "sfCrosses");
    public static final URI GEO_SF_WITHIN = new URIImpl(NS_GEOF + "sfWithin");
    public static final URI GEO_SF_CONTAINS = new URIImpl(NS_GEOF + "sfContains");
    public static final URI GEO_SF_OVERLAPS = new URIImpl(NS_GEOF + "sfOverlaps");
}


text:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using NLog;
using NLog.Config;
using SP2013Access.Logging;

namespace SP2013Access
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Logger _logger;

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            RecentSites = new ObservableCollection<RecentSite>();
            LoadMenu();
        }

        public ObservableCollection<RecentSite> RecentSites { get; }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ClientTreeView.SiteLoadingEvent += ClientTreeView_SiteOpening;
            Globals.SplashScreen.LoadComplete();

            var logViewer = LogViewer;
            _logger = LogManager.GetLogger("Logger");

            Dispatcher.Invoke(() =>
            {
                var target = new LogViewerTarget
                {
                    Name = "LogViewer",
                    Layout =
                        "[${longdate:useUTC=false}] :: [${level:uppercase=true}] :: ${logger}:${callsite} :: ${message} ${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}",
                    TargetLogViewer = logViewer
                };
                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                _logger.Info("Ready");
                LoadSite();
            });
        }

        private void LoadMenu()
        {
            RecentMenuItem.DataContext = this;
            RecentSites.Clear();

            foreach (var recentSite in Globals.Configuration.RecentSites.OrderBy(recentSite => recentSite.Url))
            {
                RecentSites.Add(recentSite);
            }
        }

        private void LoadSiteMenuItem_OnClick(object sender, RoutedEventArgs e)
        {
            LoadSite();
        }

        private void ClientTreeView_SiteOpening(object sender, EventArgs e)
        {
            LoadSite();
        }

        private void LoadSite(RecentSite recentSite = null)
        {
            if (recentSite == null)
            {
                recentSite = Globals.Configuration.RecentSites.LastOrDefault();
            }

            var openSiteWindow = new OpenSiteWindow(recentSite)
            {
                Owner = this
            };

            if (openSiteWindow.ShowDialog() == true)
            {
                var clientContext = openSiteWindow.ClientContext;
                if (clientContext != null)
                {
                    _logger.Info("Connected to {0}", clientContext.Url);
                    ClientTreeView.Fill(clientContext, _logger);
                }
                LoadMenu();
            }
        }

        private void RecentMenuItem_OnClick(object sender, RoutedEventArgs e)
        {
            var menuItem = e.OriginalSource as MenuItem;
            if (menuItem != null)
            {
                var recentSite = menuItem.DataContext as RecentSite;
                LoadSite(recentSite);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            ClientTreeView.Unload();
        }
    }
}