text:
package io.github.azagniotov.stubby4j.handlers;

import io.github.azagniotov.stubby4j.annotations.GeneratedCodeClassCoverageExclusion;
import io.github.azagniotov.stubby4j.cli.CommandLineInterpreter;
import io.github.azagniotov.stubby4j.server.JettyContext;
import io.github.azagniotov.stubby4j.stubs.StubHttpLifecycle;
import io.github.azagniotov.stubby4j.stubs.StubRepository;
import io.github.azagniotov.stubby4j.stubs.StubResponse;
import io.github.azagniotov.stubby4j.stubs.proxy.StubProxyConfig;
import io.github.azagniotov.stubby4j.utils.ConsoleUtils;
import io.github.azagniotov.stubby4j.utils.DateTimeUtils;
import io.github.azagniotov.stubby4j.utils.HandlerUtils;
import io.github.azagniotov.stubby4j.utils.JarUtils;
import io.github.azagniotov.stubby4j.utils.ObjectUtils;
import io.github.azagniotov.stubby4j.utils.ReflectionUtils;
import io.github.azagniotov.stubby4j.utils.StringUtils;
import io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.RuntimeMXBean;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static io.github.azagniotov.stubby4j.utils.HandlerUtils.getHtmlResourceByName;
import static io.github.azagniotov.stubby4j.utils.StringUtils.toUpper;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.BODY;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.FILE;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.POST;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.PROXY_CONFIG;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.REQUEST;
import static io.github.azagniotov.stubby4j.yaml.ConfigurableYAMLProperty.RESPONSE;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;

@GeneratedCodeClassCoverageExclusion
public final class StatusPageHandler extends AbstractHandler implements AbstractHandlerExtension {

    private static final RuntimeMXBean RUNTIME_MX_BEAN = ManagementFactory.getRuntimeMXBean();
    private static final MemoryMXBean MEMORY_MX_BEAN = ManagementFactory.getMemoryMXBean();
    private static final List<ConfigurableYAMLProperty> FIELDS_FOR_AJAX_LINKS = unmodifiableList(asList(FILE, BODY, POST));

    private static final String TEMPLATE_LOADED_FILE_METADATA_PAIR = "%s=%s";
    private static final String TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK = "[view]";
    private static final String TEMPLATE_AJAX_TO_STATS_HYPERLINK = "[view]";
    private static final String TEMPLATE_HTML_TABLE_ROW = "
%s	%s
";
    private static final String NEXT_IN_THE_QUEUE = " NEXT IN THE QUEUE";
    private static final String HTML_BR = "
";

    private final StubRepository stubRepository;
    private final JettyContext jettyContext;

    public StatusPageHandler(final JettyContext jettyContext, final StubRepository stubRepository) {
        this.jettyContext = jettyContext;
        this.stubRepository = stubRepository;
    }

    @Override
    public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
        if (logAndCheckIsHandled("status", baseRequest, request, response)) {
            return;
        }
        baseRequest.setHandled(true);
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(HttpStatus.OK_200);
        response.setHeader(HttpHeader.SERVER.asString().toLowerCase(Locale.US), HandlerUtils.constructHeaderServerName());

        try {
            response.getWriter().println(buildStatusPageHtml());
        } catch (final Exception ex) {
            HandlerUtils.configureErrorResponse(response, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString());
        }

        ConsoleUtils.logOutgoingResponse(request.getRequestURI(), response);
    }

    private String buildStatusPageHtml() throws Exception {
        final StringBuilder builder = new StringBuilder();

        final String templateHtmlTable = getHtmlResourceByName("_table");

        builder.append(buildJvmParametersHtmlTable(templateHtmlTable));
        builder.append(buildJettyParametersHtmlTable(templateHtmlTable));
        builder.append(buildStubbyParametersHtmlTable(templateHtmlTable));
        builder.append(buildEndpointStatsHtmlTable(templateHtmlTable));

        final Map<String, StubProxyConfig> proxyConfigs = stubRepository.getProxyConfigs();
        if (!proxyConfigs.isEmpty()) {
            builder.append(HTML_BR);
            final String proxyConfigDefaultName = StubProxyConfig.Builder.DEFAULT_UUID;
            builder.append(buildStubProxyConfigtHtmlTable(proxyConfigs.get(proxyConfigDefaultName), templateHtmlTable));
            for (Map.Entry<String, StubProxyConfig> entry : proxyConfigs.entrySet()) {
                if (entry.getKey().equals(proxyConfigDefaultName)) {
                    continue;
                }
                builder.append(buildStubProxyConfigtHtmlTable(entry.getValue(), templateHtmlTable));
            }
            builder.append(HTML_BR).append(HTML_BR);
        }

        final List<StubHttpLifecycle> stubHttpLifecycles = stubRepository.getStubs();
        for (final StubHttpLifecycle stubHttpLifecycle : stubHttpLifecycles) {
            builder.append(buildStubRequestHtmlTable(stubHttpLifecycle, templateHtmlTable));
            builder.append(buildStubResponseHtmlTable(stubHttpLifecycle, templateHtmlTable));
            builder.append(HTML_BR).append(HTML_BR);
        }

        final long timestamp = System.currentTimeMillis();
        return HandlerUtils.populateHtmlTemplate("status", timestamp, timestamp, builder.toString());
    }

    private String buildStubProxyConfigtHtmlTable(final StubProxyConfig stubProxyConfig, final String templateHtmlTable) throws Exception {
        final String proxyUuid = stubProxyConfig.getUUID();
        final String ajaxLinkToRequestAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, PROXY_CONFIG, proxyUuid, "proxyConfigAsYAML");
        final StringBuilder proxyConfigTableBuilder = buildStubHtmlTableBody(proxyUuid, PROXY_CONFIG.toString(), ReflectionUtils.getProperties(stubProxyConfig));
        proxyConfigTableBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToRequestAsYaml));

        return String.format(templateHtmlTable, PROXY_CONFIG, proxyConfigTableBuilder.toString());
    }

    private String buildStubRequestHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) throws Exception {
        final String resourceId = stubHttpLifecycle.getResourceId();
        final String ajaxLinkToRequestAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, ConfigurableYAMLProperty.HTTPLIFECYCLE, "requestAsYAML");
        final StringBuilder requestTableBuilder = buildStubHtmlTableBody(resourceId, REQUEST.toString(), ReflectionUtils.getProperties(stubHttpLifecycle.getRequest()));
        requestTableBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToRequestAsYaml));

        return String.format(templateHtmlTable, REQUEST, requestTableBuilder.toString());
    }

    private String buildStubResponseHtmlTable(final StubHttpLifecycle stubHttpLifecycle, final String templateHtmlTable) throws Exception {
        final String resourceId = stubHttpLifecycle.getResourceId();
        final StringBuilder responseTableBuilder = new StringBuilder();
        final List<StubResponse> allResponses = stubHttpLifecycle.getResponses();
        for (int sequenceId = 0; sequenceId < allResponses.size(); sequenceId++) {

            final boolean isResponsesSequenced = allResponses.size() != 1;
            final int nextSequencedResponseId = stubHttpLifecycle.getNextSequencedResponseId();
            final String nextResponseLabel = (isResponsesSequenced && nextSequencedResponseId == sequenceId ? NEXT_IN_THE_QUEUE : "");
            final String responseTableTitle = (isResponsesSequenced ? String.format("%s/%s%s", RESPONSE, sequenceId, nextResponseLabel) : RESPONSE.toString());
            final StubResponse stubResponse = allResponses.get(sequenceId);
            final Map<String, String> stubResponseProperties = ReflectionUtils.getProperties(stubResponse);
            final StringBuilder sequencedResponseBuilder = buildStubHtmlTableBody(resourceId, responseTableTitle, stubResponseProperties);
            final String ajaxLinkToResponseAsYaml = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, ConfigurableYAMLProperty.HTTPLIFECYCLE, "responseAsYAML");
            sequencedResponseBuilder.append(interpolateHtmlTableRowTemplate("RAW YAML", ajaxLinkToResponseAsYaml));

            responseTableBuilder.append(String.format(templateHtmlTable, responseTableTitle, sequencedResponseBuilder.toString()));
        }

        return responseTableBuilder.toString();
    }

    private String buildJvmParametersHtmlTable(final String templateHtmlTable) throws Exception {

        final StringBuilder builder = new StringBuilder();
        if (!RUNTIME_MX_BEAN.getInputArguments().isEmpty()) {
            builder.append(interpolateHtmlTableRowTemplate("INPUT ARGS", RUNTIME_MX_BEAN.getInputArguments()));
        }
        builder.append(interpolateHtmlTableRowTemplate("HEAP MEMORY USAGE", MEMORY_MX_BEAN.getHeapMemoryUsage()));
        builder.append(interpolateHtmlTableRowTemplate("NON-HEAP MEMORY USAGE", MEMORY_MX_BEAN.getNonHeapMemoryUsage()));

        return String.format(templateHtmlTable, "jvm", builder.toString());
    }

    private String buildJettyParametersHtmlTable(final String templateHtmlTable) throws Exception {

        final StringBuilder builder = new StringBuilder();
        final String host = jettyContext.getHost();
        final int adminPort = jettyContext.getAdminPort();
        builder.append(interpolateHtmlTableRowTemplate("HOST", host));
        builder.append(interpolateHtmlTableRowTemplate("ADMIN PORT", adminPort));
        builder.append(interpolateHtmlTableRowTemplate("STUBS PORT", jettyContext.getStubsPort()));
        builder.append(interpolateHtmlTableRowTemplate("STUBS TLS PORT", jettyContext.getStubsTlsPort()));
        final String endpointRegistration = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), AdminPortalHandler.ADMIN_ROOT, host, adminPort);
        builder.append(interpolateHtmlTableRowTemplate("NEW STUB DATA POST URI", endpointRegistration));

        return String.format(templateHtmlTable, "jetty parameters", builder.toString());
    }

    private String buildStubbyParametersHtmlTable(final String templateHtmlTable) throws Exception {

        final StringBuilder builder = new StringBuilder();
        builder.append(interpolateHtmlTableRowTemplate("VERSION", JarUtils.readManifestImplementationVersion()));
        builder.append(interpolateHtmlTableRowTemplate("RUNTIME CLASSPATH", RUNTIME_MX_BEAN.getClassPath()));
        builder.append(interpolateHtmlTableRowTemplate("LOCAL BUILT DATE", JarUtils.readManifestBuiltDate()));
        builder.append(interpolateHtmlTableRowTemplate("UPTIME", HandlerUtils.calculateStubbyUpTime(RUNTIME_MX_BEAN.getUptime())));
        builder.append(interpolateHtmlTableRowTemplate("INPUT ARGS", CommandLineInterpreter.PROVIDED_OPTIONS));
        builder.append(interpolateHtmlTableRowTemplate("STUBBED ENDPOINTS", stubRepository.getStubs().size()));
        builder.append(interpolateHtmlTableRowTemplate("LOADED YAML", buildLoadedFileMetadata(stubRepository.getYamlConfig())));

        if (!stubRepository.getExternalFiles().isEmpty()) {
            final StringBuilder externalFilesMetadata = new StringBuilder();
            for (Map.Entry<File, Long> entry : stubRepository.getExternalFiles().entrySet()) {
                final File externalFile = entry.getKey();
                externalFilesMetadata.append(buildLoadedFileMetadata(externalFile));
            }
            builder.append(interpolateHtmlTableRowTemplate("LOADED EXTERNAL FILES", externalFilesMetadata.toString()));
        }

        return String.format(templateHtmlTable, "stubby4j parameters", builder.toString());
    }

    private String buildEndpointStatsHtmlTable(final String templateHtmlTable) throws Exception {

        final StringBuilder builder = new StringBuilder();
        if (stubRepository.getResourceStats().isEmpty()) {
            builder.append(interpolateHtmlTableRowTemplate("ENDPOINT HITS", "No requests were made to stubby yet"));
        } else {
            builder.append(interpolateHtmlTableRowTemplate("ENDPOINT HITS", TEMPLATE_AJAX_TO_STATS_HYPERLINK));
        }

        return String.format(templateHtmlTable, "stubby stats", builder.toString());
    }

    private String buildLoadedFileMetadata(final File file) throws IOException {
        final StringBuilder builder = new StringBuilder();
        builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "parentDir", determineParentDir(file))).append(HTML_BR);
        builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "name", file.getName())).append(HTML_BR);
        builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "size", String.format("%1$,.2f", ((double) file.length() / 1024)) + "kb")).append(HTML_BR);
        builder.append(String.format(TEMPLATE_LOADED_FILE_METADATA_PAIR, "lastModified", DateTimeUtils.systemDefault(file.lastModified()))).append(HTML_BR);

        return "
" + builder.toString() + "
";
    }

    private String determineParentDir(final File file) throws IOException {
        return (ObjectUtils.isNull(file.getParentFile()) ? file.getCanonicalPath().replaceAll(file.getName(), "") : file.getParentFile().getCanonicalPath() + "/");
    }

    private StringBuilder buildStubHtmlTableBody(final String resourceId, final String stubTypeName, final Map<String, String> stubObjectProperties) throws Exception {
        final StringBuilder builder = new StringBuilder();

        for (final Map.Entry<String, String> keyValue : stubObjectProperties.entrySet()) {
            final String value = keyValue.getValue();
            final String key = keyValue.getKey();

            if (!StringUtils.isSet(value)) {
                continue;
            }

            builder.append(buildHtmlTableSingleRow(resourceId, stubTypeName, key, value));
        }
        return builder;
    }

    private String buildHtmlTableSingleRow(final String resourceId, final String stubTypeName, final String fieldName, final String value) {

        if (!ConfigurableYAMLProperty.isUnknownProperty(fieldName) && FIELDS_FOR_AJAX_LINKS.contains(ConfigurableYAMLProperty.valueOf(toUpper(fieldName)))) {
            final String cleansedStubTypeName = stubTypeName.replaceAll(NEXT_IN_THE_QUEUE, "");   //Only when there are sequenced responses
            final String ajaxHyperlink = String.format(TEMPLATE_AJAX_TO_RESOURCE_HYPERLINK, resourceId, cleansedStubTypeName, fieldName);
            return interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), ajaxHyperlink);
        }

        final String escapedValue = StringUtils.escapeHtmlEntities(value);
        if (fieldName.equals(ConfigurableYAMLProperty.URL.toString())) {
            final String urlAsHyperlink = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTP.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsPort());
            final String tlsUrlAsHyperlink = HandlerUtils.linkifyRequestUrl(HttpScheme.HTTPS.asString(), escapedValue, jettyContext.getHost(), jettyContext.getStubsTlsPort());

            final String tableRowWithUrl = interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), urlAsHyperlink);
            final String tableRowWithTlsUrl = interpolateHtmlTableRowTemplate("TLS " + StringUtils.toUpper(fieldName), tlsUrlAsHyperlink);

            return String.format("%s%s", tableRowWithUrl, tableRowWithTlsUrl);
        }

        return interpolateHtmlTableRowTemplate(StringUtils.toUpper(fieldName), escapedValue);
    }

    private String interpolateHtmlTableRowTemplate(final Object... tokens) {
        return String.format(TEMPLATE_HTML_TABLE_ROW, tokens);
    }
}


text:
"""
PyMdown Settings.

Manage Settings

Licensed under MIT
Copyright (c) 2014 - 2015 Isaac Muse <isaacmuse@gmail.com>
"""
from __future__ import unicode_literals
from __future__ import absolute_import
import codecs
import traceback
import os.path as path
import cgi
from collections import OrderedDict
from copy import deepcopy
from .. import util
from .. import logger
from .. import compat
from .merge import MergeSettings
from .validate import Validate
try:
    from pygments.styles import get_style_by_name
    from pygments.formatters import get_formatter_by_name
    PYGMENTS_AVAILABLE = True
except Exception:  # pragma: no cover
    PYGMENTS_AVAILABLE = False

def get_pygment_style(style, css_class='codehilite'):
    """Get the specified pygments sytle CSS."""

    try:
        # Try and request pygments to generate it
        text = get_formatter_by_name('html', style=style).get_style_defs('.' + css_class)
    except Exception:
        # Try and request pygments to generate default
        text = get_formatter_by_name('html', style="default").get_style_defs('.' + css_class)
    return '<style>\n%s\n</style>\n' % text if text is not None else ""

class Settings(object):
    """
    Settings object for merging global settings with frontmatter.

    Contains global settings, and a user can
    retrieve a settings dict merged with a file's frontmatter.
    """

    def __init__(self, **kwargs):
        """Initialize."""

        self.settings = {
            "page": {
                "title": None,
                "encoding": kwargs.get('output_encoding', 'utf-8'),
                "destination": None,
                "basepath": None,
                "relpath": None,
                "css": [],
                "js": [],
                "content": '',
            },
            "extra": {},
            "pymdown_settings": {}
        }
        self.critic = kwargs.get('critic', util.CRITIC_IGNORE)
        self.plain = kwargs.get('plain', False)
        self.batch = kwargs.get('batch', False)
        self.encoding = util._get_encoding(kwargs.get('encoding', 'utf-8'))
        self.preview = kwargs.get('preview', False)
        self.is_stream = kwargs.get('stream', False)
        self.force_stdout = kwargs.get('force_stdout', False)
        self.force_no_template = kwargs.get('force_no_template', False)
        self.pygments_noclasses = False

        # Use default settings file if one was not provided
        settings_path = kwargs.get('settings_path', None)
        self.settings_path = settings_path if settings_path is not None else path.basename(util.DEFAULT_SETTINGS)

    def unpack_settings_file(self):  # pragma: no cover
        """Unpack default settings file."""

        text = util.load_text_resource(util.DEFAULT_SETTINGS, internal=True)
        try:
            with codecs.open(self.settings_path, "w", encoding="utf-8") as f:
                f.write(text)
        except Exception:
            logger.Log.error(traceback.format_exc())

    def read_settings(self):
        """
        Get and read the settings.

        Unpack the settings file if needed.
        """

        settings = None

        # Unpack settings file if needed
        if not path.exists(self.settings_path):
            self.unpack_settings_file()  # pragma: no cover

        # Try and read settings file
        try:
            with codecs.open(self.settings_path, "r", encoding='utf-8') as f:
                contents = f.read()
                settings = util.yaml_load(contents)
        except Exception:  # pragma: no cover
            logger.Log.error(traceback.format_exc())

        if settings is None:
            settings = OrderedDict()

        Validate(provide_defaults=True).validate(settings)

        self.settings["pymdown_settings"] = settings

    def get(self, file_name, **kwargs):
        """Get the complete settings object for the given file."""

        output = kwargs.get('output', None)
        basepath = kwargs.get('basepath', None)
        relpath = kwargs.get('relpath', None)
        frontmatter = kwargs.get('frontmatter', None)
        title = kwargs.get('title', None)

        self.file_name = file_name
        settings = deepcopy(self.settings)
        settings["page"]["destination"] = util.resolve_destination(
            output,
            self.file_name,
            critic_mode=self.critic,
            batch=self.batch
        )
        settings["page"]["basepath"] = util.resolve_base_path(
            basepath,
            self.file_name,
            is_stream=self.is_stream
        )
        settings["page"]["relpath"] = util.resolve_relative_path(relpath)
        if frontmatter is not None:
            # Apply frontmatter by merging it to the settings
            merge = MergeSettings(self.file_name, self.is_stream)
            merge.merge(frontmatter, settings)

        # Handle title
        if title is None and file_name is not None:
            title = path.splitext(path.basename(path.abspath(file_name)))[0]
        if settings["page"]["title"] is not None:
            title = settings["page"]["title"]
        else:
            title = compat.to_unicode(title) if title else "Untitled"
        settings["page"]["title"] = cgi.escape(title)

        # Store destination as our output reference directory.
        # This is used for things like converting relative paths.
        # If there is no output location, try to come up with a rational
        # output reference directory by falling back to the source file.
        if settings['page']['destination'] is not None:
            self.out = path.dirname(path.abspath(settings['page']['destination']))
        elif file_name:
            self.out = path.dirname(path.abspath(self.file_name))
        else:
            self.out = None

        # Try to come up with a sane relative path since one was not provided
        if settings['page']['relpath'] is None:
            if settings['page']['destination'] is not None:
                settings['page']['relpath'] = path.dirname(
                    path.abspath(settings['page']['destination'])
                )
            elif file_name:
                settings['page']['relpath'] = path.dirname(
                    path.abspath(self.file_name)
                )

        # Process special output flags
        if self.force_stdout:
            settings["page"]["destination"] = None
        if self.force_no_template:
            settings['pymdown_settings']['template'] = None

        # Do some post processing on the settings
        self.post_process_settings(settings)
        return settings

    def load_highlight(self, highlight_style, use_pygments_css, pygments_class):
        """Load Syntax highlighter CSS."""

        style = None

        if not self.plain:
            if highlight_style is not None and use_pygments_css:
                # Ensure pygments is enabled in the highlighter
                style = get_pygment_style(highlight_style, pygments_class)

        return style

    def set_style(self, extensions, settings):
        """Load up needed Pygments style."""

        style = settings["pymdown_settings"]['pygments_style']

        if not PYGMENTS_AVAILABLE:  # pragma: no cover
            settings["pymdown_settings"]["use_pygments_css"] = False

        if settings["pymdown_settings"]["use_pygments_css"]:
            # Ensure a working style is set
            try:
                # Check if the desired style exists internally
                get_style_by_name(style)
            except Exception:
                logger.Log.error("Cannot find style: %s! Falling back to 'default' style." % style)
                style = "default"

        settings["pymdown_settings"]["pygments_style"] = style
        settings["page"]["pygments_style"] = self.load_highlight(
            style,
            settings["pymdown_settings"]["use_pygments_css"],
            settings["pymdown_settings"]['pygments_class']
        )

    def post_process_settings(self, settings):
        """Process the settings files making needed adjustement."""

        extensions = settings["pymdown_settings"]["markdown_extensions"]

        critic_mode = "ignore"
        if self.critic & util.CRITIC_ACCEPT:
            critic_mode = "accept"
        elif self.critic & util.CRITIC_REJECT:
            critic_mode = "reject"
        elif self.critic & util.CRITIC_VIEW:
            critic_mode = "view"

        # Remove critic extension if manually defined
        # and remove plainhtml if defined and --plain-html is specified on CLI
        if "pymdownx.critic" in extensions and critic_mode != 'ignore':
            del extensions["pymdownx.critic"]
        if "pymdownx.plainhtml" in extensions and self.plain:
            del extensions["pymdownx.plainhtml"]

        # Ensure previews are using absolute paths or relative paths
        if self.preview or not settings["pymdown_settings"]["disable_path_conversion"]:
            # Add pathconverter extension if not already set.
            if "pymdownx.pathconverter" not in extensions:
                extensions["pymdownx.pathconverter"] = {
                    "base_path": "${BASE_PATH}",
                    "relative_path": "${REL_PATH}" if not self.preview else "${OUTPUT}",
                    "absolute": settings["pymdown_settings"]["path_conversion_absolute"]
                }
            elif self.preview and "pymdownx.pathconverter" in extensions:
                if extensions["pymdownx.pathconverter"] is None:
                    extensions["pymdownx.pathconverter"] = {}
                if "base_path" not in extensions["pymdownx.pathconverter"]:
                    extensions["pymdownx.pathconverter"]["base_path"] = "${BASE_PATH}"
                extensions["pymdownx.pathconverter"]["relative_path"] = "${OUTPUT}"

        # Add critic to the end since it is most reliable when applied to the end.
        if critic_mode != "ignore":
            extensions["pymdownx.critic"] = {"mode": critic_mode}

        # Append plainhtml.
        # Most reliable when applied to the end. Okay to come after critic.
        if self.plain:
            extensions['pymdownx.plainhtml'] = None

        # Set extensions to its own key
        settings["pymdown_settings"]["markdown_extensions"] = extensions

        # Set style
        self.set_style(extensions, settings)

redpajama_set_name: RedPajamaGithub


text:
/*
* SonarSensor.cpp
*
*  Created on: Oct 26, 2017
*      Author: Tyler Lucas <tyblu@live.com>
*/

#include "SonarSensor.h"

#define MAX_ECHO_TIME_US 2332UL	// 2 * 40 cm / speed of sound in microseconds = 2332...
#define MEASUREMENT_DELAY_MS 60	// time between measurements [ms]

//#define TybluLsq_DEBUG_MODE
#ifdef TybluLsq_DEBUG_MODE
#	include <Arduino.h>	// only for Serial debug messages
#	define DEBUG1(x) Serial.print("SonarSensor : "); Serial.println(x); delay(2)	// note missing ';'
#	define DEBUG2(x,y) Serial.print("SonarSensor : "); Serial.print(x); Serial.println(y); delay(2)	// note missing ';'
#else
#	define DEBUG1(x)
#	define DEBUG2(x,y)
#endif

/* Post-conditions:
 - triggerPin set to output and LOW
 - echoPin set to input
 */
SonarSensor::SonarSensor(int triggerPin, int echoPin)
	: triggerPin(triggerPin)
	, echoPin(echoPin)
{
	pinMode(triggerPin, OUTPUT);
	digitalWrite(triggerPin, LOW);
	pinMode(echoPin, INPUT);
}

/* Preconditions: triggerPin is LOW. */
uint32_t SonarSensor::getMeasurement()
{
	digitalWrite(triggerPin, LOW);
	delayMicroseconds(2);
	digitalWrite(triggerPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(triggerPin, LOW);

	return pulseIn(echoPin, HIGH, MAX_ECHO_TIME_US);
}

uint32_t SonarSensor::getMeasurement(uint16_t count)
{
	uint32_t sum = 0;
	uint16_t iteration = 0;
	while (iteration < count)
	{
		sum += getMeasurement();
		delay(MEASUREMENT_DELAY_MS);
		iteration++;
	}
	return (sum + count/2)/ count;
}


text:
import scala.concurrent.{ExecutionContext, Future}
import ExecutionContext.Implicits.global

object Start {
  def main(args: Array[String]) {
    Foo.call(Start.<ref>func1)
  }

  def func1(a: A) = Future(a)
  def func1(a: A, b: Int) = Future(a)
}

object Foo {
  def call[A <: Letter, B](func: (A) => Future[A]): Unit = {
    // implementation
  }
}

sealed trait Letter {
  def name: String
}

class A extends Letter {
  override def name = "A"
}


text:
<!DOCTYPE html>

    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

TODO write content

    index.html

    <button type="button" onclick="toggleShared()">shared</button>


text:
var Notify = window.Notify.default;

function onShowNotification () {
  // console.log('notification is shown!');
}

function onCloseNotification () {
  // console.log('notification is closed!');
}

function onClickNotification () {
  // console.log('notification was clicked!');
}

function onErrorNotification () {
  console.error('Error showing notification. You may need to request permission.');
}

function onPermissionGranted (data) {
  console.log('Permission has been granted by the user');
  doNotification(data);
}

function onPermissionDenied() {
  console.warn('Permission has been denied by the user');
}

function doNotification(event) {
  var myNotification = new Notify("Neue Buchung", {
    body: event.payment_type + ": " + event.value + "€ von/nach " + event.src_dest + ": " + event.description,
    tag: event.id,
    notifyShow: onShowNotification,
    notifyClose: onCloseNotification,
    notifyClick: onClickNotification,
    notifyError: onErrorNotification,
    timeout: 10
  });

  myNotification.show();
}

/** lookup constant name from value */
EventSource.prototype.byIndex = function(i){
  var ii = 0;

  for (var lbl in this){
    if (ii == i)
      return lbl;

    ii += 1;
  }
};

function initEventSource(attempt = 0) {
  var es = new EventSource(SSE_URL);
  console.info('Attempt #' + attempt + ' connecting to ' + es.url);

  es.onerror = function(e) {
    es.close();
    backoff = Math.pow(2, attempt++);
    console.log('Error establishing EventSource connection to '
      + es.url
      + '; current status is: '
      + es.byIndex(es.readyState)
      + '. Trying again in '
      + backoff + ' seconds'
    );

    setTimeout(initEventSource, 1000 * backoff, attempt);
  };

  es.onopen = function(e) {
    attempt = 0;
    console.log('Successfully established EventSource connection to ' + es.url);
  };

  es.onmessage = function(event) {
    console.info(event);

    var doc = JSON.parse(event.data);

    if (!Notify.needsPermission) {
        doNotification(doc);
    } else if (Notify.isSupported()) {
        Notify.requestPermission(onPermissionGranted(doc), onPermissionDenied(doc));
    }
  };
};

initEventSource();


text:
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using NUnit.Framework;
using XenAdmin.Commands;
using XenAdmin.Network;
using XenAdmin.Wizards.CrossPoolMigrateWizard;
using XenAdmin.Wizards.GenericPages;

namespace XenAdminTests.WizardTests.tampa_cpm_one_and_two_host_pools
{
    [TestFixture, Category(TestCategories.UICategoryB)]
    internal class CrossPoolMigrateWizardTest : CrossPoolMigrateWizardTestBase
    {
        public CrossPoolMigrateWizardTest()
            : base(new[] { "Destination Pool", "Storage", "Networking", "Migration Network", "Finish" }, true, true)
        {
            TargetPool = "PoolOfOne";
            SourcePool = "16And23";
            Vm = "16local";
        }
    }

    [TestFixture, Category(TestCategories.UICategoryB)]
    internal class CrossPoolMigrateWizardIntraPoolTest : CrossPoolMigrateWizardTestBase
    {
        public CrossPoolMigrateWizardIntraPoolTest()
            : base(new[] { "Destination Pool", "Storage", "Migration Network", "Finish" }, true, true)
        {
            TargetPool = SourcePool = "16And23";
            Vm = "16local";
        }
    }

    internal abstract class CrossPoolMigrateWizardTestBase : WizardTest<CrossPoolMigrateWizard>
    {
        public CrossPoolMigrateWizardTestBase(string[] pageNames, bool canFinish, bool doFinish)
            : base(pageNames, canFinish, doFinish)

        {
        }

        protected string TargetPool { set; private get; }
        protected string SourcePool { set; private get; }
        protected string Vm { set; private get; }

        protected override CrossPoolMigrateWizard NewWizard()
        {
            IXenConnection connection = GetAnyConnection(c => c.Name == SourcePool);
            return new CrossPoolMigrateWizard(connection,
                new SelectedItemCollection(new SelectedItem(GetAnyVM(v => v.Name() == Vm))), null, WizardMode.Migrate);
        }

        protected override void TestPage(string pageName)
        {
            if (pageName == "Destination Pool")
                MW(()=>
                       {
                           Thread.Sleep(1000); //Allow the destination combo box to populate
                           ComboBox cb = TestUtils.GetComboBox(wizard, "m_pageDestination.m_comboBoxConnection");
                           SelectItemFromComboBox(cb, TargetPool);
                           Thread.Sleep(3000); //Allow the data grid view to populate
                       });

        }

        private void SelectItemFromComboBox(ComboBox cb, string itemName)
        {
            foreach(IEnableableXenObjectComboBoxItem item in cb.Items)
            {
                if (item.Item.Name() == itemName)
                {
                    cb.SelectedItem = item;
                    return;
                }
            }
        }
    }
}


text:
<!--
  Copyright The Ohio State University Research Foundation, The University of Chicago -
Argonne National Laboratory, Emory University, SemanticBits LLC, and Ekagra Software Technologies Ltd.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-general/LICENSE.txt for details.
-->
<?xml version="1.0" encoding="UTF-8"?>

<!-- ===================================================================== -->
<!--                                                                       -->
<!--  JBoss Server Configuration                                           -->
<!--                                                                       -->
<!-- ===================================================================== -->

<!-- $Id: postgres-ds.xml,v 1.1 2007-04-10 20:52:21 parmarv Exp $ -->
<!-- ==================================================================== -->
<!--  Datasource config for Postgres                                      -->
<!-- ==================================================================== -->

<datasources>

  <local-tx-datasource>
    <jndi-name>csmupt</jndi-name>
    <connection-url>jdbc:postgresql://<<server_name>>:5432/postgres</connection-url>
    <driver-class>org.postgresql.Driver</driver-class>
    <user-name><<postgres_database_user_name>></user-name>
    <password><<postgres_database_password>></password>
        <!-- sql to call when connection is created.  Can be anything, select 1 is valid for PostgreSQL
        <new-connection-sql>select 1</new-connection-sql>
        -->

        <!-- sql to call on an existing pooled connection when it is obtained from pool.  Can be anything, select 1 is valid for PostgreSQL
        <check-valid-connection-sql>select 1</check-valid-connection-sql>
        -->

      <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
      <metadata>
         <type-mapping>PostgreSQL 8.2</type-mapping>
      </metadata>
  </local-tx-datasource>

</datasources>


text:
/* global window, $ */
var code = require('./code');

module.exports = {
    launch: function () {
        window.app = this;
        code.docWrite('Woo! View source to see what rendered me.');
    }
};

$(function () {
    module.exports.launch();
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: Q3PopupMenu Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

Qt3SupportLight

Q3PopupMenu

A

A

A

                Print

Contents

Public Functions

Detailed Description

Q3PopupMenu Class Reference

The Q3PopupMenu class is a thin compatibility wrapper around QMenu. More...

 #include <Q3PopupMenu>

This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information.

Inherits: QMenu.

List of all members, including inherited members

Public Functions

 	Q3PopupMenu ( QWidget * parent = 0, const char * name = 0 )

 int 	exec ()

 int 	exec ( const QPoint & pos, int indexAtPoint = 0 )

 int 	margin () const

 void 	setMargin ( int margin )

34 public functions inherited from QMenu

221 public functions inherited from QWidget

29 public functions inherited from QObject

13 public functions inherited from QPaintDevice

Additional Inherited Members

4 properties inherited from QMenu

58 properties inherited from QWidget

1 property inherited from QObject

19 public slots inherited from QWidget

1 public slot inherited from QObject

4 signals inherited from QMenu

1 signal inherited from QWidget

1 signal inherited from QObject

2 static public members inherited from QMenu

4 static public members inherited from QWidget

7 static public members inherited from QObject

16 protected functions inherited from QMenu

37 protected functions inherited from QWidget

8 protected functions inherited from QObject

1 protected function inherited from QPaintDevice

1 protected slot inherited from QWidget

Detailed Description

The Q3PopupMenu class is a thin compatibility wrapper around QMenu.

Use QMenu in new applications. Note that the menu's actions must be Q3Actions.

Member Function Documentation

Q3PopupMenu::Q3PopupMenu ( QWidget * parent = 0, const char * name = 0 )

Constructs a menu with the given parent and name.

int Q3PopupMenu::exec ()

Pops up the menu and returns the ID of the action that was selected.

See also QMenu::exec().

int Q3PopupMenu::exec ( const QPoint & pos, int indexAtPoint = 0 )

Pops up the menu at coordinate pos and returns the ID of the action that was selected.

If indexAtPoint is specified, the menu will pop up with the item at index indexAtPoint under the mouse cursor.

See also QMenu::exec().

int Q3PopupMenu::margin () const

Returns the width of the margin around the contents of the widget.

This function uses QWidget::getContentsMargins() to get the margin.

This function was introduced in Qt 4.2.

See also setMargin() and QWidget::getContentsMargins().

void Q3PopupMenu::setMargin ( int margin )

Sets the width of the margin around the contents of the widget to margin.

This function uses QWidget::setContentsMargins() to set the margin.

This function was introduced in Qt 4.2.

See also margin() and QWidget::setContentsMargins().

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
<!DOCTYPE html>

	<title>Legendary Jazz</title>

WELCOME to LEGENDARY JAZZ🎷

Here I will upload notable jazz recordings, history, and opinions about Jazz

Home

Recordings

History

Op-Eds

Village Vanguard Website

MY PERSONAL FAVORITE JAZZ PLAYERS:

Charlie Parker: Personal Website

Duke Ellington: Personal Website

Miles Davis: Personal Website

Benny Goodman: Personal Website

<video width="500" height="300" controls>
  <source src="Charlie Parker.mp4" type="video/mp4">
</video>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Brilliant.ProjectStudio
{
    /// <summary>
    /// 配置管理
    /// </summary>
    public static class ConfigMgr
    {
        #region 成员变量
        private const string PROVIDER_FILENAME = "Provider.json";
        private const string TEMPLATE_FILENAME = "Template.json";
        private const string LOGIN_FILENAME = "Login.json";
        private static string configPath;
        private static string templatePath;
        #endregion

        /// <summary>
        /// 配置文件路径
        /// </summary>
        public static string ConfigPath
        {
            get { return ConfigMgr.configPath; }
        }

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static ConfigMgr()
        {
            configPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\ProjectStudio";
            if (!Directory.Exists(configPath))
            {
                Directory.CreateDirectory(configPath);
            }
            templatePath = configPath + "\\Template";
            if (!Directory.Exists(templatePath))
            {
                Directory.CreateDirectory(templatePath);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="fileFullName">全路径</param>
        /// <param name="content">内容</param>
        public static void Save(string fileFullName, string content)
        {
            using (FileStream fs = new FileStream(fileFullName, FileMode.Create, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(content);
                IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length, (asyncResult) =>
                {
                    FileStream stream = (FileStream)asyncResult.AsyncState;
                    stream.EndWrite(asyncResult);
                },
                    fs);
                fs.Flush();
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="fileFullName">全路径</param>
        /// <returns>配置</returns>
        public static T Load<T>(string fileFullName) where T : new()
        {
            if (!File.Exists(fileFullName))
            {
                return default(T);
            }
            string config = File.ReadAllText(fileFullName);
            return JsonSerializer.JSDeSerialize<T>(config);
        }

        /// <summary>
        /// 获取数据库驱动程序列表
        /// </summary>
        public static List<ProviderInfo> GetProviders()
        {
            string fullName = configPath + "\\" + PROVIDER_FILENAME;
            if (!File.Exists(fullName))
            {
                List<ProviderInfo> list = new List<ProviderInfo>();
                ProviderInfo p1 = new ProviderInfo();
                p1.Name = "SqlServer";
                p1.ProviderName = "Brilliant.Data.Provider.SqlServer";
                p1.ConnectionString = "Data Source={0};Database={1};uid={2};pwd={3}";
                list.Add(p1);

                ProviderInfo p2 = new ProviderInfo();
                p2.Name = "MySql";
                p2.ProviderName = "Brilliant.Data.Provider.MySql";
                p2.ConnectionString = "Data Source={0};Database={1};User Id={2};Password={3};charset=utf8;";
                list.Add(p2);

                ProviderInfo p3 = new ProviderInfo();
                p3.Name = "Oracle";
                p3.ProviderName = "Brilliant.Data.Provider.Oracle";
                p3.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT=1521))(CONNECT_DATA=(SERVICE_NAME={1})));Persist Security Info=True;User ID={2};Password={3};";
                list.Add(p3);

                ProviderInfo p4 = new ProviderInfo();
                p4.Name = "SQLite";
                p4.ProviderName = "Brilliant.Data.Provider.SQLite";
                p4.ConnectionString = @"Data Source={0}\{1};New=False;Compress=True;Synchronous=Off;UTF8Encoding=True;Version=3;";
                list.Add(p4);
                string content = JsonSerializer.JSSerialize(list);
                Save(fullName, content);
                return list;
            }
            else
            {
                return Load<List<ProviderInfo>>(fullName);
            }
        }

        /// <summary>
        /// 保存数据库驱动程序列表
        /// </summary>
        public static void SetProviders(List<ProviderInfo> list)
        {
            string fullName = configPath + "\\" + PROVIDER_FILENAME;
            string content = JsonSerializer.JSSerialize(list);
            Save(fullName, content);
        }

        /// <summary>
        /// 获取模板列表
        /// </summary>
        public static List<TemplateInfo> GetTemplates()
        {
            string fullName = configPath + "\\" + TEMPLATE_FILENAME;
            if (!File.Exists(fullName))
            {
                List<TemplateInfo> list = new List<TemplateInfo>();
                TemplateInfo t1 = new TemplateInfo();
                t1.Name = "ComEntity";
                t1.Path = String.Format("{0}\\{1}.tt", templatePath, t1.Name);
                t1.Output = ".cs";
                t1.FileType = "Entity";
                list.Add(t1);
                File.WriteAllText(t1.Path, ResTemplate.ComEntity);

                TemplateInfo t2 = new TemplateInfo();
                t2.Name = "ComBLL";
                t2.Path = String.Format("{0}\\{1}.tt", templatePath, t2.Name);
                t2.Output = ".cs";
                t2.FileType = "BizBase";
                list.Add(t2);
                File.WriteAllText(t2.Path, ResTemplate.ComBLL);

                TemplateInfo t3 = new TemplateInfo();
                t3.Name = "ComBLLExtend";
                t3.Path = String.Format("{0}\\{1}.tt", templatePath, t3.Name);
                t3.Output = ".cs";
                t3.FileType = "Biz";
                list.Add(t3);
                File.WriteAllText(t3.Path, ResTemplate.ComBLLExtend);

                TemplateInfo t4 = new TemplateInfo();
                t4.Name = "OAEntity";
                t4.Path = String.Format("{0}\\{1}.tt", templatePath, t4.Name);
                t4.Output = ".cs";
                t4.FileType = "Entity";
                list.Add(t4);
                File.WriteAllText(t4.Path, ResTemplate.OAEntity);

                TemplateInfo t5 = new TemplateInfo();
                t5.Name = "OABLL";
                t5.Path = String.Format("{0}\\{1}.tt", templatePath, t5.Name);
                t5.Output = ".cs";
                t5.FileType = "Biz";
                list.Add(t5);
                File.WriteAllText(t5.Path, ResTemplate.OABLL);

                TemplateInfo t6 = new TemplateInfo();
                t6.Name = "OABLLExtend";
                t6.Path = String.Format("{0}\\{1}.tt", templatePath, t6.Name);
                t6.Output = ".cs";
                t6.FileType = "Biz";
                list.Add(t6);
                File.WriteAllText(t6.Path, ResTemplate.OABLLExtend);

                string content = JsonSerializer.JSSerialize(list);
                Save(fullName, content);
                return list;
            }
            else
            {
                return Load<List<TemplateInfo>>(fullName);
            }
        }

        /// <summary>
        /// 获取登录信息列表
        /// </summary>
        public static List<LoginInfo> GetLogins()
        {
            string fullName = configPath + "\\" + LOGIN_FILENAME;
            if (!File.Exists(fullName))
            {
                List<LoginInfo> list = new List<LoginInfo>();
                LoginInfo info = new LoginInfo();
                info.DefaultDB = "master";
                info.Pwd = "123456";
                info.ServerName = "127.0.0.1";
                info.ServerType = "SqlServer";
                info.Uid = "sa";
                list.Add(info);
                string content = JsonSerializer.JSSerialize(list);
                Save(fullName, content);
                return list;
            }
            else
            {
                return Load<List<LoginInfo>>(fullName);
            }
        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        public static void SetLogins(List<LoginInfo> list)
        {
            string fullName = configPath + "\\" + LOGIN_FILENAME;
            string content = JsonSerializer.JSSerialize(list);
            Save(fullName, content);
        }
    }
}


text:
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
	use SoftDeletes;

	protected $fillable = [ 'title', 'content' ];

	protected $perPage = 20;

	public function setPerPage ($perPage) {
		// if the value is somehow not falsy
		if ($perPage) {
			parent::setPerPage($perPage);
		}

		return $this;
	}

	public function scopeSearch ($query, $search) {
		if (!$search) {
			return;
		}
		$this->scopeSearchOnTitle($query, $search);
		$this->scopeSearchOnContent($query, $search);
	}

	public function scopeSearchOnTitle ($query, $search) {
		if (!$search) {
			return;
		}

		$query->orWhere('title', 'LIKE', sprintf("%%%s%%", $search));
	}

	public function scopeSearchOnContent ($query, $search) {
		if (!$search) {
			return;
		}
		$query->orWhere('content', 'LIKE', sprintf("%%%s%%", $search));
	}

	public function tags () {
		return $this->belongsToMany(Tag::class);
	}

	public function user () {
		return $this->belongsTo(User::class);
	}
}


text:
package com.wci.umls.server.jpa.algo;

import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.google.common.io.Files;
import com.wci.umls.server.helpers.CancelException;
import com.wci.umls.server.helpers.ConfigUtility;

/**
 * File sorter for RF2 files. This creates files with standard file names in the
 * specified output directory. See the source code for details.
 */
public class Rf2FileSorter {

  /** The sort by effective time. */
  private boolean sortByEffectiveTime = false;

  /** The require all files. */
  private boolean requireAllFiles = false;

  /** The input dir. */
  private String inputDir = null;

  /** The output dir. */
  private String outputDir = null;

  /** The cancel flag. */
  private boolean requestCancel = false;

  /** The directory map. */
  Map<String, String> dirMap = new HashMap<>();

  /**
   * Instantiates an empty {@link Rf2FileSorter}.
   *
   * @throws Exception if anything goes wrong
   */
  public Rf2FileSorter() throws Exception {
    dirMap = new HashMap<>();

    dirMap.put("sct2_Concept_", "/Terminology");
    dirMap.put("sct2_Relationship_", "/Terminology");
    dirMap.put("sct2_StatedRelationship_", "/Terminology");
    dirMap.put("sct2_Description_", "/Terminology");
    dirMap.put("sct2_TextDefinition_", "/Terminology");
    dirMap.put("Refset_Simple", "/Refset/Content");
    dirMap.put("AttributeValue", "/Refset/Content");
    dirMap.put("AssociationReference", "/Refset/Content");
    // dirMap.put("ComplexMap", "/Refset/Map");
    dirMap.put("ExtendedMap", "/Refset/Map");
    dirMap.put("SimpleMap", "/Refset/Map");
    dirMap.put("Language", "/Refset/Language");
    dirMap.put("RefsetDescriptor", "/Refset/Metadata");
    dirMap.put("ModuleDependency", "/Refset/Metadata");
    dirMap.put("DescriptionType", "/Refset/Metadata");
  }

  /**
   * Sets the input dir.
   *
   * @param inputDir the input dir
   */
  public void setInputDir(String inputDir) {
    this.inputDir = inputDir;
  }

  /**
   * Sets the output dir.
   *
   * @param outputDir the output dir
   */
  public void setOutputDir(String outputDir) {
    this.outputDir = outputDir;
  }

  /**
   * Sets the sort by effective time.
   *
   * @param sortByEffectiveTime the sort by effective time
   */
  public void setSortByEffectiveTime(boolean sortByEffectiveTime) {
    this.sortByEffectiveTime = sortByEffectiveTime;
  }

  /**
   * Sets the require all files flag.
   *
   * @param requireAllFiles the require all files
   */
  public void setRequireAllFiles(boolean requireAllFiles) {
    this.requireAllFiles = requireAllFiles;
  }

  /**
   * Returns the file version.
   *
   * @return the file version
   * @throws Exception the exception
   */
  public String getFileVersion() throws Exception {

    String fileVersion = null;

    for (final String dirName : dirMap.values()) {
      final File file = new File(inputDir + dirName);
      if (file != null && file.exists()) {
        for (final String fileName : file.list()) {
          // match last _dddddd
          try {
            Matcher matcher = Pattern.compile("\\d+")
                .matcher(fileName.substring(fileName.lastIndexOf('_')));
            matcher.find();
            fileVersion = matcher.group();
          } catch (Exception e) {
            // do nothing
          }

        }
      }
    }

    if (fileVersion == null) {
      Logger.getLogger(getClass()).warn("Make sure you are pointing to a Snapshot or Delta directory - " + inputDir);
      throw new Exception(
          "Unable to determine file version from input directory " + inputDir);
    }
    return fileVersion;
  }

  /**
   * Return the extension (and namespace if present).
   *
   * @return the file extension info
   * @throws Exception the exception
   */
  public String getFileExtensionInfo() throws Exception {
    String fileExtension = null;

    for (final String dirName : dirMap.values()) {
      final File file = new File(inputDir + dirName);
      if (file != null && file.exists()) {
        for (final String fileName : file.list()) {
          // match last _dddddd
          try {

            Matcher matcher = Pattern.compile(".*_Concept_Snapshot_([^_]*)")
                .matcher(fileName);
            matcher.find();
            fileExtension = matcher.group(1);
          } catch (Exception e) {
            // do nothing
          }

        }
      }
    }

    if (fileExtension == null) {
      throw new Exception(
          "Unable to determine file version from input directory " + inputDir);
    }
    return fileExtension;
  }

  /**
   * Sort files.
   *
   * @throws Exception the exception
   */

  public void compute() throws Exception {
    Logger.getLogger(getClass()).info("Start sorting files");

    File inputDirFile = new File(inputDir);
    File outputDirFile = new File(outputDir);

    // Remove and remake output dir
    Logger.getLogger(getClass()).info("  Remove and remake output dir");
    ConfigUtility.deleteDirectory(outputDirFile);
    if (!outputDirFile.mkdirs()) {
      throw new Exception("Problem making output dir: " + outputDir);
    }

    // Check preconditions
    if (!inputDirFile.exists()) {
      throw new Exception("Input dir does not exist: " + inputDir);
    }

    Map<String, Integer> sortByMap = new HashMap<>();
    sortByMap.put("sct2_Concept_", 0);
    sortByMap.put("sct2_Relationship_", 4);
    sortByMap.put("sct2_StatedRelationship_", 4);
    sortByMap.put("merge_Relationship", 4);
    sortByMap.put("sct2_Description_", 4);
    sortByMap.put("sct2_TextDefinition_", 4);
    sortByMap.put("merge_Description", 4);
    sortByMap.put("Refset_Simple", 5);
    sortByMap.put("AttributeValue", 5);
    sortByMap.put("AssociationReference", 5);
    // sortByMap.put("ComplexMap", 5);
    sortByMap.put("ExtendedMap", 5);
    sortByMap.put("SimpleMap", 5);
    sortByMap.put("Language", 5);
    sortByMap.put("RefsetDescriptor", 4);
    sortByMap.put("ModuleDependency", 4);
    sortByMap.put("DescriptionType", 4);

    Map<String, String> fileMap = new HashMap<>();
    fileMap.put("sct2_Concept_", "conceptsByConcept.sort");
    fileMap.put("sct2_Relationship_", "relationshipsBySourceConcept.sort");
    fileMap.put("sct2_StatedRelationship_",
        "statedRelationshipsBySourceConcept.sort");
    fileMap.put("sct2_Description_", "descriptionsByConcept.sort");
    fileMap.put("sct2_TextDefinition_", "definitionsByConcept.sort");
    fileMap.put("Refset_Simple", "simpleRefsetsByConcept.sort");
    fileMap.put("AttributeValue", "attributeValueRefsetsByRefCompId.sort");
    fileMap.put("AssociationReference",
        "associationReferenceRefsetsByRefCompId.sort");
    // fileMap.put("ComplexMap", "complexMapRefsetsByConcept.sort");
    fileMap.put("ExtendedMap", "extendedMapRefsetsByConcept.sort");
    fileMap.put("SimpleMap", "simpleMapRefsetsByConcept.sort");
    fileMap.put("Language", "languageRefsetsByDescription.sort");
    fileMap.put("RefsetDescriptor", "refsetDescriptorByRefset.sort");
    fileMap.put("ModuleDependency", "moduleDependencyByRefset.sort");
    fileMap.put("DescriptionType", "descriptionTypeByRefset.sort");

    // Sort files
    int[] fields = null;
    for (final String key : dirMap.keySet()) {

      if (requestCancel) {
        throw new CancelException("Cancel requested");
      }

      Logger.getLogger(getClass()).info("  Sorting for " + key);
      final File file = findFile(new File(inputDir + dirMap.get(key)), key);

      Logger.getLogger(getClass()).info("    file = " + file);

      // Determine fields to sort by
      if (sortByEffectiveTime) {
        fields = new int[] {
            1, sortByMap.get(key)
        };
      } else {
        fields = new int[] {
            sortByMap.get(key)
        };
      }
      // Sort the file
      if (file != null) {
        sortRf2File(file, new File(outputDir + "/" + fileMap.get(key)), fields);
      } else {
        // otherwise just create an empty "sort" file
        new File(outputDir + "/" + fileMap.get(key)).createNewFile();
      }
    }

    // Merge relationship files
    Logger.getLogger(getClass()).info("  Merging relationship files...");
    File relationshipsFile =
        new File(outputDir + "/" + fileMap.get("sct2_Relationship_"));
    File statedRelationshipsFile =
        new File(outputDir + "/" + fileMap.get("sct2_StatedRelationship_"));
    // Determine fields to sort by
    if (sortByEffectiveTime) {
      fields = new int[] {
          1, sortByMap.get("merge_Relationship")
      };
    } else {
      fields = new int[] {
          sortByMap.get("merge_Relationship")
      };
    }

    File mergedRel = ConfigUtility.mergeSortedFiles(relationshipsFile,
        statedRelationshipsFile, getComparator(fields), outputDirFile, "");

    // rename the temporary file
    Files.move(mergedRel,
        new File(outputDir + "/" + "relationshipsAllBySourceConcept.sort"));

    Thread.sleep(1000);
    Logger.getLogger(getClass()).info("Done...");

  }

  /**
   * Find file.
   *
   * @param dir the dir
   * @param prefix the prefix
   * @return the file
   * @throws Exception the exception
   */
  public File findFile(File dir, String prefix) throws Exception {
    File file = null;
    // file
    for (final File f : dir.listFiles()) {
      if (f.getName().contains(prefix)) {
        if (file != null)
          throw new Exception("Multiple " + prefix + " files");
        file = f;
      }
    }
    if (file == null) {
      if (requireAllFiles) {
        throw new Exception("Missing " + prefix + " file");
      } else {
        return null;
      }
    }
    Logger.getLogger(getClass()).info(
        "      " + prefix + " = " + file.toString() + " " + file.exists());
    return file;
  }

  /**
   * Helper function for sorting an individual file with colum comparator.
   *
   * @param fileIn the input file to be sorted
   * @param fileOut the resulting sorted file
   * @param sortColumns the columns ([0, 1, ...]) to compare by
   * @throws Exception the exception
   */
  private void sortRf2File(File fileIn, File fileOut, final int[] sortColumns)
    throws Exception {
    Comparator<String> comp;
    // Comparator to split on \t and sort by sortColumn
    comp = getComparator(sortColumns);

    StringBuilder columns = new StringBuilder();
    boolean first = true;
    for (final int sortColumn : sortColumns) {
      if (!first) {
        columns.append(", ");
        first = false;
      }
      columns.append(sortColumn);
    }
    Logger.getLogger(getClass()).info("    Sorting " + fileIn.getName()
        + "  into " + fileOut.toString() + " by columns " + columns);
    FileSorter.sortFile(fileIn.toString(), fileOut.toString(), comp);

  }

  /**
   * Returns the comparator.
   *
   * @param sortColumns the sort columns
   * @return the comparator
   */
  @SuppressWarnings("static-method")
  private Comparator<String> getComparator(final int[] sortColumns) {
    return new Comparator<String>() {
      @Override
      public int compare(String s1, String s2) {
        String v1[] = s1.split("\t");
        String v2[] = s2.split("\t");
        for (final int sortColumn : sortColumns) {
          final int cmp = v1[sortColumn].compareTo(v2[sortColumn]);
          if (cmp != 0) {
            return cmp;
          }
        }
        return 0;
      }
    };
  }

}


text:
package com.proofpoint.reporting;

// Overridden method, overridden annotation from parent => B
public class TestInheritance3
    extends TestInheritanceBase
{
    public TestInheritance3()
    {
        super(B.class, B.class);
    }

    private static class A
    {
        @Reported
        protected Object getValue()
        {
            return null;
        }
    }

    private static class B
            extends A
    {
        @Override
        @Reported
        public Object getValue()
        {
            return null;
        }
    }

}


text:
module PubliSci

  class SADI_request
    def self.send_request(service, turtle)
      response = RestClient.post(service, turtle, content_type: 'text/rdf+n3', accept: 'text/rdf+n3')
      RDF::Repository.new << RDF::Turtle::Reader.new(response)
    end

    def self.fetch_async(service,turtle)
      gr = send_request(service,turtle)

      rdfs = RDF::Vocabulary.new("http://www.w3.org/2000/01/rdf-schema#")
      polls = RDF::Query.execute(gr) do
        pattern [:obj, rdfs.isDefinedBy, :def]
      end

      poll_time = {}
      polls.map(&:def).select{|res| res.to_s["?poll="]}.each{|poll_url|
        poll_time[poll_url.to_s] = Time.now
      }

      results = []
      until results.size == poll_time.keys.size
        poll_url = poll_time.sort_by{|k,v| v}.first.first
        t = Time.now

        if poll_time[poll_url] > t
          puts "no poll urls ready, sleeping #{poll_time[poll_url] - t}"
          sleep poll_time[poll_url] - t
        end

        result = poll(poll_url)
        if result.is_a? Fixnum
          puts "#{poll_url} Response not ready, waiting #{result}"
          poll_time[poll_url] = Time.now + result
        else
          results << result
        end
      end

      results
    end

    def self.poll(url)
      resp = RestClient.get(url, accept: 'text/rdf+n3'){ |response, request, result, &block|
        if [301, 302, 307].include? response.code
          wait = response.headers[:retry_after]
          if wait
            return wait.to_i
          else
            response.follow_redirection(request, result, &block)
          end
        else
          response.return!(request, result, &block)
        end
      }
      resp.body
    end

    def self.try_fetch(poll_url)
      puts "polling #{poll_url}"
      loop do
        result = poll(poll_url)
        if result.is_a? Fixnum
          return result
        else
          return RDF::Repository.new << RDF::Turtle::Reader.new(result)
        end
      end
    end
  end

  class PostProcessor

    def self.process(infile,outfile,pattern)

      tmp = Tempfile.new('annot_temp')
      open(infile).each_line{|line|
        if line[pattern]
          line.scan(pattern).each{|loc|
            line.sub!(pattern,yield(loc.first))
          }
          tmp.write(line)
        else
          tmp.write(line)
        end
      }

      FileUtils.copy(tmp.path,outfile)

      outfile
    end
  end
end


text:
using System;
using System.Collections.Generic;
using Stateflow.Fields;
using Stateflow.Workflow;
using Stateflow.Fields.DataStores;

namespace LeadSample
{
	public class Lead : IIdentifiableBy<string>
	{
		private readonly WorkflowEngine<string> _workflowEngine;

		public Lead(WorkflowDefinition<string> workflowDefinition)
		{
			_workflowEngine = new WorkflowEngine<string>(workflowDefinition, null, this);
            _workflowEngine.OnStateTransition += WorkflowEngine_OnStateTransition;
		}

		void WorkflowEngine_OnStateTransition(object sender, StateChangeEventArgs<string> e)
        {
			if (e.FromState is StartState<string>)
				Console.WriteLine ("Workflow started");

			if (e.ToState is EndState<string>)
				Console.WriteLine ("Workflow completed");

            Console.WriteLine("{0}: State changed from {1} to {2} because of trigger {3}.", DateTime.Now.ToShortTimeString(), e.FromState, e.ToState, e.TriggeredBy);
        }

		public virtual IEnumerable<Trigger<string>> PermittedTriggers
        {
            get { return _workflowEngine.PermittedTriggers; }
        }

        /// <summary>
        /// Gets or sets the state of the workflow.
        /// </summary>
        /// <value>
        /// The state of the workflow.
        /// </value>
		public virtual State<string> CurrentState {
			get { return _workflowEngine.CurrentState; }
        }

	    public virtual void ChangeState(string newState)
	    {
	        _workflowEngine.ChangeState(newState);
	    }

		public IFieldsItem<string> Fields { get; set; }

		public string Id
		{
			get;
			set;
		}
	}
}


text:
//
//  MinorMonsterRoom.h
//  SurvivalDungeon
//
//  Created by Marlon Andrade on 24/02/2015.
//
//

#ifndef __SurvivalDungeon__MinorMonsterRoom__
#define __SurvivalDungeon__MinorMonsterRoom__

#include "DungeonRoom.h"

class MinorMonsterRoom : public DungeonRoom {
  CC_SYNTHESIZE_RETAIN(cocos2d::EventListenerCustom*,
                       _roomHasBeenPlacedListener,
                       RoomHasBeenPlacedListener);

public:
  CREATE_FUNC(MinorMonsterRoom);

  virtual std::string getImagePath();

  virtual void riseMonster();
  virtual void hasBeenPlaced(RoomPlacementData* placement);
};

#endif /* defined(__SurvivalDungeon__MinorMonsterRoom__) */


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="org.motechproject.sms.smpp"/>
    <context:annotation-config/>

    <bean id="smsApiSettings" class="org.motechproject.server.config.SettingsFacade" autowire="byType">
        <property name="configFiles">
            <list>
                <value>classpath:sms.properties</value>
            </list>
        </property>
        <property name="moduleName" value="sms-smpp"/>
    </bean>

    <bean id="smsSmppSettings" class="org.motechproject.server.config.SettingsFacade" autowire="byType">
        <property name="configFiles">
            <list>
                <value>classpath:smpp.properties</value>
            </list>
        </property>
        <property name="moduleName" value="sms-smpp"/>
    </bean>

    <bean id="smslibService" class="org.smslib.Service" factory-method="getInstance"/>

    <bean id="smppDBConnector" factory-bean="couchDbManager" factory-method="getConnector">
        <constructor-arg value="motech-sms-audit"/>
    </bean>

</beans>


text:
#include <iostream>

#include <GL/glew.h>

#include <pangolin/pangolin.h>
#include <pangolin/gl/glcuda.h>
#include <pangolin/gl/glvbo.h>

#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
#include <vector_types.h>

using namespace pangolin;
using namespace std;

// Mesh size
const int mesh_width=256;
const int mesh_height=256;

extern "C" void launch_kernel(float4* dVertexArray, uchar4* dColourArray, unsigned int width, unsigned int height, float time);

int main( int /*argc*/, char* argv[] )
{
//  cudaGLSetGLDevice(0);

  pangolin::CreateWindowAndBind("Main",640,480);
  glewInit();

  // 3D Mouse handler requires depth testing to be enabled
  glEnable(GL_DEPTH_TEST);

  // Create vertex and colour buffer objects and register them with CUDA
  GlBufferCudaPtr vertex_array(
      GlArrayBuffer, mesh_width*mesh_height, GL_FLOAT, 4,
      cudaGraphicsMapFlagsWriteDiscard, GL_STREAM_DRAW
  );
  GlBufferCudaPtr colour_array(
      GlArrayBuffer, mesh_width*mesh_height, GL_UNSIGNED_BYTE, 4,
      cudaGraphicsMapFlagsWriteDiscard, GL_STREAM_DRAW
  );

  // Define Camera Render Object (for view / scene browsing)
  pangolin::OpenGlRenderState s_cam(
    ProjectionMatrix(640,480,420,420,320,240,0.1,1000),
    ModelViewLookAt(-0,2,-2, 0,0,0, AxisY)
  );
  const int UI_WIDTH = 180;

  // Add named OpenGL viewport to window and provide 3D Handler
  View& d_cam = pangolin::Display("cam")
    .SetBounds(0.0, 1.0, Attach::Pix(UI_WIDTH), 1.0, -640.0f/480.0f)
    .SetHandler(new Handler3D(s_cam));

  // Add named Panel and bind to variables beginning 'ui'
  // A Panel is just a View with a default layout and input handling
  View& d_panel = pangolin::CreatePanel("ui")
      .SetBounds(0.0, 1.0, 0.0, Attach::Pix(UI_WIDTH));

  // Default hooks for exiting (Esc) and fullscreen (tab).
  for(int frame=0; !pangolin::ShouldQuit(); ++frame)
  {
    static double time = 0;
    static Var<double> delta("ui.time delta", 0.001, 0, 0.005);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    d_cam.Activate(s_cam);
    glColor3f(1.0,1.0,1.0);

    {
      CudaScopedMappedPtr var(vertex_array);
      CudaScopedMappedPtr car(colour_array);
      launch_kernel((float4*)*var,(uchar4*)*car,mesh_width,mesh_height,time);
      time += delta;
    }

    pangolin::RenderVboCbo(vertex_array, colour_array);

    // Swap frames and Process Events
    pangolin::FinishFrame();
  }

  return 0;
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0012_remove_appuser_name'),
    ]

    operations = [
        migrations.AddField(
            model_name='appuser',
            name='name',
            field=models.CharField(default='user', max_length=128),
        ),
    ]


text:
   <title>CaptureIEFromCurrentPos</title>
   <meta name="generator"  content="HelpMaker" >
   <meta name="keywords"  content="System Requirements," >

      <title></title>
CaptureIEFromCurrentPos

        Previous Top Next

<title></title>
True/False. If set to False then the web page being captured will be
scrolled to top before starting the capture.

Example

Capturing IE web page with scrolling


text:
Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values.

Observables are declarative—that is, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

An observable can deliver multiple values of any type—literals, messages, or events, depending on the context. The API for receiving values is the same whether the values are delivered synchronously or asynchronously. Because setup and teardown logic are both handled by the observable, your application code only needs to worry about subscribing to consume values, and when done, unsubscribing. Whether the stream was keystrokes, an HTTP response, or an interval timer, the interface for listening to values and stopping listening is the same.

Because of these advantages, observables are used extensively within Angular, and are recommended for app development as well.

## Basic usage and terms

As a publisher, you create an `Observable` instance that defines a *subscriber* function. This is the function that is executed when a consumer calls the `subscribe()` method. The subscriber function defines how to obtain or generate values or messages to be published.

To execute the observable you have created and begin receiving notifications, you call its `subscribe()` method, passing an *observer*. This is a JavaScript object that defines the handlers for the notifications you receive. The `subscribe()` call returns a `Subscription` object that has an `unsubscribe()` method, which you call to stop receiving notifications.

Here's an example that demonstrates the basic usage model by showing how an observable could be used to provide geolocation updates.

## Defining observers

A handler for receiving observable notifications implements the `Observer` interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send:

| Notification type | Description |
|:---------|:-------------------------------------------|
| `next`  | Required. A handler for each delivered value. Called zero or more times after execution starts.|
| `error` | Optional. A handler for an error notification. An error halts execution of the observable instance.|
| `complete` | Optional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.|

An observer object can define any combination of these handlers. If you don't supply a handler for a notification type, the observer ignores notifications of that type.

## Subscribing

An `Observable` instance begins publishing values only when someone subscribes to it. You subscribe by calling the `subscribe()` method of the instance, passing an observer object to receive the notifications.

In order to show how subscribing works, we need to create a new observable. There is a constructor that you use to create new instances, but for illustration, we can use some methods from the RxJS library that create simple observables of frequently used types:

  * `of(...items)`—Returns an `Observable` instance that synchronously delivers the values provided as arguments.
  * `from(iterable)`—Converts its argument to an `Observable` instance. This method is commonly used to convert an array to an observable.

Here's an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console:

Alternatively, the `subscribe()` method can accept callback function definitions in line, for `next`, `error`, and `complete` handlers. For example, the following `subscribe()` call is the same as the one that specifies the predefined observer:

In either case, a `next` handler is required. The `error` and `complete` handlers are optional.

Note that a `next()` function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a *stream*. Any type of value can be represented with an observable, and the values are published as a stream.

## Creating observables

Use the `Observable` constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable's `subscribe()` method executes. A subscriber function receives an `Observer` object, and can publish values to the observer's `next()` method.

For example, to create an observable equivalent to the `of(1, 2, 3)` above, you could do something like this:

To take this example a little further, we can create an observable that publishes events. In this example, the subscriber function is defined inline.

Now you can use this function to create an observable that publishes keydown events:

## Multicasting

A typical observable creates a new, independent execution for each subscribed observer. When an observer subscribes, the observable wires up an event handler and delivers values to that observer. When a second observer subscribes, the observable then wires up a new event handler and delivers values to that second observer in a separate execution.

Sometimes, instead of starting an independent execution for each subscriber, you want each subscription to get the same values—even if values have already started emitting. This might be the case with something like an observable of clicks on the document object.

*Multicasting* is the practice of broadcasting to a list of multiple subscribers in a single execution. With a multicasting observable, you don't register multiple listeners on the document, but instead re-use the first listener and send values out to each subscriber.

When creating an observable you should determine how you want that observable to be used and whether or not you want to multicast its values.

Let's look at an example that counts from 1 to 3, with a one-second delay after each number emitted.

Notice that if you subscribe twice, there will be two separate streams, each emitting values every second. It looks something like this:

 Changing the observable to be multicasting could look something like this:

   Multicasting observables take a bit more setup, but they can be useful for certain applications. Later we will look at tools that simplify the process of multicasting, allowing you to take any observable and make it multicasting.

## Error handling

Because observables produce values asynchronously, try/catch will not effectively catch errors. Instead, you handle errors by specifying an `error` callback on the observer. Producing an error also causes the observable to clean up subscriptions and stop producing values. An observable can either produce values (calling the `next` callback), or it can complete, calling either the `complete` or `error` callback.

myObservable.subscribe({
  next(num) { console.log('Next num: ' + num)},
  error(err) { console.log('Received an errror: ' + err)}
});

Error handling (and specifically recovering from an error) is covered in more detail in a later section.


text:
namespace Sample.Images.Worker;

using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SlimMessageBus;

public class Program
{
    public static void Main()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        var loggerFactory = LoggerFactory.Create(cfg => cfg.AddConfiguration(configuration.GetSection("Logging")).AddConsole());
        var logger = loggerFactory.CreateLogger<Program>();

        logger.LogInformation("Starting worker...");
        using (var container = ContainerSetup.Create(configuration, loggerFactory))
        {
            // eager load the singleton, so that is starts consuming messages
            var messageBus = container.Resolve<IMessageBus>();
            logger.LogInformation("Worker ready");

            Console.WriteLine("Press enter to stop the application...");
            Console.ReadLine();

            logger.LogInformation("Stopping worker...");
        }
        logger.LogInformation("Worker stopped");
    }
}


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">

	<modelVersion>4.0.0</modelVersion>

	<!-- 父级模块 -->
	<parent>
		<groupId>org.xs.dntown</groupId>
		<artifactId>dntown-wx</artifactId>
		<version>1.0</version>
	</parent>

	<artifactId>dntown-wx-front</artifactId>
	<packaging>war</packaging>

	<!-- 依赖项定义 -->
	<dependencies>

		<!-- dntown-wx-core -->
		<dependency>
			<groupId>org.xs.dntown</groupId>
		    <artifactId>dntown-wx-core</artifactId>
		    <version>1.0</version>
		</dependency>

		<!-- dntown-wx-game24 -->
		<dependency>
			<groupId>org.xs.dntown</groupId>
		    <artifactId>dntown-wx-game24</artifactId>
		    <version>1.0</version>
		</dependency>

		<!-- dntown-wx-idiom -->
		<dependency>
			<groupId>org.xs.dntown</groupId>
		    <artifactId>dntown-wx-idiom</artifactId>
		    <version>1.0</version>
		</dependency>
	</dependencies>
</project>


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

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

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

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

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

Pathfinder
    v3.0

The definitive Hacknet programmable modding system

Pathfinder.Mission.GoalInstance Member List

This is the complete list of members for Pathfinder.Mission.GoalInstance, including all inherited members.

CreateInstance(string id)	Pathfinder.Mission.GoalInstance	static

GetInstanceData(string key)	Pathfinder.Mission.GoalInstance

GetInstanceData< T >(string key)	Pathfinder.Mission.GoalInstance

Interface	Pathfinder.Mission.GoalInstance

InterfaceId	Pathfinder.Mission.GoalInstance

isComplete(List< string > additionalDetails=null)	Pathfinder.Mission.GoalInstance

IsInstanceSaveable(string key)	Pathfinder.Mission.GoalInstance

Mission	Pathfinder.Mission.GoalInstance

OnAdd(Hacknet.ActiveMission mission)	Pathfinder.Mission.GoalInstance

reset()	Pathfinder.Mission.GoalInstance

SaveString	Pathfinder.Mission.GoalInstance

SetInstanceData(string key, object val, bool shouldSave=false)	Pathfinder.Mission.GoalInstance

SetInstanceDataSaveable(string key, bool shouldSave)	Pathfinder.Mission.GoalInstance

TestCompletable()	Pathfinder.Mission.GoalInstance

this[string key]	Pathfinder.Mission.GoalInstance

Generated by
    doxygen 1.8.13


text:
{% extends "base.html" %}

{% block title %}Login{% endblock %}

{% block content %}

            Login

        {% if form.errors %}

                Your username and password didn't match.

        {% endif %}

        <form action="." method="post" class="ac-form">
            {% for field in form %}

                    {{ field.label_tag }} {{ field }}

                    {% if field.help_text %}

                        {{ field.help_text|safe }}

                    {% endif %}

            {% endfor %}

            <input type="submit" class="btn btn-primary ac-submit" value="Login" />
            New User?
            <input type="hidden" name="next" value="{{ next }}" />

                Forgotten your password?

            {% csrf_token %}
        </form>

                 Login in with twitter

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite">

    <mx.citydevs.hackcdmx.views.CustomTextView
        android:id="@+id/item_infractions_nombre"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        android:gravity="left"
        android:textSize="@dimen/abc_text_size_small_material"
        android:text=""
        android:textColor="@color/colorBlack"
        app:typeface="Tw_Cen_MT_Bold"/>

    <mx.citydevs.hackcdmx.views.CustomTextView
        android:id="@+id/item_infractions_ley"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="5dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorAppGrey"
        app:typeface="Tw_Cen_MT"/>

    <mx.citydevs.hackcdmx.views.CustomTextView
        android:id="@+id/item_infractions_monto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="5dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorAppGrey"
        app:typeface="Tw_Cen_MT"/>

    <mx.citydevs.hackcdmx.views.CustomTextView
        android:id="@+id/item_infractions_puntos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="5dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorAppGrey"
        app:typeface="Tw_Cen_MT"/>

    <mx.citydevs.hackcdmx.views.CustomTextView
        android:id="@+id/item_infractions_corralon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorAppGrey"
        app:typeface="Tw_Cen_MT"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorAppGrey"/>
</LinearLayout>


text:
package loci.common.utests;

import static org.testng.AssertJUnit.assertEquals;

import java.io.IOException;

import loci.common.IRandomAccess;
import loci.common.utests.providers.IRandomAccessProvider;
import loci.common.utests.providers.IRandomAccessProviderFactory;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

/**
 * Tests for reading longs from a loci.common.IRandomAccess.
 *
 * @see loci.common.IRandomAccess
 */
@Test(groups="readTests")
public class ReadLongTest {

  private static final byte[] PAGE = new byte[] {
    // 64-bit long
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
    // 64-bit long
    (byte) 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x02,
    // 64-bit long
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03,
    // 64-bit long
    (byte) 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x04,
    // 64-bit long
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05,
    // 64-bit long (-1)
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
    // 64-bit long
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x07,
    // 64-bit long (-2)
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
    (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFE
  };

  private static final String MODE = "r";

  private static final int BUFFER_SIZE = 1024;

  private IRandomAccess fileHandle;

  @Parameters({"provider"})
  @BeforeMethod
  public void setUp(String provider) throws IOException {
    IRandomAccessProviderFactory factory = new IRandomAccessProviderFactory();
    IRandomAccessProvider instance = factory.getInstance(provider);
    fileHandle = instance.createMock(PAGE, MODE, BUFFER_SIZE);
  }

  @Test
  public void testLength() throws IOException {
    assertEquals(64, fileHandle.length());
  }

  @Test
  public void testSequentialReadLong() throws IOException {
    assertEquals(1, fileHandle.readLong());
    assertEquals(1152921504606846722L, fileHandle.readLong());
    assertEquals(3, fileHandle.readLong());
    assertEquals(1152921504606846724L, fileHandle.readLong());
    assertEquals(5, fileHandle.readLong());
    assertEquals(-1L, fileHandle.readLong());
    assertEquals(7, fileHandle.readLong());
    assertEquals(-2L, fileHandle.readLong());
  }

  @Test
  public void testSeekForwardReadLong() throws IOException {
    fileHandle.seek(8);
    assertEquals(1152921504606846722L, fileHandle.readLong());
    assertEquals(3, fileHandle.readLong());
  }

  @Test
  public void testResetReadLong() throws IOException {
    assertEquals(1, fileHandle.readLong());
    assertEquals(1152921504606846722L, fileHandle.readLong());
    fileHandle.seek(0);
    assertEquals(1, fileHandle.readLong());
    assertEquals(1152921504606846722L, fileHandle.readLong());
  }

  @Test
  public void testSeekBackReadLong() throws IOException {
    fileHandle.seek(16);
    fileHandle.seek(8);
    assertEquals(1152921504606846722L, fileHandle.readLong());
    assertEquals(3, fileHandle.readLong());
  }

  @Test
  public void testRandomAccessReadLong() throws IOException {
    testSeekForwardReadLong();
    testSeekBackReadLong();
    // The test relies on a "new" file or reset file pointer
    fileHandle.seek(0);
    testResetReadLong();
  }

}


text:
package org.springframework.http;

import java.time.Duration;
import java.util.Optional;

import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

/**
 * An {@code HttpCookie} sub-class with the additional attributes allowed in
 * the "Set-Cookie" response header. To build an instance use the {@link #from}
 * static method.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 * @see RFC 6265
 */
public final class ResponseCookie extends HttpCookie {

	private final Duration maxAge;

	private final Optional<String> domain;

	private final Optional<String> path;

	private final boolean secure;

	private final boolean httpOnly;

	/**
	 * Private constructor. See {@link #from(String, String)}.
	 */
	private ResponseCookie(String name, String value, Duration maxAge, String domain,
			String path, boolean secure, boolean httpOnly) {

		super(name, value);
		Assert.notNull(maxAge);
		this.maxAge = maxAge;
		this.domain = Optional.ofNullable(domain);
		this.path = Optional.ofNullable(path);
		this.secure = secure;
		this.httpOnly = httpOnly;
	}

	/**
	 * Return the cookie "Max-Age" attribute in seconds.
	 *
	 *
A positive value indicates when the cookie expires relative to the
	 * current time. A value of 0 means the cookie should expire immediately.
	 * A negative value means no "Max-Age" attribute in which case the cookie
	 * is removed when the browser is closed.
	 */
	public Duration getMaxAge() {
		return this.maxAge;
	}

	/**
	 * Return the cookie "Domain" attribute.
	 */
	public Optional<String> getDomain() {
		return this.domain;
	}

	/**
	 * Return the cookie "Path" attribute.
	 */
	public Optional<String> getPath() {
		return this.path;
	}

	/**
	 * Return {@code true} if the cookie has the "Secure" attribute.
	 */
	public boolean isSecure() {
		return this.secure;
	}

	/**
	 * Return {@code true} if the cookie has the "HttpOnly" attribute.
	 * @see http://www.owasp.org/index.php/HTTPOnly
	 */
	public boolean isHttpOnly() {
		return this.httpOnly;
	}

	@Override
	public int hashCode() {
		int result = super.hashCode();
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.domain);
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.path);
		return result;
	}

	@Override
	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof ResponseCookie)) {
			return false;
		}
		ResponseCookie otherCookie = (ResponseCookie) other;
		return (getName().equalsIgnoreCase(otherCookie.getName()) &&
				ObjectUtils.nullSafeEquals(this.path, otherCookie.getPath()) &&
				ObjectUtils.nullSafeEquals(this.domain, otherCookie.getDomain()));
	}

	/**
	 * Factory method to obtain a builder for a server-defined cookie that starts
	 * with a name-value pair and may also include attributes.
	 * @param name the cookie name
	 * @param value the cookie value
	 * @return the created cookie instance
	 */
	public static ResponseCookieBuilder from(final String name, final String value) {

		return new ResponseCookieBuilder() {

			private Duration maxAge = Duration.ofSeconds(-1);

			private String domain;

			private String path;

			private boolean secure;

			private boolean httpOnly;

			@Override
			public ResponseCookieBuilder maxAge(Duration maxAge) {
				this.maxAge = maxAge;
				return this;
			}

			@Override
			public ResponseCookieBuilder maxAge(long maxAgeSeconds) {
				this.maxAge = maxAgeSeconds >= 0 ? Duration.ofSeconds(maxAgeSeconds) : Duration.ofSeconds(-1);
				return this;
			}

			@Override
			public ResponseCookieBuilder domain(String domain) {
				this.domain = domain;
				return this;
			}

			@Override
			public ResponseCookieBuilder path(String path) {
				this.path = path;
				return this;
			}

			@Override
			public ResponseCookieBuilder secure(boolean secure) {
				this.secure = secure;
				return this;
			}

			@Override
			public ResponseCookieBuilder httpOnly(boolean httpOnly) {
				this.httpOnly = httpOnly;
				return this;
			}

			@Override
			public ResponseCookie build() {
				return new ResponseCookie(name, value, this.maxAge, this.domain, this.path,
						this.secure, this.httpOnly);
			}
		};
	}

	/**
	 * A builder for a server-defined HttpCookie with attributes.
	 */
	public interface ResponseCookieBuilder {

		/**
		 * Set the cookie "Max-Age" attribute.
		 *
		 *
A positive value indicates when the cookie should expire relative
		 * to the current time. A value of 0 means the cookie should expire
		 * immediately. A negative value results in no "Max-Age" attribute in
		 * which case the cookie is removed when the browser is closed.
		 */
		ResponseCookieBuilder maxAge(Duration maxAge);

		/**
		 * Set the cookie "Max-Age" attribute in seconds.
		 */
		ResponseCookieBuilder maxAge(long maxAgeSeconds);

		/**
		 * Set the cookie "Path" attribute.
		 */
		ResponseCookieBuilder path(String path);

		/**
		 * Set the cookie "Domain" attribute.
		 */
		ResponseCookieBuilder domain(String domain);

		/**
		 * Add the "Secure" attribute to the cookie.
		 */
		ResponseCookieBuilder secure(boolean secure);

		/**
		 * Add the "HttpOnly" attribute to the cookie.
		 * @see http://www.owasp.org/index.php/HTTPOnly
		 */
		ResponseCookieBuilder httpOnly(boolean httpOnly);

		/**
		 * Create the HttpCookie.
		 */
		ResponseCookie build();
	}

}


text:
SCRIPT=$(readlink -f "$0")
CWD=$(dirname "$SCRIPT")

# make dir that is used in sphinx config
mkdir -p sphinx
sed -i s\~SPHINX_BASE_DIR~$PWD/sphinx~g $CWD/../sphinx/sphinx.conf

# Setup source database
mysql -D yiitest -u travis < $CWD/../sphinx/source.sql

# setup test Sphinx indexes:
indexer --config $CWD/../sphinx/sphinx.conf --all

# run searchd:
searchd --config $CWD/../sphinx/sphinx.conf


text:
namespace InterpreterPattern
{
    public interface IExpression
    {
        int Operate();
    }
}


text: Currently going through "Crafting Rails 4 Applications" by José Valim.