text:
import io
import json

import pytest
from typing import Tuple, Dict
from CircleCI import Client, circleci_workflows_list_command, circleci_artifacts_list_command, \
    circleci_workflow_jobs_list_command, circleci_workflow_last_runs_command, DEFAULT_LIMIT_VALUE
from CommonServerPython import CommandResults

fake_client = Client('', '', False, False, '', '', '')

def util_load_json(path):
    with io.open(path, mode='r', encoding='utf-8') as f:
        return json.loads(f.read())

test_data = util_load_json('test_data/circle_ci_commands_test_data.json')

@pytest.mark.parametrize('command_func, func_name',
                         [(circleci_workflows_list_command, 'get_workflows_list'),
                          (circleci_artifacts_list_command, 'get_job_artifacts'),
                          (circleci_workflow_jobs_list_command, 'get_workflow_jobs'),
                          (circleci_workflow_last_runs_command, 'get_last_workflow_runs')])
def test_circleci_commands(mocker, command_func, func_name):
    """
    Given:
    - 'args': XSOAR arguments

    When:
    - Executing a CircleCI command.

    Then:
    - Ensure expected CommandResults object is returned.

    """
    command_test_data = test_data[func_name]
    mocker.patch.object(fake_client, func_name, return_value=command_test_data['response'])
    result: CommandResults = command_func(fake_client, dict())
    assert result.outputs_prefix == command_test_data['outputs_prefix']
    assert result.outputs_key_field == command_test_data['outputs_key_field']
    assert result.outputs == command_test_data['outputs']

GET_COMMON_ARGUMENTS_INPUTS = [(Client('', '', False, False, vc_type='a', organization='b', project='c'), dict(),
                                ('a', 'b', 'c', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x'}, ('x', 'b', 'c', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'organization': 'x'}, ('a', 'x', 'c', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'project': 'x'}, ('a', 'b', 'x', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'limit': 1}, ('a', 'b', 'c', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'limit': 1}, ('x', 'b', 'c', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'organization': 'x', 'limit': 1}, ('a', 'x', 'c', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'project': 'x', 'limit': 1}, ('a', 'b', 'x', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'organization': 'y'}, ('x', 'y', 'c', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'project': 'y'}, ('x', 'b', 'y', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'organization': 'x', 'project': 'y'}, ('a', 'x', 'y', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'organization': 'y', 'project': 'z'},
                                ('x', 'y', 'z', DEFAULT_LIMIT_VALUE)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'organization': 'y', 'limit': 1},
                                ('x', 'y', 'c', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'project': 'y', 'limit': 1},
                                ('x', 'b', 'y', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'organization': 'x', 'project': 'y', 'limit': 1},
                                ('a', 'x', 'y', 1)),
                               (Client('', '', False, False, vc_type='a', organization='b', project='c'),
                                {'vcs_type': 'x', 'organization': 'y', 'project': 'z', 'limit': 1},
                                ('x', 'y', 'z', 1)),
                               ]

@pytest.mark.parametrize('client, args, expected', GET_COMMON_ARGUMENTS_INPUTS)
def test_get_common_arguments(client: Client, args: Dict, expected: Tuple[str, str, str, int]):
    """
    Given:
    - XSOAR arguments

    When:
    - Extracting common used args for few commands.

    Then
    - Ensure the common commands are extracted as expected, and uses default value of instance parameter if not found.
    """
    from CircleCI import get_common_arguments
    assert get_common_arguments(client, args) == expected


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEmployeeSkillsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employee_skills', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('employee_id')->unsigned();
            $table->integer('skill_id')->unsigned();
	    $table->string('details');
	    $table->foreign('employee_id')->references('id')->on('employees')->onDelete('cascade');
	    $table->foreign('skill_id')->references('id')->on('skills')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('employee_skills');
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.dmdirc.parser.irc.processors;

import com.dmdirc.parser.common.ParserError;
import com.dmdirc.parser.events.ChannelKickEvent;
import com.dmdirc.parser.interfaces.ChannelClientInfo;
import com.dmdirc.parser.interfaces.ChannelInfo;
import com.dmdirc.parser.irc.IRCChannelClientInfo;
import com.dmdirc.parser.irc.IRCChannelInfo;
import com.dmdirc.parser.irc.IRCClientInfo;
import com.dmdirc.parser.irc.IRCParser;

import java.time.LocalDateTime;
import java.util.Arrays;

import javax.inject.Inject;

/**
 * Process a channel kick.
 */
public class ProcessKick extends IRCProcessor {

    /**
     * Create a new instance of the IRCProcessor Object.
     *
     * @param parser IRCParser That owns this IRCProcessor
     */
    @Inject
    public ProcessKick(final IRCParser parser) {
        super(parser, "KICK");
    }

    /**
     * Process a channel kick.
     *
     * @param date The LocalDateTime that this event occurred at.
     * @param sParam Type of line to process ("KICK")
     * @param token IRCTokenised line to process
     */
    @Override
    public void process(final LocalDateTime date, final String sParam, final String... token) {
        callDebugInfo(IRCParser.DEBUG_INFO, "processKick: %s | %s", sParam, Arrays.toString(token));

        final IRCClientInfo iClient = getClientInfo(token[3]);
        final IRCClientInfo iKicker = getClientInfo(token[0]);
        final IRCChannelInfo iChannel = getChannel(token[2]);

        if (iClient == null) {
            return;
        }

        if (IRCParser.ALWAYS_UPDATECLIENT && iKicker != null && iKicker.getHostname().isEmpty()) {
            // To facilitate dmdirc formatter, get user information
            iKicker.setUserBits(token[0], false);
        }

        if (iChannel == null) {
            if (iClient != parser.getLocalClient()) {
                callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got kick for channel (" + token[2] + ") that I am not on. [User: " + token[3] +

                        ']', parser.getLastLine()));
            }
        } else {
            String sReason = "";
            if (token.length > 4) {
                sReason = token[token.length - 1];
            }
            final IRCChannelClientInfo iChannelClient = iChannel.getChannelClient(iClient);
            if (iChannelClient == null) {
                // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got kick for channel ("+token[2]+") for a non-existant user. [User: "+token[0]+"]", parser.getLastLine()));
                return;
            }
            final IRCChannelClientInfo iChannelKicker = iChannel.getChannelClient(token[0], true);
            if (parser.getRemoveAfterCallback()) {
                callDebugInfo(IRCParser.DEBUG_INFO, "processKick: calling kick before. {%s | %s | %s | %s | %s}", iChannel, iChannelClient, iChannelKicker, sReason, token[0]);
                callChannelKick(date, iChannel, iChannelClient, iChannelKicker, sReason, token[0]);
            }
            callDebugInfo(IRCParser.DEBUG_INFO, "processKick: removing client from channel { %s | %s }", iChannel, iClient);
            iChannel.delClient(iClient);
            callDebugInfo(IRCParser.DEBUG_INFO, "processKick: removed client from channel { %s | %s }", iChannel, iClient);
            if (!parser.getRemoveAfterCallback()) {
                callDebugInfo(IRCParser.DEBUG_INFO, "processKick: calling kick after. {%s | %s | %s | %s | %s}", iChannel, iChannelClient, iChannelKicker, sReason, token[0]);
                callChannelKick(date, iChannel, iChannelClient, iChannelKicker, sReason, token[0]);
            }
            if (iClient == parser.getLocalClient()) {
                iChannel.emptyChannel();
                parser.removeChannel(iChannel);
            }
        }
    }

    /**
     * Callback to all objects implementing the ChannelKick Callback.
     *
     * @param date The LocalDateTime that this event occurred at.
     * @param cChannel Channel where the kick took place
     * @param cKickedClient ChannelClient that got kicked
     * @param cKickedByClient ChannelClient that did the kicking
     * @param sReason Reason for kick (may be "")
     * @param sKickedByHost Hostname of Kicker (or servername)
     */
    protected void callChannelKick(final LocalDateTime date, final ChannelInfo cChannel,
            final ChannelClientInfo cKickedClient, final ChannelClientInfo cKickedByClient,
            final String sReason, final String sKickedByHost) {
        getCallbackManager().publish(
                new ChannelKickEvent(parser, date, cChannel, cKickedClient,
                        cKickedByClient, sReason, sKickedByHost));
    }

}


text:
package org.springframework.cloud.task.sqoop.job;

import org.junit.Test;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * @author Thomas Risberg
 */
public class SqoopToolJobPropertiesTests {

	@Test
	public void testActionCanBeCustomized() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		EnvironmentTestUtils.addEnvironment(context, "action: create");
		EnvironmentTestUtils.addEnvironment(context, "job-name: myjob");
		EnvironmentTestUtils.addEnvironment(context, "metastore-url: jdbc:hsqldb:hsql://localhost:16000/sqoop");
		context.register(Conf.class);
		context.refresh();
		SqoopJobTaskProperties properties = context.getBean(SqoopJobTaskProperties.class);
		assertThat(properties.getAction(), equalTo("create"));
	}

	@Test
	public void testJobNameCanBeCustomized() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		EnvironmentTestUtils.addEnvironment(context, "action: exec");
		EnvironmentTestUtils.addEnvironment(context, "job-name: anotherjob");
		EnvironmentTestUtils.addEnvironment(context, "metastore-url: jdbc:hsqldb:hsql://localhost:16000/sqoop");
		context.register(Conf.class);
		context.refresh();
		SqoopJobTaskProperties properties = context.getBean(SqoopJobTaskProperties.class);
		assertThat(properties.getJobName(), equalTo("anotherjob"));
	}

	@Test
	public void testMetastoreUrlCanBeCustomized() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		EnvironmentTestUtils.addEnvironment(context, "action: exec");
		EnvironmentTestUtils.addEnvironment(context, "job-name: myjob");
		EnvironmentTestUtils.addEnvironment(context, "metastore-url: jdbc:hsqldb:hsql://localhost:12345/sqoop");
		context.register(Conf.class);
		context.refresh();
		SqoopJobTaskProperties properties = context.getBean(SqoopJobTaskProperties.class);
		assertThat(properties.getMetastoreUrl(), equalTo("jdbc:hsqldb:hsql://localhost:12345/sqoop"));
	}

	@Test
	public void testMetastoreUsernameCanBeCustomized() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		EnvironmentTestUtils.addEnvironment(context, "action: exec");
		EnvironmentTestUtils.addEnvironment(context, "job-name: myjob");
		EnvironmentTestUtils.addEnvironment(context, "metastore-url: jdbc:hsqldb:hsql://localhost:16000/sqoop");
		EnvironmentTestUtils.addEnvironment(context, "metastore-username: spring");
		context.register(Conf.class);
		context.refresh();
		SqoopJobTaskProperties properties = context.getBean(SqoopJobTaskProperties.class);
		assertThat(properties.getMetastoreUsername(), equalTo("spring"));
	}

	@Test
	public void testMetastorePasswordCanBeCustomized() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		EnvironmentTestUtils.addEnvironment(context, "action: exec");
		EnvironmentTestUtils.addEnvironment(context, "job-name: myjob");
		EnvironmentTestUtils.addEnvironment(context, "metastore-url: jdbc:hsqldb:hsql://localhost:16000/sqoop");
		EnvironmentTestUtils.addEnvironment(context, "metastore-password: secret");
		context.register(Conf.class);
		context.refresh();
		SqoopJobTaskProperties properties = context.getBean(SqoopJobTaskProperties.class);
		assertThat(properties.getMetastorePassword(), equalTo("secret"));
	}

	@Configuration
	@EnableConfigurationProperties(SqoopJobTaskProperties.class)
	static class Conf {
	}
}


text:
#include "stdafx.h"
#include "CmdGetInstallInfo.h"
#include "meta.h"

CmdGetInstallInfo::CmdGetInstallInfo(HeadsetIntegrationService* headsetIntegrationService)
{
  m_headsetIntegrationService = headsetIntegrationService;
}

CmdGetInstallInfo::~CmdGetInstallInfo()
{
}

bool CmdGetInstallInfo::CanExecute(const Request& request)
{
  return (request.message == "getinstallinfo");
}

void CmdGetInstallInfo::Execute(const Request& request)
{
  m_headsetIntegrationService->Event(request, "getinstallinfo", {
    std::make_pair(JSON_KEY_VERSION_CHROMEHOST, VERSION),
    std::make_pair(JSON_KEY_VERSION_NATIVESDK, getNativeSDKVersion()),
    std::make_pair(JSON_KEY_LOGPATH, getLogFilePath())
  });
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using JKang.IpcServiceFramework;

using TestFtpServer.Api;

namespace TestFtpServer.Shell.Commands
{
    public class CloseCommandHandler : IRootCommandInfo
    {
        private readonly IAsyncEnumerable<ICommandInfo> _subCommands;

        /// <summary>
        /// Initializes a new instance of the <see cref="CloseCommandHandler"/> class.
        /// </summary>
        /// <param name="client">The IPC client.</param>
        public CloseCommandHandler(
            IpcServiceClient<IFtpServerHost> client)
        {
            _subCommands = new ICommandInfo[]
                {
                    new CloseConnectionCommandHandler(client),
                }
               .ToAsyncEnumerable();
        }

        /// <inheritdoc />
        public string Name { get; } = "close";

        /// <inheritdoc />
        public IReadOnlyCollection<string> AlternativeNames { get; } = Array.Empty<string>();

        /// <inheritdoc />
        public IAsyncEnumerable<ICommandInfo> GetSubCommandsAsync(CancellationToken cancellationToken)
            => _subCommands;
    }
}


text:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'PayStand_PayStandMagento',
    __DIR__
);


text:
<?php

class Object_Class_Data_Select extends Object_Class_Data {

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "select";

    /**
     * Available options to select
     *
     * @var array
     */
    public $options;

    /**
     * @var integer
     */
    public $width;

    /**
     * Type for the column to query
     *
     * @var string
     */
    public $queryColumnType = "varchar(255)";

    /**
     * Type for the column
     *
     * @var string
     */
    public $columnType = "varchar(255)";

    /**
     * Type for the generated phpdoc
     *
     * @var string
     */
    public $phpdocType = "string";

    /**
     * @return array
     */
    public function getOptions() {
        return $this->options;
    }

    /**
     * @param array $options
     * @return void
     */
    public function setOptions($options) {
        $this->options = $options;
        return $this;
    }

    /**
     * @return integer
     */
    public function getWidth() {
        return $this->width;
    }

    /**
     * @param array $options
     * @return void
     */
    public function setWidth($width) {
        $this->width = $this->getAsIntegerCast($width);
        return $this;
    }

    /**
     * @see Object_Class_Data::getDataForResource
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForResource($data, $object = null) {
        return $data;
    }

    /**
     * @see Object_Class_Data::getDataFromResource
     * @param string $data
     * @return string
     */
    public function getDataFromResource($data) {
        return $data;
    }

    /**
     * @see Object_Class_Data::getDataForQueryResource
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForQueryResource($data, $object = null) {
        return $data;
    }

    /**
     * @see Object_Class_Data::getDataForEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataForEditmode($data, $object = null) {
        return $this->getDataForResource($data, $object);
    }

    /**
     * @see Object_Class_Data::getDataFromEditmode
     * @param string $data
     * @param null|Object_Abstract $object
     * @return string
     */
    public function getDataFromEditmode($data, $object = null) {
        return $this->getDataFromResource($data);
    }

    /**
     * @see Object_Class_Data::getVersionPreview
     * @param string $data
     * @return string
     */
    public function getVersionPreview($data) {
        return $data;
    }

    /** True if change is allowed in edit mode.
     * @return bool
     */
    public function isDiffChangeAllowed() {
        return true;
    }

    /** See parent class.
     * @param mixed $data
     * @param null $object
     * @return array|null
     */
    public function getDiffDataForEditMode($data, $object = null) {
        $result = array();

        $diffdata = array();
        $diffdata["data"] = $data;
        $diffdata["disabled"] = false;
        $diffdata["field"] = $this->getName();
        $diffdata["key"] = $this->getName();
        $diffdata["type"] = $this->fieldtype;

        $value = "";
        foreach ($this->options as $option) {
            if ($option["value"] == $data) {
                $value = $option["key"];
                break;
            }
        }

        $diffdata["value"] = $value;
        $diffdata["title"] = !empty($this->title) ? $this->title : $this->name;

        $result[] = $diffdata;

        return $result;
    }

    /**
     * Checks if data is valid for current data field
     *
     * @param mixed $data
     * @param boolean $omitMandatoryCheck
     * @throws Exception
     */
    public function checkValidity($data, $omitMandatoryCheck = false) {
        if (!$omitMandatoryCheck and $this->getMandatory() and strlen( (string) $data ) == 0) {
            throw new Exception("Empty mandatory field [ " . $this->getName() . " ]");
        }
    }
}


text:
import pytest  # isort:skip

pytest.importorskip("elasticsearch")  # isort:skip

import json
import os

from elasticsearch import VERSION as ES_VERSION
from elasticsearch import Elasticsearch
from elasticsearch.serializer import JSONSerializer

import elasticapm
from elasticapm.conf.constants import TRANSACTION
from elasticapm.utils import compat

pytestmark = [pytest.mark.elasticsearch]

if "ES_URL" not in os.environ:
    pytestmark.append(pytest.mark.skip("Skipping elasticsearch test, no ES_URL environment variable"))

document_type = "_doc" if ES_VERSION[0] >= 6 else "doc"

class NumberObj:
    def __init__(self, value):
        self.value = value

class SpecialEncoder(JSONSerializer):
    def default(self, obj):
        if isinstance(obj, NumberObj):
            return obj.value
        return JSONSerializer.default(self, obj)

    def force_key_encoding(self, obj):
        if isinstance(obj, dict):

            def yield_key_value(d):
                for key, value in compat.iteritems(d):
                    try:
                        yield self.default(key), self.force_key_encoding(value)
                    except TypeError:
                        yield key, self.force_key_encoding(value)

            return dict(yield_key_value(obj))
        else:
            return obj

    def dumps(self, obj):
        return super(SpecialEncoder, self).dumps(self.force_key_encoding(obj))

@pytest.fixture
def elasticsearch(request):
    """Elasticsearch client fixture."""
    client = Elasticsearch(hosts=os.environ["ES_URL"], serializer=SpecialEncoder())
    try:
        yield client
    finally:
        client.indices.delete(index="*")

@pytest.mark.integrationtest
def test_ping(instrument, elasticapm_client, elasticsearch):
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.ping()
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    assert span["name"] == "ES HEAD /"
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["destination"] == {
        "address": os.environ["ES_URL"],
        "service": {"name": "", "resource": "elasticsearch", "type": ""},
    }
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_info(instrument, elasticapm_client, elasticsearch):
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.info()
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]

    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    assert span["name"] == "ES GET /"
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_create(instrument, elasticapm_client, elasticsearch):
    elasticapm_client.begin_transaction("test")
    if ES_VERSION[0] < 7:
        r1 = elasticsearch.create(index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"})
    else:
        r1 = elasticsearch.create(index="tweets", id=1, body={"user": "kimchy", "text": "hola"})
    r2 = elasticsearch.create(
        index="tweets", doc_type=document_type, id=2, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]

    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 2

    for i, span in enumerate(spans):
        if ES_VERSION[0] >= 5:
            assert span["name"] in (
                "ES PUT /tweets/%s/%d/_create" % (document_type, i + 1),
                "ES PUT /tweets/_create/%d" % (i + 1),
            )
        else:
            assert span["name"] == "ES PUT /tweets/%s/%d" % (document_type, i + 1)
        assert span["type"] == "db"
        assert span["subtype"] == "elasticsearch"
        assert span["action"] == "query"
        assert span["context"]["db"]["type"] == "elasticsearch"
        assert "statement" not in span["context"]["db"]
        assert span["context"]["http"]["status_code"] == 201

@pytest.mark.integrationtest
def test_index(instrument, elasticapm_client, elasticsearch):
    elasticapm_client.begin_transaction("test")
    if ES_VERSION[0] < 7:
        r1 = elasticsearch.index("tweets", document_type, {"user": "kimchy", "text": "hola"})
    else:
        r1 = elasticsearch.index(index="tweets", body={"user": "kimchy", "text": "hola"})
    r2 = elasticsearch.index(
        index="tweets", doc_type=document_type, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]

    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 2

    for span in spans:
        assert span["name"] == "ES POST /tweets/%s" % document_type
        assert span["type"] == "db"
        assert span["subtype"] == "elasticsearch"
        assert span["action"] == "query"
        assert span["context"]["db"]["type"] == "elasticsearch"
        assert "statement" not in span["context"]["db"]
        assert span["context"]["http"]["status_code"] == 201

@pytest.mark.integrationtest
def test_exists(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.exists(id=1, index="tweets", doc_type=document_type)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert result
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    assert span["name"] == "ES HEAD /tweets/%s/1" % document_type
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.skipif(ES_VERSION[0] < 5, reason="unsupported method")
@pytest.mark.integrationtest
def test_exists_source(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    if ES_VERSION[0] < 7:
        assert elasticsearch.exists_source("tweets", document_type, 1) is True
    else:
        assert elasticsearch.exists_source(index="tweets", id=1, doc_type=document_type) is True
    assert elasticsearch.exists_source(index="tweets", doc_type=document_type, id=1) is True
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]

    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 2

    for span in spans:
        assert span["name"] == "ES HEAD /tweets/%s/1/_source" % document_type
        assert span["type"] == "db"
        assert span["subtype"] == "elasticsearch"
        assert span["action"] == "query"
        assert span["context"]["db"]["type"] == "elasticsearch"
        assert "statement" not in span["context"]["db"]
        assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_get(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    # this is a fun one. Order pre-6x was (index, id, doc_type), changed to (index, doc_type, id) in 6.x, and reverted
    # to (index, id, doc_type) in 7.x. OK then.
    if ES_VERSION[0] == 6:
        r1 = elasticsearch.get("tweets", document_type, 1)
    else:
        r1 = elasticsearch.get(index="tweets", id=1, doc_type=document_type)
    r2 = elasticsearch.get(index="tweets", doc_type=document_type, id=1)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    for r in (r1, r2):
        assert r["found"]
        assert r["_source"] == {"user": "kimchy", "text": "hola"}
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 2

    for span in spans:
        assert span["name"] == "ES GET /tweets/%s/1" % document_type
        assert span["type"] == "db"
        assert span["subtype"] == "elasticsearch"
        assert span["action"] == "query"
        assert span["context"]["db"]["type"] == "elasticsearch"
        assert "statement" not in span["context"]["db"]
        assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_get_source(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    if ES_VERSION[0] < 7:
        r1 = elasticsearch.get_source("tweets", document_type, 1)
    else:
        r1 = elasticsearch.get_source(index="tweets", id=1, doc_type=document_type)
    r2 = elasticsearch.get_source(index="tweets", doc_type=document_type, id=1)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]

    for r in (r1, r2):
        assert r == {"user": "kimchy", "text": "hola"}

    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 2

    for span in spans:
        assert span["name"] == "ES GET /tweets/%s/1/_source" % document_type
        assert span["type"] == "db"
        assert span["subtype"] == "elasticsearch"
        assert span["action"] == "query"
        assert span["context"]["db"]["type"] == "elasticsearch"
        assert "statement" not in span["context"]["db"]
        assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_update_document(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    r1 = elasticsearch.update(
        index="tweets", id=1, doc_type=document_type, body={"doc": {"text": "adios"}}, refresh=True
    )
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    r2 = elasticsearch.get(index="tweets", doc_type=document_type, id=1)
    assert r2["_source"] == {"user": "kimchy", "text": "adios"}
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1

    span = spans[0]
    assert span["name"] == "ES POST /tweets/%s/1/_update" % document_type
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert "statement" not in span["context"]["db"]
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_search_body(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola", "userid": 1}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    search_query = {"query": {"term": {"user": "kimchy"}}, "sort": ["userid"]}
    result = elasticsearch.search(body=search_query)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert result["hits"]["hits"][0]["_source"] == {"user": "kimchy", "text": "hola", "userid": 1}
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Depending on ES_VERSION, could be /_all/_search or /_search, and GET or POST
    assert span["name"] in ("ES GET /_search", "ES GET /_all/_search", "ES POST /_search")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert json.loads(span["context"]["db"]["statement"]) == json.loads(
        '{"sort": ["userid"], "query": {"term": {"user": "kimchy"}}}'
    ) or json.loads(span["context"]["db"]["statement"]) == json.loads(
        '{"query": {"term": {"user": "kimchy"}}, "sort": ["userid"]}'
    )
    if ES_VERSION[0] >= 7:
        assert span["context"]["db"]["rows_affected"] == 1
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_search_querystring(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    search_query = "user:kimchy"
    result = elasticsearch.search(q=search_query, index="tweets")
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert result["hits"]["hits"][0]["_source"] == {"user": "kimchy", "text": "hola"}
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Starting in 7.5.1, these turned into POST instead of GET. That detail is
    # unimportant for these tests.
    assert span["name"] in ("ES GET /tweets/_search", "ES POST /tweets/_search")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["db"]["statement"] == "q=user:kimchy"
    if ES_VERSION[0] >= 7:
        assert span["context"]["db"]["rows_affected"] == 1
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_search_both(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    search_querystring = "text:hola"
    search_query = {"query": {"term": {"user": "kimchy"}}}
    result = elasticsearch.search(body=search_query, q=search_querystring, index="tweets")
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert len(result["hits"]["hits"]) == 1
    assert result["hits"]["hits"][0]["_source"] == {"user": "kimchy", "text": "hola"}
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Starting in 7.6.0, these turned into POST instead of GET. That detail is
    # unimportant for these tests.
    assert span["name"] in ("ES GET /tweets/_search", "ES POST /tweets/_search")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["db"]["statement"].startswith('q=text:hola\n\n{"query":')
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_count_body(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    search_query = {"query": {"term": {"user": "kimchy"}}}
    result = elasticsearch.count(body=search_query)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert result["count"] == 1
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Depending on ES_VERSION, could be /_all/_count or /_count, and either GET
    # or POST. None of these details actually matter much for this test.
    # Technically no version does `POST /_all/_count` but I added it anyway
    assert span["name"] in ("ES GET /_count", "ES GET /_all/_count", "ES POST /_count", "ES POST /_all/_count")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert json.loads(span["context"]["db"]["statement"]) == json.loads('{"query": {"term": {"user": "kimchy"}}}')
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_count_querystring(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    search_query = "user:kimchy"
    result = elasticsearch.count(q=search_query, index="tweets")
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    assert result["count"] == 1
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Starting in 7.5.1, these turned into POST instead of GET. That detail is
    # unimportant for these tests.
    assert span["name"] in ("ES GET /tweets/_count", "ES POST /tweets/_count")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["db"]["statement"] == "q=user:kimchy"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_delete(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(
        index="tweets", doc_type=document_type, id=1, body={"user": "kimchy", "text": "hola"}, refresh=True
    )
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.delete(id=1, index="tweets", doc_type=document_type)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)

    span = spans[0]
    assert span["name"] == "ES DELETE /tweets/%s/1" % document_type
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_multiple_indexes(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(index="tweets", doc_type="users", id=1, body={"user": "kimchy", "text": "hola"}, refresh=True)
    elasticsearch.create(index="snaps", doc_type="posts", id=1, body={"user": "kimchy", "text": "hola"}, refresh=True)
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.search(index=["tweets", "snaps"], q="user:kimchy")
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    # Starting in 7.6.0, these turned into POST instead of GET. That detail is
    # unimportant for these tests.
    assert span["name"] in ("ES GET /tweets,snaps/_search", "ES POST /tweets,snaps/_search")
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.skipif(ES_VERSION[0] >= 7, reason="doc_type unsupported")
@pytest.mark.integrationtest
def test_multiple_indexes_doctypes(instrument, elasticapm_client, elasticsearch):
    elasticsearch.create(index="tweets", doc_type="users", id=1, body={"user": "kimchy", "text": "hola"}, refresh=True)
    elasticsearch.create(index="snaps", doc_type="posts", id=1, body={"user": "kimchy", "text": "hola"}, refresh=True)
    elasticapm_client.begin_transaction("test")
    result = elasticsearch.search(index=["tweets", "snaps"], doc_type=["users", "posts"], q="user:kimchy")
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    assert span["name"] == "ES GET /tweets,snaps/users,posts/_search"
    assert span["type"] == "db"
    assert span["subtype"] == "elasticsearch"
    assert span["action"] == "query"
    assert span["context"]["db"]["type"] == "elasticsearch"
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_custom_serializer(instrument, elasticapm_client, elasticsearch):
    if ES_VERSION[0] < 7:
        elasticsearch.index("test-index", document_type, {"2": 1})
    else:
        elasticsearch.index(index="test-index", body={"2": 1})
    elasticapm_client.begin_transaction("test")
    search_query = {"query": {"term": {NumberObj(2): {"value": 1}}}}
    result = elasticsearch.search(index="test-index", body=search_query)
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)
    span = spans[0]
    assert json.loads(span["context"]["db"]["statement"]) == json.loads('{"query":{"term":{"2":{"value":1}}}}')
    assert span["context"]["http"]["status_code"] == 200

@pytest.mark.integrationtest
def test_dropped_span(instrument, elasticapm_client, elasticsearch):
    elasticapm_client.begin_transaction("test")
    with elasticapm.capture_span("test", leaf=True):
        elasticsearch.ping()
    elasticapm_client.end_transaction("test", "OK")

    transaction = elasticapm_client.events[TRANSACTION][0]
    spans = elasticapm_client.spans_for_transaction(transaction)
    assert len(spans) == 1
    span = spans[0]
    assert span["name"] == "test"


text:
layout: page
title: "Page Not Found"
description: "Page not found. Your pixels are in another canvas."
---

Sorry, but the page you were trying to view does not exist

__________________________________________________________

If I lose myself tonight , It'll be by your side.


text:
import argparse
import itertools
import json
import logging
import multiprocessing
import re
import threading
from multiprocessing.dummy import Pool
from operator import itemgetter
from typing import List
from urllib.parse import urlparse

import requests
import sseclient
from colors import color
from tqdm import tqdm

TEST_FAILURE_REGEX = re.compile('(\S+)\s*>\s*(\S+).*FAILED')

YELLOW_STARS_SEPARATOR = color("***********************************************************************************",
                               fg='yellow')

class SingleFailure:
    """Information container class for detected failures."""
    def __init__(self, class_name, method, build_json):
        self.class_name = class_name
        self.method = method
        self.build_json = build_json

    def __str__(self):
        return f"Failure({self.class_name}, {self.method}, ({self.build_json['name']} ...))"

def main(url, team, pipeline, job, max_fetch_count, build_count, authorization_cookie, threaded):
    builds = get_builds_summary_sheet(url, team, pipeline, job, max_fetch_count, authorization_cookie)

    build_to_examine = get_builds_to_examine(builds, build_count)
    expected_failed_builds = [int(b['name']) for b in build_to_examine if b['status'] == 'failed']
    expected_failed_builds_count = len(expected_failed_builds)
    logging.info(f"Expecting {expected_failed_builds_count} runs to have failure strings: {expected_failed_builds}")

    long_list_of_failures = aggregate_failure_information(authorization_cookie, build_to_examine, threaded, url)

    failure_url_base = f"{url}/teams/{team}/pipelines/{pipeline}/jobs/{job}/builds/"

    print_results(len(build_to_examine), expected_failed_builds, long_list_of_failures, url, failure_url_base)

def aggregate_failure_information(authorization_cookie, build_to_examine, threaded, url) -> List[SingleFailure]:
    progress_bar = tqdm(total=len(build_to_examine), desc="Build pages examined")

    def build_examiner(build):
        """ Convenience method for thread pool / list comprehension consumption below."""
        return examine_build_and_update_progress(authorization_cookie, build, url, progress_bar)

    if threaded:
        # Number of CPUs is not necessarily number of CPUs available.
        # Since it's a minor thing, we'll just ask for half.
        n_cpus = multiprocessing.cpu_count() // 2 + 1
        logging.info(f"Using {n_cpus} threads to make queries.")

        pool = Pool(n_cpus)
        list_of_list_of_failures = pool.map(build_examiner, build_to_examine)
    else:
        list_of_list_of_failures = [build_examiner(build) for build in build_to_examine]
    return list(itertools.chain(*list_of_list_of_failures))

def examine_build_and_update_progress(authorization_cookie, build, url, progress_bar) -> List[SingleFailure]:
    my_pid = threading.current_thread()
    logging.debug(f"[{my_pid}] Examining {build['name']}")
    failures = examine_build(authorization_cookie, build, url)
    progress_bar.update(1)
    return failures

def examine_build(authorization_cookie, build, url) -> List[SingleFailure]:
    session = requests.Session()

    event_response = get_event_response(authorization_cookie, build, session, url)
    logging.debug("Event Status is {}".format(event_response.status_code))

    build_status, event_output = assess_event_response(event_response)
    this_build_failures = assess_event_output_for_failure(build, event_output)
    logging.debug("Results: Job status is {}".format(build_status))

    return this_build_failures

def assess_event_output_for_failure(build, event_output) -> List[SingleFailure]:
    all_failures = []
    for line in event_output.splitlines():
        """Returns true if no failure is found, false if a failure is found."""
        test_failure_matcher = TEST_FAILURE_REGEX.search(line)
        if test_failure_matcher:
            class_name, method_name = test_failure_matcher.groups()
            this_failure = SingleFailure(class_name, method_name, build)
            all_failures.append(this_failure)
            logging.debug(f"Failure identified, {this_failure}")
    return all_failures

def assess_event_response(event_response):
    event_outputs = []
    build_status = 'unknown'
    event_client = sseclient.SSEClient(event_response)

    for event in event_client.events():
        event_json = json.loads(event.data if event.data else "{}")
        build_status = (event_json['data']['status']
                        if event_json.get('event', 'not-a-status-event') == 'status'
                        else build_status)
        if event.event == 'end' or event_json['event'] == 'status' and build_status == 'succeeded':
            return build_status, ''.join(event_outputs)
        elif event.data:
            if event_json['event'] == 'status':
                if build_status == 'succeeded':
                    return build_status, ''.join(event_outputs)
            elif event_json['event'] == 'log':
                event_outputs.append(event_json['data']['payload'])

            logging.debug("***************************************************")
            logging.debug("Event *{}* - {}".format(event.event, json.loads(event.data)))
    print("Current status:", build_status)
    print("Current aggregated event output stream:", ''.join(event_outputs))
    raise RuntimeError("An event response has no 'end' event and no 'succeeded'.  See the failing output above.")

def get_event_response(authorization_cookie, build, session, base_url):
    event_url = f'{base_url}{build["api_url"]}/events'
    event_response = session.get(event_url, cookies=authorization_cookie, stream=True, timeout=60)
    if event_response.status_code != 200:
        raise IOError(f"Event response query to endpoint < {event_url} > returned code {event_response.status_code}.")
    return event_response

def print_results(n_builds_analyzed, expected_failed_builds, long_list_of_failures, url, failure_url_base):
    if long_list_of_failures or expected_failed_builds:
        print_failures(n_builds_analyzed, expected_failed_builds, long_list_of_failures, url, failure_url_base)
    else:
        print(color("No failures! 100% success rate", fg='green', style='bold'))

def print_failures(completed, expected_failed_builds, long_list_of_failures, url, failure_url_base):
    print(YELLOW_STARS_SEPARATOR)
    print_success_rate_and_expectation_warning(completed, expected_failed_builds, long_list_of_failures,
                                               failure_url_base)
    print_failures_in_classes_that_share_method_names(completed, long_list_of_failures)
    print_class_and_test_failures_with_links(completed, long_list_of_failures, url)

    # Then highlight any build runs that failed hard / timed out.

def print_failures_in_classes_that_share_method_names(completed, long_list_of_failures):
    classes_with_a_particular_failure = {}
    for failure in long_list_of_failures:
        test_name = failure.method
        class_name = failure.class_name
        if test_name not in classes_with_a_particular_failure:
            classes_with_a_particular_failure[test_name] = {}
            classes_with_a_particular_failure[test_name][class_name] = 1
        elif class_name not in classes_with_a_particular_failure[test_name]:
            classes_with_a_particular_failure[test_name][class_name] = 1
        else:
            classes_with_a_particular_failure[test_name][class_name] += 1
    # Filter to only those methods that are found in multiple classes
    classes_with_a_particular_failure = {m: cl for m, cl in classes_with_a_particular_failure.items() if len(cl) > 1}
    if classes_with_a_particular_failure:
        print("The following test methods see failures in more than one class.  There may be a failing *TestBase class")
        for test_name, classes_and_counts in classes_with_a_particular_failure.items():
            formatted_class_output = ""
            total_failure_count = sum(count for _, count in classes_and_counts.items())
            formatted_test_name_with_success_rate = success_rate_string(f"*.{test_name}", total_failure_count, None)
            for failing_class, failure_count in classes_and_counts.items():
                formatted_class_output += "\n  "
                class_name_without_package = failing_class.split('.')[-1]
                formatted_class_output += success_rate_string(class_name_without_package, failure_count, completed)

            print(f"\n{formatted_test_name_with_success_rate}:{formatted_class_output}")
        print()
        print(YELLOW_STARS_SEPARATOR)
        print()

def print_class_and_test_failures_with_links(completed, long_list_of_failures, url):
    failed_classes = set(failure.class_name for failure in long_list_of_failures)
    for this_class_name in failed_classes:
        this_class_failures = [failure for failure in long_list_of_failures if failure.class_name == this_class_name]
        failed_tests = set(failure.method for failure in this_class_failures)
        class_build_failures_count = sum(1 for _ in {failure.build_json['name'] for failure in this_class_failures})

        print(success_rate_string(this_class_name, class_build_failures_count, completed))

        for this_test_method_name in failed_tests:
            this_test_method_failures = [failure for failure in this_class_failures
                                         if failure.method == this_test_method_name]
            test_build_failures_count = sum(
                1 for _ in {failure.build_json['name'] for failure in this_test_method_failures})
            print(" | ", success_rate_string("." + this_test_method_name, test_build_failures_count, completed))

            for this_failure in this_test_method_failures:
                build = this_failure.build_json
                failed_build_url = (f"{url}/teams/{build['team_name']}/pipelines/"
                                    f"{build['pipeline_name']}/jobs/{build['job_name']}/builds/{build['name']}")

                print(" | ", " | ",
                      color(f"Failed build {build['name']:3s} ", fg='red'),
                      color(f"at {failed_build_url}", fg='magenta', style='bold'))

def success_rate_string(identifier, failure_count, total_count):
    """Only prints percentage if total_count is not None"""
    return " ".join((color(f"{identifier}: ", fg='cyan'),
                     color(f"{failure_count} failures", fg='red'),
                     ""
                     if total_count is None else
                     color(f"({((total_count - failure_count) / total_count) * 100:6.3f}% success rate)", fg='blue')))

def print_success_rate_and_expectation_warning(completed, expected_failed_builds, long_list_of_test_failures,
                                               failure_url_base):
    # "Build failures" will refer to jobs that went red
    # "Test failures" will refer to jobs whose output matched our parsing regex

    build_failure_count = len(expected_failed_builds)
    test_failure_set = {int(failure.build_json['name']) for failure in long_list_of_test_failures}
    test_failure_count = sum(1 for _ in test_failure_set)

    # Matched failure string (in long_list) but not an expected failure (box went red)
    test_failure_not_build_failure = [name for name in test_failure_set if name not in expected_failed_builds]

    # Expected failures (box went red) but did not match a failure string (in long_list)
    build_failure_not_test_failure = [name for name in expected_failed_builds if name not in test_failure_set]

    rate = (completed - test_failure_count) * 100 / completed

    print(" Overall build success rate:",
          color(f"{rate:.5f}% ({completed - test_failure_count} of {completed})", fg='blue'))

    if build_failure_not_test_failure:
        print(color(f'>>>>> {build_failure_count} jobs "went red," '
                    f'but only {test_failure_count} were detected test failures. <<<<<',
                    fg='red', style='bold'))
        print(f"Please manually inspect the following builds:")
        for build_failure in build_failure_not_test_failure:
            print(f"  {failure_url_base}/{build_failure}")
    if test_failure_not_build_failure:
        print(color(f'>>>>> OH NO!  A test failure was detected, but the job "went green" anyway!! <<<<',
                    fg='red', style='bold'))
        print(f"Please manually inspect the following builds:")
        for test_failure in test_failure_not_build_failure:
            print(f"  {failure_url_base}/{test_failure}")
    print(YELLOW_STARS_SEPARATOR)
    print()

def get_builds_to_examine(builds, build_count):
    """
    :param builds: Build summary JSON
    :param build_count: number of completed builds to return.  Return all if 0
    """
    # possible build statuses:
    statuses = ['succeeded', 'failed', 'aborted', 'errored', 'pending', 'started']
    succeeded, failed, aborted, errored, pending, started = sieve(builds, lambda b: b['status'], *statuses)
    completed_builds = succeeded + failed
    completed_builds.sort(key=itemgetter('id'), reverse=True)
    builds_to_analyze = completed_builds[:build_count] if build_count else completed_builds
    logging.debug(f"{len(aborted)} aborted builds in examination range: {list_and_sort_by_name(aborted)}")
    logging.debug(f"{len(errored)} errored builds in examination range: {list_and_sort_by_name(errored)}")
    logging.debug(f"{len(pending)} pending builds in examination range: {list_and_sort_by_name(pending)}")
    logging.debug(f"{len(started)} started builds in examination range: {list_and_sort_by_name(started)}")

    if build_count and len(completed_builds) < build_count:
        raise RuntimeError(
            "The build report returned the {} most recent builds, with only {} of these completed.  "
            "This cannot satisfy the desired target of {} jobs to analyze.".format(
                len(builds), len(completed_builds), build_count))

    first_build = builds_to_analyze[-1]['name']
    last_build = builds_to_analyze[0]['name']
    logging.info(f"{len(started)} completed builds to examine, ranging "
                 f"{first_build} - {last_build}: {list_and_sort_by_name(builds_to_analyze)}")
    failures_in_analysis_range = list_and_sort_by_name([build for build in builds_to_analyze
                                                        if build['status'] == 'failed'])
    logging.info(f"{len(failures_in_analysis_range)} expected failures in analysis range: {failures_in_analysis_range}")
    return builds_to_analyze

def list_and_sort_by_name(builds):
    return sorted([int(b['name']) for b in builds], reverse=True)

def get_builds_summary_sheet(url, team, pipeline, job, max_fetch_count, authorization_cookie):
    session = requests.Session()
    if max_fetch_count == 0:
        # Snoop the top result's name to discover the number of jobs that have been queued.
        snoop = get_builds_summary_sheet(url, team, pipeline, job, 1, authorization_cookie)
        max_fetch_count = int(snoop[0]['name'])
        logging.info(f"Snooped: fetching a full history of {max_fetch_count} builds.")

    builds_url = '{}/api/v1/teams/{}/pipelines/{}/jobs/{}/builds'.format(url, team, pipeline, job)
    build_params = {'limit': max_fetch_count}
    build_response = session.get(builds_url, cookies=authorization_cookie, params=build_params)
    if build_response.status_code != 200:
        raise IOError(f"Initial build summary query returned status code {build_response.status_code}.")
    return build_response.json()

def sieve(iterable, inspector, *keys):
    """Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation.
    e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]]
    """
    s = {k: [] for k in keys}
    for item in iterable:
        k = inspector(item)
        if k not in s:
            raise KeyError(f"Unexpected key <{k}> found by inspector in sieve.")
        s[inspector(item)].append(item)
    return [s[k] for k in keys]

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Required args
    parser.add_argument('url',
                        help="URL to Concourse.",
                        type=lambda s: s.rstrip('/'))
    parser.add_argument('pipeline',
                        help="Name of pipeline.",
                        type=str)
    parser.add_argument('job',
                        help="Name of job.",
                        type=str)
    parser.add_argument('n',
                        help="Number of completed jobs to examine.  Enter 0 to examine all jobs fetched.",
                        type=int,
                        nargs='?',
                        default=50)
    # Optional args
    parser.add_argument('--team',
                        help='Team to which the provided pipeline belongs.  [Default="main"]',
                        type=str,
                        nargs='?',
                        default="main")
    parser.add_argument('--initial-fetch',
                        help="Limit size of initial build-status page.  [Default=100]",
                        type=int,
                        nargs='?',
                        default=100)
    parser.add_argument('--cookie-token',
                        help='If authentication is required (e.g., team="staging"), '
                             "provide your ATC-Authorization cookie's token here.  "
                             "Unfortunately, this is currently done by logging in via a web browser, "
                             "inspecting your cookies, and pasting it here.",
                        type=lambda t: {u'ATC-Authorization':
                                        '"Bearer {}"'.format(t if not t.startswith("Bearer ") else t[7:])})
    parser.add_argument('--threaded',
                        help="Use multiple cores to hasten api requests.",
                        action="store_true")
    parser.add_argument('--verbose',
                        help="Enable info logging.",
                        action="store_true")
    parser.add_argument('--debug',
                        help="Enable debug logging.  Implies --verbose",
                        action="store_true")

    args = parser.parse_args()

    # Validation
    concourse_url = urlparse(args.url)
    if not concourse_url.scheme or not concourse_url.netloc or concourse_url.path != '':
        print(color("Url {} seems to be invalid. Please check your arguments.".format(args.url), fg='red'))
        exit(1)

    # Examination limit should be less than fetch limit, or either/both should be set to 0 for full analysis
    if args.initial_fetch and args.n and args.initial_fetch < args.n:
        raise AssertionError("Fetching fewer jobs than you will analyze is pathological.")

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
    elif args.verbose:
        logging.getLogger().setLevel(logging.INFO)

    main(args.url, args.team, args.pipeline, args.job, args.initial_fetch, args.n, args.cookie_token, args.threaded)


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2022 informedcitizenry <informedcitizenry@gmail.com>
//
// Licensed under the MIT license. See LICENSE for full license information.
//
//-----------------------------------------------------------------------------

using System.Collections.Generic;
using System.Linq;

namespace Sixty502DotNet
{
    /// <summary>
    /// Maintains a collection of <see cref="AnonymousLabel"/> symbols and
    /// resolves references to them.
    /// </summary>
    public class AnonymousLabelCollection
    {
        readonly private List<KeyValuePair<int, AnonymousLabel>> _forwardRefs;
        readonly private List<KeyValuePair<int, AnonymousLabel>> _backwardRefs;
        readonly private IScope _scope;

        /// <summary>
        /// Construct a new instance of the <see cref="AnonymousLabelCollection"/>
        /// class.
        /// </summary>
        /// <param name="scope">The collection's scope.</param>
        public AnonymousLabelCollection(IScope scope)
        {
            _scope = scope;
            _forwardRefs = new List<KeyValuePair<int, AnonymousLabel>>();
            _backwardRefs = new List<KeyValuePair<int, AnonymousLabel>>();
        }

        /// <summary>
        /// Define a <see cref="AnonymousLabel"/> in the collection.
        /// </summary>
        /// <param name="reference"></param>
        public void Define(AnonymousLabel reference)
        {
            if (reference.LabelType == AnonymousLabel.Backward)
            {
                _backwardRefs.Insert(0, new KeyValuePair<int, AnonymousLabel>(reference.Index, reference));
            }
            else
            {
                _forwardRefs.Add(new KeyValuePair<int, AnonymousLabel>(reference.Index, reference));
            }
        }

        /// <summary>
        /// Resolve a <see cref="AnonymousLabel"/> in the collection.
        /// </summary>
        /// <param name="atIndex">The index of the anonymous label.</param>
        /// <returns>The label if found at the index, otherwise
        /// <c>null</c>.</returns>
        public AnonymousLabel? Resolve(int atIndex)
        {
            var lineRef = _forwardRefs.FirstOrDefault(lr => lr.Key == atIndex);
            if (lineRef.Value == null)
            {
                lineRef = _backwardRefs.FirstOrDefault(lr => lr.Key == atIndex);
            }
            if (lineRef.Value == null)
            {
                return _scope?.EnclosingScope?.ResolveAnonymousLabel(atIndex);
            }
            return lineRef.Value;
        }

        /// <summary>
        /// Get the collection of all unreferenced anonymous labels.
        /// </summary>
        /// <returns>A collection of unreferenced anonymous labels.</returns>
        public IReadOnlyCollection<SymbolBase> GetUnreferencedSymbols()
        {
            var unreferenced = new List<SymbolBase>();
            foreach (var ref_ in _forwardRefs)
            {
                if (!ref_.Value.IsReferenced)
                    unreferenced.Add(ref_.Value);
            }
            foreach (var ref_ in _backwardRefs)
            {
                if (!ref_.Value.IsReferenced)
                    unreferenced.Add(ref_.Value);
            }
            return unreferenced.AsReadOnly();
        }

        /// <summary>
        /// Resolve a <see cref="AnonymousLabel"/> in the collection.
        /// </summary>
        /// <param name="name">The reference name.</param>
        /// <param name="fromIndex">The starting index from which to
        /// refer.</param>
        /// <returns>The anonymous label if found by name from the given index,
        /// otherwise <c>null</c>.</returns>
        public AnonymousLabel? Resolve(string name, int fromIndex)
        {
            IList<KeyValuePair<int, AnonymousLabel>> tolook;
            int refsCount;
            if (name[0] == '+')
            {
                tolook = _forwardRefs.Where(kvp => kvp.Key > fromIndex).ToList();
                refsCount = tolook.Count;
            }
            else
            {
                tolook = _backwardRefs.Where(kvp => kvp.Key <= fromIndex).ToList();
                refsCount = tolook.Count;
            }
            int remain = name.Length - refsCount;
            if (remain <= 0)
            {
                return tolook[name.Length - 1].Value;
            }
            // not in my scope, is it in my parent's?
            string trimmed = refsCount == 0 ? name : name.Substring(0, remain);
            return _scope.EnclosingScope?.ResolveAnonymousLabel(trimmed, fromIndex);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.camera">

    <uses-feature android:name="android.hardware.camera"    android:required="true" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"  />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <provider
                    android:name="android.support.v4.content.FileProvider"
                    android:authorities="com.example.android.fileprovider"
                    android:exported="false"
                    android:grantUriPermissions="true">
                    <meta-data
                        android:name="android.support.FILE_PROVIDER_PATHS"
                        android:resource="@xml/file_paths"></meta-data>
                </provider>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
Sound::Sound()
{}

Sound::~Sound()
{}

void Sound::PlaySound(std::string pathSound, sf::Sound* sound)
{
  if (!this->buffer.loadFromFile(pathSound))
    return;
  sound->setBuffer(this->buffer);
  sound->play();
  return;
}

void Sound::PlayMusic(std::string pathSound, sf::Music* music)
{
  music->openFromFile(pathSound.c_str());
  music->play();
  return;
}

void Sound::PlayLoopMusic(std::string pathSound, sf::Music* music)
{
  music->openFromFile(pathSound.c_str());
  music->play();
  music->setLoop(true);
  return;
}

void Sound::SetVolumeMusic(sf::Music* music, int volume)
{
  music->setVolume(volume);
}

void Sound::StopMusic(sf::Music* music)
{
  music->stop();
}


text:
#ifndef TCP_TRAFFIC_FEED_H
#define TCP_TRAFFIC_FEED_H

#include "TrafficFeed.h"

class Selectable;

/**
 * Creates feeds from a TCP connection.
 */
class TCPTrafficFeed: public TrafficFeed {
public:
   TCPTrafficFeed( uint32 port,
                   Selectable& shutdownNotifier  );
   ~TCPTrafficFeed();

   /// @copydoc TCPTrafficFeed::eos()
   bool eos() const;

   /// @copydoc TCPTrafficFeed::getData(Data)
   bool getData( Data& data );

private:
   struct Impl;
   Impl *m_impl;
};

#endif // TCP_TRAFFIC_FEED_H


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


text:
#ifndef InspectorFrontendClient_h
#define InspectorFrontendClient_h

#include <wtf/Forward.h>
#include <wtf/Vector.h>

namespace WebCore {

class ContextMenuItem;
class Event;

class InspectorFrontendClient {
public:
    enum DockSide {
        UNDOCKED = 0,
        DOCKED_TO_RIGHT,
        DOCKED_TO_BOTTOM
    };

    virtual ~InspectorFrontendClient() { }

    virtual void windowObjectCleared() = 0;
    virtual void frontendLoaded() = 0;

    virtual void moveWindowBy(float x, float y) = 0;

    virtual String localizedStringsURL() = 0;

    virtual void bringToFront() = 0;
    virtual void closeWindow() = 0;

    virtual void requestSetDockSide(DockSide) = 0;
    virtual void changeAttachedWindowHeight(unsigned) = 0;
    virtual void changeAttachedWindowWidth(unsigned) = 0;

    virtual void setToolbarHeight(unsigned) = 0;

    virtual void openInNewTab(const String& url) = 0;

    virtual bool canSave() = 0;
    virtual void save(const WTF::String& url, const WTF::String& content, bool base64Encoded, bool forceSaveAs) = 0;
    virtual void append(const WTF::String& url, const WTF::String& content) = 0;

    virtual void inspectedURLChanged(const String&) = 0;

    virtual void sendMessageToBackend(const String&) = 0;

    virtual bool supportsFileSystems() = 0;
    virtual void requestFileSystems() = 0;
    virtual void addFileSystem() = 0;
    virtual void removeFileSystem(const String& fileSystemPath) = 0;

    virtual bool isUnderTest() = 0;
};

} // namespace WebCore

#endif


text:
If you are still using Cocos2d-html5 or Cocos2d-JSB v2.x, you need to read the previous upgrade guide first : [Upgrade guide from Cocos2d-html5 v2.2.x to Cocos2d-JS v3.0 beta](../../v3.0a/upgrade-guide/en.md)

## 1. Layer baking

In v3.0, you can start to bake a layer to a static cache, so that it can be rendered more efficiently.

```
var layer = new cc.Layer();
layer.bake();

// To disable bake
layer.unbake();
```

Detailed informations can be found in [layer baking document](../../../v3.0/bake-layer/en.md)

## 2. Object pool extension: `cc.pool`

An object pool implementation have been proposed: `cc.pool`, it can helps you to improve your game performance for objects which need frequent release and recreate operations

Some common use case is :
    - Bullets in game (die very soon, massive creation and recreation, no side effect on other objects)
    - Blocks in Candy Crash (massive creation and recreation)
    - etc...

When you no longer need an object and hope that it can be reused, you can add it to the object pool with `cc.pool.putInPool(obj)`.

```
layer.removeChild(sprite);
cc.pool.putInPool(sprite);
```

When you want to retrieve an object from object pool, you can use `cc.pool.getFromPool()`.

```
cc.pool.getFromPool(cc.Sprite, "a.png");
```

You can check whether there is objects available in the pool for a given class with `cc.pool.hasObj(cc.Sprite)`.

You can also clean the pool and release all objects with `cc.pool.drainAllPool()`.

## 3. New easing functions

We added a bunch of new easing functions listing below:

```
cc.easeBezierAction(p0, p1, p2, p3) // Have issues in JSB
cc.easeQuadraticActionIn()
cc.easeQuadraticActionOut()
cc.easeQuadraticActionInOut()
cc.easeQuarticActionIn()
cc.easeQuarticActionOut()
cc.easeQuarticActionInOut()
cc.easeQuinticActionIn()
cc.easeQuinticActionOut()
cc.easeQuinticActionInOut()
cc.easeCircleActionIn()
cc.easeCircleActionOut()
cc.easeCircleActionInOut()
cc.easeCubicActionIn()
cc.easeCubicActionOut()
cc.easeCubicActionInOut()
```

Just for a remindment, the new API for using an easing action is `action.easing(cc.easeQuadraticActionIn())`.

## 4. jsb namespace

We added jsb namespace to contain all jsb only APIs:

```
cc.fileUtils                    --> jsb.fileUtils
cc.Reflection                   --> jsb.Reflection
cc.AssetsManager                --> jsb.AssetsManager
cc.EventAssetsManager           --> jsb.EventAssetsManager
cc.EventListenerAssetsManager   --> jsb.EventListenerAssetsManager
```

And some new functions have been bound to `jsb.fileUtils`:

```
jsb.fileUtils.getSearchPaths()
jsb.fileUtils.setSearchPaths(paths)
jsb.fileUtils.getSearchResolutionsOrder()
jsb.fileUtils.setSearchResolutionsOrder(orders)
jsb.fileUtils.addSearchResolutionsOrder(order)
```

## 5. ccui

### 5.1 ccui.Widget's boundary functions have been renamed

```
getLeftInParent     -->     getLeftBoundary
getBottomInParent   -->     getBottomBoundary
getRightInParent    -->     getRightBoundary
getTopInParent      -->     getTopBoundary
```

### 5.2 `getContentSize` and `setContentSize`

We also added `getContentSize` and `setContentSize` to `ccui.Widget`, so that it can share the same usage with `cc.Node`.

```
// Added
ccui.Widget#getContentSize
ccui.Widget#setContentSize
```
### 5.3 `addEventListenerXXX` functions have been merged

All `addEventListenerXXX` in ccui have been renamed to `addEventListener` to ensure better develop experience.

```
ccui.CheckBox#addEventListenerCheckBox      --> ccui.CheckBox#addEventListener
ccui.Slider#addEventListenerSlider          --> ccui.Slider#addEventListener
ccui.TextField#addEventListenerTextField    --> ccui.TextField#addEventListener
ccui.PageView#addEventListenerPageView      --> ccui.PageView#addEventListener
ccui.ScrollView#addEventListenerScrollView  --> ccui.ScrollView#addEventListener
ccui.ListView#addEventListenerListView      --> ccui.ListView#addEventListener
```

## 6 cc.AssetsManager

A new API `downloadFailedAssets` allows you to restart failed download, and other great improvement can be found in upgraded [Assets manager document](../../../v3/assets-manager/en.md)

## 7. Other API modifications

### 7.1 cc.FadeIn

```
cc.FadeIn.create(duration, toOpacity)   -->     cc.FadeIn.create(duration)
```

### 7.2 Formatted string in cc.log

```
var str = "The number is";
var number = cc.random0To1() * 10;
cc.log("%s : %d", str, number);
```

### 7.3 Affine transform util functions

To adapte our naming protocole, we have renamed all affine transform functions, here is the list:

```
cc.AffineTransformMake              ->  cc.affineTransformMake
cc.PointApplyAffineTransform        ->  cc.pointApplyAffineTransform
cc.\_PointApplyAffineTransform       ->  cc._pointApplyAffineTransform
cc.SizeApplyAffineTransform         ->  cc.sizeApplyAffineTransform
cc.AffineTransformMakeIdentity      ->  cc.affineTransformMakeIdentity
cc.AffineTransformIdentity          ->  cc.affineTransformIdentity
cc.RectApplyAffineTransform	        ->  cc.rectApplyAffineTransform
cc.\_RectApplyAffineTransformIn      ->  cc._rectApplyAffineTransformIn
cc.AffineTransformTranslate         ->  cc.affineTransformTranslate
cc.AffineTransformScale             ->  cc.affineTransformScale
cc.AffineTransformRotate            ->  cc.affineTransformRotate
cc.AffineTransformConcat            ->  cc.affineTransformConcat
cc.AffineTransformEqualToTransform  ->  cc.affineTransformEqualToTransform
cc.AffineTransformInvert            ->  cc.affineTransformInvert
```

### 7.4 cc.RenderTexture

```
cc.RenderTexture.beginWithClear(r, g, b, a, depthValue, stencilValue)
```

`cc.RenderTexture`'s `beginWithClear` function now start to accept color value from 0-255 for `r`, `g`, `b`, `a` parameters, please stop to use float value parameters.

### 7.5 cc.sys.platform

Added `cc.sys.platform` for detecting target platform.

### 7.6 [JSB]console.log

Bound `console.log` function for JSB.

### 7.7 Formatted string

Added `cc.formatStr` for string formatting, for example:

```
cc.formatStr("a: %d, b: %b", a, b);
```

The following APIs also support formatted string as parameters:

```
cc.log(message, ...)
cc.assert(condition, message, ...)
cc.warn(message, ...)
cc.error(message, ...)
```

### 7.8 Function refactoration for adapting naming protocole

```
cc.pool.hasObj                  -> cc.pool.hasObject
cc.pool.removeObj               -> cc.pool.removeObject
cc.textureCache.textureForKey   -> cc.textureCache.getTextureForKey
cc.TMXTilemap#propertiesForGID  -> cc.TMXTilemap#getPropertiesForGID
```

### 7.9 Added getter and setter for device's target density dpi

```
// Added
cc.DENSITYDPI_DEVICE = "device-dpi";
cc.DENSITYDPI_HIGH = "high-dpi";
cc.DENSITYDPI_MEDIUM = "medium-dpi";
cc.DENSITYDPI_LOW = "low-dpi";

cc.view.setTargetDensityDPI(targetDensityDPI)
cc.view.getTargetDensityDPI()
```


text:
package com.wasihaider.viewpagerpreview;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class CustomPagerAdapter extends FragmentPagerAdapter {
    Fragment fragments [];
    public CustomPagerAdapter(FragmentManager fm, int count) {
        super(fm);
        fragments = new Fragment[count];
        for (int i = 0; i < fragments.length; i++){
            fragments[i] = Test.newInstance(i);
        }

    }

    @Override
    public int getCount() {
        return fragments.length;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }
}


text:
layout: post
title: "Spotify Mengeluarkan Release Radar Playlist Rilis Lagu Terbaru"
subtitle: "Setiap Jumat akan ada playlist dari lagu-lagu rilis terbaru."
description: "Spotify mengeluarkan release radar setiap Jumat akan ada playlist dari lagu-lagu rilis terbaru."
date: 2016-08-06
author: "Adhy Suryadi"
tags: [ Blogging ]
header-img: "img/post/release-radar.jpg"
image: "img/post/release-radar.jpg"
social-js: "https://cdn.ampproject.org/v0/amp-social-share-0.1.js"
iframe-js: "https://cdn.ampproject.org/v0/amp-iframe-0.1.js"
accordion-js: "https://cdn.ampproject.org/v0/amp-accordion-0.1.js"
---

Seiring semakin populernya Spotify sebagai pemutar musik dari seluruh dunia, Spotify semakin mengerti akan kebutuhan penggunanya. Untuk itu kini Spotify mengeluarkan **Release Radar** yang menyajikan plasylist dari lagu-lagu yang baru dirilis.

**Release Radar** ini akan keluar setiap hari Jumat dan selalu diperbaharui dengan lagu-lagu rilis terbaru dari penyanyi-penyanyi favorite Anda atau mungkin dari penyanyi yang Anda sendiri belum mengenalnya.

Release Radar memberikan kesempatan Anda sampai dua jam untuk menikmati lagu-lagu terbaru dari artis yang Anda ikuti dan dengarkan, ditambah dengan beberapa lagu-lagu baru berdasarkan kebiasaan mendengarkan musik Anda. Release Radar adalah pelengkap sempurna untuk New Music Jumat, yang menghubungkan Anda dengan artis baru yang mungkin saja Anda belum mengetahuinya. Release Radar hadir dalam aplikasi mobile dan desktop juga website.
{% include adsense_middle_post.html %}
Dengan Release Radar, Anda tidak akan ketinggalan rilis lagu terbaru dari penyanyi favorite Anda.

Di bawah ini widget Spotify untuk Release Radar.

<amp-iframe width="750" height="421"
    sandbox="allow-scripts allow-same-origin"
    layout="responsive"
    frameborder="0"
    resizable="resizable"
    src="https://embed.spotify.com/?uri=spotify%3Auser%3Aspotify%3Aplaylist%3A37i9dQZEVXbcrUfXWtsKxA">

Read more!

</amp-iframe>

**[Open Playlist On The Web](https://open.spotify.com/user/spotify/playlist/37i9dQZEVXbcrUfXWtsKxA "Open Playlist On The Web"){: target="_blank" rel="nofollow"}** - *[Source](https://news.spotify.com/us/2016/08/05/release-radar-your-personalized-playlist-of-the-newest-releases/ "Source"){: target="_blank" rel="nofollow"}*


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>Packer.pb</title>

;
; ------------------------------------------------------------
;
;   PureBasic - Compressor example file
;
;    (c) Fantaisie Software
;
; ------------------------------------------------------------
;

UseBriefLZPacker() ; Small and fast packer

If ReadFile(0, OpenFileRequester("Choose a file to compress", "", "*.*", 0))
  FileLength = Lof(0)

  ; Allocate the 2 memory buffers needed for compression..
  ;
  *Source = AllocateMemory(FileLength)
  *Target = AllocateMemory(FileLength)
  If FileLength And *Source And *Target
    ReadData(0, *Source, FileLength) ; Read the whole file in the memory buffer

    ; Compress the file, which is in memory (and use a timer to see the time spend by compression..)
    ;
    CompressedLength = CompressMemory(*Source, FileLength, *Target, FileLength)
    If CompressedLength

      DecompressedLength = UncompressMemory(*Target, CompressedLength, *Source, FileLength)
      If DecompressedLength = FileLength
        MessageRequester("Info", "De/Compression succeded:"+#LF$+#LF$+"Old size: "+Str(FileLength)+#LF$+"New size: "+Str(CompressedLength))
      EndIf
    Else
      MessageRequester("Error", "Can't compress the file")
    EndIf

    FreeMemory(*Source)
    FreeMemory(*Target)

  EndIf

  CloseFile(0)
EndIf

End


text:
package com.octoperf.metrics.service.api;

import javaslang.control.Try;

public interface CachingService {

  <R> Try.CheckedSupplier<R> cache(Try.CheckedSupplier<R> func);
}


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

//
// use Psr\Container\ContainerInterface;
// use Twig\Environment as TwigEnvironment;
// use Twig\Extension\ProfilerExtension;
// use Twig\Profiler\Profile;
// use Viserio\Bridge\Twig\DataCollector\TwigDataCollector;
// use Viserio\Contract\Container\ServiceProvider as ServiceProviderContract;
// use Viserio\Contract\Config\ProvidesDefaultConfig as ProvidesDefaultConfigContract;
// use Viserio\Contract\Config\RequiresComponentConfig as RequiresComponentConfigContract;
// use Viserio\Contract\Profiler\Profiler as ProfilerContract;
// use Viserio\Component\Config\Traits\OptionsResolverTrait;
//
// class TwigBridgeDataCollectorsServiceProvider implements
//    ServiceProviderContract,
//    RequiresComponentConfigContract,
//    ProvidesDefaultConfigContract
// {
//    use OptionsResolverTrait;
//
//    /**
//     * {@inheritdoc}
//     */
//    public function getFactories(): array
//    {
//        return [
//            Profile::class => static function (): Profile {
//                return new Profile();
//            },
//        ];
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    public function getExtensions(): array
//    {
//        return [
//            TwigEnvironment::class  => [self::class, 'extendTwigEnvironment'],
//            ProfilerContract::class => [self::class, 'extendProfiler'],
//        ];
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    public static function getDimensions(): iterable
//    {
//        return ['viserio', 'profiler'];
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    public static function getDefaultOptions(): array
//    {
//        return [
//            'collector' => [
//                'twig' => false,
//            ],
//        ];
//    }
//
//    /**
//     * Extend viserio profiler with data collector.
//     *
//     * @param \Psr\Container\ContainerInterface                  $container
//     * @param null|\Viserio\Contract\Profiler\Profiler $profiler
//     *
//     * @return null|\Viserio\Contract\Profiler\Profiler
//     */
//    public static function extendProfiler(
//        ContainerInterface $container,
//        ?ProfilerContract $profiler = null
//    ): ?ProfilerContract {
//        if ($profiler !== null) {
//            $options = self::resolveOptions($container->get('config'));
//
//            if ($options['collector']['twig'] === true) {
//                $profiler->addCollector(new TwigDataCollector(
//                    $container->get(Profile::class),
//                    $container->get(TwigEnvironment::class)
//                ));
//            }
//        }
//
//        return $profiler;
//    }
//
//    /**
//     * Wrap Twig Environment.
//     *
//     * @param \Psr\Container\ContainerInterface $container
//     * @param null|\Twig\Environment            $twig
//     *
//     * @return null|\Twig\Environment
//     */
//    public static function extendTwigEnvironment(
//        ContainerInterface $container,
//        ?TwigEnvironment $twig = null
//    ): ?TwigEnvironment {
//        if ($twig !== null) {
//            $options = self::resolveOptions($container->get('config'));
//
//            if ($options['collector']['twig'] === true) {
//                $twig->addExtension(new ProfilerExtension(
//                    $container->get(Profile::class)
//                ));
//            }
//        }
//
//        return $twig;
//    }
// }


text:
#include "util.h"
#include "accrpt.h"
#include "ci.h"

#define usage  "[ -f report_files_list | accuracy_report1 accuracy_report2 ... ] >resultfile"

Accdata accdata;
Obslist obslist;

char *inputfilename;

Option option[] =
{
    {'f', &inputfilename, NULL},
    {'\0'}
};

/**********************************************************************/

void process_file(filename)
char *filename;
{
    long chars, errors;
    chars  = accdata.characters;
    errors = accdata.errors;
    read_accrpt(&accdata, filename);
    append_obs(&obslist, accdata.characters - chars, accdata.errors - errors);
}
/**********************************************************************/

void write_results()
{
    double lower, upper;
    compute_ci(&obslist, &lower, &upper);
    printf("%14ld   Observations\n", obslist.count);
    printf("%14ld   Characters\n", accdata.characters);
    printf("%14ld   Errors\n", accdata.errors);
    printf("%14.2f%%  Accuracy\n",
    100.0 * (accdata.characters - accdata.errors) / accdata.characters);
    printf("%6.2f%%,%6.2f%%  %s\n", lower, upper,
    "Approximate 95% Confidence Interval for Accuracy");
}
/**********************************************************************/

int main(argc, argv)
int argc;
char *argv[];
{
    int i;
    initialize(&argc, argv, usage, option);
    if (argc < 2 && !inputfilename)
    error("not enough input files", Exit);

    process_all_files_from(inputfilename, &process_file);

    for (i = 0; i < argc; i++)
	process_file(argv[i]);
    write_results();
    return 0;
}


text:
package ast;

public class Plus extends Unary{
	public Plus (Exp factor){
		super(factor);
	}
}


text:
app.controller('EditorController', ['$scope', '$http', 'userinfo', '$location',
    function($scope, $http, userinfo, $location) {
        $scope.title = "";
        $scope.content = "";

        $scope.formData = {};
        $scope.submitForm = function() {
        $http({
          method  : 'POST',
          url     : 'http://chinnnoo.xyz:8889/api/article/uid/' + userinfo.getInfo().uid,
          data    : $.param($scope.formData),
          headers : {'Content-Type': 'application/x-www-form-urlencoded'}
         })
          .success(function(data) {
            console.log("sent");
            $location.url("http://chinnnoo.xyz/#/");
            console.log("redirect to http://chinnnoo.xyz/#/");
          });
        };

        $scope.tinymceOptions = {
            onChange: function(e) {
                // put logic here for keypress and cut/paste changes
            },

            setup: function(editor) {

                editor.on('init', function() {
                    // Default classes of tinyMCE are a bit weird
                    // I add my own class on init
                    // this also sets the empty class on the editor on init
                    tinymce.DOM.addClass(editor.bodyElement, 'content-editor empty');
                });

                // You CAN do it on 'change' event, but tinyMCE sets debouncing on that event
                // so for a tiny moment you would see the placeholder text and the text you you typed in the editor
                // the selectionchange event happens a lot more and with no debouncing, so in some situations
                // you might have to go back to the change event instead.
                editor.on('selectionchange', function() {
                    if (editor.getContent() === "") {
                        tinymce.DOM.addClass(editor.bodyElement, 'empty');
                    } else {
                        tinymce.DOM.removeClass(editor.bodyElement, 'empty');
                    }
                });
            },
            inline: true,
            menubar: false,
            toolbar: 'styleselect | bold italic | link image',
            plugins: 'advlist autolink link image lists charmap',
            skin: 'lightgray',
            theme: 'modern'
        };

        $scope.$on('$routeChangeSuccess', function() {
            console.log("Scrolled to the top of the article");
            window.scrollTo(0, 0);
        });
        $scope.$on('$viewContentLoaded', function(){
          //Here your view content is fully loaded !!
          NProgress.done();
        });
    }
]);


text:
module MEnv.Foreign.GLFW
  (
    foreignBegin,
    foreignEnd,
    foreignHandleEnd,

  ) where

import MEnv

foreignBegin :: MEnv res ()
foreignBegin =
    return ()

foreignEnd :: MEnv res ()
foreignEnd =
    return ()

foreignHandleEnd :: a -> a -> MEnv res a
foreignHandleEnd a a' =
    return a


text:
package org.apache.causeway.viewer.wicket.model.models;

import java.util.Objects;
import java.util.Optional;

import org.springframework.lang.Nullable;

import org.apache.causeway.applib.annotation.BookmarkPolicy;
import org.apache.causeway.applib.id.LogicalType;
import org.apache.causeway.applib.services.bookmark.Bookmark;
import org.apache.causeway.core.metamodel.context.MetaModelContext;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.object.ManagedObjects;
import org.apache.causeway.core.metamodel.object.PackedManagedObject;
import org.apache.causeway.core.metamodel.objectmanager.memento.ObjectMemento;
import org.apache.causeway.core.metamodel.spec.ObjectSpecification;
import org.apache.causeway.core.metamodel.util.Facets;

import lombok.NonNull;
import lombok.Synchronized;
import lombok.val;

/**
 * @since 2.0
 */
public final class ManagedObjectModel
extends ModelAbstract<ManagedObject> {

    private static final long serialVersionUID = 1L;

    private ObjectMemento memento;

    protected ManagedObjectModel(
            @NonNull final MetaModelContext commonContext) {
        this(commonContext, null);
    }

    protected ManagedObjectModel(
            @NonNull final MetaModelContext commonContext,
            @Nullable final ObjectMemento initialMemento) {

        super(commonContext);
        this.memento = initialMemento;
    }

    @Override
    protected ManagedObject load() {
        if (memento == null) {
            return null;
        }
        return getObjectManager().demementify(memento);
    }

    @Override
    public void setObject(final ManagedObject adapter) {

        if(ManagedObjects.isNullOrUnspecifiedOrEmpty(adapter)) {
            super.setObject(null);
            memento = null;
            return;
        }

        super.setObject(adapter);

        if(adapter instanceof PackedManagedObject) {
            setObjectCollection((PackedManagedObject)adapter);
        } else {
            memento = adapter.getMemento().orElseThrow();
        }
    }

    public void setObjectCollection(final PackedManagedObject adapter) {

        if(ManagedObjects.isNullOrUnspecifiedOrEmpty(adapter)) {
            super.setObject(null);
            memento = null;
            return;
        }

        super.setObject(adapter);
        memento = adapter.getMemento().orElseThrow();
    }

    public final Bookmark asBookmarkIfSupported() {
        return memento!=null
                ? memento.getBookmark()
                : null;
    }

    public final String oidStringIfSupported() {
        return memento!=null
                ? memento.toString()
                : null;
    }

    /**
     * free of side-effects, used for serialization
     * @implNote overriding this must be consistent with {@link #getTypeOfSpecification()}
     */
    public Optional<LogicalType> getLogicalElementType() {
        return Optional.ofNullable(memento)
                .map(ObjectMemento::getLogicalType);
    }

    private transient ObjectSpecification elementTypeSpec;
    private transient boolean isObjectSpecMemoized = false;
    /**
     * @implNote can be overridden by sub-models (eg {@link ScalarModel}) that know the type of
     * the adapter without there being one. Overriding this must be consistent
     * with {@link #getLogicalElementType()}
     */
    @Synchronized
    public ObjectSpecification getTypeOfSpecification() {
        if(!isObjectSpecMemoized) {
            val logicalType = getLogicalElementType().orElse(null);
            elementTypeSpec = super.getSpecificationLoader().specForLogicalType(logicalType).orElse(null);
            isObjectSpecMemoized = true;
        }
        return elementTypeSpec;
    }

    public final boolean hasAsRootPolicy() {
        return Facets.bookmarkPolicyMatches(BookmarkPolicy.AS_ROOT::equals)
                .test(getTypeOfSpecification());
    }

    public final boolean hasAsChildPolicy() {
        return Facets.bookmarkPolicyMatches(BookmarkPolicy.AS_CHILD::equals)
                .test(getTypeOfSpecification());
    }

    public boolean isEmpty() {
        return memento == null;
    }

    // -- CONTRACT

    @Override
    public final int hashCode() {
        return Objects.hashCode(memento);
    }

    @Override
    public final boolean equals(final Object obj) {
        if(obj instanceof ManagedObjectModel) {
            val other = (ManagedObjectModel) obj;
            return Objects.equals(this.memento, other.memento);
        }
        return false;
    }

    // -- DEPRECATIONS

//    private ObjectMemento memento() {
//        return memento;
//    }
//
//    private void memento(final ObjectMemento memento) {
//        val manageObject = super.getMetaModelContext().reconstructObject(memento);
//        super.setObject(manageObject);
//        this.memento = memento;
//        this.elementTypeSpec = null; // invalidate
//    }

}


text:
(function(document, window, $) {
  'use strict';

  window.App = Site.extend({
    handleSlidePanel: function() {
      if (typeof $.slidePanel === 'undefined') return;

      var defaults = $.components.getDefaults("slidePanel");
      var options = $.extend({}, defaults, {
        template: function(options) {
          return '
' +
            '

' +
            '

' +
            '

' +
            '

' +
            '
';
        },
        afterLoad: function() {
          this.$panel.find('.' + this.options.classes.base + '-scrollable').asScrollable({
            namespace: 'scrollable',
            contentSelector: '>',
            containerSelector: '>'
          });
        }
      });

      $(document).on('click', '[data-toggle=slidePanel]', function(e) {
        $.slidePanel.show({
          url: $(this).data('url'),
          settings: {
            cache: false
          }
        }, options);

        e.stopPropagation();
      });
    },
    handleMultiSelect: function() {
      var $all = $('.select-all');

      $(document).on('change', '.multi-select', function(e, isSelectAll) {
        if (isSelectAll) return;

        var $select = $('.multi-select'),
          total = $select.length,
          checked = $select.find('input:checked').length;
        if (total === checked) {
          $all.find('input').prop('checked', true);
        } else {
          $all.find('input').prop('checked', false);
        }
      });

      $all.on('change', function() {
        var checked = $(this).find('input').prop('checked');

        $('.multi-select input').each(function() {
          $(this).prop('checked', checked).trigger('change', [true]);
        });

      });
    },

    handleListActions: function() {
      $(document).on('click', '[data-toggle="list-editable"]', function() {
        var $btn = $(this),
          $list = $btn.parents('.list-group-item'),
          $content = $list.find('.list-content'),
          $editable = $list.find('.list-editable');

        $content.hide();
        $editable.show();
        $editable.find('input:first-child').focus().select();
      });

      $(document).on('keydown', '.list-editable [data-bind]', function(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);

        if (keycode == 13 || keycode == 27) {
          var $input = $(this),
            bind = $input.data('bind'),
            $list = $input.parents('.list-group-item'),
            $content = $list.find('.list-content'),
            $editable = $list.find('.list-editable'),
            $update = bind ? $list.find(bind) : $list.find('.list-text');

          if (keycode == 13) {
            $update.html($input.val());
          } else {
            $input.val($update.text());
          }

          $content.show();
          $editable.hide();
        }
      });

      $(document).on('click', '[data-toggle="list-editable-close"]', function() {
        var $btn = $(this),
          $list = $btn.parents('.list-group-item'),
          $content = $list.find('.list-content'),
          $editable = $list.find('.list-editable');

        $content.show();
        $editable.hide();
      });
    },

    run: function(next) {
      this.handleSlidePanel();
      this.handleListActions();
      next();
    }
  });
})(document, window, jQuery);