text:
// THIS FILE IS GENERATED BY ZAP

#pragma once

void __attribute__((weak)) MatterIdentifyPluginClientInitCallback() {}
void MatterIdentifyPluginServerInitCallback();
void __attribute__((weak)) MatterGroupsPluginClientInitCallback() {}
void MatterGroupsPluginServerInitCallback();
void __attribute__((weak)) MatterScenesPluginClientInitCallback() {}
void MatterScenesPluginServerInitCallback();
void __attribute__((weak)) MatterOnOffPluginClientInitCallback() {}
void MatterOnOffPluginServerInitCallback();
void __attribute__((weak)) MatterOnOffSwitchConfigurationPluginClientInitCallback() {}
void MatterOnOffSwitchConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterLevelControlPluginClientInitCallback() {}
void MatterLevelControlPluginServerInitCallback();
void __attribute__((weak)) MatterBinaryInputBasicPluginClientInitCallback() {}
void MatterBinaryInputBasicPluginServerInitCallback();
void __attribute__((weak)) MatterPulseWidthModulationPluginClientInitCallback() {}
void MatterPulseWidthModulationPluginServerInitCallback();
void __attribute__((weak)) MatterDescriptorPluginClientInitCallback() {}
void MatterDescriptorPluginServerInitCallback();
void __attribute__((weak)) MatterBindingPluginClientInitCallback() {}
void MatterBindingPluginServerInitCallback();
void __attribute__((weak)) MatterAccessControlPluginClientInitCallback() {}
void MatterAccessControlPluginServerInitCallback();
void __attribute__((weak)) MatterBridgedActionsPluginClientInitCallback() {}
void MatterBridgedActionsPluginServerInitCallback();
void __attribute__((weak)) MatterBasicPluginClientInitCallback() {}
void MatterBasicPluginServerInitCallback();
void __attribute__((weak)) MatterOtaSoftwareUpdateProviderPluginClientInitCallback() {}
void MatterOtaSoftwareUpdateProviderPluginServerInitCallback();
void __attribute__((weak)) MatterOtaSoftwareUpdateRequestorPluginClientInitCallback() {}
void MatterOtaSoftwareUpdateRequestorPluginServerInitCallback();
void __attribute__((weak)) MatterLocalizationConfigurationPluginClientInitCallback() {}
void MatterLocalizationConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterTimeFormatLocalizationPluginClientInitCallback() {}
void MatterTimeFormatLocalizationPluginServerInitCallback();
void __attribute__((weak)) MatterUnitLocalizationPluginClientInitCallback() {}
void MatterUnitLocalizationPluginServerInitCallback();
void __attribute__((weak)) MatterPowerSourceConfigurationPluginClientInitCallback() {}
void MatterPowerSourceConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterPowerSourcePluginClientInitCallback() {}
void MatterPowerSourcePluginServerInitCallback();
void __attribute__((weak)) MatterGeneralCommissioningPluginClientInitCallback() {}
void MatterGeneralCommissioningPluginServerInitCallback();
void __attribute__((weak)) MatterNetworkCommissioningPluginClientInitCallback() {}
void MatterNetworkCommissioningPluginServerInitCallback();
void __attribute__((weak)) MatterDiagnosticLogsPluginClientInitCallback() {}
void MatterDiagnosticLogsPluginServerInitCallback();
void __attribute__((weak)) MatterGeneralDiagnosticsPluginClientInitCallback() {}
void MatterGeneralDiagnosticsPluginServerInitCallback();
void __attribute__((weak)) MatterSoftwareDiagnosticsPluginClientInitCallback() {}
void MatterSoftwareDiagnosticsPluginServerInitCallback();
void __attribute__((weak)) MatterThreadNetworkDiagnosticsPluginClientInitCallback() {}
void MatterThreadNetworkDiagnosticsPluginServerInitCallback();
void __attribute__((weak)) MatterWiFiNetworkDiagnosticsPluginClientInitCallback() {}
void MatterWiFiNetworkDiagnosticsPluginServerInitCallback();
void __attribute__((weak)) MatterEthernetNetworkDiagnosticsPluginClientInitCallback() {}
void MatterEthernetNetworkDiagnosticsPluginServerInitCallback();
void __attribute__((weak)) MatterTimeSynchronizationPluginClientInitCallback() {}
void MatterTimeSynchronizationPluginServerInitCallback();
void __attribute__((weak)) MatterBridgedDeviceBasicPluginClientInitCallback() {}
void MatterBridgedDeviceBasicPluginServerInitCallback();
void __attribute__((weak)) MatterSwitchPluginClientInitCallback() {}
void MatterSwitchPluginServerInitCallback();
void __attribute__((weak)) MatterAdministratorCommissioningPluginClientInitCallback() {}
void MatterAdministratorCommissioningPluginServerInitCallback();
void __attribute__((weak)) MatterOperationalCredentialsPluginClientInitCallback() {}
void MatterOperationalCredentialsPluginServerInitCallback();
void __attribute__((weak)) MatterGroupKeyManagementPluginClientInitCallback() {}
void MatterGroupKeyManagementPluginServerInitCallback();
void __attribute__((weak)) MatterFixedLabelPluginClientInitCallback() {}
void MatterFixedLabelPluginServerInitCallback();
void __attribute__((weak)) MatterUserLabelPluginClientInitCallback() {}
void MatterUserLabelPluginServerInitCallback();
void __attribute__((weak)) MatterProxyConfigurationPluginClientInitCallback() {}
void MatterProxyConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterProxyDiscoveryPluginClientInitCallback() {}
void MatterProxyDiscoveryPluginServerInitCallback();
void __attribute__((weak)) MatterProxyValidPluginClientInitCallback() {}
void MatterProxyValidPluginServerInitCallback();
void __attribute__((weak)) MatterBooleanStatePluginClientInitCallback() {}
void MatterBooleanStatePluginServerInitCallback();
void __attribute__((weak)) MatterModeSelectPluginClientInitCallback() {}
void MatterModeSelectPluginServerInitCallback();
void __attribute__((weak)) MatterDoorLockPluginClientInitCallback() {}
void MatterDoorLockPluginServerInitCallback();
void __attribute__((weak)) MatterWindowCoveringPluginClientInitCallback() {}
void MatterWindowCoveringPluginServerInitCallback();
void __attribute__((weak)) MatterBarrierControlPluginClientInitCallback() {}
void MatterBarrierControlPluginServerInitCallback();
void __attribute__((weak)) MatterPumpConfigurationAndControlPluginClientInitCallback() {}
void MatterPumpConfigurationAndControlPluginServerInitCallback();
void __attribute__((weak)) MatterThermostatPluginClientInitCallback() {}
void MatterThermostatPluginServerInitCallback();
void __attribute__((weak)) MatterFanControlPluginClientInitCallback() {}
void MatterFanControlPluginServerInitCallback();
void __attribute__((weak)) MatterThermostatUserInterfaceConfigurationPluginClientInitCallback() {}
void MatterThermostatUserInterfaceConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterColorControlPluginClientInitCallback() {}
void MatterColorControlPluginServerInitCallback();
void __attribute__((weak)) MatterBallastConfigurationPluginClientInitCallback() {}
void MatterBallastConfigurationPluginServerInitCallback();
void __attribute__((weak)) MatterIlluminanceMeasurementPluginClientInitCallback() {}
void MatterIlluminanceMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterTemperatureMeasurementPluginClientInitCallback() {}
void MatterTemperatureMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterPressureMeasurementPluginClientInitCallback() {}
void MatterPressureMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterFlowMeasurementPluginClientInitCallback() {}
void MatterFlowMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterRelativeHumidityMeasurementPluginClientInitCallback() {}
void MatterRelativeHumidityMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterOccupancySensingPluginClientInitCallback() {}
void MatterOccupancySensingPluginServerInitCallback();
void __attribute__((weak)) MatterWakeOnLanPluginClientInitCallback() {}
void MatterWakeOnLanPluginServerInitCallback();
void __attribute__((weak)) MatterChannelPluginClientInitCallback() {}
void MatterChannelPluginServerInitCallback();
void __attribute__((weak)) MatterTargetNavigatorPluginClientInitCallback() {}
void MatterTargetNavigatorPluginServerInitCallback();
void __attribute__((weak)) MatterMediaPlaybackPluginClientInitCallback() {}
void MatterMediaPlaybackPluginServerInitCallback();
void __attribute__((weak)) MatterMediaInputPluginClientInitCallback() {}
void MatterMediaInputPluginServerInitCallback();
void __attribute__((weak)) MatterLowPowerPluginClientInitCallback() {}
void MatterLowPowerPluginServerInitCallback();
void __attribute__((weak)) MatterKeypadInputPluginClientInitCallback() {}
void MatterKeypadInputPluginServerInitCallback();
void __attribute__((weak)) MatterContentLauncherPluginClientInitCallback() {}
void MatterContentLauncherPluginServerInitCallback();
void __attribute__((weak)) MatterAudioOutputPluginClientInitCallback() {}
void MatterAudioOutputPluginServerInitCallback();
void __attribute__((weak)) MatterApplicationLauncherPluginClientInitCallback() {}
void MatterApplicationLauncherPluginServerInitCallback();
void __attribute__((weak)) MatterApplicationBasicPluginClientInitCallback() {}
void MatterApplicationBasicPluginServerInitCallback();
void __attribute__((weak)) MatterAccountLoginPluginClientInitCallback() {}
void MatterAccountLoginPluginServerInitCallback();
void __attribute__((weak)) MatterElectricalMeasurementPluginClientInitCallback() {}
void MatterElectricalMeasurementPluginServerInitCallback();
void __attribute__((weak)) MatterTestClusterPluginClientInitCallback() {}
void MatterTestClusterPluginServerInitCallback();


text:
import socket
import binascii
import re
import logging
import time
from contextlib import contextmanager
from functools import wraps

from django.conf import settings

from paucore.stats.slowjam import slowjam_context

logger = logging.getLogger(__name__)

class DummySocket(object):

    def sendto(self, value, addr):
        pass

class StatsdClient(object):
    """A very basic client for aggregating application stats to statsd/graphite

    Some guiding ideas:
    1- Always log stats to a bucket based on the current machine (and region)
    2- Most stats are based on the current application and evironment so make that the default prefix
    3- Some metrics don't fit neatly within an application bucket (ex: size of message queues). Allow overriding the
    prefix/bucket so the stat gets logged to somewhere other than #2
    """

    def __init__(self, hosts, app, environment, region, machine):
        if settings.UNIT_TESTING:
            self.sock = DummySocket()
        else:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        addrs = []
        for host in hosts:
            host, port = host.split(':', 1)
            port = int(port)
            addrs.append((socket.gethostbyname(host), port))

        self.addrs = addrs
        self.count = len(addrs)
        self.app = app
        self.environment = environment
        self.region = region
        self.machine = re.sub(r"\.", "-", machine)

    def get_addr(self, stat):
        return self.addrs[(binascii.crc32(stat) & 0xffffffff) % self.count]

    def make_prefix(self, prefix):
        if prefix is None:
            return '%s.%s' % (self.environment, self.app)
        else:
            return prefix

    def graphite_duration(self, stat, elapsed_time, prefix=None, fmt=None, extras=None):
        try:
            self.sock.sendto('all.%s.%s:%d|ms' % (self.make_prefix(prefix), stat, elapsed_time), self.get_addr(stat))
        except:
            logger.exception('Dropping graphite_duration stat=%s on floor:', stat)

    def graphite_count(self, stat, delta, prefix=None, fmt=None, extras=None):
        try:
            self.sock.sendto('all.%s.%s:%d|c' % (self.make_prefix(prefix), stat, delta), self.get_addr(stat))
        except:
            logger.exception('Dropping graphite_count=%s on floor:', stat)

    def graphite_gauge(self, stat, value, prefix=None):
        # n.b., you should probably only use these from guaranteed-unique tasks
        try:
            self.sock.sendto('all.%s.%s:%d|g' % (self.make_prefix(prefix), stat, value), self.get_addr(stat))
        except:
            logger.exception('Dropping graphite_gauge=%s on floor:', stat)

    def graphite_set(self, stat, value, prefix=None):
        # only put id-like values in here
        try:
            self.sock.sendto('all.%s.%s:%s|s' % (self.make_prefix(prefix), stat, value), self.get_addr(stat))
        except:
            logger.exception('Dropping graphite_set=%s on floor:', stat)

app = getattr(settings, 'HOSTING_APP', 'unknown')
environment = getattr(settings, 'ENVIRONMENT', 'unknown')
region = getattr(settings, 'REGION', 'unknown')
machine = getattr(settings, 'SERVER_HOSTNAME', 'unknown')

hosts = getattr(settings, 'STATSD_HOSTS', ['localhost:8125'])

_instance = StatsdClient(hosts, app, environment, region, machine)

def graphite_duration(stat, elapsed_time, prefix=None):
    # TODO: Hook this up to slowjam?
    if _instance:
        _instance.graphite_duration(stat, elapsed_time, prefix)

def graphite_count(stat, delta=1, prefix=None, fmt=None, extras=None, tag=None):
    slowjam_context.mark(stat, fmt, extras, tag)
    if _instance:
        _instance.graphite_count(stat, delta, prefix)

def graphite_increment(stats, prefix=None):
    graphite_count(stats, 1, prefix)

def graphite_decrement(stats, prefix=None):
    graphite_count(stats, -1, prefix)

def graphite_gauge(stat, value, prefix=None):
    if _instance:
        _instance.graphite_gauge(stat, value, prefix=prefix)

def graphite_set(stat, value, prefix=None):
    if _instance:
        _instance.graphite_set(stat, value, prefix=prefix)

@contextmanager
def graphite_timer(stat, label=None, logger=logging.getLogger('timer'), prefix=None, extras=None, tag=None):
    start_time = time.time()

    with slowjam_context.event(stat, fmt=label, extras=extras, tag=tag) as ctx:
        yield ctx

    end_time = time.time()
    request_time_ms = (end_time - start_time) * 1000

    if _instance:
        _instance.graphite_duration(stat, request_time_ms, prefix)

    if label:
        logger.info("%s took %dms" % (label, request_time_ms))

def timer(stat, label=None, logger=logging.getLogger('timer'), prefix=None, extras=None, tag=None, log_args=False):
    def timer_decorator(f):
        @wraps(f)
        def wrapped_f(*args, **kwargs):
            _extras = dict(extras) if extras else {}
            if log_args:
                if args:
                    _extras['args'] = args
                if kwargs:
                    _extras['kwargs'] = kwargs
            with graphite_timer(stat, label=label, logger=logger, prefix=prefix, extras=_extras, tag=tag):
                return f(*args, **kwargs)
        return wrapped_f
    return timer_decorator

redpajama_set_name: RedPajamaGithub


text:
#include <iostream>
#include <memory>
#include <vector>

#include "HandEvaluator\HandEvaluator.h"

#include "Action.h"
#include "Board.h"
#include "Player.h"
#include "Position.h"
#include "StateType.h"
#include "Street.h"

class State
{
public:
	State();
	State(std::vector<Player>& players,
		std::shared_ptr<Board> board,
		double pot,
		Position::Position seatToAct,
		Position::Position lastBettor,
		Street street,
		double wagerToCall,
		double playerWager,
		std::shared_ptr<State> prevState,
		StateType::StateType nextStateType);
	virtual StateType::StateType Type() const = 0;
	virtual void SetValue(bool isFinal = false) = 0;
public:
	std::shared_ptr<State> PrevState();
	StateType::StateType NextStateType() const;
	void SetNextStateType(StateType::StateType nextStateType);
	const Board& GetBoard() const;
	std::shared_ptr<Board> GetBoard();
	double Pot() const;
	void SetPot(double wager);
	const Player& FirstToAct();
	Position::Position SeatToAct() const;
	void SetSeatToAct();
	void SetSeatToAct(Position::Position position);
	void SetLastActed(Position::Position position);
	Position::Position LastBettor() const;
	void SetLastBettor(Position::Position position);
	Player& ToAct();
	Player& LastActed();
	std::vector<Player>& Players();
	const Player& Hero() const;
	Street CurrentStreet() const;
	void SetStreet(Street street);
	double WagerToCall() const;
	void SetWagerToCall(double wager);
	double PlayerWager() const;
	void SetPlayerWager(double wager);
	bool FacingCheck() const;
	bool IsFinal() const;
	bool IsFinalState() const;
	bool IsClosingAction(const Player& player) const;
	double Value() const;
	double GetPlayerShowdownValue(Player& player);
public:
	State& operator=(const State& rhs);
	friend std::ostream& operator<<(std::ostream& os, const State& state);
protected:
	static constexpr Position::Position NoLastBettor = Position::Position::None;
	static const omp::HandEvaluator evaluator;
protected:
	std::shared_ptr<State> prevState;
	StateType::StateType nextStateType;
	std::vector<Player> players;
	std::shared_ptr<Board> board;
	double pot;
	Position::Position seatToAct;
	Position::Position lastActed;
	Position::Position lastBettor;
	Street street;
	double wagerToCall;
	double playerWager;
	double value;
protected:
	const Player& NextToAct();
private:
	int IndexOf(Position::Position pos) const;
	int IndexOf(const Player& player) const;
	const Player& PlayerAt(Position::Position pos) const;
};


text:
shared_examples "paginated list" do
  it { expect(json_response).to have_key(:meta) }
  it { expect(json_response[:meta]).to have_key(:pagination) }
  it { expect(json_response[:meta][:pagination]).to have_key(:per_page) }
  it { expect(json_response[:meta][:pagination]).to have_key(:total_pages) }
  it { expect(json_response[:meta][:pagination]).to have_key(:total_objects) }
end


text:
layout: post
title: CC2500 Project (Part 7) - More Lights and Power Supplies!
categories:
- cc2500
- projects
tags: []
status: publish
type: post
comments: true
meta:
  blogger_blog: blog.alvarop.com
  blogger_author: ''
  blogger_permalink: /2012/02/cc2500-project-part-7-more-lights-and.html
  dsq_thread_id: '614650587'
---
Here's another quick update (with lots of pictures and a video!) I ordered another RGB LED strip from adafruit in order to test how my system works with multiple devices. I don't have my PCB's yet (I shipped them to NY by mistake...), so I had to build everything on breadboards.

{% include image.html
            img="/images/blgr/s640/IMG_7221.jpg"
            title="My messy work space."
            caption="My messy work space."
            url="/images/blgr/IMG_7221.jpg" %}

The main problem with my previous design is that it required two separate power supplies. The LED strip runs off 12v, while the microcontroller and radio run at 3.33v. I had a couple of MC34063A DC/DC converters laying around, so I figured I'd make a 12-3.3v converter. I also had an LD33V linear regulator, so I decided to try them both.

{% include image.html
            img="/images/blgr/s640/IMG_7225.jpg"
            title=""
            caption=""
            url="/images/blgr/IMG_7225.jpg" %}

Unfortunately, I didn't have the exact parts required to make the switching regulator, so I had to use the closest available. This produced an extremely noisy (± 400mV) output, which resulted in a non-working microcontroller. I was able to temporarily solve the problem with some decoupling capacitors, but I still need to get the right parts to make it more stable. What happened was that the microcontroller would start and then just hang or reset at random. At first I thought it was a code issue, but then I looked at the power supply... I'm glad I bought an oscilloscope, otherwise this problem would have been pretty hard to solve.

{% include image.html
            img="/images/blgr/s640/IMG_7227.jpg"
            title="That's a huge 0.33 Ohm resistor (It's all I had...)"
            caption="That's a huge 0.33 Ohm resistor (It's all I had...)"
            url="/images/blgr/IMG_7227.jpg" %}

Since the DC/DC converter was not behaving too well, I decided to use the linear regulator with the other circuit. Dropping 12v to 3.3v with a linear regulator produces a lot of heat. I had to get a heat sink, otherwise I would burn my hand if I touched it. It's a huge waste of power, but it works for now...

{% include image.html
            img="/images/blgr/s640/IMG_7228.jpg"
            title="Dropping from 12v to 3.3v generates a LOT of heat. (Thankfully, I had a heat sink)"
            caption="Dropping from 12v to 3.3v generates a LOT of heat. (Thankfully, I had a heat sink)"
            url="/images/blgr/IMG_7228.jpg" %}

In order to drive the second LED strip, I had to put together another RGB LED driver board. It's just three MOSFETs, along with some resistors and BJT's to drive them. I connect the 12v power supply directly to these, and then connect it to the microcontroller board's power supply. The next thing to do will be to have them all on the same PCB...

{% include image.html
            img="/images/blgr/s640/IMG_7231.jpg"
            title="RGB LED Driver (There are some surface mount resistors and transistors on the other side)"
            caption="RGB LED Driver (There are some surface mount resistors and transistors on the other side)"
            url="/images/blgr/IMG_7231.jpg" %}

So what did I end up doing with these? Well, I put one on top of a shelf, and the second under... Ok, I don't know what it's called. It might be a kitchen counter-top, but I'm not sure. Here are some photos that will hopefully make more sense.

{% include image.html
            img="/images/blgr/s640/IMG_7236.jpg"
            title="Shelf plus LED strip."
            caption="Shelf plus LED strip."
            url="/images/blgr/IMG_7236.jpg" %}

{% include image.html
            img="/images/blgr/s640/IMG_7240.jpg"
            title=""
            caption=""
            url="/images/blgr/IMG_7240.jpg" %}

I tried getting a video of the whole setup, but my camera doesn't seem to like low light situations. It looks much better in person!


text:
from pandas import DataFrame
from scipy.fftpack import rfft, rfftfreq
import time
import numpy as np

class EMG_preparer():

    """ An EMG_preparer prepares EMG data for training a subvocal recognition classification system. Scipy's cwt algorithm is used to yield energy spectrum summations for each phoneme in a file.

    Attributes:
        window_size: float. Specifies size, in milliseconds, of the Fourier transformed windows to return.
        real_time: boolean. If True, EMG data has real units of time (such as ns or ms). If False, EMG data has sequential sample number as temporal indicator (dimensionless count).
        sample_rate: float. Specifies number of samples per second.
        power_spectrum: boolean. Specifies whether to find a power spectrum using the data after FT has been applied. Practically, this means finding the absolute values of the intensities returned by the Fourier transform so all results are positive. If false, the raw rfft results are used for each window.

    """
    def __init__(self):
        """ Initialize the EMG_preparer Object. """

        pass

    def process(self, data, num_phonemes=None, wavelets=False):
        """ process is a method for summing CWT energies from EMG data into windows for each phoneme in the file.

        Attributes:
            data: a pandas DataFrame containing subvocalization EMG data processed by CWT, with any number of columns.
        Returns:
            a DataFrame containing summed energy spectrum windows for each phoneme based on an even splitting of the data.
        """

        if num_phonemes:
            num_windows = num_phonemes
            self.samples_per_window = int(data.shape[0]//num_windows)

        if wavelets:
            windows = DataFrame()
            # Go through each row from first index to last for each window
            for window in range(num_windows):
                first_index = int(window * self.samples_per_window)
                last_index = int(first_index + self.samples_per_window)
                data_window = DataFrame(data.iloc[first_index:last_index])
                # Sum up the squares of amplitudes in each column
                new_row = data_window.abs().pow(2).sum(axis=0)
                windows = windows.append(new_row, ignore_index = True)
            # Return all the windows
            return windows


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>se.jsa.twyn</groupId>
    <artifactId>twyn</artifactId>
    <version>0.41-beta</version>
    <packaging>jar</packaging>

    <name>twyn</name>
    <url>https://github.com/joakimsahlstrom/twyn</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jackson.version>2.9.10.8</jackson.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.abstractmeta</groupId>
            <artifactId>compilation-toolbox</artifactId>
            <version>0.3.1</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>[4.13.1,)</version>
            <scope>test</scope>
        </dependency>

        <!--
        <dependency>
            <groupId>com.google.testing.compile</groupId>
            <artifactId>compile-testing</artifactId>
            <version>0.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
            <scope>test</scope>
        </dependency>
        -->
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>11</release>
                    <compilerArgument>-proc:none</compilerArgument>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
#ifndef LUDI_GRAPHICS_TESSELLATOR_STAGE_H_
#define LUDI_GRAPHICS_TESSELLATOR_STAGE_H_

namespace ludi {
namespace graphics {
    /*! Represents the tessellator stage. */
    template <>
    class TessellatorStage_<LUDI_GRAPHICS_PLATFORM_BASE> {
    public:
        /*! Represents a tessellator state. */
        class State {
        protected:
            // nothing for now.

        public:
            /*! Constructs a tessellator stage state. */
            inline State();

            /*! Destructor. */
            inline virtual ~State();

        public:
            /*! Clears the state. */
            inline void Clear();

            /*! Touches all the update bits. */
            inline void Touch();

        public:
            // nothing for now.
        };

    protected:
        State current_;		//!< Current state.
        State desired_;		//!< Desired state.

    public:
        /*! Constructs a tessellator stage. */
        inline TessellatorStage_();

        /*! Destructor. */
        inline virtual ~TessellatorStage_();

    public:
        /*! Applies the desired state to the gpu. */
        virtual void Apply(reference_ptr<Context*> context, bool force = false) = 0;
        /*! Restores the current state to the gpu. */
        virtual void Restore() = 0;

    public:
        /*! Clears the desired state. */
        inline virtual void Clear();
        /*! Clears the current state. */
        inline virtual void Reset();

    public:
        const State& current() const { return current_; }
        State& desired() { return desired_; }
    };

} // graphics
} // ludi

// Inline defintion
#include <TessellatorStage.inl>

// Platform-specific definition
#include <Null/TessellatorStage.Null.h>
#include <Metal/TessellatorStage.Metal.h>

#endif // LUDI_GRAPHICS_TESSELLATOR_STAGE_H_


text:
This is a Python script that translates Chinese characters (traditional or simplified) to Hanyu Pinyin.

## Usage

Translation can be applied to a single file or all files in a directory (including nested directories).  By default it translates just the file name, but it can also translate the file contents, or both filename and contents.  There is also an option to translate a given string.

For example, to translate the file contents for a file named `test1.txt` in the `test` directory:
```
python translate.py -f test/test1.txt -p text
```

### Options

The following is a list of the possible options and their default values.

Note that `Short Name` parameters are specified with a single dash (e.g. `-h`), while `Long Name` parameters are specified with a double-dash (e.g. `--help`).

| Short Name | Long Name | Default | Description |
| --- | --- | --- |  --- |
| h | help | - | Shows the script usage and help options. |
| f | file | - | The input file to translate.  One of `file`, `dir`, or `string` is required. |
| d | dir | - | The input directory to translate (translates all files in nested directories).  One of `file`, `dir`, or `string` is required. |
| s | string | - | The string to translate.  One of `file`, `dir`, or `string` is required. |
| p | process | `filename` | Determines what is processed - `filename`, `text`, or `both`. |
| t | tones | `false` | Output the pinyin tone numbers. |
| c | capitalize | `true` | Capitalize the pinyin (otherwise all lower case). |
| b | backup | `true` | Backup each translated file (e.g. `filename.ext.BAK`). |

## License

Copyright 2016 Jeremy Parr-Pearson

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

--------------------------------------------------------------------------------

The following components are provided under the Creative Commons Attribution-ShareAlike 3.0 License.

CC-CEDICT Chinese English Dictionary - [http://cc-cedict.org/](http://cc-cedict.org/)


text:
var pc_progressive;

// load csv file and create the chart
d3.csv('data/itg.csv', function(data) {
  var colorgen = d3.scale.category20();
  var colors = {};
  // _(data).chain()
  //   .pluck('group')
  //   .uniq()
  //   .each(function(d,i) {
  //     colors[d] = colorgen(i);
  //   });

  var color = function(d) { return colors[d.group]; };

  pc_progressive = d3.parcoords()("#example-progressive")
    .data(data)
    .color(color)
    .alpha(0.4)
    .margin({ top: 24, left: 150, bottom: 12, right: 0 })
    .mode("queue")
    .render()
    .brushable()  // enable brushing
    .interactive()  // command line mode

  pc_progressive.svg.selectAll("text")
    .style("font", "10px sans-serif");
});


text:
package org.apache.wicket.markup;

/**
 * Holds markup as a resource (the stream that the markup came from) and a list of MarkupElements
 * (the markup itself).
 *
 * @see MarkupElement
 * @see ComponentTag
 * @see org.apache.wicket.markup.RawMarkup
 *
 * @author Jonathan Locke
 * @author Juergen Donnerstag
 */
public abstract interface IMarkup
{
	/**
	 * Find the markup element index of the component with 'path'
	 *
	 * @param path
	 *            The component path expression
	 * @param id
	 *            The component's id to search for
	 * @return -1, if not found
	 */
	int findComponentIndex(final String path, final String id);

	/**
	 * For Wicket it would be sufficient for this method to be package protected. However to allow
	 * wicket-bench easy access to the information ...
	 *
	 * @param index
	 *            Index into markup list
	 * @return Markup element
	 */
	MarkupElement get(final int index);

	/**
	 * Gets the markup encoding. A markup encoding may be specified in a markup file with an XML
	 * encoding specifier of the form <?xml ... encoding="..." ?>.
	 *
	 * @return Encoding, or null if not found.
	 */
	String getEncoding();

	/**
	 * Gets the resource that contains this markup
	 *
	 * @return The resource where this markup came from
	 */
	MarkupResourceStream getResource();

	/**
	 * Get the wicket namespace valid for this specific markup
	 *
	 * @return wicket namespace
	 */
	String getWicketNamespace();

	/**
	 * Return the XML declaration string, in case if found in the markup.
	 *
	 * @return Null, if not found.
	 */
	String getXmlDeclaration();

	/**
	 * For Wicket it would be sufficient for this method to be package protected. However to allow
	 * wicket-bench easy access to the information ...
	 *
	 * @return Number of markup elements
	 */
	int size();

	/**
	 * @return String representation of markup list
	 */
	String toDebugString();

	/**
	 * @return String representation of markup list
	 */
	@Override
	String toString();
}


text:
package com.simpligility.maven.plugins.android.standalonemojos;

import java.io.File;
import java.util.Arrays;

import org.apache.maven.model.Build;
import org.apache.maven.project.MavenProject;
import org.easymock.EasyMock;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import com.simpligility.maven.plugins.android.AbstractAndroidMojoTestCase;
import com.simpligility.maven.plugins.android.CommandExecutor;
import com.simpligility.maven.plugins.android.config.ConfigHandler;
import com.simpligility.maven.plugins.android.standalonemojos.MonkeyMojo;

/**
 * Test the Monkey mojo. Tests options' default values and parsing. We do not test the command line that is passed to
 * the adb bridge, it should be possible to mock it though.
 *
 * @author Stéphane Nicolas <snicolas@octo.com>
 *
 */
@Ignore("This test has to be migrated to be an IntegrationTest using AbstractAndroidMojoIntegrationTest")
@RunWith( PowerMockRunner.class )
@PrepareForTest(
{ CommandExecutor.Factory.class, ConfigHandler.class } )
public class MonkeyMojoTest extends AbstractAndroidMojoTestCase< MonkeyMojo >
{
    @Override
    public String getPluginGoalName()
    {
        return "monkey";
    }

    /**
     * Tests all options, checks if their default values are correct.
     *
     * @throws Exception
     */
    public void testDefaultMonkeyConfig() throws Exception
    {
        // given
        MonkeyMojo mojo = createMojo( "monkey-config-project0" );
        final ConfigHandler cfh = new ConfigHandler( mojo, this.session, this.execution );
        cfh.parseConfiguration();

        // when
        Boolean automatorSkip = Whitebox.getInternalState( mojo, "parsedSkip" );

        // then
        assertTrue( "Monkey skip parameter should be true", automatorSkip );
    }

    /**
     * Tests all options, checks if their default values are correct.
     *
     * @throws Exception
     */
    public void testDefaultUnskippedMonkeyConfig() throws Exception
    {
        // given
        MonkeyMojo mojo = createMojo( "monkey-config-project1" );

        MavenProject project = EasyMock.createNiceMock( MavenProject.class );
        Whitebox.setInternalState( mojo, "project", project );
        File projectBaseDir = new File( getBasedir() );
        Build projectBuild = new Build();
        String buildName = "monkey-config-project1-15.4.3.1011";
        projectBuild.setFinalName( buildName );
        projectBuild.setDirectory( "target/" );
        projectBuild.setSourceDirectory( "src/" );
        projectBuild.setOutputDirectory( "classes/" );
        EasyMock.expect( project.getBasedir() ).andReturn( projectBaseDir ).anyTimes();
        EasyMock.expect( project.getBuild() ).andReturn( projectBuild ).anyTimes();
        PowerMock.replay( project );

        // when
        final ConfigHandler cfh = new ConfigHandler( mojo, this.session, this.execution );
        cfh.parseConfiguration();

        // then
        Boolean monkeySkip = Whitebox.getInternalState( mojo, "parsedSkip" );
        Integer monkeyEventCount = Whitebox.getInternalState( mojo, "parsedEventCount" );
        Long monkeySeed = Whitebox.getInternalState( mojo, "parsedSeed" );
        Long monkeyThrottle = Whitebox.getInternalState( mojo, "parsedThrottle" );
        Integer monkeyPercentTouch = Whitebox.getInternalState( mojo, "parsedPercentTouch" );
        Integer monkeyPercentMotion = Whitebox.getInternalState( mojo, "parsedPercentMotion" );
        Integer monkeyPercentTrackball = Whitebox.getInternalState( mojo, "parsedPercentTrackball" );
        Integer monkeyPercentNav = Whitebox.getInternalState( mojo, "parsedPercentNav" );
        Integer monkeyPercentMajorNav = Whitebox.getInternalState( mojo, "parsedPercentMajorNav" );
        Integer monkeyPercentSyskeys = Whitebox.getInternalState( mojo, "parsedPercentSyskeys" );
        Integer monkeyPercentAppSwitch = Whitebox.getInternalState( mojo, "parsedPercentAppswitch" );
        Integer monkeyPercentAnyEvent = Whitebox.getInternalState( mojo, "parsedPercentAnyevent" );

        String[] monkeyPackages = Whitebox.getInternalState( mojo, "parsedPackages" );
        String[] monkeyCategories = Whitebox.getInternalState( mojo, "parsedCategories" );

        Boolean monkeyDebugNoEvents = Whitebox.getInternalState( mojo, "parsedDebugNoEvents" );
        Boolean monkeyHprof = Whitebox.getInternalState( mojo, "parsedHprof" );
        Boolean monkeyIgnoreCrashes = Whitebox.getInternalState( mojo, "parsedIgnoreCrashes" );
        Boolean monkeyIgnoreTimeouts = Whitebox.getInternalState( mojo, "parsedIgnoreTimeouts" );
        Boolean monkeyIgnoreSecurityExceptions = Whitebox.getInternalState( mojo, "parsedIgnoreSecurityExceptions" );
        Boolean monkeyKillProcessAfterError = Whitebox.getInternalState( mojo, "parsedKillProcessAfterError" );
        Boolean monkeyMonitorNativeCrashes = Whitebox.getInternalState( mojo, "parsedMonitorNativeCrashes" );
        Boolean monkeyCreateReport = Whitebox.getInternalState( mojo, "parsedCreateReport" );

        assertFalse( "Monkey skip parameter should be false", monkeySkip );
        final int expectedEventCount = 1000;
        assertEquals( "Monkey eventCount parameter should be 5000", new Integer( expectedEventCount ), //
                monkeyEventCount );
        assertNull( "Monkey seed should be null", monkeySeed );
        assertNull( "Monkey throttle should be null", monkeyThrottle );
        assertNull( "Monkey percentTouch should be null", monkeyPercentTouch );
        assertNull( "Monkey percentMotion should be null", monkeyPercentMotion );
        assertNull( "Monkey percentTrackball should be null", monkeyPercentTrackball );
        assertNull( "Monkey percentNav should be null", monkeyPercentNav );
        assertNull( "Monkey percentMajorNav should be null", monkeyPercentMajorNav );
        assertNull( "Monkey percentSyskeys should be null", monkeyPercentSyskeys );
        assertNull( "Monkey percentAppswitch should be null", monkeyPercentAppSwitch );
        assertNull( "Monkey percentAnyevent should be null", monkeyPercentAnyEvent );

        assertNull( "Monkey packages should be null", monkeyPackages );
        assertNull( "Monkey categories should be null", monkeyCategories );

        assertFalse( "Monkey debugNoEvents should be false", monkeyDebugNoEvents );
        assertFalse( "Monkey hprof should be false", monkeyHprof );
        assertFalse( "Monkey ignoreCrashes should be false", monkeyIgnoreCrashes );
        assertFalse( "Monkey ignoreTimeouts should be false", monkeyIgnoreTimeouts );
        assertFalse( "Monkey ignoreSecurityExceptions should be false", monkeyIgnoreSecurityExceptions );
        assertFalse( "Monkey killProcessAfterError should be false", monkeyKillProcessAfterError );
        assertFalse( "Monkey monitorNativeCrashes should be false", monkeyMonitorNativeCrashes );
        assertFalse( "Monkey createReport should be false", monkeyCreateReport );
    }

    /**
     * Tests all options, checks if they are parsed correctly.
     *
     * @throws Exception
     */
    public void testCustomMonkeyConfig() throws Exception
    {
        // given
        MonkeyMojo mojo = createMojo( "monkey-config-project2" );
        MavenProject project = EasyMock.createNiceMock( MavenProject.class );
        Whitebox.setInternalState( mojo, "project", project );
        File projectBaseDir = new File( getBasedir() );
        Build projectBuild = new Build();
        String buildName = "ui-automator-config-project1-15.4.3.1011";
        projectBuild.setFinalName( buildName );
        projectBuild.setDirectory( "target/" );
        projectBuild.setSourceDirectory( "src/" );
        projectBuild.setOutputDirectory( "classes/" );
        EasyMock.expect( project.getBasedir() ).andReturn( projectBaseDir ).anyTimes();
        EasyMock.expect( project.getBuild() ).andReturn( projectBuild ).anyTimes();

        PowerMock.replay( project );

        // when
        final ConfigHandler cfh = new ConfigHandler( mojo, this.session, this.execution );
        cfh.parseConfiguration();

        // then
        Boolean monkeySkip = Whitebox.getInternalState( mojo, "parsedSkip" );
        Integer monkeyEventCount = Whitebox.getInternalState( mojo, "parsedEventCount" );
        Long monkeySeed = Whitebox.getInternalState( mojo, "parsedSeed" );
        Long monkeyThrottle = Whitebox.getInternalState( mojo, "parsedThrottle" );
        Integer monkeyPercentTouch = Whitebox.getInternalState( mojo, "parsedPercentTouch" );
        Integer monkeyPercentMotion = Whitebox.getInternalState( mojo, "parsedPercentMotion" );
        Integer monkeyPercentTrackball = Whitebox.getInternalState( mojo, "parsedPercentTrackball" );
        Integer monkeyPercentNav = Whitebox.getInternalState( mojo, "parsedPercentNav" );
        Integer monkeyPercentMajorNav = Whitebox.getInternalState( mojo, "parsedPercentMajorNav" );
        Integer monkeyPercentSyskeys = Whitebox.getInternalState( mojo, "parsedPercentSyskeys" );
        Integer monkeyPercentAppSwitch = Whitebox.getInternalState( mojo, "parsedPercentAppswitch" );
        Integer monkeyPercentAnyEvent = Whitebox.getInternalState( mojo, "parsedPercentAnyevent" );

        String[] monkeyPackages = Whitebox.getInternalState( mojo, "parsedPackages" );
        String[] monkeyCategories = Whitebox.getInternalState( mojo, "parsedCategories" );

        Boolean monkeyDebugNoEvents = Whitebox.getInternalState( mojo, "parsedDebugNoEvents" );
        Boolean monkeyHprof = Whitebox.getInternalState( mojo, "parsedHprof" );
        Boolean monkeyIgnoreCrashes = Whitebox.getInternalState( mojo, "parsedIgnoreCrashes" );
        Boolean monkeyIgnoreTimeouts = Whitebox.getInternalState( mojo, "parsedIgnoreTimeouts" );
        Boolean monkeyIgnoreSecurityExceptions = Whitebox.getInternalState( mojo, "parsedIgnoreSecurityExceptions" );
        Boolean monkeyKillProcessAfterError = Whitebox.getInternalState( mojo, "parsedKillProcessAfterError" );
        Boolean monkeyMonitorNativeCrashes = Whitebox.getInternalState( mojo, "parsedMonitorNativeCrashes" );
        Boolean monkeyCreateReport = Whitebox.getInternalState( mojo, "parsedCreateReport" );

        assertFalse( "Monkey skip parameter should be false", monkeySkip );
        final int expectedEventCount = 5000;
        assertEquals( "Monkey eventCount parameter should be 5000", new Integer( expectedEventCount ), //
                monkeyEventCount );
        final int expectedSeed = 123456;
        assertEquals( "Monkey seed should be 123456", new Long( expectedSeed ), monkeySeed );
        assertEquals( "Monkey throttle should be 10", new Long( 10 ), monkeyThrottle );
        assertEquals( "Monkey percentTouch should be 10", new Integer( 10 ), monkeyPercentTouch );
        assertEquals( "Monkey percentMotion should be 10", new Integer( 10 ), monkeyPercentMotion );
        assertEquals( "Monkey percentTrackball should be 10", new Integer( 10 ), monkeyPercentTrackball );
        assertEquals( "Monkey percentNav should be 10", new Integer( 10 ), monkeyPercentNav );
        assertEquals( "Monkey percentMajorNav should be 10", new Integer( 10 ), monkeyPercentMajorNav );
        assertEquals( "Monkey percentSyskeys should be 10", new Integer( 10 ), monkeyPercentSyskeys );
        assertEquals( "Monkey percentAppswitch should be 10", new Integer( 10 ), monkeyPercentAppSwitch );
        assertEquals( "Monkey percentAnyevent should be 10", new Integer( 10 ), monkeyPercentAnyEvent );

        String[] expectedPackages = new String[]
        { "com.foo", "com.bar" };
        assertTrue( "Monkey packages should be [com.foo,com.bar]", Arrays.equals( expectedPackages, monkeyPackages ) );
        String[] expectedCategories = new String[]
        { "foo", "bar" };
        assertTrue( "Monkey categories should be [foo,bar]", Arrays.equals( expectedCategories, monkeyCategories ) );

        assertTrue( "Monkey debugNoEvents should be true", monkeyDebugNoEvents );
        assertTrue( "Monkey hprof should be true", monkeyHprof );
        assertTrue( "Monkey ignoreCrashes should be true", monkeyIgnoreCrashes );
        assertTrue( "Monkey ignoreTimeouts should be true", monkeyIgnoreTimeouts );
        assertTrue( "Monkey ignoreSecurityExceptions should be true", monkeyIgnoreSecurityExceptions );
        assertTrue( "Monkey killProcessAfterError should be true", monkeyKillProcessAfterError );
        assertTrue( "Monkey monitorNativeCrashes should be true", monkeyMonitorNativeCrashes );
        assertTrue( "Monkey createReport should be true", monkeyCreateReport );

    }

}


text:
package uk.ac.kcl.testexecutionlisteners;

import org.junit.Ignore;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import uk.ac.kcl.utils.DbmsTestUtils;
import uk.ac.kcl.utils.TestUtils;

@Ignore
public class PdfboxTestExecutionListener extends AbstractTestExecutionListener {

    public PdfboxTestExecutionListener(){}

    @Override
    public void beforeTestClass(TestContext testContext) {
        DbmsTestUtils dbTestUtils =
                testContext.getApplicationContext().getBean(DbmsTestUtils.class);
        dbTestUtils.createJobRepository();
        dbTestUtils.createTikaTable();
        dbTestUtils.createBasicOutputTable();
        TestUtils testUtils =
                testContext.getApplicationContext().getBean(TestUtils.class);
        Environment env = testContext.getApplicationContext().getBean(Environment.class);
        testUtils.deleteESTestIndexAndSetUpMapping();
        testUtils.insertTestBinariesForPdfbox("tblInputDocs");

    }

}


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--

-->
<configuration>
  <property>
    <name>dfs.permissions.enabled</name>
    <value>true</value>
    <on-ambari-upgrade add="true"/>
  </property>
  <property>
    <name>dfs.permissions.superusergroup</name>
    <value>hdfs</value>
    <on-ambari-upgrade add="true"/>
  </property>
</configuration>


text:
var manual = require('manual');
var Parser = require('./parser');

module.exports = {
  MarkdownRenderer: require('./render/markdown'),
  TextRenderer: require('./render/text'),
  ManualRenderer: require('./render/man'),
  Renderer: require('./renderer'),
  Parser: Parser,
  parser: Parser.parse,
  Lexer: require('./lexer'),
  manual: manual,
  tokens: require('./tokens'),
  stringify: require('./stringify'),
  links: require('./links'),
  defaults: require('./defaults')
}


text: export { default } from 'ember-fhir/models/explanation-of-benefit-detail';


text:
package com.streamsets.pipeline.stage.connection.remote;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

@GenerateResourceBundle
public enum Protocol implements Label {
  SFTP("SFTP"),
  FTP("FTP"),
  FTPS("FTPS"),
  ;

  private final String label;

  Protocol(String label) { this.label = label; }

  @Override
  public String getLabel() {
    return label;
  }
}


text:
.. _afo-service-index:

HealthMonitor
=============

.. autoclass:: dyn.tm.services.active_failover.HealthMonitor
    :members:
    :undoc-members:

Active Failover
===============

.. autoclass:: dyn.tm.services.active_failover.ActiveFailover
    :members:
    :undoc-members:

Active Failover Examples
------------------------
The following examples highlight how to use the :class:`ActiveFailover` class to
get/create :class:`ActiveFailover`'s on the dyn.tm System and how to edit these
objects from within a Python script.

Creating a new Active Failover Service
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following example shows how to create a new :class:`ActiveFailover` on the
dyn.tm System and how to edit some of the fields using the returned
:class:`ActiveFailover` object.
::

    >>> from dyn.tm.services.active_failover import HealthMonitor, ActiveFailover,
    >>> # Create a dyn.tmSession
    >>> mon = HealthMonitor(protocol='HTTP', interval='1', expected='Example')
    >>> # Assuming you own the zone 'example.com'
    >>> afo = ActiveFailover('example.com', 'example.com.', '127.0.0.1', 'ip',
    ...                      '127.0.0.2', mon, 'mycontact')
    >>> afo.notify_events = 'ip, nosrv'
    >>> afo.notify_events
    u'ip, nosrv'

Getting an Existing Active Failover Service
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The following example shows how to get an existing :class:`ActiveFailover` from
the dyn.tm System and how to edit some of the same fields mentioned above.
::

    >>> from dyn.tm.services.active_failover import HealthMonitor, ActiveFailover,
    >>> # Create a dyn.tmSession
    >>> # Once again, assuming you own 'example.com'
    >>> afo = ActiveFailover('example.com', 'example.com.')
    >>> afo.active
    u'Y'
    >>> afo.deactivate()
    >>> afo.active
    u'N'


text:
package org.opencloudb.server.response;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.opencloudb.MycatCluster;
import org.opencloudb.MycatConfig;
import org.opencloudb.MycatNode;
import org.opencloudb.MycatServer;
import org.opencloudb.config.Alarms;
import org.opencloudb.config.Fields;
import org.opencloudb.config.model.CobarNodeConfig;
import org.opencloudb.config.model.SchemaConfig;
import org.opencloudb.mysql.PacketUtil;
import org.opencloudb.net.mysql.EOFPacket;
import org.opencloudb.net.mysql.FieldPacket;
import org.opencloudb.net.mysql.ResultSetHeaderPacket;
import org.opencloudb.net.mysql.RowDataPacket;
import org.opencloudb.server.ServerConnection;
import org.opencloudb.util.IntegerUtil;
import org.opencloudb.util.StringUtil;

/**
 * @author mycat
 */
public class ShowCobarCluster {

    private static final Logger alarm = Logger.getLogger("alarm");

    private static final int FIELD_COUNT = 2;
    private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
    private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
    private static final EOFPacket eof = new EOFPacket();
    static {
        int i = 0;
        byte packetId = 0;
        header.packetId = ++packetId;
        fields[i] = PacketUtil.getField("HOST", Fields.FIELD_TYPE_VAR_STRING);
        fields[i++].packetId = ++packetId;
        fields[i] = PacketUtil.getField("WEIGHT", Fields.FIELD_TYPE_LONG);
        fields[i++].packetId = ++packetId;
        eof.packetId = ++packetId;
    }

    public static void response(ServerConnection c) {
        ByteBuffer buffer = c.allocate();

        // write header
        buffer = header.write(buffer, c);

        // write field
        for (FieldPacket field : fields) {
            buffer = field.write(buffer, c);
        }

        // write eof
        buffer = eof.write(buffer, c);

        // write rows
        byte packetId = eof.packetId;
        for (RowDataPacket row : getRows(c)) {
            row.packetId = ++packetId;
            buffer = row.write(buffer, c);
        }

        // last eof
        EOFPacket lastEof = new EOFPacket();
        lastEof.packetId = ++packetId;
        buffer = lastEof.write(buffer, c);

        // post write
        c.write(buffer);
    }

    private static List<RowDataPacket> getRows(ServerConnection c) {
        List<RowDataPacket> rows = new LinkedList<RowDataPacket>();
        MycatConfig config = MycatServer.getInstance().getConfig();
        MycatCluster cluster = config.getCluster();
        Map<String, SchemaConfig> schemas = config.getSchemas();
        SchemaConfig schema = (c.getSchema() == null) ? null : schemas.get(c.getSchema());

        // 如果没有指定schema或者schema为null,则使用全部集群。
        if (schema == null) {
            Map<String, MycatNode> nodes = cluster.getNodes();
            for (MycatNode n : nodes.values()) {
                if (n != null && n.isOnline()) {
                    rows.add(getRow(n, c.getCharset()));
                }
            }
        } else {
            String group = (schema.getGroup() == null) ? "default" : schema.getGroup();
            List<String> nodeList = cluster.getGroups().get(group);
            if (nodeList != null && nodeList.size() > 0) {
                Map<String, MycatNode> nodes = cluster.getNodes();
                for (String id : nodeList) {
                    MycatNode n = nodes.get(id);
                    if (n != null && n.isOnline()) {
                        rows.add(getRow(n, c.getCharset()));
                    }
                }
            }
            // 如果schema对应的group或者默认group都没有有效的节点,则使用全部集群。
            if (rows.size() == 0) {
                Map<String, MycatNode> nodes = cluster.getNodes();
                for (MycatNode n : nodes.values()) {
                    if (n != null && n.isOnline()) {
                        rows.add(getRow(n, c.getCharset()));
                    }
                }
            }
        }

        if (rows.size() == 0) {
            alarm.error(Alarms.CLUSTER_EMPTY + c.toString());
        }

        return rows;
    }

    private static RowDataPacket getRow(MycatNode node, String charset) {
        CobarNodeConfig conf = node.getConfig();
        RowDataPacket row = new RowDataPacket(FIELD_COUNT);
        row.add(StringUtil.encode(conf.getHost(), charset));
        row.add(IntegerUtil.toBytes(conf.getWeight()));
        return row;
    }

}


text:
package com.intellij.openapi.vcs.changes.ui;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.tree.DefaultTreeModel;
import java.util.List;

public class FilePathChangesTreeList extends ChangesTreeList<FilePath> {

  public FilePathChangesTreeList(@NotNull Project project,
                                 @NotNull List<FilePath> originalFiles,
                                 boolean showCheckboxes,
                                 boolean highlightProblems,
                                 @Nullable Runnable inclusionListener,
                                 @Nullable ChangeNodeDecorator nodeDecorator) {
    super(project, originalFiles, showCheckboxes, highlightProblems, inclusionListener, nodeDecorator);
  }

  @Override
  protected DefaultTreeModel buildTreeModel(final List<FilePath> changes, ChangeNodeDecorator changeNodeDecorator) {
    return new TreeModelBuilder(myProject, false).buildModelFromFilePaths(changes);
  }

  @Override
  protected List<FilePath> getSelectedObjects(final ChangesBrowserNode<FilePath> node) {
    return node.getAllFilePathsUnder();
  }

  @Override
  @Nullable
  protected FilePath getLeadSelectedObject(final ChangesBrowserNode node) {
    Object userObject = node.getUserObject();
    return userObject instanceof FilePath ? (FilePath)userObject : null;
  }
}


text:
package com.kevlindev.pinconverter;

import com.kevlindev.pinconverter.model.Board;

/**
 * WingRegistry
 *
 * @author Kevin Lindsey
 * @version 1.0
 */
public class WingRegistry extends BoardRegistry {
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.kevlindev.pinconverter.BoardRegistry#addBoard(com.kevlindev.pinconverter
	 * .model.Board)
	 */
	@Override
	public void addBoard(Board board) {
		super.addBoard(board);

		board.setIsWing(true);
	}
}


text:
package com.impetus.client;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.impetus.client.entities.AddressMTORedis;
import com.impetus.client.entities.PersonMTORedis;

public class RedisAssociationTestMTO
{

    private EntityManagerFactory emf;

    private EntityManager em;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
        emf = Persistence.createEntityManagerFactory("redis_pu");
        em = getNewEM();
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception
    {
        em.close();
        emf.close();
    }

    @Test
    public void testCrud()
    {

        AddressMTORedis address = new AddressMTORedis(100.0);
        address.setAddress("Gr. Noida");

        PersonMTORedis person1 = getPerson("1", "User1", 20, address);
        PersonMTORedis person2 = getPerson("2", "User2", 40, address);
        em.persist(person1);
        em.persist(person2);

        PersonMTORedis resultPerson1 = em.find(PersonMTORedis.class, "1");
        PersonMTORedis resultPerson2 = em.find(PersonMTORedis.class, "2");

        notNullCheck(resultPerson1, resultPerson2);
        Assert.assertEquals("1", resultPerson1.getPersonId());
        Assert.assertEquals("User1", resultPerson1.getPersonName());
        Assert.assertEquals(20, resultPerson1.getAge().intValue());

        Assert.assertEquals("2", resultPerson2.getPersonId());
        Assert.assertEquals("User2", resultPerson2.getPersonName());
        Assert.assertEquals(40, resultPerson2.getAge().intValue());

        Assert.assertEquals(100.0, resultPerson1.getAddress().getAddressId());
        Assert.assertEquals("Gr. Noida", resultPerson1.getAddress().getAddress());
        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());
        Assert.assertEquals("Gr. Noida", resultPerson2.getAddress().getAddress());

        em.clear();
        address.setAddress("NCR");
        person1.setPersonName("User3");
        person1.setAddress(address);

        em.merge(person1);
        em = getNewEM();

        resultPerson1 = em.find(PersonMTORedis.class, "1");
        resultPerson2 = em.find(PersonMTORedis.class, "2");

        notNullCheck(resultPerson1, resultPerson2);
        Assert.assertEquals("1", resultPerson1.getPersonId());
        Assert.assertEquals("User3", resultPerson1.getPersonName());
        Assert.assertEquals(20, resultPerson1.getAge().intValue());

        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());
        Assert.assertEquals("NCR", resultPerson2.getAddress().getAddress());

        em.remove(resultPerson1);
        em.remove(resultPerson2);

        Assert.assertNull(em.find(PersonMTORedis.class, "1"));
        Assert.assertNull(em.find(PersonMTORedis.class, "2"));
        // Assert.assertNull(em.find(AddressMTORedis.class, 100.0));
    }

    @Test
    public void testQuery()
    {

        AddressMTORedis address = new AddressMTORedis(100.0);
        address.setAddress("Gr. Noida");

        PersonMTORedis person1 = getPerson("1", "User1", 20, address);
        PersonMTORedis person2 = getPerson("2", "User2", 40, address);
        em.persist(person1);
        em.persist(person2);

        Query query = em.createQuery("Select e from PersonMTORedis e");
        List<PersonMTORedis> queryResult = query.getResultList();

        Assert.assertEquals(2, queryResult.size());
        PersonMTORedis resultPerson1 = queryResult.get(0);
        PersonMTORedis resultPerson2 = queryResult.get(1);

        notNullCheck(resultPerson1, resultPerson2);
        for (PersonMTORedis resultPerson : queryResult)
        {

            if (resultPerson.getPersonId().equals("1"))
            {
                Assert.assertEquals("User1", resultPerson.getPersonName());
                Assert.assertEquals(20, resultPerson.getAge().intValue());
            }
            else
            {
                Assert.assertEquals("2", resultPerson.getPersonId());
                Assert.assertEquals("User2", resultPerson.getPersonName());
                Assert.assertEquals(40, resultPerson.getAge().intValue());
            }
        }

        Assert.assertEquals(100.0, resultPerson1.getAddress().getAddressId());
        Assert.assertEquals("Gr. Noida", resultPerson1.getAddress().getAddress());
        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());
        Assert.assertEquals("Gr. Noida", resultPerson2.getAddress().getAddress());

        em.clear();
        address.setAddress("NCR");
        person1.setPersonName("User3");
        person1.setAddress(address);

        em.merge(person1);
        em = getNewEM();

        query = em.createQuery("Select e from PersonMTORedis e");
        queryResult = query.getResultList();

        Assert.assertEquals(2, queryResult.size());
        resultPerson1 = queryResult.get(0);
        resultPerson2 = queryResult.get(1);

        notNullCheck(resultPerson1, resultPerson2);
        for (PersonMTORedis resultPerson : queryResult)
        {

            if (resultPerson.getPersonId().equals("1"))
            {
                Assert.assertEquals("User3", resultPerson.getPersonName());
                Assert.assertEquals(20, resultPerson.getAge().intValue());
            }
            else
            {
                Assert.assertEquals("2", resultPerson.getPersonId());
                Assert.assertEquals("User2", resultPerson.getPersonName());
                Assert.assertEquals(40, resultPerson.getAge().intValue());
            }
        }

        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());
        Assert.assertEquals("NCR", resultPerson2.getAddress().getAddress());

        em.remove(resultPerson1);
        em.remove(resultPerson2);

        Assert.assertNull(em.find(PersonMTORedis.class, "1"));
        Assert.assertNull(em.find(PersonMTORedis.class, "2"));
        // Assert.assertNull(em.find(AddressMTORedis.class, 100.0));
    }

    private boolean notNullCheck(PersonMTORedis resultPerson1, PersonMTORedis resultPerson2)
    {

        Assert.assertNotNull(resultPerson1);
        Assert.assertNotNull(resultPerson2);
        Assert.assertNotNull(resultPerson1.getAddress());
        Assert.assertNotNull(resultPerson2.getAddress());

        return true;
    }

    private PersonMTORedis getPerson(String personId, String personName, int age, AddressMTORedis address)
    {

        PersonMTORedis person = new PersonMTORedis(personId);
        person.setAge(age);
        person.setPersonName(personName);
        person.setAddress(address);

        return person;
    }

    private EntityManager getNewEM()
    {
        if (em != null && em.isOpen())
        {
            em.close();
        }
        // Delete by query.
        Query query = em.createQuery("Delete from PersonMTORedis p");
        int updateCount = query.executeUpdate();
        return em = emf.createEntityManager();
    }
}


text:
node-red
========

A collection of Node.js utilities


text:
require 'open3'
require 'pgversion'

module Transferatu
  class RunnerFactory
    def self.runner_for(transfer)
      from_type, to_type = transfer.from_type, transfer.to_type

      if from_type == 'gof3r' && to_type == 'gof3r'
        raise ArgumentError, "S3 transfers not supported"
      end

      to_version = nil
      logger = ThreadSafeLogger.new(transfer).method(:log)
      sink = case to_type
             when 'pg_restore'
               to_version = PGVersion.parse(Sequel.connect(transfer.to_url) do |c|
                                              c.fetch("SELECT version()").get(:version)
                                            end)
               pg_root = "/app/bin/pg/#{to_version.major_minor}"
               PGRestoreSink.new(transfer.to_url,
                                 opts: {
                                   no_owner: true,
                                   no_privileges: true,
                                   verbose: true,
                                   format: 'custom'
                                 },
                                 root: pg_root,
                                 logger: logger)
             when 'gof3r'
               Gof3rSink.new(transfer.to_url, logger: logger)
             else
               raise ArgumentError, "Unkown transfer sink type: #{to_type}"
             end

      source = case from_type
               when 'pg_dump'
                 # N.B.: if the pg_root has already been set, only
                 # override it if the source is of a higher version.
                 # This can be useful for upgrades and is necessary
                 # for downgrades.
                 from_version = PGVersion.parse(Sequel.connect(transfer.from_url) do |c|
                                                  c.fetch("SELECT version()").get(:version)
                                                end)
                 source_bytes = Sequel.connect(transfer.from_url) do |c|
                   c.fetch("SELECT pg_database_size(current_database()) AS size").get(:size)
                 end
                 transfer.update(source_bytes: source_bytes)
                 pg_root = if to_version.nil? || from_version > to_version
                             "/app/bin/pg/#{from_version.major_minor}"
                           else
                             "/app/bin/pg/#{to_version.major_minor}"
                           end
                 PGDumpSource.new(transfer.from_url,
                                  opts: {
                                    no_owner: true,
                                    no_privileges: true,
                                    verbose: true,
                                    format: 'custom'
                                  },
                                  root: pg_root,
                                  logger: logger)
               when 'gof3r'
                 Gof3rSource.new(transfer.from_url, logger: logger)
               when 'htcat'
                 HtcatSource.new(transfer.from_url, logger: logger)
               else
                 raise ArgumentError, "Unkown transfer source type: #{from_type}"
               end
      DataMover.new(source, sink)
    end
  end

  class ShellFuture
    # The arguments are the return values of popen
    attr_reader :stdin, :stdout, :stderr
    def initialize(stdin, stdout, stderr, wthr)
      @stdin, @stdout, @stderr = stdin, stdout, stderr
      @wthr = wthr
      @log_threads = []
    end

    # Asynchronously write each line of of stdout to the +log+
    # function, which must accept a single String argument, then close
    # the stream (+wait+ will wait for output to be drained before
    # returning).
    def drain_stdout(logger)
      drain_stream(@stdout, logger)
    end

    # Same as drain_stdout, but for standard error.
    def drain_stderr(logger)
      drain_stream(@stderr, logger)
    end

    # Wait for the process to finish. Returns the resulting
    # Process::Status of the process.
    def wait
      status = @wthr.value

      @log_threads.each { |thr| thr.join }
      [ @stdin, @stdout, @stderr ].each do |stream|
        stream.close unless stream.closed?
      end
      status
    end

    def cancel
      if @wthr
        Process.kill("INT", @wthr.pid)
      end
    rescue Errno::ESRCH
      # Do nothing; our async pg_dump may have completed. N.B.: this
      # means that right now, canceled transfers can in fact complete
      # successfully. This may be a bug or a feature. TBD.
    end

    private

    def drain_stream(stream, logger)
      @log_threads << Thread.new do
        begin
          stream.each_line { |l| logger.call(l.strip) }
        ensure
          stream.close
        end
      end
    end
  end

  module Commandable
    # Takes a hash of snake-cased symbol keys and values that define
    # #to_s and builds an Array of command arguments with the
    # corresponding GNU flag representation. Returns the resulting
    # command as an array, ready to pass to Open3#popen or its kin.
    def command(cmd, opts, *args)
      result = if cmd.is_a? Array
                 cmd
               else
                 [ cmd ]
               end
      opts.each do |k,v|
        kstr = k.to_s
        if kstr.length == 1
          result << "-#{kstr}"
        else
          result << "--#{kstr.gsub(/_/, '-')}"
        end
        unless v == true
          result << v.to_s
        end
      end
      result + args
    end

    def run_command(env={}, cmd)
      stdin, stdout, stderr, wthr = Open3.popen3(env, *cmd)
      ShellFuture.new(stdin, stdout, stderr, wthr)
    end
  end

  # A source that runs pg_dump
  class PGDumpSource
    include Commandable
    extend Forwardable

    def_delegators :@future, :cancel

    def initialize(url, opts: {}, logger:, root:)
      uri = URI.parse(url)
      dbname = uri.path[1..-1]
      @env = { "LD_LIBRARY_PATH" => "#{root}/lib", "PGPASSWORD" => uri.password }
      @cmd = command("#{root}/bin/pg_dump",
                     opts.merge(username: uri.user,
                                host: uri.host,
                                port: uri.port || 5432), dbname)
      @logger = logger
    end

    def run_async
      @logger.call("Running #{@cmd.join(' ')}", level: :internal)
      @future = run_command(@env, @cmd)
      @future.drain_stderr(@logger)
      @future.stdout
    end

    def wait
      @logger.call "waiting for pg_dump to complete"
      result = @future.wait
      @logger.call "pg_dump done"
      @logger.call("exit status details: #{result.inspect}", level: :internal)

      result.success? == true
    end
  end

  # A Sink that uploads to S3
  class Gof3rSink
    include Commandable
    extend Forwardable

    def_delegators :@future, :cancel

    def initialize(url, opts: {}, logger:)
      # assumes https://bucket.as3.amazonaws.com/key/path URIs
      uri = URI.parse(url)
      hostname = uri.hostname
      bucket = hostname.split('.').shift
      key = uri.path.sub(/\A\//, '')
      # gof3r put -b $bucket -k $key -m x-amz-server-side-encryption:AES256;
      # we assume the S3 keys are in the environment for now.
      @cmd = command(%W(gof3r put), { b: bucket, k: key,
                                      m: 'x-amz-server-side-encryption:AES256'})
      @logger = logger
    end

    def run_async
      @logger.call("Running #{@cmd.join(' ')}", level: :internal)
      @future = run_command(@cmd)
      @future.drain_stdout(@logger)
      @future.drain_stderr(->(line) { @logger.call(line, level: :internal) })
      @future.stdin
    end

    def wait
      @logger.call "waiting for upload to complete"
      result = @future.wait
      @logger.call "upload done"
      @logger.call("exit status details: #{result.inspect}", level: :internal)

      result.success? == true
    end
  end

  # A Sink that restores a custom-format Postgres dump into a database
  class PGRestoreSink
    include Commandable
    extend Forwardable

    def_delegators :@future, :cancel

    def initialize(url, opts: {}, logger:, root:)
      uri = URI.parse(url)
      dbname = uri.path[1..-1]
      @env = { "LD_LIBRARY_PATH" => "#{root}/lib", "PGPASSWORD" => uri.password }
      @cmd = command("#{root}/bin/pg_restore",
                     opts.merge(username: uri.user,
                                host: uri.host,
                                port: uri.port || 5432,
                                dbname: dbname))
      @logger = logger
    end

    def run_async
      @logger.call("Running #{@cmd.join(' ')}}", level: :internal)
      @future = run_command(@env, @cmd)
      # We don't expect any output from stdout. Capture it anyway, but
      # keep it internal.
      @future.drain_stdout(->(line) { @logger.call(line, level: :internal) })
      # pg_restore basically uses two exit codes: 1 and 0. This means
      # we can't rely on exit status to tell us much of anything,
      # since there's no way for an unprivileged user to comment on an
      # extension, and that's a standard part of a pg_dump, and
      # there's no way to avoid these. Instead, we watch for these and
      # compare them against the total number of errors reported by
      # pg_restore. This is pretty gross (e.g., it does not work with
      # a localized pg_restore), but safer.
      @failed_extension_comment_count = 0
      @failed_plpgsql_create = false
      @pg_restore_error_count = 0
      @future.drain_stderr(->(line) do
                             if line =~ /\ACommand was: COMMENT ON EXTENSION /
                               @failed_extension_comment_count += 1
                             elsif line =~ /\ACommand was: CREATE(?: OR REPLACE)? PROCEDURAL LANGUAGE plpgsql;/
                               # N.B.: we do a boolean flag here instead of a count so that
                               # if for whatever crazy reason we see this multiple tiimes, it
                               # should fail to match the error count and the overall transfer
                               # will rightly fail.
                               @failed_plpgsql_create = true
                             elsif line =~ /\AWARNING: errors ignored on restore: (\d+)/
                               @pg_restore_error_count = $1.to_i
                             end
                             @logger.call(line)
                           end)
      @future.stdin
    end

    def wait
      @logger.call "waiting for restore to complete"
      result = @future.wait
      @logger.call "restore done"
      return true if result.success? == true

      if result.exitstatus == 1
        expected_err_count = @failed_extension_comment_count
        if @failed_plpgsql_create
          expected_err_count += 1
        end
        return expected_err_count == @pg_restore_error_count
      else
        return false
      end
    end
  end

  # A source that runs Gof3r to fetch from an S3 URL we have access to
  class Gof3rSource
    include Commandable
    extend Forwardable

    def_delegators :@future, :cancel

    def initialize(url, opts: {}, logger:)
      # assumes https://bucket.as3.amazonaws.com/key/path URIs
      uri = URI.parse(url)
      hostname = uri.hostname
      bucket = hostname.split('.').shift
      key = URI.decode(uri.path.sub(/\A\//, ''))
      # gof3r get -b $bucket -k $key; we assume the S3 keys are in the
      # environment.
      @cmd = command(%W(gof3r get), { b: bucket, k: key})
      @url = url
      @logger = logger
    end

    def run_async
      @logger.call("Running #{@cmd.join(' ')}", level: :internal)
      @future = run_command(@cmd)
      @future.drain_stderr(@logger)
      @future.stdout
    end

    def wait
      @logger.call "waiting for download to complete"
      result = @future.wait
      @logger.call "download done"
      result.success? == true
    end
  end

  # A source that runs htcat to fetch from any URL
  class HtcatSource
    include Commandable
    extend Forwardable

    def_delegators :@future, :cancel

    def initialize(url, opts: {}, logger:)
      # htcat $url
      @cmd = command('htcat', {}, url)
      @uri = URI.parse(url)
      @logger = logger
    end

    def run_async
      @logger.call("Running htcat #{@uri.scheme} ...", level: :internal)
      @future = run_command(@cmd)
      @future.drain_stderr(@logger)
      @future.stdout
    end

    def wait
      @logger.call "waiting for download to complete"
      result = @future.wait
      @logger.call "download done"
      result.success? == true
    end
  end
end


text:
package org.selfstudy.javalang.common.generics.exercise.ex26;

/**
 * @author liqingsong on 2018/8/9
 * @project javalang-common
 */
public class Main {
    public static void arrayCovariance(){
        Number[] numbers = new Integer[10];
        for(int i = 0; i < 10 ; i++){
            numbers[i] = i;
        }

        for(Number n: numbers){
            System.out.println(n);
        }
    }

    public static void main(String[] args){
        arrayCovariance();
    }

}


text: print "script1 in master branch."


text:
package org.gillius.jalleg.example;

import org.gillius.jalleg.binding.ALLEGRO_COLOR;
import org.gillius.jalleg.binding.ALLEGRO_FONT;
import org.gillius.jalleg.binding.AllegroLibrary.ALLEGRO_BITMAP;
import org.gillius.jalleg.framework.AllegroAddon;
import org.gillius.jalleg.framework.Game;
import org.gillius.jalleg.framework.io.AllegroLoader;
import org.gillius.jalleg.framework.math.Rect;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static org.gillius.jalleg.binding.AllegroLibrary.*;

public class ImageExample extends Game {
	private ALLEGRO_COLOR white;
	private ALLEGRO_FONT font;

	private ALLEGRO_BITMAP bitmap;
	private int myshaWidth;
	private int myshaHeight;

	private Random random = new Random();

	private List<ImageInstance> images = new ArrayList<>();

	public ImageExample() {
		setAutoResize(true);
	}

	@Override
	protected void onAllegroStarted() throws IOException {
		initAddons(AllegroAddon.Image, AllegroAddon.Keyboard);

		white = al_map_rgb_f(1f, 1f, 1f);
		font = al_create_builtin_font();

		bitmap = AllegroLoader.loadBitmapFromClasspath("/org/gillius/jalleg/example/mysha256x256.png");
		myshaWidth = al_get_bitmap_width(bitmap);
		myshaHeight = al_get_bitmap_height(bitmap);

		initStatsCollection(1, TimeUnit.SECONDS);
	}

	@Override
	protected void update() {
		Rect screen = new Rect(0, 0, getDisplayWidth(), getDisplayHeight());

		if (images.isEmpty() || isKeyDown(ALLEGRO_KEY_UP)) {
			images.add(new ImageInstance(
					new Rect(random.nextFloat() * screen.right(), random.nextFloat() * screen.bottom(), myshaWidth, myshaHeight)
			));
		} else if (isKeyDown(ALLEGRO_KEY_DOWN)) {
			images.remove(images.size() - 1);
		}

		for (ImageInstance image : images)
			image.update(screen);
	}

	@Override
	protected void render() {
		for (ImageInstance image : images)
			image.render();

		al_draw_text(font, white, 1, getDisplayHeight() - al_get_font_line_height(font) - 1, ALLEGRO_ALIGN_LEFT,
		             "Myshas: " + images.size() + " (up or down key to change)");

		if (lastStats != null)
			al_draw_text(font, white, 1, 1, ALLEGRO_ALIGN_LEFT, lastStats.getStatsString());
	}

	public static void main(String[] args) {
		new ImageExample().run();
	}

	private class ImageInstance {
		private Rect pos;
		private int dx = 2;
		private int dy = 2;

		public ImageInstance(Rect pos) {
			this.pos = pos;
		}

		public void update(Rect screen) {
			if (pos.outsideX(screen))
				dx = -dx;
			if (pos.outsideY(screen))
				dy = -dy;
			pos.constrainWithin(screen);

			pos.move(dx, dy);
		}

		public void render() {
			al_draw_bitmap(bitmap, pos.x, pos.y, 0);
		}
	}
}


text:
@interface NSMenuItem (StateAware)

@property (nonatomic,copy) NSString *onTitle;
@property (nonatomic,copy) NSString *offTitle;

@end


text:
FROM cdh4-pdsn-mr1:latest

ENV DEBIAN_FRONTEND noninteractive

RUN mkdir -p /deploy/ && \
    wget --no-check-certificate -qO- https://github.com/ownport/docker-cdh-pseudo/archive/master.tar.gz | tar -xz -C /deploy

RUN apt-get update && apt-get install -y hive

RUN /deploy/docker-cdh-pseudo-master/rerun config:init --export-to /configs/

# clean temporary files after installation
RUN /deploy/docker-cdh-pseudo-master/rerun misc:clean

# Run configuration
CMD ["/configs/rerun", "rc0:config-init", "--run"]


text:
using System.Collections.Generic;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using JetBrains.Annotations;
using Synergy.Contracts;
using Synergy.NHibernate.Conventions;
using Synergy.NHibernate.Domain;
using Synergy.NHibernate.Extensions;
using Synergy.NHibernate.Test.Database.Words;

namespace Synergy.NHibernate.Test.Database.Users
{
    public class User : Entity
    {
        public User()
        {
            this.Groups = new HashSet<WordGroup>();
        }

        public virtual string Email { get; set; }

        public virtual ISet<WordGroup> Groups { get; set; }

        [UsedImplicitly]
        public class Map : IAutoMappingOverride<User>
        {
            public const int EmailLength = 255;

            public void Override([NotNull] AutoMapping<User> mapping)
            {
                Fail.IfArgumentNull(mapping, nameof(mapping));

                mapping.Schema(SampleDatabase.SchemaName);

                mapping.Map(u => u.Email)
                       .Length(Map.EmailLength)
                       .Index(IndexNamingConvention.GetIndexName<User>(u => u.Email))
                       .UniqueKey("UQ_Email");

                mapping.HasManyBidirectional(user => user.Groups, group => group.Owner);
            }
        }
    }
}


text:
var STORAGE_KEY = 'lifecycle-state:' + location.pathname;

var getStoredState = function getStoredState() {
    var storedState;
    try {
        storedState = JSON.parse(localStorage.getItem(STORAGE_KEY));
    } catch (err) {
        // Do nothing.
    }
    return storedState || [];
};

var appendStoredState = function appendStoredState(state, date) {
    var stateHistory = getStoredState();

    stateHistory.push({ state: state, date: date });
    localStorage.setItem(STORAGE_KEY, JSON.stringify(stateHistory));
};

var clearStoredState = function clearStoredState() {
    localStorage.removeItem(STORAGE_KEY);
};

var updateDisplayedState = function updateDisplayedState() {
    var addRow = function(entry) {
        var tr = document.createElement('tr');
        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        td1.innerText = entry.state;
        td2.innerText = entry.date;
        tr.appendChild(td1);
        tr.appendChild(td2);
        tbody.appendChild(tr);
    };
    var removeRow = function(row) {
        row.parentNode.removeChild(row);
    };

    var tbody = document.getElementById('output');
    var entries = getStoredState();
    var rows = [].slice.call(tbody.children);
    var min = Math.min(entries.length, rows.length);
    var max = Math.max(entries.length, rows.length);

    for (var i = min; i < max; i++) {
        if (i >= rows.length) {
            addRow(entries[i]);
        } else {
            removeRow(rows[i]);
        }
    }
};

document.getElementById('clear').onclick = function() {
    clearStoredState();
    updateDisplayedState();
};

updateDisplayedState();

// Subscribe to lifecycle state changes.
cotonic.broker.subscribe("model/lifecycle/event/state", function(m) {
    appendStoredState(m.payload, new Date().toISOString());

    updateDisplayedState();
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleLocalSettings">
    <option name="modificationStamps">
      <map>
        <entry key="$PROJECT_DIR$/../../idea/RepositoryManager" value="1401676166271" />
        <entry key="$PROJECT_DIR$/../../java/hibernate/jpa-test" value="1390825157946" />
        <entry key="$PROJECT_DIR$/../../java/idea/gradle-tutor" value="1391000044734" />
        <entry key="$PROJECT_DIR$/../../java/idea/repository-manager" value="1401966795936" />
      </map>
    </option>
  </component>
  <component name="IdProvider" IDEtalkID="AC2DD3DD0447D14FA18A025A415CF2CF" />
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
package com.seekgd.ssm.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * JSON和Class转换工具。
 *
 * @author huanghao
 *
 */

public class JacksonMapper {

    protected static final Logger logger = LoggerFactory.getLogger(JacksonMapper.class);

    /**
     * jackson 的映射类, 将类型信息一并转换
     */
    public static final ObjectMapper classMapper = new ObjectMapper();

    /**
     * jackson 的映射类, 忽略类型信息
     */
    public static final ObjectMapper jsonMapper = new ObjectMapper();

    static {
        /** 将java对象的类的信息加上 */
        classMapper.enableDefaultTyping();
        /**
         * 忽略的序列化设置。1、json串中存在的属性(且java对象中不存在的属性值),
         * 在转换为java对象时忽略。2、java对象存在(且没有实际的属性或值) 转换为json时忽略信息。
         */
        classMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        classMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    /**
     * 从jsonNode对象中取值,如果未找到返回空字符串
     */
    public static final String getValue(JsonNode node, String key) {
        return node.get(key) != null ? node.get(key).asText() : "";
    }

    /**
     * 从jsonNode对象中查找对应的键值,如果未找到返回空字符串
     */
    public static final String findValue(JsonNode node, String key) {
        return node.findValue(key) != null ? node.findValue(key).asText() : "";
    }

    /**
     * 从jsonNode对象中查找对应的键的list值的集合,如果未找到返回空List
     */
    public static final List<String> findValues(JsonNode node, String key) {
        return node.findValuesAsText(key) != null ? node.findValuesAsText(key) : new ArrayList<String>(0);
    }

    /**
     * 转换json字符串 包括类型信息,如果转换出现异常返回空字符串
     */
    public static final String toCJsonString(Object obj) {
        String json = "";
        try {
            json = classMapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error(obj.getClass().getName() + "对象转换包含类型信息的json出错!", e);
        }
        return json;
    }

    /**
     * 转换json字符串 不包括类型信息,如果转换出现异常返回空字符串
     */
    public static final String toJsonString(Object obj) {
        String json = "";
        try {
            json = jsonMapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error(obj.getClass().getName() + "对象转换为json出错!", e);
        }
        return json;
    }

    /**
     * 转换json字符串 包括类型信息,如果转换出现异常返回长度为0的字节数组
     */
    public static final byte[] toBytes(Object obj) {
        byte[] jsonBytes = new byte[0];
        try {
            jsonBytes = classMapper.writeValueAsBytes(obj);
        } catch (Exception e) {
            logger.error(obj.getClass().getName() + "对象转换为byte出错!", e);
        }
        return jsonBytes;
    }

    /**
     * 将json字符串转换为具体的类型对象,如果转换出现异常返回null
     */
    @SuppressWarnings("unchecked")
    public static final <T> T jsonToClass(String json, Class<T> tClass) {
        if (json == null || "".equals(json.trim())) return null;

        T req = null;
        try {
            req = tClass == String.class ? (T) json : tClass == JsonNode.class ? (T) toJsonNode(json) : Map.class.isAssignableFrom(tClass) ? jsonMapper.readValue(json, tClass) : classMapper.readValue(json, tClass);
        } catch (Exception e) {
            logger.error("json字符串转换java对象:" + tClass.getName() + "出错!", e);
        }
        return req;
    }

    /**
     * 将JsonNode 转换为具体的类型对象,如果转换出现异常返回null
     */
    @SuppressWarnings("unchecked")
    public static final <T> T jsonNodeToClass(JsonNode jsonNode, Class<T> tClass) {
        if (jsonNode == null) return null;

        T req = null;
        try {
            req = tClass == String.class ? (T) jsonNode.toString() :
                    tClass == JsonNode.class ? (T) jsonNode : Map.class.isAssignableFrom(tClass) ? jsonMapper.convertValue(jsonNode, tClass) : classMapper.convertValue(jsonNode, tClass);
        } catch (Exception e) {
            logger.error("jsonNode对象转换java对象:" + tClass.getName() + "出错!", e);
        }
        return req;
    }

    /**
     * 将json 转换为JsonNode对象,如果转换出现异常返回null
     */
    public static final JsonNode toJsonNode(String json) {
        if (json == null || "".equals(json.trim())) return null;
        JsonNode node = null;
        try {
            node = jsonMapper.readTree(json);
        } catch (IOException e) {
            logger.error("json字符串:" + json + ", 转换jsonNode对象出错!", e);
        }
        return node;
    }

    /**
     * 将InputStream 转换为JsonNode对象
     */
    public static final JsonNode readJsonNode(InputStream in) throws JsonProcessingException, IOException {
        return jsonMapper.readTree(read(in));
    }

    /**
     * 包装request的输入流(且必须包装,转换速度有很大的区别),必须设置UTF-8编码,不然中文会乱码
     */
    public static final BufferedReader read(InputStream in) throws UnsupportedEncodingException {
        return new BufferedReader(new InputStreamReader(in, "UTF-8"));
    }
}


text:
namespace TheXDS.MCART.Types.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using static TheXDS.MCART.Misc.Internals;

public static partial class CollectionExtensions
{
    [Conditional("EnforceContracts")]
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    [DebuggerNonUserCode]
    private static void AddClone_Contract<T>(ICollection<T> collection, T item) where T : ICloneable
    {
        NullCheck(collection, nameof(collection));
        NullCheck(item, nameof(item));
    }

    [Conditional("EnforceContracts")]
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    [DebuggerNonUserCode]
    private static void AddClones_Contract<T>(this ICollection<T> collection, IEnumerable<T> source)
    {
        NullCheck(collection, nameof(collection));
        NullCheck(source, nameof(source));
    }

    [Conditional("EnforceContracts")]
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    [DebuggerNonUserCode]
    private static void AddRange_Contract<T>(this ICollection<T> collection, IEnumerable<T> items)
    {
        NullCheck(collection, nameof(collection));
        NullCheck(items, nameof(items));
    }

    private static void ToObservable_Contract<T>(this ICollection<T> collection)
    {
        NullCheck(collection, nameof(collection));
    }

    private static void Push_Contract<TCollection>(this ICollection<TCollection> collection)
    {
        NullCheck(collection, nameof(collection));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.apache.poi.xwpf.usermodel.XWPFParagraph (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.poi.xwpf.usermodel.XWPFParagraph

Packages that use XWPFParagraph

Package
Description

org.apache.poi.xwpf.extractor

org.apache.poi.xwpf.model

org.apache.poi.xwpf.usermodel

Uses of XWPFParagraph in org.apache.poi.xwpf.extractor

Methods in org.apache.poi.xwpf.extractor with parameters of type XWPFParagraph

Modifier and Type
Method and Description

void
XWPFWordExtractor.appendParagraphText(java.lang.StringBuffer text,
                   XWPFParagraph paragraph)

Uses of XWPFParagraph in org.apache.poi.xwpf.model

Fields in org.apache.poi.xwpf.model declared as XWPFParagraph

Modifier and Type
Field and Description

protected XWPFParagraph
XWPFParagraphDecorator.paragraph

Methods in org.apache.poi.xwpf.model with parameters of type XWPFParagraph

Modifier and Type
Method and Description

XWPFFooter
XWPFHeaderFooterPolicy.createFooter(org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum type,
            XWPFParagraph[] pars)

Creates a new footer of the specified type, to which the
  supplied (and previously unattached!) paragraphs are
  added to.

XWPFHeader
XWPFHeaderFooterPolicy.createHeader(org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum type,
            XWPFParagraph[] pars)

Creates a new header of the specified type, to which the
  supplied (and previously unattached!) paragraphs are
  added to.

Constructors in org.apache.poi.xwpf.model with parameters of type XWPFParagraph

Constructor and Description

XWPFCommentsDecorator(XWPFParagraph paragraph,
                     XWPFParagraphDecorator nextDecorator)

XWPFHyperlinkDecorator(XWPFParagraph prgrph,
                      XWPFParagraphDecorator nextDecorator,
                      boolean outputHyperlinkUrls)

Deprecated.

XWPFParagraphDecorator(XWPFParagraph paragraph)

XWPFParagraphDecorator(XWPFParagraph paragraph,
                      XWPFParagraphDecorator nextDecorator)

Uses of XWPFParagraph in org.apache.poi.xwpf.usermodel

Fields in org.apache.poi.xwpf.usermodel with type parameters of type XWPFParagraph

Modifier and Type
Field and Description

protected java.util.List<XWPFParagraph>
XWPFTableCell.paragraphs

protected java.util.List<XWPFParagraph>
XWPFDocument.paragraphs

Methods in org.apache.poi.xwpf.usermodel that return XWPFParagraph

Modifier and Type
Method and Description

XWPFParagraph
XWPFFootnote.addNewParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP paragraph)

add a new paragraph to the end of the footnote

XWPFParagraph
XWPFTableCell.addParagraph()

Add a Paragraph to this Table Cell

XWPFParagraph
XWPFDocument.createParagraph()

Appends a new paragraph to this document

XWPFParagraph
XWPFDocument.getLastParagraph()

XWPFParagraph
XWPFRun.getParagraph()

Deprecated.

use XWPFRun.getParent() instead

XWPFParagraph
XWPFTableCell.getParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP p)

if there is a corresponding XWPFParagraph of the parameter ctTable in the paragraphList of this table
 the method will return this paragraph
 if there is no corresponding XWPFParagraph the method will return null

XWPFParagraph
XWPFFootnote.getParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP p)

if there is a corresponding XWPFParagraph of the parameter ctTable in the paragraphList of this header or footer
 the method will return this paragraph
 if there is no corresponding XWPFParagraph the method will return null

XWPFParagraph
IBody.getParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP p)

if there is a corresponding XWPFParagraph of the parameter ctTable in the paragraphList of this header or footer
 the method will return this paragraph
 if there is no corresponding XWPFParagraph the method will return null

XWPFParagraph
XWPFDocument.getParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP p)

get the paragraph with the CTP class p

XWPFParagraph
XWPFHeaderFooter.getParagraph(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP p)

if there is a corresponding XWPFParagraph of the parameter ctTable in the paragraphList of this header or footer
 the method will return this paragraph
 if there is no corresponding XWPFParagraph the method will return null

XWPFParagraph
XWPFTableCell.getParagraphArray(int pos)

XWPFParagraph
XWPFFootnote.getParagraphArray(int pos)

Returns the paragraph that holds
  the text of the header or footer.

XWPFParagraph
IBody.getParagraphArray(int pos)

Returns the paragraph that of position pos

XWPFParagraph
XWPFDocument.getParagraphArray(int pos)

Returns the paragraph that of position pos

XWPFParagraph
XWPFHeaderFooter.getParagraphArray(int pos)

Returns the paragraph that holds
  the text of the header or footer.

XWPFParagraph
XWPFTableCell.insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor)

add a new paragraph at position of the cursor

XWPFParagraph
XWPFFootnote.insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor)

add a new paragraph at position of the cursor

XWPFParagraph
IBody.insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor)

inserts a new paragraph at position of the cursor

XWPFParagraph
XWPFDocument.insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor)

Add a new paragraph at position of the cursor.

XWPFParagraph
XWPFHeaderFooter.insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor)

add a new paragraph at position of the cursor

Methods in org.apache.poi.xwpf.usermodel that return types with arguments of type XWPFParagraph

Modifier and Type
Method and Description

java.util.List<XWPFParagraph>
XWPFHeaderFooter.getListParagraph()

get a List of all Paragraphs

java.util.List<XWPFParagraph>
XWPFTableCell.getParagraphs()

returns a list of paragraphs

java.util.List<XWPFParagraph>
XWPFFootnote.getParagraphs()

java.util.List<XWPFParagraph>
IBody.getParagraphs()

Returns the paragraph(s) that holds
  the text of the header or footer.

java.util.List<XWPFParagraph>
XWPFDocument.getParagraphs()

java.util.List<XWPFParagraph>
XWPFHeaderFooter.getParagraphs()

Returns the paragraph(s) that holds
  the text of the header or footer.

java.util.Iterator<XWPFParagraph>
XWPFDocument.getParagraphsIterator()

java.util.Iterator<XWPFParagraph>
XWPFFootnote.iterator()

Methods in org.apache.poi.xwpf.usermodel with parameters of type XWPFParagraph

Modifier and Type
Method and Description

void
XWPFTableCell.addParagraph(XWPFParagraph p)

add a Paragraph to this TableCell

int
XWPFDocument.getPosOfParagraph(XWPFParagraph p)

Get the position of the paragraph, within the list
  of all the body elements.

void
XWPFTableCell.setParagraph(XWPFParagraph p)

void
XWPFDocument.setParagraph(XWPFParagraph paragraph,
            int pos)

copies content of a paragraph to a existing paragraph in the list paragraphs at position pos

Constructors in org.apache.poi.xwpf.usermodel with parameters of type XWPFParagraph

Constructor and Description

XWPFRun(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR r,
       XWPFParagraph p)

Deprecated.

Use XWPFRun.XWPFRun(CTR, IRunBody)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.