text:
///////////////////////////////////////////////////////////////////////////////
// QueryDataForm.cs - Windows Forms test dialog for WintabDN
//
// Copyright (c) 2010, Wacom Technology Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WintabDN
{
    public partial class QueryDataForm : Form
    {
        private CWintabContext m_logContext = null;
        private CWintabData m_wtData = null;

        UInt32 m_maxPackets = 10;
        const bool REMOVE = true;

        public QueryDataForm()
        {
            InitializeComponent();

            try
            {
                // Open a Wintab context that does not send Wintab data events.
                m_logContext = OpenQueryDigitizerContext();

                // Create a data object.
                m_wtData = new CWintabData(m_logContext);

                m_wtData.SetWTPacketEventHandler(MyWTPacketEventHandler);

                //TraceMsg("Press \"Test\" and touch pen to tablet.\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private CWintabContext OpenQueryDigitizerContext()
        {
            bool status = false;
            CWintabContext logContext = null;

            try
            {
                // Get the default digitizing context.  Turn off events.  Control system cursor.
                logContext = CWintabInfo.GetDefaultDigitizingContext(ECTXOptionValues.CXO_SYSTEM);

                logContext.Options |= (uint)ECTXOptionValues.CXO_MESSAGES;
                logContext.Options &= ~(uint)ECTXOptionValues.CXO_SYSTEM;

                if (logContext == null)
                {
                    TraceMsg("OpenQueryDigitizerContext: FAILED to get default digitizing context.\n");
                    //System.Diagnostics.Debug.WriteLine("FAILED to get default digitizing context.");
                    return null;
                }

                // Modify the digitizing region.
                logContext.Name = "WintabDN Query Data Context";

                //WintabAxis tabletX = CWintabInfo.GetTabletAxis(EAxisDimension.AXIS_X);
                //WintabAxis tabletY = CWintabInfo.GetTabletAxis(EAxisDimension.AXIS_Y);

               //// Output X/Y values 1-1 with tablet dimensions.
               // logContext.OutOrgX = logContext.OutOrgY = 0;
               // logContext.OutExtX = tabletX.axMax;
               // logContext.OutExtY = tabletY.axMax;

                logContext.SysOrgX = logContext.SysOrgY = 0;
                logContext.SysExtX = SystemInformation.PrimaryMonitorSize.Width;
                logContext.SysExtY = SystemInformation.PrimaryMonitorSize.Height;

                // Open the context, which will also tell Wintab to send data packets.
                status = logContext.Open();

                TraceMsg("Context Open: " + (status ? "PASSED [ctx=" + logContext.HCtx + "]" : "FAILED") + "\n");
                //System.Diagnostics.Debug.WriteLine("Context Open: " + (status ? "PASSED [ctx=" + logContext.HCtx + "]" : "FAILED"));
            }
            catch (Exception ex)
            {
                TraceMsg("OpenQueryDigitizerContext: ERROR : " + ex.ToString());
            }

            return logContext;
        }

        /// <summary>
        /// Responds to pen data by removing or peek/flushing data.
        /// </summary>
        /// <param name="sender_I"></param>
        /// <param name="eventArgs_I"></param>
        public void MyWTPacketEventHandler(Object sender_I, MessageReceivedEventArgs eventArgs_I)
        {
            UInt32 numPkts = 0;

            //System.Diagnostics.Debug.WriteLine("Received WT_PACKET event");
            if (m_wtData == null)
            {
                return;
            }

            bool removeData = this.removeRadioButton.Checked;

            try
            {
                // If removeData is true, packets are removed as they are read.
                // If removeData is false, peek at packets only (packets flushed below).
                WintabPacket[] packets = m_wtData.GetDataPackets(m_maxPackets, removeData, ref numPkts);

                if (numPkts > 0)
                {
                    for (int idx = 0; idx < packets.Length; idx++)
                    {
                        TraceMsg(
                            "Context:" + packets[idx].pkContext +
                            " Status:" + packets[idx].pkStatus +
                            " ID:" + packets[idx].pkSerialNumber +
                            " X:" + packets[idx].pkX +
                            " Y:" + packets[idx].pkY +
                            " P:" + packets[idx].pkNormalPressure + "\n");
                    }

                    // If the peek button was pressed, then flush the packets we just peeked at.
                    if (!removeData)
                    {
                        TraceMsg("Flushing " + numPkts.ToString() + " pending data packets...\n\n");
                        m_wtData.FlushDataPackets(numPkts);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("MyWTPacketEventHandler ERROR: " + ex.ToString());
            }
        }

        ///////////////////////////////////////////////////////////////////////
        private void clearButton_Click(object sender, EventArgs e)
        {
            testTextBox.Clear();
        }

        ///////////////////////////////////////////////////////////////////////
        void TraceMsg(string msg)
        {
            testTextBox.AppendText(msg);

            // Scroll to bottom of list.
            testTextBox.SelectionLength = 0;
            testTextBox.SelectionStart = testTextBox.Text.Length;
            testTextBox.ScrollToCaret();

            testTextBox.Update();
        }

    }
}


text:
package org.kie.pmml.pmml_4_2.model.mining;

import java.util.List;

public interface PredicateRuleProducer {
	public String getPredicateRule();
	public List<String> getPredicateFieldNames();
	public List<String> getFieldMissingFieldNames();
	public boolean isAlwaysTrue();
	public boolean isAlwaysFalse();
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace ngraph;

static string s_manifest = "${MANIFEST}";

NGRAPH_TEST(${BACKEND_NAME}, random_uniform_all_static_seed_unused)
{
    auto min_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{63.0f});
    auto max_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{120.0f});
    auto result_shape =
        make_shared<op::v0::Constant>(element::i64, Shape{3}, std::vector<float>{50, 200, 100});
    auto use_fixed_seed =
        make_shared<op::v0::Constant>(element::boolean, Shape{}, std::vector<char>{0});
    size_t fixed_seed = 9999;

    auto ru = make_shared<op::v0::RandomUniform>(
        min_val, max_val, result_shape, use_fixed_seed, fixed_seed);

    auto f = make_shared<Function>(OutputVector{ru}, ParameterVector{});

    auto backend = runtime::Backend::create("${BACKEND_NAME}");

    auto ex = backend->compile(f);

    auto t_r = backend->create_tensor(element::f32, Shape{50, 200, 100});

    ex->call_with_validate({t_r}, {});
    auto results_0 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x <= 120.0f); }));

    ex->call_with_validate({t_r}, {});
    auto results_1 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x <= 120.0f); }));

    ASSERT_FALSE(test::all_close_f(results_0, results_1)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";
}

NGRAPH_TEST(${BACKEND_NAME}, random_uniform_all_static_seed_used)
{
    auto min_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{63.0f});
    auto max_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{120.0f});
    auto result_shape =
        make_shared<op::v0::Constant>(element::i64, Shape{3}, std::vector<float>{50, 200, 100});
    auto use_fixed_seed =
        make_shared<op::v0::Constant>(element::boolean, Shape{}, std::vector<char>{1});
    size_t fixed_seed = 9999;

    auto ru = make_shared<op::v0::RandomUniform>(
        min_val, max_val, result_shape, use_fixed_seed, fixed_seed);

    auto f = make_shared<Function>(OutputVector{ru}, ParameterVector{});

    auto backend = runtime::Backend::create("${BACKEND_NAME}");

    auto ex = backend->compile(f);

    auto t_r = backend->create_tensor(element::f32, Shape{50, 200, 100});

    ex->call_with_validate({t_r}, {});
    auto results_0 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x <= 120.0f); }));

    ex->call_with_validate({t_r}, {});
    auto results_1 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x <= 120.0f); }));

    ASSERT_TRUE(test::all_close_f(results_0, results_1));
}

NGRAPH_TEST(${BACKEND_NAME}, random_uniform_seed_use_dynamic)
{
    auto min_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{63.0f});
    auto max_val = make_shared<op::v0::Constant>(element::f32, Shape{}, std::vector<float>{120.0f});
    auto result_shape =
        make_shared<op::v0::Constant>(element::i64, Shape{3}, std::vector<float>{50, 200, 100});
    auto use_fixed_seed = make_shared<op::v0::Parameter>(element::boolean, Shape{});
    size_t fixed_seed = 9999;

    auto ru = make_shared<op::v0::RandomUniform>(
        min_val, max_val, result_shape, use_fixed_seed, fixed_seed);

    auto f = make_shared<Function>(OutputVector{ru}, ParameterVector{use_fixed_seed});

    auto backend = runtime::Backend::create("${BACKEND_NAME}");

    auto ex = backend->compile(f);

    auto t_use_fixed_seed = backend->create_tensor(element::boolean, Shape{});
    auto t_r = backend->create_tensor(element::f32, Shape{50, 200, 100});

    copy_data(t_use_fixed_seed, std::vector<char>{1});

    ex->call_with_validate({t_r}, {t_use_fixed_seed});
    auto results_0 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x <= 120.0f); }));

    ex->call_with_validate({t_r}, {t_use_fixed_seed});
    auto results_1 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x <= 120.0f); }));

    ASSERT_TRUE(test::all_close_f(results_0, results_1));

    copy_data(t_use_fixed_seed, std::vector<char>{0});

    ex->call_with_validate({t_r}, {t_use_fixed_seed});
    auto results_2 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x <= 120.0f); }));

    ex->call_with_validate({t_r}, {t_use_fixed_seed});
    auto results_3 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x >= 63.0f); }));
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x <= 120.0f); }));

    ASSERT_FALSE(test::all_close_f(results_2, results_3)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";
}

NGRAPH_TEST(${BACKEND_NAME}, random_uniform_all_static_range_dynamic)
{
    auto min_val = make_shared<op::v0::Parameter>(element::f32, Shape{});
    auto max_val = make_shared<op::v0::Parameter>(element::f32, Shape{});
    auto result_shape =
        make_shared<op::v0::Constant>(element::i64, Shape{3}, std::vector<float>{50, 200, 100});
    auto use_fixed_seed =
        make_shared<op::v0::Constant>(element::boolean, Shape{}, std::vector<char>{0});
    size_t fixed_seed = 9999;

    auto ru = make_shared<op::v0::RandomUniform>(
        min_val, max_val, result_shape, use_fixed_seed, fixed_seed);

    auto f = make_shared<Function>(OutputVector{ru}, ParameterVector{min_val, max_val});

    auto backend = runtime::Backend::create("${BACKEND_NAME}");

    auto ex = backend->compile(f);

    auto t_min_val = backend->create_tensor(element::f32, Shape{});
    auto t_max_val = backend->create_tensor(element::f32, Shape{});
    auto t_r = backend->create_tensor(element::f32, Shape{50, 200, 100});

    copy_data(t_min_val, std::vector<float>{-10.0f});
    copy_data(t_max_val, std::vector<float>{10.0f});

    ex->call_with_validate({t_r}, {t_min_val, t_max_val});
    auto results_0 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x <= 10.0f); }));

    ex->call_with_validate({t_r}, {t_min_val, t_max_val});
    auto results_1 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x <= 10.0f); }));

    ASSERT_FALSE(test::all_close_f(results_0, results_1)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";

    copy_data(t_min_val, std::vector<float>{23.0f});
    copy_data(t_max_val, std::vector<float>{490.0f});

    ex->call_with_validate({t_r}, {t_min_val, t_max_val});
    auto results_2 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x >= 23.0f); }));
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x <= 490.0f); }));

    ex->call_with_validate({t_r}, {t_min_val, t_max_val});
    auto results_3 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x >= 23.0f); }));
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x <= 490.0f); }));

    ASSERT_FALSE(test::all_close_f(results_2, results_3)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";
}

NGRAPH_TEST(${BACKEND_NAME}, random_uniform_dynamic_shapes)
{
    auto min_val = make_shared<op::v0::Parameter>(element::f32, Shape{});
    auto max_val = make_shared<op::v0::Parameter>(element::f32, Shape{});
    auto result_shape = make_shared<op::v0::Parameter>(element::i64, PartialShape::dynamic(1));
    auto use_fixed_seed = make_shared<op::v0::Parameter>(element::boolean, Shape{});
    size_t fixed_seed = 9999;

    auto ru = make_shared<op::v0::RandomUniform>(
        min_val, max_val, result_shape, use_fixed_seed, fixed_seed);

    auto f = make_shared<Function>(OutputVector{ru},
                                   ParameterVector{min_val, max_val, result_shape, use_fixed_seed});

    // Getting a dynamic backend here.
    auto backend = runtime::Backend::create("${BACKEND_NAME}", true);

    auto ex = backend->compile(f);

    shared_ptr<runtime::Tensor> t_min_val;
    shared_ptr<runtime::Tensor> t_max_val;
    shared_ptr<runtime::Tensor> t_result_shape;
    shared_ptr<runtime::Tensor> t_use_fixed_seed;
    auto t_r = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic());

    // Set some starting values.
    t_min_val = backend->create_tensor(element::f32, Shape{});
    t_max_val = backend->create_tensor(element::f32, Shape{});
    t_result_shape = backend->create_tensor(element::i64, Shape{3});
    t_use_fixed_seed = backend->create_tensor(element::boolean, Shape{});
    copy_data(t_min_val, std::vector<float>{-10.0f});
    copy_data(t_max_val, std::vector<float>{10.0f});
    copy_data(t_result_shape, std::vector<int64_t>{10, 100, 100});
    copy_data(t_use_fixed_seed, std::vector<char>{0});

    ex->call_with_validate({t_r}, {t_min_val, t_max_val, t_result_shape, t_use_fixed_seed});
    ASSERT_EQ(t_r->get_shape(), (Shape{10, 100, 100}));

    auto results_0 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_0.begin(), results_0.end(), [](float x) { return (x <= 10.0f); }));

    ex->call_with_validate({t_r}, {t_min_val, t_max_val, t_result_shape, t_use_fixed_seed});
    auto results_1 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_1.begin(), results_1.end(), [](float x) { return (x <= 10.0f); }));

    ASSERT_FALSE(test::all_close_f(results_0, results_1)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";

    // Change the shape, run again with same executable.
    t_result_shape = backend->create_tensor(element::i64, Shape{2});
    copy_data(t_result_shape, std::vector<int64_t>{500, 2000});

    ex->call_with_validate({t_r}, {t_min_val, t_max_val, t_result_shape, t_use_fixed_seed});
    ASSERT_EQ(t_r->get_shape(), (Shape{500, 2000}));

    auto results_2 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_2.begin(), results_2.end(), [](float x) { return (x <= 10.0f); }));

    ex->call_with_validate({t_r}, {t_min_val, t_max_val, t_result_shape, t_use_fixed_seed});
    auto results_3 = read_vector<float>(t_r);
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x >= -10.0f); }));
    ASSERT_TRUE(
        std::all_of(results_3.begin(), results_3.end(), [](float x) { return (x <= 10.0f); }));

    ASSERT_FALSE(test::all_close_f(results_2, results_3)) << "Two different randomly generated "
                                                             "large vectors matched exactly, even "
                                                             "though use_fixed_seed was not set.";
}


text:
package be.kdg.healthtips.task;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;

import com.temboo.Library.Fitbit.Sleep.GetSleep;
import com.temboo.core.TembooException;
import com.temboo.core.TembooSession;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import be.kdg.healthtips.activity.LoginActivity;
import be.kdg.healthtips.auth.FitbitTokenManager;
import be.kdg.healthtips.session.TembooSessionManager;

public class GetDaySleepATask extends AsyncTask<Void, Void, JSONObject> {
    private FitbitTokenManager tokenManager;
    private Context context;

    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    public GetDaySleepATask(Context context) {
        super();
        this.tokenManager = FitbitTokenManager.getInstance(context);
        this.context = context;
    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            TembooSession session = TembooSessionManager.getSession();
            GetSleep getSleep = new GetSleep(session);

            GetSleep.GetSleepInputSet input = getSleep.newInputSet();
            input.set_AccessToken(tokenManager.getFitBitAccesToken());
            input.set_Date(sdf.format(new Date()));
            input.set_AccessTokenSecret(tokenManager.getFitBitAccesTokenSecret());
            input.set_ConsumerSecret(FitbitTokenManager.getConsumerSecret());
            input.set_ConsumerKey(FitbitTokenManager.getConsumerKey());

            GetSleep.GetSleepResultSet result = getSleep.execute(input);
            return new JSONObject(result.get_Response());
        } catch (TembooException e) {
            if (e.getMessage().contains("status code of 401")) {
                Intent intent = new Intent(context, LoginActivity.class);
                context.startActivity(intent);
            }
            System.err.println("Temboo throwed an exception, can't get sleep from Temboo API.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
<?php
/**
 * Send a message to the registry.
 *
 * @param string $register The register to read from.
 * @param string $register_class (optional) If set, will load a custom registry class.
 * @param string $topic The topic in the register to read from.
 * @param string $message The message to send.
 * @param string $message_key (optional) If set, will create the message with this as the key.
 * @param string $message_format (optional) The format of the message. Defaults to string.
 * Also supports json for storing an array of data.
 * @param integer $delay (optional) The delay in seconds to send by. Defaults to 0.
 * @param integer $ttl (optional) The time to live of the message. Defaults to 0, or forever.
 * @param integer $kill (optional) Defaults to false.
 *
 * @package modx
 * @subpackage processors.system.registry.register
 */

if (!isset($scriptProperties['register']) || empty($scriptProperties['register']) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $scriptProperties['register'])) return $modx->error->failure($modx->lexicon('error'));
if (!isset($scriptProperties['topic']) || empty($scriptProperties['topic'])) return $modx->error->failure($modx->lexicon('error'));

$register = trim($scriptProperties['register']);
$register_class = isset($scriptProperties['register_class']) ? trim($scriptProperties['register_class']) : 'registry.modFileRegister';

$topic = trim($scriptProperties['topic']);

$message = isset($scriptProperties['message']) ? trim($scriptProperties['message']) : '';
$message_key = isset($scriptProperties['message_key']) ? $scriptProperties['message_key'] : '';
$message_format = isset($scriptProperties['message_format']) ? trim($scriptProperties['message_format']) : 'string';

if (!empty($message)) {
    $options = array();
    $options['delay'] = isset($scriptProperties['delay']) ? intval($scriptProperties['delay']) : 0;
    $options['ttl'] = isset($scriptProperties['ttl']) ? intval($scriptProperties['ttl']) : 0;
    $options['kill'] = (isset($scriptProperties['kill']) && !empty($scriptProperties['kill'])) ? true : false;

    $modx->getService('registry', 'registry.modRegistry');
    $modx->registry->addRegister($register, $register_class, array('directory' => $register));
    if (!$modx->registry->$register->connect()) return $modx->error->failure($modx->lexicon('error'));

    $modx->registry->$register->subscribe($topic);

    switch ($message_format) {
        case 'json':
            $message = $modx->fromJSON($message);
            break;
        case 'string':
        default:
            break;
    }

    if (empty($message_key)) {
        if (is_scalar($message)) {
            $message = array($message);
        }
    } else {
        $message = array($message_key => $message);
    }

    if (!$modx->registry->$register->send($topic, $message, $options)) {
        return $modx->error->failure($modx->lexicon('error'));
    }

    return $modx->error->success('');
}
return $modx->error->failure($modx->lexicon('error'));


text:
<?xml version="1.0" encoding="UTF-8" ?>
<Response>
    <Pause length="3"/>
    <Say voice="alice">
        Listen up, Dave.
        I know there's someone else in your life.
        The kids and I ... we love you so much. But we are tired of sharing you. How could you do this to us?
    </Say>
    <Pause length="4"/>
    <Say voice="alice">
        Do you still love us?
        If yes, show me and our children a sign that your love is real.
        Barbra has a new cat.
    </Say>
</Response>


text:
require 'net/http'
require 'remote_util'
class RuleImageURLs < Customization
  @image_sizes = Hash[ "small" => 100, "medium" => 150, "large" => 250 ]
  @product_type = ['BDepartments','FDepartments', 'ADepartments']
  @needed_features = [{TextSpec => 'thumbnail_url'}]
  @rule_type = 'Text'
  @size_existence = Hash[ "small" => false, "medium" => false, "large" => false ]

  def RuleImageURLs.compute(values, pid)
    unless values[0] =~ /noimage/ || values[0] !~ /.*[Pp]roducts\/.*/
      /.*[Pp]roducts\/(?<thumbnail_url>.*)/ =~ values[0]
      retailer = Product.find(pid).retailer
      base_url = ""
      case retailer
      when "B"
        base_url = "http://www.bestbuy.ca/multimedia/Products/"
      when "F"
        base_url = "http://www.futureshop.ca/multimedia/Products/"
      end

      uses_default_url = true
      sku = Product.find(pid).sku
      sku_url = ""
      if thumbnail_url =~ /.*\d+\.jpg/
        # Image follows the pattern
        sku_url = sku[0..2].to_s+"/"+sku[0..4].to_s+"/"+sku.to_s+".jpg"
      else
        # Image URL is different
        /.*\d{2,3}x\d{2,3}\/(?<sku_url>.+)/ =~ thumbnail_url
        uses_default_url = false
      end
      # Check existence of each size

      @size_existence['small'] = false
      @size_existence['medium'] = false
      @size_existence['large'] = false

      if size_exists?("#{base_url}#{@image_sizes["small"]}x#{@image_sizes["small"]}/#{sku_url}")
        @size_existence['small'] = true
      end
      if size_exists?("#{base_url}#{@image_sizes["medium"]}x#{@image_sizes["medium"]}/#{sku_url}")
        @size_existence['medium'] = true
      end
      if size_exists?("#{base_url}#{@image_sizes["large"]}x#{@image_sizes["large"]}/#{sku_url}")
        @size_existence['large'] = true
      end
      res = []
      @image_sizes.each do |name, size|
        /(?<size_tag>\w).*/ =~ name
        if @size_existence[name] && !sku_url.empty?
          name = "image_url_#{size_tag}"
          # Save if URL is different from the default
          unless uses_default_url
            res << makespec(pid, name, "#{base_url}#{size}x#{size}/#{sku_url}")
          end
          #Remove old substitute sizes if they exist
          p = TextSpec.find_or_initialize_by_product_id_and_name(pid, name)
          p.destroy if p
        else
          # Save other image size (ideally larger) in its place
          case size_tag
          when "s"
            if @size_existence['medium']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["medium"]}x#{@image_sizes["medium"]}/#{sku_url}")
            elsif @size_existence['large']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["large"]}x#{@image_sizes["large"]}/#{sku_url}")
            else
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{thumbnail_url}")
            end
          when "m"
            if @size_existence['large']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["large"]}x#{@image_sizes["large"]}/#{sku_url}")
            elsif @size_existence['small']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["small"]}x#{@image_sizes["small"]}/#{sku_url}")
            else
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{thumbnail_url}")
            end
          when "l"
            if @size_existence['medium']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["medium"]}x#{@image_sizes["medium"]}/#{sku_url}")
            elsif @size_existence['small']
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{@image_sizes["small"]}x#{@image_sizes["small"]}/#{sku_url}")
            else
              res << makespec(pid, "image_url_#{size_tag}", "#{base_url}#{thumbnail_url}")
            end
          end
        end
      end
    else
      unless (Session.retailer == 'A' and values[0] =~ /images-amazon/) # for amazon, if there is a url in the input, do nothing since fine
        BinSpec.find_or_initialize_by_product_id_and_name(pid, "missingImage").update_attributes(value: true)
      end
    end
    res
  end

  def RuleImageURLs.size_exists?(url)
    # Check for existence
    url = URI.parse(url.gsub('[', '%5B').gsub(']', '%5D'))
    result = RemoteUtil.do_with_retry(exceptions: [Timeout::Error]) do |except|
      if not except.nil?
        puts "Timeout retrieving image (" + url.to_s + "), will retry"
      end
      Net::HTTP.start(url.host, url.port).head(url.request_uri).code
    end
    return result == "200"
  end

  def RuleImageURLs.makespec(pid, name, value)
    url_to_add = TextSpec.find_or_initialize_by_product_id_and_name(pid, name)
    url_to_add.value = value
    url_to_add
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungal Diversity 26(2): 434 (2007)

#### Original name
Helicoma palmarum G.Z. Zhao, Xing Z. Liu & W.P. Wu

### Remarks
null


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150320142311 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE INDEX first_name ON users (first_name)');
        $this->addSql('CREATE INDEX last_name ON users (last_name)');
        $this->addSql('ALTER TABLE user_photos DROP FOREIGN KEY FK_6D24FBE47E3C61F9');
        $this->addSql('ALTER TABLE user_photos ADD CONSTRAINT FK_6D24FBE47E3C61F9 FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE CASCADE');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE user_photos DROP FOREIGN KEY FK_6D24FBE47E3C61F9');
        $this->addSql('ALTER TABLE user_photos ADD CONSTRAINT FK_6D24FBE47E3C61F9 FOREIGN KEY (owner_id) REFERENCES users (id)');
        $this->addSql('DROP INDEX first_name ON users');
        $this->addSql('DROP INDEX last_name ON users');
    }
}


text:
/*global require, describe, it, beforeEach, afterEach*/
'use strict';
var mocks = require('../utils');
var sinon = require('sinon');
var expect  = require('chai').expect;

var kArbitraryRoom = {'_id': '1', name: '', options: {p2p: true, data: ''}};
var kArbitraryService = {'_id': '1', rooms: [kArbitraryRoom]};

describe('RpcPublic API', function() {
  var tokenRegistryMock,
      serviceRegistryMock,
      cloudHandlerMock,
      rpcPublic;

  beforeEach(function() {
    mocks.start(mocks.licodeConfig);
    tokenRegistryMock = mocks.start(mocks.tokenRegistry);
    serviceRegistryMock = mocks.start(mocks.serviceRegistry);
    cloudHandlerMock = mocks.start(mocks.cloudHandler);
    rpcPublic = require('../../rpc/rpcPublic');
  });

  afterEach(function() {
    mocks.stop(mocks.licodeConfig);
    mocks.stop(tokenRegistryMock);
    mocks.stop(serviceRegistryMock);
    mocks.stop(cloudHandlerMock);
    mocks.deleteRequireCache();
    mocks.reset();
  });

  describe('delete token', function() {
    it('should fail if token does not exist', function(done) {
      tokenRegistryMock.getToken.callsArgWithAsync(1, undefined);
      rpcPublic.deleteToken('1', function(type, message) {
        expect(type).to.equal('callback');
        expect(message).to.equal('error');
        done();
      });
    });

    it('should fail when removing an expired test token', function(done) {
      var arbitraryToken = {use: 500, service: kArbitraryService};
      tokenRegistryMock.getToken.callsArgWithAsync(1, arbitraryToken);
      serviceRegistryMock.getService.callsArgWithAsync(1, kArbitraryService);
      tokenRegistryMock.removeToken.callsArgAsync(1);
      rpcPublic.deleteToken('1', function(type, message) {
        expect(type).to.equal('callback');
        expect(message).to.equal('error');
        done();
      });
    });

    it('should succeed when removing a test token', function(done) {
      var arbitraryToken = {use: 1, service: kArbitraryService};
      tokenRegistryMock.getToken.callsArgWithAsync(1, arbitraryToken);
      serviceRegistryMock.getService.callsArgWithAsync(1, kArbitraryService);
      tokenRegistryMock.removeToken.callsArgAsync(1);
      rpcPublic.deleteToken('1', function(type, message) {
        expect(type).to.equal('callback');
        expect(message).to.deep.equal(arbitraryToken);
        expect(tokenRegistryMock.updateToken.callCount).to.equal(1);
        done();
      });
    });

    it('should succeed when removing a token', function(done) {
      var arbitraryToken = {service: kArbitraryService};
      tokenRegistryMock.getToken.callsArgWithAsync(1, arbitraryToken);
      tokenRegistryMock.removeToken.callsArgAsync(1);
      rpcPublic.deleteToken('1', function(type, message) {
        expect(type).to.equal('callback');
        expect(message).to.deep.equal(arbitraryToken);
        expect(tokenRegistryMock.removeToken.callCount).to.equal(1);
        done();
      });
    });
  });

  it('should add new erizo controllers', function() {
    var callback = sinon.stub();
    cloudHandlerMock.addNewErizoController.callsArgWith(1, 'id1');
    rpcPublic.addNewErizoController('message', callback);
    expect(callback.withArgs('callback', 'id1').callCount).to.equal(1);
    expect(cloudHandlerMock.addNewErizoController.callCount).to.equal(1);
  });

  it('should send keepAlives', function() {
    var callback = sinon.stub();
    cloudHandlerMock.keepAlive.callsArgWith(1, 'result1');
    rpcPublic.keepAlive('message', callback);
    expect(callback.withArgs('callback', 'result1').callCount).to.equal(1);
    expect(cloudHandlerMock.keepAlive.callCount).to.equal(1);
  });

  it('should set info', function() {
    var callback = sinon.stub();
    rpcPublic.setInfo('params1', callback);
    expect(callback.withArgs('callback').callCount).to.equal(1);
    expect(cloudHandlerMock.setInfo.withArgs('params1').callCount).to.equal(1);
  });

  it('should kill cloud handler', function() {
    var callback = sinon.stub();
    rpcPublic.killMe('ip1', callback);
    expect(callback.withArgs('callback').callCount).to.equal(1);
    expect(cloudHandlerMock.killMe.withArgs('ip1').callCount).to.equal(1);
  });
});


text:
/* ***** ----------------------------------------------- ***** **
/* ***** Gulp - Scripts
/* ***** ----------------------------------------------- ***** */

import addSrc from 'gulp-add-src';
import babel from 'rollup-plugin-babel';
import browserSync from 'browser-sync';
import concat from 'gulp-concat';
import commonjs from 'rollup-plugin-commonjs';
import config from '../config';
import eslint from 'gulp-eslint';
import gif from 'gulp-if';
import gulp from 'gulp';
import header from 'gulp-header';
import json from 'rollup-plugin-json';
import modernizr from 'gulp-modernizr';
import nodeResolve from 'rollup-plugin-node-resolve';
import plumber from 'gulp-plumber';
import rename from 'gulp-rename';
import rollup from 'gulp-better-rollup';
import size from 'gulp-size';
import sourcemaps from 'gulp-sourcemaps';
import terser from 'gulp-terser';

// Environment variables
const isDevelopment = process.env.NODE_ENV === 'development';

// Create a custom Modernizr build by crawling the .scss and .js files
const scriptsModernizr = () => {
  return gulp.src(config.scripts.modernizr.src)
    .pipe(plumber())
    .pipe(modernizr(config.scripts.modernizr.options))
    .pipe(concat('modernizr.js'))
    .pipe(gulp.dest(config.scripts.modernizrDest));
}

// Lint files with ESLint
const scriptsLint = () => {
  return gulp.src(config.scripts.watchSrc)
    .pipe(eslint())
    .pipe(eslint.format());
}

/*
** -- Create sourcemaps if in development mode (use gulp --production or gulp --staging to disable soucemaps)
** -- Bundle all files
** -- Minify all files
** -- Add ByMattLee header to bundled file
** -- Print bundled file size
** -- Reload browser
*/
const scriptsMain = () => {
  return gulp.src(config.scripts.src)
    .pipe(plumber())
    .pipe(addSrc.prepend(config.scripts.modernizrFileSrc))
    .pipe(gif(isDevelopment, sourcemaps.init()))
      .pipe(rollup({
        plugins: [
          babel({
            exclude: 'node_modules/**'
          }),
          nodeResolve(),
          commonjs(),
          json()
        ]
      }, 'umd'))
      .pipe(terser({
        format: {
          comments: false
        }
      }))
      .pipe(concat('main.js'))
      .pipe(rename({
        suffix: '.min'
      }))
      .pipe(header(config.fileHeader.join('\n')))
      .pipe(size({
        title: 'Compressed File Size:',
        showFiles: true
      }))
    .pipe(gif(isDevelopment, sourcemaps.write('./')))
    .pipe(gulp.dest(config.scripts.dest))
    .pipe(browserSync.stream());
}

const scriptsBuild = gulp.series(scriptsModernizr, scriptsLint, scriptsMain);
const scriptsWatch = gulp.series(scriptsLint, scriptsMain);

export { scriptsBuild, scriptsWatch };


text:
Simplified version for beginner programmers by John Magee based on
[http://www.python.org/dev/peps/pep-0008](Style Guide for Python Code).

##  Introduction

This simplified style guide is intended to help beginner Python progammers adhere to basic coding conventions. Properly styled computer code is more easily read and understood by humans. You may revisit code you write later, or you may work on code with other people in the future. It's important that your code is easily understood by yourself and others.

This guide is a simplified version of *Style Guide for Python Code* by Guido van Rossum and Barry Warsaw. The original document has been placed in the public domain by the authors and is available here:
[http://www.python.org/dev/peps/pep-0008]().

## Consistency

Code is read much more often than it is written. The guidelines provided here are intended to improve the
readability of code and make it consistent across the wide spectrum of Python code.  So readability counts.

A style guide is about consistency.  Consistency with this style guide is important.  Consistency within a project is more important. Consistency within one module or function is most important.

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply.  When in doubt, use your best judgment.  Look at other examples and decide what looks best.  And don't hesitate to ask!

Two good reasons to break a particular rule:
*  When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.

* To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this may also be an opportunity to clean up someone else's mess.

##    Code lay-out
### Indentation

Use 4 spaces per indentation level.

For really old code that you don't want to mess up, you can continue to use 8-space tabs.

### Tabs or Spaces?

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only.

### Maximum Line Length

Limit all lines to a maximum of 79 characters.

There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices disrupts the visual structure of the code, making it more difficult to understand.  Therefore, please limit all lines to a maximum of 79 characters.

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.  If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better.

### Blank Lines

Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line.

Extra blank lines may be used (sparingly) to separate groups of related functions.  Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Use blank lines in functions, sparingly, to indicate logical sections.

## Imports
### Placement

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

**Note:** Our text violates this. Please adhere to the convention in your own code.

### Formatting

Imports should usually be on separate lines, e.g.:

Yes:

	import os
	import sys

No:

	import sys, os

It's okay to write this though:

	from subprocess import Popen, PIPE
##   Whitespace in Expressions and Statements

### Avoid extraneous whitespace in the following situations:

Immediately inside parentheses, brackets or braces.

Yes:

	spam(ham[1], {eggs: 2})

No:

	spam( ham[ 1 ], { eggs: 2 } )

Immediately before a comma, semicolon, or colon:

Yes:

	if x == 4: print x, y; x, y = y, x

No:

	if x == 4 : print x , y ; x , y = y , x

Immediately before the open parenthesis that starts the argument list of a function call:

Yes:

	spam(1)

No:

	spam (1)

Immediately before the open parenthesis that starts an indexing or slicing:

Yes:

	dict['key'] = list[index]

No:

	dict ['key'] = list [index]

More than one space around an assignment or other operator to align it with another.

Yes:

	x = 1
	y = 2
	long_variable = 3

No:

	x             = 1
	y             = 2
	long_variable = 3

### Places to use spaces:

Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, **in**, **not in**, **is**, **is not**), Booleans (**and**, **or**, **not**).

Use spaces around arithmetic operators:

Yes:

	i = i + 1
	submitted += 1
	x = x * 2 - 1
	hypot2 = x * x + y * y
	c = (a + b) * (a - b)

No:

	i=i+1
	submitted +=1
	x = x*2 - 1
	hypot2 = x*x + y*y
	c = (a+b) * (a-b)

Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

	if foo == 'blah':
		do_blah_thing()
	do_one()
	do_two()
	do_three()

Rather not:

	if foo == 'blah': do_blah_thing()
	do_one(); do_two(); do_three()

## Comments

Comments that contradict the code are worse than no comments.  Always make a priority of keeping the comments up-to-date when the code changes.

Comments should be complete sentences.  If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers).

If a comment is short, the period at the end can be omitted.  Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period.

You should use two spaces after a sentence-ending period.

### Header Comments
Header comments appear at the top of a file. These lines typically include the filename, author, date, version number, and a description of what the file is for and what it contains. For class assignments, headers should also course name, number, section, instructor, and assignment
number.

The detailed file documentation is best placed in a python *docstring*
at the top of the file, rather than in ad hoc comment strings. Properly
using docstrings helps integrate your code into the python help system.

Example:

    """
    File: <filename>
    Copyright (c) 2016 <your name>
    License: MIT

    Course: PHYS227
    Assignment: 1.1
    Date: Feb 7, 2016
    Email: somebody@mail.chapman.edu
    Name: Som Ebody
    Description: a basic start-up program.
    """

### Function Comments

Function comments are like the description part of a header comment, but contain
information specific to what a function does. These comments should also include
a description of the purpose and expected input arguments, the expected output
values, and how error conditions are handled.

The detailed documentation of functions is best placed in a python *docstring*
after the function definition, rather than in ad hoc comment strings. Properly
using docstrings helps integrate your code into the python help system.

Example:

	def calcHypotenuse(a, b):
      """Solve the Pythagorean theorem a^2 + b^2 = c^2 for the value of c.

      Inputs: a and b are the lengths of sides of a right triangle.
      Output: c is the length of the hypotenuse.
      """
      return math.sqrt(a**2 + b**2)

Ideally your code should be self-documenting and Pythonic, so docstrings should
be used liberally. Other common conventions like littering your code with
irrelevant comment strings ##### are discouraged in favor of code clarity.

### Block Comments

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code.  Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

Paragraphs inside a block comment are separated by a line containing a single #.

### Inline Comments

Use inline comments sparingly.

An inline comment is a comment on the same line as a statement.  Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are unnecessary and in fact distracting if they statethe obvious.  Don't do this:

	x = x + 1       # Increment x

But sometimes, something like this  is useful:

	x = x + 1          # Compensate for border

##  Naming Conventions

There are various naming conventions used in Python and other programming languages. The two common ones we will see are lowercase_with_underscore and mixedCase (aka lowerCamelCase).

For consistency, we should stick to the mixedCase convention. Multi-word names should start with a lowercase letter, and each new word should start with a capital letter. You can never have a space within a name. For example,

	sumOfSquares
	printHappyBirthday
	totalApples

### Names to Avoid

Never use the characters `l` (lowercase letter el), `O` (uppercase letter oh), or `I` (uppercase letter eye) as single character variable names.

In some typefaces, these characters are indistinguishable from the numerals one and zero.

In general, try to avoid using single character names. There are some times when using `x`, `y`, `z` for axis names, or `a`, `b`, `c` for the sides of a triangle, or `i`, `j`, `k` for indices will make sense,  For most other cases, create names that have meaning for their function.


text:
using NUnit.Framework;

namespace MeetMe.Data.Models.Tests.CommentTests
{
    [TestFixture]
    public class CustomUserId_Should
    {
        [TestCase(1)]
        [TestCase(550)]
        public void SetCustomUserId_Correct(int id)
        {
            // Arrange
            var comment = new Comment();

            // Act
            comment.CustomUserId = id;

            // Assert
            Assert.AreEqual(comment.CustomUserId, id);
        }
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_above="@+id/button"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit Showing List"
        android:id="@+id/button"
        android:onClick="sendMessage"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/button5" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/editText"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:text="1.0"
        android:layout_toStartOf="@+id/button5" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update"
        android:onClick="sendMessage5"
        android:id="@+id/button5"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Update at:23 Oct 2015 , 11:25"
        android:id="@+id/textView7"
        android:layout_above="@+id/button5"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>


text:
package org.apache.jackrabbit.core.util.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The connection helper for Oracle databases of version 10.2 and later.
 */
public class OracleConnectionHelper extends ConnectionHelper {

    /**
     * the default logger
     */
    private static Logger log = LoggerFactory.getLogger(OracleConnectionHelper.class);

    /**
     * @param dataSrc the {@code DataSource} on which this helper acts
     * @param block whether to block on connection loss until the db is up again
     */
    public OracleConnectionHelper(DataSource dataSrc, boolean block) {
        super(dataSrc, true, block);
    }

    /**
     * Initializes the helper: checks for valid driver version.
     * Subclasses that override this method should still call it!
     *
     * @throws Exception on error
     */
    public void init() throws Exception {
         // check driver version
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            if (metaData.getDriverMajorVersion() < 10) {
                // Oracle drivers prior to version 10 only support
                // writing BLOBs up to 32k in size...
                log.warn("Unsupported driver version detected: "
                        + metaData.getDriverName()
                        + " v" + metaData.getDriverVersion());
            }
        } catch (SQLException e) {
            log.warn("Can not retrieve driver version", e);
        } finally {
            DbUtility.close(connection, null, null);
        }
    }

    /**
     * Since Oracle only supports table names up to 30 characters in
     * length illegal characters are simply replaced with "_" rather than
     * escaping them with "_x0000_".
     *
     * {@inheritDoc}
     */
    @Override
    protected final void replaceCharacter(StringBuilder escaped, char c) {
        escaped.append("_");
    }
}


text:
package cli

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"regexp"
	"sort"

	"github.com/fatih/color"
	"github.com/mike182uk/snpt/internal/snippet"
	prompt "github.com/segmentio/go-prompt"
)

// GenerateSnippetDescription generates a snippet description
func GenerateSnippetDescription(snpt snippet.Snippet) string {
	yellow := color.New(color.FgYellow).SprintFunc()
	desc := yellow(snpt.Filename)

	if snpt.Description != "" {
		desc += fmt.Sprintf(" - %s", snpt.Description)
	}

	desc += fmt.Sprintf(" [%s]", snpt.GetId())

	return desc
}

// ResolveSnippet resolves a snippet via either a passed argument, standard input or user prompt
func ResolveSnippet(args []string, hasInput bool, in io.Reader, snptStore *snippet.Store) (snippet.Snippet, error) {
	var (
		snpt       snippet.Snippet
		snptID     string
		promptOpts []string
		snpts      snippet.Snippets
	)

	snpts, err := snptStore.GetAll()

	if err != nil {
		return snpt, err
	}

	sort.Sort(snpts)

	// if there are no snippets, return early
	if len(snpts) == 0 {
		return snpt, nil
	}

	// if there is input data, try and read from it
	if hasInput {
		input, err := ioutil.ReadAll(in)

		if err != nil {
			return snpt, errors.New("Failed to read from stdin")
		}

		snptID = extractSnippetID(string(input))

		// if there was a second argument passed on the cli, try and use it as an id
	} else if len(args) == 1 {
		snptID = args[0]

		// if there was no input and the id was not passed as an argument, prompt the
		// user to select a snippet
	} else {
		for _, snpt := range snpts {
			promptOpts = append(promptOpts, GenerateSnippetDescription(snpt))
		}

		i := prompt.Choose("Choose a snippet", promptOpts)

		snptID = extractSnippetID(promptOpts[i])
	}

	// return found snippet
	for _, snpt := range snpts {
		if snpt.GetId() == snptID {
			return snpt, nil
		}
	}

	// return an empty snippet if no snippet was found
	return snpt, nil
}

func extractSnippetID(s string) string {
	re := regexp.MustCompile(`(?m:\[([A-Za-z0-9]+)\])`)
	m := re.FindStringSubmatch(s)

	if len(m) == 2 {
		return m[1]
	}

	return ""
}

// PrintSuccess prints a success message
func PrintSuccess(out io.Writer, format string, a ...interface{}) {
	printWithColor(out, color.FgGreen, format, a...)
}

// PrintError prints an error message
func PrintError(out io.Writer, format string, a ...interface{}) {
	printWithColor(out, color.FgRed, format, a...)
}

// PrintInfo prints an info message
func PrintInfo(out io.Writer, format string, a ...interface{}) {
	printWithColor(out, color.FgBlue, format, a...)
}

func printWithColor(out io.Writer, ca color.Attribute, format string, a ...interface{}) {
	c := color.New(ca).SprintFunc()
	s := c(fmt.Sprintf(format, a...))

	fmt.Fprintln(out, s)
}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// testing_codegen_util.h
//
// Identification: test/include/codegen/testing_codegen_util.h
//
// Copyright (c) 2015-2018, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include <vector>

#include "catalog/catalog.h"
#include "codegen/buffering_consumer.h"
#include "codegen/compilation_context.h"
#include "codegen/execution_consumer.h"
#include "codegen/value.h"
#include "common/container_tuple.h"
#include "expression/comparison_expression.h"
#include "expression/constant_value_expression.h"
#include "expression/tuple_value_expression.h"
#include "planner/binding_context.h"
#include "storage/data_table.h"
#include "storage/database.h"

#include "common/harness.h"
#include "executor/testing_executor_util.h"

namespace peloton {
namespace test {

using ExpressionPtr = std::unique_ptr<expression::AbstractExpression>;
using ConstExpressionPtr =
    std::unique_ptr<const expression::AbstractExpression>;

using PlanPtr = std::unique_ptr<planner::AbstractPlan>;
using ConstPlanPtr = std::unique_ptr<const planner::AbstractPlan>;

/**
 * This is a scoped file handle that automatically deletes/removes the file
 * with the given name when the class goes out of scope and the destructor is
 * called.
 */
struct TempFileHandle {
  std::string name;
  TempFileHandle(std::string _name);
  ~TempFileHandle();
};

/**
 * Common base class for all codegen tests. This class has four test tables
 * whose IDs and names are stored in test_table_oids and test_table_names,
 * respectively. The test tables all have the exact schema: column "a" and "b"
 * are integers, column "c" is a decimal, and column "d" is a varchar. The table
 * with the highest OID also has a primary key on column "a".
 */
class PelotonCodeGenTest : public PelotonTest {
 public:
  std::string test_db_name = "peloton_codegen";
  std::vector<std::string> test_table_names = {"table1", "table2", "table3",
                                               "table4", "table5"};
  std::vector<oid_t> test_table_oids;

  PelotonCodeGenTest(oid_t tuples_per_tilegroup = DEFAULT_TUPLES_PER_TILEGROUP,
                     peloton::LayoutType layout_type = LayoutType::ROW);

  struct CodeGenStats {
    codegen::QueryCompiler::CompileStats compile_stats;
    codegen::Query::RuntimeStats runtime_stats;
  };

  virtual ~PelotonCodeGenTest();

  // Get the test database
  storage::Database &GetDatabase() const { return *test_db; }

  // Get the test table with the given ID
  storage::DataTable &GetTestTable(oid_t table_id) const {
    return *GetDatabase().GetTableWithOid(static_cast<uint32_t>(table_id));
  }

  // Get the layout table
  storage::DataTable *GetLayoutTable() const { return layout_table; }

  // Create the schema (common among all tables)
  catalog::Column GetTestColumn(uint32_t col_id) const;

  std::unique_ptr<catalog::Schema> CreateTestSchema() const;

  // Create the test tables
  void CreateTestTables(concurrency::TransactionContext *txn,
                        oid_t tuples_per_tilegroup,
                        peloton::LayoutType layout_type);

  // Load the given table with the given number of rows
  void LoadTestTable(oid_t table_id, uint32_t num_rows,
                     bool insert_nulls = false);

  // Load tables with the specified layout
  void CreateAndLoadTableWithLayout(peloton::LayoutType layout_type,
                                    oid_t tuples_per_tilegroup,
                                    oid_t tile_group_count, oid_t column_count,
                                    bool is_inlined);

  // Compile and execute the given plan
  CodeGenStats CompileAndExecute(
      planner::AbstractPlan &plan, codegen::ExecutionConsumer &consumer);

  CodeGenStats CompileAndExecuteCache(
      std::shared_ptr<planner::AbstractPlan> plan,
      codegen::ExecutionConsumer &consumer, bool &cached,
      std::vector<type::Value> params = {});

  //===--------------------------------------------------------------------===//
  // Helpers
  //===--------------------------------------------------------------------===//
  ExpressionPtr ConstIntExpr(int64_t val);

  ExpressionPtr ConstDecimalExpr(double val);

  ExpressionPtr ColRefExpr(type::TypeId type, uint32_t col_id);
  ExpressionPtr ColRefExpr(type::TypeId type, bool left, uint32_t col_id);

  ExpressionPtr CmpExpr(ExpressionType cmp_type, ExpressionPtr &&left,
                        ExpressionPtr &&right);

  ExpressionPtr CmpLtExpr(ExpressionPtr &&left, ExpressionPtr &&right);
  ExpressionPtr CmpLteExpr(ExpressionPtr &&left, ExpressionPtr &&right);
  ExpressionPtr CmpGtExpr(ExpressionPtr &&left, ExpressionPtr &&right);
  ExpressionPtr CmpGteExpr(ExpressionPtr &&left, ExpressionPtr &&right);
  ExpressionPtr CmpEqExpr(ExpressionPtr &&left, ExpressionPtr &&right);

  ExpressionPtr OpExpr(ExpressionType op_type, type::TypeId type,
                       ExpressionPtr &&left, ExpressionPtr &&right);

 private:
  storage::Database *test_db;
  storage::DataTable *layout_table;
};

//===----------------------------------------------------------------------===//
// A query consumer that prints the tuples to standard out
//===----------------------------------------------------------------------===//
class Printer : public codegen::ExecutionConsumer {
 public:
  Printer(std::vector<oid_t> cols, planner::BindingContext &context) {
    for (oid_t col_id : cols) {
      ais_.push_back(context.Find(col_id));
    }
  }

  bool SupportsParallelExec() const override { return false; }

  // None of these are used, except ConsumeResult()
  void InitializeQueryState(codegen::CompilationContext &) override {}
  void TearDownQueryState(codegen::CompilationContext &) override {}

  void Prepare(codegen::CompilationContext &ctx) override;
  void ConsumeResult(codegen::ConsumerContext &ctx,
                     codegen::RowBatch::Row &) const override;

 private:
  std::vector<const planner::AttributeInfo *> ais_;
};

}  // namespace test
}  // namespace peloton


text:
namespace Colore.Effects.Keyboard
{
    using System.ComponentModel;
    using System.Runtime.Serialization;

    using JetBrains.Annotations;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    /// <summary>
    /// Supported built-in keyboard effects.
    /// </summary>
    [PublicAPI]
    [JsonConverter(typeof(StringEnumConverter))]
    public enum KeyboardEffectType
    {
        /// <summary>
        /// No effect.
        /// </summary>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_NONE")]
        None = 0,

        /// <summary>
        /// Custom effect.
        /// </summary>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_CUSTOM")]
        Custom = 2,

        /// <summary>
        /// Static effect.
        /// </summary>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_STATIC")]
        Static = 4,

        /// <summary>
        /// Reserved effect.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Advanced)]
        [PublicAPI]
        [EnumMember(Value = "CHROMA_RESERVED")]
        Reserved = 7,

        /// <summary>
        /// Custom effect with keys.
        /// </summary>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_CUSTOM_KEY")]
        CustomKey = 8,

        /// <summary>
        /// Custom effect for extended keyboards.
        /// </summary>
        /// <remarks>
        /// The extended APIs are within the "v2" namespace in the Keyboard namespace in the SDK.
        /// </remarks>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_CUSTOM2")]
        ExtendedCustom = 9,

        /// <summary>
        /// Invalid effect.
        /// </summary>
        [PublicAPI]
        [EnumMember(Value = "CHROMA_INVALID")]
        Invalid = 10
    }
}


text:
package com.yiibai.struts2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private String user;
	private String password;
	private String name;

	public String execute() {
		String ret = ERROR;
		Connection conn = null;
		try {
			String URL = "jdbc:mysql://localhost/teststruts";
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(URL, "root", "ictehi");
			String sql = "SELECT name FROM login WHERE";
			sql += " user = ? AND password = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, user);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				name = rs.getString(1);
				ret = SUCCESS;
			}
		} catch (Exception e) {
			ret = ERROR;
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
				}
			}
		}
		return ret;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


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

namespace Infestation
{
    public abstract class Catalyst : Supplement
    {
        public Catalyst(int healthEffect, int powerEffect, int aggressionEffect)
            :base (healthEffect, powerEffect, aggressionEffect)
        {
        }
    }
}


text:
require 'transproc/version'
require 'transproc/function'
require 'transproc/functions'
require 'transproc/composer'
require 'transproc/error'
require 'transproc/store'
require 'transproc/registry'
require 'transproc/support/deprecations'

module Transproc
  # Function registry
  #
  # @api private
  def self.functions
    @_functions ||= {}
  end

  # Register a new function
  #
  # @example
  #   Transproc.register(:to_json, -> v { v.to_json })
  #
  #   Transproc(:map_array, Transproc(:to_json))
  #
  #
  # @return [Function]
  #
  # @api public
  def self.register(*args, &block)
    name, fn = *args
    if functions.include? name
      raise FunctionAlreadyRegisteredError, "Function #{name} is already defined"
    end
    functions[name] = fn || block
  end

  # Get registered function with provided name
  #
  # @param [Symbol] name The name of the registered function
  #
  # @api private
  def self.[](name, *args)
    fn = functions.fetch(name) { raise FunctionNotFoundError.new(name) }

    if args.any?
      fn.with(*args)
    else
      fn
    end
  end
end

require 'transproc/array'
require 'transproc/hash'

# Access registered functions
#
# @example
#   Transproc(:map_array, Transproc(:to_string))
#
#   Transproc(:to_string) >> Transproc(-> v { v.upcase })
#
# @param [Symbol,Proc] fn The name of the registered function or an anonymous proc
# @param [Array] args Optional addition args that a given function may need
#
# @return [Function]
#
# @api public
def Transproc(fn, *args)
  Transproc::Deprecations.announce(
    'Transproc()',
    'Define your own function registry using Transproc::Registry extension'
  )

  case fn
  when Proc then Transproc::Function.new(fn, args: args)
  when Symbol
    fun = Transproc[fn, *args]
    case fun
    when Transproc::Function, Transproc::Composite then fun
    else Transproc::Function.new(fun, args: args)
    end
  end
end


text:
<!DOCTYPE html>

<button class="text">Click</button>


text:
package com.example.puremvc_appfacade.Runs;

import android.util.Log;
import com.example.puremvc_appfacade.Runs.protocol.IMediator;
import com.example.puremvc_appfacade.Runs.protocol.INotification;

/**
 * Created by dev_wang on 2017/1/24.
 */

public class Mediator implements IMediator {
    protected String TAG = this.getClass().getName();
    private Object viewComponent = null;
    private String mediatorName = null;

    @Override
    public void initializeMediator() {
        Log.i(TAG,"initializeMediator " + this.getClass().getName());
        // will override by sub class
    }

    @Override
    public void onRegister() {
        // will override by sub class
    }

    @Override
    public void onRemove() {
        // will override by sub class
    }

    @Override
    public void setViewComponent(Object viewComponent) {
        this.viewComponent = viewComponent;
    }

    @Override
    public Object getViewComponent() {
        return this.viewComponent;
    }

    @Override
    public void setMediatorName(String name) {
        this.mediatorName = name;
    }

    @Override
    public String getMediatorName() {
        return this.mediatorName;
    }

    @Override
    public void handleNotification(INotification notification) {
        // will override by sub class
        Log.i(TAG,"handleNotification " + this.getClass().getName());
    }

    @Override
    public String[] listNotificationInterests() {
        return null;
    }
}


text:
<?php

namespace MajorGlitches;

use ALttP\Item;
use ALttP\World;
use TestCase;

/**
 * @group MajorGlitches
 */
class OpenEscapeTest extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();
        $this->world = World::factory('open', ['difficulty' => 'test_rules', 'logic' => 'MajorGlitches']);
        $this->collected->setChecksForWorld($this->world->id);
    }

    public function tearDown(): void
    {
        parent::tearDown();
        unset($this->world);
    }

    /**
     * @param string $location
     * @param bool $access
     * @param array $items
     * @param array $except
     *
     * @dataProvider accessPool
     */
    public function testLocation(string $location, bool $access, array $items, array $except = [])
    {
        if (count($except)) {
            $this->collected = $this->allItemsExcept($except);
        }

        $this->addCollected($items);

        $this->assertEquals($access, $this->world->getLocation($location)
            ->canAccess($this->collected));
    }

    /**
     * @param string $location
     * @param bool $access
     * @param string $item
     * @param array $items
     * @param array $except
     *
     * @dataProvider fillPool
     */
    public function testFillLocation(string $location, bool $access, string $item, array $items = [], array $except = [])
    {
        if (count($except)) {
            $this->collected = $this->allItemsExcept($except);
        }

        $this->addCollected($items);

        $this->assertEquals($access, $this->world->getLocation($location)
            ->fill(Item::get($item, $this->world), $this->collected));
    }

    public function fillPool()
    {
        return [

            ["Sanctuary", true, 'KeyH2', [], ['KeyH2']],

            ["Sewers - Secret Room - Left", true, 'KeyH2', [], ['KeyH2']],

            ["Sewers - Secret Room - Middle", true, 'KeyH2', [], ['KeyH2']],

            ["Sewers - Secret Room - Right", true, 'KeyH2', [], ['KeyH2']],

            ["Sewers - Dark Cross", true, 'KeyH2', [], ['KeyH2']],

            ["Hyrule Castle - Boomerang Chest", false, 'KeyH2', [], ['KeyH2']],

            ["Hyrule Castle - Map Chest", true, 'KeyH2', [], ['KeyH2']],

            ["Hyrule Castle - Zelda's Cell", false, 'KeyH2', [], ['KeyH2']],
        ];
    }

    public function accessPool()
    {
        return [
            ["Sanctuary", true, []],

            ["Sewers - Secret Room - Left", False, []],
            ["Sewers - Secret Room - Left", true, ['ProgressiveGlove']],
            ["Sewers - Secret Room - Left", true, ['PowerGlove']],
            ["Sewers - Secret Room - Left", true, ['TitansMitt']],
            ["Sewers - Secret Room - Left", true, ['Lamp', 'KeyH2']],

            ["Sewers - Secret Room - Middle", false, []],
            ["Sewers - Secret Room - Middle", true, ['ProgressiveGlove']],
            ["Sewers - Secret Room - Middle", true, ['PowerGlove']],
            ["Sewers - Secret Room - Middle", true, ['TitansMitt']],
            ["Sewers - Secret Room - Middle", true, ['Lamp', 'KeyH2']],

            ["Sewers - Secret Room - Right", false, []],
            ["Sewers - Secret Room - Right", true, ['ProgressiveGlove']],
            ["Sewers - Secret Room - Right", true, ['PowerGlove']],
            ["Sewers - Secret Room - Right", true, ['TitansMitt']],
            ["Sewers - Secret Room - Right", true, ['Lamp', 'KeyH2']],

            ["Sewers - Dark Cross", False, [], ['Lamp']],
            ["Sewers - Dark Cross", true, ['Lamp']],

            ["Hyrule Castle - Boomerang Chest", false, []],
            ["Hyrule Castle - Boomerang Chest", true, ['KeyH2']],

            ["Hyrule Castle - Map Chest", true, []],

            ["Hyrule Castle - Zelda's Cell", false, []],
            ["Hyrule Castle - Zelda's Cell", true, ['KeyH2']],

            ["Link's Uncle", true, []],

            ["Secret Passage", true, []],
        ];
    }
}


text:
import React, { Component } from 'react';

export default class Page1 extends Component<any,any> {
  render() {
    return (
      <div className="page1"> Page1 ccxccc </div>
    );
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls hist. -nat. Mus. natn. hung. 8: 6 (1910)

#### Original name
Septoria scirpicola Hollós

### Remarks
null


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.CheckedIcon = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

const CheckedIcon = _ref => {
  let {
    color,
    title,
    ...other
  } = _ref;
  return /*#__PURE__*/_react.default.createElement("svg", (0, _extends2.default)({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 11 8",
    width: "11",
    height: "8",
    fill: color
  }, other), title && /*#__PURE__*/_react.default.createElement("title", null, title), /*#__PURE__*/_react.default.createElement("path", {
    d: "M.904 4.06l1.414-1.414L4.44 4.768 8.682.525l1.414 1.414L4.44 7.596.904 4.061z"
  }));
};

exports.CheckedIcon = CheckedIcon;
CheckedIcon.propTypes = {
  color: _propTypes.default.string,
  title: _propTypes.default.string
};
CheckedIcon.defaultProps = {
  color: '#fff',
  title: ''
};


text:
When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.
## Setting Up the project locally
## Submitting a Pull Request
* Please go through existing issues and pull requests to check if somebody else is already working on it.
* Increase the version numbers.
* You may merge the Pull Request in once you have the sign-off of other developer, or if you do not have permission to do that, you may request to the reviewer to merge it for you.
## Code of conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).


text:
package biz.jovido.seed.content;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author Stephan Grundner
 */
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason="No such item")
public class ItemNotPublishedException extends RuntimeException {

    public ItemNotPublishedException() {
    }

    public ItemNotPublishedException(String message) {
        super(message);
    }

    public ItemNotPublishedException(String message, Throwable cause) {
        super(message, cause);
    }

    public ItemNotPublishedException(Throwable cause) {
        super(cause);
    }

    public ItemNotPublishedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
package com.forsvarir.mud.commands;

import com.forsvarir.mud.Player;
import com.forsvarir.mud.actions.RoomActions;
import com.forsvarir.mud.communications.MessageSender;
import org.springframework.stereotype.Service;

@Service
public class LookCommand implements MudCommand {
    private final MessageSender messageSender;
    private final RoomActions roomActions;

    public LookCommand(MessageSender messageSender, RoomActions roomActions) {
        this.messageSender = messageSender;
        this.roomActions = roomActions;
    }

    @Override
    public void processCommand(String arguments, Player sender) {
        var roomView = roomActions.buildRoomViewForPlayer(sender.getRoom(), sender);
        messageSender.sendToPlayer(roomView, sender);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity repository-class="ItoSoftware\Components\ModelBundle\Entity\ScoreRepository" name="ItoSoftware\Components\ModelBundle\Entity\Score">
    <id name="id" type="integer" column="id">
      <generator strategy="AUTO"/>
    </id>
    <field name="number" type="integer" column="number"/>
    <field name="active" type="boolean" column="active"/>
    <field name="date" type="datetime" column="date"/>

    <many-to-one field="activity" target-entity="Score">
        <join-column name="activity_id" referenced-column-name="id" />
    </many-to-one>

  </entity>
</doctrine-mapping>


text:
layout: bare
title: W-JAX 2013 GitHub Workshop
description: W-JAX 2013 GitHub Workshop Class Notes
tags: [notes]
path: classnotes/2013-11-04-w-jax-2013-github-workshop.md
eventdate: 2013-11-04
---

## Teachers
* Tim Berglund ([Twitter](http://twitter.com/tlberglund), [GitHub](https://github.com/tlberglund))

## Resources

* [Adding SSL Certificates for GitHub.com (Common for Windows XP)](http://stackoverflow.com/questions/3777075/https-github-access/4454754#4454754)
* Disabling SSL Certificate Checks for Git:

        git config --global http.sslVerify false
* [Open Source Git Ignore Templates](https://github.com/github/gitignore)
* [Book Authoring on Git and GitHub](http://teach.github.com/articles/book-authoring-using-git-and-github/)
* [Post Receive Hooks](https://help.github.com/articles/post-receive-hooks)
* [GitHub Training Videos](http://training.github.com/resources/videos/)
* [Using Git with Media Temple](http://carl-topham.com/theblog/post/using-git-media-temple/)
* [GitHub Training Feedback and Follow-up Questions](https://github.com/githubtraining/feedback/issues?state=open)
* [GitHub Commit Status API for Continuous Integration](https://github.com/blog/1227-commit-status-api)
* [Git Credential Cache for HTTP](http://teach.github.com/articles/lesson-git-credential-cache/)
* [GitHub Issues Cheatsheet](http://teach.github.com/articles/github-issues-cheatsheet/)
* [Jenkins Git Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin)
* [Open Source Git Ignores](https://github.com/github/gitignore)
* [Ship of Theseus - Related to Similarity Index](http://en.wikipedia.org/wiki/Ship_of_Theseus)
* [git-p4 Perforce Script](http://answers.perforce.com/articles/KB_Article/Git-P4)
* [Unix watch command](http://en.wikipedia.org/wiki/Watch_(Unix\))
* [SHA-1 Hash Collisions](http://git-scm.com/book/ch6-1.html#A-SHORT-NOTE-ABOUT-SHA-1)
* [NPD Git Cheatsheet](http://ndpsoftware.com/git-cheatsheet.html)
* [More Git Cheatsheets](http://teach.github.com/articles/git-cheatsheets/)

## Installation
* Git Installation
    * [The Git-SCM Web Site (All Platforms)](http://git-scm.com)
    * [The GitHub for Windows Client and Command Line](http://windows.github.com)
* Minimum is 1.7.ANYTHING, but can have issues with HTTPS credential prompting.
* Best is 1.8.0 or higher

## Suggested Books, Articles
* [Free ProGit Book](http://git-scm.com/book)
* [Getting started with Version Control](http://teach.github.com/articles/lesson-new-to-version-control/)
* [The GitHub Flow](http://scottchacon.com/2011/08/31/github-flow.html)
* [DVCS Workflows Book](https://github.com/zkessin/dvcs-workflows)
* [Git Cheat Sheets](http://teach.github.com/articles/git-cheatsheets/)
* [Git Workflow Links](https://pinboard.in/u:matthew.mccullough/t:git+workflow)

## Course Materials, Links
* [Git Teaching Materials](http://teach.github.com)
* [Course Slides](http://teach.github.com/presentations/)
* [Course Slides Source](https://github.com/github/teach.github.com/tree/gh-pages/presentations)
* [Post-event Git and GitHub questions](https://github.com/githubtraining/feedback/)
* [Free Office Hours Sessions](http://training.github.com/web/free-classes/)

## Command History

    git --version
    git --versi
    git init wjax
    ls -la
    tree .git
    git config user.name
    git config user.email
    git config --global user.name "Tim Berglund"
    git config --global user.email "tlberglund@github.com"
    git config --global color.ui auto
    git config color.ui
    git help config
    git commit -m "Initial commit"
    git loglive
    git commit -m "Noblest man"
    git diff
    git diff --word-diff
    git diff --color-words
    git diff HEAD
    git diff HEAD --color-words
    git diff --staged
    git commit -m 'Costly blood'
    git commit -m "Iambic"
    ls .git
    git log
    git help log
    git log --format=raw
    git log --graph
    git log --graph --decorate
    git log --graph --decorate --oneline
    git log --graph --decorate --oneline --all
    git config --global alias.lol "log --graph --decorate --oneline --all"
    git log --format=raw -1
    watch -n 1 "git lol"
    generaterandomfiles 6 junk txt
    cat junk1.txt
    git commit -m "Cruft"
    git rm junk1.txt
    rm junk2.txt
    git rm junk2.txt
    open .
    git add -u .
    git rm --cached junk6.txt
    git commit -m "Anti-cruft"
    ll ~ > console.log
    mkdir -p build/classes/main
    echo "monkey" > build/classes/main/AngryMonkey.class
    vi .gitignore
    git add .gitignore
    git commit -m "Git Ignore"
    git ls
    generaterandomfiles 5 file txt
    ls -l ~ > listing.txt
    git commit -m "Things to move"
    mkdir files
    rm console.log
    rm junk6.txt
    rm -rf build
    git mv file1.txt files/
    mv file2.txt files/
    git rm file2.txt
    git add files/file2.txt
    git status -u
    git add temp/file2.txt
    git help status
    git reset HEAD temp/file2.txt
    cp files/file2.txt temp/
    git status -u
    rm -rf temp
    git commit -m "Moved files"
    vi listing.txt
    git commit -m "Move and change"
    git log --stat 1
    git log --stat -1
    git log --stat -1 -M
    git log --stat -1 -M80
    git log --stat -- files/listing.txt
    git log --stat --follow -- files/listing.txt
    vi files/listing.txt
    git commit -m "Change after move"
    git log --stat -M --follow -- files/listing.txt
    git log --stat -M80 --follow -- files/listing.txt
    git commit -m "Tim lied"
    git log --stat -M
    mkdir temp
    mv files/listing.txt temp/monkey.txt
    vi temp/monkey.txt
    git add -A .
    git commit -m "Tim REALLY lied"
    git log -M --stat
    git reset --hard HEAD^
    tree
    git branch feature
    cat .git/refs/heads/master
    cat .git/refs/heads/feature
    git commit -m "Ruby lips"
    git commit -m "Title"
    git merge feature -m "Merged"
    git branch -d feature
    git branch feature2
    git branch monkey bca4
    git branch -d monkey
    git commit -m "Cursed limbs"
    git commit -m "Civil strife"
    git merge feature2
    git help merge
    git reset --hard a3f6f
    git checkout feature2
    git commit -m "Raven intro"
    git merge feature2
    git commit -m "Merged again"
    git loglive -10
    git branch -d feature2
    git branch feature3
    vi README.md
    git add README.md
    git commit -m "Add README"
    git checkout feature3
    git commit -m "Blood and destruction"
    git add raven.txt
    git commit -m "Lost Lenore"
    git rebase master
    git merge feature3
    git reflog
    git branch -d feature3
    git branch feature4
    git checkout -b feature4
    git branch
    git commit -m "Radiant"
    cd files
    generaterandomchanges 10 random txt
    git rebase -i 2f63fc7
    git checkout feature
    git checkout feature4
    git reset --hard 3652723
    git reflog
    git reset --hard HEAD@{1}
    git merge feature4
    git branch -d feature4
    export PS1="$ "
    git remote add origin https://github.com/githubteacher/wjax2013.git
    cat .git/config
    git push -u origin master
    git branch -a
    git diff origin/master
    git pull
    cat caesar.txt
    git commit -m "Nameless"
    git commit -m "Rustling"
    git lol -5
    tr.git
    cd scratch
    cd wjax
    git clone https://github.com/githubstudent/wjax2013.git
    cd wjax2013
    git --version
    git config --global --unset credential.helper
    git config credential.helper
    git commit -m "Choked pity"
    git commit -m "Caesar Rage"
    git loglive -8
    git pull https://github.com/githubstudent/wjax2013.git master
    git commit -m "Caesar Rage Merge"
    git remote
    git remote add teacher https://github.com/githubteacher/wjax2013.git
    git pull teacher master
    cd ..
    ls
    git clone https://github.com/githubteacher/wjax2013.git teacher-wjax
    cd teacher-wjax
    git config --global credential.helper cache
    git commit -m "Cry HAVOC"
    git loglive -5
    git loglive -6
    git lol
    git config branch.master.rebase true
    git config --global branch.autosetuprebase always
    git commit -m "Carrion men"
    git add caesar.txt
    git status
    vi caesar.txt
    git rebase --continue
    git loglive -12
    while :\ndo\ngit pull\nsleep 1\ndone
    git loglive -15
    git loglive -16
    git loglive -20
    git loglive -18
    git tag LITTLE_CHANGE
    tree .git/refs
    git tag -a BEFORE_REBASE_PULLS 89cce
    git show LITTLE_CHANGE
    git show 48b7dee
    git show BEFORE_REBASE_PULLS
    git push origin LITTLE_CHANGE
    git push --tags
    git checkout -b tlberglund
    vi ra
    pwd
    l
    ll
    git log -- raven.txt
    git checkout ff968b87 -- raven.txt
    git commit -m "Fantastic"
    git push --set-upstream origin tlberglund
    vi raven.txt
    git add .
    git commit -m "Still beating"
    git push
    git checkout master
    git branch -d tlberglund
    git fetch
    git pull
    git pull --prune
    git fetch --pruen
    git fetch --prune


text:
var u = Ti.Android != undefined ? 'dp' : 0;
//A window object which will be associated with the stack of windows
exports.AppWindow = function(args) {
	var instance = Ti.UI.createWindow(args);

	var view = Ti.UI.createView({
		height : 40 + u,
		width : 320 + u,
		layout : 'horizontal',
		top : 0 + u,
		borderColor : '#133899',
		borderWidth : 1,
		borderRadius : 1
	});
	instance.add(view);
	var buttonshare = Ti.UI.createButton({
		title : 'Share',
		left : 5 + u,
		right : 5 + u,
		bottom : 1 + u,
		height : 40 + u,
		width : 150 + u
	});
	view.add(buttonshare);
	var buttoncheckin = Ti.UI.createButton({
		title : 'Check-In',
		left : 5 + u,
		right : 5 + u,
		bottom : 1 + u,
		height : 40 + u,
		width : 150 + u
	});
	view.add(buttoncheckin);
	buttoncheckin.addEventListener('click', function() {
		globals.tabs.currentTab.open(Ti.UI.createWindow({
			title : 'New Window',
			backgroundColor : 'white'
		}));
	});

	//news feed
	var scrollView = Titanium.UI.createScrollView({
		contentWidth:'auto',
		contentHeight:'auto',
		top:50,
		showVerticalScrollIndicator:true,
		showHorizontalScrollIndicator:false
	});

	instance.add(scrollView);

	var view = Ti.UI.createView({
		backgroundColor:'#EFEFEF',
		borderRadius:10,
		width:300,
		height:1000,
		top:0
	});

	scrollView.add(view);

	var button = Titanium.UI.createButton({
		title:'Scroll to Top',
		height:40,
		width:200,
		bottom:10
	});
	view.add(button);
	button.addEventListener('click', function()
	{
		scrollView.scrollTo(0,0);
	});

	return instance;
};


text:
{% load i18n %}
{% load cookielaw_tags %}<!doctype html>
<html lang="{{LANGUAGE_CODE}}">
<head>
<title>{% block title %}{% endblock %}</title>
<meta charset="{% block content_type %}{% endblock content_type %}" />
{% block head_meta %}
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
{% endblock head_meta %}
{% block extra_style %}{% endblock %}
{% block extra_head %}{% endblock %}
</head>
{% block tag_body %}
<body>
{% cookielaw_banner %}
{% endblock %}
{% block body %}{% endblock %}
<script src="{{STATIC_URL}}cookielaw/js/cookielaw.js"></script>
</body>
</html>


text:
from robot.errors import DataError

class XmlElementHandler(object):

    def __init__(self, execution_result, root_handler=None):
        self._stack = [(root_handler or RootHandler(), execution_result)]

    def start(self, elem):
        handler, result = self._stack[-1]
        handler = handler.get_child_handler(elem)
        result = handler.start(elem, result)
        self._stack.append((handler, result))

    def end(self, elem):
        handler, result = self._stack.pop()
        handler.end(elem, result)

class _Handler(object):

    def __init__(self):
        self._child_handlers = dict((c.tag, c) for c in self._children())

    def _children(self):
        return []

    def get_child_handler(self, elem):
        try:
            return self._child_handlers[elem.tag]
        except KeyError:
            raise DataError("Incompatible XML element '%s'." % elem.tag)

    def start(self, elem, result):
        return result

    def end(self, elem, result):
        pass

    def _timestamp(self, elem, attr_name):
        timestamp = elem.get(attr_name)
        return timestamp if timestamp != 'N/A' else None

class RootHandler(_Handler):

    def _children(self):
        return [RobotHandler()]

class RobotHandler(_Handler):
    tag = 'robot'

    def start(self, elem, result):
        generator = elem.get('generator', 'unknown').split()[0].upper()
        result.generated_by_robot = generator == 'ROBOT'
        return result

    def _children(self):
        return [RootSuiteHandler(), StatisticsHandler(), ErrorsHandler()]

class SuiteHandler(_Handler):
    tag = 'suite'

    def start(self, elem, result):
        return result.suites.create(name=elem.get('name', ''),
                                    source=elem.get('source'))

    def _children(self):
        return [DocHandler(), MetadataHandler(), SuiteStatusHandler(),
                KeywordHandler(), TestCaseHandler(), self]

class RootSuiteHandler(SuiteHandler):

    def start(self, elem, result):
        result.suite.name = elem.get('name', '')
        result.suite.source = elem.get('source')
        return result.suite

    def _children(self):
        return SuiteHandler._children(self)[:-1] + [SuiteHandler()]

class TestCaseHandler(_Handler):
    tag = 'test'

    def start(self, elem, result):
        return result.tests.create(name=elem.get('name', ''),
                                   timeout=elem.get('timeout'))

    def _children(self):
        return [DocHandler(), TagsHandler(), TestStatusHandler(), KeywordHandler()]

class KeywordHandler(_Handler):
    tag = 'kw'

    def start(self, elem, result):
        return result.keywords.create(kwname=elem.get('name', ''),
                                      libname=elem.get('library', ''),
                                      timeout=elem.get('timeout'),
                                      type=elem.get('type', 'kw'))

    def _children(self):
        return [DocHandler(), ArgumentsHandler(), AssignHandler(),
                TagsHandler(), KeywordStatusHandler(), MessageHandler(), self]

class MessageHandler(_Handler):
    tag = 'msg'

    def end(self, elem, result):
        result.messages.create(elem.text or '',
                               elem.get('level', 'INFO'),
                               elem.get('html', 'no') == 'yes',
                               self._timestamp(elem, 'timestamp'))

class _StatusHandler(_Handler):
    tag = 'status'

    def _set_status(self, elem, result):
        result.status = elem.get('status', 'FAIL')

    def _set_message(self, elem, result):
        result.message = elem.text or ''

    def _set_times(self, elem, result):
        result.starttime = self._timestamp(elem, 'starttime')
        result.endtime = self._timestamp(elem, 'endtime')

class KeywordStatusHandler(_StatusHandler):

    def end(self, elem, result):
        self._set_status(elem, result)
        self._set_times(elem, result)
        if result.type == result.TEARDOWN_TYPE:
            self._set_message(elem, result)

class SuiteStatusHandler(_StatusHandler):

    def end(self, elem, result):
        self._set_message(elem, result)
        self._set_times(elem, result)

class TestStatusHandler(_StatusHandler):

    def end(self, elem, result):
        self._set_status(elem, result)
        self._set_message(elem, result)
        self._set_times(elem, result)

class DocHandler(_Handler):
    tag = 'doc'

    def end(self, elem, result):
        result.doc = elem.text or ''

class MetadataHandler(_Handler):
    tag = 'metadata'

    def _children(self):
        return [MetadataItemHandler()]

class MetadataItemHandler(_Handler):
    tag = 'item'

    def end(self, elem, result):
        result.metadata[elem.get('name', '')] = elem.text or ''

class TagsHandler(_Handler):
    tag = 'tags'

    def _children(self):
        return [TagHandler()]

class TagHandler(_Handler):
    tag = 'tag'

    def end(self, elem, result):
        result.tags.add(elem.text or '')

class AssignHandler(_Handler):
    tag = 'assign'

    def _children(self):
        return [AssignVarHandler()]

class AssignVarHandler(_Handler):
    tag = 'var'

    def end(self, elem, result):
        result.assign += (elem.text or '',)

class ArgumentsHandler(_Handler):
    tag = 'arguments'

    def _children(self):
        return [ArgumentHandler()]

class ArgumentHandler(_Handler):
    tag = 'arg'

    def end(self, elem, result):
        result.args += (elem.text or '',)

class ErrorsHandler(_Handler):
    tag = 'errors'

    def start(self, elem, result):
        return result.errors

    def _children(self):
        return [MessageHandler()]

class StatisticsHandler(_Handler):
    tag = 'statistics'

    def get_child_handler(self, elem):
        return self


text:
from aserializer.utils import py2to3

_serializer_registry = {}

class SerializerNotRegistered(Exception):
    message = 'Not in register.'

def register_serializer(name, cls):
    if name in _serializer_registry:
        return
    _serializer_registry[name] = cls

def get_serializer(serializer):
    if isinstance(serializer, py2to3.string):
        name = serializer
    elif isinstance(serializer, py2to3._class):
        name = serializer.__name__
    elif serializer is None:
        raise AttributeError('Can not get a serializer class from None.')
    else:
        raise AttributeError('Not a class.')
    if name in _serializer_registry:
        return _serializer_registry[name]
    raise SerializerNotRegistered()