text:
package org.elasticsearch.index.get;

import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.RandomObjects;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentHelper.toXContent;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.elasticsearch.index.get.DocumentFieldTests.randomDocumentField;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertToXContentEquivalent;

public class GetResultTests extends ESTestCase {

    public void testToAndFromXContent() throws Exception {
        XContentType xContentType = randomFrom(XContentType.values());
        Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
        GetResult getResult = tuple.v1();
        GetResult expectedGetResult = tuple.v2();
        boolean humanReadable = randomBoolean();
        BytesReference originalBytes = toShuffledXContent(getResult, xContentType, ToXContent.EMPTY_PARAMS, humanReadable, "_source");
        //test that we can parse what we print out
        GetResult parsedGetResult;
        try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
            parsedGetResult = GetResult.fromXContent(parser);
            assertNull(parser.nextToken());
        }
        assertEquals(expectedGetResult, parsedGetResult);
        //print the parsed object out and test that the output is the same as the original output
        BytesReference finalBytes = toXContent(parsedGetResult, xContentType, humanReadable);
        assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
        //check that the source stays unchanged, no shuffling of keys nor anything like that
        assertEquals(expectedGetResult.sourceAsString(), parsedGetResult.sourceAsString());
    }

    public void testToXContent() throws IOException {
        {
            GetResult getResult = new GetResult("index", "id", 0, 1, 1, true, new BytesArray("{ \"field1\" : " +
                    "\"value1\", \"field2\":\"value2\"}"), singletonMap("field1", new DocumentField("field1",
                    singletonList("value1"))), singletonMap("field1", new DocumentField("metafield",
                            singletonList("metavalue"))));
            String output = Strings.toString(getResult);
            assertEquals("{\"_index\":\"index\",\"_id\":\"id\",\"_version\":1,\"_seq_no\":0,\"_primary_term\":1," +
                "\"metafield\":\"metavalue\",\"found\":true,\"_source\":{ \"field1\" : \"value1\", \"field2\":\"value2\"}," +
                "\"fields\":{\"field1\":[\"value1\"]}}", output);
        }
        {
            GetResult getResult = new GetResult("index", "id", UNASSIGNED_SEQ_NO, 0, 1, false, null, null, null);
            String output = Strings.toString(getResult);
            assertEquals("{\"_index\":\"index\",\"_id\":\"id\",\"found\":false}", output);
        }
    }

    public void testToAndFromXContentEmbedded() throws Exception {
        XContentType xContentType = randomFrom(XContentType.values());
        Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
        GetResult getResult = tuple.v1();
        // We don't expect to retrieve the index/type/id of the GetResult because they are not rendered
        // by the toXContentEmbedded method.
        GetResult expectedGetResult = new GetResult(null, null, tuple.v2().getSeqNo(), tuple.v2().getPrimaryTerm(), -1,
                tuple.v2().isExists(), tuple.v2().sourceRef(), tuple.v2().getDocumentFields(),
            tuple.v2().getMetadataFields());

        boolean humanReadable = randomBoolean();
        BytesReference originalBytes = toXContentEmbedded(getResult, xContentType, humanReadable);

        // Test that we can parse the result of toXContentEmbedded()
        GetResult parsedEmbeddedGetResult;
        try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            parsedEmbeddedGetResult = GetResult.fromXContentEmbedded(parser);
            assertNull(parser.nextToken());
        }
        assertEquals(expectedGetResult, parsedEmbeddedGetResult);
        //print the parsed object out and test that the output is the same as the original output
        BytesReference finalBytes = toXContentEmbedded(parsedEmbeddedGetResult, xContentType, humanReadable);
        assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
        //check that the source stays unchanged, no shuffling of keys nor anything like that
        assertEquals(expectedGetResult.sourceAsString(), parsedEmbeddedGetResult.sourceAsString());
    }

    public void testToXContentEmbedded() throws IOException {
        Map<String, DocumentField> fields = new HashMap<>();
        fields.put("foo", new DocumentField("foo", singletonList("bar")));
        fields.put("baz", new DocumentField("baz", Arrays.asList("baz_0", "baz_1")));

        GetResult getResult = new GetResult("index", "id", 0, 1, 2, true,
                new BytesArray("{\"foo\":\"bar\",\"baz\":[\"baz_0\",\"baz_1\"]}"), fields, null);

        BytesReference originalBytes = toXContentEmbedded(getResult, XContentType.JSON, false);
        assertEquals("{\"_seq_no\":0,\"_primary_term\":1,\"found\":true,\"_source\":{\"foo\":\"bar\",\"baz\":[\"baz_0\",\"baz_1\"]}," +
                "\"fields\":{\"foo\":[\"bar\"],\"baz\":[\"baz_0\",\"baz_1\"]}}", originalBytes.utf8ToString());
    }

    public void testToXContentEmbeddedNotFound() throws IOException {
        GetResult getResult = new GetResult("index", "id", UNASSIGNED_SEQ_NO, 0, 1, false, null, null, null);

        BytesReference originalBytes = toXContentEmbedded(getResult, XContentType.JSON, false);
        assertEquals("{\"found\":false}", originalBytes.utf8ToString());
    }

    public void testGetSourceAsBytes() {
        XContentType xContentType = randomFrom(XContentType.values());
        Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
        GetResult getResult = tuple.v1();
        if (getResult.isExists() && getResult.isSourceEmpty() == false) {
            assertNotNull(getResult.sourceRef());
        } else {
            assertNull(getResult.sourceRef());
        }
    }

    public void testEqualsAndHashcode() {
        checkEqualsAndHashCode(randomGetResult(XContentType.JSON).v1(), GetResultTests::copyGetResult, GetResultTests::mutateGetResult);
    }

    public static GetResult copyGetResult(GetResult getResult) {
        return new GetResult(getResult.getIndex(), getResult.getId(),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(),
            getResult.isExists(), getResult.internalSourceRef(), getResult.getDocumentFields(), getResult.getMetadataFields());
    }

    public static GetResult mutateGetResult(GetResult getResult) {
        List<Supplier<GetResult>> mutations = new ArrayList<>();
        mutations.add(() -> new GetResult(randomUnicodeOfLength(15), getResult.getId(),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(),
                getResult.isExists(), getResult.internalSourceRef(), getResult.getFields(), null));
        mutations.add(() -> new GetResult(getResult.getIndex(), randomUnicodeOfLength(15),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(),
            getResult.isExists(), getResult.internalSourceRef(), getResult.getFields(), null));
        mutations.add(() -> new GetResult(getResult.getIndex(), getResult.getId(),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), randomNonNegativeLong(),
            getResult.isExists(), getResult.internalSourceRef(), getResult.getFields(), null));
        mutations.add(() -> new GetResult(getResult.getIndex(), getResult.getId(),
            getResult.isExists() ? UNASSIGNED_SEQ_NO : getResult.getSeqNo(),
            getResult.isExists() ? 0 : getResult.getPrimaryTerm(),
            getResult.getVersion(), getResult.isExists() == false, getResult.internalSourceRef(), getResult.getFields(), null));
        mutations.add(() -> new GetResult(getResult.getIndex(), getResult.getId(),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(), getResult.isExists(),
            RandomObjects.randomSource(random()), getResult.getFields(), null));
        mutations.add(() -> new GetResult(getResult.getIndex(), getResult.getId(),
            getResult.getSeqNo(), getResult.getPrimaryTerm(), getResult.getVersion(),
                getResult.isExists(), getResult.internalSourceRef(), randomDocumentFields(XContentType.JSON).v1(), null));
        return randomFrom(mutations).get();
    }

    public static Tuple<GetResult, GetResult> randomGetResult(XContentType xContentType) {
        final String index = randomAlphaOfLengthBetween(3, 10);
        final String id = randomAlphaOfLengthBetween(3, 10);
        final long version;
        final long seqNo;
        final long primaryTerm;
        final boolean exists;
        BytesReference source = null;
        Map<String, DocumentField> fields = null;
        Map<String, DocumentField> expectedFields = null;
        Map<String, DocumentField> metaFields = null;
        Map<String, DocumentField> expectedMetaFields = null;
        if (frequently()) {
            version = randomNonNegativeLong();
            seqNo = randomNonNegativeLong();
            primaryTerm = randomLongBetween(1, 100);
            exists = true;
            if (frequently()) {
                source = RandomObjects.randomSource(random());
            }
            if (randomBoolean()) {
                Tuple<Map<String, DocumentField>, Map<String, DocumentField>> tuple = randomDocumentFields(xContentType);
                fields = new HashMap<>();
                metaFields = new HashMap<>();
                GetResult.splitFieldsByMetadata(tuple.v1(), fields, metaFields);

                expectedFields = new HashMap<>();
                expectedMetaFields = new HashMap<>();
                GetResult.splitFieldsByMetadata(tuple.v2(), expectedFields, expectedMetaFields);
            }
        } else {
            seqNo = UNASSIGNED_SEQ_NO;
            primaryTerm = UNASSIGNED_PRIMARY_TERM;
            version = -1;
            exists = false;
        }
        GetResult getResult = new GetResult(index, id, seqNo, primaryTerm, version, exists, source, fields, metaFields);
        GetResult expectedGetResult = new GetResult(index, id, seqNo, primaryTerm, version, exists, source,
            expectedFields, expectedMetaFields);
        return Tuple.tuple(getResult, expectedGetResult);
    }

    public static Tuple<Map<String, DocumentField>,Map<String, DocumentField>> randomDocumentFields(XContentType xContentType) {
        int numFields = randomIntBetween(2, 10);
        Map<String, DocumentField> fields = new HashMap<>(numFields);
        Map<String, DocumentField> expectedFields = new HashMap<>(numFields);
        while (fields.size() < numFields) {
            Tuple<DocumentField, DocumentField> tuple = randomDocumentField(xContentType);
            DocumentField getField = tuple.v1();
            DocumentField expectedGetField = tuple.v2();
            if (fields.putIfAbsent(getField.getName(), getField) == null) {
                assertNull(expectedFields.putIfAbsent(expectedGetField.getName(), expectedGetField));
            }
        }
        return Tuple.tuple(fields, expectedFields);
    }

    private static BytesReference toXContentEmbedded(GetResult getResult, XContentType xContentType, boolean humanReadable)
            throws IOException {
        return XContentHelper.toXContent(getResult::toXContentEmbedded, xContentType, humanReadable);
    }
}


text:
// @inheritedComponent Paper

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import { capitalize } from '../utils/helpers';
import Paper from '../Paper';

export const styles = theme => {
  const backgroundColorDefault =
    theme.palette.type === 'light' ? theme.palette.grey[100] : theme.palette.grey[900];

  return {
    root: {
      display: 'flex',
      flexDirection: 'column',
      width: '100%',
      boxSizing: 'border-box', // Prevent padding issue with the Modal and fixed positioned AppBar.
      zIndex: theme.zIndex.appBar,
      flexShrink: 0,
    },
    positionFixed: {
      position: 'fixed',
      top: 0,
      left: 'auto',
      right: 0,
    },
    positionAbsolute: {
      position: 'absolute',
      top: 0,
      left: 'auto',
      right: 0,
    },
    positionSticky: {
      position: 'sticky',
      top: 0,
      left: 'auto',
      right: 0,
    },
    positionStatic: {
      position: 'static',
    },
    colorDefault: {
      backgroundColor: backgroundColorDefault,
      color: theme.palette.getContrastText(backgroundColorDefault),
    },
    colorPrimary: {
      backgroundColor: theme.palette.primary.main,
      color: theme.palette.primary.contrastText,
    },
    colorSecondary: {
      backgroundColor: theme.palette.secondary.main,
      color: theme.palette.secondary.contrastText,
    },
  };
};

function AppBar(props) {
  const { children, classes, className: classNameProp, color, position, ...other } = props;

  const className = classNames(
    classes.root,
    classes[`position${capitalize(position)}`],
    {
      [classes[`color${capitalize(color)}`]]: color !== 'inherit',
      'mui-fixed': position === 'fixed', // Useful for the Dialog
    },
    classNameProp,
  );

  return (
    <Paper square component="header" elevation={4} className={className} {...other}>
      {children}
    </Paper>
  );
}

AppBar.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node.isRequired,
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The color of the component. It supports those theme colors that make sense for this component.
   */
  color: PropTypes.oneOf(['inherit', 'primary', 'secondary', 'default']),
  /**
   * The positioning type. The behavior of the different options is described
   * [here](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning).
   * Note: `sticky` is not universally supported and will fall back to `static` when unavailable.
   */
  position: PropTypes.oneOf(['fixed', 'absolute', 'sticky', 'static']),
};

AppBar.defaultProps = {
  color: 'primary',
  position: 'fixed',
};

export default withStyles(styles, { name: 'MuiAppBar' })(AppBar);

redpajama_set_name: RedPajamaGithub


text:
package org.rogerfs.common.store

object Path {
  private val PATH_REG_EXP = """^(?:\/[A-Za-z0-9_\-\.]+)+\/?$"""

  def getPath(filePath: String): IPath = {
    if (isValid(filePath)) {
      val path = normalize(filePath)
      val nodes = path.split("/").dropWhile(str => str.isEmpty)
      val name = nodes.last
      val parent = nodes.init.mkString("/", "/", "")
      new InternalPath(path, name, parent)
    } else {
      throw new InvalidPathException("PATH is not valid!!")
    }
  }

  def normalize(filePath: String): String = {
    val lowercaseFilePath = filePath.toLowerCase

    val removeSlashFilePath = if (lowercaseFilePath.last == '/') {
      lowercaseFilePath.substring(0, lowercaseFilePath.length - 1)
    } else {
      lowercaseFilePath
    }

    removeSlashFilePath
  }

  def isValid(filePath: String): Boolean = {
    PATH_REG_EXP.r.findFirstIn(filePath).isDefined
  }

  class InternalPath(val path: String, val name: String, val parent: String) extends IPath {
    override def getName: String = name

    override def getParent: String = parent

    override def getPath: String = path

    override def toString: String = path
  }

}


text:
class String
  def secure_compare(other)
    return false unless self.class === other
    return false unless self.bytesize == other.bytesize

    l = self.unpack "C#{self.bytesize}"
    res = 0
    other.each_byte { |byte| res |= byte ^ l.shift }
    res == 0
  end
end


text:
package com.morningstar.swagger;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.wordnik.swagger.model.ApiInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;

@Configuration
@EnableSwagger //Loads the spring beans required by the framework
public class RecordShopSwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    /**
     * Required to autowire SpringSwaggerConfig
     */
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc framework - allowing for multiple
     * swagger groups i.e. same code base multiple swagger resource listings.
     */
    @Bean //Don't forget the @Bean annotation
    public SwaggerSpringMvcPlugin swaggerSpringMvcPlugin(){
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .genericModelSubstitutes(ResponseEntity.class)
                .build();
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                "Morningstar Data API v2.0",
                "My Apps API Description",
                "My Apps API terms of service",
                "My Apps API Contact Email",
                "My Apps API Licence Type",
                "My Apps API License URL"
        );
        return apiInfo;
    }
}


text:
package com.pardot.rhombus;

import com.pardot.rhombus.util.UuidUtil;
import org.junit.Test;
import static org.junit.Assert.*;

import java.util.UUID;

/**
 * Pardot, an ExactTarget company
 * User: Michael Frank
 * Date: 5/6/13
 */
public class UuidUtilTest {

	@Test
	public void testUuidUtil() {
		int namespace = 47;
		long name = 722338;
		UUID namespaceUuid = UuidUtil.namespaceUUID(namespace, name);

        assertEquals(namespace, UuidUtil.namespaceFromUUID(namespaceUuid).intValue());
        assertEquals(name, UuidUtil.nameFromUUID(namespaceUuid).longValue());
	}

    @Test
    public void testMaxValues() {
        int namespace = 0xffffffff;
        long name = 0xffffffffffffffffL;
        UUID namespaceUuid = UuidUtil.namespaceUUID(namespace, name);

        assertEquals(namespace, UuidUtil.namespaceFromUUID(namespaceUuid).intValue());
        assertEquals(name, UuidUtil.nameFromUUID(namespaceUuid).longValue());
    }

    @Test
    public void testMinValues() {
        int namespace = 1;
        long name = 1;
        UUID namespaceUuid = UuidUtil.namespaceUUID(namespace, name);

        assertEquals(namespace, UuidUtil.namespaceFromUUID(namespaceUuid).intValue());
        assertEquals(name, UuidUtil.nameFromUUID(namespaceUuid).longValue());
    }

    @Test
    public void testNonUniformValues() {
        int namespace = 0x12345678;
        long name = 0x1234567890ABCDEFL;
        UUID namespaceUuid = UuidUtil.namespaceUUID(namespace, name);

        assertEquals(namespace, UuidUtil.namespaceFromUUID(namespaceUuid).intValue());
        assertEquals(name, UuidUtil.nameFromUUID(namespaceUuid).longValue());
    }

    @Test
    public void testNonUniformValuesInTheOtherDirection() {
        int namespace = 0x87654321;
        long name = 0xFEDCBA0987654321L;
        UUID namespaceUuid = UuidUtil.namespaceUUID(namespace, name);

        assertEquals(namespace, UuidUtil.namespaceFromUUID(namespaceUuid).intValue());
        assertEquals(name, UuidUtil.nameFromUUID(namespaceUuid).longValue());
    }
}


text:
"""Unit tests for the "update_role" module."""

import unittest
import argparse

from unittest import mock

from google.auth.transport import requests

from . import update_role

class UpdateRoleTest(unittest.TestCase):

  def test_initialize_command_line_args(self):
    actual = update_role.initialize_command_line_args(
        ["--name=Test", "--is-default=true"])
    self.assertEqual(
        actual,
        argparse.Namespace(
            credentials_file=None, name="Test", is_default=True, region="us"))

  @mock.patch.object(requests, "AuthorizedSession", autospec=True)
  @mock.patch.object(requests.requests, "Response", autospec=True)
  def test_update_role_error(self, mock_response, mock_session):
    mock_session.request.return_value = mock_response
    type(mock_response).status_code = mock.PropertyMock(return_value=400)
    mock_response.raise_for_status.side_effect = (
        requests.requests.exceptions.HTTPError())

    with self.assertRaises(requests.requests.exceptions.HTTPError):
      update_role.update_role(mock_session, "", False)

  @mock.patch.object(requests, "AuthorizedSession", autospec=True)
  @mock.patch.object(requests.requests, "Response", autospec=True)
  def test_update_role(self, mock_response, mock_session):
    mock_session.request.return_value = mock_response
    type(mock_response).status_code = mock.PropertyMock(return_value=200)
    role_id = "Test"
    is_default = True
    expected = {
        "name":
            "Test",
        "title":
            "Test role",
        "description":
            "The Test role",
        "createTime":
            "2020-11-05T00:00:00Z",
        "isDefault":
            True,
        "permissions": [{
            "name": "Test",
            "title": "Test permission",
            "description": "The Test permission",
            "createTime": "2020-11-05T00:00:00Z",
        },]
    }
    mock_response.json.return_value = expected
    actual = update_role.update_role(mock_session, role_id, is_default)
    self.assertEqual(actual, expected)

if __name__ == "__main__":
  unittest.main()


text:
Item 1

Item 2


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Templating\Helper;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Templating\Helper\Helper;

/**
 * RequestHelper provides access to the current request parameters.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class RequestHelper extends Helper
{
    protected $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    /**
     * Returns a parameter from the current request object.
     *
     * @param string $key     The name of the parameter
     * @param string $default A default value
     *
     * @return mixed
     *
     * @see Request::get()
     */
    public function getParameter($key, $default = null)
    {
        return $this->getRequest()->get($key, $default);
    }

    /**
     * Returns the locale.
     *
     * @return string
     */
    public function getLocale()
    {
        return $this->getRequest()->getLocale();
    }

    private function getRequest()
    {
        if (!$this->requestStack->getCurrentRequest()) {
            throw new \LogicException('A Request must be available.');
        }

        return $this->requestStack->getCurrentRequest();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'request';
    }
}


text:
title:  Les
date:   20/04/2020
---

### We werken aan deze les.
Kom alsjeblieft terug.


text:
require "test_helper"
require "minitest/spec"

module Sidekiq::Cron
  class RakeTest < ActiveSupport::TestCase
    extend Minitest::Spec::DSL

    let(:rake) { Rake::Application.new }

    %w[sidekiq_cron:load sidekiq_cron:clear].each do |task_name|
      before do
        Rake.application = rake
        Rake.load_rakefile(
          GEM_LIB_PATH.join("tasks/sidekiq_cron/tasks.rake").to_s
        )
        Rake::Task.define_task(:environment)
      end

      describe task_name do
        it "runs" do
          rake[task_name].invoke
        end
      end
    end
  end
end


text:
using System;
using System.Net;

namespace Orleans.Runtime
{
    ///
    /// The ILogConsumer distinguishes between four categories of logs:
    /// <list type="table"><listheader><term>Value</term><description>Description</description></listheader>
    /// <item>
    /// <term>Runtime</term>
    /// <description>Logs that are written by the Orleans run-time itself.
    /// This category should not be used by application code.</description>
    /// </item>
    /// <item>
    /// <term>Grain</term>
    /// <description>Logs that are written by application grains.
    /// This category should be used by code that runs as Orleans grains in a silo.</description>
    /// </item>
    /// <item>
    /// <term>Application</term>
    /// <description>Logs that are written by the client application.
    /// This category should be used by client-side application code.</description>
    /// </item>
    /// <item>
    /// <term>Provider</term>
    /// <description>Logs that are written by providers.
    /// This category should be used by provider code.</description>
    /// </item>
    /// </list>
    ///
    public enum LoggerType
    {
        Runtime,
        Grain,
        Application,
        Provider
    }

    ///
    /// An interface used to consume log entries.
    /// Instaces of a class implementing this should be added to <see cref="LogManager.LogConsumers"/> collection in order to retrieve events.
    ///
    public interface ILogConsumer
    {
        ///
        /// The method to call during logging.
        /// This method should be very fast, since it is called synchronously during Orleans logging.
        ///
        /// <param name="severity">The severity of the message being traced.</param>
        /// <param name="loggerType">The type of logger the message is being traced through.</param>
        /// <param name="caller">The name of the logger tracing the message.</param>
        /// <param name="myIPEndPoint">The <see cref="IPEndPoint"/> of the Orleans client/server if known. May be null.</param>
        /// <param name="message">The message to log.</param>
        /// <param name="exception">The exception to log. May be null.</param>
        /// <param name="eventCode">Numeric event code for this log entry. May be zero, meaning 'Unspecified'.
        /// In general, all log entries at severity=Error or greater should specify an explicit error code value.</param>
        void Log(
            Severity severity,
            LoggerType loggerType,
            string caller,
            string message,
            IPEndPoint myIPEndPoint,
            Exception exception,
            int eventCode = 0
            );
    }

    ///
    /// An interface used to consume log entries, when a Flush function is also supported.
    /// Instances of a class implementing this should be added to <see cref="LogManager.LogConsumers"/> collection in order to retrieve events.
    ///
    public interface IFlushableLogConsumer : ILogConsumer
    {
        /// Flush any pending log writes.
        void Flush();
    }

    ///
    /// An interface used to consume log entries, when a Close function is also supported.
    /// Instances of a class implementing this should be added to <see cref="LogManager.LogConsumers"/> collection in order to retrieve events.
    ///
    public interface ICloseableLogConsumer : ILogConsumer
    {
        /// Close this log.
        void Close();
    }
}


text:
package com.dailystudio.app.utils;

import android.text.TextUtils;

import com.dailystudio.development.Logger;

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

public class ArrayUtils {

	public static final String DEFAULT_ARRAY_DELIMITER = ",";

	public static String stringArrayToString(String[] strings) {
		return stringArrayToString(strings, DEFAULT_ARRAY_DELIMITER);
	}

	public static String stringArrayToString(String[] strings, String delimiter) {
		if (strings == null || delimiter == null) {
			return null;
		}

		final int N = strings.length;
		if (N <= 0) {
			return null;
		}

		StringBuilder builder = new StringBuilder();

		int i;
		for (i = 0; i < N; i++) {
			builder.append(strings[i]);
			if (i != (N - 1)) {
				builder.append(delimiter);
			}
		}

		return builder.toString();
	}

	public static String[] toStringArray(String string, String delimiter) {
		if (string == null || delimiter == null) {
			return null;
		}

		return string.split(delimiter);
	}

	public static Integer[] toIntegerArray(int[] array) {
		if (array == null) {
			return null;
		}

		List<Integer> newArray = new ArrayList<>();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			newArray.add(array[i]);
		}

		return newArray.toArray(new Integer[0]);
	}

	public static Double[] toDoubleArray(double[] array) {
		if (array == null) {
			return null;
		}

		List<Double> newArray = new ArrayList<>();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			newArray.add(array[i]);
		}

		return newArray.toArray(new Double[0]);
	}

	public static String intArrayToString(int[] array) {
		return intArrayToString(array, DEFAULT_ARRAY_DELIMITER);
	}

	public static String intArrayToString(int[] array, String delimiter) {
		if (array == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			sb.append(String.valueOf(array[i]));
			if (i != (N - 1)) {
				sb.append(delimiter);
			}
		}

		return sb.toString();
	}

	public static String longArrayToString(long[] array) {
		return longArrayToString(array, DEFAULT_ARRAY_DELIMITER);
	}

	public static String longArrayToString(long[] array, String delimiter) {
		if (array == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			sb.append(String.valueOf(array[i]));
			if (i != (N - 1)) {
				sb.append(delimiter);
			}
		}

		return sb.toString();
	}

	public static String floatArrayToString(float[] array) {
		return floatArrayToString(array, DEFAULT_ARRAY_DELIMITER);
	}

	public static String floatArrayToString(float[] array, String delimiter) {
		if (array == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			sb.append(String.valueOf(array[i]));
			if (i != (N - 1)) {
				sb.append(delimiter);
			}
		}

		return sb.toString();
	}

	public static String arrayToString(Object[] array) {
		return arrayToString(array, DEFAULT_ARRAY_DELIMITER);
	}

	public static String arrayToString(Object[] array, String delimiter) {
		if (array == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		final int N = array.length;

		for (int i = 0; i < N; i++) {
			sb.append(array[i]);
			if (i != (N - 1)) {
				sb.append(delimiter);
			}
		}

		return sb.toString();
	}

	/**
	 * XXX: Code from com.google.common.primitives.Bytes
	 *
	 * Returns the index of the first appearance of the value {@code target} in {@code array}.
	 *
	 * @param array an array of {@code byte} values, possibly empty
	 * @param target a primitive {@code byte} value
	 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
	 *     such index exists.
	 */
	public static int indexOf(byte[] array, byte target) {
		return indexOf(array, target, 0, array.length);
	}

	public static int indexOf(byte[] array, byte target, int start, int end) {
		for (int i = start; i < end; i++) {
			if (array[i] == target) {
				return i;
			}
		}
		return -1;
	}

	public static int bytesToInteger(byte[] a) {
		return bytesToInteger(a, 0);
	}

	public static String bytesToString(byte[] a) {
		return bytesToString(a, true);
	}

	public static String bytesToString(byte[] a, boolean trim) {
		if (a == null) {
			return null;
		}

		int index = ArrayUtils.indexOf(a, (byte)0);

		return new String(a, 0, index).trim();
	}

	public static int bytesToInteger(byte[] a, int startIndex) {
		if (a == null ||
				startIndex + 3 >= a.length) {
			return 0;
		}

		return (a[startIndex] & 0xff)
				| ((a[startIndex + 1] << 8) & 0xff00)
				| ((a[startIndex + 2] << 24) >>> 8)
				| (a[startIndex + 3] << 24); // byte[] to int
	}

	public static String byteArrayToHex(byte[] a) {
		return byteArrayToHex(a, false);
	}

	public static String byteArrayToHex(byte[] a, boolean withSplitter) {
		if (a == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();

		final int N = a.length;

		for(int i = 0; i < N; i++) {
			sb.append(String.format("%02X", a[i]&0xff));
			if (withSplitter && i != (N - 1)) {
				sb.append(':');
			}
		}

		return sb.toString();
	}

	public static byte[] hexStringToByteArray(String hexString) {
		if (TextUtils.isEmpty(hexString)) {
			return null;
		}

		final int N = hexString.length();

		if (N % 2 != 0) {
			Logger.warn("length of hex string is invalid. len = %d", N);

			return null;
		}

		StringBuilder builder = new StringBuilder("0");
		byte[] bytes = new byte[N / 2];
		for (int i = 0; i < N; i += 2) {
			bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
					+ Character.digit(hexString.charAt(i + 1), 16));
/*
			Logger.debug("current byte[%c%c]: byte = %02X ",
					hexString.charAt(i), hexString.charAt(i + 1),
					bytes[i / 2]);
*/
		}

		return bytes;
	}

	public static <T> List<T> arrayToList(T[] arrays) {
		if (arrays == null
				|| arrays.length <= 0) {
			return null;
		}

		List<T> list = new ArrayList<>();

		for (T item: arrays) {
			list.add(item);
		}

		return list;
	}

}


text:
<form name="newOrder">
	<input type="text" name="id" ng-model="order[params.id].id">
	<input type="text" name="name" ng-model="order[params.id].name">
	<input type="text" name="quantity" ng-model="order[params.id].quantity">
	Delete
	Save
</form>


text:
Content addressable gzipped storage on top of S3

[![Build Status](https://img.shields.io/travis/ForbesLindesay/s3cas-gzip/master.svg)](https://travis-ci.org/ForbesLindesay/s3cas-gzip)
[![Dependency Status](https://img.shields.io/david/ForbesLindesay/s3cas-gzip.svg)](https://david-dm.org/ForbesLindesay/s3cas-gzip)
[![NPM version](https://img.shields.io/npm/v/s3cas-gzip.svg)](https://www.npmjs.org/package/s3cas-gzip)

## Installation

    npm install s3cas-gzip

## Usage

```js
var assert = require('assert');
var connect = require('s3cas-gzip');

var client = connect(process.env.CONNECTION);

client.put(new Buffer('Hello World')).then(function (id) {
  assert(typeof id === 'string');
  return client.get(id);
}).then(function (buffer) {
  assert(Buffer.isBuffer(buffer));
  assert(buffer.toString('utf8') === 'Hello World');
}).done(function () {
  console.log('tests passed')
});
```

```
CONNECTION="{key}@{secret}@{bucket}" node test
```

## License

  MIT


text:
typedef NS_ENUM(NSUInteger, WYCPCircleLayerType) {

    kWYCPCircleLayerTypeNormalSolid,

    kWYCPCircleLayerTypeNormalHollow,

    kWYCPCircleLayerTypeHighlighted
};

@interface WYCPCircleLayer : CAShapeLayer

@property (nonatomic, assign) BOOL animatable;

- (instancetype)initWithFrame:(CGRect)frame type:(WYCPCircleLayerType)type radius:(CGFloat)radius color:(UIColor *)color;

@end

@interface WYCircleProgressBar : UIView

@property (nonatomic, strong) UIColor *highlightedColor;
@property (nonatomic, strong) UIColor *normalColor;
@property (nonatomic, readonly) CGPoint currentPosition;
@property (nonatomic, assign) NSInteger progress;

@property (nonatomic, assign) BOOL animatable;

- (instancetype)initWithFrame:(CGRect)frame radius:(CGFloat)radius circlesCount:(NSInteger)circlesCount;

///////--------------------------------------- UNAVAILABLE ------------------------------------------///////

- (instancetype)init UNAVAILABLE_ATTRIBUTE;
- (instancetype)initWithFrame:(CGRect)frame UNAVAILABLE_ATTRIBUTE;

@end


text:
package com.asksunny.hadoop.mr;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class SpringMapper extends SpringMapReduceBase
implements Mapper<LongWritable, Text, Text, NullWritable>
{

	public SpringMapper() {
		super();
	}

	@Override
	public void map(LongWritable arg0, Text inData,
			OutputCollector<Text, NullWritable> out, Reporter reporter)
			throws IOException
	{

		if(getDataProcessor().accept(inData)){
			Text ret = getDataProcessor().process(inData);
			if(ret!=null){
				out.collect(ret, NullWritable.get());
			}
		}
	}
}


text:
extern "C" {
#endif

// Private structure representing a single storage record.
typedef struct SbStorageRecordPrivate SbStorageRecordPrivate;

// A handle to an open storage record.
typedef SbStorageRecordPrivate* SbStorageRecord;

// Well-defined value for an invalid storage record handle.
#define kSbStorageInvalidRecord (SbStorageRecord) NULL

// Returns whether the given storage record handle is valid.
static SB_C_INLINE bool SbStorageIsValidRecord(SbStorageRecord record) {
  return record != kSbStorageInvalidRecord;
}

// Opens and returns the SbStorageRecord for |user| named |name|, blocking I/O
// on the calling thread until the open is completed. If |user| is not a valid
// |SbUser|, the function returns |kSbStorageInvalidRecord|. Will return an
// |SbStorageRecord| of size zero if the record does not yet exist. Opening an
// already-open |SbStorageRecord| has undefined behavior.
//
// If |name| is NULL, opens the default storage record for the user, like what
// would have been saved with the previous version of SbStorageOpenRecord.
//
// |user|: The user for which the storage record will be opened.
// |name|: The filesystem-safe name of the record to open.
SB_EXPORT SbStorageRecord SbStorageOpenRecord(SbUser user, const char* name);

// Closes |record|, synchronously ensuring that all written data is flushed.
// This function performs blocking I/O on the calling thread.
//
// The return value indicates whether the operation succeeded. Storage writes
// should be as atomic as possible, so the record should either be fully
// written or deleted (or, even better, untouched).
//
// |record|: The storage record to close. |record| is invalid after this point,
// and subsequent calls referring to |record| will fail.
SB_EXPORT bool SbStorageCloseRecord(SbStorageRecord record);

// Returns the size of |record|, or |-1| if there is an error. This function
// performs blocking I/O on the calling thread.
//
// |record|: The record to retrieve the size of.
SB_EXPORT int64_t SbStorageGetRecordSize(SbStorageRecord record);

// Reads up to |data_size| bytes from |record|, starting at the beginning of
// the record. The function returns the actual number of bytes read, which
// must be <= |data_size|. The function returns |-1| in the event of an error.
// This function makes a best-effort to read the entire record, and it performs
// blocking I/O on the calling thread until the entire record is read or an
// error is encountered.
//
// |record|: The record to be read.
// |out_data|: The data read from the record.
// |data_size|: The amount of data, in bytes, to read.
SB_EXPORT int64_t SbStorageReadRecord(SbStorageRecord record,
                                      char* out_data,
                                      int64_t data_size);

// Replaces the data in |record| with |data_size| bytes from |data|. This
// function always deletes any previous data in that record. The return value
// indicates whether the write succeeded. This function makes a best-effort to
// write the entire record, and it may perform blocking I/O on the calling
// thread until the entire record is written or an error is encountered.
//
// While |SbStorageWriteRecord()| may defer the persistence,
// |SbStorageReadRecord()| is expected to work as expected immediately
// afterwards, even without a call to |SbStorageCloseRecord()|. The data should
// be persisted after a short time, even if there is an unexpected process
// termination before |SbStorageCloseRecord()| is called.
//
// |record|: The record to be written to.
// |data|: The data to write to the record.
// |data_size|: The amount of |data|, in bytes, to write to the record.
SB_EXPORT bool SbStorageWriteRecord(SbStorageRecord record,
                                    const char* data,
                                    int64_t data_size);

// Deletes the |SbStorageRecord| for |user| named |name|. The return value
// indicates whether the record existed and was successfully deleted. If the
// record did not exist or could not be deleted, the function returns |false|.
//
// If |name| is NULL, deletes the default storage record for the user, like what
// would have been deleted with the previous version of SbStorageDeleteRecord.
//
// This function must not be called while the user's storage record is open.
// This function performs blocking I/O on the calling thread.
//
// |user|: The user for whom the record will be deleted.
// |name|: The filesystem-safe name of the record to open.
SB_EXPORT bool SbStorageDeleteRecord(SbUser user, const char* name);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // STARBOARD_STORAGE_H_


text:
from blog_nb import __version__

def test_version():
    assert __version__ == '0.1.0'


text:
package smoketest.websocket.tomcat.snake;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Sets up the timer for the multi-player snake game WebSocket example.
 */
public final class SnakeTimer {

	private static final long TICK_DELAY = 100;

	private static final Object MONITOR = new Object();

	private static final Log logger = LogFactory.getLog(SnakeTimer.class);

	private static final ConcurrentHashMap<Integer, Snake> snakes = new ConcurrentHashMap<>();

	private static Timer gameTimer = null;

	private SnakeTimer() {
	}

	public static void addSnake(Snake snake) {
		synchronized (MONITOR) {
			if (snakes.isEmpty()) {
				startTimer();
			}
			snakes.put(Integer.valueOf(snake.getId()), snake);
		}
	}

	public static Collection<Snake> getSnakes() {
		return Collections.unmodifiableCollection(snakes.values());
	}

	public static void removeSnake(Snake snake) {
		synchronized (MONITOR) {
			snakes.remove(Integer.valueOf(snake.getId()));
			if (snakes.isEmpty()) {
				stopTimer();
			}
		}
	}

	public static void tick() throws Exception {
		StringBuilder sb = new StringBuilder();
		for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator.hasNext();) {
			Snake snake = iterator.next();
			snake.update(SnakeTimer.getSnakes());
			sb.append(snake.getLocationsJson());
			if (iterator.hasNext()) {
				sb.append(',');
			}
		}
		broadcast(String.format("{'type': 'update', 'data' : [%s]}", sb.toString()));
	}

	public static void broadcast(String message) throws Exception {
		Collection<Snake> snakes = new CopyOnWriteArrayList<>(SnakeTimer.getSnakes());
		for (Snake snake : snakes) {
			try {
				snake.sendMessage(message);
			}
			catch (Throwable ex) {
				// if Snake#sendMessage fails the client is removed
				removeSnake(snake);
			}
		}
	}

	public static void startTimer() {
		gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer");
		gameTimer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				try {
					tick();
				}
				catch (Throwable ex) {
					logger.error("Caught to prevent timer from shutting down", ex);
				}
			}
		}, TICK_DELAY, TICK_DELAY);
	}

	public static void stopTimer() {
		if (gameTimer != null) {
			gameTimer.cancel();
		}
	}

}