text:
using System;
using System.Linq;
using Moq;
using Nimator.Settings;
using NUnit.Framework;

namespace Nimator.Notifiers.Opsgenie
{
    [TestFixture]
    public class OpsGenieAlertConverterTests
    {
        private OpsGenieSettings settings;
        private OpsGenieAlertConverter sut;

        [SetUp]
        public void Setup()
        {
            settings = new OpsGenieSettings
            {
                Threshold = NotificationLevel.Error,
                HeartbeatName = "dummy-heartbeat",
                TeamName = "dummy-team",
                ApiKey = "dummy-api-key",
            };

            sut = new OpsGenieAlertConverter(settings);
        }

        [TestCase(null)]
        [TestCase("")]
        [TestCase("    ")]
        public void Constructor_WhenSettingsTeamNameInvalid_ThrowsException(string input)
        {
            settings.TeamName = input;

            var exception = Assert.Throws<ArgumentException>(() => new OpsGenieAlertConverter(settings));

            Assert.That(exception.ParamName, Is.EqualTo("TeamName"));
        }

        [Test]
        public void Convert_WhenResultIsNull_ThrowsException()
        {
            var exception = Assert.Throws<ArgumentNullException>(() => sut.Convert(null));

            Assert.That(exception.ParamName, Is.EqualTo("result"));
        }

        [TestCase(null, "Unknown message")]
        [TestCase("", "Unknown message")]
        [TestCase("some message", "some message")]
        public void Convert_WhenMessageIsFilled_ReturnsExpectedMessage(string input, string expected)
        {
            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.Message).Returns(input);

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Message, Is.EqualTo(expected));
        }

        [Test]
        public void Convert_WhenMessageIsTooLarge_ReturnsTruncatedMessage()
        {
            string input =
                "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
            string expected = input.Substring(0, 130);

            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.Message).Returns(input);

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Message, Is.EqualTo(expected));
        }

        [Test]
        public void Convert_WhenCalled_ReturnsExpectedAlias()
        {
            var resultMock = new Mock<INimatorResult>();

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Alias, Is.EqualTo("nimator-failure"));
        }

        [TestCase(null, null)]
        [TestCase("", "")]
        [TestCase("some message", "some message")]
        public void Convert_WhenRenderPlainTextIsFilled_ReturnsExpectedMessage(string input, string expected)
        {
            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.RenderPlainText(settings.Threshold)).Returns(input);

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Description, Is.EqualTo(expected));
        }

        [Test]
        public void Convert_WhenRenderPlainTextIsTooLarge_ReturnsTruncatedMessage()
        {
            string input = GenerateRandomString(15010);
            string expected = input.Substring(0, 15000);

            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.RenderPlainText(settings.Threshold)).Returns(input);

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Description, Is.EqualTo(expected));
        }

        [Test]
        public void Convert_WhenTeamNameIsSet_ReturnsExpectedResponders()
        {
            settings.TeamName = "Some team name";

            var resultMock = new Mock<INimatorResult>();
            var result = sut.Convert(resultMock.Object);

            var responder = result.Responders.Single();

            Assert.That(responder.Name, Is.EqualTo(settings.TeamName));
            Assert.That(responder.Type, Is.EqualTo(OpsGenieResponderType.Team));
        }

        [Test]
        public void Convert_WhenFirstFailedLayerName_ReturnsExpectedTags()
        {
            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.GetFirstFailedLayerName()).Returns("Some layer");

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Tags.Length, Is.EqualTo(2));
            Assert.That(result.Tags[0], Is.EqualTo("Nimator"));
            Assert.That(result.Tags[1], Is.EqualTo("Some layer"));
        }

        [Test]
        public void Convert_WhenFirstFailedLayerNameIsTooLong_ReturnsExpectedTags()
        {
            string input = GenerateRandomString(55);
            string expected = input.Substring(0, 50);

            var resultMock = new Mock<INimatorResult>();
            resultMock.Setup(r => r.GetFirstFailedLayerName()).Returns(input);

            var result = sut.Convert(resultMock.Object);

            Assert.That(result.Tags[1], Is.EqualTo(expected));
        }

        private static Random randomGenerator = new Random();
        internal static string GenerateRandomString(int stringLength)
        {
            const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@$?_-";
            char[] chars = new char[stringLength];

            for (int i = 0; i < stringLength; i++)
            {
                chars[i] = allowedChars[randomGenerator.Next(0, allowedChars.Length)];
            }

            return new string(chars);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var update = require('./_update')
var reconcile = require('../strategy/reconcile')

avalon.directive('html', {
    parse: function (copy, src, binding) {
        if (!src.isVoidTag) {
            //将渲染函数的某一部分存起来,渲在c方法中转换为函数
            copy[binding.name] = avalon.parseExpr(binding)
            copy.vmodel = '__vmodel__'
            copy.local = '__local__'
        } else {
            copy.children = '[]'
        }
    },
    diff: function (copy, src, name) {
        var copyValue = copy[name] + ''

        if (!src.dynamic['ms-html'] || !src.render || copyValue !== src[name]) {
            src[name] = copyValue

            var oldTree = avalon.speedUp(avalon.lexer(copyValue))

            var render = avalon.render(oldTree, copy.local)
            src.render = render

            var newTree = render(copy.vmodel, copy.local)

            src.children = copy.children = newTree
            update(src, this.update)
        } else if (src.render) {
            var newTree = src.render(copy.vmodel, copy.local)
            copy.children = newTree
        }
    },
    update: function (dom, vdom, parent) {
        vdom.dynamic['ms-html'] = 1
        avalon.clearHTML(dom)
        dom.appendChild(avalon.domize(vdom.children))
    }
})


text:
=begin
##########################################################################
#
#  INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL
#  __________________
#
#  (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE
#  All Rights Reserved.
#  Product / Project: Flint IT Automation Platform
#  NOTICE:  All information contained herein is, and remains
#  the property of INFIVERVE TECHNOLOGIES PTE LIMITED.
#  The intellectual and technical concepts contained
#  herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED.
#  Dissemination of this information or any form of reproduction of this material
#  is strictly forbidden unless prior written permission is obtained
#  from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE.
=end

# begin
@log.trace("Started executing 'serviceNow:incident:priority.rb' flintbit...")
begin
    # Flintbit Input Parameters
    @connector_name = @input.get('connector_name')                 # Name of the ServiceNow Connector
    if @connector_name.nil?
       @connector_name = 'servicenow'
    end
    @action = 'update-record'
    @tableName = 'incident'
    @sysid  = @input.get('sys-id')
    @sysparm_display_value = @input.get('sysparm_display_value')
    data = {}
    data["impact"]=@input.get('impact')
    data["urgency"]=@input.get('urgency')

    @log.info("Flintbit input parameters are, connector name :: #{@connector_name} |action :: #{@action}| tableName :: #{@tableName} | sysid :: #{@sysid} |
state :: #{data}")

          response = @call.connector(@connector_name)
                          .set('action', @action)
                          .set('table-name', @tableName)
                          .set('data', data)
                          .set('sys-id', @sysid)
                          .set('sysparm_display_value', @sysparm_display_value)
                          .sync

    # ServiceNow Connector Response Meta Parameters
    response_exitcode = response.exitcode           # Exit status code
    response_message = response.message             # Execution status message

    # ServiceNow Connector Response Parameters
  response_body = response.get('body')# Response body

    if response_exitcode == 0
        result = @util.json(response_body)
        @log.info("Success in executing serviceNow Connector, where exitcode :: #{response_exitcode} | message :: #{response_message}")
        @log.info("#{result}")
        @output.setraw('result', response_body)
        @log.trace("Finished executing 'serviceNow' flintbit with success...")
    else
        @log.error("Failure in executing serviceNow Connector where, exitcode :: #{response_exitcode} | message :: #{response_message}")
        @output.set('error', response_message)
        @log.trace("Finished executing 'serviceNow' flintbit with error...")
    end
rescue Exception => e
    @log.error(e.message)
    @output.set('exit-code', 1).set('message', e.message)
end
@log.trace("Finished executing 'serviceNow:incident:priority.rb' flintbit...")
# end


text:
require 'net/http'
require_relative '../internal_error_from_exception_response'

#
# Response checked for socket error
#
class SocketErrorResponse
  def initialize(tries)
    @tries = tries
  end

  def check(response)
    response.receive
  rescue SocketError => e
    retry unless (@tries -= 1).zero?
    InternalErrorFromExceptionResponse.new(e).receive
  end
end


text:
import convertHrtime from "convert-hrtime"

export function calcElapsedTime(startTime: [number, number]): string {
  const elapsed = process.hrtime(startTime)

  return convertHrtime(elapsed)[`seconds`].toFixed(3)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2015 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!--
    A NestedScrollView behaves like a ScrollView, but it can be placed into
    other nested scrolling containers or have other nested scrolling containers
    placed into it.
-->
<android.support.v4.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearance"
            android:text="@string/nested_scroll_long_text" />
        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:padding="16dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearance"
                android:text="@string/nested_scroll_long_text" />
        </android.support.v4.widget.NestedScrollView>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearance"
            android:text="@string/nested_scroll_long_text" />
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>


text:
5.times { Thing.create }

5.times { Item.create }


text: Examples showcasing MasterLeague.net API


text:
'use strict';
// Message model
// Stores recieved messages
var mongoose = require('mongoose');

var MessageSchema = new mongoose.Schema({
	from: String,
	body: String,
	response: String,
	timestamp: {
		type: Date,
		default: Date.now
	}
});

// export
module.exports = mongoose.model('Message', MessageSchema);


text:
  Varouville est
       un village
       géographiquement positionné dans le département de Manche en Basse-Normandie. Elle comptait 296 habitants en 2008.

À proximité de Varouville sont positionnées géographiquement les villes de
Néville-sur-Mer située à 2 km, 175 habitants,
Tocqueville à 2 km, 273 habitants,
Cosqueville à 3 km, 560 habitants,
Clitourps à 1 km, 179 habitants,
Saint-Pierre-Église à 2 km, 1 785 habitants,
Gouberville à 3 km, 130 habitants,
 entre autres. De plus, Varouville est située à seulement 18 km de Cherbourg-Octeville.

Si vous pensez emmenager à Varouville, vous pourrez aisément trouver une maison à acheter.

Le nombre de logements, à Varouville, était réparti en 2011 en zero appartements et 123 maisons soit
 un marché plutôt équilibré.


text:
package org.dashbuilder.displayer.client.resources.i18n;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.ConstantsWithLookup;

public interface DisplayerSettingsEditorConstants extends ConstantsWithLookup {

    public static final DisplayerSettingsEditorConstants INSTANCE = GWT.create( DisplayerSettingsEditorConstants.class );

    // Position enum literals

    String POSITION_BOTTOM();

    String POSITION_TOP();

    String POSITION_LEFT();

    String POSITION_RIGHT();

    String POSITION_IN();

    // Common settings editor literals

    String settingsEditor_caption();

    String settingsJsonSource_caption();

    String common_showTitle();

    String common_title();

    String common_title_placeholder();

    String common_renderer();

    String common_columns();

    String common_columns_placeholder();

    String chart_width();

    String chart_height();

    String chart_topMargin();

    String chart_bottomMargin();

    String chart_leftMargin();

    String chart_rightMargin();

    String chart_legendShow();

    String chart_legendPosition();

    String chart_3d();

    String table_pageSize();

    String table_width();

    String table_sortEnabled();

    String table_sortColumn();

    String table_sortColumn_placeholder();

    String table_sortOrder();

    String table_ascSortOrder();

    String table_descSortOrder();

    String xaxis_showLabels();

    String xaxis_angle();

    String xaxis_title();

    String xaxis_title_placeholder();

    String yaxis_showLabels();

    String yaxis_angle();

    String yaxis_title();

    String yaxis_title_placeholder();

    String meter_start();

    String meter_warning();

    String meter_critical();

    String meter_end();

    String barchart_orientation();

    String barchart_horizontal();

    String barchart_vertical();

    String filter_enabled();

    String filter_self();

    String filter_listening();

    String filter_notifications();
}


text:
package io.digdag.core.schedule;

import java.time.Instant;
import java.util.List;
import com.google.common.base.Optional;
import io.digdag.spi.ScheduleTime;
import io.digdag.core.repository.ResourceConflictException;
import io.digdag.core.repository.ResourceNotFoundException;

public interface ScheduleStoreManager
{
    ScheduleStore getScheduleStore(int siteId);

    interface ScheduleAction
    {
        void schedule(ScheduleControlStore store, StoredSchedule schedule);
    }

    void lockReadySchedules(Instant currentTime, ScheduleAction func);

    interface ScheduleLockAction <T>
    {
        T call(ScheduleControlStore store, StoredSchedule storedSched)
            throws ResourceNotFoundException, ResourceConflictException;
    }

    <T> T lockScheduleById(long schedId, ScheduleLockAction<T> func)
        throws ResourceNotFoundException, ResourceConflictException;
}


text:
require_relative 'support/int_helper'
include SetupHelper

RSpec.describe Pakyow::Presenter::Presenter do
  include ReqResHelpers

  before do
    Pakyow::Config.presenter.view_doc_class = Pakyow::Presenter::StringDoc
    @store = :test
    Pakyow::App.stage(:test)
    @presenter = Pakyow.app.presenter
    @path = '/'
    @presenter.prepare_with_context(Pakyow::AppContext.new(mock_request(@path)))
  end

  after do
    teardown
  end

  context 'test view' do
    before do
      reset_index_contents
    end

    it 'is built for request' do
      expect(@presenter.view).to be_a Pakyow::Presenter::ViewComposer
      expect(@presenter.view.composed).to be_a Pakyow::Presenter::View

      page = @presenter.store.page(@path)
      template = @presenter.store.template(@path)
      view = @presenter.store.view(@path)

      expect(view).to eq @presenter.view.composed
      expect(page).to eq @presenter.composer.page
      expect(template).to eq @presenter.composer.template
    end

    it 'returns content' do
      view = @presenter.store.view(@path)
      expect(view.to_html).to eq @presenter.content
    end

    it 'is rebuilt when path is set' do
      original_view = @presenter.view
      expect(original_view).to eq @presenter.view

      @presenter.path = 'multi'
      expect(original_view).to_not eq @presenter.view
      expect(Pakyow::Presenter::ViewComposer).to eq @presenter.view.class
    end

    it 'is cached' do
      file = File.join(VIEW_PATH, 'index.html')
      new_content = 'reloaded'
      original_content = File.open(file, 'r').read
      File.open(file, 'w') { |f| f.write(new_content) }
      composed = str_to_doc(@presenter.view.composed.to_html).css('body').text.strip

      expect(original_content.strip).to eq composed
    end

    it 'is reloaded' do
      file = File.join(VIEW_PATH, 'index.html')
      new_content = 'reloaded'
      File.open(file, 'w') { |f| f.write(new_content) }
      @presenter.load
      setup
      composed = str_to_doc(@presenter.view.composed.to_html).css('body').first.text.strip

      expect(new_content).to eq composed
    end

    it 'is set from view composer' do
      path = 'composer'
      comparison_view = @presenter.store.view(path)
      @presenter.compose_at(path)

      expect(comparison_view).to eq @presenter.view.composed
    end

    it 'can be overidden' do
      @presenter.view = Pakyow::Presenter::View.new('foo')
      expect('foo').to eq @presenter.view.to_html
    end

    it 'can be tested for existence' do
      expect(@presenter.view?('/')).to be true
      expect(@presenter.view?('/fail')).to be false
    end
  end

  context 'test path' do
    it 'can be set and retrieved' do
      path = 'multi'
      @presenter.path = path
      expect(path).to eq @presenter.path
    end
  end

  context 'test store' do
    it 'can be changed' do
      original_store = @presenter.store
      @presenter.store = :test
      expect(original_store).to_not eq @presenter.store
    end
  end

  context 'test template' do
    it 'for route is accessible' do
      expect(@presenter.store.template(@path)).to eq @presenter.composer.template
    end

    it 'instance can be set and retrieved' do
      template = @presenter.store.template(:multi)
      @presenter.template = template
      expect(template).to eq @presenter.composer.template
    end

    it 'can be set by name and retrieved' do
      name = :multi
      template = @presenter.store.template(name)
      @presenter.template = name
      expect(template).to eq @presenter.composer.template
    end

    it 'uses current template' do
      @presenter.template = :multi
      expect('multi').to eq @presenter.view.composed.title
    end
  end

  context 'test page' do
    it 'has a route accessible for default page' do
      expect(@presenter.store.page(@path)).to eq @presenter.composer.page
    end

    it 'can by set and retrieved' do
      page = @presenter.store.page('sub')
      @presenter.page = page
      expect(page).to eq @presenter.composer.page
    end

    it 'uses current page' do
      page = @presenter.store.page('sub')
      @presenter.page = page
      composed = str_to_doc(@presenter.view.composed.to_html).css('body').text.strip

      expect(page.content(:default).to_s.strip).to eq composed
    end
  end

  context 'test presented' do
    it 'has correct value' do
      expect(@presenter.presented?).to be true

      @presenter.prepare_with_context(Pakyow::AppContext.new(mock_request('/fail')))

      expect(@presenter.presented?).to be false
    end
  end

  context 'test composer' do
    it 'composes from current context' do
      path = 'composer'
      @presenter.prepare_with_context(Pakyow::AppContext.new(mock_request(path)))
      expect(@presenter.store.view(path)).to eq @presenter.compose.view
    end

    it 'can precompose' do
      @presenter.prepare_with_context(Pakyow::AppContext.new(mock_request('composer')))
      composer = @presenter.composer

      @presenter.precompose!
      expect(composer.view).to eq @presenter.view
    end
  end

  context 'test partial' do
    it 'can be set' do
      @presenter.view.partials = { partial: 'partial1' }
      partial = Pakyow::Presenter::Partial.load(File.join(VIEW_PATH, '_partial1.html'))
      expect(partial).to eq @presenter.view.partial(:partial)
    end
  end
end


text:
class OverwatchShotAction : public BaseAction
{
protected:
	ShootAction* m_shoot;

	virtual void _Execute(float dTime);

public:
	OverwatchShotAction(Character* owner, ShootAction* shootAction);
	~OverwatchShotAction();

#ifndef NETWORK_SERVER
	static OverwatchShotAction* Read(RakNet::BitStream& bsIn);
#endif

#ifdef NETWORK_SERVER
	virtual void Write(RakNet::BitStream& bs);
#endif
};


text:
package org.apache.commons.configuration2.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 *

 * A class for selecting a specific node based on a key or a set of keys.
 *

 *

 * An instance of this class is initialized with the key of a node. It is also possible to concatenate multiple keys -
 * e.g. if a sub key is to be constructed from another sub key. {@code NodeSelector} provides the {@code select()}
 * method which evaluates the wrapped keys on a specified root node and returns the resulting unique target node. The
 * class expects that the key(s) stored in an instance select exactly one target node. If this is not the case, result
 * is null indicating that the selection criteria are not sufficient.
 *

 *

 * Implementation node: Instances of this class are immutable. They can be shared between arbitrary components.
 *

 *
 * @since 2.0
 */
public class NodeSelector {
    /** Stores the wrapped keys. */
    private final List<String> nodeKeys;

    /**
     * Creates a new instance of {@code NodeSelector} and initializes it with the key to the target node.
     *
     * @param key the key
     */
    public NodeSelector(final String key) {
        this(Collections.singletonList(key));
    }

    /**
     * Creates a new instance of {@code NodeSelector} and initializes it with the list of keys to be used as selection
     * criteria.
     *
     * @param keys the keys for selecting nodes
     */
    private NodeSelector(final List<String> keys) {
        nodeKeys = keys;
    }

    /**
     * Applies this {@code NodeSelector} on the specified root node. This method applies the selection criteria stored in
     * this object and tries to determine a single target node. If this is successful, the target node is returned.
     * Otherwise, result is null.
     *
     * @param root the root node on which to apply this selector
     * @param resolver the {@code NodeKeyResolver}
     * @param handler the {@code NodeHandler}
     * @return the selected target node or null
     */
    public ImmutableNode select(final ImmutableNode root, final NodeKeyResolver<ImmutableNode> resolver, final NodeHandler<ImmutableNode> handler) {
        List<ImmutableNode> nodes = new LinkedList<>();
        final Iterator<String> itKeys = nodeKeys.iterator();
        getFilteredResults(root, resolver, handler, itKeys.next(), nodes);

        while (itKeys.hasNext()) {
            final String currentKey = itKeys.next();
            final List<ImmutableNode> currentResults = new LinkedList<>();
            nodes.forEach(currentRoot -> getFilteredResults(currentRoot, resolver, handler, currentKey, currentResults));
            nodes = currentResults;
        }

        return nodes.size() == 1 ? nodes.get(0) : null;
    }

    /**
     * Creates a sub {@code NodeSelector} object which uses the key(s) of this selector plus the specified key as selection
     * criteria. This is useful when another selection is to be performed on the results of a first selector.
     *
     * @param subKey the additional key for the sub selector
     * @return the sub {@code NodeSelector} instance
     */
    public NodeSelector subSelector(final String subKey) {
        final List<String> keys = new ArrayList<>(nodeKeys.size() + 1);
        keys.addAll(nodeKeys);
        keys.add(subKey);
        return new NodeSelector(keys);
    }

    /**
     * Compares this object with another one. Two instances of {@code NodeSelector} are considered equal if they have the
     * same keys as selection criteria.
     *
     * @param obj the object to be compared
     * @return a flag whether these objects are equal
     */
    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof NodeSelector)) {
            return false;
        }

        final NodeSelector c = (NodeSelector) obj;
        return nodeKeys.equals(c.nodeKeys);
    }

    /**
     * Returns a hash code for this object.
     *
     * @return a hash code
     */
    @Override
    public int hashCode() {
        return nodeKeys.hashCode();
    }

    /**
     * Returns a string representation for this object. This string contains the keys to be used as selection criteria.
     *
     * @return a string for this object
     */
    @Override
    public String toString() {
        return new ToStringBuilder(this).append("keys", nodeKeys).toString();
    }

    /**
     * Executes a query for a given key and filters the results for nodes only.
     *
     * @param root the root node for the query
     * @param resolver the {@code NodeKeyResolver}
     * @param handler the {@code NodeHandler}
     * @param key the key
     * @param nodes here the results are stored
     */
    private void getFilteredResults(final ImmutableNode root, final NodeKeyResolver<ImmutableNode> resolver, final NodeHandler<ImmutableNode> handler,
        final String key, final List<ImmutableNode> nodes) {
        final List<QueryResult<ImmutableNode>> results = resolver.resolveKey(root, key, handler);
        results.forEach(result -> {
            if (!result.isAttributeResult()) {
                nodes.add(result.getNode());
            }
        });
    }
}


text:
/**
 * Created by tr1o5087 on 17.02.2015.
 */

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * A Logback appender that publishes log data to an AMQP topic
 * exchange for other applications to consume. Data is published
 * using the logging context and log level as the publishing key.
 * This allows many applications' log data to be aggregated into a
 * single AMQP exchange and allows consumers to selectively
 * subscribe to a subset of log data.
 */
public class SampleAmqpAppender extends AppenderBase<ILoggingEvent> {

    /**
     * The Layout used to format the log message body.
     */
    private Layout<ILoggingEvent> layout;

    /**
     * AMQP server connection parameters
     */
    private String host;
    private int port;
    private String virtualHost;
    private String username;
    private String password;
    private String exchangeName;
    private String routingKey;

    /**
     * Connection and Channel properties that will be
     * initialized using the above provided properties.
     */
    private Connection connection;
    private Channel channel;

    @Override
    public void start() {

        // Create a Connection and Channel to the AMQP server
        // using supplied properties.
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(this.host);
        factory.setUsername(this.username);
        factory.setPassword(this.password);
        factory.setVirtualHost(this.virtualHost);
        factory.setPort(this.port);
        factory.setRequestedHeartbeat(0);

//        Map<String, Object> args = new HashMap<String, Object>();
//        args.put("x-message-ttl", 10000);
        try {
            this.connection = factory.newConnection();
            this.channel = this.connection.createChannel();
            // exchangeDeclare() is idempotent. We use a "topic"
            // exchange for pub-sub style messaging.
            this.channel.exchangeDeclare(this.exchangeName, "direct", true);
        } catch (final IOException e) {
            e.printStackTrace();
        }
        super.start();
    }

    @Override
    public void stop() {
        try {
            this.channel.close();
        } catch (IOException ignored) {
        }
        try {
            this.connection.close();
        } catch (IOException ignored) {
        }
        super.stop();
    }

    @Override
    protected void append(final ILoggingEvent event) {

        // Add useful information about the logging event
        // to AMQP message headers.
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("context", event.getLoggerContextVO().getName());
        headers.put("level", event.getLevel().levelStr);
        headers.put("timestamp", event.getTimeStamp());
        headers.put("loggerName", event.getLoggerName());
        headers.put("threadName", event.getThreadName());
        headers.put("message", event.getMessage());

        // Build a publishing key using the logging context and log level.
        // Logging context usually corresponds to application name.
        final String context = event.getLoggerContextVO().getName();
        final Level level = event.getLevel();

        ObjectMapper mapper = new ObjectMapper();

        // Use the provided layout to format the logging event
        // and set that as the AMQP message payload.
        String message = this.layout.doLayout(event);
        final byte[] payload = message.getBytes();

        BasicProperties props = new BasicProperties.Builder()
                .contentType("application/json")
                .deliveryMode(2)
                .priority(0)
                .headers(headers)
                .build();
        try {
            final byte[] valueAsBytes = mapper.writeValueAsBytes(headers);
            // Publish the log data.
            this.channel.basicPublish(this.exchangeName, this.routingKey, props, valueAsBytes);
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public void setLayout(Layout<ILoggingEvent> layout) {
        this.layout = layout;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setVirtualHost(String virtualHost) {
        this.virtualHost = virtualHost;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setExchangeName(String exchangeName) {
        this.exchangeName = exchangeName;
    }
    public void setRoutingKey(String routingKey) {
        this.routingKey = routingKey;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("host: ");
        sb.append(this.host);
        sb.append(", port: ");
        sb.append(this.port);
        sb.append(", virtualHost: ");
        sb.append(this.virtualHost);
        sb.append(", username: ");
        sb.append(this.username);
        sb.append(", exchangeName: ");
        sb.append(this.exchangeName);
        sb.append(", routingKey: ");
        sb.append(this.routingKey);
        return sb.toString();
    }
}


text:
namespace google_breakpad {

class ExploitabilityLinux : public Exploitability {
 public:
  ExploitabilityLinux(Minidump *dump,
                      ProcessState *process_state);

  // Parameters are the minidump to analyze, the object representing process
  // state, and whether to enable objdump disassembly.
  // Enabling objdump will allow exploitability analysis to call out to
  // objdump for diassembly. It is used to check the identity of the
  // instruction that caused the program to crash. If there are any
  // portability concerns, this should not be enabled.
  ExploitabilityLinux(Minidump *dump,
                      ProcessState *process_state,
                      bool enable_objdump);

  virtual ExploitabilityRating CheckPlatformExploitability();

 private:
  friend class ExploitabilityLinuxTest;

  // Takes the address of the instruction pointer and returns
  // whether the instruction pointer lies in a valid instruction region.
  bool InstructionPointerInCode(uint64_t instruction_ptr);

  // Checks the exception that triggered the creation of the
  // minidump and reports whether the exception suggests no exploitability.
  bool BenignCrashTrigger(const MDRawExceptionStream *raw_exception_stream);

  // This method checks if the crash occurred during a write to read-only or
  // invalid memory. It does so by checking if the instruction at the
  // instruction pointer is a write instruction, and if the target of the
  // instruction is at a spot in memory that prohibits writes.
  bool EndedOnIllegalWrite(uint64_t instruction_ptr);

#ifndef _WIN32
  // Disassembles raw bytes via objdump and pipes the output into the provided
  // buffer, given the desired architecture, the file from which objdump will
  // read, and the buffer length. The method returns whether the disassembly
  // was a success, and the caller owns all pointers.
  static bool DisassembleBytes(const string &architecture,
                               const uint8_t *raw_bytes,
                               const unsigned int MAX_OBJDUMP_BUFFER_LEN,
                               char *objdump_output_buffer);

  // Parses the objdump output given in |objdump_output_buffer| and extracts
  // the line of the first instruction into |instruction_line|.  Returns true
  // when the instruction line is successfully extracted.
  static bool GetObjdumpInstructionLine(
      const char *objdump_output_buffer,
      string *instruction_line);

  // Tokenizes out the operation and operands from a line of instruction
  // disassembled by objdump. This method modifies the pointers to match the
  // tokens of the instruction, and returns if the tokenizing was a success.
  // The caller owns all pointers.
  static bool TokenizeObjdumpInstruction(const string &line,
                                         string *operation,
                                         string *dest,
                                         string *src);

  // Calculates the effective address of an expression in the form reg+a or
  // reg-a, where 'reg' is a register and 'a' is a constant, and writes the
  // result in the pointer. The method returns whether the calculation was
  // a success. The caller owns the pointer.
  static bool CalculateAddress(const string &address_expression,
                               const DumpContext &context,
                               uint64_t *write_address);
#endif  // _WIN32

  // Checks if the stack pointer points to a memory mapping that is not
  // labelled as the stack.
  bool StackPointerOffStack(uint64_t stack_ptr);

  // Checks if the stack or heap are marked executable according
  // to the memory mappings.
  bool ExecutableStackOrHeap();

  // Whether this exploitability engine is permitted to shell out to objdump
  // to disassemble raw bytes.
  bool enable_objdump_;
};

}  // namespace google_breakpad

#endif  // GOOGLE_BREAKPAD_PROCESSOR_EXPLOITABILITY_LINUX_H_


text:
{% for post in site.linkposts %}
{% include post-info.html %}
{% endfor %}


text:
package main

import (
	"encoding/json"
	"net/http"
	"os"
)

func fileExists(fp string) bool {
	info, err := os.Stat(fp)
	if err != nil {
		return false
	}
	return info.IsDir() == false
}

func dirExists(fp string) bool {
	info, err := os.Stat(fp)
	if err != nil {
		return false
	}
	return info.IsDir()
}

func printError(w http.ResponseWriter, err interface{}) {
	printJson(w, err)
}

func printJson(w http.ResponseWriter, obj interface{}) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	json.NewEncoder(w).Encode(obj)
}


text:
<!doctype html>

  <title>core-toolbar</title>

  <link rel="import" href="core-toolbar.html">

  <core-toolbar>

    Toolbar: light-theme (default)
  </core-toolbar>

  <core-toolbar theme="core-dark-theme">

    Toolbar: dark-theme
  </core-toolbar>

  <core-toolbar class="tall">

    Toolbar: tall
  </core-toolbar>

  <core-toolbar class="tall">

    Toolbar: tall with actions pin to the bottom
  </core-toolbar>

  <core-toolbar class="medium-tall">

    Toolbar: medium tall with label aligns to the bottom
  </core-toolbar>

  <core-toolbar class="tall">

Toolbar: label aligns to the middle

some stuffs align to the bottom

  </core-toolbar>


text:
import {BOTab} from "./BOTab";
/**
 * Created by Louis on 24/02/2017.
 */
export class BOTabsContainer{

  constructor(
    public tabs: BOTab[],
    public cssClass:string,
    public isDisplay:boolean
  )
  {}
}


text:
@component("self_help_fest")
    San Bernardino
@endcomponent


text:
/**
 * 2014Äê11ÔÂ8ÈÕ ÉÏÎç11:11:53
 */
package action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 *
 *
 * @author wavky.wand
 *
 */
public class MasterCheckInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com
	 * .opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		ActionContext ac = invocation.getInvocationContext();
		Boolean isMaster = (Boolean) ac.getSession().get("isMaster");
		if (isMaster != null && isMaster) {
			String result = invocation.invoke();
			return result;
		} else {
			return Action.LOGIN;
		}
	}

}


text:
package com.mendeley.sdk.request;

import android.content.res.AssetManager;
import android.test.AndroidTestCase;

import com.mendeley.sdk.AuthTokenManager;
import com.mendeley.sdk.ClientCredentials;
import com.mendeley.sdk.testUtils.InMemoryAuthTokenManager;
import com.mendeley.sdk.Mendeley;
import com.mendeley.sdk.RequestsFactory;
import com.mendeley.sdk.request.endpoint.DocumentEndpoint;
import com.mendeley.sdk.request.endpoint.OAuthTokenEndpoint;
import com.mendeley.sdk.testUtils.ClientCredentialsFromAssetsFactory;
import com.mendeley.sdk.testUtils.TestAccountSetupUtils;
import com.mendeley.sdk.testUtils.EmailAndPasswordFromAssetsFactory;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

public abstract class SignedInTest extends AndroidTestCase {

    private RequestsFactory requestsFactory;
    private ClientCredentials clientCredentials;
    private AuthTokenManager authTokenManager;

    private TestAccountSetupUtils testAccountSetupUtils;
    private Random random;

    @Override
    protected void setUp() throws Exception {
        random = new Random();

        final AssetManager assetManager =  getContext().getAssets();
        clientCredentials = ClientCredentialsFromAssetsFactory.create(assetManager);
        authTokenManager = new InMemoryAuthTokenManager();

        // sign in
        final EmailAndPasswordFromAssetsFactory.UsernameAndPassword usernameAndPassword = EmailAndPasswordFromAssetsFactory.create(assetManager);
        new OAuthTokenEndpoint.AccessTokenWithPasswordRequest(authTokenManager, clientCredentials, usernameAndPassword.username, usernameAndPassword.password).run();

        requestsFactory = new Mendeley.RequestFactoryImpl(authTokenManager, clientCredentials);
        testAccountSetupUtils = new TestAccountSetupUtils(authTokenManager, clientCredentials, requestsFactory);

        // reset account
        testAccountSetupUtils.cleanAll();
    }

    protected final RequestsFactory getRequestFactory() {
        return requestsFactory;
    }

    protected final AuthTokenManager getAuthTokenManager() {
        return authTokenManager;
    }

    protected final ClientCredentials getClientCredentials() {
        return clientCredentials;
    }

    protected final TestAccountSetupUtils getTestAccountSetupUtils() {
        return testAccountSetupUtils;
    }

    protected final Random getRandom() {
        return random;
    }

    public String generateRandomString(int length) {
        int asciiFirst = 33;
        int asciiLast = 126;
        Integer[] exceptions = {34, 39, 96};

        List<Integer> exceptionsList = Arrays.asList(exceptions);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int charIndex;
            do {
                charIndex = random.nextInt(asciiLast - asciiFirst + 1) + asciiFirst;
            }
            while (exceptionsList.contains(charIndex));

            builder.append((char) charIndex);
        }

        return builder.toString();
    }

    protected Date getServerDate() throws Exception {
        // wait a bit, so we get a "fresh" date
        Thread.sleep(1000);
        return getRequestFactory().newGetDocumentsRequest((DocumentEndpoint.DocumentRequestParameters) null).run().serverDate;
    }
}


text:
.SUFFIXES:

.SUFFIXES: .js .ts .pug .html .sass

JSBUILDER = export NODE_ENV=production; node util/scripts/build.js

.PHONY: default
default: dist

.PHONY: init
init: mkdirs clean util/bin/modd util/bin/sassc
	npm install

util/bin/modd:
	curl -o tmp/modd.tgz -L https://github.com/cortesi/modd/releases/download/v0.4/modd-0.4-linux64.tgz
	tar axvf tmp/modd.tgz --directory tmp
	mv tmp/modd*/modd util/bin/modd
	rm -rf tmp/*

util/bin/sassc:
	mkdir -p tmp/sassc
	git clone https://github.com/sass/sassc.git tmp/sassc
	git clone https://github.com/sass/libsass.git tmp/libsass
	git clone https://github.com/sass/sass-spec.git tmp/sass-spec
	export SASS_LIBSASS_PATH=$(shell pwd)/tmp/libsass; \
		export SASS_SPEC_PATH=$(shell pwd)/tmp/sass-spec; \
		cd tmp/sassc; make
	mv tmp/sassc/bin/sassc util/bin/sassc
	rm -rf tmp/*

.PHONY: mkdirs
mkdirs:
	mkdir -p tmp
	mkdir -p util/bin
	mkdir -p dist

.PHONY:	clean
clean:
	rm -rf tmp/*
	rm -rf util/bin/*
	rm -rf dist/*
	rm -rf node_modules

.PHONY:	watch
watch:
	modd

# Sass / CSS

.PHONY: css
css: dist/index.css

dist/index.css: $(shell find sass -name *.sass)
	util/bin/sassc sass/index.sass | node node_modules/.bin/postcss --config postcss.json > $@

# Pug / Html

.PHONY: html
html: dist/index.html

dist/index.html: $(shell find pug -name *.pug)
	node node_modules/.bin/pug -O package.json pug/index.pug -o $(dir $@)

# TypeScript / Javascript

.PHONY: js
js: dist/index.js

dist/index.js: $(shell find ts -name *.ts -or -name *.tsx)
	$(JSBUILDER) -c ts/index.ts > dist/index.js

# dist/

dist: dist/index.css dist/index.html dist/index.js


text:
body,html,#Spreads{color:#000}
body{background:#fff}
form>article{background-color:#fff}
svg{fill:#000}
textarea,input,input[type="button"]{color:#000}
textarea:hover,input:hover{color:#000}


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    # == Attributes
    #  boolean_node :include, 'Include', 'true', 'false', :optional => true
    #  boolean_node :include_item_count, 'IncludeItemCount', 'true', 'false', :optional => true
    #  boolean_node :include_favorite_searche_count, 'IncludeFavoriteSearcheCount', 'true', 'false', :optional => true
    #  boolean_node :include_favorite_seller_count, 'IncludeFavoriteSellerCount', 'true', 'false', :optional => true
    #  text_node :sort, 'Sort', :optional => true
    #  numeric_node :max_results, 'MaxResults', :optional => true
    #  text_node :user_defined_list_name, 'UserDefinedListName', :optional => true
    #  boolean_node :include_list_contents, 'IncludeListContents', 'true', 'false', :optional => true
    class MyeBaySelection
      include XML::Mapping
      include Initializer
      root_element_name 'MyeBaySelection'
      boolean_node :include, 'Include', 'true', 'false', :optional => true
      boolean_node :include_item_count, 'IncludeItemCount', 'true', 'false', :optional => true
      boolean_node :include_favorite_searche_count, 'IncludeFavoriteSearcheCount', 'true', 'false', :optional => true
      boolean_node :include_favorite_seller_count, 'IncludeFavoriteSellerCount', 'true', 'false', :optional => true
      text_node :sort, 'Sort', :optional => true
      numeric_node :max_results, 'MaxResults', :optional => true
      text_node :user_defined_list_name, 'UserDefinedListName', :optional => true
      boolean_node :include_list_contents, 'IncludeListContents', 'true', 'false', :optional => true
    end
  end
end


text:
"use strict";

function DocumentAddress() {
  Array.apply(this);
  if (arguments.length > 0) {
    this._pushVals(arguments);
  }
}

DocumentAddress.Prototype = function() {
  this.isBefore = function(other) {
    if (this.length === 0) {
      return false;
    }
    if (other.length === 0) {
      return false;
    }
    var aIsShorter = (this.length < other.length);
    for (var idx = 0;; idx++) {
      var a = this[idx];
      var b = other[idx];
      if (a === undefined) {
        if (aIsShorter) {
          return true;
        } else {
          return false;
        }
      }
      if (b === undefined) {
        return false;
      }
      if (a === b) continue;
      return (a < b);
    }
  };
  this.isAfter = function(other) {
    return other.isBefore(this);
  };
  this.isEqual = function(other) {
    return DocumentAddress.equal(this, other);
  };
  this.equals = this.isEqual;
  this.append = function(other) {
    return this._pushVals(other);
  };
  this.clone = function() {
    return new DocumentAddress().append(this);
  };
  this.slice = function() {
    return new DocumentAddress()._pushVals(Array.prototype.slice.apply(this, arguments));
  };
  this.push = function() {
    Array.prototype.push.apply(this, arguments);
    return this;
  };
  this._pushVals = function(arr) {
    Array.prototype.push.apply(this, arr);
    return this;
  };
};
DocumentAddress.Prototype.prototype = Array.prototype;
DocumentAddress.prototype = new DocumentAddress.Prototype();
DocumentAddress.prototype.constructor = DocumentAddress;

DocumentAddress.equal = function(a, b) {
  var len = a.length;
  if (len !== b.length) return false;
  for (var idx = 0; idx < len; idx++) {
    if (a[idx] !== b[idx]) {
      return false;
    }
  }
  return true;
};

module.exports = DocumentAddress;


text:
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="GadgetDeviceGrouping" version="1.0.0" type="dashboards/gadget" serverRole="CDMFAnalytics">
    <file>device-grouping</file>
</artifact>


text:
require 'net/http'
require 'whois'

module WebChecker

  class NotHttpURIError < StandardError; end
  class InvalidHostError < StandardError; end

  class Http
    def initialize(uri_str, limit = 10)
      @uri_str, @limit = uri_str, limit
      @uri_str = "http://#{@uri_str}" unless @uri_str.include?('://')
      @uri = URI(@uri_str)
      raise NotHttpURIError, "Not HTTP URI: #{@uri_str}" unless @uri.scheme.include?('http')
      raise InvalidHostError, "Domain or host does not exists: #{@uri.host}" unless domain_exists?(@uri.host)
    end

    def accessible?
      return false if @limit == 0
      begin
        Net::HTTP.start(@uri.host, @uri.port, :use_ssl => @uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
          request = Net::HTTP::Get.new(@uri.request_uri)
          response = http.request(request)
          case response
            when Net::HTTPSuccess      then true
            when Net::HTTPClientError  then false
            when Net::HTTPServerError  then false
            when Net::HTTPRedirection
              location = response['location']
              unless location.include?('://')
                host_with_protocol = @uri_str[/^[^\:]+\:\/\/[^\/]+/, 0]
                location = host_with_protocol + location
              end
              self.class.new(location, @limit - 1).accessible?
            else
              false
          end
        end
      rescue SocketError
        false
      end
    end

    private
      def domain_exists?(domain)
        begin
          Whois::Client.new.lookup(domain)
        rescue Whois::ServerNotFound
          return false
        rescue Whois::ConnectionError
          return true
        end
        true
      end
  end
end


text:
Planning
========

Use the following to work with extension:wiretap

```sql
SELECT
	p.page_id AS page_id
	p.page_title AS page_title,
	p.page_namespace AS page_namespace,
	COUNT(DISTINCT(user_name)) AS unique_hits,
	red.rd_namespace AS redir_to_ns,
	red.rd_title AS redir_to_title,
	redir_page.page_id AS redir_id
FROM wiretap AS w
INNER JOIN page AS p ON
	p.page_id = w.page_id
LEFT JOIN redirect AS red ON
	red.rd_from = p.page_id
LEFT JOIN page AS redir_page ON
	red.rd_namespace = redir_page.page_namespace
	AND red.rd_title = redir_page.page_title
WHERE
	hit_timestamp > 20140801000000
GROUP BY
	p.page_namespace, p.page_title
ORDER BY
	unique_hits DESC
LIMIT 20;
```

Use something like this to count watches and such:

```sql
SELECT * FROM (
	SELECT
		p.page_title,
		p.page_namespace,
		p.page_counter,
		p.page_len,
		SUM( IF(w.wl_title IS NOT NULL, 1, 0) ) AS num_watches,
		p.page_counter / SUM( IF(w.wl_title IS NOT NULL, 1, 0) ) AS view_watch_ratio,
		p.page_len / SUM( IF(w.wl_title IS NOT NULL, 1, 0) ) AS length_watch_ratio
	FROM
		watchlist AS w
	LEFT JOIN page AS p ON
		w.wl_title = p.page_title
		AND w.wl_namespace = p.page_namespace
	LEFT JOIN categorylinks AS c ON
		c.cl_from = p.page_id
	LEFT JOIN user AS u ON
		u.user_id = w.wl_user
	LEFT JOIN revision AS r ON
		r.rev_id = p.page_latest
	WHERE
		p.page_namespace = 0
		AND p.page_is_redirect = 0
		AND r.rev_timestamp > 20140701000000
	GROUP BY
		p.page_title, p.page_namespace
	ORDER BY
		view_watch_ratio DESC
) AS tmp WHERE num_watches < 2 LIMIT 10;
```

Or combine them like this:

```sql
SELECT
	p.page_id AS page_id,
	p.page_title AS page_title,
	p.page_namespace AS page_namespace,
	COUNT(DISTINCT(user_name)) AS unique_hits,
	red.rd_namespace AS redir_to_ns,
	red.rd_title AS redir_to_title,
	redir_page.page_id AS redir_id,
	(
		SELECT COUNT(*)
		FROM watchlist AS watch
		WHERE
			watch.wl_namespace = p.page_namespace
			AND watch.wl_title = p.page_title
	) AS watches
FROM wiretap AS w
INNER JOIN page AS p ON
	p.page_id = w.page_id
LEFT JOIN redirect AS red ON
	red.rd_from = p.page_id
LEFT JOIN page AS redir_page ON
	red.rd_namespace = redir_page.page_namespace
	AND red.rd_title = redir_page.page_title
WHERE
	hit_timestamp > 20140801000000
GROUP BY
	p.page_namespace, p.page_title
ORDER BY
	unique_hits DESC
LIMIT 20;
```

Counting reviews required per day
---------------------------------

```sql
SELECT user_id from user where user_name = "Athomaso";

SELECT
	SUBSTR( r.rev_timestamp, 1, 8 ) AS rev_date,
	COUNT( DISTINCT( CONCAT( p.page_namespace, ':', p.page_title ) ) ) AS revised_pages,
	COUNT( * ) AS total_revisions
FROM revision AS r
LEFT JOIN page AS p ON
	r.rev_page = p.page_id
INNER JOIN watchlist AS w ON
	p.page_namespace = w.wl_namespace
	AND p.page_title = w.wl_title
	AND w.wl_user = 2
WHERE
	r.rev_timestamp > 20140601000000
GROUP BY
	rev_date
ORDER BY
	rev_date DESC
LIMIT 100000;
```


text:
import java.lang.System;

/**
 * This class should compile when a data operation (data-import) phase is invoked.
 * This insures the building/packaging of the normal lifecycle occurs as a predecessor.
 */
public class Test
{
    public static void main(String[] args) {
        System.out.println("this class should have compiled to validate a data operation does a normal build; e.g. package lifecycle executes");
    }
}


text:
use std::time::Duration as StdDuration;
use time::Duration;

pub fn to_std_duration(duration: Duration) -> StdDuration {
    StdDuration::from_millis(duration.num_milliseconds() as u64)
}


text:
package com.java110.user.cmd.wechatSubscribe;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.AbstractServiceCmdListener;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.intf.user.IWechatSubscribeV1InnerServiceSMO;
import com.java110.po.wechatSubscribe.WechatSubscribePo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 类表述:保存
 * 服务编码:wechatSubscribe.saveWechatSubscribe
 * 请求路劲:/app/wechatSubscribe.SaveWechatSubscribe
 * add by 吴学文 at 2022-02-22 16:17:23 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网:http://www.homecommunity.cn
 * 温馨提示:如果您对此文件进行修改 请不要删除原有作者及注释信息,请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复,注释10至20行 加入 20行至30行
 */
@Java110Cmd(serviceCode = "wechatSubscribe.saveWechatSubscribe")
public class SaveWechatSubscribeCmd extends AbstractServiceCmdListener {

    private static Logger logger = LoggerFactory.getLogger(SaveWechatSubscribeCmd.class);

    public static final String CODE_PREFIX_ID = "10";

    @Autowired
    private IWechatSubscribeV1InnerServiceSMO wechatSubscribeV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "openId", "请求报文中未包含openId");
Assert.hasKeyAndValue(reqJson, "appId", "请求报文中未包含appId");
Assert.hasKeyAndValue(reqJson, "openType", "请求报文中未包含openType");

    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

       WechatSubscribePo wechatSubscribePo = BeanConvertUtil.covertBean(reqJson, WechatSubscribePo.class);
        wechatSubscribePo.setSubId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        int flag = wechatSubscribeV1InnerServiceSMOImpl.saveWechatSubscribe(wechatSubscribePo);

        if (flag < 1) {
            throw new CmdException("保存数据失败");
        }

        cmdDataFlowContext.setResponseEntity(ResultVo.success());
    }
}


text:
Depends on how the source JavaScript library is written, you can create your typings in several ways.

If the

The source JavaScript library can be written in several ways:

- CommonJS module (typically nodeJS)
- Global

When creating typings, the first thing you need to decide is what kind of typings you are writing?

The answer of this question depends on a few factors:

- How does the source being referenced?
- Does the source being referenced through `require('...')`, `import ... from '...'`, global, or all of the above?

  > How can the source being referenced?


text:
* Readability! Readability!! Readability!!!
* Break nesting as much as possible
* user "not" operators while comparing to avoid nesting of statements inside if construct


text:
from openstack import service_filter

class TelemetryService(service_filter.ServiceFilter):
    """The telemetry service."""

    valid_versions = [service_filter.ValidVersion('v2')]

    def __init__(self, version=None):
        """Create a telemetry service."""
        super(TelemetryService, self).__init__(service_type='metering',
                                               version=version)


text:
<script>
var siteImLookingAt, siteCore, siteLink, $newDiv;

// arguments[0] is the HTML widget your code is sitting in.  Using this, it is possible to identify the site containing the HTML widget
siteImLookingAt = arguments[0].closest('.ui-dialog').find('.sites_core').data('controllers');

siteCore = siteImLookingAt.sites_core;

siteLink = siteImLookingAt && siteCore && siteCore.options.site;

// This code below uses jQuery to create a DIV and uses one of Frog's utitilies to create a unique ID, allowing jQuery to append to the div, $newDiv.
$newDiv = $("<div>", {
        id: Frog.Utilities.generateSimpleId()
    }
);

// Knowing the siteLink from the above, we can use Frog's API sites.getInfo to return the site's icon
Frog.Model
    .api('share.getList', {
        target: "CF96C84720025152F781FF7433761F0D75EAEDCC694DC59C"
    }).done(function(siteResponse) {

        //Create an variable to add a title to the DIV
        var alt="";
        // share.getList does not differentiate between public in school and public on the web, if company is defined, the site is not private
        if (siteResponse.data.company!==undefined && siteResponse.data.company!==null) {
            $newDiv.addClass(
                // Use fontawesome to dpecit status
                "fa fa-unlock-alt fa-3x"
            );
            alt += "Site is not private and is shared with:\n";
        } else {
            $newDiv.addClass(
                "fa fa-lock fa-3x"
            );
            alt += "Site is private and is visible to:\n";
        }
        //Loop through siteResponse.data.user object and return the displayname value
        for (var key in siteResponse.data.user) {
            var obj = siteResponse.data.user[key];
            alt+=obj.identity.displayname+'\n';
        }
        // set the alt variable as $newDiv's title
        $newDiv.attr('title', alt);
    });

arguments[0].append($newDiv);

</script>


text:
package com.phoenixnap.oss.ramlplugin.raml2code.github;

import org.junit.Test;

import com.phoenixnap.oss.ramlplugin.raml2code.rules.GitHubAbstractRuleTestBase;
import com.phoenixnap.oss.ramlplugin.raml2code.rules.Spring4ControllerInterfaceRule;

/**
 * @author aleksandars
 * @since 0.10.12
 */
public class Issue210RulesTest extends GitHubAbstractRuleTestBase {

	@Test
	public void applySpring4ControllerInterfaceRule_shouldCreate_valid_class_inheritance() throws Exception {
		loadRaml("issue-210.raml");
		rule = new Spring4ControllerInterfaceRule();
		rule.apply(getControllerMetadata(), jCodeModel);
		verifyGeneratedCode("Issue210Spring4ControllerStub");
	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using ZWave.Channel;
using ZWave.Channel.Protocol;

namespace ZWave.CommandClasses
{
    public class MultiChannelCapabilityReport : NodeReport
    {
        private const int _numberOfFixedParams = 3;

        public bool IsDynamic { get; }

        public byte EndPoint { get; }

        public CommandClass[] SupportedCommandClasses { get; }

        public MultiChannelCapabilityReport(Node node, byte[] payload)
            : base(node)
        {
            if (payload == null)
                throw new ArgumentNullException(nameof(payload));
            if (payload.Length < _numberOfFixedParams)
                throw new ReponseFormatException($"The response was not in the expected format. {GetType().Name}: Payload: {BitConverter.ToString(payload)}");

            IsDynamic = (payload[0] & 0x80) > 0;
            EndPoint = (byte)(payload[0] & 0x7F);

            // Ignoring payload[1] - Generic Device Class
            // Ignoring payload[2] - Specific Device Class
            //
            SupportedCommandClasses = new CommandClass[payload.Length - _numberOfFixedParams];
            for (int i = 0; i < SupportedCommandClasses.Length; i++)
            {
                SupportedCommandClasses[i] = (CommandClass)payload[_numberOfFixedParams + i];
            }
        }
    }
}


text:
* Use PostCSS 5.0 API.
* Do not add spaces to selector in compressed CSS.
* Move nodes with its comment above.

## 0.3.2
* Fix `@supports` at-rule support (by Ben Briggs).

## 0.3.1
* Pass PostCSS Plugin Guidelines.

## 0.3
* Do not unwrap custom at-rules.
* Add `bubble` option to unwrap some custom at-rules.
* Support PostCSS 4.1 API.
* Fix last semicolon after unwrapping.

## 0.2.2
* Module returns function to have common PostCSS API.

## 0.2.1
* Add comma support to selectors unwrap.

## 0.2
* Use PostCSS 4.0.
* Fix indent, when move rules to other parent.

## 0.1
* Initial release.