text:
use super::*;
use beacon_chain::test_utils::{BeaconChainHarness, EphemeralHarnessType};
use state_processing::{
    per_block_processing, per_block_processing::errors::ExitInvalid, BlockProcessingError,
    BlockSignatureStrategy, ConsensusContext, VerifyBlockRoot,
};
use types::{BeaconBlock, BeaconState, Epoch, EthSpec, SignedBeaconBlock};

// Default validator index to exit.
pub const VALIDATOR_INDEX: u64 = 0;
// Epoch that the state will be transitioned to by default, equal to SHARD_COMMITTEE_PERIOD.
pub const STATE_EPOCH: Epoch = Epoch::new(256);

struct ExitTest {
    validator_index: u64,
    exit_epoch: Epoch,
    state_epoch: Epoch,
    #[allow(clippy::type_complexity)]
    state_modifier: Box<dyn FnOnce(&mut BeaconState<E>)>,
    #[allow(clippy::type_complexity)]
    block_modifier:
        Box<dyn FnOnce(&BeaconChainHarness<EphemeralHarnessType<E>>, &mut BeaconBlock<E>)>,
    #[allow(dead_code)]
    expected: Result<(), BlockProcessingError>,
}

impl Default for ExitTest {
    fn default() -> Self {
        Self {
            validator_index: VALIDATOR_INDEX,
            exit_epoch: STATE_EPOCH,
            state_epoch: STATE_EPOCH,
            state_modifier: Box::new(|_| ()),
            block_modifier: Box::new(|_, _| ()),
            expected: Ok(()),
        }
    }
}

impl ExitTest {
    async fn block_and_pre_state(self) -> (SignedBeaconBlock<E>, BeaconState<E>) {
        let harness = get_harness::<E>(
            self.state_epoch.start_slot(E::slots_per_epoch()),
            VALIDATOR_COUNT,
        )
        .await;
        let mut state = harness.get_current_state();
        (self.state_modifier)(&mut state);

        let block_modifier = self.block_modifier;
        let validator_index = self.validator_index;
        let exit_epoch = self.exit_epoch;

        let (signed_block, state) = harness
            .make_block_with_modifier(state.clone(), state.slot() + 1, |block| {
                harness.add_voluntary_exit(block, validator_index, exit_epoch);
                block_modifier(&harness, block);
            })
            .await;
        (signed_block, state)
    }

    fn process(
        block: &SignedBeaconBlock<E>,
        state: &mut BeaconState<E>,
    ) -> Result<(), BlockProcessingError> {
        let mut ctxt = ConsensusContext::new(block.slot());
        per_block_processing(
            state,
            block,
            BlockSignatureStrategy::VerifyIndividual,
            VerifyBlockRoot::True,
            &mut ctxt,
            &E::default_spec(),
        )
    }

    #[cfg(all(test, not(debug_assertions)))]
    async fn run(self) -> BeaconState<E> {
        let spec = &E::default_spec();
        let expected = self.expected.clone();
        assert_eq!(STATE_EPOCH, spec.shard_committee_period);

        let (block, mut state) = self.block_and_pre_state().await;

        let result = Self::process(&block, &mut state);

        assert_eq!(result, expected);

        state
    }

    async fn test_vector(self, title: String) -> TestVector {
        let (block, pre_state) = self.block_and_pre_state().await;
        let mut post_state = pre_state.clone();
        let (post_state, error) = match Self::process(&block, &mut post_state) {
            Ok(_) => (Some(post_state), None),
            Err(e) => (None, Some(format!("{:?}", e))),
        };

        TestVector {
            title,
            pre_state,
            block,
            post_state,
            error,
        }
    }
}

vectors_and_tests!(
    // Ensures we can process a valid exit,
    valid_single_exit,
    ExitTest::default(),
    // Tests three exits in the same block.
    valid_three_exits,
    ExitTest {
        block_modifier: Box::new(|harness, block| {
            harness.add_voluntary_exit(block, 1, STATE_EPOCH);
            harness.add_voluntary_exit(block, 2, STATE_EPOCH);
        }),
        ..ExitTest::default()
    },
    // Ensures that a validator cannot be exited twice in the same block.
    invalid_duplicate,
    ExitTest {
        block_modifier: Box::new(|_, block| {
            // Duplicate the exit
            let exit = block.body().voluntary_exits().get(0).unwrap().clone();
            block.body_mut().voluntary_exits_mut().push(exit).unwrap();
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 1,
            reason: ExitInvalid::AlreadyExited(0),
        }),
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // validator = state.validators[voluntary_exit.validator_index]
    // ```
    invalid_validator_unknown,
    ExitTest {
        block_modifier: Box::new(|_, block| {
            block
                .body_mut()
                .voluntary_exits_mut()
                .get_mut(0)
                .unwrap()
                .message
                .validator_index = VALIDATOR_COUNT as u64;
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::ValidatorUnknown(VALIDATOR_COUNT as u64),
        }),
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify exit has not been initiated
    // assert validator.exit_epoch == FAR_FUTURE_EPOCH
    // ```
    invalid_exit_already_initiated,
    ExitTest {
        state_modifier: Box::new(|state| {
            state.validators_mut().get_mut(0).unwrap().exit_epoch = STATE_EPOCH + 1;
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::AlreadyExited(0),
        }),
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify the validator is active
    // assert is_active_validator(validator, get_current_epoch(state))
    // ```
    invalid_not_active_before_activation_epoch,
    ExitTest {
        state_modifier: Box::new(|state| {
            state.validators_mut().get_mut(0).unwrap().activation_epoch =
                E::default_spec().far_future_epoch;
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::NotActive(0),
        }),
        ..ExitTest::default()
    },
    // Also tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify the validator is active
    // assert is_active_validator(validator, get_current_epoch(state))
    // ```
    invalid_not_active_after_exit_epoch,
    ExitTest {
        state_modifier: Box::new(|state| {
            state.validators_mut().get_mut(0).unwrap().exit_epoch = STATE_EPOCH;
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::NotActive(0),
        }),
        ..ExitTest::default()
    },
    // Ensures we can process an exit from genesis.
    valid_genesis_epoch,
    ExitTest {
        exit_epoch: Epoch::new(0),
        ..ExitTest::default()
    },
    // Ensures we can process an exit from the previous epoch.
    valid_previous_epoch,
    ExitTest {
        exit_epoch: STATE_EPOCH - 1,
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Exits must specify an epoch when they become valid; they are not
    // # valid before then
    // assert get_current_epoch(state) >= voluntary_exit.epoch
    // ```
    invalid_future_exit_epoch,
    ExitTest {
        exit_epoch: STATE_EPOCH + 1,
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::FutureEpoch {
                state: STATE_EPOCH,
                exit: STATE_EPOCH + 1,
            },
        }),
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify the validator has been active long enough
    // assert get_current_epoch(state) >= validator.activation_epoch + PERSISTENT_COMMITTEE_PERIOD
    // ```
    invalid_too_young_by_one_epoch,
    ExitTest {
        state_epoch: STATE_EPOCH - 1,
        exit_epoch: STATE_EPOCH - 1,
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::TooYoungToExit {
                current_epoch: STATE_EPOCH - 1,
                earliest_exit_epoch: STATE_EPOCH,
            },
        }),
        ..ExitTest::default()
    },
    // Also tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify the validator has been active long enough
    // assert get_current_epoch(state) >= validator.activation_epoch + PERSISTENT_COMMITTEE_PERIOD
    // ```
    invalid_too_young_by_a_lot,
    ExitTest {
        state_epoch: Epoch::new(0),
        exit_epoch: Epoch::new(0),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::TooYoungToExit {
                current_epoch: Epoch::new(0),
                earliest_exit_epoch: STATE_EPOCH,
            },
        }),
        ..ExitTest::default()
    },
    // Tests the following line of the spec:
    //
    // Spec v0.12.1
    //
    // ```ignore
    // # Verify signature
    // domain = get_domain(state, DOMAIN_VOLUNTARY_EXIT,
    // voluntary_exit.epoch)
    // signing_root = compute_signing_root(voluntary_exit, domain)
    // assert bls.Verify(validator.pubkey, signing_root,
    // signed_voluntary_exit.signature)
    // ```
    invalid_bad_signature,
    ExitTest {
        block_modifier: Box::new(|_, block| {
            // Shift the validator index by 1 so that it's mismatched from the key that was
            // used to sign.
            block
                .body_mut()
                .voluntary_exits_mut()
                .get_mut(0)
                .unwrap()
                .message
                .validator_index = VALIDATOR_INDEX + 1;
        }),
        expected: Err(BlockProcessingError::ExitInvalid {
            index: 0,
            reason: ExitInvalid::BadSignature,
        }),
        ..ExitTest::default()
    }
);

#[cfg(all(test, not(debug_assertions)))]
mod custom_tests {
    use super::*;

    fn assert_exited(state: &BeaconState<E>, validator_index: usize) {
        let spec = E::default_spec();

        let validator = &state.validators()[validator_index];
        assert_eq!(
            validator.exit_epoch,
            // This is correct until we exceed the churn limit. If that happens, we
            // need to introduce more complex logic.
            state.current_epoch() + 1 + spec.max_seed_lookahead,
            "exit epoch"
        );
        assert_eq!(
            validator.withdrawable_epoch,
            validator.exit_epoch + E::default_spec().min_validator_withdrawability_delay,
            "withdrawable epoch"
        );
    }

    #[tokio::test]
    async fn valid() {
        let state = ExitTest::default().run().await;
        assert_exited(&state, VALIDATOR_INDEX as usize);
    }

    #[tokio::test]
    async fn valid_three() {
        let state = ExitTest {
            block_modifier: Box::new(|harness, block| {
                harness.add_voluntary_exit(block, 1, STATE_EPOCH);
                harness.add_voluntary_exit(block, 2, STATE_EPOCH);
            }),
            ..ExitTest::default()
        }
        .run()
        .await;

        for i in &[VALIDATOR_INDEX, 1, 2] {
            assert_exited(&state, *i as usize);
        }
    }
}


text:
html-cr-exit
============

CR Exit Data

redpajama_set_name: RedPajamaGithub


text:
package com.wowwee.roboremote.robots;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.wowwee.bluetoothrobotcontrollib.BluetoothRobot;
import com.wowwee.bluetoothrobotcontrollib.roboremoteblue.RoboRemoteBlueFinder;
import com.wowwee.roboremotebluesampleproject.App;

import java.util.ArrayList;
import java.util.List;

public class BluetoothRobotFinder extends BaseRobotFinder {
    private boolean isEnableBluetooth = false;
    private BluetoothAdapter mBluetoothAdapter;

    private BluetoothRobotFinder() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // only for gingerbread and newer versions
            isEnableBluetooth = true;
        }

        if (isEnableBluetooth) {
            final BluetoothManager bluetoothManager = (BluetoothManager) App.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();

            // Set BluetoothAdapter to SnapPetsFinder
            RoboRemoteBlueFinder.getInstance().setBluetoothAdapter(mBluetoothAdapter);

            // Set Context to SnapPetsFinder
            RoboRemoteBlueFinder.getInstance().setApplicationContext(App.getContext());
            RoboRemoteBlueFinder.getInstance().setScanOptionsFlagMask(RoboRemoteBlueFinder.RPFScanOptionMask_FilterByProductId);
            RoboRemoteBlueFinder.getInstance().scanForRoboremoteBlue();

            App.getContext().registerReceiver(mRoboRemoteBlueFinderBroadcastReceiver, RoboRemoteBlueFinder.getRoboRemoteBlueFinderIntentFilter());
        }
    }

    static class BluetoothRobotFinderInstanceHolder {
        static BluetoothRobotFinder instance = new BluetoothRobotFinder();
    }

    public static BluetoothRobotFinder getInstance() {
        return BluetoothRobotFinderInstanceHolder.instance;
    }

    private final BroadcastReceiver mRoboRemoteBlueFinderBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (RoboRemoteBlueFinder.RoboRemoteBlueFinder_RobotsFound.equals(action)) {
                updateRobotsEvent();
            }
        }
    };

    @Override
    public void findAllRobots(RobotsFoundListener listener) {
        List<IRobot> robots = new ArrayList<IRobot>();
        if (isEnableBluetooth) {
            List<BluetoothRobot> listSnapPets = RoboRemoteBlueFinder.getInstance().getDevicesFound();
            for (BluetoothRobot bRobot : listSnapPets) {
                robots.add(com.wowwee.roboremote.robots.BluetoothRobot.Factory.getInstance().create(bRobot));
            }
            listener.onFound(robots);
        }
    }

    @Override
    public void startScan() {
        if (isEnableBluetooth) {
            for (Object obj : RoboRemoteBlueFinder.getInstance().getDevicesConnected()) {
                BluetoothRobot robot = (BluetoothRobot) obj;
                robot.disconnect();
            }
            App.getContext().registerReceiver(mRoboRemoteBlueFinderBroadcastReceiver, RoboRemoteBlueFinder.getRoboRemoteBlueFinderIntentFilter());
            RoboRemoteBlueFinder.getInstance().stopScanForRoboRemoteBlueRobots();
            RoboRemoteBlueFinder.getInstance().clearFoundRoboRemoteBlueRobotList();
            RoboRemoteBlueFinder.getInstance().scanForRoboremoteBlue();
        }
    }

    @Override
    public void stopScan() {
        if (isEnableBluetooth) {
            RoboRemoteBlueFinder.getInstance().stopScanForRoboRemoteBlueRobots();
            RoboRemoteBlueFinder.getInstance().clearFoundRoboRemoteBlueRobotList();
            App.getContext().unregisterReceiver(mRoboRemoteBlueFinderBroadcastReceiver);
        }
    }

    @Override
    public void rescan() {
        if (isEnableBluetooth) {
            RoboRemoteBlueFinder.getInstance().stopScanForRoboRemoteBlueRobots();
            RoboRemoteBlueFinder.getInstance().clearFoundRoboRemoteBlueRobotList();
            RoboRemoteBlueFinder.getInstance().scanForRoboremoteBlue();
        }
    }
}


text:
#ifndef __ASM_ARM_MACH_IRQ_H
#define __ASM_ARM_MACH_IRQ_H

#include <linux/irq.h>

struct seq_file;

/*
 * This is internal.  Do not use it.
 */
extern void (*init_arch_irq)(void);
extern void init_FIQ(void);
extern int show_fiq_list(struct seq_file *, void *);

/*
 * This is for easy migration, but should be changed in the source
 */
#define do_bad_IRQ(irq,desc)				\
do {							\
	spin_lock(&desc->lock);				\
	handle_bad_irq(irq, desc);			\
	spin_unlock(&desc->lock);			\
} while(0)

#endif


text:
package witai

type Context map[string]string

func (self Context) Get(key string) string {
	return self[key]
}

func (self Context) Add(key, value string) {
	self[key] = value
}

func (self Context) HasKey(key string) bool {
	return self[key] != ""
}


text:
export DEBIAN_FRONTEND=noninteractive

# Update the box
apt-get -qqy update
apt-get -qqy install linux-headers-$(uname -r) build-essential

# Install development tools
apt-get -qqy install zlib1g-dev libssl-dev libreadline-gplv2-dev \
  curl wget vim mc screen zsh unzip pbzip2 lsof htop iotop dstat \
  telnet tcpdump make python python-apt ruby \
  openjdk-7-jre

# Remove unneeded items
apt-get purge exim4 exim4-base

# Set up sudo
echo 'vagrant ALL=NOPASSWD:ALL' > /etc/sudoers.d/vagrant

# Disable barriers on root filesystem
sed -i 's/noatime,errors/barrier=0,noatime,errors/' /etc/fstab

# Tweak sshd to prevent DNS resolution (speed up logins)
echo 'UseDNS no' >> /etc/ssh/sshd_config

# Remove 5s grub timeout to speed up booting
cat <<EOF > /etc/default/grub
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.

GRUB_DEFAULT=0
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet"
GRUB_CMDLINE_LINUX="debian-installer=en_US"
EOF

update-grub


text:
import os
import tempfile
import hashlib
import mimetypes
from django.test import TestCase, Client
from django.test.utils import override_settings
from kolibri.auth.models import DeviceOwner
from kolibri.content.models import File, ContentNode
from kolibri.content.utils.paths import get_content_storage_file_path
from le_utils.constants import file_formats, format_presets

CONTENT_STORAGE_DIR_TEMP = tempfile.mkdtemp()

@override_settings(
    CONTENT_STORAGE_DIR=CONTENT_STORAGE_DIR_TEMP,
)
class DownloadContentTestCase(TestCase):
    """
    Test case for the downloadcontent endpoint.
    """

    def setUp(self):
        # create DeviceOwner to pass the setup_wizard middleware check
        DeviceOwner.objects.create(username='test-device-owner', password=123)

        self.client = Client()
        self.hash = hashlib.md5("DUMMYDATA".encode()).hexdigest()
        self.extension = file_formats.PDF
        self.filename = "{}.{}".format(self.hash, self.extension)
        self.title = "abc123!@#$%^&*();'[],./?><"
        self.contentnode = ContentNode(title=self.title)
        self.available = True
        self.preset = format_presets.DOCUMENT
        self.file = File(checksum=self.hash, extension=self.extension, available=self.available,
                         contentnode=self.contentnode, preset=self.preset)

        self.path = get_content_storage_file_path(self.filename)
        path_dir = os.path.dirname(self.path)
        if not os.path.exists(path_dir):
            os.makedirs(path_dir)
        tempfile = open(self.path, "w")
        tempfile.write("test")
        tempfile.close()

    def test_generate_download_filename(self):
        self.assertEqual(self.file.get_download_filename(), "abc123._Document.{}".format(self.extension))

    def test_generate_download_url(self):
        self.assertEqual(self.file.get_download_url(), "/downloadcontent/{}/{}".format(self.filename,
                                                                                self.file.get_download_filename()))

    def test_download_existing_file(self):
        response = self.client.get(self.file.get_download_url())
        self.assertEqual(response.status_code, 200)

    def test_download_non_existing_file(self):
        bad_download_url = self.file.get_download_url().replace(self.file.get_download_url()[25:25], "aaaaa")
        response = self.client.get(bad_download_url)
        self.assertEqual(response.status_code, 404)

    def test_download_headers(self):
        response = self.client.get(self.file.get_download_url())
        self.assertEqual(response['Content-Type'], mimetypes.guess_type(self.filename)[0])
        self.assertEqual(response['Content-Disposition'], 'attachment;')
        self.assertEqual(response['Content-Length'], str(os.path.getsize(self.path)))


text:
require File.expand_path('../test_helper', __FILE__)

class TestContributionActivation < Minitest::Test
  FIXTURE = API_FIXTURES.fetch("contribution_activation")
  ORGANIZATION_ID = "1234"
  CONTRIBUTION_PRODUCT_ID = "9bd2876a-c423-4a2a-8c25-bff66dde76fe"
  CONTRIBUTION_ACTIVATION_ID = "90d20db5-6bdd-466f-a0ec-17c6271a0a2a"

  def test_retrieve()
    stub_request(:get, /\/contributionActivations\/#{CONTRIBUTION_ACTIVATION_ID}/).
      to_return(status: 200, body: FIXTURE.to_json)

    ca = MyJohnDeere::ContributionActivation.retrieve(default_access_token,
      CONTRIBUTION_ACTIVATION_ID)
    assert_equal CONTRIBUTION_ACTIVATION_ID, ca.id
    assert_equal CONTRIBUTION_PRODUCT_ID, ca.contribution_product_id
    assert_equal "ACTIVATED", ca.activation_status
  end

  def test_create
    expected_body = {"@type"=>"ContributionActivation",
 "activationStatus"=>"ACTIVATED",
 "links"=>
  [{"@type"=>"Link",
    "rel"=>"ContributionProduct",
    "uri"=>
     "https://sandboxapi.deere.com/platform/contributionProducts/#{CONTRIBUTION_PRODUCT_ID}"}]}.to_json()
    stub_request(:post, /contributionActivations/).
      with(body: expected_body,
      headers: {'Accept'=>'application/vnd.deere.axiom.v3+json', 'Content-Length'=>expected_body.length, 'Content-Type'=>'application/vnd.deere.axiom.v3+json'}).
      to_return(status: 201, headers: {"Location"=>"https://sandboxapi.deere.com/platform/contributionActivations/#{CONTRIBUTION_ACTIVATION_ID}"})
    response = MyJohnDeere::ContributionActivation.create(default_access_token,
      ORGANIZATION_ID,
      CONTRIBUTION_PRODUCT_ID,
      activated: true
    )
    assert_equal CONTRIBUTION_ACTIVATION_ID, response.id
  end
end


text:
Public

Public on the web

Private

<?php

	//$buzz = createBuzz();

	// Set the default value for a new post to be False
	//$newPost = false;
	//if (isset($_POST['buzzPostContent']))
	//{
	//	$object = new buzzObject($_POST['buzzPostContent']);
	//	$post = buzzPost::createPost($object);
	//	$newPost = $buzz->createPost($post);
	//}

	// My oAuth Key
	$oAuthKey = 'buzz.hekainteractive.com';

	// My API key
	$apiKey = 'AIzaSyBl28hAJjlt9CU10uSnPaKEGBAbx_PmO18';

	// Get the users id
	//** Find out how to get the users ID
	// Until I can figure out how to get the logged in users ID, I will use the default @me
	//userId = userId;
	$userId = '@me';

	// Send the POST request to this address
	$postAddr = 'https://www.googleapis.com/buzz/v1/activities/' . $userId . '/@self?' . $apiKey . '&alt=json';

	// Default new post form
	echo "

				<form action=\"" . $postAddr . "\" method=\"post\">
					Enter post text:

					<textarea name=\"buzzPostContent\" class=\"ui-corner-all\"></textarea>

					<input type=\"submit\" value=\"Create post\">
				</form>

";

		// If the user creates a new post, let them know that the new post has been created
		//if ($newPost)
		//{
		//	echo "
New post has been created:
";
		//	displayBuzzPost($buzz, $newPost);
		//}
	echo "
\n";
?>

Attach: Link Photo

<?php
 /* // the post to create
    $post = array(
        'data' => array(
            'object' => array('type' => 'note',
                'content' => '$_POST("buzzPostContent")')));

// create an activity
    $activity = $buzz->insertActivities('@self', $post); */
?>


text:
var _ = require('underscore');
var cdb = require('cartodb-deep-insights.js');
var createTextLabelsTabPane = require('../../../../../javascripts/cartodb3/components/tab-pane/create-text-labels-tab-pane');

describe('components/tab-pane/create-text-labels-tab-pane', function () {
  beforeEach(function () {
    this.items = [{
      selected: false,
      label: 'label one',
      createContentView: function () {
        return new cdb.core.View();
      }
    }, {
      selected: false,
      label: 'label two',
      createContentView: function () {
        return new cdb.core.View();
      }
    }];
  });

  it('should create view', function () {
    var view = createTextLabelsTabPane(this.items);
    expect(view).toEqual(jasmine.any(cdb.core.View));
    expect(view.collection.size()).toEqual(2);

    view.render();
    expect(_.size(view._subviews)).toEqual(3);
  });

  it('should add the labels', function () {
    var view = createTextLabelsTabPane(this.items);
    view.render();
    expect(view.$el.html()).toContain('label one');
    expect(view.$el.html()).toContain('label two');
  });

  it('should throw error if label is not provided', function () {
    var items = _.clone(this.items);
    delete items[0].label;
    expect(function () { createTextLabelsTabPane(items); }).toThrow(new Error('label should be provided'));
  });

  it('should throw error if contentView is not provided', function () {
    var items = _.clone(this.items);
    delete items[0].createContentView;
    expect(function () { createTextLabelsTabPane(items); }).toThrow(new Error('createContentView should be provided'));
  });

  it('should allow to set custom options for the pane and its items', function () {
    var view = createTextLabelsTabPane(this.items, {
      tabPaneOptions: {
        className: 'MyCoolLabelTabPane',
        tabPaneItemOptions: {
          tagName: 'li',
          className: 'CDB-NavMenu-Item'
        }
      },
      tabPaneItemLabelOptions: {
        tagName: 'button',
        className: 'CDB-NavMenu-Link'
      }
    });
    view.render();
    expect(view.$el.hasClass('MyCoolLabelTabPane')).toBeTruthy();
    expect(view.$el.find('li.CDB-NavMenu-Item').length).toBe(2);
    expect(view.$el.find('button.CDB-NavMenu-Link').length).toBe(2);
  });
});


text:
import {browserOnly, nodeOnly} from '@webex/test-helper-mocha';
import {assert} from '@webex/test-helper-chai';
import testUsers from '@webex/test-helper-test-users';
import WebexCore, {filterScope} from '@webex/webex-core';
import refreshCallback from '@webex/test-helper-refresh-callback';

/* eslint camelcase: [0] */

describe('webex-core', () => {
  describe('Credentials', () => {
    describe('Token', () => {
      let webex, user;

      before(() => testUsers.create({count: 1})
        .then(([u]) => {
          user = u;
        }));

      describe('#downscope()', () => {
        it('retrieves an access token with a subset of scopes', () => {
          webex = new WebexCore({credentials: user.token});
          const allScope = webex.credentials.config.scope;
          const apiScope = filterScope('spark:kms', allScope);

          return webex.credentials.supertoken.downscope('spark:kms')
            .then((downscopedToken) => downscopedToken.validate())
            .then((details) => assert.deepEqual(details.scope, ['spark:kms']))
            .then(() => webex.credentials.supertoken.downscope(apiScope))
            .then((downscopedToken) => downscopedToken.validate())
            .then((details) => assert.sameMembers(details.scope, apiScope.split(' ')))
            .then(() => assert.isRejected(webex.credentials.supertoken.downscope(allScope), /token: scope reduction requires a reduced scope/));
        });
      });

      describe('#refresh()', () => {
        nodeOnly(it)('refreshes the token, returning a new Token instance', () => {
          webex = new WebexCore({credentials: user.token});

          return webex.credentials.supertoken.refresh()
            .then((token2) => {
              assert.notEqual(token2.access_token, webex.credentials.supertoken.access_token);
              assert.equal(token2.refresh_token, webex.credentials.supertoken.refresh_token);
            });
        });

        browserOnly(it)('refreshes the token, returning a new Token instance', () => {
          webex = new WebexCore({
            credentials: user.token,
            config: {
              credentials: {
                refreshCallback
              }
            }
          });

          return webex.credentials.supertoken.refresh()
            .then((token2) => {
              assert.notEqual(token2.access_token, webex.credentials.supertoken.access_token);
              assert.equal(token2.refresh_token, webex.credentials.supertoken.refresh_token);
            });
        });
      });

      describe('#validate()', () => {
        it('shows the token\'s scopes', () => {
          webex = new WebexCore({credentials: user.token});

          return webex.credentials.supertoken.validate()
            .then((details) => {
              const detailScope = details.scope.sort();
              const localScope = webex.credentials.config.scope.split(' ').sort();

              assert.sameMembers(detailScope, localScope);
              assert.lengthOf(detailScope, localScope.length);
              assert.equal(details.clientId, webex.credentials.config.client_id);
            });
        });
      });

      // These tests have a bit of shared state, so revoke() needs to go last
      describe('#revoke()', () => {
        it('revokes the token', () => {
          webex = new WebexCore({credentials: user.token});

          return webex.credentials.supertoken.revoke()
            .then(() => {
              assert.isUndefined(webex.credentials.supertoken.access_token);
              assert.isDefined(webex.credentials.supertoken.refresh_token);
              assert.isUndefined(webex.credentials.supertoken.expires_in);
            });
        });
      });
    });
  });
});


text:
<html>
<head>
	<meta charset="utf-8"/>
	<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="sidekick.js"></script>
	<script type="text/javascript" src="datetime.js"></script>
	<script type="text/javascript" src="stopwatch.js"></script>
	<script type="text/javascript" src="background.js"></script>
</head>

</html>


text:
/**
 * The Prototype thing always caused confusion with me so I sat down and
 * figured out a way that works for me.
 * Using almost pure javascript and a little helping method I want to
 * outline here how inheritance is done in the libraries of this project.
 * It was very important for me to be able to write the bulk of the
 * (class)-definitions in the {}-object-literal form. Because this, I
 * think, is better to read.
 *
 * There could be more magic with some kind of wrapping method, but I like
 * the verbosity of this approach and I see no significant improvement
 * syntaxwise when wrapping this together.
 */

/**
 * Set the properties of the (propably empty) prototype object of your
 * constructor.
 */
function enhance(constructor, blueprint)
{
    for(var i in blueprint)
    {
        var getter = blueprint.__lookupGetter__(i),
            setter = blueprint.__lookupSetter__(i);
        if ( getter || setter ) {
            if ( getter )
                constructor.prototype.__defineGetter__(i, getter);
            if ( setter )
                constructor.prototype.__defineSetter__(i, setter);
        } else
            constructor.prototype[i] = blueprint[i];
    };
}

/*****************************
 * Abstract Object Conctructor
 *****************************/
/*constructor*/
Abstract = function()
{
    /**
     * this is a dirty trick: only init (build state) if this is ment as
     * constructor not as a prototype for inheritance. This is the main
     * problem with the prototype thing in javascript, i think: the double
     * usage of constructors in different contexts. just be aware of it
     **/
    if(arguments.length)
        this.__init__.apply(this, arguments);
};
/*definition*/
enhance(Abstract, {
    __init__: function(name)
    {
        this.counter = 0;
        this.name = name;
    },
    set name(val)
    {
        this._name = val + ':';
    },
    get name()
    {
        return '!' + this._name;
    },
    do: function()
    {
        this.count();
        console.log(this.name, this.counter, 'not implemented');
    },
    count: function()
    {
        this.counter++;
    }
});

/*****************************
 * General Object Conctructor
 *****************************/
/*constructor*/
General = function(name)
{
    /*building state with Abstract constructor*/
    Abstract.call(this, name);
};
/*inheritance*/
General.prototype = new Abstract;
/*definition*/
enhance(General,
{
    do: function()
    {
        this.count();
        console.log(this.name, this.counter);
    },
});

/*****************************
 * Special Object Conctructor
 *****************************/
/*constructor*/
Special = function(name)
{
    /*building state with General constructor*/
    General.call(this, name);
};
/*inheritance*/
Special.prototype = new General;
/*definition*/
enhance(Special,
{
    do: function()
    {
        this.count();
        console.log(this.name, this.counter, 'special');
    }
});

window.onload = function(){
    console.log('init');

    pens = [
        new Abstract('abstract A'),
        new Abstract('abstract B'),
        new General('general A'),
        new General('general B'),
        new Special('special A'),
        new Special('special B'),
    ];
    for (var i = 0; i < pens.length; i++) {
        pens[i].do();
    }
    for (var i = 0; i < pens.length; i++) {
        pens[i].do();
    }

    console.log((pens[0] instanceof Abstract));
    console.log((pens[2] instanceof Abstract));
    console.log((pens[2] instanceof Special));
    console.log((pens[2] instanceof General));

    /*
    expected:
        init
        !abstract A: 1 not implemented
        !abstract B: 1 not implemented
        !general A: 1
        !general B: 1
        !special A: 1 special
        !special B: 1 special
        !abstract A: 2 not implemented
        !abstract B: 2 not implemented
        !general A: 2
        !general B: 2
        !special A: 2 special
        !special B: 2 special
        true
        true
        false
        true
    */
};


text:
package com.cloudray.scalapress.plugin.attachment

import javax.persistence.{ElementCollection, Table, Entity}
import com.cloudray.scalapress.section.Section
import com.cloudray.scalapress.media.AssetStore
import com.cloudray.scalapress.util.Scalate
import scala.beans.BeanProperty
import java.util
import scala.collection.JavaConverters._
import com.cloudray.scalapress.framework.ScalapressRequest

/** @author Stephen Samuel */
@Entity
@Table(name = "blocks_attachments")
class AttachmentSection extends Section {

  @ElementCollection
  @BeanProperty
  var attachments: java.util.List[Attachment] = new util.ArrayList[Attachment]()

  override def desc: String = "Shows attachments for a folder or object"
  override def backoffice: String = "/backoffice/plugin/attachment/section/" + id

  def render(sreq: ScalapressRequest): Option[String] = {
    val assetStore = sreq.context.assetStore
    if (attachments.isEmpty) None
    else Some(html(attachments.asScala, assetStore))
  }

  def html(attachments: Seq[Attachment], assetStore: AssetStore): String = {
    val start = "
"
    val body = renderAttachments(attachments, assetStore)
    val end = "
"
    start + body + end
  }

  def renderAttachments(attachments: Seq[Attachment], assetStore: AssetStore): String =
    attachments.map(renderAttachment(_, assetStore)).mkString("\n")

  def getLink(attachment: Attachment, store: AssetStore): String = store.link(attachment.assetKey)

  def renderAttachment(attachment: Attachment, store: AssetStore): String = {
    val link = getLink(attachment, store)
    Scalate.layout("/com/cloudray/scalapress/plugin/attachment/attachment.ssp",
      Map("description" -> attachment.description, "link" -> link))
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Modern Business - Start Bootstrap Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                itKonekt

                        Home

                        Partners

                        News

                        Blog

                        Contact

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Registration

                            Login

                            New account

                                    <form class="form-horizontal" role="form">

                                            <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username or email">

                                            <input id="login-password" type="password" class="form-control" name="password" placeholder="password">

                                                <input type="checkbox" value="remember-me">Remember me

                                            <button class="btn btn-lg btn-primary btn-block" type="submit">
                                                Sign in
                                            </button>

                                    </form>

                                        Forgot the password?

                                    <form>

                                            Name
                                            <input type="text" class="form-control" id="name" placeholder="">

                                            Password
                                            <input type='password' class='form-control' id='password' placeholder='*******' />

                                            Email
                                            <input type='email' class='form-control' id='email' placeholder='email@some.com' />

                                        <button type="submit" class="btn btn-success pull-right">Create account</button>
                                    </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Važna napomena

                    Sajt predstavlja kopiju sajta itKonekt.

Blog Post
                    by Start Bootstrap

Home

Blog Post

 Posted on August 24, 2013 at 9:00 PM

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ducimus, vero, obcaecati, aut, error quam sapiente nemo saepe quibusdam sit excepturi nam quia corporis eligendi eos magni recusandae laborum minus inventore?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos, doloribus, dolorem iusto blanditiis unde eius illum consequuntur neque dicta incidunt ullam ea hic porro optio ratione repellat perspiciatis. Enim, iure!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, nostrum, aliquid, animi, ut quas placeat totam sunt tempora commodi nihil ullam alias modi dicta saepe minima ab quo voluptatem obcaecati?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum, dolor quis. Sunt, ut, explicabo, aliquam tenetur ratione tempore quidem voluptates cupiditate voluptas illo saepe quaerat numquam recusandae? Qui, necessitatibus, est!

Leave a Comment:

                    <form role="form">

                            <textarea class="form-control" rows="3"></textarea>

                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>

Start Bootstrap
                            August 25, 2014 at 9:30 PM

                        Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Start Bootstrap
                            August 25, 2014 at 9:30 PM

                        Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Nested Start Bootstrap
                                    August 25, 2014 at 9:30 PM

                                Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Blog Search

                        <input type="text" class="form-control">

                            <button class="btn btn-default" type="button"></button>

Blog Categories

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Category Name

Side Widget Well

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.

Copyright © itKonekt 2015


text:
<?php
class Required extends Requirement {

    public function check($arr, $name, $prev = null) {
        if(!isset($arr[$name]))
            throw new MyHttpException(400);
        return $arr[$name];
    }
}


text:
<?php

namespace Logger\Loggers\FileLogger;

use Logger\LoggerException;

/**
 * Description of FileLoggerException
 *
 * @author Zeakis George <zeageorge@gmail.com>
 */
class FileLoggerException extends LoggerException
{

}