text:
import copy
from itertools import cycle
from itertools import product
from netaddr import EUI
from netaddr import IPNetwork
from netaddr import mac_unix_expanded
import random
import six
import string

MANUFACTURERS = {
    'real': (
        'Supermicro',
        '80AD',
        'Dell',
        'Samsung',
    ),
    'virtual': (
        'VirtualBox',
    )
}

SAMPLE_CPUS = {
    'real': (
        {
            'model': 'Intel(R) Xeon(R) CPU E5-2620 0 @ 2.00GHz',
            'frequency': 2001
        },
        {
            'model': 'Intel(R) Xeon(R) CPU E31230 @ 3.20GHz',
            'frequency': 3201
        },
        {
            'model': 'Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz',
            'frequency': 2185
        }
    ),
    'virtual': (
        {
            'model': 'QEMU Virtual CPU version 1.0',
            'frequency': 1999
        },
    )
}

SAMPLE_INTERFACE_OFFLOADING_MODES = [
    {
        'name': 'tx-checksumming',
        'state': True,            # True, false, null
        'sub': [
            {
                'name': 'tx-checksum-sctp',
                'state': False,   # True, false, null
                'sub': []
            },
            {
                'name': 'tx-checksum-ipv6',
                'state': True,    # True, false, null
                'sub': []
            },
            {
                'name': 'tx-checksum-ipv4',
                'state': None,    # True, false, null
                'sub': []
            }
        ]
    },
    {
        'name': 'rx-checksumming',
        'state': None,
        'sub': []
    }
]

DISK_SAMPLES = [
    {
        'model': 'TOSHIBA MK1002TS',
        'name': 'sda',
        'disk': 'sda',
        'size': 1000204886016
    },
    {
        'model': 'Virtual Floppy0',
        'name': 'sde',
        'disk': 'sde',
        'size': 0
    },
    {
        'model': 'Virtual HDisk0',
        'name': 'sdf',
        'disk': 'sdf',
        'size': 0
    },
    {
        'model': 'Silicon-Power16G',
        'name': 'sdb',
        'disk': 'sdb',
        'size': 155692564480
    },
    {
        'model': 'WDC WD3200BPVT-7',
        'name': 'sda',
        'disk': 'sda',
        'size': 320072933376
    },
    {
        'model': 'QEMU HARDDISK',
        'name': 'sda',
        'disk': 'sda',
        'size': 68719476736
    }
]

MEMORY_DEVICE_SAMPLES = [
    {
        'frequency': 1333,
        'type': 'DDR3',
        'size': 8589934592
    },
    {
        'frequency': 1333,
        'type': 'DDR3',
        'size': 4294967296
    },
    {
        'type': 'RAM',
        'size': 10737418240
    },
    {
        'type': 'Flash',
        'size': 16777216
    }
]

NETWORK_1 = '10.20.0.0/16'
NETWORK_2 = '172.18.67.0/24'

class FakeNodesGenerator:
    """This class uses to generate fake nodes
    """

    def __init__(self):
        self.net1 = IPNetwork(NETWORK_1)
        self.net1_ip_pool = cycle(self.net1.iter_hosts())
        self.net2 = IPNetwork(NETWORK_2)
        self.net2_ip_pool = cycle(self.net2.iter_hosts())

        self.mcounter = dict()
        self.mac_counter = 0

    def _get_network_data(self, net_name):
        if net_name == 'net1':
            return str(next(self.net1_ip_pool)), str(self.net1.netmask)
        if net_name == 'net2':
            return str(next(self.net2_ip_pool)), str(self.net2.netmask)
        return None, None

    def _generate_mac(self):
        # MAC's starts from FF:FF:FF:FF:FF:FE counting down
        mac = str(EUI(281474976710654 - self.mac_counter,
                      dialect=mac_unix_expanded))
        self.mac_counter += 1
        return mac

    @staticmethod
    def _get_disk_suffixes(amount):
        length = 1
        counter = 0
        while counter < amount:
            for item in product(string.ascii_lowercase, repeat=length):
                if counter == amount:
                    break
                counter += 1
                yield ''.join(item)
            length += 1

    def _generate_disks_meta(self, amount):
        disks = []
        total_size = 0
        for i, disk_suffix in enumerate(self._get_disk_suffixes(amount)):
            new_disk = copy.deepcopy(random.choice(DISK_SAMPLES))
            # disks total size shouldn't be 0
            if i == amount - 1 and total_size == 0:
                while new_disk['size'] == 0:
                    new_disk = copy.deepcopy(random.choice(DISK_SAMPLES))
            new_disk.update({
                'name': 'sd{0}'.format(disk_suffix),
                'disk': 'sd{0}'.format(disk_suffix)
            })
            total_size += new_disk['size']
            disks.append(new_disk)
        return disks

    @staticmethod
    def _get_random_iface_offloading_modes():
        offloading_modes = copy.deepcopy(SAMPLE_INTERFACE_OFFLOADING_MODES)
        for mode in offloading_modes:
            mode['state'] = random.choice([True, False, None])
            for sub in mode.get('sub', []):
                sub['state'] = random.choice([True, False, None])
        return offloading_modes

    def _generate_interfaces_meta(self, known_mac, known_ip, known_ip_mask,
                                  use_offload_iface, amount):
        ifaces = []
        driver = random.choice(['igb'] * 9 + ['mlx4_en', 'eth_ipoib', 'e1000'])
        name = random.choice(['eth'] * 8 + ['wlan', 'p2p'])
        know_interface_num = random.randint(0, amount - 1)

        for i in six.moves.range(amount):
            max_speed = random.choice([100, 1000, 56000])
            current_speed_set = [
                random.randint(max_speed * 0.5, max_speed) for _ in range(3)]
            current_speed_set.append(None)

            new_iface = {
                'name': '{0}{1}'.format(name, i),
                'driver': driver,
                'bus_info': '0000:0{0}:00.0'.format(i),
                'max_speed': max_speed,
                'current_speed': random.choice(current_speed_set),
                'pxe': random.choice([True, False])
            }
            if i == know_interface_num:
                new_iface.update({
                    'mac': known_mac,
                    'ip': known_ip,
                    'netmask': known_ip_mask
                })
            else:
                new_iface['mac'] = self._generate_mac()
                net = random.choice(['net1', 'net2', None])
                if net:
                    ip, netmask = self._get_network_data(net)
                    new_iface.update({
                        'ip': ip,
                        'netmask': netmask
                    })

            if use_offload_iface:
                new_iface['offloading_modes'] = \
                    self._get_random_iface_offloading_modes()

            ifaces.append(new_iface)
        return ifaces

    @staticmethod
    def _generate_systems_meta(hostname, manufacture, platform_name):
        return {
            'manufacturer': manufacture,
            'version': '{0}.{0}'.format(random.randint(0, 10),
                                        random.randint(0, 9)),
            'serial': ''.join(
                [str(random.randint(0, 9)) for _ in six.moves.range(10)]),
            'fqdn': '{0}.mirantis.net'.format(hostname),
            'product': platform_name,
            'family': 'To be filled by O.E.M.'
        }

    @staticmethod
    def _generate_cpu_meta(kind):
        real_proc = random.choice([0, 1, 2, 4])
        total_proc = real_proc * random.choice([1, 2, 4]) or 1
        proc = random.choice(SAMPLE_CPUS[kind])
        return {
            'real': real_proc,
            'total': total_proc,
            'spec': [copy.deepcopy(proc) for _ in six.moves.range(total_proc)]
        }

    @staticmethod
    def _generate_memory_meta(amount):
        max_capacity = 1024 ** 3 * random.choice([8, 16, 32, 64])
        total_capacity = 0
        devices = []
        for _ in six.moves.range(amount):
            new_memory = copy.deepcopy(
                random.choice(MEMORY_DEVICE_SAMPLES))
            if (total_capacity + new_memory['size']) > max_capacity:
                if total_capacity == 0:
                    new_memory['size'] = max_capacity
                else:
                    break
            total_capacity += new_memory['size']
            devices.append(new_memory)
        return {
            'slots': len(devices),
            'total': total_capacity,
            'maximum_capacity': max_capacity,
            'devices': devices
        }

    def generate_fake_node(self, pk, is_online=True, is_error=False,
                           use_offload_iface=False, min_ifaces_num=1):
        """Generate one fake node
        :param int pk: node's database primary key
        :param bool is_online: node's online status
        :param bool is_error: node's error status
        :param bool use_offload_iface: use offloading_modes data for
                                       node's interfaces or not
        :returns: kwargs dict that represents fake node
        """

        kind = random.choice(['real', 'virtual'])
        manufacture = random.choice(MANUFACTURERS[kind])
        self.mcounter[manufacture] = self.mcounter.get(manufacture, 0) + 1
        hostname = 'node-{0}'.format(pk)
        platform_name = random.choice(['', 'X9SCD', 'N5110', 'X9DRW'])
        mac = self._generate_mac()
        net = random.choice(['net1', 'net2'])
        ip, netmask = self._get_network_data(net)

        return {
            'pk': pk,
            'model': 'nailgun.node',
            'fields': {
                'status': 'error' if is_error else 'discover',
                'manufacturer': manufacture,
                'name': manufacture + ' {0}({1})'.format(
                    platform_name, self.mcounter.get(manufacture)),
                'hostname': hostname,
                'ip': ip,
                'mac': mac,
                'online': is_online,
                'labels': {},
                'pending_addition': False,
                'pending_deletion': False,
                'platform_name': platform_name,
                'os_platform': 'ubuntu',
                'progress': 0,
                'timestamp': '',
                'meta': {
                    'cpu': self._generate_cpu_meta(kind),
                    'interfaces': self._generate_interfaces_meta(
                        mac, ip, netmask, use_offload_iface,
                        random.randrange(min_ifaces_num, 7)),
                    'disks': self._generate_disks_meta(random.randint(1, 7)),
                    'system': self._generate_systems_meta(
                        hostname, manufacture, platform_name),
                    'memory': self._generate_memory_meta(random.randint(1, 8))
                }
            }
        }

    def generate_fake_nodes(self, total_nodes_count, error_nodes_count=None,
                            offline_nodes_count=None,
                            offloading_ifaces_nodes_count=None,
                            min_ifaces_num=1):
        """Generate list of fake nodes
        :param int total_nodes_count: total count of nodes to generate
        :param int error_nodes_count: count of error nodes (optional)
        :param int offline_nodes_count: count of offline nodes (optional)
        :param int offloading_ifaces_nodes_count: count of nodes with interface
                                                  using offloading (optional)
        :returns: list of dicts, each of which represents node
        """
        if error_nodes_count is None:
            error_nodes_count = int(0.09 * total_nodes_count)
        if offline_nodes_count is None:
            offline_nodes_count = int(0.08 * total_nodes_count)
        if error_nodes_count + offline_nodes_count > total_nodes_count:
            error_nodes_count = int(0.09 * total_nodes_count)
            offline_nodes_count = int(0.08 * total_nodes_count)
        if offloading_ifaces_nodes_count is None:
            offloading_ifaces_nodes_count = int(0.2 * total_nodes_count)

        total_nodes_range = six.moves.range(total_nodes_count)
        # Making error and offline random sets non intersecting
        error_nodes_indexes = set(random.sample(
            total_nodes_range, error_nodes_count))
        offline_nodes_indexes = set(random.sample(
            set(total_nodes_range) - error_nodes_indexes,
            offline_nodes_count
        ))
        offloading_ifaces_nodes_indexes = set(random.sample(
            total_nodes_range, offloading_ifaces_nodes_count))

        res = []
        for i in total_nodes_range:
            node = self.generate_fake_node(
                i + 1,
                is_online=i not in offline_nodes_indexes,
                is_error=i in error_nodes_indexes,
                use_offload_iface=i in offloading_ifaces_nodes_indexes,
                min_ifaces_num=min_ifaces_num
            )
            res.append(node)
        return res


text:
<?xml version="1.0" encoding="UTF-8"?>
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:ns5="http://www.w3.org/1999/xhtml" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" version="5.0-subset Scilab"
xml:id="mdaqPing">
	<refnamediv>
		<refname>mdaqPing</refname>
		<refpurpose>Checks connection with MicroDAQ</refpurpose>
	</refnamediv>

	<refsynopsisdiv>
		<title>Calling Sequence</title>
		<synopsis>
			result = mdaqPing();
		</synopsis>
	</refsynopsisdiv>

	<refsection id="Description_mdaqPing">
		<title>Description</title>
		<para>
			This function checks connection with MicroDAQ device. This function can be helpful to verify if Ethernet of Wi-Fi connection is working properly. Function uses IP address which was set during microdaq_setup call or with mdaqSetIP call.
		</para>
	</refsection>

	<refsection id="Parameters_mdaqPing">
		<title>Output arguments</title>
		<itemizedlist>
			<listitem><para><emphasis role="bold">result: </emphasis> Negative if unable to connect to MicroDAQ device</para></listitem>
		</itemizedlist>
	</refsection>

	<refsection>
        <title>Examples</title>
        <programlisting role="example"><![CDATA[
// mdaqPing usage example
mdaqPing();
 ]]></programlisting>
    </refsection>

  <refsection id="SeeAlso_mdaqPing">
		<title>See Also</title>
		<simplelist type="inline">
			<member><link linkend="mdaqOpen">mdaqOpen</link></member>
			<member><link linkend="mdaqClose">mdaqClose</link></member>
			<member><link linkend="mdaqSetIP">mdaqSetIP</link></member>
		</simplelist>
  </refsection>
</refentry>

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.squeeze import get_squeezer_by_name
from utils.parameter_parser import parse_params

class FeatureSqueezingRC:
    def __init__(self, keras_model, rc_name):
        # Example of rc_name: FeatureSqueezing?squeezer=bit_depth_1
        self.model_predict = lambda x: keras_model.predict(x)
        subject, params = parse_params(rc_name)
        assert subject == 'FeatureSqueezing'

        if params.has_key('squeezer'):
            self.filter = get_squeezer_by_name(params['squeezer'], 'python')
        elif params.has_key('squeezers'):
            squeezer_names = params['squeezers'].split(',')
            self.filters = [ get_squeezer_by_name(squeezer_name, 'python') for squeezer_name in squeezer_names ]

            def filter_func(x, funcs):
                x_p = x
                for func in funcs:
                    x_p = func(x_p)
                return x_p

            self.filter = lambda x: filter_func(x, self.filters)

    def predict(self, X):
        X_filtered = self.filter(X)
        Y_pred = self.model_predict(X_filtered)
        return Y_pred

    def visualize_and_predict(self, X):
        X_filtered = self.filter(X)
        Y_pred = self.model_predict(X_filtered)
        return X_filtered, Y_pred


text:
import logging
import sys
import uuid

from volttron.platform.vip.agent import Agent, Core, PubSub, RPC, compat
from volttron.platform.agent import utils
from volttron.platform.messaging.health import Status, STATUS_BAD

utils.setup_logging()
_log = logging.getLogger(__name__)
__version__ = '3.7'

def thresholddetection_agent(config_path, **kwargs):
    """Load configuration for ThresholdDetectionAgent

    :param config_path: Path to a configuration file.

    :type config_path: str
    :returns: ThresholdDetectionAgent instance
    :rtype: ThresholdDetectionAgent
    """
    config = utils.load_config(config_path)
    return ThresholdDetectionAgent(config, **kwargs)

class ThresholdDetectionAgent(Agent):
    """
    Listen to topics and publish alerts when thresholds are passed.

    The agent's configuration specifies which topics to watch, the
    topic's threshold, and the message to send in an alert. Topics
    can specify a maximum and minimum threshold. Non-numberic data
    will be ignored.

    Example configuration:

    .. code-block:: python

        {
            "datalogger/log/platfor/cpu_percent": {
                "threshold_max": 99,
            },
            "some/temperature/topic": {
                "threshold_min": 0,
            },
            "devices/some/device/topic/all": {
                "some_point": {
                    "threshold_max": 42,
                    "threshold_min": 0
                }
            }
        }

    """
    def __init__(self, config, **kwargs):
        super(ThresholdDetectionAgent, self).__init__(**kwargs)
        self.config_topics = {}

        self.vip.config.set_default("config", config)
        self.vip.config.subscribe(self._config_add, actions="NEW", pattern="config")
        self.vip.config.subscribe(self._config_del, actions="DELETE", pattern="config")
        self.vip.config.subscribe(self._config_mod, actions="UPDATE", pattern="config")

    def _config_add(self, config_name, action, contents):
        """
        Configstore callback

        Subscribes to configured topics with customized callbacks
        """
        self.config_topics[config_name] = set()
        for topic, values in contents.iteritems():
            self.config_topics[config_name].add(topic)
            _log.info("Subscribing to {}".format(topic))

            if topic.startswith("devices/") and topic.endswith("/all"):
                self._create_device_subscription(topic, values)
            else:
                self._create_standard_subscription(topic, values)

    def _create_device_subscription(self, topic, device_points):
        """
        Subscribe to points in a device's all publish and alert if
        values are out of range

        :param topic: All topic from a device scrape
        :type topic: str

        :param device_points: Dictionary of points to thresholds
        :type device_points: dict
        """
        for point, values in device_points.iteritems():
            threshold_max = values.get('threshold_max')
            threshold_min = values.get('threshold_min')

            def callback(peer, sender, bus, topic, headers, message):
                data = message[0].get(point)

                try:
                    float(data)
                except ValueError:
                    return

                if threshold_max is not None and data > threshold_max:
                    self._alert(topic, threshold_max, data, point=point)
                elif threshold_min is not None and data < threshold_min:
                    self._alert(topic, threshold_min, data, point=point)

            self.vip.pubsub.subscribe('pubsub', topic, callback)

    def _create_standard_subscription(self, topic, values):
        """
        Subscribe to a topic and alert if its message is out of range

        :param topic: All topic from a device scrape
        :type topic: str

        :param device_points: Dictionary of points to thresholds
        :type device_points: dict
        """
        threshold_max = values.get('threshold_max')
        threshold_min = values.get('threshold_min')

        def callback(peer, sender, bus, topic, headers, data):
            try:
                float(data)
            except ValueError:
                return

            if threshold_max is not None and data > threshold_max:
                self._alert(topic, threshold_max, data)
            elif threshold_min is not None and data < threshold_min:
                self._alert(topic, threshold_min, data)

        self.vip.pubsub.subscribe('pubsub', topic, callback)

    def _config_del(self, config_name, action, contents):
        """
        Configstore callback

        Unsubscribes from topics in a deleted configuration.
        """
        topics = self.config_topics.pop(config_name)
        for t in topics:
            _log.info("Unsubscribing from {}".format(t))
            self.vip.pubsub.unsubscribe(peer='pubsub',
                                        prefix=t,
                                        callback=None).get()

    def _config_mod(self, *args):
        """
        Configstore callback

        Unsubscribes and resubscribes to updated configuration.
        """
        self._config_del(*args)
        self._config_add(*args)

    def _alert(self, topic, threshold, data, point=''):
        """
        Raise alert for the given topic.

        :param topic: Topic that has published some threshold-exceeding value.
        :type topic: str

        :param threshold: Value that has been exceeded. Used in alert message.
        :type threshold: float

        :param data: Value that is out of range. Used in alert message.
        :type data: float

        :param point: Optional point name. Used in alert message.
        :type point: str
        """
        if point:
            point = '({})'.format(point)

        if threshold < data:
            custom = "above"
        else:
            custom = "below"

        message = "{topic}{point} value ({data})" \
                  "is {custom} acceptable limit ({threshold})"

        message = message.format(topic=topic,
                                 point=point,
                                 data=data,
                                 custom=custom,
                                 threshold=threshold)

        status = Status.build(STATUS_BAD, message)
        self.vip.health.send_alert(topic, status)

def main(argv=sys.argv):
    """Main method called by the platform."""
    utils.vip_main(thresholddetection_agent,
                   identity='platform.thresholddetection',
                   version=__version__)

if __name__ == '__main__':
    # Entry point for script
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        pass


text:
#include <catch.hpp>
#include <risc_v/risc_v.h>
#include <simulator.h>

static auto get_op_with_trap( Trap trap)
{
    Operation op( 0x100, 0x104);
    op.set_trap( trap);
    return op;
}

TEST_CASE("RISCV32 driver - no trap")
{
    auto sim = Simulator::create_simulator( "riscv32", true);
    auto drv = create_riscv32_driver( sim.get());
    auto expected_pc = sim->get_pc();
    CHECK( drv->handle_trap( get_op_with_trap( Trap( Trap::NO_TRAP))) == Trap::NO_TRAP);
    CHECK( sim->get_pc() == expected_pc);
}

TEST_CASE("RISCV32 driver - breakpoint")
{
    auto sim = Simulator::create_simulator( "riscv32", true);
    auto drv = create_riscv32_driver( sim.get());
    sim->write_csr_register( "stvec", 0x8000);
    CHECK( drv->handle_trap( get_op_with_trap( Trap( Trap::BREAKPOINT))) == Trap::NO_TRAP);
    auto expected_pc = trap_vector_address<Addr>( sim->read_csr_register( "stvec"));
    CHECK( sim->get_pc() == expected_pc);
    auto expected_cause = Trap( Trap::BREAKPOINT).to_riscv_format();
    CHECK( sim->read_csr_register( "scause") == expected_cause);
}


text:
package com.github.andr83.parsek.spark.sink

import com.github.andr83.parsek._
import com.typesafe.config.Config
import com.typesafe.scalalogging.slf4j.LazyLogging
import net.ceedubs.ficus.Ficus._
import org.apache.spark.rdd.RDD

/**
  * Sink is define destination of rdd. It can be stored to filesystem, db, kafka and etc
  *
  * @author andr83
  */
abstract class Sink extends LazyLogging {
  def sink(rdd: RDD[PValue], time: Long): Unit
}

object Sink {
  def apply(config: Config): Sink = {
    val sinkType = config.as[Option[String]]("type")
      .getOrElse(throw new IllegalStateException("Sink config must have type property"))
    val className = if (sinkType.contains(".")) sinkType
    else
      getClass.getPackage.getName + "." + sinkType.head.toUpper + sinkType.substring(1) + "Sink"
    val constructor = Class.forName(className).getConstructor(classOf[Config])
    constructor.newInstance(config).asInstanceOf[Sink]
  }
}


text:
from django.conf import settings
from django.http import HttpResponse

class PistonKeyAuthentication(object):

    def is_authenticated(self, request):
        return hasattr(request, 'apikey') and request.apikey['status'] == 'A'

    def challenge(self):
        resp = HttpResponse("Authorization Required", content_type="text/plain")
        resp.status_code = 401
        return resp


text:
import six
import unittest

import os
import shutil

from coopy.journal import DiskJournal

JOURNAL_DIR = 'journal_test/'
CURRENT_DIR = os.getcwd()

class TestJournal(unittest.TestCase):
    def setUp(self):
        os.mkdir(JOURNAL_DIR)

    def tearDown(self):
        shutil.rmtree(JOURNAL_DIR)

    def test_current_journal_file(self):
        journal = DiskJournal(JOURNAL_DIR, CURRENT_DIR)
        expected_file_name = '%s%s' % (JOURNAL_DIR,
                                      'transaction_000000000000002.log')

        self.assertEquals(expected_file_name,
                          journal.current_journal_file(JOURNAL_DIR).name)

        # test hack! - create next file
        new_file_name = expected_file_name.replace('2','3')
        open(new_file_name, 'wt').close()

        self.assertEquals(new_file_name,
                          journal.current_journal_file(JOURNAL_DIR).name)

    def test_receive(self):
        import pickle
        class Message(object):
            def __init__(self, value):
                self.value = value
            def __getstate__(self):
                raise pickle.PicklingError()

        message = Message('test message')
        journal = DiskJournal(JOURNAL_DIR, CURRENT_DIR)
        journal.setup()

        self.assertRaises(
                            pickle.PicklingError,
                            journal.receive,
                            (message)
                          )

    def test_close(self):
        journal = DiskJournal(JOURNAL_DIR, CURRENT_DIR)
        self.assertTrue(not journal.file)

        journal.setup()
        self.assertTrue(not journal.file.closed)

        journal.close()
        self.assertTrue(journal.file.closed)

    def test_setup(self):
        journal = DiskJournal(JOURNAL_DIR, CURRENT_DIR)
        self.assertEquals(JOURNAL_DIR, journal.basedir)

        journal.setup()
        expected_file_name = '%s%s' % (JOURNAL_DIR,
                                      'transaction_000000000000002.log')
        self.assertEquals(expected_file_name,
                          journal.file.name)

        if six.PY3:
            import pickle
        else:
            import cPickle as pickle
        # test hack
        pickle_class = pickle.Pickler(open(expected_file_name, 'rb'))\
                                                            .__class__
        self.assertTrue(isinstance(journal.pickler, pickle_class))


text:
<?php
App::uses('Section', 'Model');

/**
 * Section Test Case
 *
 */
class SectionTest extends CakeTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'app.section'
	);

/**
 * setUp method
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();
		$this->Section = ClassRegistry::init('Section');
	}

	public function test_addSection() {
		$section['Section']['parent_id'] = 0;
		$section['Section']['name']      = 'Section 4';
		$section['Section']['status']    = 1;

		$this->Section->save($section);

		$sections = $this->Section->find('all');

		$this->assertCount(4, $sections);
	}

	public function test_getChildren() {
		$section['Section']['parent_id'] = 2;
		$section['Section']['name']      = 'Section 4';
		$section['Section']['status']    = 1;

		$this->Section->save($section);

		$children = $this->Section->children(2, true);

		$this->assertCount(2, $children);
	}

/**
 * tearDown method
 *
 * @return void
 */
	public function tearDown() {
		unset($this->Section);

		parent::tearDown();
	}

}


text:
<?php

namespace Batrac\Core;

class App
{
    /**
     * @var array
     */
    public static $config;

    /**
     * @var $request Request
     */
    public static $request;

    /**
     * @var $response Response
     */
    public static $response;

    /**
     * @param $config
     */
    public static function run($config)
    {
        self::$config = $config;
        try {
            self::$request  = new Request();
            self::$response = new Response();
            self::call();
        } catch (InvalidException $error) {
            $error->display();
        }
        self::$response->output();
    }

    /**
     * @throws InvalidException
     */
    public static function call()
    {
        $action = ucfirst(self::$request->action);
        try {
            //$class = self::validateCall();
            $class = 'application\\controllers\\' . ucfirst(self::$request->controller);
            $controller = new $class();
            if (empty($params)) {
                $response = $controller->$action();
            } else {
                $params = !is_array($params) ? array($params) : $params;
                $response = call_user_func_array(array($controller, ), $params);
            }
            self::$response->setBody($response);
        } catch (NoticeException $error) {
            $error->display();
        }

    }

    private static function validateCall()
    {
        $controller = 'application\\controllers\\' . ucfirst(self::$request->controller);
        $reflection = new \ReflectionMethod($controller, ucfirst(self::$request->action));
        $countWaitingParams = $reflection->getNumberOfParameters();
        $countWaitingRequiredParams = $reflection->getNumberOfRequiredParameters();
        $countComingParams = count(self::$request->params);
        if ($countComingParams > $countWaitingParams || $countComingParams < $countWaitingRequiredParams) {
            throw new InvalidException("Passed wrong number of arguments to the method", 404);
        } else {
            return $controller;
        }
    }
}


text:
title: Use the Double Equals to Assert Equality
localeTitle: 使用Double Equals来断言平等
---
## 使用Double Equals来断言平等

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/use-the-double-equals-to-assert-equality/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。


text:
var ObjectID = require('mongodb').ObjectID,
    janitor = require('../../../lib/janitor');

//
// PARAM of vote_id
//
exports.vote_id = function(req, res, next, id){
    req.db.collection('vote', function(er, collection) {
        collection.findOne({_id: new ObjectID.createFromHexString(id)}, function(err, vote) {
            if (!vote) return next(new Error('Vote not found'));
            req.vote = vote;
            next();
        });
    });
}

//
// GET vote page.
//
exports.index = function(req, res){
    console.log(req.vote);
    req.db.collection('ballot', function(er, collection) {
        collection.findOne({_id: req.vote.ballot}, function(err, ballot) {
            var ballotIndex = {};
            if (!ballot) return next(new Error('Ballot not found'));
            ballot.games.forEach(function(game){
                ballotIndex[game.id] = game;
            });
            req.vote.vote.forEach(function(tier, i){
                tier.forEach(function(gameId, j){
                    req.vote.vote[i][j] = ballotIndex[gameId] || 'Unknown game index';
                });
            });
            janitor.render(res, 'vote', {vote: req.vote.vote, nickname: req.vote.nickname, ballot: req.vote.ballot});
        });
    });
};


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

namespace _02_Phonebook_UPD
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedDictionary<string, string> phonebook = new SortedDictionary<string, string>();

            string[] inputDetails = Console.ReadLine().Split();

            while (inputDetails[0] != "END")
            {
                if (inputDetails.Length == 3) //add to the dict
                {
                    phonebook[inputDetails[1]] = inputDetails[2];
                }
                else if (inputDetails.Length == 2) //find
                {
                    if (phonebook.ContainsKey(inputDetails[1]))
                    {
                        Console.WriteLine($"{inputDetails[1]} -> {phonebook[inputDetails[1]]}");
                    }
                    else
                    {
                        Console.WriteLine($"Contact {inputDetails[1]} does not exist.");
                    }
                }
                else //list all
                {
                    foreach (var kvp in phonebook)
                    {
                        Console.WriteLine($"{kvp.Key} -> {kvp.Value}");
                    }
                }

                inputDetails = Console.ReadLine().Split();

            }
        }
    }
}


text:
"""Content cluster

MIT License (MIT)

Copyright (c) 2015 Julien BLEGEAN <julien.blegean@aalto.fi>
"""

import networkx as nx
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import re
import datetime
import redis
import string
import numpy as np
import math
import Image
import community
import itertools
import os
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, dendrogram,fcluster
from operator import itemgetter
import sys
from collections import Counter
import random
from pylab import rcParams
import pylab as pl
import lda
from gensim import models
from gensim import corpora, models, matutils
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn import feature_extraction
from sklearn.cluster import DBSCAN
import re

def clusterize(tweets) :
  #transformer = TfidfTransformer()
  #tfidf = transformer.fit_transform(np.array(tweets.values()))

  if "-lda" in sys.argv :
    tfidf = models.tfidfmodel.TfidfModel(tweets.values())
    corpus = tfidf[tweets.values()]
    corpus = tweets.values()
    lda = models.ldamodel.LdaModel(corpus=corpus, id2word = dicog,num_topics=5)
    topics = lda.print_topics(5, 10)
    for topic in topics :
      topic = re.sub(r'([0-9\.]*)\*','', topic)
      print(topic)
    f = open('topiclusters_11','w')
    counters = {}
    for key,vec in tweets.items() :
      topd = lda[tfidf[vec]]
      topd = sorted(topd,key=lambda x: x[1], reverse=True)
      topd = topd[0][0]
      uid = t2u[key]
      if uid not in counters :
        counters[uid] = Counter()
      counters[uid][topd] += 1
    for user in counters :
      mc = counters[user].most_common()
      mc = int(mc[0][0])
      out = '%s,%s\n' % (user,mc)
      f.write(out)

  if "-lsi" in sys.argv :
    tfidf = models.tfidfmodel.TfidfModel(tweets.values())
    corpus = tfidf[tweets.values()]
    lsi = models.lsimodel.LsiModel(corpus=corpus, id2word = dicog,num_topics=5)
    topics = lsi.print_topics(5, 10)
    for topic in topics :
      topic = re.sub(r'([0-9\.]*)\*','', topic)
      print(topic)

#    model = lda.LDA(n_topics=5, n_iter=500, random_state=1)
#    model.fit(tfidf.toarray())
#    topic_word = model.topic_word_  # model.components_ also works
#    n_top_words = 10

#    for i, topic_dist in enumerate(topic_word):
#      topic_words = np.array(vocab)[np.argsort(topic_dist)][:-n_top_words:-1]
#      print('Topic {}: {}'.format(i, ' '.join(topic_words)))

  if "-dbscan" in sys.argv :
    db = DBSCAN(eps=1.1).fit(tfidf.toarray())

    labels = db.labels_
    print(len(labels))

    clusters = {}
    for i in range(len(labels)) :
      if labels[i] not in clusters :
        clusters[labels[i]] = []
      clusters[labels[i]].append(tweets.keys()[i])

    for c in clusters :
      print(" ")
      print("cluster %s " % c)
      print("------------")
      i  = 0
      for tid in clusters[c] :
        i += 1
        if i == 30 :
          break
        print(vec2bow(tweets[tid]))

  return 0

def bow2vec(words) :
  words = dict(words)
  return [words[x] if x in words else 0 for x in vocab]

def vec2bow(vec) :
  words = []
  for v in range(len(vec)) :
    if vec[v] != 0 :
      words.append(vocab[v])
  return words

if "-process" in sys.argv :
  filepath = str(sys.argv[1])

  # redis connection
  rt = redis.StrictRedis(host='localhost', port=6379, db=1)
  r = redis.StrictRedis(host='localhost', port=6379, db=0)

  plabels = open("../sc_11_02_09").readlines()
#  plabels = open("../tclusters_info").readlines()
  l = 0
  labels = {}
  for l in plabels :
    kv = l.strip().split(",")
    uid = kv[0]
    labels[uid] = kv[1]

  vocab = open("dictionary_11_08").readlines()
  vocab = [v.strip() for v in vocab]

  tweets = {}

  time = []
  i = 0
  for ar in sys.argv :
    i = i + 1
    if ar == "-h" :
      time.append(sys.argv[i])
      time.append(sys.argv[i+1])

  if len(time) > 0 :
    dfrom = datetime.datetime.strptime(time[0], '%H:%M')
    dfrom = datetime.time(dfrom.hour,dfrom.minute)

    dto = datetime.datetime.strptime(time[1], '%H:%M')
    dto = datetime.time(dto.hour,dto.minute)
  # counter
  k = 0

  if "-lda" in sys.argv or "-lsi" in sys.argv :
    dicog = corpora.Dictionary.load("dictionary_gensim_11_08")

  vectorizer = feature_extraction.text.CountVectorizer()

  t2u = {}

  # iterate tweets
  with open(filepath) as f:
      for tweet in f:
        if math.fmod(k,100000) == 0 :
          print(k)
        # get the content
        tweet = re.findall('"((?:(?!(?:",")).)*)"', tweet)

        tdate = datetime.datetime.strptime(tweet[1], '%Y-%m-%d %H:%M:%S')
        tdate = datetime.time(tdate.hour,tdate.minute)

        if len(time) == 0 or len(time) > 0 and tdate >= dfrom and tdate <= dto :
          tid = tweet[0]
          words = tweet[3].split(",")
          words = [w for w in words if w not in ["amp","ferguson",""] and not w.isdigit()]
          if len(words) > 3:
            counts = Counter(words).most_common()
            vec = bow2vec(counts)
            if sum(vec) > 0 :
              if "-lda" in sys.argv or "-lsi" in sys.argv :
                tweets[tid] = dicog.doc2bow(words)
                t2u[tid] = tweet[2]
              else :
                tweets[tid] = vec
        k = k + 1
  print("%s tweets founds." % len(tweets))
  clusterize(tweets)


text:
using System;
using System.IO;
using System.Text;
using System.Collections;

namespace Nini.Ini
{
	#region IniReadState enumeration
	/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/docs/*' />
	public enum IniReadState : int
	{
		/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/Value[@name="Closed"]/docs/*' />
		Closed,
		/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/Value[@name="EndOfFile"]/docs/*' />
		EndOfFile,
		/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/Value[@name="Error"]/docs/*' />
		Error,
		/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/Value[@name="Initial"]/docs/*' />
		Initial,
		/// <include file='IniReader.xml' path='//Enum[@name="IniReadState"]/Value[@name="Interactive"]/docs/*' />
		Interactive
	};
	#endregion

	#region IniType enumeration
	/// <include file='IniReader.xml' path='//Enum[@name="IniType"]/docs/*' />
	public enum IniType : int
	{
		/// <include file='IniReader.xml' path='//Enum[@name="IniType"]/Value[@name="Section"]/docs/*' />
		Section,
		/// <include file='IniReader.xml' path='//Enum[@name="IniType"]/Value[@name="Key"]/docs/*' />
		Key,
		/// <include file='IniReader.xml' path='//Enum[@name="IniType"]/Value[@name="Empty"]/docs/*' />
		Empty
	}
	#endregion

	/// <include file='IniReader.xml' path='//Class[@name="IniReader"]/docs/*' />
	public class IniReader : IDisposable
	{
		#region Private variables
		int lineNumber = 1;
		int column = 1;
		IniType iniType = IniType.Empty;
		TextReader textReader = null;
		bool ignoreComments = false;
		StringBuilder name = new StringBuilder ();
		StringBuilder value = new StringBuilder ();
		StringBuilder comment = new StringBuilder ();
		IniReadState readState = IniReadState.Initial;
		bool hasComment = false;
		bool disposed = false;
		bool lineContinuation = false;
		bool acceptCommentAfterKey = true;
		bool acceptNoAssignmentOperator = false;
		bool consumeAllKeyText = false;
		char[] commentDelimiters = new char[] { ';' };
		char[] assignDelimiters = new char[] { '=' };
		#endregion

		#region Public properties
		/// <include file='IniReader.xml' path='//Property[@name="Name"]/docs/*' />
		public string Name
		{
			get { return this.name.ToString (); }
		}

		/// <include file='IniReader.xml' path='//Property[@name="Value"]/docs/*' />
		public string Value
		{
			get { return this.value.ToString (); }
		}

		/// <include file='IniReader.xml' path='//Property[@name="Type"]/docs/*' />
		public IniType Type
		{
			get { return iniType; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="Comment"]/docs/*' />
		public string Comment
		{
			get { return (hasComment) ? this.comment.ToString () : null; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="LineNumber"]/docs/*' />
		public int LineNumber
		{
			get { return lineNumber; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="LinePosition"]/docs/*' />
		public int LinePosition
		{
			get { return column; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="IgnoreComments"]/docs/*' />
		public bool IgnoreComments
		{
			get { return ignoreComments; }
			set { ignoreComments = value; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="ReadState"]/docs/*' />
		public IniReadState ReadState
		{
			get { return readState; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="LineContinuation"]/docs/*' />
		public bool LineContinuation
		{
			get { return lineContinuation; }
			set { lineContinuation = value; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="AcceptCommentAfterKey"]/docs/*' />
		public bool AcceptCommentAfterKey
		{
			get { return acceptCommentAfterKey; }
			set { acceptCommentAfterKey = value; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="AcceptNoAssignmentOperator"]/docs/*' />
		public bool AcceptNoAssignmentOperator
		{
			get { return acceptNoAssignmentOperator; }
			set { acceptNoAssignmentOperator = value; }
		}

		/// <include file='IniReader.xml' path='//Property[@name="ConsumeAllKeyText"]/docs/*' />
		public bool ConsumeAllKeyText
		{
			get { return consumeAllKeyText; }
			set { consumeAllKeyText = value; }
		}
		#endregion

		#region Constructors
		/// <include file='IniReader.xml' path='//Constructor[@name="ConstructorPath"]/docs/*' />
		public IniReader (string filePath)
		{
			textReader = new StreamReader (filePath);
		}

		/// <include file='IniReader.xml' path='//Constructor[@name="ConstructorTextReader"]/docs/*' />
		public IniReader (TextReader reader)
		{
			textReader = reader;
		}

		/// <include file='IniReader.xml' path='//Constructor[@name="ConstructorStream"]/docs/*' />
		public IniReader (Stream stream)
			: this (new StreamReader (stream))
		{
		}
		#endregion

		#region Public methods
		/// <include file='IniReader.xml' path='//Method[@name="Read"]/docs/*' />
		public bool Read ()
		{
			bool result = false;

			if (readState != IniReadState.EndOfFile
				|| readState != IniReadState.Closed) {
				readState = IniReadState.Interactive;
				result = ReadNext ();
			}

			return result;
		}

		/// <include file='IniReader.xml' path='//Method[@name="MoveToNextSection"]/docs/*' />
		public bool MoveToNextSection ()
		{
			bool result = false;

			while (true)
			{
				result = Read ();

				if (iniType == IniType.Section || !result) {
					break;
				}
			}

			return result;
		}

		/// <include file='IniReader.xml' path='//Method[@name="MoveToNextKey"]/docs/*' />
		public bool MoveToNextKey ()
		{
			bool result = false;

			while (true)
			{
				result = Read ();

				if (iniType == IniType.Section) {
					result = false;
					break;
				}
				if (iniType == IniType.Key || !result) {
					break;
				}
			}

			return result;
		}

		/// <include file='IniReader.xml' path='//Method[@name="Close"]/docs/*' />
		public void Close ()
		{
			Reset ();
			readState = IniReadState.Closed;

			if (textReader != null) {
				textReader.Close ();
			}
		}

		/// <include file='IniReader.xml' path='//Method[@name="Dispose"]/docs/*' />
		public void Dispose ()
		{
			Dispose (true);
		}

		/// <include file='IniReader.xml' path='//Method[@name="GetCommentDelimiters"]/docs/*' />
		public char[] GetCommentDelimiters ()
		{
			char[] result = new char[commentDelimiters.Length];
			Array.Copy (commentDelimiters, 0, result, 0, commentDelimiters.Length);

			return result;
		}

		/// <include file='IniReader.xml' path='//Method[@name="SetCommentDelimiters"]/docs/*' />
		public void SetCommentDelimiters (char[] delimiters)
		{
			if (delimiters.Length < 1) {
				throw new ArgumentException ("Must supply at least one delimiter");
			}

			commentDelimiters = delimiters;
		}

		/// <include file='IniReader.xml' path='//Method[@name="GetAssignDelimiters"]/docs/*' />
		public char[] GetAssignDelimiters ()
		{
			char[] result = new char[assignDelimiters.Length];
			Array.Copy (assignDelimiters, 0, result, 0, assignDelimiters.Length);

			return result;
		}

		/// <include file='IniReader.xml' path='//Method[@name="SetAssignDelimiters"]/docs/*' />
		public void SetAssignDelimiters (char[] delimiters)
		{
			if (delimiters.Length < 1) {
				throw new ArgumentException ("Must supply at least one delimiter");
			}

			assignDelimiters = delimiters;
		}
		#endregion

		#region Protected methods
		/// <include file='IniReader.xml' path='//Method[@name="DisposeBoolean"]/docs/*' />
		protected virtual void Dispose (bool disposing)
		{
			if (!disposed) {
				textReader.Close ();
				disposed = true;

				if (disposing) {
					GC.SuppressFinalize (this);
				}
			}
		}
		#endregion

		#region Private methods
		/// <summary>
		/// Destructor.
		/// </summary>
		~IniReader ()
		{
			Dispose (false);
		}

		/// <summary>
		/// Resets all of the current INI line data.
		/// </summary>
		private void Reset ()
		{
			this.name.Remove (0, this.name.Length);
			this.value.Remove (0, this.value.Length);
			this.comment.Remove (0, this.comment.Length);
			iniType = IniType.Empty;
			hasComment = false;
		}

		/// <summary>
		/// Reads the next INI line item.
		/// </summary>
		private bool ReadNext ()
		{
			bool result = true;
			int ch = PeekChar ();
			Reset ();

			if (IsComment (ch)) {
				iniType = IniType.Empty;
				ReadChar (); // consume comment character
				ReadComment ();

				return result;
			}

			switch (ch)
			{
				case ' ':
				case '\t':
				case '\r':
					SkipWhitespace ();
					ReadNext ();
					break;
				case '\n':
					ReadChar ();
					break;
				case '[':
					ReadSection ();
					break;
				case -1:
					readState = IniReadState.EndOfFile;
					result = false;
					break;
				default:
					ReadKey ();
					break;
			}

			return result;
		}

		/// <summary>
		/// Reads a comment. Must start after the comment delimiter.
		/// </summary>
		private void ReadComment  ()
		{
			int ch = -1;
			SkipWhitespace ();
			hasComment = true;

			do
			{
				ch = ReadChar ();
				this.comment.Append ((char)ch);
			} while (!EndOfLine (ch));

			RemoveTrailingWhitespace (this.comment);
		}

		/// <summary>
		/// Removes trailing whitespace from a StringBuilder.
		/// </summary>
		private void RemoveTrailingWhitespace (StringBuilder builder)
		{
			string temp = builder.ToString ();

			builder.Remove (0, builder.Length);
			builder.Append (temp.TrimEnd (null));
		}

		/// <summary>
		/// Reads a key.
		/// </summary>
		private void ReadKey ()
		{
			int ch = -1;
			iniType = IniType.Key;

			while (true)
			{
				ch = PeekChar ();

				if (IsAssign (ch)) {
					ReadChar ();
					break;
				}

				if (EndOfLine (ch)) {
					if (acceptNoAssignmentOperator) {
						break;
					}
					throw new IniException (this,
						String.Format ("Expected assignment operator ({0})",
										assignDelimiters[0]));
				}

				this.name.Append ((char)ReadChar ());
			}

			ReadKeyValue ();
			SearchForComment ();
			RemoveTrailingWhitespace (this.name);
		}

		/// <summary>
		/// Reads the value of a key.
		/// </summary>
		private void ReadKeyValue ()
		{
			int ch = -1;
			bool foundQuote = false;
			int characters = 0;
			SkipWhitespace ();

			while (true)
			{
				ch = PeekChar ();

				if (!IsWhitespace (ch)) {
					characters++;
				}

				if (!this.ConsumeAllKeyText && ch == '"') {
					ReadChar ();

					if (!foundQuote && characters == 1) {
						foundQuote = true;
						continue;
					} else {
						break;
					}
				}

				if (foundQuote && EndOfLine (ch)) {
					throw new IniException (this, "Expected closing quote (\")");
				}

				// Handle line continuation
				if (lineContinuation && ch == '\\')
				{
					StringBuilder buffer = new StringBuilder ();
					buffer.Append ((char)ReadChar ()); // append '\'

					while (PeekChar () != '\n' && IsWhitespace (PeekChar ()))
					{
						if (PeekChar () != '\r') {
							buffer.Append ((char)ReadChar ());
						} else {
							ReadChar (); // consume '\r'
						}
					}

					if (PeekChar () == '\n') {
						// continue reading key value on next line
						ReadChar ();
						continue;
					} else {
						// Replace consumed characters
						this.value.Append (buffer.ToString ());
					}
				}

				if (!this.ConsumeAllKeyText) {
					// If accepting comments then don't consume as key value
					if (acceptCommentAfterKey && IsComment (ch) && !foundQuote) {
						break;
					}
				}

				// Always break at end of line
				if (EndOfLine (ch)) {
					break;
				}

				this.value.Append ((char)ReadChar ());
			}

			if (!foundQuote) {
				RemoveTrailingWhitespace (this.value);
			}
		}

		/// <summary>
		/// Reads an INI section.
		/// </summary>
		private void ReadSection ()
		{
			int ch = -1;
			iniType = IniType.Section;
			ch = ReadChar (); // consume "["

			while (true)
			{
				ch = PeekChar ();
				if (ch == ']') {
					break;
				}
				if (EndOfLine (ch)) {
					throw new IniException (this, "Expected section end (])");
				}

				this.name.Append ((char)ReadChar ());
			}

			ConsumeToEnd (); // all after '[' is garbage
			RemoveTrailingWhitespace (this.name);
		}

		/// <summary>
		/// Looks for a comment.
		/// </summary>
		private void SearchForComment ()
		{
			int ch = ReadChar ();

			while (!EndOfLine (ch))
			{
				if (IsComment (ch)) {
					if (ignoreComments) {
						ConsumeToEnd ();
					} else {
						ReadComment ();
					}
					break;
				}
				ch = ReadChar ();
			}
		}

		/// <summary>
		/// Consumes all data until the end of a line.
		/// </summary>
		private void ConsumeToEnd ()
		{
			int ch = -1;

			do
			{
				ch = ReadChar ();
			} while (!EndOfLine (ch));
		}

		/// <summary>
		/// Returns and consumes the next character from the stream.
		/// </summary>
		private int ReadChar ()
		{
			int result = textReader.Read ();

			if (result == '\n') {
				lineNumber++;
				column = 1;
			} else {
				column++;
			}

			return result;
		}

		/// <summary>
		/// Returns the next upcoming character from the stream.
		/// </summary>
		private int PeekChar ()
		{
			return textReader.Peek ();
		}

		/// <summary>
		/// Returns true if a comment character is found.
		/// </summary>
		private bool IsComment (int ch)
		{
			return HasCharacter (commentDelimiters, ch);
		}

		/// <summary>
		/// Returns true if character is an assign character.
		/// </summary>
		private bool IsAssign (int ch)
		{
			return HasCharacter (assignDelimiters, ch);
		}

		/// <summary>
		/// Returns true if the character is found in the given array.
		/// </summary>
		private bool HasCharacter (char[] characters, int ch)
		{
			bool result = false;

			for (int i = 0; i < characters.Length; i++)
			{
				if (ch == characters[i])
				{
					result = true;
					break;
				}
			}

			return result;
		}

		/// <summary>
		/// Returns true if a value is whitespace.
		/// </summary>
		private bool IsWhitespace (int ch)
		{
			return ch == 0x20 || ch == 0x9 || ch == 0xD || ch == 0xA;
		}

		/// <summary>
		/// Skips all whitespace.
		/// </summary>
		private void SkipWhitespace ()
		{
			while (IsWhitespace (PeekChar ()))
			{
				if (EndOfLine (PeekChar ())) {
					break;
				}

				ReadChar ();
			}
		}

		/// <summary>
		/// Returns true if an end of line is found.  End of line
		/// includes both an end of line or end of file.
		/// </summary>
		private bool EndOfLine (int ch)
		{
			return (ch == '\n' || ch == -1);
		}
		#endregion
	}
}


text:
#pragma once

#include <map>
#include <QList>
#include <QStringList>
#include <sstream>
#include <cassert>

namespace clockwork {

template<class KeyType, class ValueType>
class Factory
{
public:
   /**
    * Instantiate a Factory with a default key.
    * @param key the factory's default key.
    */
   explicit Factory(const KeyType& key) :
   _defaultKey(key)
   {}
   /**
    * The destructor.
    */
   virtual ~Factory()
   {
      _map.clear();
   }
   /**
    * Return the default key.
    */
   const KeyType& getDefaultKey() const
   {
      return _defaultKey;
   }
   /**
    * Return a list of keys in the factory.
    */
   QList<KeyType> getKeys() const
   {
      QList<KeyType> output;
      for (const auto& entry : _map)
         output << entry.first;

      return output;
   }
   /**
    * Return the keys in the form of a list of strings.
    */
   QStringList getKeysAsStrings() const
   {
      QStringList output;
      std::stringstream sstream;

      for (const auto& entry : _map)
      {
         sstream << entry.first;
         output << QString(sstream.str());

         // Clear the string stream.
         sstream.str(std::string());
      }
      return output;
   }
   /**
    * Return the default value, i.e. the value associated to the default key.
    */
   ValueType& getDefaultValue()
   {
      return get(_defaultKey);
   }
   /**
    * Return an element from the factory associated to the given key.
    * @param key the element's key.
    */
   ValueType& get(const KeyType& key)
   {
      assert(exists(key));
      return _map[key];
   }
   /**
    * Delete an item with the given key from the factory.
    * @param key the element's key.
    */
   void remove(const KeyType& key)
   {
      if (exists(key))
         _map.erase(key);
   }
   /**
    * Add an element to the factory.
    * @param key the element's key.
    * @param value the actual element.
    */
   void put(const KeyType& key, ValueType value)
   {
      // If the key exists, then remove its old value before setting a new one.
      if (exists(key))
         remove(key);

      _map.insert(std::pair<const KeyType, ValueType>(key, value));
   }
   /**
    * Return true if a given key exists in the factory.
    * @param key the key to query.
    */
   bool exists(const KeyType& key) const
   {
      return (!_map.empty() && _map.find(key) != _map.end());
   }
private:
   /**
    * The default key.
    */
   const KeyType _defaultKey;
   /**
    * The map containing key-value pairs.
    */
   std::map<KeyType, ValueType> _map;
};

} // namespace clockwork


text:
package com.example.residentevil.configuration;

import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class ApplicationBeanConfiguration {

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { Comp3423Component } from './comp-3423.component';

describe('Comp3423Component', () => {
  let component: Comp3423Component;
  let fixture: ComponentFixture<Comp3423Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ Comp3423Component ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Comp3423Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
<!-- **************************************************************************
#
# Copyright (C) 2004-2009 Oracle Corporation
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#         Kohsuke Kawaguchi
#
#************************************************************************** -->

<div>
  Mavenでのビルドで必要となるプロパティをここに(標準のプロパティファイル形式で)指定します。:
  <pre># comment
name1=value1
name2=value2
</pre>
  これらのプロパティは、Mavenに<tt>"-Dname1=value1 -Dname2=value2"</tt>のように渡されます。
</div>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using Xunit;
using Tests.HashSet_HashSetTestSupport;

namespace Tests
{
    public class HashSet_TrimExcessTests
    {
        //Test 1: Set is empty
        [Fact]
        public static void TrimExcess_Test1()
        {
            HashSet<int> hashSet;

            hashSet = new HashSet<int>();
            hashSet.TrimExcess();

            HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], EqualityComparer<int>.Default);
        }

        //Test 2: Set is full
        [Fact]
        public static void TrimExcess_Test2()
        {
            HashSet<int> hashSet;
            int[] values;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 197, out values);
            hashSet.TrimExcess();

            HashSetTestSupport<int>.VerifyHashSet(hashSet, values, EqualityComparer<int>.Default);
        }

        //Test 3: Call Repeatedly
        [Fact]
        public static void TrimExcess_Test3()
        {
            HashSet<int> hashSet;
            int[] values;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 197, out values);
            hashSet.Clear();
            hashSet.TrimExcess();
            hashSet.TrimExcess();

            HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[0], EqualityComparer<int>.Default);
        }

        //Test 4: Call, Remove one so trimming would change, Call Again
        [Fact]
        public static void TrimExcess_Test4()
        {
            HashSet<int> hashSet;
            HashSet<int> hashSet2;
            int[] values;
            List<int> remainingValues;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 198, out values);
            remainingValues = new List<int>(values);
            hashSet.Remove(0);
            remainingValues.Remove(0);
            hashSet.TrimExcess();

            hashSet2 = new HashSet<int>();
            AddItemsInt(hashSet2, 197);

            HashSetTestSupport<int>.VerifyHashSet(hashSet, remainingValues, EqualityComparer<int>.Default);
        }

        //Test 5: Array is Large and Sparse
        [Fact]
        public static void TrimExcess_Test5()
        {
            HashSet<int> hashSet;
            HashSet<int> hashSet2;
            int[] values;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 17519);
            hashSet.Clear();
            AddItemsInt(hashSet, 197, out values);
            hashSet.TrimExcess();

            hashSet2 = new HashSet<int>();
            AddItemsInt(hashSet2, 197);

            HashSetTestSupport<int>.VerifyHashSet(hashSet, values, EqualityComparer<int>.Default);
        }

        //Test 6: Array is Large and mostly full (some trimming should occur)
        [Fact]
        public static void TrimExcess_Test6()
        {
            HashSet<int> hashSet;
            HashSet<int> hashSet2;
            int[] values;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 17519);
            hashSet.Clear();
            AddItemsInt(hashSet, 8419, out values);
            hashSet.TrimExcess();

            hashSet2 = new HashSet<int>();
            AddItemsInt(hashSet2, 8419);

            HashSetTestSupport<int>.VerifyHashSet(hashSet, values, EqualityComparer<int>.Default);
        }

        //Test 7: Array is Large and mostly full (no trimming should occur)
        [Fact]
        public static void TrimExcess_Test7()
        {
            HashSet<int> hashSet;
            int[] values;

            hashSet = new HashSet<int>();
            AddItemsInt(hashSet, 17519);
            hashSet.Clear();
            AddItemsInt(hashSet, 17000, out values);
            hashSet.TrimExcess();

            HashSetTestSupport<int>.VerifyHashSet(hashSet, values, EqualityComparer<int>.Default);
        }

        public static void AddItemsInt(HashSet<int> set, int number)
        {
            int nextInt = 1;
            Func<int> nextIntFunc = () =>
            {
                int current = nextInt;
                nextInt++;
                return current;
            };

            set.Add(0);
            for (int x = 1; x < number; x++)
            {
                bool notAdded = false;
                while (!notAdded)
                {
                    int value = nextIntFunc();
                    notAdded = set.Add(value);
                }
            }
        }

        public static void AddItemsInt(HashSet<int> set, int number, out int[] values)
        {
            int nextInt = 1;
            Func<int> nextIntFunc = () =>
            {
                int current = nextInt;
                nextInt++;
                return current;
            };

            values = new int[number];
            set.Add(0);
            values[0] = 0;
            for (int x = 1; x < number; x++)
            {
                bool notAdded = false;
                while (!notAdded)
                {
                    int value = nextIntFunc();
                    notAdded = set.Add(value);
                    values[x] = value;
                }
            }
        }
    }
}