text:
layout: styleguide
title: Grid - Marginless Combinations
---

{% include styleguide/grid/marginless/combinations/index.html %}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by sheldon on 2016/4/15.
 */

'use strict';

define(function (require, exports, module) {
    module.exports = function (app) {
        require('services/queryQoutiqueListService.js')(app);
        app.register.controller('RecommendCtrl', ['$scope','Qoutique','$location',
            function ($scope,Qoutique,$location) {
                //$scope.goBack = function () {
                //    window.history.go(-1);
                //};

                $scope.data = Qoutique.query({
                    isBoutique:true
                });
                $scope.data.$promise.then(function (res) {
                    if (res.result != 0){
                        Toast(res.msg,3000);
                        $scope.loadError = true;
                    }
                }).catch(function(error){
                    $scope.loadError = true;
                });

                console.log($scope.data);

                $scope.jumpToGoods = function (x) {
                    if (myBridge) {
                        var jumpUrl = encodeURI($location.absUrl().split('#')[0] + x + '&cityName=' + $scope.cityName);
                        myBridge.callHandler('sendMessageToApp', {
                            type: 2, data: {
                                url: jumpUrl,
                                title: '产品详情',
                                leftNavItems: [1],
                                rightNavItems: [0]
                            }
                        }, function (response) {
                            //todo custom
                        });
                    }
                };

                console.log($scope.data);
            }])
    }
});


text:
using namespace std;

struct test {
	static int i;
};

int main() {
	struct test t;
	cout<<"Works!";
	return 0;
}


text:
import random
import time

class Passenger:
    def __init__(self, world, screen, x, y):
        self.pygame = world.pygame
        self.screen, self.world = screen, world
        model = random.choice(["boy.png", "girl.png"])
        self.image = self.pygame.image.load("./images/passengers/" + model)
        self.x, self.y, self.distance = x, y, random.randint(5000, 10000)
        self.drawing, self.ride = False, False
        self.ui = self.pygame.font.SysFont("monaco", 25)

    def draw(self):
        if self.drawing:
            self.screen.blit(self.image, [self.x, self.y])
        if self.world.taxi.passenger:
            ui_distance = self.ui.render("Distance: %s" % self.distance, 1, (255, 255, 255))
            self.screen.blit(ui_distance, (475, 50))
        else:
            ui_distance = self.ui.render("Distance: 0", 1, (255, 255, 255))
            self.screen.blit(ui_distance, (475, 50))

    # move passenger
    def move(self):
        if self.y >= 480:
            self.change()
            self.y = 0
            self.drawing = False
        key = self.pygame.key.get_pressed()
        if key[self.pygame.K_UP]:
            if self.world.taxi.gear == 1:
                self.y += 0.2
            elif self.world.taxi.gear == 2:
                self.y += 0.4
            elif self.world.taxi.gear == 3:
                self.y += 0.5
            elif self.world.taxi.gear == 4:
                self.y += 0.75

    # passenger game logic
    def update(self):
        if not self.world.taxi.passenger:
            current = self.world.taxi.last_trip
            t = random.randint(current + 5, current + 30)
            if t == int(time.time()):
                self.drawing = True
            key = self.pygame.key.get_pressed()
            if key[self.pygame.K_z] and (self.ride == False) and (self.drawing == True):
                self.drawing = False
                self.world.taxi.add_passenger()

    # change pass
    def change(self):
        model = random.choice(["boy.png", "girl.png"])
        self.image = self.pygame.image.load("./images/passengers/" + model)

    # cab ride
    def cab_ride(self):
        self.distance -= 1000
        if self.distance <= 0:
            self.distance = 0

    # update distance
    def update_dist(self):
        self.distance = random.randint(5000, 10000)


text:
package org.apache.druid.tests.indexer;

import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.testing.guice.DruidTestModuleFactory;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.io.Closeable;

@Guice(moduleFactory = DruidTestModuleFactory.class)
public class ITSystemTableBatchIndexTaskTest extends AbstractITBatchIndexTest
{

  private static final Logger LOG = new Logger(ITSystemTableBatchIndexTaskTest.class);
  private static String INDEX_TASK = "/indexer/wikipedia_index_task.json";
  private static String SYSTEM_QUERIES_RESOURCE = "/indexer/sys_segment_batch_index_queries.json";
  private static String INDEX_DATASOURCE = "wikipedia_index_test";

  @Test
  public void testIndexData() throws Exception
  {
    LOG.info("Starting batch index sys table queries");
    try (
        final Closeable indexCloseable = unloader(INDEX_DATASOURCE + config.getExtraDatasourceNameSuffix());
    ) {
      doIndexTestSqlTest(
          INDEX_DATASOURCE,
          INDEX_TASK,
          SYSTEM_QUERIES_RESOURCE
      );
    }
  }

}


text:
package energy.usef.dso.workflow.plan.connection.forecast;

/**
 * Event implementation for starting CommonReferenceQuery workflow.
 */
public class CommonReferenceQueryEvent {

    @Override
    public String toString() {
        return "CommonReferenceQueryEvent" + "[" + "]";
    }
}


text:
package excelcom.test;

import excelcom.util.Util;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Tests for Util Class
 */
public class UtilTest {

    @Test
    public void shouldGetCharacterPositionInAlphabet() {
        assertEquals(1, Util.getPositionInAlphabet('a'));
        assertEquals(1, Util.getPositionInAlphabet('A'));
        assertEquals(4, Util.getPositionInAlphabet('d'));
        assertEquals(4, Util.getPositionInAlphabet('D'));
        assertEquals(26, Util.getPositionInAlphabet('z'));
        assertEquals(26, Util.getPositionInAlphabet('Z'));
    }

    @Test
    public void shouldGetRangeSize() {
        assertArrayEquals(new int[]{1,1}, Util.getRangeSize("C3"));
        assertArrayEquals(new int[]{2,3}, Util.getRangeSize("A1:C2"));
        assertArrayEquals(new int[]{3,3}, Util.getRangeSize("AA1:AC3"));
        assertArrayEquals(new int[]{3,3}, Util.getRangeSize("AAA1:AAC3"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldNoticeWrongRangeFormat() {
        Util.getRangeSize("A2:B5:C6");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldNoticeWrongColumnSize() {
        Util.getRangeSize("ABCD3:ABCDE4");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldNoticeWrongRowSize() {
        Util.getRangeSize("A2000000:A2000001");
    }

    @Test
    public void shouldGetColumnName() {
        assertEquals("A", Util.getColumnName(1));
        assertEquals("B", Util.getColumnName(2));
        assertEquals("AA", Util.getColumnName(27));
        assertEquals("XFD", Util.getColumnName(16384));
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldNoticeTooBigColumnIndex() {
        Util.getColumnName(17000);
    }

    @Test
    public void shouldConvertBoundsToRange() {
        assertEquals("B2:E4", Util.boundsToRange(1,1,3,4));
    }
}


text:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
import { mustBe, a } from "zafiro-validators";

@Entity()
export default class User {

    @PrimaryGeneratedColumn()
    @mustBe(a.number().optional())
    public id: number;

    @Column({ unique: true })
    @mustBe(a.string().email().required())
    public email: string;

    @Column()
    @mustBe(a.string().min(3).required())
    public givenName: string;

    @Column()
    @mustBe(a.string().min(3).required())
    public familyName: string;

    @Column()
    @mustBe(a.boolean().required())
    public isBanned: boolean;

}


text:
extern "C" {
#endif

///
// Structure representing a message. Can be used on any process and thread.
///
typedef struct _cef_process_message_t {
  ///
  // Base structure.
  ///
  cef_base_t base;

  ///
  // Returns true (1) if this object is valid. Do not call any other functions
  // if this function returns false (0).
  ///
  int (CEF_CALLBACK *is_valid)(struct _cef_process_message_t* self);

  ///
  // Returns true (1) if the values of this object are read-only. Some APIs may
  // expose read-only objects.
  ///
  int (CEF_CALLBACK *is_read_only)(struct _cef_process_message_t* self);

  ///
  // Returns a writable copy of this object.
  ///
  struct _cef_process_message_t* (CEF_CALLBACK *copy)(
      struct _cef_process_message_t* self);

  ///
  // Returns the message name.
  ///
  // The resulting string must be freed by calling cef_string_userfree_free().
  cef_string_userfree_t (CEF_CALLBACK *get_name)(
      struct _cef_process_message_t* self);

  ///
  // Returns the list of arguments.
  ///
  struct _cef_list_value_t* (CEF_CALLBACK *get_argument_list)(
      struct _cef_process_message_t* self);
} cef_process_message_t;

///
// Create a new cef_process_message_t object with the specified name.
///
CEF_EXPORT cef_process_message_t* cef_process_message_create(
    const cef_string_t* name);

#ifdef __cplusplus
}
#endif

#endif  // CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_


text:
import os

from django.template import loader, TemplateDoesNotExist
try:
    # Django < 1.8
    from django.template.loader import find_template as django_find_template
except ImportError:
    # Django >= 1.8
    from django.template.loader import get_template as django_find_template

from django.conf import settings

SIMPLE_TEMPLATES_AB_PARAM = getattr(settings, 'SIMPLE_TEMPLATES_AB_PARAM', 'ab')
SIMPLE_TEMPLATES_AB_DIR = getattr(settings, 'SIMPLE_TEMPLATES_AB_DIR', 'ab_templates')

def find_template(template):
    try:
        django_find_template(template)
        return template
    except TemplateDoesNotExist:
        return None

def get_ab_template(request, default=None):
    """
    This function simply returns the a/b template path if the ab GET parameter exists, otherwise the contents of `default`.

    The path for the ab template is the concatenation of:
     - the SIMPLE_TEMPLATES_AB_DIR setting,
     - the path to the `default` template and
     - the SIMPLE_TEMPLATES_AB_PARAM value from request.GET
    """
    template_name = request.GET.get(SIMPLE_TEMPLATES_AB_PARAM)
    if template_name:
        if default:
            (filepath, extension) = os.path.splitext(default)
            template_name = os.path.join(SIMPLE_TEMPLATES_AB_DIR, filepath, template_name + extension or '')
        return find_template(template_name) or default
    return default


text:
SmartRoutes.FormValidator = function() {

    var fields = ko.observableArray();

    var formValid = ko.computed(function() {
        var valid = true;
        ko.utils.arrayForEach(fields(), function(validationInfo) {
            valid = valid && validationInfo.valid();
        });
        return valid;
    });

    var fieldTypes = {
        text: 0,
    };

    function ValidateTextField(newValue, regexString) {
        var regex = new RegExp(regexString);
        return regex.test(newValue);
    };

    function ValidateTextFieldCallback(newValue) {
        var valid = ValidateTextField(newValue, this.regex);

        // Update the observable field.
        this.valid(valid);

        if (this.callback && (typeof this.callback === "function")) {
            this.callback(valid, this.element);
        }
    };

    function ForceValidateAllFields() {
        $.each(fields(), function(index, info) {
            info.dataBinding.valueHasMutated();
        });
    };

    return {
        // Public:

        // element - jquery object for the dom element
        // validationCallback - function taking a boolean indicating true if the field
        //                      validated successfully, false otherwise
        // section - an integer identifying the section of the form for this field
        AddTextField: function(dataBinding, validationCallback, regex, element) {
            if (dataBinding && regex) {
                var validationInfo = {
                    fieldType: fieldTypes.text,
                    dataBinding: dataBinding,
                    callback: validationCallback,
                    regex: regex,
                    element: element,
                    valid: ko.observable(false),
                };

                fields.push(validationInfo);

                dataBinding.subscribe(ValidateTextFieldCallback, validationInfo);
            }
        },

        IsFormValid: function() {
            return formValid();
        },

        ClearValidators: function() {
            fields([]);
        },

        ValidateAllFields: function() {
            ForceValidateAllFields();
        },
    };
};


text:
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/medialive/model/AudioOnlyHlsSettings.h>
#include <aws/medialive/model/Fmp4HlsSettings.h>
#include <aws/medialive/model/FrameCaptureHlsSettings.h>
#include <aws/medialive/model/StandardHlsSettings.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace MediaLive
{
namespace Model
{

  /**
   * Hls Settings

See Also:
   AWS
   * API Reference

   */
  class AWS_MEDIALIVE_API HlsSettings
  {
  public:
    HlsSettings();
    HlsSettings(Aws::Utils::Json::JsonView jsonValue);
    HlsSettings& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const AudioOnlyHlsSettings& GetAudioOnlyHlsSettings() const{ return m_audioOnlyHlsSettings; }

    inline bool AudioOnlyHlsSettingsHasBeenSet() const { return m_audioOnlyHlsSettingsHasBeenSet; }

    inline void SetAudioOnlyHlsSettings(const AudioOnlyHlsSettings& value) { m_audioOnlyHlsSettingsHasBeenSet = true; m_audioOnlyHlsSettings = value; }

    inline void SetAudioOnlyHlsSettings(AudioOnlyHlsSettings&& value) { m_audioOnlyHlsSettingsHasBeenSet = true; m_audioOnlyHlsSettings = std::move(value); }

    inline HlsSettings& WithAudioOnlyHlsSettings(const AudioOnlyHlsSettings& value) { SetAudioOnlyHlsSettings(value); return *this;}

    inline HlsSettings& WithAudioOnlyHlsSettings(AudioOnlyHlsSettings&& value) { SetAudioOnlyHlsSettings(std::move(value)); return *this;}

    inline const Fmp4HlsSettings& GetFmp4HlsSettings() const{ return m_fmp4HlsSettings; }

    inline bool Fmp4HlsSettingsHasBeenSet() const { return m_fmp4HlsSettingsHasBeenSet; }

    inline void SetFmp4HlsSettings(const Fmp4HlsSettings& value) { m_fmp4HlsSettingsHasBeenSet = true; m_fmp4HlsSettings = value; }

    inline void SetFmp4HlsSettings(Fmp4HlsSettings&& value) { m_fmp4HlsSettingsHasBeenSet = true; m_fmp4HlsSettings = std::move(value); }

    inline HlsSettings& WithFmp4HlsSettings(const Fmp4HlsSettings& value) { SetFmp4HlsSettings(value); return *this;}

    inline HlsSettings& WithFmp4HlsSettings(Fmp4HlsSettings&& value) { SetFmp4HlsSettings(std::move(value)); return *this;}

    inline const FrameCaptureHlsSettings& GetFrameCaptureHlsSettings() const{ return m_frameCaptureHlsSettings; }

    inline bool FrameCaptureHlsSettingsHasBeenSet() const { return m_frameCaptureHlsSettingsHasBeenSet; }

    inline void SetFrameCaptureHlsSettings(const FrameCaptureHlsSettings& value) { m_frameCaptureHlsSettingsHasBeenSet = true; m_frameCaptureHlsSettings = value; }

    inline void SetFrameCaptureHlsSettings(FrameCaptureHlsSettings&& value) { m_frameCaptureHlsSettingsHasBeenSet = true; m_frameCaptureHlsSettings = std::move(value); }

    inline HlsSettings& WithFrameCaptureHlsSettings(const FrameCaptureHlsSettings& value) { SetFrameCaptureHlsSettings(value); return *this;}

    inline HlsSettings& WithFrameCaptureHlsSettings(FrameCaptureHlsSettings&& value) { SetFrameCaptureHlsSettings(std::move(value)); return *this;}

    inline const StandardHlsSettings& GetStandardHlsSettings() const{ return m_standardHlsSettings; }

    inline bool StandardHlsSettingsHasBeenSet() const { return m_standardHlsSettingsHasBeenSet; }

    inline void SetStandardHlsSettings(const StandardHlsSettings& value) { m_standardHlsSettingsHasBeenSet = true; m_standardHlsSettings = value; }

    inline void SetStandardHlsSettings(StandardHlsSettings&& value) { m_standardHlsSettingsHasBeenSet = true; m_standardHlsSettings = std::move(value); }

    inline HlsSettings& WithStandardHlsSettings(const StandardHlsSettings& value) { SetStandardHlsSettings(value); return *this;}

    inline HlsSettings& WithStandardHlsSettings(StandardHlsSettings&& value) { SetStandardHlsSettings(std::move(value)); return *this;}

  private:

    AudioOnlyHlsSettings m_audioOnlyHlsSettings;
    bool m_audioOnlyHlsSettingsHasBeenSet;

    Fmp4HlsSettings m_fmp4HlsSettings;
    bool m_fmp4HlsSettingsHasBeenSet;

    FrameCaptureHlsSettings m_frameCaptureHlsSettings;
    bool m_frameCaptureHlsSettingsHasBeenSet;

    StandardHlsSettings m_standardHlsSettings;
    bool m_standardHlsSettingsHasBeenSet;
  };

} // namespace Model
} // namespace MediaLive
} // namespace Aws


text:
import subprocess
import sys

import netaddr
from oslo_config import cfg
import six

from rally.common.i18n import _
from rally.common import logging
from rally.common import sshutils
from rally.plugins.openstack.scenarios.cinder import utils as cinder_utils
from rally.plugins.openstack.scenarios.nova import utils as nova_utils
from rally.plugins.openstack.wrappers import network as network_wrapper
from rally.task import atomic
from rally.task import utils
from rally.task import validation

LOG = logging.getLogger(__name__)

VM_BENCHMARK_OPTS = [
    cfg.FloatOpt("vm_ping_poll_interval", default=1.0,
                 help="Interval between checks when waiting for a VM to "
                 "become pingable"),
    cfg.FloatOpt("vm_ping_timeout", default=120.0,
                 help="Time to wait for a VM to become pingable")]

CONF = cfg.CONF
benchmark_group = cfg.OptGroup(name="benchmark", title="benchmark options")
CONF.register_opts(VM_BENCHMARK_OPTS, group=benchmark_group)

class Host(object):

    ICMP_UP_STATUS = "ICMP UP"
    ICMP_DOWN_STATUS = "ICMP DOWN"

    name = "ip"

    def __init__(self, ip):
        self.ip = netaddr.IPAddress(ip)
        self.status = self.ICMP_DOWN_STATUS

    @property
    def id(self):
        return self.ip.format()

    @classmethod
    def update_status(cls, server):
        """Check ip address is pingable and update status."""
        ping = "ping" if server.ip.version == 4 else "ping6"
        if sys.platform.startswith("linux"):
            cmd = [ping, "-c1", "-w1", server.ip.format()]
        else:
            cmd = [ping, "-c1", server.ip.format()]

        proc = subprocess.Popen(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.wait()
        LOG.debug("Host %s is ICMP %s"
                  % (server.ip.format(), proc.returncode and "down" or "up"))
        if proc.returncode == 0:
            server.status = cls.ICMP_UP_STATUS
        else:
            server.status = cls.ICMP_DOWN_STATUS
        return server

    def __eq__(self, other):
        if not isinstance(other, Host):
            raise TypeError("%s should be an instance of %s" % (
                other, Host.__class__.__name__))
        return self.ip == other.ip and self.status == other.status

class VMScenario(nova_utils.NovaScenario, cinder_utils.CinderScenario):
    """Base class for VM scenarios with basic atomic actions.

    VM scenarios are scenarios executed inside some launched VM instance.
    """

    USER_RWX_OTHERS_RX_ACCESS_MODE = 0o755

    RESOURCE_NAME_PREFIX = "rally_vm_"

    @atomic.action_timer("vm.run_command_over_ssh")
    def _run_command_over_ssh(self, ssh, command):
        """Run command inside an instance.

        This is a separate function so that only script execution is timed.

        :param ssh: A SSHClient instance.
        :param command: Dictionary specifying command to execute.
            See `rally info find VMTasks.boot_runcommand_delete' parameter
            `command' docstring for explanation.

        :returns: tuple (exit_status, stdout, stderr)
        """
        validation.check_command_dict(command)

        # NOTE(pboldin): Here we `get' the values and not check for the keys
        # due to template-driven configuration generation that can leave keys
        # defined but values empty.
        if command.get("script_file") or command.get("script_inline"):
            cmd = command["interpreter"]
            if command.get("script_file"):
                stdin = open(command["script_file"], "rb")
            elif command.get("script_inline"):
                stdin = six.moves.StringIO(command["script_inline"])
        elif command.get("remote_path"):
            cmd = command["remote_path"]
            stdin = None

        if command.get("local_path"):
            remote_path = cmd[-1] if isinstance(cmd, (tuple, list)) else cmd
            ssh.put_file(command["local_path"], remote_path,
                         mode=self.USER_RWX_OTHERS_RX_ACCESS_MODE)

        if command.get("command_args"):
            if not isinstance(cmd, (list, tuple)):
                cmd = [cmd]
            # NOTE(pboldin): `ssh.execute' accepts either a string interpreted
            # as a command name or the list of strings that are converted into
            # single-line command with arguments.
            cmd = cmd + list(command["command_args"])

        return ssh.execute(cmd, stdin=stdin)

    def _boot_server_with_fip(self, image, flavor, use_floating_ip=True,
                              floating_network=None, **kwargs):
        """Boot server prepared for SSH actions."""
        kwargs["auto_assign_nic"] = True
        server = self._boot_server(image, flavor, **kwargs)

        if not server.networks:
            raise RuntimeError(
                "Server `%s' is not connected to any network. "
                "Use network context for auto-assigning networks "
                "or provide `nics' argument with specific net-id." %
                server.name)

        if use_floating_ip:
            fip = self._attach_floating_ip(server, floating_network)
        else:
            internal_network = list(server.networks)[0]
            fip = {"ip": server.addresses[internal_network][0]["addr"]}

        return server, {"ip": fip.get("ip"),
                        "id": fip.get("id"),
                        "is_floating": use_floating_ip}

    @atomic.action_timer("vm.attach_floating_ip")
    def _attach_floating_ip(self, server, floating_network):
        internal_network = list(server.networks)[0]
        fixed_ip = server.addresses[internal_network][0]["addr"]

        fip = network_wrapper.wrap(self.clients, self).create_floating_ip(
            ext_network=floating_network,
            tenant_id=server.tenant_id, fixed_ip=fixed_ip)

        self._associate_floating_ip(server, fip["ip"], fixed_address=fixed_ip,
                                    atomic_action=False)

        return fip

    @atomic.action_timer("vm.delete_floating_ip")
    def _delete_floating_ip(self, server, fip):
        with logging.ExceptionLogger(
                LOG, _("Unable to delete IP: %s") % fip["ip"]):
            if self.check_ip_address(fip["ip"])(server):
                self._dissociate_floating_ip(server, fip["ip"],
                                             atomic_action=False)
                network_wrapper.wrap(self.clients, self).delete_floating_ip(
                    fip["id"], wait=True)

    def _delete_server_with_fip(self, server, fip, force_delete=False):
        if fip["is_floating"]:
            self._delete_floating_ip(server, fip)
        return self._delete_server(server, force=force_delete)

    @atomic.action_timer("vm.wait_for_ssh")
    def _wait_for_ssh(self, ssh):
        ssh.wait()

    @atomic.action_timer("vm.wait_for_ping")
    def _wait_for_ping(self, server_ip):
        server = Host(server_ip)
        utils.wait_for_status(
            server,
            ready_statuses=[Host.ICMP_UP_STATUS],
            update_resource=Host.update_status,
            timeout=CONF.benchmark.vm_ping_timeout,
            check_interval=CONF.benchmark.vm_ping_poll_interval
        )

    def _run_command(self, server_ip, port, username, password, command,
                     pkey=None):
        """Run command via SSH on server.

        Create SSH connection for server, wait for server to become available
        (there is a delay between server being set to ACTIVE and sshd being
        available). Then call run_command_over_ssh to actually execute the
        command.

        :param server_ip: server ip address
        :param port: ssh port for SSH connection
        :param username: str. ssh username for server
        :param password: Password for SSH authentication
        :param command: Dictionary specifying command to execute.
            See `rally info find VMTasks.boot_runcommand_delete' parameter
            `command' docstring for explanation.
        :param pkey: key for SSH authentication

        :returns: tuple (exit_status, stdout, stderr)
        """
        pkey = pkey if pkey else self.context["user"]["keypair"]["private"]
        ssh = sshutils.SSH(username, server_ip, port=port,
                           pkey=pkey, password=password)
        self._wait_for_ssh(ssh)
        return self._run_command_over_ssh(ssh, command)


text:
namespace rocksdb {

namespace {
void VerifyInitializationOfCompactionJobStats(
      const CompactionJobStats& compaction_job_stats) {
#if !defined(IOS_CROSS_COMPILE)
  ASSERT_EQ(compaction_job_stats.elapsed_micros, 0U);

  ASSERT_EQ(compaction_job_stats.num_input_records, 0U);
  ASSERT_EQ(compaction_job_stats.num_input_files, 0U);
  ASSERT_EQ(compaction_job_stats.num_input_files_at_output_level, 0U);

  ASSERT_EQ(compaction_job_stats.num_output_records, 0U);
  ASSERT_EQ(compaction_job_stats.num_output_files, 0U);

  ASSERT_EQ(compaction_job_stats.is_manual_compaction, false);

  ASSERT_EQ(compaction_job_stats.total_input_bytes, 0U);
  ASSERT_EQ(compaction_job_stats.total_output_bytes, 0U);

  ASSERT_EQ(compaction_job_stats.total_input_raw_key_bytes, 0U);
  ASSERT_EQ(compaction_job_stats.total_input_raw_value_bytes, 0U);

  ASSERT_EQ(compaction_job_stats.smallest_output_key_prefix[0], 0);
  ASSERT_EQ(compaction_job_stats.largest_output_key_prefix[0], 0);

  ASSERT_EQ(compaction_job_stats.num_records_replaced, 0U);

  ASSERT_EQ(compaction_job_stats.num_input_deletion_records, 0U);
  ASSERT_EQ(compaction_job_stats.num_expired_deletion_records, 0U);

  ASSERT_EQ(compaction_job_stats.num_corrupt_keys, 0U);
#endif  // !defined(IOS_CROSS_COMPILE)
}

}  // namespace

// TODO(icanadi) Make it simpler once we mock out VersionSet
class CompactionJobTest : public testing::Test {
 public:
  CompactionJobTest()
      : env_(Env::Default()),
        dbname_(test::TmpDir() + "/compaction_job_test"),
        mutable_cf_options_(Options(), ImmutableCFOptions(Options())),
        table_cache_(NewLRUCache(50000, 16)),
        write_buffer_(db_options_.db_write_buffer_size),
        versions_(new VersionSet(dbname_, &db_options_, env_options_,
                                 table_cache_.get(), &write_buffer_,
                                 &write_controller_)),
        shutting_down_(false),
        mock_table_factory_(new mock::MockTableFactory()) {
    EXPECT_OK(env_->CreateDirIfMissing(dbname_));
    db_options_.db_paths.emplace_back(dbname_,
                                      std::numeric_limits<uint64_t>::max());
    NewDB();
    std::vector<ColumnFamilyDescriptor> column_families;
    cf_options_.table_factory = mock_table_factory_;
    column_families.emplace_back(kDefaultColumnFamilyName, cf_options_);

    EXPECT_OK(versions_->Recover(column_families, false));
  }

  std::string GenerateFileName(uint64_t file_number) {
    FileMetaData meta;
    std::vector<DbPath> db_paths;
    db_paths.emplace_back(dbname_, std::numeric_limits<uint64_t>::max());
    meta.fd = FileDescriptor(file_number, 0, 0);
    return TableFileName(db_paths, meta.fd.GetNumber(), meta.fd.GetPathId());
  }

  // Corrupts key by changing the type
  void CorruptKey(InternalKey* ikey) {
    std::string keystr = ikey->Encode().ToString();
    keystr[keystr.size() - 8] = kTypeLogData;
    ikey->DecodeFrom(Slice(keystr.data(), keystr.size()));
  }

  // returns expected result after compaction
  mock::MockFileContents CreateTwoFiles(bool gen_corrupted_keys) {
    mock::MockFileContents expected_results;
    const int kKeysPerFile = 10000;
    const int kCorruptKeysPerFile = 200;
    const int kMatchingKeys = kKeysPerFile / 2;
    SequenceNumber sequence_number = 0;

    auto corrupt_id = [&](int id) {
      return gen_corrupted_keys && id > 0 && id <= kCorruptKeysPerFile;
    };

    for (int i = 0; i < 2; ++i) {
      mock::MockFileContents contents;
      SequenceNumber smallest_seqno = 0, largest_seqno = 0;
      InternalKey smallest, largest;
      for (int k = 0; k < kKeysPerFile; ++k) {
        auto key = ToString(i * kMatchingKeys + k);
        auto value = ToString(i * kKeysPerFile + k);
        InternalKey internal_key(key, ++sequence_number, kTypeValue);
        // This is how the key will look like once it's written in bottommost
        // file
        InternalKey bottommost_internal_key(key, 0, kTypeValue);
        if (corrupt_id(k)) {
          CorruptKey(&internal_key);
          CorruptKey(&bottommost_internal_key);
        }
        if (k == 0) {
          smallest = internal_key;
          smallest_seqno = sequence_number;
        } else if (k == kKeysPerFile - 1) {
          largest = internal_key;
          largest_seqno = sequence_number;
        }
        contents.insert({internal_key.Encode().ToString(), value});
        if (i == 1 || k < kMatchingKeys || corrupt_id(k - kMatchingKeys)) {
          expected_results.insert(
              {bottommost_internal_key.Encode().ToString(), value});
        }
      }

      uint64_t file_number = versions_->NewFileNumber();
      EXPECT_OK(mock_table_factory_->CreateMockTable(
          env_, GenerateFileName(file_number), std::move(contents)));

      VersionEdit edit;
      edit.AddFile(0, file_number, 0, 10, smallest, largest, smallest_seqno,
                   largest_seqno, false);

      mutex_.Lock();
      versions_->LogAndApply(versions_->GetColumnFamilySet()->GetDefault(),
                             mutable_cf_options_, &edit, &mutex_);
      mutex_.Unlock();
    }
    versions_->SetLastSequence(sequence_number + 1);
    return expected_results;
  }

  void NewDB() {
    VersionEdit new_db;
    new_db.SetLogNumber(0);
    new_db.SetNextFile(2);
    new_db.SetLastSequence(0);

    const std::string manifest = DescriptorFileName(dbname_, 1);
    unique_ptr<WritableFile> file;
    Status s = env_->NewWritableFile(
        manifest, &file, env_->OptimizeForManifestWrite(env_options_));
    ASSERT_OK(s);
    unique_ptr<WritableFileWriter> file_writer(
        new WritableFileWriter(std::move(file), EnvOptions()));
    {
      log::Writer log(std::move(file_writer));
      std::string record;
      new_db.EncodeTo(&record);
      s = log.AddRecord(record);
    }
    ASSERT_OK(s);
    // Make "CURRENT" file that points to the new manifest file.
    s = SetCurrentFile(env_, dbname_, 1, nullptr);
  }

  void RunCompaction(const std::vector<FileMetaData*>& files) {
    auto cfd = versions_->GetColumnFamilySet()->GetDefault();

    CompactionInputFiles compaction_input_files;
    compaction_input_files.level = 0;
    for (auto file : files) {
      compaction_input_files.files.push_back(file);
    }
    Compaction compaction(cfd->current()->storage_info(),
                          *cfd->GetLatestMutableCFOptions(),
                          {compaction_input_files}, 1, 1024 * 1024, 10, 0,
                          kNoCompression, {});
    compaction.SetInputVersion(cfd->current());

    LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, db_options_.info_log.get());
    mutex_.Lock();
    EventLogger event_logger(db_options_.info_log.get());
    CompactionJob compaction_job(
        0, &compaction, db_options_, env_options_, versions_.get(),
        &shutting_down_, &log_buffer, nullptr, nullptr, nullptr, {},
        table_cache_, &event_logger, false, dbname_, &compaction_job_stats_);

    VerifyInitializationOfCompactionJobStats(compaction_job_stats_);

    compaction_job.Prepare();
    mutex_.Unlock();
    ASSERT_OK(compaction_job.Run());
    mutex_.Lock();
    Status s;
    compaction_job.Install(&s, *cfd->GetLatestMutableCFOptions(), &mutex_);
    ASSERT_OK(s);
    mutex_.Unlock();

    ASSERT_GE(compaction_job_stats_.elapsed_micros, 0U);
    ASSERT_EQ(compaction_job_stats_.num_input_files, files.size());
    ASSERT_EQ(compaction_job_stats_.num_output_files, 1U);
  }

  Env* env_;
  std::string dbname_;
  EnvOptions env_options_;
  MutableCFOptions mutable_cf_options_;
  std::shared_ptr<Cache> table_cache_;
  WriteController write_controller_;
  DBOptions db_options_;
  ColumnFamilyOptions cf_options_;
  WriteBuffer write_buffer_;
  std::unique_ptr<VersionSet> versions_;
  InstrumentedMutex mutex_;
  std::atomic<bool> shutting_down_;
  std::shared_ptr<mock::MockTableFactory> mock_table_factory_;
  CompactionJobStats compaction_job_stats_;
};

TEST_F(CompactionJobTest, Simple) {
  auto expected_results = CreateTwoFiles(false);
  auto cfd = versions_->GetColumnFamilySet()->GetDefault();
  auto files = cfd->current()->storage_info()->LevelFiles(0);
  ASSERT_EQ(2U, files.size());

  RunCompaction(files);
  mock_table_factory_->AssertLatestFile(expected_results);
}

TEST_F(CompactionJobTest, SimpleCorrupted) {
  auto expected_results = CreateTwoFiles(true);
  auto cfd = versions_->GetColumnFamilySet()->GetDefault();
  auto files = cfd->current()->storage_info()->LevelFiles(0);

  RunCompaction(files);
  ASSERT_EQ(compaction_job_stats_.num_corrupt_keys, 400U);
  mock_table_factory_->AssertLatestFile(expected_results);
}

}  // namespace rocksdb

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
package io.github.biezhi.wechat.api.model;

import io.github.biezhi.wechat.api.request.BaseRequest;
import io.github.biezhi.wechat.utils.StringUtils;
import lombok.Data;

import java.io.Serializable;

/**
 * 登录会话
 *
 * @author biezhi
 * @date 2018/1/18
 */
@Data
public class LoginSession implements Serializable {

    private Account account;

    private String userName;
    private String nickName;

    private String      url;
    private String      fileUrl;
    private String      syncUrl;
    private String      deviceId;
    private String      sKey;
    private String      wxSid;
    private String      wxUin;
    private String      passTicket;
    private String      syncKeyStr;
    private Integer     inviteStartCount;
    private BaseRequest baseRequest;
    private SyncKey     syncKey;

    public String getSyncOrUrl() {
        if (StringUtils.isNotEmpty(this.syncUrl)) {
            return this.syncUrl;
        }
        return this.url;
    }

    public String getFileUrl() {
        if (StringUtils.isNotEmpty(this.fileUrl)) {
            return this.fileUrl;
        }
        return this.url;
    }

    public void setSyncKey(SyncKey syncKey) {
        this.syncKey = syncKey;

        StringBuilder syncKeyBuf = new StringBuilder();
        for (KeyItem item : syncKey.getList()) {
            syncKeyBuf.append("|").append(item.getKey()).append("_").append(item.getVal());
        }
        if (syncKeyBuf.length() > 0) {
            this.syncKeyStr = syncKeyBuf.substring(1);
        }
    }

}


text:
package org.hibernate.mapping;

/**
 * Enumeration of the known places from which a piece of metadata may come.
 *
 * @author Steve Ebersole
 */
public enum MetadataSource {
	HBM,
	ANNOTATIONS,
	OTHER
}


text:
<?php

/**
 * This class can be used to cache the result and output of any PHP callable (function and method calls).
 *
 * @package    symfony
 * @subpackage cache
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfFunctionCache
{
  protected $cache = null;

  /**
   * Constructor.
   *
   * @param sfCache $cache An sfCache object instance
   */
  public function __construct(sfCache $cache)
  {
    $this->cache = $cache;
  }

  /**
   * Calls a cacheable function or method (or not if there is already a cache for it).
   *
   * Arguments of this method are read with func_get_args. So it doesn't appear in the function definition.
   *
   * The first argument can be any PHP callable:
   *
   * $cache->call('functionName', array($arg1, $arg2));
   * $cache->call(array($object, 'methodName'), array($arg1, $arg2));
   *
   * @param mixed $callable  A PHP callable
   * @param array $arguments An array of arguments to pass to the callable
   *
   * @return mixed The result of the function/method
   */
  public function call($callable, $arguments = array())
  {
    // Generate a cache id
    $key = $this->computeCacheKey($callable, $arguments);

    $serialized = $this->cache->get($key);
    if ($serialized !== null)
    {
      $data = unserialize($serialized);
    }
    else
    {
      $data = array();

      if (!is_callable($callable))
      {
        throw new sfException('The first argument to call() must be a valid callable.');
      }

      ob_start();
      ob_implicit_flush(false);

      try
      {
        $data['result'] = call_user_func_array($callable, $arguments);
      }
      catch (Exception $e)
      {
        ob_end_clean();
        throw $e;
      }

      $data['output'] = ob_get_clean();

      $this->cache->set($key, serialize($data));
    }

    echo $data['output'];

    return $data['result'];
  }

  /**
   * Returns the cache instance.
   *
   * @return sfCache The sfCache instance
   */
  public function getCache()
  {
    return $this->cache;
  }

  /**
   * Computes the cache key for a given callable and the arguments.
   *
   * @param mixed $callable  A PHP callable
   * @param array $arguments An array of arguments to pass to the callable
   *
   * @return string The associated cache key
   */
  public function computeCacheKey($callable, $arguments = array())
  {
    return md5(serialize($callable).serialize($arguments));
  }
}


text:
class AddUniqueIndexOnPracticeCode < ActiveRecord::Migration[5.0]
  def change
    remove_index :patient_practices, :code
    add_index :patient_practices, :code, unique: true
  end
end


text:
package collins.controllers.actions.resources

import collins.controllers.actions.AssetAction
import collins.controllers.actions.EphemeralDataHolder
import collins.controllers.actions.RequestDataHolder
import collins.controllers.actions.SecureAction
import collins.models.AssetMeta.Enum.ChassisTag
import collins.util.MessageHelperI
import collins.validation.StringUtil

trait IntakeAction extends AssetAction with MessageHelperI {
  this: SecureAction =>

  val assetId: Long

  override val parentKey = "asset.intake.error"

  val Stage1Template = views.html.resources.intake
  val Stage2Template = views.html.resources.intake2
  val Stage3Template = views.html.resources.intake3

  override def validate(): Either[RequestDataHolder,RequestDataHolder] = {
    withValidAsset(assetId) { asset =>
      assetIntakeAllowed(asset) match {
        case None =>
          Right(EphemeralDataHolder())
        case Some(err) =>
          Left(RequestDataHolder.error400(err))
      }
    }
  }

  protected def cleanString(input: String) = StringUtil.trim(input)

  protected def verifyChassisTag(tag: String): Either[RequestDataHolder,String] = cleanString(tag) match {
    case None => Left(RequestDataHolder.error400(chassisInvalidMessage))
    case Some(chassisTag) =>
      definedAsset.getMetaAttribute(ChassisTag.toString, 10) match {
        case Nil =>
          Left(RequestDataHolder.error400(chassisNotFoundMessage))
        case head :: Nil if head.getValue != chassisTag =>
          Left(RequestDataHolder.error400(chassisMismatchMessage(head.getValue, chassisTag)))
        case head :: Nil =>
          Right(chassisTag)
        case head :: tail =>
          Left(RequestDataHolder.error400(chassisMultipleMessage))
      }
  }

  protected def chassisInvalidMessage =
    messageWithDefault("chassisInvalid", "Invalid chassis tag specified")
  protected def chassisMismatchMessage(expectedTag: String, actualTag: String) =
    messageWithDefault("chassisMismatch", "Chassis tags do not match",
      definedAsset.tag, expectedTag, actualTag)
  protected def chassisMultipleMessage =
    messageWithDefault("chassisMultiple", "Asset has multiple chassis tags", definedAsset.tag)
  protected def chassisNotFoundMessage =
    messageWithDefault("chassisNotFound", "No chassis tag found for asset", definedAsset.tag)
}


text:
using Xunit;

namespace System.Reflection.Tests
{
    public class ModuleTests
    {
        // This applies on all platforms. See System.Reflection.TypeExtensions.CoreCLR.Tests for more
        // test cases that rely on platform-specific capabilities.
        [Fact]
        public void GetModuleVersionId_HasModuleVersionId_BehaveConsistently()
        {
            Module module = typeof(ModuleTests).GetTypeInfo().Assembly.ManifestModule;

            if (module.HasModuleVersionId())
            {
                Assert.NotEqual(Guid.Empty, module.GetModuleVersionId());
            }
            else
            {
                Assert.Throws<InvalidOperationException>(() => module.GetModuleVersionId());
            }
        }
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/dontalign_3.dir/dontalign.cpp.o"
  "dontalign_3.pdb"
  "dontalign_3"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/dontalign_3.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
package com.yahoo.dba.perf.myperf.process;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Logger;

import com.yahoo.dba.perf.myperf.common.DBGroupInfo;
import com.yahoo.dba.perf.myperf.common.DBInstanceInfo;
import com.yahoo.dba.perf.myperf.common.MetricsGroup;
import com.yahoo.dba.perf.myperf.common.MyPerfContext;
import com.yahoo.dba.perf.myperf.common.UserDefinedMetrics;
import com.yahoo.dba.perf.myperf.metrics.MetricsDbBase;

/**
 * Handle metrics retention
 * @author xrao
 *
 */
public class MetricsRetentionTask implements Runnable{

  private static Logger logger = Logger.getLogger(MetricsRetentionTask.class.getName());

  private int renentionDays;
  private MyPerfContext context;

  private int[] dbidToPurge = null; //set as one time job, reuse code

  /**
   *
   * @param context
   * @param metricsDB
   * @param renentionDays will be ignored if dbidToPurge is set
   * @param dbidToPurge use to start a one time job to purge data for a specific db, set to -1 otherwise
   */
  public MetricsRetentionTask(MyPerfContext context,
		  int renentionDays,
		  int[] dbidToPurge)
  {
    this.renentionDays = renentionDays;
    this.context = context;
    this.dbidToPurge = dbidToPurge;
  }

  @Override
  public void run()
  {
	Thread.currentThread().setName("MetricsRetentionTask");
	logger.info("Starting metrics purge job");

	if(this.context.getMetricDb() == null)
	{
		logger.info("MetricsDB has yet to set.");
		return;
	}
	//get all dbids
    List<Integer> ids = new ArrayList<Integer>();
    if(this.dbidToPurge == null)
    {
      for(Map.Entry<String, DBGroupInfo> e: context.getDbInfoManager().getClusters().entrySet())
      {
        DBGroupInfo g = e.getValue();
        for(DBInstanceInfo i: g.getInstances())
        {
          ids.add(i.getDbid());
       }
      }
    }else
    {
      for(int id : this.dbidToPurge)
    	ids.add(id);
    }
    Calendar c = Calendar.getInstance();
	c.add(Calendar.DATE, -this.renentionDays);
	Date dt = c.getTime();

    //now get current timestamp
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
	sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    long endDate = Long.parseLong(sdf.format(dt));
    List<MetricsGroup> mgs = new ArrayList<MetricsGroup>();

    String [] groupNames = this.context.getMetricsDef().getGroupNames();
    for(String grpName: groupNames)
    {
      MetricsGroup group = this.context.getMetricsDef().getGroupByName(grpName);
      if(group == null)continue; //not supposed to be so
      if (group.getSubGroups().size() == 0) //no sub group, add self
      {
    	    mgs.add(group);
	  }else
      {
    	  for(MetricsGroup g: group.getSubGroups())
    		  mgs.add(g);
      }
    }

    for(Map.Entry<String, UserDefinedMetrics> entry: this.context.getMetricsDef().getUdmManager().getUdms().entrySet())
    {
      MetricsGroup group = entry.getValue().getMetricsGroup();
      if(group == null)continue; //not supposed to be so
      mgs.add(group);
    }

    for(int dbid: ids)
    {
      logger.info("Check and purge db: "+dbid);
      for(MetricsGroup g: mgs)
      {
    	if(this.dbidToPurge != null )
    	  this.context.getMetricDb().purgeAll(g.getSinkTableName(), dbid);
    	else
    	  this.context.getMetricDb().purge(g.getSinkTableName(), dbid, endDate);
      }
    }
    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("yyyyMMdd");
	sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    purgeAlertReports(Integer.parseInt(sdf2.format(dt)));
	logger.info("Ended metrics purge job");

	if(this.dbidToPurge == null)
		this.context.getMetricDb().purgeAlerts(endDate);

	//for now, we only do it once a day.
	//TODO keep consistency with DB add/update/delete
	logger.info("Retention job done.");
  }

  /**
   *
   * @param lastPurgeDate The last date the report will be purged, in YYYYMMDD format
   */
  private void purgeAlertReports(int lastPurgeDate)
  {
	  try
	  {
	    //also remove old alert reports
	    //report root
		File rootPath = this.context.getAlertRootPath();
		if(!rootPath.exists() && !rootPath.isDirectory())
		{
			logger.warning("Failed to find alert root path: "+rootPath.getPath());
			return;
		}
		logger.warning("Start to purge alert reports: "+rootPath.getPath()+", before "+lastPurgeDate);

		File[] dirByDates = rootPath.listFiles();
		for(File dir: dirByDates)
		{
			String name = dir.getName();
			logger.info("Trying to delete report for date: "+name);
			if(name.indexOf(".")>0)
				name = name.substring(0, name.indexOf("."));
			try
			{
				int nameDate = Integer.parseInt(name);
				if(nameDate<lastPurgeDate)
				{
					if(dir.isDirectory())
					{
						for(File ar: dir.listFiles())
						{
							//don't expect subdir
							if(ar.isFile())
								ar.delete();
						}
					}
					dir.delete();
				}
			}catch(Exception ex)
			{
				logger.warning("Failed to delete report for date: "+name);
			}
		}
	  }catch(Throwable th)
	  {
		  logger.warning("Failed to purge report data: "+th.getMessage());
	  }
  }
}


text:
package org.jboss.pnc.rest.endpoint;

import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.User;
import org.jboss.pnc.rest.configuration.BuildConfigurationSupportedGenericParameters;
import org.jboss.pnc.rest.provider.BuildConfigurationProvider;
import org.jboss.pnc.rest.restmodel.BuildConfigurationRest;
import org.jboss.pnc.rest.restmodel.response.Singleton;
import org.jboss.pnc.rest.utils.EndpointAuthenticationProvider;
import org.jboss.pnc.rest.validation.exceptions.InvalidEntityException;
import org.jboss.pnc.enums.RebuildMode;
import org.jboss.pnc.spi.datastore.Datastore;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationRepository;
import org.jboss.pnc.spi.exception.BuildConflictException;
import org.jboss.pnc.spi.exception.CoreException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import javax.ws.rs.core.Response;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.jboss.pnc.common.util.RandomUtils.randInt;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 *
 * @author Jakub Bartecek <jbartece@redhat.com>
 *
 */
public class BuildConfigurationEndpointTest {

    private static final int CURRENT_USER = randInt(1000, 100000);

    private static final String CUSTOM_PME_PARAMETERS = "CUSTOM_PME_PARAMETERS";

    @Mock
    private BuildConfigurationRepository buildConfigurationRepository;

    @Mock
    private Datastore datastore;

    @Mock
    private EndpointAuthenticationProvider authProvider;

    @Spy
    private BuildConfigurationSupportedGenericParameters supportedGenericParameters;

    @InjectMocks
    private BuildConfigurationProvider bcProvider = new BuildConfigurationProvider();

    private BuildConfigurationEndpoint bcEndpoint;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        bcEndpoint = new BuildConfigurationEndpoint(
                bcProvider,
                null,
                null,
                null,
                null,
                authProvider,
                supportedGenericParameters);

        User user = mock(User.class);
        when(user.getId()).thenReturn(CURRENT_USER);
        when(authProvider.getCurrentUser(any())).thenReturn(user);
    }

    @Test
    public void testGetBCWithGenericParameters() {
        // given
        final String KEY = "KEY";
        final String VALUE = "VALUE";

        Map<String, String> genericParams = new HashMap<>();
        genericParams.put(KEY, VALUE);
        BuildConfiguration bcGiven = BuildConfiguration.Builder.newBuilder()
                .id(1)
                .genericParameters(genericParams)
                .build();
        when(buildConfigurationRepository.queryById(1)).thenReturn(bcGiven);

        // when
        Response response = bcEndpoint.getSpecific(1);

        // then
        assertThat(response.getStatus()).isEqualTo(200);
        @SuppressWarnings("unchecked")
        BuildConfigurationRest bcRest = ((Singleton<BuildConfigurationRest>) response.getEntity()).getContent();

        Map<String, String> supportedParameters = bcRest.getGenericParameters();
        assertThat(supportedParameters).containsKey(KEY);
        assertThat(supportedParameters.get(KEY)).startsWith(VALUE);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testGetPMEGenericParameterWithDescription() {
        // when
        Response response = bcEndpoint.getSupportedGenericParameters();

        // then
        assertThat(response.getStatus()).isEqualTo(200);

        Map<String, String> supportedParameters = (Map<String, String>) bcEndpoint.getSupportedGenericParameters()
                .getEntity();

        assertThat(supportedParameters).containsKey(CUSTOM_PME_PARAMETERS);
        assertThat(supportedParameters.get(CUSTOM_PME_PARAMETERS)).startsWith("Additional");
    }

    @Test(expected = InvalidEntityException.class)
    public void invalidBuildOptionsRejectedTest()
            throws InvalidEntityException, MalformedURLException, CoreException, BuildConflictException {
        // when
        bcEndpoint.trigger(1, null, false, false, false, false, true, null, null);
    }

}


text:
.dojoxGridRtl .dojoxGridFBarStatus {
	margin-left: 0;
	margin-right: 9px;
	float: right;
}
.dojoxGridRtl .dojoxGridFBarClearFilterBtn {
	margin-left: 0;
	margin-right: 10px;
	float: right;
}
.dojoxGridRtl .dojoxGridFBarCloseBtn {
	margin: 0 0 0 4px;
	float: left;
}
.dj_ie .dojoxGridRtl .dojoxGridFBarCloseBtn {
	left: 2px;
	right: auto;
}
.dijitRtl .dojoxGridFDPaneRelation {
	margin: 0 4px 3px 0;
}
.dijitRtl .dojoxGridFDPane .dijitAccordionTitleFocus {
	margin-right: 0;
	margin-left: 14px;
}
.dijitRtl .dojoxGridFDPane .dijitAccordionTitle .dijitButton {
	left: 3px;
	right: auto;
}
.dj_ie6 .dijitRtl .dojoxGridFDPane .dijitAccordionTitle .dijitButton{
	left: -290px;
}
.dijitRtl .dojoxGridFDPaneBtns {
	left: 0;
	right: auto;
}
.dijitRtl .dojoxGridFDPaneBtns .dijitButton,
.dijitRtl .dojoxGridClearFilterBtns .dijitButton,
.dijitRtl .dojoxGridFCBoxEndValue {
	float: left;
}
.dijitRtl .dojoxGridFCBoxRangeValueTxt {
	margin-left: 0;
	margin-right: 4px;
}
.dijitRtl .dojoxGridFStatusTipTitle {
	margin-left: 1em;
	margin-right: 0;
}
.dijitRtl .dojoxGridFStatusTipHandle {
	padding-left: 16px;
	padding-right: 0;
}
.dijitRtl .dojoxGridFStatusTipDetail .dijitButton {
	left: 0;
	right: auto;
}
.dijitRtl .dojoxGridTrueBox,
.dijitRtl .dojoxGridFalseBox {
	float: right;
}
.claro .dojoxGridRtl .dojoxGridFBar {
	border-right: 1px solid white;
}
.claro .dijitRtl .dojoxGridFStatusTip th div {
	border-left: 1px solid #BCBCBC;
	border-right: 1px solid white;
}
.claro .dijitRtl .dojoxGridFStatusTip th.lastColumn div {
	border-left: 1px solid #BCBCBC;
}


text:
package package sihwan.test.sub1

// thanks linux
public class Sub1 {
	public Sub1() {
		// power of git
		System.out.println("This is sub1");
		// edit
		String edit = "Edit line"; // fix by linux
		// thanks linux
		//add source
		// add 1
		// add 2
	}
}


text:
package com.oficina.saude.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.oficina.saude.model.Farmaceutico;

public interface Farmaceuticos extends JpaRepository<Farmaceutico, Long> {

}


text:
package com.google.common.reflect;

import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;

import junit.framework.TestCase;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;

/**
 * Unit tests of {@link Element}.
 *
 * @author Ben Yu
 */
public class ElementTest extends TestCase {

  public void testPrivateField() throws Exception {
    Element element = A.field("privateField");
    assertTrue(element.isPrivate());
    assertFalse(element.isAbstract());
    assertFalse(element.isPackagePrivate());
    assertFalse(element.isProtected());
    assertFalse(element.isPublic());
    assertFalse(element.isFinal());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testPackagePrivateField() throws Exception {
    Element element = A.field("packagePrivateField");
    assertFalse(element.isPrivate());
    assertTrue(element.isPackagePrivate());
    assertFalse(element.isProtected());
    assertFalse(element.isPublic());
    assertFalse(element.isFinal());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testProtectedField() throws Exception {
    Element element = A.field("protectedField");
    assertFalse(element.isPrivate());
    assertFalse(element.isPackagePrivate());
    assertTrue(element.isProtected());
    assertFalse(element.isPublic());
    assertFalse(element.isFinal());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testPublicField() throws Exception {
    Element element = A.field("publicField");
    assertFalse(element.isPrivate());
    assertFalse(element.isPackagePrivate());
    assertFalse(element.isProtected());
    assertTrue(element.isPublic());
    assertFalse(element.isFinal());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testFinalField() throws Exception {
    Element element = A.field("finalField");
    assertTrue(element.isFinal());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testStaticField() throws Exception {
    Element element = A.field("staticField");
    assertTrue(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testVolatileField() throws Exception {
    Element element = A.field("volatileField");
    assertTrue(element.isVolatile());
  }

  public void testTransientField() throws Exception {
    Element element = A.field("transientField");
    assertTrue(element.isTransient());
  }

  public void testConstructor() throws Exception {
    Element element = A.constructor();
    assertTrue(element.isPublic());
    assertFalse(element.isPackagePrivate());
    assertFalse(element.isAbstract());
    assertFalse(element.isStatic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testAbstractMethod() throws Exception {
    Element element = A.method("abstractMethod");
    assertTrue(element.isPackagePrivate());
    assertTrue(element.isAbstract());
    assertFalse(element.isFinal());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testOverridableMethod() throws Exception {
    Element element = A.method("overridableMethod");
    assertTrue(element.isPackagePrivate());
    assertFalse(element.isAbstract());
    assertFalse(element.isFinal());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testPrivateMethod() throws Exception {
    Element element = A.method("privateMethod");
    assertFalse(element.isAbstract());
    assertTrue(element.isPrivate());
    assertFalse(element.isPackagePrivate());
    assertFalse(element.isPublic());
    assertFalse(element.isProtected());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testProtectedMethod() throws Exception {
    Element element = A.method("protectedMethod");
    assertFalse(element.isAbstract());
    assertFalse(element.isPrivate());
    assertFalse(element.isPackagePrivate());
    assertFalse(element.isFinal());
    assertFalse(element.isPublic());
    assertTrue(element.isProtected());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testFinalMethod() throws Exception {
    Element element = A.method("publicFinalMethod");
    assertFalse(element.isAbstract());
    assertFalse(element.isPrivate());
    assertTrue(element.isFinal());
    assertTrue(element.isPublic());
    assertTrue(element.isAnnotationPresent(Tested.class));
  }

  public void testNativeMethod() throws Exception {
    Element element = A.method("nativeMethod");
    assertTrue(element.isNative());
    assertTrue(element.isPackagePrivate());
  }

  public void testSynchronizedMethod() throws Exception {
    Element element = A.method("synchronizedMethod");
    assertTrue(element.isSynchronized());
  }

  public void testUnannotatedMethod() throws Exception {
    Element element = A.method("notAnnotatedMethod");
    assertFalse(element.isAnnotationPresent(Tested.class));
  }

  public void testEquals() throws Exception {
    new EqualsTester()
        .addEqualityGroup(A.field("privateField"), A.field("privateField"))
        .addEqualityGroup(A.field("publicField"))
        .addEqualityGroup(A.constructor(), A.constructor())
        .addEqualityGroup(A.method("privateMethod"), A.method("privateMethod"))
        .addEqualityGroup(A.method("publicFinalMethod"))
        .testEquals();
  }

  public void testNulls() {
    new NullPointerTester()
        .testAllPublicStaticMethods(Element.class);
  }

  @Retention(RetentionPolicy.RUNTIME)
  private @interface Tested {}

  private static abstract class A {
    @Tested private boolean privateField;
    @Tested int packagePrivateField;
    @Tested protected int protectedField;
    @Tested public String publicField;
    @Tested private static Iterable<String> staticField;
    @Tested private final Object finalField;
    private volatile char volatileField;
    private transient long transientField;

    @Tested public A(Object finalField) {
      this.finalField = finalField;
    }

    @Tested abstract void abstractMethod();

    @Tested void overridableMethod() {}

    @Tested protected void protectedMethod() {}

    @Tested private void privateMethod() {}

    @Tested public final void publicFinalMethod() {}

    void notAnnotatedMethod() {}

    static Element field(String name) throws Exception {
      Element element = new Element(A.class.getDeclaredField(name));
      assertEquals(name, element.getName());
      assertEquals(A.class, element.getDeclaringClass());
      return element;
    }

    static Element constructor() throws Exception {
      Constructor<?> constructor = A.class.getDeclaredConstructor(Object.class);
      Element element = new Element(constructor);
      assertEquals(constructor.getName(), element.getName());
      assertEquals(A.class, element.getDeclaringClass());
      return element;
    }

    static Element method(String name, Class<?>... parameterTypes) throws Exception {
      Element element = new Element(A.class.getDeclaredMethod(name, parameterTypes));
      assertEquals(name, element.getName());
      assertEquals(A.class, element.getDeclaringClass());
      return element;
    }

    native void nativeMethod();

    synchronized void synchronizedMethod() {}
  }
}


text:
var li = document.createElement("li");
var bt = document.createElement("button");
var ul = document.getElementsByTagName('ul')[0];

li.innerText=bt;
bt.innerText= 'Developer';
ul.appendChild(bt);


text:
<!---
  category: MapsAndLocation
  samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=619977&clcid=0x409
--->

# MapControl sample

This sample demonstrates how to use the universal map control ([MapControl]( https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.controls.maps.mapcontrol.aspx)) in a UWP app.

* MapControl Basics: adjusting the ZoomLevel, Heading, DesiredPtich, and map stype
* Adding points of interest on the map: PushPins, images, and shapes
* Adding XAML overlays on the map
* Showing 3D locations in MapControl
* Showing Streetside experience within MapControl
* Launching Maps using URI Schemes

This sample is written in XAML and C#.

## For more info

[How to display maps in the Map control](https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn642089.aspx)

[How to display pushpins, shapes, and controls on a map](https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn792121.aspx)

[MapControl API reference]( https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.controls.maps.mapcontrol.aspx)

[URI scheme for Windows Maps app]( https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj635237.aspx)

## Operating system requirements

**Client:** Windows 10

## Build the sample

1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio 2015 and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio 2015 Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.

## Run the sample

To debug the app and then run it, press F5 or use **Debug** \> **Start Debugging**. To run the app without debugging, press Ctrl+F5 or use **Debug** \> **Start Without Debugging**.


text:
.. Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.

   This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0
   International License (the "License"). You may not use this file except in compliance with the
   License. A copy of the License is located at http://creativecommons.org/licenses/by-nc-sa/4.0/.

   This file 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.

.. _aws-boto3-secrets-manager:

###################
AWS Secrets Manager
###################

This Python example shows you how to retrieve the decrypted secret value from an AWS Secrets Manager secret. The secret could be created using either the Secrets Manager console or the CLI/SDK.

The code uses the AWS SDK for Python to retrieve a decrypted secret value.

For more information about using an Amazon Secrets Manager, see
`Tutorial: Storing and Retrieving a Secret <https://docs.aws.amazon.com/secretsmanager/latest/userguide/tutorials_basic.html>`_
in the *AWS Secrets Manager Developer Guide*.

All the example code for the Amazon Web Services (AWS) SDK for Python is available `here on GitHub <https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/python/example_code>`_.

Prerequisite tasks
==================

To set up and run this example, you must first set up the following:

* Configure your AWS credentials, as described in :doc:`quickstart`.
* Create a secret with the AWS Secrets Manager, as described in the `AWS Secrets Manager Developer Guide <https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html>`_

Retrieve the secret value
=============================================

The following example shows how to:

* Retrieve a secret value using
  `get_secret_value <https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager.html#SecretsManager.Client.get_secret_value>`_.

Example
-------

.. code-block:: python

    import boto3
    from botocore.exceptions import ClientError

    def get_secret():
        secret_name = "MySecretName"
        region_name = "us-west-2"

        session = boto3.session.Session()
        client = session.client(
            service_name='secretsmanager',
            region_name=region_name,
        )

        try:
            get_secret_value_response = client.get_secret_value(
                SecretId=secret_name
            )
        except ClientError as e:
            if e.response['Error']['Code'] == 'ResourceNotFoundException':
                print("The requested secret " + secret_name + " was not found")
            elif e.response['Error']['Code'] == 'InvalidRequestException':
                print("The request was invalid due to:", e)
            elif e.response['Error']['Code'] == 'InvalidParameterException':
                print("The request had invalid params:", e)
            elif e.response['Error']['Code'] == 'DecryptionFailure':
                print("The requested secret can't be decrypted using the provided KMS key:", e)
            elif e.response['Error']['Code'] == 'InternalServiceError':
                print("An error occurred on service side:", e)
        else:
            # Secrets Manager decrypts the secret value using the associated KMS CMK
            # Depending on whether the secret was a string or binary, only one of these fields will be populated
            if 'SecretString' in get_secret_value_response:
                text_secret_data = get_secret_value_response['SecretString']
            else:
                binary_secret_data = get_secret_value_response['SecretBinary']

            # Your code goes here.


text:
package io.enmasse.systemtest.selenium.resources;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

public class ConnectionWebItem extends WebItem implements Comparable<ConnectionWebItem> {
    private WebElement checkBox;
    private String host;
    private WebElement hostRoute;
    private String containerId;
    private String protocol;
    private String timeCreated;
    private double messagesIn;
    private double messagesOut;
    private int senders;
    private int receivers;

    public ConnectionWebItem(WebElement item) {
        this.webItem = item;
        this.checkBox = webItem.findElement(By.xpath("./td[@data-key='0']")).findElement(By.tagName("input"));
        this.host = parseName(webItem.findElement(By.xpath("./td[@data-label='Hostname']")));
        this.hostRoute = webItem.findElement(By.xpath("./td[@data-label='Hostname']"));
        this.containerId = webItem.findElement(By.xpath("./td[@data-label='Container ID']")).getText();
        this.protocol = webItem.findElement(By.xpath("./td[@data-label='Protocol']")).getText().split(" ")[0];
        this.timeCreated = webItem.findElement(By.xpath("./td[@data-label='Time created']")).getText();
        this.messagesIn = defaultDouble(webItem.findElement(By.xpath("./td[@data-label='Message In']")).getText());

        // messagesOut won't be present for brokered address spaces.
        By messsageOutXpath = By.xpath("./td[@data-label='Message Out']");
        if (!webItem.findElements(messsageOutXpath).isEmpty()) {
            this.messagesOut = defaultDouble(webItem.findElement(messsageOutXpath).getText());
        }
        this.senders = defaultInt(webItem.findElement(By.xpath("./td[@data-label='Senders']")).getText());
        this.receivers = defaultInt(webItem.findElement(By.xpath("./td[@data-label='Receivers']")).getText());
    }

    public String getHost() {
        return host;
    }

    public String getContainerId() {
        return containerId;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getTimeCreated() {
        return timeCreated;
    }

    public double getMessagesIn() {
        return messagesIn;
    }

    public double getMessagesOut() {
        return messagesOut;
    }

    public int getSenders() {
        return senders;
    }

    public int getReceivers() {
        return receivers;
    }

    public WebElement getHostRoute() { return hostRoute; }

    public WebElement getCheckBox() {
        return checkBox;
    }

    private String parseName(WebElement elem) {
        try {
            return elem.findElement(By.tagName("a")).getText();
        } catch (Exception ex) {
            return elem.findElements(By.tagName("p")).get(0).getText();
        }
    }

    @Override
    public String toString() {
        return String.format("host: %s, containerId: %s, messagesIn: %f, messagesOut: %f, senders: %d, receivers: %d",
                this.host,
                this.containerId,
                this.messagesIn,
                this.messagesOut,
                this.senders,
                this.receivers);
    }

    @Override
    public int compareTo(ConnectionWebItem o) {
        return host.compareTo(o.host);
    }

}


text:
<%= titulo %>

    <% if ( botonMenu ) {%>

            Menu

    <%}%>

        <% if (usuario) { %>

                <%= usuario.get('usuario') %>

                <%= usuario.get('email') %>

                Destacamento

                <%= usuario.get('destacamento').destacamento %>

                Ultima sincronización: <%= fechaUltimaSincronizacion %>

               Cerrar sesión

        <% } else { %>

                Login

        <% } %>

            Sincronizar Datos

            Actualizar app

        <% if (isAdmin) { %>

            Opciones administrativas:

                Configuracion

                Almacenamiento local

                Borrar almacenamiento local

        <% }%>

version <%= version %>


text:
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.lieve.online.portal.dao.UserDao">
    <resultMap type="com.lieve.online.portal.entity.User" id="usermap">
        <id column="id" property="id"/>
        <result column="name" property="username"/>
        <result column="age" property="age"/>
    </resultMap>

    <resultMap id="resultUserArticleList" type="com.lieve.online.portal.entity.Article">
        <id column="id" property="id" />
        <result column="title" property="title"/>
        <result column="content" property="content"/>

        <association property="user" javaType="com.lieve.online.portal.entity.User">
            <id column="id" property="id"/>
            <result column="name" property="username"/>
            <result column="age" property="age"/>
        </association>
    </resultMap>

    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.lieve.online.portal.entity.User">
        insert into User(id, name, age)
        values(#{id}, #{username}, #{age})
    </insert>
    <delete id="deleteUser" >
        delete from user where id = #{id}
    </delete>
    <update id="updateUser" parameterType="com.lieve.online.portal.entity.User">
        update user set name = #{username},
        age = #{age} where id = #{id}
    </update>
    <select id="selectUser"  resultMap="usermap">
        select * from user where id = #{id}
    </select>
    <select id="selectUsers" parameterType="String" resultMap="usermap">
        select * from user where name like #{username}
    </select>

    <select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
        select user.id, user.name, user.age, article.id aid, article.title, article.content
        from user, article
        where user.id = article.userid and user.id = #{id};
    </select>

</mapper>


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// AlertmanagerConfig alertmanager config
//
// swagger:model alertmanagerConfig
type AlertmanagerConfig struct {

	// original
	// Required: true
	Original *string `json:"original"`
}

// Validate validates this alertmanager config
func (m *AlertmanagerConfig) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateOriginal(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *AlertmanagerConfig) validateOriginal(formats strfmt.Registry) error {

	if err := validate.Required("original", "body", m.Original); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *AlertmanagerConfig) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *AlertmanagerConfig) UnmarshalBinary(b []byte) error {
	var res AlertmanagerConfig
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
USE [ANTERO]
GO
IF NOT EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_tieteenala' AND COLUMN_NAME='jarjestys_paatieteenala_koodi')

BEGIN
	ALTER TABLE dw.d_tieteenala ADD jarjestys_paatieteenala_koodi AS case when paatieteenala_koodi = -1 then '99999' else cast(paatieteenala_koodi as varchar(10)) END
END


text:
package com.ilivoo.my.utility;

public final class ExceptionUtils {

}


text:
module VirtualMonkey
  module Command

# monkey destroy --tag unique_tag
    def self.destroy
      @@options = Trollop::options do
        text @@available_commands[:destroy]
        eval(VirtualMonkey::Command::use_options(:config_file, :only, :keep, :prefix, :yes))
      end

      raise "--config_file is required" unless @@options[:config_file]
      load_config_file
      @@dm = DeploymentMonk.new(@@options[:prefix])
      select_only_logic("Really destroy")
      destroy_all_logic
    end

  end
end


text: Android app to monitor analogue gauges and report their values


text:
package org.apache.dubbo.event;

import java.util.concurrent.ForkJoinPool;

/**
 * Parallel {@link EventDispatcher} implementation uses {@link ForkJoinPool#commonPool() JDK common thread pool}
 *
 * @see ForkJoinPool#commonPool()
 * @since 2.7.5
 */
public class ParallelEventDispatcher extends AbstractEventDispatcher {

    public ParallelEventDispatcher() {
        super(ForkJoinPool.commonPool());
    }
}


text:
/**
 * \file RaspiCommonSettings.c
 *
 * Description
 *
 * Handles general settings applicable to all the camera applications
 */

#ifndef RASPIGENERALSETTINGS_H_
#define RASPIGENERALSETTINGS_H_

#include "interface/mmal/mmal_parameters_camera.h"

typedef struct
{
   char camera_name[MMAL_PARAMETER_CAMERA_INFO_MAX_STR_LEN]; // Name of the camera sensor
   int width;                          /// Requested width of image
   int height;                         /// requested height of image
   char *filename;                     /// filename of output file
   int cameraNum;                      /// Camera number
   int sensor_mode;                    /// Sensor mode. 0=auto. Check docs/forum for modes selected by other values.
   int verbose;                        /// !0 if want detailed run information
   int gps;                            /// Add real-time gpsd output to output

} RASPICOMMONSETTINGS_PARAMETERS;

void raspicommonsettings_set_defaults(RASPICOMMONSETTINGS_PARAMETERS *);
void raspicommonsettings_dump_parameters(RASPICOMMONSETTINGS_PARAMETERS *);
void raspicommonsettings_display_help();
int raspicommonsettings_parse_cmdline(RASPICOMMONSETTINGS_PARAMETERS *state, const char *arg1, const char *arg2, void (*app_help)(char*));

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
 <!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/html; charset=utf-8"/>
<title>Tests basic mouse event handlers</title>

SVG Image
Reference Image

<object data="svggen/script-handle-03-b-2.svg" width="480" height="360" type="image/svg+xml"/>

If the test passes, all the markers should have turned to green
				after the events have been triggered on the target. If any event
				has not triggered, its marker will remain red.


text:
require 'spec_helper'

describe Algebra::Projection do
  context 'remove attributes in predicate' do
    subject { restriction.project([:name]) }

    let(:left)        { Relation.new([[:id, Integer]], (0..11).map { |n| [n] })                            }
    let(:right)       { Relation.new([[:name, String]], [['Dan Kubb'], ['John Doe'], ['Jane Doe']])        }
    let(:relation)    { left * right                                                                       }
    let(:restriction) { relation.restrict { |r| r.id.gte(1).and(r.id.lte(10)).and(r.name.eq('Dan Kubb')) } }

    it 'returns a relation with a single tuple' do
      should == [['Dan Kubb']]
    end
  end
end


text:
import { visit } from '@ember/test-helpers';
import { module, test } from 'qunit';

import { setupApplicationTest } from 'cargo/tests/helpers';

module('Route | crate.version | crate links', function (hooks) {
  setupApplicationTest(hooks);

  test('shows all external crate links', async function (assert) {
    let crate = this.server.create('crate', {
      name: 'foo',
      homepage: 'https://crates.io/',
      documentation: 'https://doc.rust-lang.org/cargo/getting-started/',
      repository: 'https://github.com/rust-lang/crates.io.git',
    });
    this.server.create('version', { crate, num: '1.0.0' });

    await visit('/crates/foo');

    assert.dom('[data-test-homepage-link] a').hasText('crates.io').hasAttribute('href', 'https://crates.io/');

    assert
      .dom('[data-test-docs-link] a')
      .hasText('doc.rust-lang.org/cargo/getting-started')
      .hasAttribute('href', 'https://doc.rust-lang.org/cargo/getting-started/');

    assert
      .dom('[data-test-repository-link] a')
      .hasText('github.com/rust-lang/crates.io')
      .hasAttribute('href', 'https://github.com/rust-lang/crates.io.git');
  });

  test('shows no external crate links if none are set', async function (assert) {
    let crate = this.server.create('crate', { name: 'foo' });
    this.server.create('version', { crate, num: '1.0.0' });

    await visit('/crates/foo');

    assert.dom('[data-test-homepage-link]').doesNotExist();
    assert.dom('[data-test-docs-link]').doesNotExist();
    assert.dom('[data-test-repository-link]').doesNotExist();
  });

  test('hide the homepage link if it is the same as the repository', async function (assert) {
    let crate = this.server.create('crate', {
      name: 'foo',
      homepage: 'https://github.com/rust-lang/crates.io',
      repository: 'https://github.com/rust-lang/crates.io',
    });
    this.server.create('version', { crate, num: '1.0.0' });

    await visit('/crates/foo');

    assert.dom('[data-test-homepage-link]').doesNotExist();
    assert.dom('[data-test-docs-link]').doesNotExist();

    assert
      .dom('[data-test-repository-link] a')
      .hasText('github.com/rust-lang/crates.io')
      .hasAttribute('href', 'https://github.com/rust-lang/crates.io');
  });

  test('hide the homepage link if it is the same as the repository plus `.git`', async function (assert) {
    let crate = this.server.create('crate', {
      name: 'foo',
      homepage: 'https://github.com/rust-lang/crates.io/',
      repository: 'https://github.com/rust-lang/crates.io.git',
    });
    this.server.create('version', { crate, num: '1.0.0' });

    await visit('/crates/foo');

    assert.dom('[data-test-homepage-link]').doesNotExist();
    assert.dom('[data-test-docs-link]').doesNotExist();

    assert
      .dom('[data-test-repository-link] a')
      .hasText('github.com/rust-lang/crates.io')
      .hasAttribute('href', 'https://github.com/rust-lang/crates.io.git');
  });
});


text:
# Contributing to Etherjar

If you would like to contribute code you can do so through GitHub by forking the repository and sending pull requests.

## License

By contributing your code, you agree to license your contribution under the terms of the APLv2: http://www.apache.org/licenses/LICENSE-2.0

If you are adding a new file it should have a header like this:

```

 ```


text: export { WatsonHealthStackedMove24 as default } from "../../../";


text:
'use strict';

var chai = require('chai');

// Extend Chai with assertions about promises
//chai.use(require('chai-as-promised'));

// Exports
module.exports = {
    expect: chai.expect,
    should: chai.should()
};


text:
package org.kie.processmigration.it;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.appformer.maven.integration.MavenRepository;
import org.codehaus.plexus.util.StringOutputStream;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.processmigration.model.Execution;
import org.kie.processmigration.model.Migration;
import org.kie.processmigration.model.MigrationDefinition;
import org.kie.processmigration.model.Plan;
import org.kie.processmigration.model.ProcessRef;
import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.api.model.KieContainerResource;
import org.kie.server.api.model.ReleaseId;
import org.kie.server.api.model.definition.ProcessDefinition;
import org.kie.server.api.model.instance.ProcessInstance;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;
import org.kie.server.client.ProcessServicesClient;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

public class ProcessMigrationIntegrationTest {

    private static final String ARTIFACT_ID = "test";
    private static final String GROUP_ID = "com.myspace.test";
    private static final String SOURCE_CONTAINER_ID = "test_1.0.0";
    private static final String TARGET_CONTAINER_ID = "test_2.0.0";
    private static final String PIM_ENDPOINT = System.getProperty("pim.endpoint");
    private static final String PIM_REST_ENDPOINT = System.getProperty("pim.rest.endpoint");

    private static String CONTAINER_ID = "test";
    private static String PROCESS_ID = "test.myprocess";

    private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();

    private HttpClient client;
    private String kieServerId;

    @Before
    public void init() throws IOException {
        KieServicesClient kieClient = createClient();
        kieServerId = kieClient.getServerInfo().getResult().getServerId();
        deployProcesses(kieClient);
        ProcessServicesClient processClient = kieClient.getServicesClient(ProcessServicesClient.class);
        ProcessDefinition definition = processClient.getProcessDefinition(CONTAINER_ID, PROCESS_ID);
        assertNotNull(definition);
        assertEquals(PROCESS_ID, definition.getId());
        client = HttpClientBuilder.create().setDefaultCredentialsProvider(getBasicAuth()).build();
    }

    @Test
    public void testLivenessCheck() throws IOException {
        HttpGet get = new HttpGet(PIM_ENDPOINT + "/health/live");
        assertHealthCheck(client.execute(get));
    }

    @Test
    public void testReadinessCheck() throws IOException {
        HttpGet get = new HttpGet(PIM_ENDPOINT + "/health/ready");
        assertHealthCheck(client.execute(get));
    }

    private void assertHealthCheck(HttpResponse response) throws IOException {
        assertEquals(Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode());
        OutputStream os = new ByteArrayOutputStream();
        InputStream is = response.getEntity().getContent();
        JsonArray checks = Json.createReader(is).readObject().getJsonArray("checks");
        assertEquals(1, checks.size());
        JsonObject serviceCheck = checks.getJsonObject(0);
        assertEquals("service", serviceCheck.getString("name"));
        assertEquals("UP", serviceCheck.getString("status"));
    }

    @Test
    public void testMigration() throws IOException, JAXBException {
        // Given
        startProcesses();

        // When
        createMigration();

        // Then
        ProcessServicesClient processClient = createClient().getServicesClient(ProcessServicesClient.class);
        List<ProcessInstance> instances = processClient.findProcessInstances(SOURCE_CONTAINER_ID, 0, 10);
        assertEquals(1, instances.size());
        assertEquals(Long.valueOf(2L), instances.get(0).getId());

        instances = processClient.findProcessInstances(TARGET_CONTAINER_ID, 0, 10);
        assertEquals(1, instances.size());
        assertEquals(Long.valueOf(1L), instances.get(0).getId());
    }

    private Migration createMigration() throws IOException, JAXBException {
        Plan plan = createPlan();
        MigrationDefinition def = new MigrationDefinition();
        def.setPlanId(plan.getId());
        def.setKieServerId(kieServerId);
        def.setProcessInstanceIds(Arrays.asList(1L));
        def.setExecution(new Execution().setType(Execution.ExecutionType.SYNC));

        HttpPost post = preparePost("/migrations");

        StringWriter writer = new StringWriter();
        mapper.writeValue(writer, def);
        post.setEntity(new StringEntity(writer.toString()));
        HttpResponse r = client.execute(post);
        assertEquals(HttpStatus.SC_OK, r.getStatusLine().getStatusCode());
        StringReader reader = new StringReader(EntityUtils.toString(r.getEntity()));
        Migration migration = mapper.readValue(reader, Migration.class);
        assertNotNull(migration);
        assertEquals("kermit", migration.getDefinition().getRequester());
        return migration;
    }

    private Plan createPlan() throws IOException, JAXBException {
        Plan plan = new Plan();
        plan.setSource(new ProcessRef().setContainerId(SOURCE_CONTAINER_ID).setProcessId(PROCESS_ID));
        plan.setTarget(new ProcessRef().setContainerId(TARGET_CONTAINER_ID).setProcessId(PROCESS_ID));

        HttpPost post = preparePost("/plans");

        StringWriter writer = new StringWriter();
        mapper.writeValue(writer, plan);
        post.setEntity(new StringEntity(writer.toString()));
        HttpResponse r = client.execute(post);
        assertEquals(HttpStatus.SC_OK, r.getStatusLine().getStatusCode());
        StringReader reader = new StringReader(EntityUtils.toString(r.getEntity()));
        return mapper.readValue(reader, Plan.class);
    }

    private HttpPost preparePost(String path) {
        HttpPost post = new HttpPost(PIM_REST_ENDPOINT + path);
        post.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        return post;
    }

    private void startProcesses() {
        ProcessServicesClient client = createClient().getServicesClient(ProcessServicesClient.class);
        client.startProcess(SOURCE_CONTAINER_ID, PROCESS_ID);
        client.startProcess(SOURCE_CONTAINER_ID, PROCESS_ID);
    }

    private void deployProcesses(KieServicesClient kieServicesClient) throws IOException {
        KieServices ks = KieServices.Factory.get();
        MavenRepository repo = MavenRepository.getMavenRepository();
        for (String version : Arrays.asList("1.0.0", "2.0.0")) {
            org.kie.api.builder.ReleaseId builderReleaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, version);
            File kjar = readFile(CONTAINER_ID + "-" + version + ".jar");
            File pom = readFile(CONTAINER_ID + "-" + version + ".pom");
            repo.installArtifact(builderReleaseId, kjar, pom);
            ReleaseId releaseId = new ReleaseId(GROUP_ID, ARTIFACT_ID, version);
            KieContainerResource resource = new KieContainerResource(CONTAINER_ID, releaseId);
            kieServicesClient.createContainer(CONTAINER_ID + "_" + version, resource);
        }
    }

    private File readFile(String resource) throws IOException {
        File tmpFile = new File(resource);
        tmpFile.deleteOnExit();
        try (OutputStream os = new FileOutputStream(tmpFile)) {
            InputStream is = ProcessMigrationIntegrationTest.class.getResource("/kjars/" + resource).openStream();
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            os.write(buffer);
        }
        return tmpFile;
    }

    private KieServicesClient createClient() {
        String kieEndpoint = System.getProperty("kie.server.endpoint");
        String kieUsername = System.getProperty("kie.server.username");
        String kiePassword = System.getProperty("kie.server.password");
        KieServicesConfiguration configuration = KieServicesFactory.newRestConfiguration(kieEndpoint, kieUsername, kiePassword);
        configuration.setTimeout(60000);
        configuration.setMarshallingFormat(MarshallingFormat.JSON);
        return KieServicesFactory.newKieServicesClient(configuration);
    }

    private CredentialsProvider getBasicAuth() {
        String pimUsername = System.getProperty("pim.username");
        String pimPassword = System.getProperty("pim.password");
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(pimUsername, pimPassword));
        return provider;
    }
}


text:
package main

import (
	"sync"

	ct "github.com/flynn/flynn/controller/types"
	"github.com/flynn/flynn/host/volume"
)

type Volume struct {
	ct.Volume

	// stateMtx protects the State field from concurrent access by both
	// the main scheduler loop and the StartJob goroutine which is
	// potentially creating the volume on the host
	stateMtx sync.RWMutex
}

func (v *Volume) GetState() ct.VolumeState {
	v.stateMtx.RLock()
	defer v.stateMtx.RUnlock()
	return v.State
}

func (v *Volume) SetState(state ct.VolumeState) {
	v.stateMtx.Lock()
	defer v.stateMtx.Unlock()
	v.State = state
}

func (v *Volume) Info() *volume.Info {
	return &volume.Info{
		ID:   v.ID,
		Type: v.Type,
		Meta: v.Meta,
	}
}

func (v *Volume) ControllerVolume() *ct.Volume {
	v.stateMtx.Lock()
	defer v.stateMtx.Unlock()
	vol := v.Volume
	return &vol
}

func NewVolume(info *volume.Info, state ct.VolumeState, hostID string) *Volume {
	return &Volume{
		Volume: ct.Volume{
			VolumeReq: ct.VolumeReq{
				Path:         info.Meta["flynn-controller.path"],
				DeleteOnStop: info.Meta["flynn-controller.delete_on_stop"] == "true",
			},
			ID:        info.ID,
			HostID:    hostID,
			Type:      info.Type,
			State:     state,
			AppID:     info.Meta["flynn-controller.app"],
			ReleaseID: info.Meta["flynn-controller.release"],
			JobType:   info.Meta["flynn-controller.type"],
			Meta:      info.Meta,
			CreatedAt: &info.CreatedAt,
		},
	}
}

type VolumeEvent struct {
	Type   VolumeEventType
	Volume *Volume
}

type VolumeEventType string

const (
	VolumeEventTypeCreate     VolumeEventType = "create"
	VolumeEventTypeDestroy    VolumeEventType = "destroy"
	VolumeEventTypeController VolumeEventType = "controller"
)


text:
            <%= MM.util.formatText(forum.name) %>

            <%= MM.util.formatText(forum.intro) %>
            <%= forum.numdiscussions %> <%= MM.lang.s("discussions") %>

        <% if (!discussions || discussions.length == 0) { %>

                <%= MM.lang.s("forumnodiscussionsyet") %>

        <% } else { %>

                <input type="checkbox" name="keepsynch" id="keepsynch" data-cmid="<%= forum.cmid %>" data-forumid="<%= forum.id %>"><%= MM.lang.s("keepsynchronising") %>

        <% _.each(discussions, function(discussion) { %>

                <img class="user-picture" src="<%= MM.util.getMoodleFilePath(discussion.userpictureurl) %>">
                <%= discussion.userfullname %>
                <time><%= MM.util.timestampToUserDate(discussion.created) %></time>

            <p role="heading" class="subject toogler" data-discussionid="<%= discussion.discussion %>">
                <%= MM.util.formatText(discussion.subject) %>

                    <%= discussion.numreplies %> <%= MM.lang.s("forumnumreplies") %>

                <% if (discussion.created != discussion.timemodified && discussion.timemodified > discussion.created) { %>
                <%= MM.util.printTimeAgo(discussion.timemodified) %>
                <% } %>

        <% }); %>

        <%= MM.util.pagingBar(forum.numdiscussions, page, perpage, "#forum/view/" + forum.course + "/" + forum.cmid + "/:page", ":page") %>

        <% } %>


text:
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

import {IRecipe} from './recipe';
import {RECIPES} from './mock-recipes';

@Injectable()
export class RecipeService {
    public recipes: IRecipe[];

    constructor(private _http: Http) {
        this.recipes = RECIPES;
    }

    addRecipe(recipe: IRecipe) {
        if (!recipe.id) {
            recipe.id = this.generateID();
        }

        this.recipes.push(recipe);
    }

    generateID(): number {
        var highestID = Math.max.apply(Math, this.recipes.map((recipe) => {
            return recipe.id;
        }));

        var nextID = highestID + 1;

        return nextID;
    }

    getNewEmptyRecipe(): IRecipe {
        return {
            title: 'New Recipe',
            instructions: []
        }
    }

    getRecipes() {
        return Promise.resolve(this.recipes);
    }

    getRecipe(id: number) {
        return Promise.resolve(this.recipes).then(recipes => recipes.filter(r => r.id === id)[0]);
    }

    scrapeRecipe(sourceUrl: string) {
        return this._http.get('scraperecipe?recipeUrl=' + sourceUrl)
            .map(res => res.json())
    }

}