text:
/**
 * @module Application
 */
define([
    'prompts/Prompt',
    'require.text!templates/prompts/prompt-rune.html'
], function(Prompt, DesktopTemplate) {
    /**
     * @class PromptRune
     * @extends {Prompt}
     */
    var PromptRune = Prompt.extend({
        /**
         * @method initialize
         * @param {Object} [options]
         * @param {PromptController} controller
         * @param {DataReview} review
         * @constructor
         */
        initialize: function(options, controller, review) {
            Prompt.prototype.initialize.call(this, options, controller, review);
            this.attempts = 0;
            this.character = undefined;
            this.maxAttempts = 3;
            this.revealed = false;
            this.taps = 0;
        },
        /**
         * @method render
         * @returns {PromptRune}
         */
        render: function() {
            app.timer.setLimits(30, 15);
            this.$el.html(this.compile(DesktopTemplate));
            this.elements.toolbar = this.$('.prompt-toolbar');
            this.elements.toolbarEraser = this.$('#toolbar-eraser');
            this.elements.toolbarReveal = this.$('#toolbar-reveal');
            this.attempts = 0;
            this.taps = 0;
            Prompt.prototype.render.call(this);
            this.canvas.getLayer('stroke').alpha = 1;
            this.canvas.showGrid().show();
            return this;
        },
        /**
         * @method renderAnswer
         * @returns {PromptRune}
         */
        renderAnswer: function() {
            Prompt.prototype.renderAnswer.call(this);
            this.canvas.disableInput();
            if (app.user.settings.isAudioEnabled() && app.user.settings.get('hideReading') && this.review.isLast()) {
                this.vocab.playAudio();
            }
            this.elements.fieldDefinition.html(this.vocab.getDefinition());
            if (app.user.settings.get('showHeisig') && this.vocab.has('heisigDefinition')) {
                this.elements.fieldHeisig.text('Keyword: ' + this.vocab.get('heisigDefinition'));
            }
            if (this.vocab.isJapanese() && app.fn.hasKana(this.vocab.get('writing'))) {
                if (app.fn.isKana(this.vocab.get('writing'))) {
                    this.elements.fieldReading.empty();
                } else if (this.review.isLast()) {
                    this.elements.fieldReading.html(this.vocab.getReading(null, {
                        hide: this.review.isLast() ? false : app.user.settings.get('hideReading'),
                        style: app.user.settings.get('readingStyle')
                    }));
                } else {
                    this.elements.fieldReading.html(this.vocab.getReading(null, {
                        hide: app.user.settings.get('hideReading'),
                        hideKana: app.user.settings.get('studyKana') ? this.vocab.getKana() : [],
                        style: app.user.settings.get('readingStyle')
                    }));
                }
            } else {
                this.elements.fieldReading.html(this.vocab.getReading(app.user.settings.get('hideReading') ? this.position + 1 : null, {
                    hide: this.review.isLast() ? false : app.user.settings.get('hideReading'),
                    style: app.user.settings.get('readingStyle')
                }));
            }
            this.elements.fieldWriting.html(this.vocab.getWriting(this.position + 1, {classes: 'highlight'}));
            if (app.user.settings.get('gradingColor')) {
                var layer = app.user.settings.get('squigs') ? 'background' : 'stroke';
                this.canvas.injectLayerColor(layer, app.user.settings.get('gradingColors')[this.review.getAt('score') - 1]);
            }
            return this;
        },
        /**
         * @method renderQuestion
         * @returns {PromptRune}
         */
        renderQuestion: function() {
            Prompt.prototype.renderQuestion.call(this);
            if (app.user.settings.isAudioEnabled() && !app.user.settings.get('hideReading') && this.review.isFirst()) {
                this.vocab.playAudio();
            }
            this.canvas.enableInput();
            this.elements.fieldDefinition.html(this.vocab.getDefinition());
            if (app.user.settings.get('showHeisig') && this.vocab.has('heisigDefinition')) {
                this.elements.fieldHeisig.text('Keyword: ' + this.vocab.get('heisigDefinition'));
            }
            if (this.vocab.isJapanese() && app.fn.hasKana(this.vocab.get('writing'))) {
                if (app.fn.isKana(this.vocab.get('writing'))) {
                    this.elements.fieldReading.empty();
                } else {
                    this.elements.fieldReading.html(this.vocab.getReading(null, {
                        hide: app.user.settings.get('hideReading'),
                        hideKana: app.user.settings.get('studyKana') ? this.vocab.getKana() : [],
                        style: app.user.settings.get('readingStyle')
                    }));
                }
            } else {
                this.elements.fieldReading.html(this.vocab.getReading(app.user.settings.get('hideReading') ? this.position : null, {
                    hide: app.user.settings.get('hideReading'),
                    style: app.user.settings.get('readingStyle')
                }));
            }
            this.elements.fieldWriting.html(this.vocab.getWriting(this.position, {classes: 'highlight'}));
            this.toggleToolbarEraser();
            return this;
        },
        /**
         * @method events
         * @returns {Object}
         */
        events: _.extend({}, Prompt.prototype.events, {
            'vclick #toolbar-eraser': 'handleToolbarEraserClicked',
            'vclick #toolbar-reveal': 'handleToolbarRevealClicked',
            'vclick #toolbar-teach': 'handleToolbarTeachClicked'
        }),
        /**
         * @method handlePromptClicked
         */
        handleCanvasClicked: function() {
            if (app.sidebars.isCollapsed() && this.promptClick) {
                if (this.review.getAt('answered')) {
                    this.next();
                } else if (!this.character.isComplete()) {
                    this.taps++;
                    this.canvas.fadeShape('background', this.character.getExpectedStroke().getShape(), {color: '#b3b3b3', milliseconds: 1000});
                }
            }
        },
        /**
         * @method handleInputDown
         */
        handleInputDown: function() {
            app.timer.stopThinking();
        },
        /**
         * @method handleInputUp
         */
        handleInputUp: function(points, shape) {
            if (points && points.length > 1 && shape) {
                var stroke = this.character.recognizeStroke(points, shape);
                if (stroke) {
                    this.attempts = 0;
                    this.toggleToolbarEraser();
                    this.canvas.lastMouseDownEvent = null;
                    if (app.user.settings.get('squigs')) {
                        this.canvas.getLayer('stroke').alpha = 1;
                        this.canvas.drawShape('stroke', shape);
                    } else {
                        this.canvas.tweenShape('stroke', stroke.getUserShape(), stroke.getShape());
                    }
                    if (this.character.isComplete()) {
                        if (this.taps > 2) {
                            this.review.setAt('score', 1);
                        } else if (this.taps >= 1 && this.character.getMax() < 6) {
                            this.review.setAt('score', 1);
                        } else if (this.taps > 1) {
                            this.review.setAt('score', 2);
                        }
                        if (app.user.settings.get('squigs')) {
                            this.canvas.tweenCharacter('background', this.review.getCharacter());
                            if (app.user.settings.get('gradingColor')) {
                                this.canvas.injectLayerColor('stroke', '#444444');
                            } else {
                                this.canvas.injectLayerColor('stroke', '#888888');
                            }
                            this.canvas.getLayer('stroke').alpha = 0.75;
                            this.review.setSquig(this.canvas.getLayer('stroke').clone(true));
                        } else {
                            this.canvas.fadeLayer('background', null);
                        }
                        this.revealed = false;
                        this.toggleToolbarReveal();
                        this.renderAnswer();
                    } else {
                        if (this.teaching) {
                            this.teach();
                        } else {
                            this.canvas.fadeLayer('background', null);
                            this.revealed = false;
                            this.toggleToolbarReveal();
                        }
                    }
                } else {
                    this.attempts++;
                    if (this.attempts > this.maxAttempts) {
                        this.canvas.fadeShape('background', this.character.getExpectedStroke().getShape(), {color: '#b3b3b3', milliseconds: 1000});
                        this.review.setAt('score', 1);
                    }
                }
            }
        },
        /**
         * @method handleCanvasSwipeUp
         */
        handleCanvasSwipeUp: function() {
            if (this.character.length) {
                this.hideNavigation();
                app.analytics.trackEvent('Prompt', 'swipeup', 'eraser');
                this.renderQuestion();
                this.character.reset();
                this.canvas.clearAll();
                this.revealed = false;
                this.toggleToolbarReveal();
            }
            this.toggleToolbarEraser();
        },
        /**
         * @method handleToolbarEraserClicked
         * @param {Event} event
         */
        handleToolbarEraserClicked: function(event) {
            event.preventDefault();
            this.gradingButtons.hide();
            app.analytics.trackEvent('Prompt', 'click', 'eraser');
            this.review.setAt('answered', false);
            this.teaching = false;
            if (this.character.length) {
                this.hideNavigation();
                this.renderQuestion();
                this.character.reset();
                this.canvas.clearAll();
                this.revealed = false;
                this.teaching = false;
                this.toggleToolbarReveal();
            }
            this.toggleToolbarEraser();
        },
        /**
         * @method handleToolbarRevealClicked
         * @param {Event} event
         */
        handleToolbarRevealClicked: function(event) {
            event.preventDefault();
            app.analytics.trackEvent('Prompt', 'click', 'reveal');
            if (this.revealed) {
                this.canvas.clearLayer('background');
                this.revealed = false;
            } else {
                this.revealCharacter();
                this.revealed = true;
            }
            this.toggleToolbarReveal();
        },
        /**
         * @method handleToolbarTeachClicked
         * @param {Event} event
         */
        handleToolbarTeachClicked: function(event) {
            event.preventDefault();
            app.analytics.trackEvent('Prompt', 'click', 'teach');
            this.review.setAt('score', 1);
            if (this.character.isComplete()) {
                this.handleToolbarEraserClicked(event);
                this.teach();
            } else {
                if (this.teaching) {
                    this.canvas.fadeLayer('background', null);
                    this.teaching = false;
                } else {
                    this.teach();
                }
            }
        },
        /**
         * @method reset
         * @returns {PromptRune}
         */
        reset: function() {
            Prompt.prototype.reset.call(this);
            this.canvas.clearAll();
            return this;
        },
        /**
         * @method resize
         * @returns {PromptRune}v
         */
        resize: function() {
            Prompt.prototype.resize.call(this);
            var canvasSize = this.canvas.getWidth();
            var contentHeight = app.router.currentPage.getContentHeight();
            var contentWidth = app.router.currentPage.getContentWidth();
            if (app.isPortrait()) {
                this.$el.css({
                    'border-bottom': '1px solid #000000',
                    'border-right': 'none',
                    height: contentHeight - canvasSize - 1,
                    'padding-top': 0,
                    width: canvasSize
                });
                this.elements.toolbar.css({
                    'border-bottom': 'none',
                    'border-top': '1px solid #000000',
                    bottom: 0,
                    top: 'auto'
                });
                this.elements.promptText.css('max-height', contentHeight - canvasSize - 36);
            } else {
                this.$el.css({
                    'border-bottom': 'none',
                    'border-right': '1px solid #000000',
                    height: canvasSize,
                    'padding-top': '36px',
                    width: contentWidth - canvasSize - 1
                });
                this.elements.toolbar.css({
                    'border-bottom': '1px solid #000000',
                    'border-top': 'none',
                    bottom: 'auto',
                    top: 0
                });
                this.elements.promptText.css('max-height', contentHeight - 36);
            }
            this.canvas.clearAll();
            if (app.user.settings.get('gradingColor') && this.character.isComplete()) {
                this.canvas.drawShape('stroke', this.character.getShape(), {
                    color: app.user.settings.get('gradingColors')[this.review.getAt('score') - 1]
                });
                if (this.review.getSquig()) {
                    this.canvas.getLayer('stroke').addChild(this.review.getSquig());
                }
            } else if (this.character.length) {
                this.canvas.drawShape('stroke', this.character.getShape());
            }
            return this;
        },
        /**
         * @method revealCharacter
         * @param {Number} [excludeStroke]
         */
        revealCharacter: function(excludeStroke) {
            this.canvas.clearLayer('background');
            this.canvas.drawShape('background', this.character.getExpectedVariations()[0].getShape(excludeStroke), {color: '#b3b3b3'});
            this.review.setAt('score', 1);
        },
        /**
         * @method teach
         * @returns {PromptRune}
         */
        teach: function() {
            var stroke = this.character.getExpectedStroke();
            if (stroke) {
                var strokeParam = stroke.getTraceParam();
                var strokePath = strokeParam.get('corners');
                this.canvas.clearLayer('background');
                this.canvas.drawShape('background', stroke.getShape(), {color: '#b3b3b3'});
                this.canvas.tracePath('background', strokePath);
                this.review.setAt('score', 1);
                this.teaching = true;
            }
            return this;
        },
        /**
         * @method toggleToolbarEraser
         */
        toggleToolbarEraser: function() {
            if (this.character.length) {
                this.elements.toolbarEraser.removeClass('text-muted');
            } else {
                this.elements.toolbarEraser.addClass('text-muted');
            }
        },
        /**
         * @method toggleToolbarReveal
         */
        toggleToolbarReveal: function() {
            if (this.revealed) {
                this.elements.toolbarReveal.addClass('text-primary');
            } else {
                this.elements.toolbarReveal.removeClass('text-primary');
            }
        }
    });

    return PromptRune;
});


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using SixLabors.ImageSharp;
using Microsoft.Extensions.Caching.Memory;
using RatpService;
using restratp.Interfaces;
using restratp.Models;
using System.Linq;

namespace restratp.Services
{
    public class LineService : BaseService, ILineService
    {
        private IImageService imageService;

        public LineService(IMapper mapper,
           IMemoryCache memoryCache,
           WsivPortType ratpService,
           IImageService imageService) :
               base(mapper, memoryCache, ratpService)
        {
            this.imageService = imageService;
        }

        public async Task<LineModel[]> GetNetworkLines(string networkId)
        {
            LineModel[] lines;
            if (!cache.TryGetValue(networkId, out lines))
            {
                var line = new Line()
                {
                    reseau = new Reseau() { code = networkId },
                    realm = "r"
                };

                var linesResponse = await ratpService.getLinesAsync(new getLinesRequest(line));
                lines = mapper.Map<Line[], LineModel[]>(linesResponse.@return);

                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromHours(24));
                // Save data in cache.
                cache.Set(networkId, lines, cacheEntryOptions);
            }

            return lines;
        }

        public async Task<string> GetLineColor(string networkId, string lineId)
        {
            string imgRGB = string.Empty;

            LineModel[] lines = await GetNetworkLines(networkId);

            var line = lines.FirstOrDefault(l => l.Id == lineId);
            if (line != null)
            {
                var imageBytes = await imageService.GetImage(line.Image);
                var image = Image.Load(imageBytes);
                var prominentColor = GetPixelsColor(image)
                                        .Where(color => color != (uint)LineColor.Black && color != (uint)LineColor.White) //not black or white
                                        .GroupBy(color => color)
                                        .OrderByDescending(grp => grp.Count())
                                        .Select(grp => grp.Key).FirstOrDefault();

                var rgbColor = new Rgba32(prominentColor);

                imgRGB = $"rgb({rgbColor.R},{rgbColor.G},{rgbColor.B})";
            }

            return imgRGB;
        }

        private IEnumerable<uint> GetPixelsColor(Image<Rgba32> img)
        {
            var heigth = img.Height;
            var length = img.Width;

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < heigth; j++)
                {
                    yield return img[i, j].PackedValue;
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <syslog.h>

#include "audio_thread.h"
#include "cras_iodev.h"
#include "cras_iodev_info.h"
#include "cras_iodev_list.h"
#include "cras_rstream.h"
#include "cras_server.h"
#include "cras_types.h"
#include "cras_system_state.h"
#include "softvol_curve.h"
#include "utlist.h"

/* Linked list of available devices. */
struct iodev_list {
	struct cras_iodev *iodevs;
	size_t size;
};

/* Separate list for inputs and outputs. */
static struct iodev_list outputs;
static struct iodev_list inputs;
/* Keep an active input and output. */
static struct cras_iodev *active_output;
static struct cras_iodev *active_input;
/* Keep a default input and output. For use when there is nothing else. */
static struct cras_iodev *default_output;
static struct cras_iodev *default_input;
/* device used for loopback. */
static struct cras_iodev *loopback_dev;
/* Keep a constantly increasing index for iodevs. Index 0 is reserved
 * to mean "no device". */
static uint32_t next_iodev_idx = 1;
/* Selected node for input and output. 0 if there is no node selected. */
static cras_node_id_t selected_input;
static cras_node_id_t selected_output;
/* Called when the nodes are added/removed. */
static struct cras_alert *nodes_changed_alert;
/* Called when the active output/input is changed */
static struct cras_alert *active_node_changed_alert;
/* Call when the volume of a node changes. */
static node_volume_callback_t node_volume_callback;
static node_volume_callback_t node_input_gain_callback;
/* Thread that handles audio input and output. */
static struct audio_thread *audio_thread;

static void nodes_changed_prepare(struct cras_alert *alert);
static void active_node_changed_prepare(struct cras_alert *alert);

static struct cras_iodev *find_dev(size_t dev_index)
{
	struct cras_iodev *dev;

	DL_FOREACH(outputs.iodevs, dev)
		if (dev->info.idx == dev_index)
			return dev;

	DL_FOREACH(inputs.iodevs, dev)
		if (dev->info.idx == dev_index)
			return dev;

	return NULL;
}

static struct cras_ionode *find_node(cras_node_id_t id)
{
	struct cras_iodev *dev;
	struct cras_ionode *node;
	uint32_t dev_index, node_index;

	dev_index = dev_index_of(id);
	node_index = node_index_of(id);

	dev = find_dev(dev_index);
	if (!dev)
		return NULL;

	DL_FOREACH(dev->nodes, node)
		if (node->idx == node_index)
			return node;

	return NULL;
}

/* Adds a device to the list.  Used from add_input and add_output. */
static int add_dev_to_list(struct iodev_list *list,
			   struct cras_iodev *dev)
{
	struct cras_iodev *tmp;
	uint32_t new_idx;

	DL_FOREACH(list->iodevs, tmp)
		if (tmp == dev)
			return -EEXIST;

	dev->format = NULL;
	dev->prev = dev->next = NULL;

	/* Move to the next index and make sure it isn't taken. */
	new_idx = next_iodev_idx;
	while (1) {
		/* Index 0 is reserved to mean "no device". */
		if (new_idx == 0)
			new_idx++;
		DL_SEARCH_SCALAR(list->iodevs, tmp, info.idx, new_idx);
		if (tmp == NULL)
			break;
		new_idx++;
	}
	dev->info.idx = new_idx;
	next_iodev_idx = new_idx + 1;
	list->size++;

	syslog(LOG_INFO, "Adding %s dev at index %u.",
	       dev->direction == CRAS_STREAM_OUTPUT ? "output" : "input",
	       dev->info.idx);
	DL_PREPEND(list->iodevs, dev);

	cras_iodev_list_update_device_list();
	return 0;
}

/* Removes a device to the list.  Used from rm_input and rm_output. */
static int rm_dev_from_list(struct iodev_list *list, struct cras_iodev *dev)
{
	struct cras_iodev *tmp;

	DL_FOREACH(list->iodevs, tmp)
		if (tmp == dev) {
			if (dev->is_open(dev))
				return -EBUSY;
			DL_DELETE(list->iodevs, dev);
			list->size--;
			return 0;
		}

	/* Device not found. */
	return -EINVAL;
}

/* Fills a dev_info array from the iodev_list. */
static void fill_dev_list(struct iodev_list *list,
			  struct cras_iodev_info *dev_info,
			  size_t out_size)
{
	int i = 0;
	struct cras_iodev *tmp;
	DL_FOREACH(list->iodevs, tmp) {
		memcpy(&dev_info[i], &tmp->info, sizeof(dev_info[0]));
		i++;
		if (i == out_size)
			return;
	}
}

static const char *node_type_to_str(enum CRAS_NODE_TYPE type)
{
	switch (type) {
	case CRAS_NODE_TYPE_INTERNAL_SPEAKER:
		return "INTERNAL_SPEAKER";
	case CRAS_NODE_TYPE_HEADPHONE:
		return "HEADPHONE";
	case CRAS_NODE_TYPE_HDMI:
		return "HDMI";
	case CRAS_NODE_TYPE_INTERNAL_MIC:
		return "INTERNAL_MIC";
	case CRAS_NODE_TYPE_MIC:
		return "MIC";
	case CRAS_NODE_TYPE_USB:
		return "USB";
	case CRAS_NODE_TYPE_BLUETOOTH:
		return "BLUETOOTH";
	case CRAS_NODE_TYPE_UNKNOWN:
	default:
		return "UNKNOWN";
	}
}

/* Fills an ionode_info array from the iodev_list. */
static int fill_node_list(struct iodev_list *list,
			  struct cras_ionode_info *node_info,
			  size_t out_size)
{
	int i = 0;
	struct cras_iodev *dev;
	struct cras_ionode *node;
	DL_FOREACH(list->iodevs, dev) {
		DL_FOREACH(dev->nodes, node) {
			node_info->iodev_idx = dev->info.idx;
			node_info->ionode_idx = node->idx;
			node_info->priority = node->priority;
			node_info->plugged = node->plugged;
			node_info->plugged_time = node->plugged_time;
			node_info->active =
				(dev == active_input || dev == active_output)
				&& (dev->active_node == node);
			node_info->volume = node->volume;
			node_info->capture_gain = node->capture_gain;
			strcpy(node_info->name, node->name);
			snprintf(node_info->type, sizeof(node_info->type), "%s",
				node_type_to_str(node->type));
			node_info++;
			i++;
			if (i == out_size)
				return i;
		}
	}
	return i;
}

/* Copies the info for each device in the list to "list_out". */
static int get_dev_list(struct iodev_list *list,
			struct cras_iodev_info **list_out)
{
	struct cras_iodev_info *dev_info;

	if (!list_out)
		return list->size;

	*list_out = NULL;
	if (list->size == 0)
		return 0;

	dev_info = malloc(sizeof(*list_out[0]) * list->size);
	if (dev_info == NULL)
		return -ENOMEM;

	fill_dev_list(list, dev_info, list->size);

	*list_out = dev_info;
	return list->size;
}

static void update_software_volume(struct cras_iodev *iodev)
{
	if (cras_iodev_software_volume_needed(iodev)) {
		unsigned int volume = cras_system_get_volume();
		float volume_scaler = softvol_get_scaler(
			cras_iodev_adjust_active_node_volume(iodev, volume));
		cras_iodev_set_software_volume(iodev, volume_scaler);
	}
	else {
		cras_iodev_set_software_volume(iodev, 1.0);
	}
}

/* Called when the system volume changes.  Pass the current volume setting to
 * the default output if it is active. */
void sys_vol_change(void *data)
{
	if (active_output &&
	    active_output->set_volume &&
	    active_output->is_open(active_output))
		active_output->set_volume(active_output);
	update_software_volume(active_output);
}

/* Called when the system mute state changes.  Pass the current mute setting
 * to the default output if it is active. */
void sys_mute_change(void *data)
{
	if (active_output &&
	    active_output->set_mute &&
	    active_output->is_open(active_output))
		active_output->set_mute(active_output);
}

/* Called when the system capture gain changes.  Pass the current capture_gain
 * setting to the default input if it is active. */
void sys_cap_gain_change(void *data)
{
	if (active_input &&
	    active_input->set_capture_gain &&
	    active_input->is_open(active_input))
		active_input->set_capture_gain(active_input);
}

/* Called when the system capture mute state changes.  Pass the current capture
 * mute setting to the default input if it is active. */
void sys_cap_mute_change(void *data)
{
	if (active_input &&
	    active_input->set_capture_mute &&
	    active_input->is_open(active_input))
		active_input->set_capture_mute(active_input);
}

/*
 * Exported Interface.
 */

void cras_iodev_list_init()
{
	cras_system_register_volume_changed_cb(sys_vol_change, NULL);
	cras_system_register_mute_changed_cb(sys_mute_change, NULL);
	cras_system_register_capture_gain_changed_cb(sys_cap_gain_change, NULL);
	cras_system_register_capture_mute_changed_cb(sys_cap_mute_change, NULL);
	nodes_changed_alert = cras_alert_create(nodes_changed_prepare);
	active_node_changed_alert = cras_alert_create(
		active_node_changed_prepare);
	audio_thread = audio_thread_create();
	audio_thread_start(audio_thread);
}

void cras_iodev_list_deinit()
{
	cras_system_remove_volume_changed_cb(sys_vol_change, NULL);
	cras_system_remove_mute_changed_cb(sys_vol_change, NULL);
	cras_system_remove_capture_gain_changed_cb(sys_cap_gain_change, NULL);
	cras_system_remove_capture_mute_changed_cb(sys_cap_mute_change, NULL);
	cras_alert_destroy(nodes_changed_alert);
	cras_alert_destroy(active_node_changed_alert);
	nodes_changed_alert = NULL;
	active_node_changed_alert = NULL;
	audio_thread_destroy(audio_thread);
}

/* Finds the current device for a stream of "type", only default streams are
 * currently supported so return the default device fot the given direction.
 */
int cras_get_iodev_for_stream_type(enum CRAS_STREAM_TYPE type,
				   enum CRAS_STREAM_DIRECTION direction,
				   struct cras_iodev **idev,
				   struct cras_iodev **odev)
{
	switch (direction) {
	case CRAS_STREAM_OUTPUT:
		*idev = NULL;
		*odev = active_output;
		break;
	case CRAS_STREAM_INPUT:
		*idev = active_input;
		*odev = NULL;
		break;
	case CRAS_STREAM_UNIFIED:
		*idev = active_input;
		*odev = active_output;
		break;
	case CRAS_STREAM_POST_MIX_PRE_DSP:
		*idev = (struct cras_iodev *)loopback_dev;
		*odev = NULL;
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

static struct cras_iodev *cras_iodev_set_active(
		enum CRAS_STREAM_DIRECTION dir,
		struct cras_iodev *new_active)
{
	struct cras_iodev *old_active;
	struct cras_iodev **curr;

	if (new_active && new_active->set_as_default)
		new_active->set_as_default(new_active);

	cras_iodev_list_notify_active_node_changed();

	audio_thread_remove_streams(audio_thread, dir);

	if (dir == CRAS_STREAM_OUTPUT) {
		curr = &active_output;
		audio_thread_set_output_dev(audio_thread, new_active);
	} else {
		curr = &active_input;
		audio_thread_set_input_dev(audio_thread, new_active);
	}

	/* Set current active to the newly requested device. */
	old_active = *curr;
	*curr = new_active;

	return old_active;
}

int cras_iodev_list_add_output(struct cras_iodev *output)
{
	int rc;

	if (output->direction != CRAS_STREAM_OUTPUT)
		return -EINVAL;

	rc = add_dev_to_list(&outputs, output);
	if (rc)
		return rc;

	if (!active_output) {
		active_output = output;
		audio_thread_set_output_dev(audio_thread, output);
	}
	if (!default_output)
		default_output = output;

	return 0;
}

int cras_iodev_list_add_input(struct cras_iodev *input)
{
	int rc;

	if (input->direction == CRAS_STREAM_POST_MIX_PRE_DSP) {
		loopback_dev = input;
		audio_thread_add_loopback_device(audio_thread, input);
		return 0;
	}

	if (input->direction != CRAS_STREAM_INPUT)
		return -EINVAL;

	rc = add_dev_to_list(&inputs, input);
	if (rc)
		return rc;

	if (!active_input) {
		active_input = input;
		audio_thread_set_input_dev(audio_thread, input);
	}
	if (!default_input)
		default_input = input;

	return 0;
}

int cras_iodev_list_rm_output(struct cras_iodev *dev)
{
	int res;

	/* Retire the current active output device before removing it from
	 * list, otherwise it could be busy and remain in the list.
	 */
	if (active_output == dev)
		cras_iodev_set_active(CRAS_STREAM_OUTPUT, default_output);

	res = rm_dev_from_list(&outputs, dev);
	if (res == 0)
		cras_iodev_list_update_device_list();
	return res;
}

int cras_iodev_list_rm_input(struct cras_iodev *dev)
{
	int res;

	/* Retire the current active input device before removing it from
	 * list, otherwise it could be busy and remain in the list.
	 */
	if (active_input == dev)
		cras_iodev_set_active(CRAS_STREAM_INPUT, default_input);

	res = rm_dev_from_list(&inputs, dev);
	if (res == 0)
		cras_iodev_list_update_device_list();
	return res;
}

int cras_iodev_list_get_outputs(struct cras_iodev_info **list_out)
{
	return get_dev_list(&outputs, list_out);
}

int cras_iodev_list_get_inputs(struct cras_iodev_info **list_out)
{
	return get_dev_list(&inputs, list_out);
}

cras_node_id_t cras_iodev_list_get_active_node_id(
	enum CRAS_STREAM_DIRECTION direction)
{
	struct cras_iodev *dev = (direction == CRAS_STREAM_OUTPUT) ?
		active_output : active_input;

	if (!dev || !dev->active_node)
		return 0;

	return cras_make_node_id(dev->info.idx, dev->active_node->idx);
}

int cras_iodev_move_stream_type(enum CRAS_STREAM_TYPE type, uint32_t index)
{
	struct cras_iodev *curr_dev, *new_dev;

	/* Find new dev */
	DL_SEARCH_SCALAR(outputs.iodevs, new_dev, info.idx, index);
	if (new_dev == NULL) {
		DL_SEARCH_SCALAR(inputs.iodevs, new_dev, info.idx, index);
		if (new_dev == NULL)
			return -EINVAL;
	}

	/* Set default to the newly requested device. */
	curr_dev = cras_iodev_set_active(new_dev->direction, new_dev);

	if (curr_dev == NULL || curr_dev == new_dev)
		return 0; /* No change or no streams to move. */

	return 0;
}

void cras_iodev_list_update_device_list()
{
	struct cras_server_state *state;

	state = cras_system_state_update_begin();
	if (!state)
		return;

	state->num_output_devs = outputs.size;
	state->num_input_devs = inputs.size;
	fill_dev_list(&outputs, &state->output_devs[0], CRAS_MAX_IODEVS);
	fill_dev_list(&inputs, &state->input_devs[0], CRAS_MAX_IODEVS);

	state->num_output_nodes = fill_node_list(&outputs,
						 &state->output_nodes[0],
						 CRAS_MAX_IONODES);
	state->num_input_nodes = fill_node_list(&inputs,
						&state->input_nodes[0],
						CRAS_MAX_IONODES);
	state->selected_output = selected_output;
	state->selected_input = selected_input;

	cras_system_state_update_complete();
}

int cras_iodev_list_register_nodes_changed_cb(cras_alert_cb cb, void *arg)
{
	return cras_alert_add_callback(nodes_changed_alert, cb, arg);
}

int cras_iodev_list_remove_nodes_changed_cb(cras_alert_cb cb, void *arg)
{
	return cras_alert_rm_callback(nodes_changed_alert, cb, arg);
}

void cras_iodev_list_notify_nodes_changed()
{
	cras_alert_pending(nodes_changed_alert);
}

static void nodes_changed_prepare(struct cras_alert *alert)
{
	cras_iodev_list_update_device_list();
}

int cras_iodev_list_register_active_node_changed_cb(cras_alert_cb cb,
						    void *arg)
{
	return cras_alert_add_callback(active_node_changed_alert, cb, arg);
}

int cras_iodev_list_remove_active_node_changed_cb(cras_alert_cb cb,
						  void *arg)
{
	return cras_alert_rm_callback(active_node_changed_alert, cb, arg);
}

void cras_iodev_list_notify_active_node_changed()
{
	cras_alert_pending(active_node_changed_alert);
	if (active_output)
		update_software_volume(active_output);
}

static void active_node_changed_prepare(struct cras_alert *alert)
{
	cras_iodev_list_update_device_list();
}

void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
				 cras_node_id_t node_id)
{
	struct cras_iodev *old_dev = NULL, *new_dev = NULL;
	cras_node_id_t *selected;

	selected = (direction == CRAS_STREAM_OUTPUT) ? &selected_output :
		&selected_input;

	/* return if no change */
	if (node_id == *selected)
		return;

	/* find the devices for the id. */
	old_dev = find_dev(dev_index_of(*selected));
	new_dev = find_dev(dev_index_of(node_id));

	/* Fail if the direction is mismatched. We don't fail for the new_dev ==
	   NULL case. That can happen if node_id is 0 (no selection), or the
	   client tries to select a non-existing node (maybe it's unplugged just
	   before the client selects it). We will just behave like there is no
	   selected node. */
	if (new_dev && new_dev->direction != direction)
		return;

	/* change to new selection */
	*selected = node_id;

	/* update new device */
	if (new_dev) {
		new_dev->update_active_node(new_dev);
		/* There is an iodev and it isn't the default, switch to it. */
		cras_iodev_move_stream_type(CRAS_STREAM_TYPE_DEFAULT, new_dev->info.idx);
	}

	/* update old device if it is not the same device */
	if (old_dev && old_dev != new_dev)
		old_dev->update_active_node(old_dev);
}

int cras_iodev_list_set_node_attr(cras_node_id_t node_id,
				  enum ionode_attr attr, int value)
{
	struct cras_ionode *node;

	node = find_node(node_id);
	if (!node)
		return -EINVAL;

	return cras_iodev_set_node_attr(node, attr, value);
}

int cras_iodev_list_node_selected(struct cras_ionode *node)
{
	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
	return (id == selected_input || id == selected_output);
}

void cras_iodev_list_set_node_volume_callbacks(node_volume_callback_t volume_cb,
					       node_volume_callback_t gain_cb)
{
	node_volume_callback = volume_cb;
	node_input_gain_callback = gain_cb;
}

void cras_iodev_list_notify_node_volume(struct cras_ionode *node)
{
	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);

	if (node_volume_callback)
		node_volume_callback(id, node->volume);

	update_software_volume(node->dev);
}

void cras_iodev_list_notify_node_capture_gain(struct cras_ionode *node)
{
	cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);

	if (node_input_gain_callback)
		node_input_gain_callback(id, node->capture_gain);
}

struct audio_thread *cras_iodev_list_get_audio_thread()
{
	return audio_thread;
}

void cras_iodev_list_reset()
{
	active_output = NULL;
	active_input = NULL;
	default_output = NULL;
	default_input = NULL;
}


text:
using System.Xml.Linq;

namespace CompositeC1Contrib.FormBuilder.Dynamic.SubmitHandlers
{
    public abstract class FormSubmitHandler
    {
        public string Name { get; set; }
        public abstract void Submit(IModelInstance instance);

        public virtual void Load(IDynamicDefinition model, XElement handler)
        {
            Name = handler.Attribute("Name").Value;
        }

        public virtual void Save(IDynamicDefinition definition, XElement handler) { }
        public virtual void Delete(IDynamicDefinition definition) { }
    }
}


text:
DD_DETAIL_BEGIN_
template <typename ValueT_>
struct BatchIterator :
#	if __cplusplus >= 201103L
	Comparable<BatchIterator<ValueT_>>,
#	else
	Comparable<BatchIterator<ValueT_> >,
#	endif
	Addable<BatchIterator<ValueT_>, DifferenceType>,
	Subtractable<BatchIterator<ValueT_>, DifferenceType>
{
	public:
	DD_ALIAS(ThisType, BatchIterator<ValueT_>);
	DD_VALUE_TYPE_NESTED(ValueT_);

	public:
	DD_ALIAS(DifferenceType, ::DD::DifferenceType);
	DD_ALIAS(CatagoryType, FreeAccessIterator);

	private:
	PointerType m_target_ DD_IN_CLASS_INITIALIZE(PointerType());
	DifferenceType m_offset_ DD_IN_CLASS_INITIALIZE(DifferenceType());

#	if __cplusplus >= 201103L
	public:
	constexpr BatchIterator() = default;

	public:
	constexpr BatchIterator(ThisType const& origin_) = default;

	public:
	constexpr BatchIterator(ThisType&& origin_) = default;
#	else
	public:
	BatchIterator() {
	}
#	endif

	public:
	DD_CONSTEXPR BatchIterator(
		ReferenceType target_,
		DifferenceType offset_ = DifferenceType()
	) DD_NOEXCEPT : m_target_(::DD::address_of(target_)), m_offset_(offset_) {
	}

	public:
	PointerType DD_CONSTEXPR get_pointer() const DD_NOEXCEPT {
		return m_target_;
	}

	public:
	DifferenceType DD_CONSTEXPR get_offset() const DD_NOEXCEPT {
		return m_offset_;
	}

	public:
	DifferenceType DD_CONSTEXPR get_difference(ThisType const& other_) const DD_NOEXCEPT {
		return other_.get_offset() - get_offset();
	}

	public:
	ValidityType DD_CONSTEXPR is_valid() const DD_NOEXCEPT {
		return get_pointer();
	}

	public:
	ValidityType DD_CONSTEXPR equal(ThisType const& other_) const DD_NOEXCEPT {
		return get_offset() == other_.get_offset();
	}

	public:
	ValidityType DD_CONSTEXPR less(ThisType const& other_) const DD_NOEXCEPT {
		return get_offset() < other_.get_offset();
	}

#	if __cplusplus >= 201103L
	public:
	ThisType& operator =(ThisType const& origin_) = default;

	public:
	ThisType& operator =(ThisType&& origin_) = default;

#	endif
	public:
	ThisType& operator ++() DD_NOEXCEPT {
		++m_offset_;
		return *this;
	}

	public:
	ThisType operator ++(int) DD_NOEXCEPT {
		ThisType result_(*this);
		++*this;
		return result_;
	}

	public:
	ThisType& operator --() DD_NOEXCEPT {
		--m_offset_;
		return *this;
	}

	public:
	ThisType operator --(int) DD_NOEXCEPT {
		ThisType result_(*this);
		--*this;
		return result_;
	}

	public:
	ThisType& operator +=(DifferenceType offset_) DD_NOEXCEPT {
		m_offset_ += offset_;
		return *this;
	}

	public:
	ThisType& operator -=(DifferenceType offset_) DD_NOEXCEPT {
		m_offset_ -= offset_;
		return *this;
	}

	public:
	ReferenceType operator *() DD_NOEXCEPT {
		return *get_pointer();
	}

	public:
	PointerType operator ->() DD_NOEXCEPT {
		return get_pointer();
	}

#	if __cplusplus >= 201103L
	public:
	explicit constexpr operator ValidityType() const noexcept {
		return is_valid();
	}

#	endif
};

template <typename ValueT_>
struct BatchRange {
	public:
	DD_ALIAS(ThisType, BatchRange<ValueT_>);
	DD_VALUE_TYPE_NESTED(ValueT_);

	public:
	DD_ALIAS(SizeType, DD::SizeType);
	DD_ALIAS(LengthType, ::DD::LengthType);

	public:
	DD_ALIAS(Iterator, BatchIterator<ValueType>);
	DD_ALIAS(ConstIterator, BatchIterator<ValueConstType>);
	DD_ITERATOR_NESTED

	public:
	ValueType value;
	LengthType length;

	public:
	Iterator begin() DD_NOEXCEPT_AS(Iterator(value)) {
		return Iterator(value);
	}

	public:
	ConstIterator DD_CONSTEXPR begin() const DD_NOEXCEPT_AS(Iterator(value)) {
		return ConstIterator(value);
	}

	public:
	Iterator end() DD_NOEXCEPT_AS(Iterator(value, length)) {
		return Iterator(value, length);
	}

	public:
	ConstIterator DD_CONSTEXPR end() const DD_NOEXCEPT_AS(Iterator(value, length)) {
		return ConstIterator(value, length);
	}

};

template <typename ValueT_>
ValidityType DD_CONSTEXPR operator ==(
	BatchIterator<ValueT_> const& iterator_1_,
	BatchIterator<ValueT_> const& iterator_2_
) DD_NOEXCEPT_AS(static_cast<ValidityType>(iterator_1_.equal(iterator_2_))) {
	return iterator_1_.equal(iterator_2_);
}

template <typename ValueT_>
ValidityType DD_CONSTEXPR operator <(
	BatchIterator<ValueT_> const& iterator_1_,
	BatchIterator<ValueT_> const& iterator_2_
) DD_NOEXCEPT_AS(static_cast<ValidityType>(iterator_1_.less(iterator_2_))) {
	return iterator_1_.less(iterator_2_);
}

template <typename ValueT_>
inline typename BatchIterator<ValueT_>::DifferenceType DD_CONSTEXPR operator -(
	BatchIterator<ValueT_> const& iterator_1_,
	BatchIterator<ValueT_> const& iterator_2_
) DD_NOEXCEPT_AS(static_cast<typename BatchIterator<ValueT_>::DifferenceType>(iterator_1_.get_difference(iterator_2_))) {
	return iterator_2_.get_difference(iterator_1_);
}

DD_DETAIL_END_

DD_BEGIN_

DD_END_

#endif


text:
Realizacja zagadnień projektu grupowego 2015 r. dla DAC System

#Uruchamianie
Do uruchomienia projektu potrzebny jest przede wszystkim zainstalowany Node wraz z npm (node package manager).
Gdy już to mamy, wykonujemy następujące polecenia wewnątrz folderu projektu:

`npm install`

`bower install` (jeśli nie działa, wpisujemy: `npm install -g bower` i potem ponownie `bower install`)

`npm install -g grunt-cli`

`npm install -g tsd`

`tsd reinstall --save`

Wszystkie zależności zostały zainstalowane. Możemy teraz uruchomić projekt wpisując `grunt serve`. Testy uruchamiane są poleceniem `grunt test`.
Najwygodniej pracuje się, kiedy uruchomimy `grunt serve`, podpinane są wtedy automatyczne watchery do plików, które kompilują wszystko gdy tylko zmieni
się zawartość któregoś z plików *.ts.


text:
// Creates the files used for input autocompletion
var qm = require('qminer');
var fs = require('fs');

console.log('Building base...');
var base = new qm.Base({
    mode:   'openReadOnly',
    dbPath: '../database/lectures/'
});

console.log('Preparing writing files...');
// initialize the autocompletion files
var authorsFs       = fs.createWriteStream('authors.aut', 'utf8');
var categoriesFs    = fs.createWriteStream('categories.aut', 'utf8');
var languagesFs     = fs.createWriteStream('languages.aut', 'utf8');
var citiesFs        = fs.createWriteStream('cities.aut', 'utf8');
// var typesFs         = fs.createWriteStream('types.aut', 'utf8');
var countriesFs     = fs.createWriteStream('countries.aut', 'utf8');
var organizationsFs = fs.createWriteStream('organizations.aut', 'utf8');

// write authors in the data
console.log('Writing authors...');
var authors = base.store("Authors").allRecords;
for (var AuthorN = 0; AuthorN < authors.length; AuthorN++) {
    var name = authors[AuthorN].name;
    if (name && name.length !== 0) {
        authorsFs.write(name + '\n');
    }
}
authorsFs.end();

// write categories in the data
console.log('Writing categories...');
var categories = base.store("Categories").allRecords;
for (var CatN = 0; CatN < categories.length; CatN++) {
    var title = categories[CatN].title;
    if (title && title.length !== 0) {
        categoriesFs.write(title + '\n');
    }
}
categoriesFs.end();

// write languages in the data
console.log('Writing languages...');
var lectures  = base.store("Lectures").allRecords;
var languageHt = new qm.ht.StrIntMap();
var typeHt     = new qm.ht.StrIntMap();
for (var LectureN = 0; LectureN < lectures.length; LectureN++) {

    var language = lectures[LectureN].language;
    if (language && language.length !== 0) {
        if (!languageHt.hasKey(language)) {
            languagesFs.write(language + '\n');
            languageHt.put(language, 1);
        }
    }

    var type = lectures[LectureN].type;
    // if (type && type.length !== 0) {
    //     if (!typeHt.hasKey(type)) {
    //         typesFs.write(type + '\n');
    //         typeHt.put(type, 1);
    //     }
    // }
}
languagesFs.end();

// write categories in the data
console.log('Writing organizations...');
var organizations = base.store("Organizations").allRecords;
var cityHt = new qm.ht.StrIntMap();
var countriesHt = new qm.ht.StrIntMap();
for (var OrgN = 0; OrgN < organizations.length; OrgN++) {
    organizationsFs.write(organizations[OrgN].name + '\n');

    var city = organizations[OrgN].city.trim();
    if (city && city.length !== 0) {
        if (!cityHt.hasKey(city)) {
            citiesFs.write(city + '\n');
            cityHt.put(city, 1);
        }
    }

    var country = organizations[OrgN].country.trim().toUpperCase();
    if (country && country.length !== 0) {
        if (!countriesHt.hasKey(country)) {
            countriesFs.write(country + '\n');
            countriesHt.put(country, 1);
        }
    }
}
organizationsFs.end();
citiesFs.end();
countriesFs.end();

console.log('Finished');
base.close();


text:
using NUnit.Framework;

namespace JoZhTranslit.Tests
{
    [TestFixture]
    public class CharArrayTests
    {
        [Test]
        public void GetMutableHashCode_Works()
        {
            var ca1 = new CharArray(2);
            ca1.Append('a');
            ca1.Append('b');

            var ca2 = new CharArray(2);
            ca2.Append('b');
            ca2.Append('a');

            Assert.That(ca1.GetMutableHashCode(), Is.Not.EqualTo(ca2.GetMutableHashCode()));

            var ca3 = new CharArray(3);
            ca3.Append('a');
            ca3.Append('b');
            ca3.Append('c');

            Assert.That(ca2.GetMutableHashCode(), Is.Not.EqualTo(ca3.GetMutableHashCode()));

            var ca4 = new CharArray(3);
            ca4.Append('a');
            ca4.Append('b');
            ca4.Append('c');

            Assert.That(ca3.GetMutableHashCode(), Is.EqualTo(ca4.GetMutableHashCode()));

        }
    }
}


text:
Tequila
=======

Tequila is a set of `Ansible <https://www.ansible.com/>`_ roles and
other tooling useful for deploying `Django
<https://www.djangoproject.com/>`_ projects.

`tequila-common <https://github.com/caktus/tequila-common>`_
    Install common system packages, set up server users and keys, add
    some basic security configuration, and create the standard project
    directory structure.

`tequila-nginx <https://github.com/caktus/tequila-nginx>`_
    Install and configure `nginx <https://nginx.org/en/docs/>`_ as a
    forwarding proxy for a Django project.

`tequila-django <https://github.com/caktus/tequila-django>`_
    Set up a Django project to run under `gunicorn
    <http://docs.gunicorn.org/en/stable/>`_ and/or `Celery
    <http://docs.celeryproject.org/en/latest/>`_.

`tequila-nodejs <https://github.com/caktus/tequila-nodejs>`_
    A thin wrapper around `geerlingguy/nodejs
    <https://github.com/geerlingguy/ansible-role-nodejs>`_,
    tequila-nodejs installs nodejs and npm, installs your project
    dependencies, and executes your front-end build script.

`tequila-postgresql <https://github.com/caktus/tequila-postgresql>`_
    Install a `PostgreSQL <https://www.postgresql.org/>`_ server and
    create a project database.

`tequila-rabbitmq <https://github.com/caktus/tequila-rabbitmq>`_
    Install and configure `RabbitMQ <https://www.rabbitmq.com/>`_ to
    use as a task queue for projects that use Celery.

Additionally, work is in progress on a couple more subprojects,

`tequila-cli <https://github.com/caktus/tequila-cli>`_
    A command-line Ansible wrapper that allows referencing inventories
    and playbooks in standard locations by more compact names, and
    allows for some actions that are difficult to do in a single
    command with standard Ansible.

`tequila-dokku <https://github.com/caktus/tequila-dokku>`_
    A role that sets up a Django project under `Dokku
    <http://dokku.viewdocs.io/dokku/>`_, a `Docker
    <https://docs.docker.com/>`_ -powered Platform-as-a-Service.

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   build_documentation
   role_development
   project_setup

Indices and tables
==================

* :ref:`search`


text:
import { Box, Clickable, Flex, ModalDialog, Spacer, Text } from "@artsy/palette"
import { graphql, useFragment } from "react-relay"
import { EntityHeaderArtistFragmentContainer } from "Components/EntityHeaders/EntityHeaderArtist"
import { MyCollectionInsightsMedianSalePriceAtAuction_artist$key } from "__generated__/MyCollectionInsightsMedianSalePriceAtAuction_artist.graphql"
import { Fragment, useState } from "react"
import { MyCollectionInsightsSelectArtistModal } from "./Components/MyCollectionInsightsSelectArtistModal"

interface MyCollectionInsightsMedianSalePriceAtAuctionProps {
  artist: MyCollectionInsightsMedianSalePriceAtAuction_artist$key
}

export const MyCollectionInsightsMedianSalePriceAtAuction: React.FC<MyCollectionInsightsMedianSalePriceAtAuctionProps> = ({
  artist,
}) => {
  const artistData = useFragment(medianSalePriceAtAuctionFragment, artist)
  const [showSelectArtistModal, setShowSelectArtistModal] = useState(false)

  return (
    <Box>
      <Text mt={2} variant={["lg-display", "lg"]}>
        Median Auction Price
      </Text>
      <Text variant={["xs", "sm-display"]} color="black60">
        Track price stability or growth of your artists
      </Text>

      <Spacer mb={[2, 4]} />

      <Flex
        flexDirection={"row"}
        justifyContent={["space-between", "flex-start"]}
      >
        <EntityHeaderArtistFragmentContainer
          artist={artistData}
          FollowButton={<Fragment></Fragment>}
          displayLink={false}
        />

        <Spacer ml={4} />

        <Clickable
          color="black60"
          textDecoration="underline"
          onClick={() => setShowSelectArtistModal(!showSelectArtistModal)}
        >
          Change Artist
        </Clickable>
      </Flex>

      {showSelectArtistModal && (
        <ModalDialog
          onClose={() => setShowSelectArtistModal(false)}
          width={["100%", 800]}
        >
          <MyCollectionInsightsSelectArtistModal />
        </ModalDialog>
      )}
    </Box>
  )
}

const medianSalePriceAtAuctionFragment = graphql`
  fragment MyCollectionInsightsMedianSalePriceAtAuction_artist on Artist {
    ...EntityHeaderArtist_artist
  }
`


text:
set -e
set -u

THIS_DIR="$(dirname "$0")"

set -x

# Installing the Ebuilds
sudo emerge --ask \
    dev-vcs/git \
    sys-devel/autoconf \
    sys-devel/automake \
    dev-libs/confuse

# Installing the python packages
pip3 install --user -r "$THIS_DIR/requirements.txt"

# Installing rust (not packaged)
curl https://sh.rustup.rs -sSf | sh

# Cargo setup
"$THIS_DIR"/cargo_setup.sh


text:
.PHONY: c c_sharp go haskell nim node python ruby clean

all: c c_sharp go haskell nim node python ruby

lib:
	cargo build

export LD_LIBRARY_PATH=../target/debug

c: lib
	cd c && gcc main.c -L ../target/debug -lstringtools -o main && ./main

c_sharp: lib
	cd c_sharp && mcs main.cs && mono main.exe

go: lib
	cd go && go run main.go

haskell: lib
	cd haskell && ghc --make main.hs -L../target/debug -lstringtools -o main && ./main

nim: lib
	cd nim && nim c -r --verbosity:0 main.nim

node: lib
	cd node && node main.js

python: lib
	cd python && python3 main.py

ruby: lib
	cd ruby && ruby main.rb

clean:
	cargo clean && rm c/main c_sharp/main.exe haskell/main


text:
from __future__ import absolute_import, division, unicode_literals

import random as insecure_random
import yaml

from cStringIO import StringIO
from datetime import datetime
from mock import ANY, Mock, patch

from changes.config import db
from changes.constants import SelectiveTestingPolicy
from changes.models.build import Build
from changes.models.job import Job
from changes.models.jobplan import JobPlan
from changes.models.project import ProjectOption
from changes.testutils import APITestCase, SAMPLE_DIFF, SAMPLE_DIFF_BYTES
from changes.testutils.build import CreateBuildsMixin
from changes.vcs.base import CommandError, RevisionResult, Vcs, UnknownRevision

_VALID_SHA = 'a' * 40
_BOGUS_SHA = 'b' * 40

class PhabricatorNotifyDiffTest(APITestCase, CreateBuildsMixin):
    path = '/api/0/phabricator/notify-diff/'

    def get_fake_vcs(self, log_results=None):
        def _log_results(parent=None, branch=None, offset=0, limit=1):
            assert not branch
            if parent not in (None, _VALID_SHA):
                raise CommandError(cmd="test command", retcode=128)
            return iter([
                RevisionResult(
                    id=_VALID_SHA,
                    message='hello world',
                    author='Foo <foo@example.com>',
                    author_date=datetime.utcnow(),
                )])
        if log_results is None:
            log_results = _log_results
        # Fake having a VCS and stub the returned commit log
        fake_vcs = Mock(spec=Vcs)
        fake_vcs.read_file.side_effect = CommandError(cmd="test command", retcode=128)
        fake_vcs.exists.return_value = True
        fake_vcs.log.side_effect = UnknownRevision(cmd="test command", retcode=128)
        fake_vcs.export.side_effect = UnknownRevision(cmd="test command", retcode=128)
        fake_vcs.get_patch_hash.return_value = 'a' * 40

        def fake_update():
            # this simulates the effect of calling update() on a repo,
            # mainly that `export` and `log` now works.
            fake_vcs.log.side_effect = log_results
            fake_vcs.export.side_effect = None
            fake_vcs.export.return_value = SAMPLE_DIFF_BYTES

        fake_vcs.update.side_effect = fake_update

        return fake_vcs

    def post_sample_patch(self, diffID=None, revisionID=None, post_data=None):
        data = {
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': diffID or insecure_random.randint(0, 100000),
            'phabricator.revisionID': revisionID or insecure_random.randint(0, 1000),
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _VALID_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>',
        }
        data.update(post_data or {})
        return self.client.post(self.path, data=data)

    @patch('changes.models.repository.Repository.get_vcs')
    def test_valid_params(self, get_vcs):
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo()

        project = self.create_project(repository=repo)
        plan = self.create_plan(project)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )
        db.session.commit()

        resp = self.post_sample_patch(diffID='1324134', revisionID='1234')
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id']

        job = Job.query.filter(
            Job.build_id == data[0]['id']
        ).first()
        build = job.build
        source = build.source

        assert build.author.name == 'David Cramer'
        assert build.author.email == 'dcramer@example.com'
        assert build.message == 'Hello world!'
        assert build.label == 'Foo Bar'
        assert build.target == 'D1234'
        assert build.selective_testing_policy is SelectiveTestingPolicy.disabled

        assert job.project == project
        assert job.label == plan.label

        assert source.repository_id == project.repository_id
        # TODO(dcramer): re-enable test when find_green_parent_sha is turned
        # assert source.revision_sha == 'b' * 40
        assert source.revision_sha == _VALID_SHA
        assert source.data == {
            'phabricator.buildTargetPHID': None,
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
        }

        patch = source.patch
        assert patch.diff == SAMPLE_DIFF
        # we still reference the precise parent revision for patches
        assert patch.parent_revision_sha == _VALID_SHA

        jobplans = list(JobPlan.query.filter(
            JobPlan.build_id == build.id,
        ))

        assert len(jobplans) == 1

        assert jobplans[0].job_id == job.id
        assert jobplans[0].plan_id == plan.id
        assert jobplans[0].project_id == project.id

    @patch('changes.lib.project_lib.contains_active_autogenerated_plan')
    @patch('changes.models.repository.Repository.get_vcs')
    def test_selective_testing(self, get_vcs, contains_active_autogenerated_plan):
        repo = self.create_repo()
        project = self.create_project(repository=repo)
        plan = self.create_plan(project)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )
        db.session.commit()
        for (is_autogenerated, selective_testing_request, expected_policy) in [
            (True, 'true', SelectiveTestingPolicy.enabled),
            (True, None, SelectiveTestingPolicy.enabled),
            (True, 'false', SelectiveTestingPolicy.disabled),
            (False, 'true', SelectiveTestingPolicy.disabled),
            (False, 'false', SelectiveTestingPolicy.disabled),
        ]:
            contains_active_autogenerated_plan.return_value = is_autogenerated
            get_vcs.return_value = self.get_fake_vcs()
            data = {}
            if selective_testing_request is not None:
                data['selective_testing'] = selective_testing_request
            resp = self.post_sample_patch(post_data=data)
            assert resp.status_code == 200
            data = self.unserialize(resp)
            assert len(data) == 1
            assert data[0]['id']
            build = Build.query.get(data[0]['id'])

            assert build.selective_testing_policy is expected_policy

    def test_with_patch_without_diffs_enabled(self):
        repo = self.create_repo()

        project = self.create_project(repository=repo)
        self.create_plan(project)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        po = ProjectOption(
            project=project,
            name='phabricator.diff-trigger',
            value='0',
        )
        db.session.add(po)
        db.session.commit()

        # Default to not creating a build (for tools)
        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 0

    @patch('changes.models.repository.Repository.get_vcs')
    def test_when_not_in_whitelist(self, get_vcs):
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo()

        project = self.create_project(repository=repo)
        self.create_plan(project)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        po = ProjectOption(
            project=project,
            name='build.file-whitelist',
            value='nonexisting_directory',
        )
        db.session.add(po)
        db.session.commit()

        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 0

    @patch('changes.models.repository.Repository.get_vcs')
    def test_when_in_whitelist(self, get_vcs):
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo()

        project = self.create_project(repository=repo)
        self.create_plan(project)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        po = ProjectOption(
            project=project,
            name='build.file-whitelist',
            value='ci/*',
        )
        db.session.add(po)
        db.session.commit()

        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 1

    @patch('changes.models.repository.Repository.get_vcs')
    def test_when_in_blacklist(self, get_vcs):
        fake_vcs = self.get_fake_vcs()
        fake_vcs.read_file.side_effect = None
        fake_vcs.read_file.return_value = yaml.safe_dump({
            'build.file-blacklist': ['ci/*'],
        })
        get_vcs.return_value = fake_vcs
        repo = self.create_repo()
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        project = self.create_project(repository=repo)
        self.create_plan(project)

        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 0

    @patch('changes.models.repository.Repository.get_vcs')
    def test_when_not_all_in_blacklist(self, get_vcs):
        fake_vcs = self.get_fake_vcs()
        fake_vcs.read_file.side_effect = None
        fake_vcs.read_file.return_value = yaml.safe_dump({
            'build.file-blacklist': ['ci/not-real'],
        })
        get_vcs.return_value = fake_vcs
        repo = self.create_repo()
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        project = self.create_project(repository=repo)
        self.create_plan(project)

        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 1

    @patch('changes.models.repository.Repository.get_vcs')
    def test_invalid_config(self, get_vcs):
        fake_vcs = self.get_fake_vcs()
        fake_vcs.read_file.side_effect = None
        fake_vcs.read_file.return_value = yaml.safe_dump({
            'build.file-blacklist': ['ci/*'],
        }) + '}'
        get_vcs.return_value = fake_vcs
        repo = self.create_repo()
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        project = self.create_project(repository=repo)
        self.create_plan(project)

        resp = self.post_sample_patch()
        assert resp.status_code == 200, resp.data
        data = self.unserialize(resp)
        assert len(data) == 1

    @patch('changes.models.repository.Repository.get_vcs')
    def test_collection_id(self, get_vcs):
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo_with_projects(count=3)
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )
        db.session.commit()
        resp = self.post_sample_patch()
        builds = self.assert_resp_has_multiple_items(resp, count=3)
        self.assert_collection_id_across_builds(builds)

    @patch('changes.models.repository.Repository.get_vcs')
    @patch('changes.api.phabricator_notify_diff.post_comment')
    def test_diff_comment(self, mock_post_comment, get_vcs):
        """Test diff commenting on a revision we can't identify on a legit project"""
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo()
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )
        project = self.create_project(repository=repo)
        self.create_plan(project)

        # Test that valid sha doesn't kick off anything
        resp = self.client.post(self.path, data={
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _VALID_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>'
        })
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert mock_post_comment.call_count == 0

        # Test that invalid sha kicks off a mock comment
        resp = self.client.post(self.path, data={
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _BOGUS_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>'
        })
        assert resp.status_code == 400
        data = self.unserialize(resp)
        assert "Unable to find base revision %s" % _BOGUS_SHA in data['error']
        mock_post_comment.assert_called_once_with('D1234', ANY)
        assert "An error occurred somewhere between Phabricator and Changes" in mock_post_comment.call_args[0][1]
        assert "Unable to find base revision %s" % _BOGUS_SHA in mock_post_comment.call_args[0][1]

    @patch('changes.models.repository.Repository.get_vcs')
    @patch('changes.api.phabricator_notify_diff.post_comment')
    def test_diff_comment_bad_project(self, mock_post_comment, get_vcs):
        """Make sure we don't comment on diffs for repos without projects/plans"""
        get_vcs.return_value = self.get_fake_vcs()
        repo = self.create_repo()
        self.create_option(
            item_id=repo.id,
            name='phabricator.callsign',
            value='FOO',
        )

        # There's no project for this repo. Don't post back comments.
        resp = self.client.post(self.path, data={
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _BOGUS_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>'
        })
        assert resp.status_code == 200
        assert self.unserialize(resp) == []
        assert mock_post_comment.call_count == 0

        # Now with a project, but no build plans. Don't post back comments
        project = self.create_project(repository=repo)
        resp = self.client.post(self.path, data={
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _BOGUS_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>'
        })
        assert resp.status_code == 200
        assert self.unserialize(resp) == []
        assert mock_post_comment.call_count == 0

        # Now with a project and a plan, kick off comment
        self.create_plan(project)
        resp = self.client.post(self.path, data={
            'phabricator.callsign': 'FOO',
            'phabricator.diffID': '1324134',
            'phabricator.revisionID': '1234',
            'phabricator.revisionURL': 'https://phabricator.example.com/D1234',
            'patch': (StringIO(SAMPLE_DIFF_BYTES), 'foo.diff'),
            'sha': _BOGUS_SHA,
            'label': 'Foo Bar',
            'message': 'Hello world!',
            'author': 'David Cramer <dcramer@example.com>'
        })
        assert resp.status_code == 400
        data = self.unserialize(resp)
        assert "Unable to find base revision %s" % _BOGUS_SHA in data['error']
        mock_post_comment.assert_called_once_with('D1234', ANY)
        assert "An error occurred somewhere between Phabricator and Changes" in mock_post_comment.call_args[0][1]
        assert "Unable to find base revision %s" % _BOGUS_SHA in mock_post_comment.call_args[0][1]


text:
redirect: /blog/protobuf-apiv2
---


text:
"""
Process an image file using tesseract.
"""
import os

from .utils import ShellParser

class Parser(ShellParser):
    """Extract text from various image file formats using tesseract-ocr"""

    def extract(self, filename, **kwargs):

        # if language given as argument, specify language for tesseract to use
        if 'language' in kwargs:
            lang = '-l %s' % kwargs['language']
        else:
            lang = ''

        # Tesseract can't output to console directly so you must first create
        # a dummy file to write to, read, and then delete
        devnull = os.devnull
        command = (
            'tesseract "%(filename)s" %(lang)s {0} > %(devnull)s && '
            'cat {0}.txt && '
            'rm -f {0} {0}.txt'
        )
        temp_filename = self.temp_filename()
        stdout, _ = self.run(command.format(temp_filename) % locals())
        return stdout


text:
namespace VZF.Types.Models
{
    using System;
    using System.Collections.Generic;

    public partial class yaf_UserForum
    {
        public int UserID { get; set; }
        public int ForumID { get; set; }
        public int AccessMaskID { get; set; }
        public System.DateTime Invited { get; set; }
        public bool Accepted { get; set; }

        public virtual yaf_AccessMask yaf_AccessMask { get; set; }
        public virtual yaf_Forum yaf_Forum { get; set; }
        public virtual yaf_User yaf_User { get; set; }
    }
}


text:
package org.spongepowered.mod.network;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraftforge.fml.common.network.FMLIndexedMessageToMessageCodec;
import org.spongepowered.api.network.Message;
import org.spongepowered.common.network.SpongeNetworkManager;

public class SpongeMessageCodec extends FMLIndexedMessageToMessageCodec<Message> {

    @Override
    public void encodeInto(ChannelHandlerContext ctx, Message msg, ByteBuf target) throws Exception {
        msg.writeTo(SpongeNetworkManager.toChannelBuf(target));
    }

    @Override
    public void decodeInto(ChannelHandlerContext ctx, ByteBuf source, Message msg) {
        msg.readFrom(SpongeNetworkManager.toChannelBuf(source));
    }

}


text:
package com.getbase.android.db.fluentsqlite;

import static com.getbase.android.db.fluentsqlite.Expressions.arg;
import static com.getbase.android.db.fluentsqlite.Expressions.column;
import static com.getbase.android.db.fluentsqlite.Expressions.literal;
import static com.getbase.android.db.fluentsqlite.Query.select;
import static com.google.common.truth.Truth.assertThat;

import com.getbase.android.db.fluentsqlite.Expressions.Expression;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.ParameterizedRobolectricTestRunner;
import org.robolectric.ParameterizedRobolectricTestRunner.Parameters;
import org.robolectric.annotation.Config;

import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

@RunWith(ParameterizedRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ExpressionsArgsCountTest {
  private int mActual;
  private int mExpected;

  public ExpressionsArgsCountTest(int actual, int expected) {
    mActual = actual;
    mExpected = expected;
  }

  private static final Map<Expression, Integer> TEST_CASES = ImmutableMap.<Expression, Integer>builder()
      .put(literal(42), 0)
      .put(arg(), 1)
      .put(arg().eq().arg(), 2)
      .put(arg().eq(arg()), 2)
      .put(column("id").in(select().column("id").from("table_a").where(column("priority").eq().arg(), "1").build()), 1)
      .put(column("id").in(select().column("id").from("table_a").where("priority=?", "1").build()), 1)
      .build();

  @Parameters
  public static Collection<Object[]> data() {
    return FluentIterable
        .from(TEST_CASES.entrySet())
        .transform(new Function<Entry<Expression, Integer>, Object[]>() {
          @Override
          public Object[] apply(Entry<Expression, Integer> input) {
            return new Object[] {
                input.getKey().getArgsCount(),
                input.getValue()
            };
          }
        })
        .toList();
  }

  @Test
  public void shouldCountExpressionArgsSql() throws Exception {
    assertThat(mActual).isEqualTo(mExpected);
  }
}


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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

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.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

=head1 NAME

Bio::EnsEMBL::VCloud::VApp

=head1 SYNOPSIS

my $vapp = Bio::EnsEMBL::VCloud::VApp->new(-NAME     => 'vapp_name',
                                           -DIRECTOR => Bio::EnsEMBL::VCloud::Director->new(-USER => 'admin', -PASS => 'xxxxx');

=head1 DESCRIPTION

A module to implement the base class representing a generic a virtual
application (vApp) in vCloud Director.
It does provide some convenience methods, e.g. power_on|off, but it's
certainly not exhaustive at this stage, i.e. does not support the full
range of operation one can do with vApp using the vCloud REST API.
=head1 METHODS

=cut

package Bio::EnsEMBL::VCloud::VApp;

use strict;
use warnings;

use Data::Dumper;
use XML::Writer;

use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw);
use Bio::EnsEMBL::VCloud::VirtualMachine;

=head2 new

  Arg [-NAME]     : String; The name of the vApp.
  Arg [-DIRECTOR] : Bio::EnsEMBL::VCloud::Director instance;
                    The vCloud Director instance where the vApp lives.
  Example         :
  Description     : instantiate an object which represents a vApp on
                    a vCloud Director instance.
  Returntype      : Bio::EnsEMBL::Embassy::VCloud::VApp
  Exceptions      : none
  Caller          : general
  Status          : stable

=cut

sub new {
  my $caller = shift;
  my $class = ref($caller) || $caller;

  my ($name, $director) =
    rearrange( [ 'NAME', 'DIRECTOR' ], @_ );

  defined $name or throw "Undefined vApp name (required)";
  defined $director or throw "Undefined vCloud Director instance (required)";

  my $self =
    bless { _data => $director->{api}->vapp_get($director->_vapp_url($name)) }, $class;
  # my $self =
  #   $class->SUPER::new($director->{api}, $director->_vapp_url($name));

  $self->{_director} = $director;

  return $self;
}

=head2 name

  Arg []     : none
  Example    : print $vapp->name, "\n";
  Description: Returns the name of the vApp.
  Returntype : String; the name of the vApp.
  Exceptions : none
  Caller     : general
  Status     : Stable

=cut

sub name {
  return $_[0]->{_data}{name};
}

=head2 href

  Arg []     : none
  Example    : print $vapp->href, "\n";
  Description: returns the vApp HREF .
  Returntype : String; the vApp HREF.
  Exceptions : none
  Caller     : general
  Status     : stable

=cut

sub href {
  return $_[0]->{_data}{href};
}

=head2 available_actions

  Arg []     : none
  Example    : print keys $vapp->available_actions(), "\n";
  Description: returns the name of the available actions which can be
               requested for a vApp associated to their corresponding
               HREFs.
  Returntype : Hash/Hashref; each key represents an action and each value
               is the corresponding href for said action to be executed.
  Exceptions : none
  Caller     : general
  Status     : stable

=cut

sub available_actions {
  my $self = shift;

  my %actions;
  for my $action ( @{$self->{_data}{Link} } ) {
    next if $action->{rel} =~ /^(up|down|edit|controlAccess)$/;
    $actions{$action->{rel}} = $action->{href};
  }
  return wantarray ? %actions : \%actions;
}

=head2 power_on

  Arg []     : none
  Example    : print $vapp->power_on();
  Description: powers on the vApp, if not already on.
  Returntype : none
  Exceptions : if the vApp cannot be powered on, since it's already
               on or some other error occurs.
  Caller     : general
  Status     : stable

=cut

sub power_on {
  my $self = shift;
  my $director = $self->{_director};

  my %actions = $self->available_actions();
  throw sprintf "Error: Unable to Power On the vApp %s.\nPerhapps the vApp is already powered on?", $self->name
    unless defined $actions{'power:powerOn'};

  my $ret = $director->{api}->post($actions{'power:powerOn'});

  throw sprintf "VApp power on request failed (%d)", $ret->[1]
    unless $ret->[1] == 202;
  $director->_monitor_task($ret->[2]);

  return;
}

=head2 power_off

  Arg []     : none
  Example    : print $vapp->power_off();
  Description: powers off the vApp, if not already off.
  Returntype : none
  Exceptions : if the vApp cannot be powered off, since it's already
               off or some other error occurs.
  Caller     : general
  Status     : stable

=cut

sub power_off {
  my $self = shift;
  my $director = $self->{_director};

  warn sprintf "Going to UNDEPLOY vApp %s.", $self->name;

  my %actions = $self->available_actions();
  warn sprintf "Error: Unable to find link to undeploy the vApp %s. Perhapps the vApp is already off?!", $self->name
    and return unless defined $actions{'undeploy'};

  my $params;
  $params = <<'END';
<UndeployVAppParams
   xmlns="http://www.vmware.com/vcloud/v1.5">
   <UndeployPowerAction>powerOff</UndeployPowerAction>
</UndeployVAppParams>
END

  my $ret = $director->{api}->post($actions{'undeploy'},
				   'application/vnd.vmware.vcloud.undeployVAppParams+xml',
				   $params);

  throw sprintf "VApp power off request failed (%d)", $ret->[1]
    unless $ret->[1] == 202;
  $director->_monitor_task($ret->[2]);

  return;
}

=head2 get_vms

  Arg []     : none
  Example    : print map { $_->href } $vapp->get_vms();
  Description: returns the list of virtual machines the vApp is composed of.
  Returntype : Array/Arrayref of Bio::EnsEMBL::VCloud::VirtualMachine instances.
  Exceptions : if cannot retrieve the list of vApp from vCloud.
  Caller     : general
  Status     : stable

=cut

sub get_vms {
  my $self = shift;
  my $director = $self->{_director};

  my @vms;
  my $data = $self->{_data}; # $self->dumper;
  exists $data->{Children}[0]{Vm} or
    throw sprintf "vApp %s: cannot find list of VMs", $self->name;

  map { push @vms, $director->get_vm($data->{Children}[0]{Vm}{$_}{href}) }
    keys %{$data->{Children}[0]{Vm}};

  return wantarray ? @vms : $vms[0];
}

=head2 snapshot

  Arg [1]    : String; the snapshot name.
  Example    : $vapp->snapshot('test_snapshot');
  Description: Implements the createSnapshot operation of the vCloud REST API.
               See http://pubs.vmware.com/vcd-51/index.jsp#com.vmware.vcloud.api.doc_51/GUID-C557E0FB-0364-47B8-A146-C70C1CAA882B.html
  Returntype : none
  Exceptions : if operation is unavailable or some error occur during the
               creation of the snapshot.
  Caller     : general
  Status     : stable

=cut

sub snapshot {
  my ($self, $name) = @_;
  my $director = $self->{_director};

  my $xml =
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" .
    "<CreateSnapshotParams " .
      "xmlns=\"http://www.vmware.com/vcloud/v1.5\" " .
      "name=\"$name\">" .
      "<Description>Demo snapshot</Description>" .
    "</CreateSnapshotParams>";

  my %actions = $self->available_actions();
  throw "Error: Unable to find vApp createSnapshot vApp operation"
    unless defined $actions{'snapshot:create'};

  my $ret = $director->{api}->post($actions{'snapshot:create'},
				   'application/vnd.vmware.vcloud.createSnapshotParams+xml',
				   $xml);

  throw sprintf "VApp createSnapshot request failed (%d)", $ret->[1]
    unless $ret->[1] == 202;
  $director->_monitor_task($ret->[2]);

  return;
}

1;


text:
import unittest
from typing import Any, Dict
from unittest import mock

from google.cloud.tasks_v2.types import Queue, Task

from airflow.providers.google.cloud.hooks.tasks import CloudTasksHook
from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id

API_RESPONSE = {}  # type: Dict[Any, Any]
PROJECT_ID = "test-project"
LOCATION = "asia-east2"
FULL_LOCATION_PATH = "projects/test-project/locations/asia-east2"
QUEUE_ID = "test-queue"
FULL_QUEUE_PATH = "projects/test-project/locations/asia-east2/queues/test-queue"
TASK_NAME = "test-task"
FULL_TASK_PATH = "projects/test-project/locations/asia-east2/queues/test-queue/tasks/test-task"

class TestCloudTasksHook(unittest.TestCase):
    def setUp(self):
        with mock.patch(
            "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
            new=mock_base_gcp_hook_no_default_project_id,
        ):
            self.hook = CloudTasksHook(gcp_conn_id="test")

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.client_info",
        new_callable=mock.PropertyMock,
    )
    @mock.patch("airflow.providers.google.cloud.hooks.tasks.CloudTasksHook._get_credentials")
    @mock.patch("airflow.providers.google.cloud.hooks.tasks.CloudTasksClient")
    def test_cloud_tasks_client_creation(self, mock_client, mock_get_creds, mock_client_info):
        result = self.hook.get_conn()
        mock_client.assert_called_once_with(
            credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value
        )
        assert mock_client.return_value == result
        assert self.hook._client == result

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.create_queue.return_value": API_RESPONSE},  # type: ignore
    )
    def test_create_queue(self, get_conn):
        result = self.hook.create_queue(
            location=LOCATION,
            task_queue=Queue(),
            queue_name=QUEUE_ID,
            project_id=PROJECT_ID,
        )

        assert result is API_RESPONSE

        get_conn.return_value.create_queue.assert_called_once_with(
            request=dict(parent=FULL_LOCATION_PATH, queue=Queue(name=FULL_QUEUE_PATH)),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.update_queue.return_value": API_RESPONSE},  # type: ignore
    )
    def test_update_queue(self, get_conn):
        result = self.hook.update_queue(
            task_queue=Queue(state=3),
            location=LOCATION,
            queue_name=QUEUE_ID,
            project_id=PROJECT_ID,
        )

        assert result is API_RESPONSE

        get_conn.return_value.update_queue.assert_called_once_with(
            request=dict(queue=Queue(name=FULL_QUEUE_PATH, state=3), update_mask=None),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.get_queue.return_value": API_RESPONSE},  # type: ignore
    )
    def test_get_queue(self, get_conn):
        result = self.hook.get_queue(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result is API_RESPONSE

        get_conn.return_value.get_queue.assert_called_once_with(
            request=dict(name=FULL_QUEUE_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.list_queues.return_value": [Queue(name=FULL_QUEUE_PATH)]},  # type: ignore
    )
    def test_list_queues(self, get_conn):
        result = self.hook.list_queues(location=LOCATION, project_id=PROJECT_ID)

        assert result == [Queue(name=FULL_QUEUE_PATH)]

        get_conn.return_value.list_queues.assert_called_once_with(
            request=dict(parent=FULL_LOCATION_PATH, filter=None, page_size=None),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.delete_queue.return_value": None},  # type: ignore
    )
    def test_delete_queue(self, get_conn):
        result = self.hook.delete_queue(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result is None

        get_conn.return_value.delete_queue.assert_called_once_with(
            request=dict(name=FULL_QUEUE_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.purge_queue.return_value": Queue(name=FULL_QUEUE_PATH)},  # type: ignore
    )
    def test_purge_queue(self, get_conn):
        result = self.hook.purge_queue(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result == Queue(name=FULL_QUEUE_PATH)

        get_conn.return_value.purge_queue.assert_called_once_with(
            request=dict(name=FULL_QUEUE_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.pause_queue.return_value": Queue(name=FULL_QUEUE_PATH)},  # type: ignore
    )
    def test_pause_queue(self, get_conn):
        result = self.hook.pause_queue(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result == Queue(name=FULL_QUEUE_PATH)

        get_conn.return_value.pause_queue.assert_called_once_with(
            request=dict(name=FULL_QUEUE_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.resume_queue.return_value": Queue(name=FULL_QUEUE_PATH)},  # type: ignore
    )
    def test_resume_queue(self, get_conn):
        result = self.hook.resume_queue(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result == Queue(name=FULL_QUEUE_PATH)

        get_conn.return_value.resume_queue.assert_called_once_with(
            request=dict(name=FULL_QUEUE_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.create_task.return_value": Task(name=FULL_TASK_PATH)},  # type: ignore
    )
    def test_create_task(self, get_conn):
        result = self.hook.create_task(
            location=LOCATION,
            queue_name=QUEUE_ID,
            task=Task(),
            project_id=PROJECT_ID,
            task_name=TASK_NAME,
        )

        assert result == Task(name=FULL_TASK_PATH)

        get_conn.return_value.create_task.assert_called_once_with(
            request=dict(parent=FULL_QUEUE_PATH, task=Task(name=FULL_TASK_PATH), response_view=None),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.get_task.return_value": Task(name=FULL_TASK_PATH)},  # type: ignore
    )
    def test_get_task(self, get_conn):
        result = self.hook.get_task(
            location=LOCATION,
            queue_name=QUEUE_ID,
            task_name=TASK_NAME,
            project_id=PROJECT_ID,
        )

        assert result == Task(name=FULL_TASK_PATH)

        get_conn.return_value.get_task.assert_called_once_with(
            request=dict(name=FULL_TASK_PATH, response_view=None),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.list_tasks.return_value": [Task(name=FULL_TASK_PATH)]},  # type: ignore
    )
    def test_list_tasks(self, get_conn):
        result = self.hook.list_tasks(location=LOCATION, queue_name=QUEUE_ID, project_id=PROJECT_ID)

        assert result == [Task(name=FULL_TASK_PATH)]

        get_conn.return_value.list_tasks.assert_called_once_with(
            request=dict(parent=FULL_QUEUE_PATH, response_view=None, page_size=None),
            retry=None,
            timeout=None,
            metadata=(),
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.delete_task.return_value": None},  # type: ignore
    )
    def test_delete_task(self, get_conn):
        result = self.hook.delete_task(
            location=LOCATION,
            queue_name=QUEUE_ID,
            task_name=TASK_NAME,
            project_id=PROJECT_ID,
        )

        assert result is None

        get_conn.return_value.delete_task.assert_called_once_with(
            request=dict(name=FULL_TASK_PATH), retry=None, timeout=None, metadata=()
        )

    @mock.patch(
        "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.get_conn",
        **{"return_value.run_task.return_value": Task(name=FULL_TASK_PATH)},  # type: ignore
    )
    def test_run_task(self, get_conn):
        result = self.hook.run_task(
            location=LOCATION,
            queue_name=QUEUE_ID,
            task_name=TASK_NAME,
            project_id=PROJECT_ID,
        )

        assert result == Task(name=FULL_TASK_PATH)

        get_conn.return_value.run_task.assert_called_once_with(
            request=dict(name=FULL_TASK_PATH, response_view=None),
            retry=None,
            timeout=None,
            metadata=(),
        )


text:
package com.bazaarvoice.commons.data.model.json;

import org.json.JSONArray;

import javax.annotation.Nullable;

public class GenericJSONArrayList extends AbstractJSONArrayList<Object> {
    public GenericJSONArrayList(@Nullable JSONArray jsonArray) {
        super(jsonArray);
    }

    @Nullable
    @Override
    protected Object getFromJSONArray(JSONArray jsonArray, int index) {
        return jsonArray.opt(index);
    }
}