text:
package gov.va.escreening.service;

import com.google.common.collect.Maps;
import gov.va.escreening.domain.MeasureTypeEnum;
import gov.va.escreening.entity.Measure;
import gov.va.escreening.entity.MeasureAnswer;
import gov.va.escreening.entity.Survey;
import gov.va.escreening.entity.SurveyMeasureResponse;
import gov.va.escreening.entity.SurveyPage;
import gov.va.escreening.repository.SurveyMeasureResponseRepository;
import gov.va.escreening.repository.VeteranAssessmentMeasureVisibilityRepository;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.text.WordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.ListMultimap;

@Transactional
@Service
public class SurveyMeasureResponseServiceImpl implements SurveyMeasureResponseService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SurveyMeasureResponseRepository surveyMeasureResponseRepository;

    @Autowired
    private VeteranAssessmentMeasureVisibilityRepository visibilityRepo;

    @Transactional(readOnly = true)
    @Override
    public Hashtable<Integer, List<SurveyMeasureResponse>> findForVeteranAssessmentId(int veteranAssessmentId, Map<Integer, Integer> tableQCntrMap) {

        List<SurveyMeasureResponse> resultList = surveyMeasureResponseRepository
                .findForVeteranAssessmentId(veteranAssessmentId);

        Hashtable<Integer, List<SurveyMeasureResponse>> surveyMeasureResponseMap = new Hashtable<Integer, List<SurveyMeasureResponse>>();

        for (SurveyMeasureResponse surveyMeasureResponse : resultList) {

            if (surveyMeasureResponseMap.containsKey(surveyMeasureResponse.getMeasureAnswer().getMeasureAnswerId())) {
                List<SurveyMeasureResponse> responses = surveyMeasureResponseMap.remove(surveyMeasureResponse
                        .getMeasureAnswer().getMeasureAnswerId());
                responses.add(surveyMeasureResponse);
                surveyMeasureResponseMap.put(surveyMeasureResponse.getMeasureAnswer().getMeasureAnswerId(), responses);
            } else {
                List<SurveyMeasureResponse> responses = new ArrayList<SurveyMeasureResponse>();
                responses.add(surveyMeasureResponse);
                surveyMeasureResponseMap.put(surveyMeasureResponse.getMeasureAnswer().getMeasureAnswerId(), responses);
            }
        }
        fillTableQuestionMap(surveyMeasureResponseMap, tableQCntrMap);

        return surveyMeasureResponseMap;
    }

    private void fillTableQuestionMap(Hashtable<Integer, List<SurveyMeasureResponse>> surveyMeasureResponseMap, Map<Integer, Integer> m) {
        for (List<SurveyMeasureResponse> smrLst : surveyMeasureResponseMap.values()) {
            for (SurveyMeasureResponse smr : smrLst) {
                if (smr.getTabularRow() != null) {
                    Integer mId = smr.getMeasure().getParent().getMeasureId();
                    Integer prevTabRowCtr = m.get(mId) == null ? 0 : m.get(mId);
                    m.put(mId, Math.max(prevTabRowCtr, smr.getTabularRow()));
                }
            }
        }
    }

    @Override
    @Transactional
    public String generateQuestionsAndAnswers(Survey survey, Integer veteranAssessmentId) {

        StringBuilder sb = new StringBuilder();
        sb.append(survey.getName() + "\n");

        ListMultimap<Integer, SurveyMeasureResponse> resp = surveyMeasureResponseRepository
                .getForVeteranAssessmentAndSurvey(
                        veteranAssessmentId, survey.getSurveyId());

        for (SurveyPage page : survey.getSurveyPageList()) {
            Map<Integer, Boolean> visibilityMap = visibilityRepo.getVisibilityMapForSurveyPage(veteranAssessmentId, page.getSurveyPageId());

            int index = 1;
            for (gov.va.escreening.entity.Measure m : page.getMeasures()) {

                if (m == null) continue;

                if (visibilityMap.containsKey(m.getMeasureId()) && !visibilityMap.get(m.getMeasureId())) {
                    continue;
                }

                String indent = "";
                if (visibilityMap.containsKey(m.getMeasureId())) {
                    indent = "  ";
                }
                appendMeasure(indent, sb, resp, m, "");
                if (m.getChildren() != null) {
                    //int childIndex = 1;
                    for (Measure measure : m.getChildren()) {
                        if (visibilityMap.containsKey(m.getMeasureId()) && !visibilityMap.get(m.getMeasureId())) {
                            continue;
                        }
                        appendMeasure("  ", sb, resp, measure, "  ");
                    }
                }
            }
        }

        return wrapLines(sb.toString()) + "\n";
    }

    private void appendMeasure(String indexStr, StringBuilder sb, ListMultimap<Integer, SurveyMeasureResponse> resp,
                               gov.va.escreening.entity.Measure m, String indentDelta) {
        String indent = "  " + indentDelta;
        String ques = m.getVistaText() == null ? m.getMeasureText() : m.getVistaText();
        ques = ques.trim().isEmpty() ? indent : indent + indexStr + ques;

        String answer = null;
        if (m.getMeasureType().getMeasureTypeId() == MeasureTypeEnum.FREETEXT.getMeasureTypeId()) {
            MeasureAnswer ma = m.getMeasureAnswerList().get(0);
            if (resp.containsKey(ma.getMeasureAnswerId())) {
                SurveyMeasureResponse mar = resp.get(ma.getMeasureAnswerId()).get(0);
                answer = mar.getTextValue();
                if (answer == null) {
                    Long l = mar.getNumberValue();
                    if (l != null)
                        answer = l.toString();
                }

            }
        } else if (m.getMeasureType().getMeasureTypeId() == MeasureTypeEnum.SELECTONE.getMeasureTypeId() ||
                m.getMeasureType().getMeasureTypeId() == MeasureTypeEnum.SELECTONEMATRIX.getMeasureTypeId()) {
            for (MeasureAnswer ma : m.getMeasureAnswerList()) {
                if (resp.containsKey(ma.getMeasureAnswerId())) {
                    for (SurveyMeasureResponse smr : resp.get(ma.getMeasureAnswerId())) {
                        if (smr.getBooleanValue() != null && smr.getBooleanValue()) {
                            answer = ma.getVistaText() == null ? ma.getAnswerText() : ma.getVistaText();
                            break;
                        }
                    }
                }
            }
        } else if (m.getMeasureType().getMeasureTypeId() == MeasureTypeEnum.SELECTMULTI.getMeasureTypeId() ||
                m.getMeasureType().getMeasureTypeId() == MeasureTypeEnum.SELECTMULTIMATRIX.getMeasureTypeId()) {
            StringBuilder answerStr = new StringBuilder();
            for (MeasureAnswer ma : m.getMeasureAnswerList()) {
                if (resp.containsKey(ma.getMeasureAnswerId())) {
                    SurveyMeasureResponse smr = resp.get(ma.getMeasureAnswerId()).get(0);
                    if (smr.getBooleanValue() != null && smr.getBooleanValue()) {
                        answerStr.append("\n    " + indent).append(ma.getVistaText() == null ? ma.getAnswerText() : ma.getVistaText());
                    }
                }
            }
            answer = answerStr.toString();
        }

        sb.append(ques);
        if (answer == null) {
            answer = "No Answer";
        }
        sb.append(" ").append(answer);
        sb.append("\n\n");
    }

    /**
     * Wraps given text to 80 columns including a 4 space indent on everything.
     *
     * @param text
     * @return
     */
    private String wrapLines(String text) {
        String newLine = "\n    ";
        Pattern prefixSpace = Pattern.compile("^(\\s+).*");
        Pattern newLineReplace = Pattern.compile("\n");

        StringBuilder wrappedText = new StringBuilder();
        String[] lines = text.split("\n");
        for (String line : lines) {
            logger.trace("wrapping line:\n{}", line);
            Matcher m = prefixSpace.matcher(line);
            String indent = m.find() ? m.group(1) : "";

            String wrappedLine = WordUtils.wrap(line, 70, "\n", true);

            //wrap method removes space if it wraps but doen't if no wrap was needed.
            if (!indent.isEmpty())
                wrappedLine = wrappedLine.replaceFirst("^\\s+", "");

            String margin = newLine + indent;
            logger.trace("margin size: {}", margin.length());

            logger.trace("wrapped by itself:\n{}", wrappedLine);

            //add margin to wrapped lines
            wrappedLine = newLineReplace.matcher(wrappedLine).replaceAll(margin);

            logger.trace("wrapped with replaced for each line margin: \n{}", wrappedLine);

            wrappedText.append(margin).append(wrappedLine);
        }

        String wrapped = wrappedText.toString();
        //logger.trace("wrapped text:\n{}", wrapped);
        return wrapped;
    }
}


text:
(function() {
	var regMetaChars = /[-\\^$*+?.()|[\]{}]/g;
	String.prototype.replaceAll = function(needle, replacement) {
		return this.replace(new RegExp(needle.replace(regMetaChars, '\\$&'),
				'g'), replacement);
	};

	String.prototype.format = function() {
		var args = arguments;
		return this.replace(/{(\d+)}/g, function(match, number) {
			return typeof args[number] !== 'undefined' ? args[number] : match;
		});
	};
}());

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const ruleMessages = require('../../utils/ruleMessages');
const selectorListCommaWhitespaceChecker = require('../selectorListCommaWhitespaceChecker');
const validateOptions = require('../../utils/validateOptions');
const whitespaceChecker = require('../../utils/whitespaceChecker');

const ruleName = 'selector-list-comma-space-after';

const messages = ruleMessages(ruleName, {
	expectedAfter: () => 'Expected single space after ","',
	rejectedAfter: () => 'Unexpected whitespace after ","',
	expectedAfterSingleLine: () => 'Expected single space after "," in a single-line list',
	rejectedAfterSingleLine: () => 'Unexpected whitespace after "," in a single-line list',
});

function rule(expectation, options, context) {
	const checker = whitespaceChecker('space', expectation, messages);

	return (root, result) => {
		const validOptions = validateOptions(result, ruleName, {
			actual: expectation,
			possible: ['always', 'never', 'always-single-line', 'never-single-line'],
		});

		if (!validOptions) {
			return;
		}

		let fixData;

		selectorListCommaWhitespaceChecker({
			root,
			result,
			locationChecker: checker.after,
			checkedRuleName: ruleName,
			fix: context.fix
				? (ruleNode, index) => {
						fixData = fixData || new Map();
						const commaIndices = fixData.get(ruleNode) || [];

						commaIndices.push(index);
						fixData.set(ruleNode, commaIndices);

						return true;
				  }
				: null,
		});

		if (fixData) {
			fixData.forEach((commaIndices, ruleNode) => {
				let selector = ruleNode.raws.selector ? ruleNode.raws.selector.raw : ruleNode.selector;

				commaIndices
					.sort((a, b) => b - a)
					.forEach((index) => {
						const beforeSelector = selector.slice(0, index + 1);
						let afterSelector = selector.slice(index + 1);

						if (expectation.startsWith('always')) {
							afterSelector = afterSelector.replace(/^\s*/, ' ');
						} else if (expectation.startsWith('never')) {
							afterSelector = afterSelector.replace(/^\s*/, '');
						}

						selector = beforeSelector + afterSelector;
					});

				if (ruleNode.raws.selector) {
					ruleNode.raws.selector.raw = selector;
				} else {
					ruleNode.selector = selector;
				}
			});
		}
	};
}

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;


text:
package proto

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
	// Verify that runtime/protoimpl is sufficiently up-to-date.
	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)

// Request to get all data in bio page.
type GetBioPageDataRequest struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	// The dcid of the entity
	Dcid string `protobuf:"bytes,1,opt,name=dcid,proto3" json:"dcid,omitempty"`
}

func (x *GetBioPageDataRequest) Reset() {
	*x = GetBioPageDataRequest{}
	if protoimpl.UnsafeEnabled {
		mi := &file_internal_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *GetBioPageDataRequest) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*GetBioPageDataRequest) ProtoMessage() {}

func (x *GetBioPageDataRequest) ProtoReflect() protoreflect.Message {
	mi := &file_internal_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use GetBioPageDataRequest.ProtoReflect.Descriptor instead.
func (*GetBioPageDataRequest) Descriptor() ([]byte, []int) {
	return file_internal_proto_rawDescGZIP(), []int{0}
}

func (x *GetBioPageDataRequest) GetDcid() string {
	if x != nil {
		return x.Dcid
	}
	return ""
}

var File_internal_proto protoreflect.FileDescriptor

var file_internal_proto_rawDesc = []byte{
	0x0a, 0x0e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x12, 0x0b, 0x64, 0x61, 0x74, 0x61, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x73, 0x22, 0x2b, 0x0a,
	0x15, 0x47, 0x65, 0x74, 0x42, 0x69, 0x6f, 0x50, 0x61, 0x67, 0x65, 0x44, 0x61, 0x74, 0x61, 0x52,
	0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x63, 0x69, 0x64, 0x18, 0x01,
	0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x63, 0x69, 0x64, 0x42, 0x09, 0x5a, 0x07, 0x2e, 0x2f,
	0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_internal_proto_rawDescOnce sync.Once
	file_internal_proto_rawDescData = file_internal_proto_rawDesc
)

func file_internal_proto_rawDescGZIP() []byte {
	file_internal_proto_rawDescOnce.Do(func() {
		file_internal_proto_rawDescData = protoimpl.X.CompressGZIP(file_internal_proto_rawDescData)
	})
	return file_internal_proto_rawDescData
}

var file_internal_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_internal_proto_goTypes = []interface{}{
	(*GetBioPageDataRequest)(nil), // 0: datacommons.GetBioPageDataRequest
}
var file_internal_proto_depIdxs = []int32{
	0, // [0:0] is the sub-list for method output_type
	0, // [0:0] is the sub-list for method input_type
	0, // [0:0] is the sub-list for extension type_name
	0, // [0:0] is the sub-list for extension extendee
	0, // [0:0] is the sub-list for field type_name
}

func init() { file_internal_proto_init() }
func file_internal_proto_init() {
	if File_internal_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_internal_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*GetBioPageDataRequest); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_internal_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   1,
			NumExtensions: 0,
			NumServices:   0,
		},
		GoTypes:           file_internal_proto_goTypes,
		DependencyIndexes: file_internal_proto_depIdxs,
		MessageInfos:      file_internal_proto_msgTypes,
	}.Build()
	File_internal_proto = out.File
	file_internal_proto_rawDesc = nil
	file_internal_proto_goTypes = nil
	file_internal_proto_depIdxs = nil
}


text:
"""Represent the Freebox router and its devices and sensors."""
from __future__ import annotations

from datetime import datetime, timedelta
import logging
import os
from pathlib import Path
from typing import Any

from freebox_api import Freepybox
from freebox_api.api.wifi import Wifi
from freebox_api.exceptions import HttpRequestError

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util import slugify

from .const import (
    API_VERSION,
    APP_DESC,
    CONNECTION_SENSORS_KEYS,
    DOMAIN,
    STORAGE_KEY,
    STORAGE_VERSION,
)

_LOGGER = logging.getLogger(__name__)

SCAN_INTERVAL = timedelta(seconds=30)

async def get_api(hass: HomeAssistant, host: str) -> Freepybox:
    """Get the Freebox API."""
    freebox_path = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY).path

    if not os.path.exists(freebox_path):
        await hass.async_add_executor_job(os.makedirs, freebox_path)

    token_file = Path(f"{freebox_path}/{slugify(host)}.conf")

    return Freepybox(APP_DESC, token_file, API_VERSION)

class FreeboxRouter:
    """Representation of a Freebox router."""

    def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
        """Initialize a Freebox router."""
        self.hass = hass
        self._entry = entry
        self._host = entry.data[CONF_HOST]
        self._port = entry.data[CONF_PORT]

        self._api: Freepybox = None
        self.name = None
        self.mac = None
        self._sw_v = None
        self._attrs = {}

        self.devices: dict[str, dict[str, Any]] = {}
        self.disks: dict[int, dict[str, Any]] = {}
        self.sensors_temperature: dict[str, int] = {}
        self.sensors_connection: dict[str, float] = {}
        self.call_list: list[dict[str, Any]] = []

        self._unsub_dispatcher = None
        self.listeners = []

    async def setup(self) -> None:
        """Set up a Freebox router."""
        self._api = await get_api(self.hass, self._host)

        try:
            await self._api.open(self._host, self._port)
        except HttpRequestError:
            _LOGGER.exception("Failed to connect to Freebox")
            return ConfigEntryNotReady

        # System
        fbx_config = await self._api.system.get_config()
        self.mac = fbx_config["mac"]
        self.name = fbx_config["model_info"]["pretty_name"]
        self._sw_v = fbx_config["firmware_version"]

        # Devices & sensors
        await self.update_all()
        self._unsub_dispatcher = async_track_time_interval(
            self.hass, self.update_all, SCAN_INTERVAL
        )

    async def update_all(self, now: datetime | None = None) -> None:
        """Update all Freebox platforms."""
        await self.update_device_trackers()
        await self.update_sensors()

    async def update_device_trackers(self) -> None:
        """Update Freebox devices."""
        new_device = False
        fbx_devices: [dict[str, Any]] = await self._api.lan.get_hosts_list()

        # Adds the Freebox itself
        fbx_devices.append(
            {
                "primary_name": self.name,
                "l2ident": {"id": self.mac},
                "vendor_name": "Freebox SAS",
                "host_type": "router",
                "active": True,
                "attrs": self._attrs,
            }
        )

        for fbx_device in fbx_devices:
            device_mac = fbx_device["l2ident"]["id"]

            if self.devices.get(device_mac) is None:
                new_device = True

            self.devices[device_mac] = fbx_device

        async_dispatcher_send(self.hass, self.signal_device_update)

        if new_device:
            async_dispatcher_send(self.hass, self.signal_device_new)

    async def update_sensors(self) -> None:
        """Update Freebox sensors."""
        # System sensors
        syst_datas: dict[str, Any] = await self._api.system.get_config()

        # According to the doc `syst_datas["sensors"]` is temperature sensors in celsius degree.
        # Name and id of sensors may vary under Freebox devices.
        for sensor in syst_datas["sensors"]:
            self.sensors_temperature[sensor["name"]] = sensor["value"]

        # Connection sensors
        connection_datas: dict[str, Any] = await self._api.connection.get_status()
        for sensor_key in CONNECTION_SENSORS_KEYS:
            self.sensors_connection[sensor_key] = connection_datas[sensor_key]

        self._attrs = {
            "IPv4": connection_datas.get("ipv4"),
            "IPv6": connection_datas.get("ipv6"),
            "connection_type": connection_datas["media"],
            "uptime": datetime.fromtimestamp(
                round(datetime.now().timestamp()) - syst_datas["uptime_val"]
            ),
            "firmware_version": self._sw_v,
            "serial": syst_datas["serial"],
        }

        self.call_list = await self._api.call.get_calls_log()

        await self._update_disks_sensors()

        async_dispatcher_send(self.hass, self.signal_sensor_update)

    async def _update_disks_sensors(self) -> None:
        """Update Freebox disks."""
        # None at first request
        fbx_disks: [dict[str, Any]] = await self._api.storage.get_disks() or []

        for fbx_disk in fbx_disks:
            self.disks[fbx_disk["id"]] = fbx_disk

    async def reboot(self) -> None:
        """Reboot the Freebox."""
        await self._api.system.reboot()

    async def close(self) -> None:
        """Close the connection."""
        if self._api is not None:
            await self._api.close()
            self._unsub_dispatcher()
        self._api = None

    @property
    def device_info(self) -> DeviceInfo:
        """Return the device information."""
        return {
            "connections": {(CONNECTION_NETWORK_MAC, self.mac)},
            "identifiers": {(DOMAIN, self.mac)},
            "name": self.name,
            "manufacturer": "Freebox SAS",
            "sw_version": self._sw_v,
        }

    @property
    def signal_device_new(self) -> str:
        """Event specific per Freebox entry to signal new device."""
        return f"{DOMAIN}-{self._host}-device-new"

    @property
    def signal_device_update(self) -> str:
        """Event specific per Freebox entry to signal updates in devices."""
        return f"{DOMAIN}-{self._host}-device-update"

    @property
    def signal_sensor_update(self) -> str:
        """Event specific per Freebox entry to signal updates in sensors."""
        return f"{DOMAIN}-{self._host}-sensor-update"

    @property
    def sensors(self) -> dict[str, Any]:
        """Return sensors."""
        return {**self.sensors_temperature, **self.sensors_connection}

    @property
    def wifi(self) -> Wifi:
        """Return the wifi."""
        return self._api.wifi


text:
package graphite

import (
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
)

var WrongUrlError = errors.New("Wrong url")

// RequestError is special error, which not only implements an error interface,
// but also provides access to `Query` field, containing original query which
// cause an error.
type RequestError struct {
	Query string
	Type  string
}

func (e RequestError) Error() string {
	return e.Type
}

// Client is client to `graphite web api` (http://graphite-api.readthedocs.io/en/latest/api.html).
// You can either instantiate it manually by providing `url` and `client` or use a `NewFromString` shortcut.
type Client struct {
	Url    url.URL
	Client *http.Client
}

// NewFromString is a convenient function for constructing `graphite.Client` from url string.
// For example 'https://my-graphite.tld'. NewFromString could return either `graphite.Client`
// instance or `WrongUrlError` error.
func NewFromString(urlString string) (*Client, error) {
	url, err := url.Parse(urlString)
	if err != nil {
		return nil, WrongUrlError
	}
	return &Client{*url, &http.Client{}}, nil
}

func (c *Client) makeRequest(q qsGenerator) ([]byte, error) {
	empty := []byte{}
	response, err := c.Client.Get(c.queryAsString(q))
	if err != nil {
		return empty, c.createError(q, "Request error")
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return empty, c.createError(q, "Wrong status code")
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return empty, c.createError(q, "Can't read response body")
	}
	return body, nil
}

func (c *Client) createError(r qsGenerator, t string) error {
	return RequestError{
		Type:  t,
		Query: c.queryAsString(r),
	}
}

func (c *Client) queryAsString(r qsGenerator) string {
	return c.Url.String() + r.toQueryString()
}

type qsGenerator interface {
	toQueryString() string
}


text:
@interface MOBProjectionEPSG4025 : MOBProjection

@end


text:
main(){

  # Set up warp files
  warp=${warp_dir}/${warp_prefix}1Warp.nii.gz
  inverse=${warp_dir}/${warp_prefix}1InverseWarp.nii.gz
  affine=${warp_dir}/${warp_prefix}0GenericAffine.mat

  # Set up fmri_reg command
  if [ ! -z $fmri_reg ]; then
    fmri_warp="-t $fmri_reg"
  fi

  # Set up time_series command
  if [ $time_series -eq 1 ]; then
    vol4d="-e 3"
  fi

  # Warp input volume to target's T1 space
  output=$output_dir/${output_prefix}.nii.gz
  if [ ! -e $output ]; then
    case $warp_setting in
      forward)
        cmd="${ANTs_dir}/antsApplyTransforms -d 3 $vol4d -i $input -r $target -n $interp -t $warp -t $affine $fmri_warp"
        cmd="$cmd -o $output"
        echo $cmd
        eval $cmd
        ;;
      inverse)
        cmd="${ANTs_dir}/antsApplyTransforms -d 3 $vol4d -i $input -r $target -n $interp $fmri_warp -t [$affine, 1]"
        cmd="$cmd -t $inverse -o $output"
        echo $cmd
        eval $cmd
        ;;
      *)
        echo "Invalid warp setting. Use either 'forward' or 'inverse'"
     esac
  else
    echo "The input volume have already been projected into ${target}'s space by ANTs"
  fi
}

##################################################################
# Function usage
##################################################################

# Usage
usage() { echo "
Usage: CBIG_antsApplyReg_vol2vol.sh -i input -r target -w warp_prefix -p output_prefix

This script applies existing warps prepared using ANTs registration to map an input volume to a target volume.

REQUIRED ARGUMENTS:

	-i <input> 		absolute path to input volume to map from
	-r <target> 		absolute path to target volume to be mapped to
	-w <warp_prefix> 	prefix of the warp files. Specifically, the affine, forward and inverse warps should have the
				following names:
					warp_prefix0GenericAffine.mat
					warp_prefix1Warp.nii.gz
					warp_prefix1InverseWarp.nii.gz
	-p <output_prefix> 	prefix for output volume

OPTIONAL ARGUMENTS:
	-f <fmri_reg>		absolute path to native-to-T1 registration file for fMRI input. The file must have been
				converted to format used by ANTs (e.g. .txt or .mat) if it was generated using other tools.
				[ default: unset ]
	-e <time_series>	set this to 1 if the input volume is 4D (time-series)
				[ default: 0 ]
	-d <warp_dir> 		absolute path to the warps
				[ default: $(pwd)/results ]
	-o <output_dir> 	absolute path to output directory
				[ default: $(pwd)/results ]
	-s <warp setting> 	warping direction ('forward' for forward warp, 'inverse' for inverse warp). For example, if
				the target space was registered to the input space during ANTs registration, then inverse
				warp should be used to now map the input to the target.
				[ default: forward ]
	-t <interp> 		interpolation (Linear, NearestNeighbor, etc.)
				[ default: Linear ]
	-a <ANTs_dir> 		directory where ANTs is installed
				[ default: $CBIG_ANTS_DIR ]
	-h			display help message

OUTPUTS:
	$0 will create 1 output file in the output directory, corresponding to the input warped into target's space.
	For example:
		output_prefix.nii.gz

EXAMPLE:
	$0 -i /path/to/my/data.nii.gz -r /path/to/my/template.nii.gz -w subject_moving_template_fixed -p data_to_template
	-f data_to_T1.txt -s forward

" 1>&2; exit 1; }

# Display help message if no argument is supplied
if [ $# -eq 0 ]; then
  usage; 1>&2; exit 1
fi

##################################################################
# Assign input variables
##################################################################

# Default parameter
warp_dir=$(pwd)/results
output_dir=$(pwd)/results
warp_setting=forward
interp=Linear
ANTs_dir=$CBIG_ANTS_DIR
time_series=0

# Assign parameter
while getopts "i:r:w:p:f:e:d:o:s:t:a:h" opt; do
  case $opt in
    i) input=${OPTARG} ;;
    r) target=${OPTARG} ;;
    w) warp_prefix=${OPTARG} ;;
    p) output_prefix=${OPTARG} ;;
    f) fmri_reg=${OPTARG} ;;
    e) time_series=${OPTARG} ;;
    d) warp_dir=${OPTARG} ;;
    o) output_dir=${OPTARG} ;;
    s) warp_setting=${OPTARG} ;;
    t) interp=${OPTARG} ;;
    a) ANTs_dir=${OPTARG} ;;
    h) usage; exit ;;
    *) usage; 1>&2; exit 1 ;;
  esac
done

##################################################################
# Check parameter
##################################################################

if [ -z $target ]; then
  echo "Reference volume not defined."; 1>&2; exit 1
fi

if [ -z $input ]; then
  echo "Input volume not defined."; 1>&2; exit 1
fi

if [ -z $warp_prefix ]; then
  echo "Warp prefix not defined."; 1>&2; exit 1
fi

if [ -z $output_prefix ]; then
  echo "Output prefix not defined."; 1>&2; exit 1
fi

##################################################################
# Disable multi-threading
##################################################################

ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS=1
export ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS

##################################################################
# Set up output directory
##################################################################

if [ ! -d "$output_dir" ]; then
  echo "Output directory does not exist. Making directory now..."
  mkdir -p $output_dir
fi

###########################################
# Implementation
###########################################

main


text:
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">

Hi all,

Below is the sign up link for on-site massages tomorrow. The moussuse will arrive after lunch. Please sign up for your time if you wish to participate :).

Makala

From: makala@nylas.com

Subject: Fwd: Refresh Corporate Confirmation

Date: Aug 28 2015, at 3:51 pm

To: Michael Grinich <mg@nylas.com>, Christine Spang <spang@nylas.com>

Nylas is Bringing Massage to the Office

Nylas and Refresh

 invite you to sign-up for

A
 Massage

on

Tuesday September 1st at
1 PM

2030 Harrison Street Floor 2 San Francisco, CA 94110

Click below to reserve your spot

 RESERVE
 NOW

Please contact Refresh Body with any issues support@refreshbody.com

Or call 800-616-9271

Refresh Body

refreshbody.com

Sincerely,

The Refresh Body Team

On-Demand, On-Location Wellness Services. Get Refresh'd

800-616-9271

Privacy Policy |
Terms of Use

Note: This is an auto-generated email.  Please do not reply.


text:
mkdir -p docs/html
mkdir -p docs/pdf

export PYTHONPATH=src:$PYTHONPATH

epydoc -v -o docs/html --html pyvision
# epydoc -v -o docs/pdf  --pdf  pyvision


text:
package io.github.galop_proxy.galop.configuration;

import java.util.Map;

import static io.github.galop_proxy.api.commons.Preconditions.checkNotNull;
import static io.github.galop_proxy.galop.configuration.ConfigurationPropertyKeys.HTTP_CONNECTION_LOG_INTERVAL;
import static io.github.galop_proxy.galop.configuration.ConfigurationPropertyKeys.HTTP_CONNECTION_TERMINATION_TIMEOUT;
import static io.github.galop_proxy.galop.configuration.FactoryUtils.parseTimeout;

final class HttpConnectionConfigurationFactoryImpl implements HttpConnectionConfigurationFactory {

    @Override
    public HttpConnectionConfiguration parse(final Map<String, String> properties) throws InvalidConfigurationException {
        checkNotNull(properties, "properties");
        final long logInterval = parseLogInterval(properties);
        final long terminationTimeout = parseTerminationTimeout(properties);
        return new HttpConnectionConfigurationImpl(logInterval, terminationTimeout);
    }

    private long parseLogInterval(final Map<String, String> properties) throws InvalidConfigurationException {

        final String intervalAsString = properties.getOrDefault(HTTP_CONNECTION_LOG_INTERVAL,
                Long.toString(ConfigurationDefaults.HTTP_CONNECTION_LOG_INTERVAL));

        final long interval;

        try {
            interval = (long) Integer.parseInt(intervalAsString);
        } catch (final NumberFormatException ex) {
            throw new InvalidConfigurationException("Property " + HTTP_CONNECTION_LOG_INTERVAL
                    + " is not a valid number: " + intervalAsString);
        }

        if (interval < 1) {
            throw new InvalidConfigurationException("Property " + HTTP_CONNECTION_LOG_INTERVAL
                    + " must be at least 1: " + interval);
        }

        return interval;

    }

    private long parseTerminationTimeout(final Map<String, String> properties) throws InvalidConfigurationException {
        return parseTimeout(properties, HTTP_CONNECTION_TERMINATION_TIMEOUT,
                ConfigurationDefaults.HTTP_CONNECTION_TERMINATION_TIMEOUT);
    }

}


text:
package com.google.j2cl.benchmarks.octane;

import com.google.j2cl.benchmarking.framework.AbstractBenchmark;
import com.google.j2cl.benchmarks.octane.navierstokes.NavierStokes;

/**
 * This is the Java port of the JavaScript implementation of NavierStokes benchmark from the V8
 * octane benchmark suite.
 *
 *
Main focus: reading and writing numeric arrays.
 *
 *
Secondary focus: floating point math.
 */
public class NavierStokesBenchmark extends AbstractBenchmark {

  private NavierStokes navierStokes;

  @Override
  public Object run() {
    navierStokes.runNavierStokes();
    return null;
  }

  @Override
  public void setupOneTime() {
    navierStokes = new NavierStokes();
    navierStokes.setup();
  }

  @Override
  public void tearDownOneTime() {
    navierStokes.tearDown();
  }
}


text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;

/**
 * The {@code VK_EXT_metal_surface} extension is an instance extension. It provides a mechanism to create a {@code VkSurfaceKHR} object (defined by the {@link KHRSurface VK_KHR_surface} extension) from {@code CAMetalLayer}, which is the native rendering surface of Apple's Metal framework.
 *
 *
VK_EXT_metal_surface

 *
 *

 *
Name String

 *
{@code VK_EXT_metal_surface}

 *
Extension Type

 *
Instance extension

 *
Registered Extension Number

 *
218

 *
Revision

 *
1

 *
Extension and Version Dependencies

 *

 *
Requires support for Vulkan 1.0

 *
Requires {@link KHRSurface VK_KHR_surface} to be enabled

 *

 *
Contact

 *

 *
Dzmitry Malyshau kvark

 *

 *

 *
 *
Other Extension Metadata

 *
 *

 *
Last Modified Date

 *
2018-10-01

 *
IP Status

 *
No known IP claims.

 *
Contributors

 *

 *
Dzmitry Malyshau, Mozilla Corp.

 *

 *

 */
public class EXTMetalSurface {

    /** The extension specification version. */
    public static final int VK_EXT_METAL_SURFACE_SPEC_VERSION = 1;

    /** The extension name. */
    public static final String VK_EXT_METAL_SURFACE_EXTENSION_NAME = "VK_EXT_metal_surface";

    /** Extends {@code VkStructureType}. */
    public static final int VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT = 1000217000;

    protected EXTMetalSurface() {
        throw new UnsupportedOperationException();
    }

    // --- [ vkCreateMetalSurfaceEXT ] ---

    /** Unsafe version of: {@link #vkCreateMetalSurfaceEXT CreateMetalSurfaceEXT} */
    public static int nvkCreateMetalSurfaceEXT(VkInstance instance, long pCreateInfo, long pAllocator, long pSurface) {
        long __functionAddress = instance.getCapabilities().vkCreateMetalSurfaceEXT;
        if (CHECKS) {
            check(__functionAddress);
        }
        return callPPPPI(instance.address(), pCreateInfo, pAllocator, pSurface, __functionAddress);
    }

    /**
     * Create a VkSurfaceKHR object for CAMetalLayer.
     *
     *
C Specification

     *
     *
To create a {@code VkSurfaceKHR} object for a {@code CAMetalLayer}, call:

     *
     *

     * VkResult vkCreateMetalSurfaceEXT(
     *     VkInstance                                  instance,
     *     const VkMetalSurfaceCreateInfoEXT*          pCreateInfo,
     *     const VkAllocationCallbacks*                pAllocator,
     *     VkSurfaceKHR*                               pSurface);

     *
     *
Valid Usage (Implicit)

     *
     *

     *
{@code instance} must be a valid {@code VkInstance} handle

     *
{@code pCreateInfo} must be a valid pointer to a valid {@link VkMetalSurfaceCreateInfoEXT} structure

     *
If {@code pAllocator} is not {@code NULL}, {@code pAllocator} must be a valid pointer to a valid {@link VkAllocationCallbacks} structure

     *
{@code pSurface} must be a valid pointer to a {@code VkSurfaceKHR} handle

     *

     *
     *
Return Codes

     *
     *

     *
On success, this command returns

     *

     *
{@link VK10#VK_SUCCESS SUCCESS}

     *

     *
On failure, this command returns

     *

     *
{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}

     *
{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}

     *
{@link KHRSurface#VK_ERROR_NATIVE_WINDOW_IN_USE_KHR ERROR_NATIVE_WINDOW_IN_USE_KHR}

     *

     *

     *
     *
See Also

     *
     *
{@link VkAllocationCallbacks}, {@link VkMetalSurfaceCreateInfoEXT}

     *
     * @param instance    the instance with which to associate the surface.
     * @param pCreateInfo a pointer to a {@link VkMetalSurfaceCreateInfoEXT} structure specifying parameters affecting the creation of the surface object.
     * @param pAllocator  the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see Memory Allocation).
     * @param pSurface    a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.
     */
    @NativeType("VkResult")
    public static int vkCreateMetalSurfaceEXT(VkInstance instance, @NativeType("VkMetalSurfaceCreateInfoEXT const *") VkMetalSurfaceCreateInfoEXT pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") LongBuffer pSurface) {
        if (CHECKS) {
            check(pSurface, 1);
        }
        return nvkCreateMetalSurfaceEXT(instance, pCreateInfo.address(), memAddressSafe(pAllocator), memAddress(pSurface));
    }

    /** Array version of: {@link #vkCreateMetalSurfaceEXT CreateMetalSurfaceEXT} */
    @NativeType("VkResult")
    public static int vkCreateMetalSurfaceEXT(VkInstance instance, @NativeType("VkMetalSurfaceCreateInfoEXT const *") VkMetalSurfaceCreateInfoEXT pCreateInfo, @Nullable @NativeType("VkAllocationCallbacks const *") VkAllocationCallbacks pAllocator, @NativeType("VkSurfaceKHR *") long[] pSurface) {
        long __functionAddress = instance.getCapabilities().vkCreateMetalSurfaceEXT;
        if (CHECKS) {
            check(__functionAddress);
            check(pSurface, 1);
        }
        return callPPPPI(instance.address(), pCreateInfo.address(), memAddressSafe(pAllocator), pSurface, __functionAddress);
    }

}


text:
//
//  SmartCoActionDelegate.h
//  appez
//
//  Created by Transility on 11/09/12.
//
//

/**
 * SmartCoActionDelegate : Defines a protocol for notifying the result for
 * completion of Co-action. Essentially used by services such as Map service
 * which lie in the co-event category
 *
 * */
#import <Foundation/Foundation.h>

@protocol SmartCoActionDelegate <NSObject>
/**
 * Indicates the successful completion of the co-action along with the data
 * corresponding to the completion
 *
 * @param mapsData
 *            : Data accompanying the completion of the co-event
 * */
@optional
-(void)didCompleteCoActionWithSuccess:(NSString*)mapsData;
/**
 * Indicates the erroneous completion of the co-event action
 *
 * @param exceptionType
 *            : Unique code corresponding to the problem in the co-event
 *
 * @param exceptionMessage
 *            : Message describing the nature of problem with the co-event
 *            execution
 * */
-(void)didCompleteCoActionWithError:(int)exceptionType WithMessage:(NSString*)exceptionMessage;
@end


text:
import getPageLabel from '../../src/PageLabel';

it('should return an object with pageLabel, pageNumber and pageNumberTotal', () => {
  const pageLabel = 'Webpage';
  const selectedPage = 5;
  const totalPages = 5;
  const { messageId, messageAttributes } = getPageLabel(pageLabel, selectedPage, totalPages);

  expect('Terra.paginator.pageCountWithLabel').toEqual(messageId);
  expect({ pageLabel, pageNumber: selectedPage, pageNumberTotal: totalPages }).toEqual(messageAttributes);
});

it('should return an object with pageNumber and pageNumberTotal', () => {
  const pageLabel = undefined;
  const selectedPage = 5;
  const totalPages = 5;
  const { messageId, messageAttributes } = getPageLabel(pageLabel, selectedPage, totalPages);

  expect('Terra.paginator.pageCount').toEqual(messageId);
  expect({ pageNumber: selectedPage, pageNumberTotal: totalPages }).toEqual(messageAttributes);
});

it('should return an object with pageLabel and pageNumber', () => {
  const pageLabel = 'Webpage';
  const selectedPage = 5;
  const totalPages = undefined;
  const { messageId, messageAttributes } = getPageLabel(pageLabel, selectedPage, totalPages);

  expect('Terra.paginator.pageIndexWithLabel').toEqual(messageId);
  expect({ pageLabel, pageNumber: selectedPage }).toEqual(messageAttributes);
});

it('should return an object with pageNumberTotal', () => {
  const pageLabel = undefined;
  const selectedPage = 5;
  const totalPages = undefined;
  const { messageId, messageAttributes } = getPageLabel(pageLabel, selectedPage, totalPages);

  expect('Terra.paginator.pageIndex').toEqual(messageId);
  expect({ pageLabel, pageNumber: selectedPage, pageNumberTotal: totalPages }).toEqual(messageAttributes);
});


text:
import numpy as np

if __name__ == "__main__":
  bins = 250

  theta_limits = [0.0, 0.1]
  theta_step = (theta_limits[1] - theta_limits[0]) / bins

  phi_limits = [-0.1, 0.1]
  phi_step = (phi_limits[1] - phi_limits[0]) / bins

  generation_params = {
    "n_particles": 100,
    "detector_layers": np.arange(0, 20) + 5,

    "theta_limits": [theta_limits[0] + 2 * theta_step, theta_limits[1] - 2 * theta_step],
    "phi_limits": [phi_limits[0] + 2 * phi_step, phi_limits[1] - 2 * phi_step],

    "trace_probability": 0.75,
    "trace_noise": 0.025,
    "detector_noise_rate": 1000.0,

    "sigma": 0.05,

    "theta_bins": bins,
    "phi_bins": bins
  }

  load_params = {
    'sigma' : 1.0,
    "theta_limits": [-np.pi / 8, np.pi / 8],
    "theta_bins": 250,
    "phi_limits": [-np.pi / 8, np.pi / 8],
    "phi_bins": 250
  }

  experiments = 100
  from pyretina.optimize import multi_start

  solver = "Newton-CG"
  solver_options = {
    "xtol" : 1.0e-4
  }

  from pyretina.plot import *
  from pyretina.evaluate import *
  from pyretina.io import from_csv

  precision = np.zeros(shape=experiments)
  recall = np.zeros(shape=experiments)

  precision_grid = np.zeros(shape=experiments)
  recall_grid = np.zeros(shape=experiments)

  for i in range(experiments):
    re = from_csv.load_dataset("data/event_hits/00163875_0143139193.tracks.csv",
                               **load_params)

    predicted, traces = multi_start(re, max_evaluations=10000, method = solver, solver_options = solver_options)

    plot_retina_results(predicted, re, 1.0e-2,
                        search_traces=traces, against='grid_search').savefig("events_img/multistart_%d.png" % i, dpi=320)

    bm = binary_metrics(predicted, re, against='true')[0]
    precision[i] = bm['precision']
    recall[i] = bm['recall']

    predicted_grid = grid_search(re)
    plot_retina_results(predicted_grid, re, 1.0e-2,
                        search_traces=None, against='true').savefig("events_img/grid_search_%d.png" % i, dpi=320)

    bm_grid = binary_metrics(predicted_grid, re, against='true')[0]

    precision_grid[i] = bm_grid['precision']
    recall_grid[i] = bm_grid['recall']

    print precision[i], recall[i]
    print precision_grid[i], recall_grid[i]

  print "Precision", precision.mean(), precision.std()
  print "Recall", recall.mean(), recall.std()

  print "Precision Grid", precision_grid.mean(), precision_grid.std()
  print "Recall Grid", recall_grid.mean(), recall_grid.std()


text:
package org.fhcrc.cpl.viewer.feature.extraction;

import org.fhcrc.cpl.toolbox.proteomics.feature.Spectrum;

/**
 * Removes background noise from spectra
 */
public class BackgroundRemover
{

    public float[][] removeBackground(float[][] spectra)
    {
        return Spectrum.RemoveBackground(spectra);
    }

    /**
     * Calculate median intensity at each point on the grid
     * @param spectra
     * @return
     */
    public float[][] calculateMedian(float[][] spectra)
    {
        int numSpectra = spectra.length;
        int spectrumHeight = spectra[0].length;

        float[][] median = new float[numSpectra][];
        for (int i = 0; i < numSpectra; i++)
            median[i] = Spectrum.MedianWindow(spectra[i], spectrumHeight, 2 * SpectrumResampler.getResampleFrequency(),
                    false);
        float[] row = null;
        for (int r = 0; r < spectrumHeight; r++)
        {
            row = Spectrum.getRow(spectra, r, row);
            float[] m = Spectrum.MedianWindow(row, numSpectra, SpectrumResampler.getResampleFrequency(), false);
            for (int s = 0; s < m.length; s++)
                median[s][r] = Math.max(median[s][r], m[s]);
        }
        return median;
    }

}


text:
create class dummy( a int );
insert into dummy values (1);

select upper(123) from dummy;

drop class dummy;


text:
package com.avsystem.commons
package misc

object CrossUtils {
  type NativeArray[A] = Array[A]
  type NativeDict[A] = MMap[String, A]

  def newNativeArray[A: ClassTag](size: Int): NativeArray[A] = new Array[A](size)
  def newNativeDict[A]: NativeDict[A] = new MHashMap[String, A]
  def unsetArrayValue: Any = null

  def wrappedArray[A: ClassTag](elems: A*): MIndexedSeq[A] = Array(elems: _*)
  def arrayBuffer[A]: MIndexedSeq[A] with MBuffer[A] = new MArrayBuffer[A]
  def dictionary[A](keyValues: (String, A)*): MMap[String, A] = MHashMap[String, A](keyValues: _*)
}


text:
<?php

namespace LeadThread\Bitly\Exceptions;

abstract class BitlyException extends \Exception
{

}


text: Testing Styleguide


text:
::: warning
This version of the Management API has been deprecated. We recommend that you use the [new version](/api/management/v2) instead.
:::


text:
import React, { useEffect, useState } from 'react';

export function MachineSet({
  disabled,
  machineErrors,
  onChange,
  machines
}: {
  onChange: (machines: string[]) => void;
  machines: string[];
  name?: string;
  disabled?: boolean;
  machineErrors?: {[K: string]: string};
}) {
  const [inputFields, setInputFields] = useState<string[]>(['', '']);

  const handleChange: (
    value: string,
    index: number
  ) => void = (value, index) => {
    let nextMachines: string[] = [...inputFields.filter((value) => value !== '')];
    if (value !== '') {
      const multiple = value.split(/[\s]/);
      if (multiple.length === 1) {
        nextMachines[index] = value;
      } else {
        nextMachines[index] = multiple[0];
        multiple.slice(1).forEach((value) => nextMachines.push(value));
      }
    } else {
      nextMachines = nextMachines.filter((_, idx) => idx !== index);
    }

    if (nextMachines.length === 0) {
      setInputFields(['', '']);
    } else {
      setInputFields([...nextMachines, '']);
    }

    onChange(nextMachines);
  };

  useEffect(() => {
    console.debug("MachineSet#useEffect(machines)");
    if (machines.length > 0) {
      setInputFields([...machines, '']);
    }
  }, [machines]);

  return (
   <>
   {inputFields.map((machine, index) => (

        <input
          required={index === 0 ? true : undefined}
          className="input"
          type="text"
          disabled={disabled}
          value={machine}
          data-testid="dc-machine"
          onChange={(event: {target: {value: string}}) => handleChange(event.target.value.trim(), index)}
        />

      {machineErrors && (machine in machineErrors) && (

{machineErrors[machine]}

      )}

   ))}
   </>
  );
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$lang['title'] = 'Candidates';
$lang['candidates'] = 'CANDIDATES';
$lang['search'] = 'Search';
$lang['searchbar'] = 'Type name/number/party/region..';
$lang['number'] = 'Number';
$lang['name'] = 'Name';
$lang['party'] = 'Party';
$lang['region'] = 'Region';
$lang['slogan'] = 'Slogan';

?>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VmDiskFileQueryFilter extends DynamicData {
  public String[] diskType;
  public int[] matchHardwareVersion;
  public String[] controllerType;
  public Boolean thin;

  public String[] getDiskType() {
    return this.diskType;
  }

  public int[] getMatchHardwareVersion() {
    return this.matchHardwareVersion;
  }

  public String[] getControllerType() {
    return this.controllerType;
  }

  public Boolean getThin() {
    return this.thin;
  }

  public void setDiskType(String[] diskType) {
    this.diskType=diskType;
  }

  public void setMatchHardwareVersion(int[] matchHardwareVersion) {
    this.matchHardwareVersion=matchHardwareVersion;
  }

  public void setControllerType(String[] controllerType) {
    this.controllerType=controllerType;
  }

  public void setThin(Boolean thin) {
    this.thin=thin;
  }
}


text:
'use strict';

const {spawn} = require('child_process');
const {join} = require('path');

const ROOT_PATH = join(__dirname, '..', '..');
const reactVersion = process.argv[2];
const inlinePackagePath = join(ROOT_PATH, 'packages', 'react-devtools-inline');
const shellPackagePath = join(ROOT_PATH, 'packages', 'react-devtools-shell');
const screenshotPath = join(ROOT_PATH, 'tmp', 'screenshots');

let buildProcess = null;
let serverProcess = null;
let testProcess = null;

function format(loggable) {
  return `${loggable}`
    .split('\n')
    .filter(line => {
      return line.trim() !== '';
    })
    .map(line => `  ${line}`)
    .join('\n');
}

function logBright(loggable) {
  console.log(`\x1b[1m${loggable}\x1b[0m`);
}

function logDim(loggable) {
  const formatted = format(loggable, 2);
  if (formatted !== '') {
    console.log(`\x1b[2m${formatted}\x1b[0m`);
  }
}

function logError(loggable) {
  const formatted = format(loggable, 2);
  if (formatted !== '') {
    console.error(`\x1b[31m${formatted}\x1b[0m`);
  }
}

function buildInlinePackage() {
  logBright('Building inline packages');

  buildProcess = spawn('yarn', ['build'], {cwd: inlinePackagePath});
  buildProcess.stdout.on('data', data => {
    logDim(data);
  });
  buildProcess.stderr.on('data', data => {
    if (`${data}`.includes('Warning')) {
      logDim(data);
    } else {
      logError(`Error:\n${data}`);

      exitWithCode(1);
    }
  });
  buildProcess.on('close', code => {
    logBright('Inline package built');

    runTestShell();
  });
}

function runTestShell() {
  const timeoutID = setTimeout(() => {
    // Assume the test shell server failed to start.
    logError('Testing shell server failed to start');
    exitWithCode(1);
  }, 30000);

  logBright('Starting testing shell server');

  if (!reactVersion) {
    serverProcess = spawn('yarn', ['start'], {cwd: shellPackagePath});
  } else {
    serverProcess = spawn('yarn', ['start'], {
      cwd: shellPackagePath,
      env: {...process.env, REACT_VERSION: reactVersion},
    });
  }

  serverProcess.stdout.on('data', data => {
    if (`${data}`.includes('Compiled successfully.')) {
      logBright('Testing shell server running');

      clearTimeout(timeoutID);

      runEndToEndTests();
    }
  });
  serverProcess.stderr.on('data', data => {
    if (`${data}`.includes('EADDRINUSE')) {
      // Something is occupying this port;
      // We could kill the process and restart but probably better to prompt the user to do this.

      logError('Free up the port and re-run tests:');
      logBright('  kill -9 $(lsof -ti:8080)');

      exitWithCode(1);
    } else if (`${data}`.includes('ERROR')) {
      logError(`Error:\n${data}`);

      exitWithCode(1);
    } else {
      // Non-fatal stuff like Babel optimization warnings etc.
      logDim(data);
    }
  });
}

async function runEndToEndTests() {
  logBright('Running e2e tests');
  if (!reactVersion) {
    testProcess = spawn('yarn', ['test:e2e', `--output=${screenshotPath}`], {
      cwd: inlinePackagePath,
    });
  } else {
    testProcess = spawn('yarn', ['test:e2e', `--output=${screenshotPath}`], {
      cwd: inlinePackagePath,
      env: {...process.env, REACT_VERSION: reactVersion},
    });
  }

  testProcess.stdout.on('data', data => {
    // Log without formatting because Playwright applies its own formatting.
    const formatted = format(data);
    if (formatted !== '') {
      console.log(formatted);
    }
  });
  testProcess.stderr.on('data', data => {
    // Log without formatting because Playwright applies its own formatting.
    const formatted = format(data);
    if (formatted !== '') {
      console.error(formatted);
    }

    exitWithCode(1);
  });
  testProcess.on('close', code => {
    logBright(`Tests completed with code: ${code}`);

    exitWithCode(code);
  });
}

function exitWithCode(code) {
  if (buildProcess !== null) {
    try {
      logBright('Shutting down build process');
      buildProcess.kill();
    } catch (error) {
      logError(error);
    }
  }

  if (serverProcess !== null) {
    try {
      logBright('Shutting down shell server process');
      serverProcess.kill();
    } catch (error) {
      logError(error);
    }
  }

  if (testProcess !== null) {
    try {
      logBright('Shutting down test process');
      testProcess.kill();
    } catch (error) {
      logError(error);
    }
  }

  process.exit(code);
}

buildInlinePackage();


text:
create index name on probe_set(`name`);

INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL, 'patch', 'patch_54_55_f.sql|probe_set.name_index');


text:
<!DOCTYPE html>

    <title>Swagger explorer</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/index.css" rel="stylesheet"/>
    <link href='css/standalone.css' rel='stylesheet'/>
    <link href='css/api-explorer.css' rel='stylesheet' type='text/css'/>

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

swagger explorer

Swagger
                        explorer


text:
--------------------------------
-- @function [parent=#TMXMapInfo] setTileSize
-- @param self
-- @param #size_table size

--------------------------------
-- @function [parent=#TMXMapInfo] initWithTMXFile
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)

--------------------------------
-- @function [parent=#TMXMapInfo] getOrientation
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- @function [parent=#TMXMapInfo] isStoringCharacters
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- @function [parent=#TMXMapInfo] setLayers
-- @param self
-- @param #array_table array

--------------------------------
-- @function [parent=#TMXMapInfo] parseXMLFile
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)

--------------------------------
-- @function [parent=#TMXMapInfo] getParentElement
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- @function [parent=#TMXMapInfo] setTMXFileName
-- @param self
-- @param #string str

--------------------------------
-- @function [parent=#TMXMapInfo] parseXMLString
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)

--------------------------------
-- overload function: getLayers()
--
-- overload function: getLayers()
--
-- @function [parent=#TMXMapInfo] getLayers
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)

--------------------------------
-- overload function: getTilesets()
--
-- overload function: getTilesets()
--
-- @function [parent=#TMXMapInfo] getTilesets
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)

--------------------------------
-- @function [parent=#TMXMapInfo] getParentGID
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- @function [parent=#TMXMapInfo] setParentElement
-- @param self
-- @param #int int

--------------------------------
-- @function [parent=#TMXMapInfo] initWithXML
-- @param self
-- @param #string str
-- @param #string str
-- @return bool#bool ret (return value: bool)

--------------------------------
-- @function [parent=#TMXMapInfo] setParentGID
-- @param self
-- @param #int int

--------------------------------
-- @function [parent=#TMXMapInfo] getLayerAttribs
-- @param self
-- @return int#int ret (return value: int)

--------------------------------
-- @function [parent=#TMXMapInfo] getTileSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- @function [parent=#TMXMapInfo] getTileProperties
-- @param self
-- @return map_table#map_table ret (return value: map_table)

--------------------------------
-- overload function: getObjectGroups()
--
-- overload function: getObjectGroups()
--
-- @function [parent=#TMXMapInfo] getObjectGroups
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)

--------------------------------
-- @function [parent=#TMXMapInfo] getTMXFileName
-- @param self
-- @return string#string ret (return value: string)

--------------------------------
-- @function [parent=#TMXMapInfo] setCurrentString
-- @param self
-- @param #string str

--------------------------------
-- @function [parent=#TMXMapInfo] setProperties
-- @param self
-- @param #map_table map

--------------------------------
-- @function [parent=#TMXMapInfo] setOrientation
-- @param self
-- @param #int int

--------------------------------
-- @function [parent=#TMXMapInfo] setTileProperties
-- @param self
-- @param #map_table map

--------------------------------
-- @function [parent=#TMXMapInfo] setMapSize
-- @param self
-- @param #size_table size

--------------------------------
-- @function [parent=#TMXMapInfo] setStoringCharacters
-- @param self
-- @param #bool bool

--------------------------------
-- @function [parent=#TMXMapInfo] getMapSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- @function [parent=#TMXMapInfo] setTilesets
-- @param self
-- @param #array_table array

--------------------------------
-- overload function: getProperties()
--
-- overload function: getProperties()
--
-- @function [parent=#TMXMapInfo] getProperties
-- @param self
-- @return map_table#map_table ret (retunr value: map_table)

--------------------------------
-- @function [parent=#TMXMapInfo] getCurrentString
-- @param self
-- @return string#string ret (return value: string)

--------------------------------
-- @function [parent=#TMXMapInfo] setLayerAttribs
-- @param self
-- @param #int int

--------------------------------
-- @function [parent=#TMXMapInfo] create
-- @param self
-- @param #string str
-- @return TMXMapInfo#TMXMapInfo ret (return value: cc.TMXMapInfo)

--------------------------------
-- @function [parent=#TMXMapInfo] createWithXML
-- @param self
-- @param #string str
-- @param #string str
-- @return TMXMapInfo#TMXMapInfo ret (return value: cc.TMXMapInfo)

--------------------------------
-- @function [parent=#TMXMapInfo] TMXMapInfo
-- @param self

return nil


text: DROP SCHEMA IF EXISTS "cmipresttest" CASCADE;


text:
describe('When logging using verbose method', function() {
    var common = testCommon('testApp');
    var $scope, ctrl, logService;

    beforeEach(inject(function ($rootScope, $controller, $exceptionHandler) {
        logService = common.logService();
        $scope = $rootScope.$new();
        ctrl = $controller('TestCtrl', {
            $scope: $scope,
            $exceptionHandler: $exceptionHandler,
            logService: logService
        });
    }));

    it('Should log expected caption & description',function () {
        common.executeTest($scope.verbose('verbose logging','testing logging using verbose method'),
                    function(requestBody) {
                        var data = JSON.parse(requestBody).logMessages[0];

                        expect(data.category).toEqual('test');
                        expect(data.caption).toEqual('verbose logging');
                        expect(data.description).toEqual('testing logging using verbose method');
                        expect(data.severity).toEqual(logService.logMessageSeverity.verbose);

                        return true;
                   });
    });

    it('Should log expected exception', function () {
        var suppliedException = new Error("supplied exception");

        common.executeTest($scope.verbose('verbose logging','testing logging using verbose method',suppliedException),
                    function(requestBody) {
                        var data = JSON.parse(requestBody).logMessages[0];

                        expect(data.exception).not.toBeNull();
                        expect(data.exception.message).toEqual('supplied exception');
                        return true;
                   });
    });

    it('Should log expected details', function (){
        common.executeTest($scope.verbose('verbose logging','testing logging using verbose method',null,"<data>details</data>"),
                    function(requestBody) {
                        var data = JSON.parse(requestBody).logMessages[0];

                        expect(data.details).toEqual("<data>details</data>");
                        expect(data.severity).toEqual(logService.logMessageSeverity.verbose);

                        return true;
                   });
    });
});


text:
import os
import tempfile
import unittest
import uuid

from conda_execute.lock import Locked

class Test_Locked(unittest.TestCase):

    def test_locked_parent_dir_always_exists(self):
        temp_dir = tempfile.mkdtemp()
        parent_dir = os.path.join(temp_dir, str(uuid.uuid4()), 'fake-env')
        with Locked(parent_dir) as locked:
            assert os.path.isdir(locked.directory_path)

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


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>GroupedDataEx - org.apache.spark.sql.hive.GroupedDataEx</title>
          <meta name="description" content="GroupedDataEx - org.apache.spark.sql.hive.GroupedDataEx" />
          <meta name="keywords" content="GroupedDataEx org.apache.spark.sql.hive.GroupedDataEx" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

org.apache.spark.sql.hive

GroupedDataEx

        class

        GroupedDataEx extends GroupedData

          Linear Supertypes

GroupedData, AnyRef, Any

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

GroupedDataEx

GroupedData

AnyRef

Any

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Instance Constructors

        new

        GroupedDataEx(df: DataFrame, groupingExprs: Seq[Expression], groupType: GroupType)

Attributes

protected[org.apache.spark.sql]

Value Members

        final
        def

        !=(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

Any

        def

        agg(exprs: Map[String, String]): DataFrame

A list of added UDAF in GroupedDataEx:

A list of added UDAF in GroupedDataEx:

voted_avg

weight_voted_avg

Definition Classes

GroupedDataEx → GroupedData

        def

        agg(expr: Column, exprs: Column*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        def

        agg(exprs: Map[String, String]): DataFrame

Definition Classes

GroupedData

        def

        agg(aggExpr: (String, String), aggExprs: (String, String)*): DataFrame

Definition Classes

GroupedData

        def

        argmin_kld(weight: String, conv: String): DataFrame

See also

hivemall.ensemble.ArgminKLDistanceUDAF

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        avg(colNames: String*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        def

        count(): DataFrame

Definition Classes

GroupedData

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        def

        max(colNames: String*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        def

        max_label(score: String, label: String): DataFrame

See also

hivemall.ensemble.MaxValueLabelUDAF"

        def

        maxrow(score: String, label: String): DataFrame

See also

hivemall.ensemble.MaxRowUDAF

        def

        mean(colNames: String*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        def

        min(colNames: String*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        def

        sum(colNames: String*): DataFrame

Definition Classes

GroupedData

Annotations

                @varargs()

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

Inherited from GroupedData

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Pluggin jRating : Ajax rating system with jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery/jRating.jquery.css" type="text/css" />

Free jQuery Plugins and Tutorials - Providing tons of Popular and Free jQuery Plugins, Javascript Libraries, Html5 and CSS3 Scripts for free download. © Copyright 2012-2013 jQueryScript.Net

jRating plugin

 Exemple 1 (Basic exemple without options) :


text:
from PyObjCTools.TestSupport import *
from Quartz.QuartzCore import *
import os

try:
    unicode
except NameError:
    unicode = str

class TestCIImageProviderHelper (NSObject):
    def provideImageData_bytesPerRow_origin__size__userInfo_(self,
            data, rowbytes, x, y, width, height, userInfo):
        pass

class TestCIImageProvider (TestCase):
    def testMethods(self):
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 0, b'o^v')
        self.assertArgIsVariableSize(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 0, b'o^v')
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 1, objc._C_ULNG)
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 2, objc._C_ULNG)
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 3, objc._C_ULNG)
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 4, objc._C_ULNG)
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 5, objc._C_ULNG)
        self.assertArgHasType(TestCIImageProviderHelper.provideImageData_bytesPerRow_origin__size__userInfo_, 6, objc._C_ID)

    def testConstants(self):
        self.assertIsInstance(kCIImageProviderTileSize, unicode)
        self.assertIsInstance(kCIImageProviderUserInfo, unicode)

    @min_os_level('10.6')
    def testConstants10_6(self):
        self.assertIsInstance(kCIOutputNativeSizeKey, unicode)

if __name__ == "__main__":
    main()


text:
from pazudorasolver.piece import Fire, Wood, Water, Dark, Light, Heart, Poison, Jammer, Unknown
from pazudorasolver.board import Board

import pytest

@pytest.fixture(scope='module')
def board_with_3_chain():
    return Board([Fire,  Wood,  Water, Dark,  Light, Heart,
                  Fire,  Water, Dark,  Light, Heart, Fire,
                  Fire,  Water, Dark,  Heart, Heart, Wood,
                  Light, Water, Light, Fire,  Wood,  Wood,
                  Dark,  Water, Dark,  Light, Light, Light], 5, 6)

@pytest.fixture(scope='module')
def board_with_1_chain():
    return Board([Fire,  Wood,  Water, Dark,  Light, Poison,
                  Water, Water, Water, Light, Heart, Jammer,
                  Fire,  Water, Dark,  Heart, Heart, Wood,
                  Light, Water, Light, Fire,  Wood,  Wood,
                  Dark,  Heart, Dark,  Light, Heart, Light], 5, 6)

@pytest.fixture(scope='module')
def board_with_0_chain():
    return Board([Unknown, Unknown, Unknown, Unknown, Unknown, Unknown,
                  Unknown, Unknown, Fire,    Unknown, Unknown, Unknown,
                  Unknown, Fire,    Unknown, Unknown, Unknown, Unknown,
                  Unknown, Fire,    Fire,    Unknown, Unknown, Unknown,
                  Unknown, Unknown, Unknown, Unknown, Unknown, Unknown], 5, 6)

def test_invalid_board():
    # length of list must be equal to row x column for the board to be valid
    with pytest.raises(Exception) as exec_info:
        Board([Fire, Water, Wood, Dark, Light, Heart, Poison, Jammer, Unknown], 10, 10)
    assert 'Given pieces do not fit specified board dimensions!' in str(exec_info.value), \
        "Board's pieces list was smaller than dimensions, but did not fail initialization!"

    with pytest.raises(Exception) as exec_info:
        Board([Fire, Water, Wood, Dark, Light, Heart, Poison, Jammer, Unknown], 2, 2)
    assert 'Given pieces do not fit specified board dimensions!' in str(exec_info.value), \
        "Board's pieces list was bigger than dimensions, but did not fail initialization!"

    with pytest.raises(Exception) as exec_info:
        Board([Fire, Water, Wood, Dark, Light, Heart, Poison, Jammer, Unknown], 0, 3)
    assert 'Given pieces do not fit specified board dimensions!' in str(exec_info.value), "Board's row was invalid, but did not fail initialization!"

def test_board_setup():
    # as long as length of piece list is equal to row x column, the board yields no error and loads from top left down to bottom right
    b = Board([Fire, Water, Wood, Dark, Light, Heart], 2, 3)
    assert isinstance(b, Board), "Board valid 2x3, but was not instantiated!"
    assert isinstance(b.cell(0, 0), Fire), "Unexpected piece @ 0,0 on 2x3 Board!"
    assert isinstance(b.cell(0, 1), Water), "Unexpected piece @ 0,1 on 2x3 Board!"
    assert isinstance(b.cell(0, 2), Wood), "Unexpected piece @ 0,2 on 2x3 Board!"
    assert isinstance(b.cell(1, 0), Dark), "Unexpected piece @ 1,0 on 2x3 Board!"
    assert isinstance(b.cell(1, 1), Light), "Unexpected piece @ 1,1 on 2x3 Board!"
    assert isinstance(b.cell(1, 2), Heart), "Unexpected piece @ 1,2 on 2x3 Board!"
    assert b.rows == 2, "2x3 board has incorrect rows property!"
    assert b.columns == 3, "2x3 board has incorrect columns property!"
    assert len(b.board) == 2 and len(b.board[0]) == 3, "2x3 board has incorrect board dimensions!"

    b = Board([Fire, Water, Wood, Dark, Light, Heart], 3, 2)
    assert isinstance(b, Board), "Board valid 3x2, but was not instantiated!"
    assert isinstance(b.cell(0, 0), Fire), "Unexpected piece @ 0,0 on 3x2 Board!"
    assert isinstance(b.cell(0, 1), Water), "Unexpected piece @ 0,1 on 3x2 Board!"
    assert isinstance(b.cell(1, 0), Wood), "Unexpected piece @ 1,0 on 3x2 Board!"
    assert isinstance(b.cell(1, 1), Dark), "Unexpected piece @ 1,1 on 3x2 Board!"
    assert isinstance(b.cell(2, 0), Light), "Unexpected piece @ 2,0 on 3x2 Board!"
    assert isinstance(b.cell(2, 1), Heart), "Unexpected piece @ 2,1 on 3x2 Board!"
    assert b.rows == 3, "3x2 board has incorrect rows property!"
    assert b.columns == 2, "3x2 board has incorrect columns property!"
    assert len(b.board) == 3 and len(b.board[0]) == 2, "3x2 board has incorrect board dimensions!"

def test_empty_board():
    # empty board should contain only Unknown pieces
    b = Board.create_empty_board(5, 6)
    unknown_pieces = [b.cell(r, c) for c in range(b.columns) for r in range(b.rows) if isinstance(b.cell(r, c), Unknown)]
    assert len(unknown_pieces) == 30, "Creating empty board does not contain only Unknown pieces!"

def test_randomized_board():
    # randomized board should contain only Fire, Water, Wood, Dark, Light, and Heart pieces
    allowed_pieces = set([Fire, Water, Wood, Dark, Light, Heart])
    b = Board.create_randomized_board(5, 6)
    pieces = [b.cell(r, c) for c in range(b.columns) for r in range(b.rows) if isinstance(b.cell(r, c), tuple(allowed_pieces))]
    assert len(pieces) == 30, "Creating randomized board contains invalid pieces!"

def test_copy_board():
    # copying a board produces another board with same setup as original
    original = Board.create_randomized_board(5, 6)
    copy = Board.copy_board(original)

    assert original.rows == copy.rows, "Copied board's rows do not match original!"
    assert original.columns == copy.columns, "Copied board's columns do not match original!"
    matching = [copy.cell(r, c)
                for c in range(original.columns) for r in range(original.rows)
                if isinstance(original.cell(r, c), type(copy.cell(r, c))) and original.cell(r, c).location == copy.cell(r, c).location]
    assert len(matching) == 30, "Copied board's board does not match original!"

def test_match_finding(board_with_3_chain, board_with_1_chain, board_with_0_chain):
    # getting matches should find all chains on the board and their correct sizes
    m = dict((piece.symbol, clusters) for piece, clusters in board_with_3_chain.get_matches())

    assert len(m.keys()) == 3, "Board with 3 chains did not yield correct match count of 3!"
    assert len(m[Fire.symbol]) == 3, "Board's Fire match is not expected 3!"
    assert (0, 0) in m[Fire.symbol], "Piece @ 0,0 is issing from 3-chain Board's Fire match list!"
    assert (1, 0) in m[Fire.symbol], "Piece @ 1,0 is issing from 3-chain Board's Fire match list!"
    assert (2, 0) in m[Fire.symbol], "Piece @ 2,0 is issing from 3-chain Board's Fire match list!"
    assert len(m[Light.symbol]) == 3, "Board's Light match is not expected 3!"
    assert (4, 3) in m[Light.symbol], "Piece @ 4,3 is issing from 3-chain Board's Light match list!"
    assert (4, 4) in m[Light.symbol], "Piece @ 4,4 is issing from 3-chain Board's Light match list!"
    assert (4, 5) in m[Light.symbol], "Piece @ 4,5 is issing from 3-chain Board's Light match list!"
    assert len(m[Water.symbol]) == 4, "Board's Water match is not expected 4!"
    assert (1, 1) in m[Water.symbol], "Piece @ 1,1 is issing from 3-chain Board's Water match list!"
    assert (2, 1) in m[Water.symbol], "Piece @ 2,1 is issing from 3-chain Board's Water match list!"
    assert (3, 1) in m[Water.symbol], "Piece @ 3,1 is issing from 3-chain Board's Water match list!"
    assert (4, 1) in m[Water.symbol], "Piece @ 4,1 is issing from 3-chain Board's Water match list!"

    m = dict((piece.symbol, clusters) for piece, clusters in board_with_1_chain.get_matches())
    assert len(m.keys()) == 1, "Board with 1 chain did not yield correct match count of 1!"
    assert len(m[Water.symbol]) == 5, "Board's Water match is not expected 5!"
    assert (1, 1) in m[Water.symbol], "Piece @ 1,1 is issing from 1-chain Board's Water match list!"
    assert (2, 1) in m[Water.symbol], "Piece @ 2,1 is issing from 1-chain Board's Water match list!"
    assert (3, 1) in m[Water.symbol], "Piece @ 3,1 is issing from 1-chain Board's Water match list!"
    assert (1, 0) in m[Water.symbol], "Piece @ 1,0 is issing from 1-chain Board's Water match list!"
    assert (1, 2) in m[Water.symbol], "Piece @ 1,2 is issing from 1-chain Board's Water match list!"

    m = dict((piece.symbol, clusters) for piece, clusters in board_with_0_chain.get_matches())
    assert len(m.keys()) == 0, "Board with 0 chain did not yield correct match count of 0!"

def test_cluster_finding(board_with_0_chain):
    # clusters on a cell should return all adjacent neighbors of the same piece
    c = board_with_0_chain.get_cluster(2, 1)
    assert isinstance(c[0], Fire), "Cluster @ 2,1 is not the expected Fire piece!"
    assert len(c[1]) == 3, "Cluster @ 2,1 does not have expected count of 3!"

    c = board_with_0_chain.get_cluster(1, 2)
    assert isinstance(c[0], Fire), "Cluster @ 1,2 is not the expected Fire piece!"
    assert len(c[1]) == 1, "Cluster @ 1,2 does not have expected count of 1!"

    c = board_with_0_chain.get_cluster(0, 0)
    assert isinstance(c[0], Unknown), "Cluster @ 0,0 is not the expected Fire piece!"
    assert len(c[1]) == 26, "Cluster @ 0,0 does not have expected count of 26!"

def test_cell_update():
    # updating a board's cell should update that cell only
    original = Board.create_randomized_board(5, 6)
    updated_board = Board.copy_board(original).update(3, 4, Jammer)
    matching = [
        updated_board.cell(r, c)
        for c in range(original.columns) for r in range(original.rows)
        if isinstance(original.cell(r, c), type(updated_board.cell(r, c))) and original.cell(r, c).location == updated_board.cell(r, c).location
    ]
    assert len(matching) == 29, "Updating board did not yield expected matching cells with original board!"
    assert isinstance(updated_board.cell(3, 4), Jammer), "Piece @ 3,4 was not updated to correct piece!"

def test_cell_swap(board_with_1_chain):
    # swapping a board's cell with another should only affect the source and target cells
    original = board_with_1_chain
    swapped_board = Board.copy_board(original)
    # swap corners where the two pieces are different
    swapped_board.swap(0, 0, 4, 5)

    matching = [
        swapped_board.cell(r, c)
        for c in range(original.columns) for r in range(original.rows)
        if isinstance(original.cell(r, c), type(swapped_board.cell(r, c))) and original.cell(r, c).location == swapped_board.cell(r, c).location
    ]
    assert len(matching) == 28, "Swapping upper left corner with lower right corner of board yielded match counts!"
    assert swapped_board.cell(0, 0).location == (0, 0), "Swapped piece @ 0,0 has invalid location!"
    assert swapped_board.cell(4, 5).location == (4, 5), "Swapped piece @ 4,5 has invalid location!"
    assert isinstance(swapped_board.cell(0, 0), type(original.cell(4, 5))), "Swapped piece @ 0,0 does not match original piece @ 4,5!"
    assert isinstance(swapped_board.cell(4, 5), type(original.cell(0, 0))), "Swapped piece @ 4,5 does not match original piece @ 0,0!"

    # swap multiple times should yield expected results
    original = Board.create_randomized_board(5, 6)
    swapped_board = Board.copy_board(original)
    swapped_board.swap(0, 0, 1, 1)
    swapped_board.swap(1, 1, 2, 2)
    swapped_board.swap(2, 2, 3, 3)
    swapped_board.swap(3, 3, 4, 4)
    assert isinstance(swapped_board.cell(0, 0), type(original.cell(1, 1))), "Swapped piece @ 0,0 does not match original @ 1,1"
    assert isinstance(swapped_board.cell(1, 1), type(original.cell(2, 2))), "Swapped piece @ 1,1 does not match original @ 2,2"
    assert isinstance(swapped_board.cell(2, 2), type(original.cell(3, 3))), "Swapped piece @ 2,2 does not match original @ 3,3"
    assert isinstance(swapped_board.cell(3, 3), type(original.cell(4, 4))), "Swapped piece @ 3,3 does not match original @ 4,4"
    assert isinstance(swapped_board.cell(4, 4), type(original.cell(0, 0))), "Swapped piece @ 4,4 does not match original @ 0,0"

def test_board_hash(board_with_0_chain, board_with_1_chain, board_with_3_chain):
    # make sure hash method returns string sequence of board going from top-left to down to bottom right (rows and then columns)
    assert board_with_0_chain.hash() == '????????R????R?????RR?????????', "Board hash yielded unexpected sequence for first test!"
    assert board_with_1_chain.hash() == 'RGBPY@BBBYH#RBPHHGYBYRGGPHPYHY', "Board hash yielded unexpected sequence for second test!"
    assert board_with_3_chain.hash() == 'RGBPYHRBPYHRRBPHHGYBYRGGPBPYYY', "Board hash yielded unexpected sequence for third test!"


text:
const hat = require('hat');
const hash = require('../lib/hash');
// eslint-disable-next-line import/no-extraneous-dependencies
const chai = require('chai');

const expect = chai.expect;

// eslint-disable-next-line no-undef
describe('#AppRTC-socket utils', () => {
  // eslint-disable-next-line no-undef
  it('hash function should be commutative', () => {
    const value1 = hat();
    const value2 = hat();
    expect(hash(value1, value2)).to.equal(hash(value2, value1));
  });
});


text:
class HomepageController < ApplicationController
  def index
    @beer_taps = BeerTap.order(:display_order)
    @pours = Pour.where("volume IS NOT NULL").order("created_at desc").limit(@beer_taps.size * 3)
  end
end


text:
import ConnectionError from '../connection-error';

/**
 * Thrown when a connection to a database times out
 */
class ConnectionTimedOutError extends ConnectionError {
  constructor(cause: Error) {
    super(cause);
    this.name = 'SequelizeConnectionTimedOutError';
  }
}

export default ConnectionTimedOutError;


text:
Restaurant Add/Drop/Vendor Editor

						Done


text:
<?php
/*
Template Name: Kontakt
*/
?>

<?php get_template_part('templates/page', 'header'); ?>
<?php get_template_part('templates/content', 'page-kontakt'); ?>


text:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using System.Web;

namespace DevCamp.WebApp.Utils
{
	public class StorageHelper
	{
		/// <summary>
		/// Adds an incident message to the queue
		/// </summary>
		/// <param name="IncidentId">The incident ID from the service</param>
		/// <param name="ImageFileName">The file name of the image</param>
		/// <returns></returns>
		public static async Task AddMessageToQueue(string IncidentId, string ImageFileName)
		{
			CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Settings.AZURE_STORAGE_CONNECTIONSTRING);
			CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
			CloudQueue msgQ = queueClient.GetQueueReference(Settings.AZURE_STORAGE_QUEUE);
			msgQ.CreateIfNotExists();

			JObject qMsgJson = new JObject();
			qMsgJson.Add("IncidentId", IncidentId);
			qMsgJson.Add("BlobContainerName", Settings.AZURE_STORAGE_BLOB_CONTAINER);
			qMsgJson.Add("BlobName", getIncidentBlobFilename(IncidentId, ImageFileName));

			var qMsgPayload = JsonConvert.SerializeObject(qMsgJson);
			CloudQueueMessage qMsg = new CloudQueueMessage(qMsgPayload);

			await msgQ.AddMessageAsync(qMsg);
		}

		/// <summary>
		/// Uploads a blob to the configured storage account
		/// </summary>
		/// <param name="IncidentId">The IncidentId the image is associated with</param>
		/// <param name="imageFile">The File</param>
		/// <returns>The Url to the blob</returns>
		public static async Task<string> UploadFileToBlobStorage(string IncidentId, HttpPostedFileBase imageFile)
		{
			string imgUri = string.Empty;

			try
			{
				CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Settings.AZURE_STORAGE_CONNECTIONSTRING);

				CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
				CloudBlobContainer container = blobClient.GetContainerReference(Settings.AZURE_STORAGE_BLOB_CONTAINER);
				container.CreateIfNotExists();
				container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

				CloudBlockBlob imgBlob = container.GetBlockBlobReference(getIncidentBlobFilename(IncidentId, imageFile.FileName));
				imgBlob.Properties.ContentType = imageFile.ContentType;
				await imgBlob.UploadFromStreamAsync(imageFile.InputStream);

				var uriBuilder = new UriBuilder(imgBlob.Uri);
				uriBuilder.Scheme = "https";
				imgUri = uriBuilder.ToString();
			}
			catch (Exception ex)
			{
				throw new HttpUnhandledException($"Unable to upload image for incident {IncidentId} to blob storage. Error:: ${ex.ToString()}");
			}
			return imgUri;
		}

		private static string getIncidentBlobFilename(string IncidentId, string FileName)
		{
			string fileExt = Path.GetExtension(FileName);
			//Remove the starting . if exists
			if (fileExt.StartsWith("."))
			{
				fileExt.TrimStart(new char[] { '.' });
			}
			return $"{IncidentId}{fileExt}";
		}
	}
}


text:
package kafka.server

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicReference
import java.util.{Collections, Properties}

import kafka.controller.KafkaController
import kafka.coordinator.group.GroupCoordinator
import kafka.coordinator.transaction.TransactionCoordinator
import kafka.utils.Logging
import org.apache.kafka.clients.ClientResponse
import org.apache.kafka.common.errors.InvalidTopicException
import org.apache.kafka.common.internals.Topic
import org.apache.kafka.common.internals.Topic.{GROUP_METADATA_TOPIC_NAME, TRANSACTION_STATE_TOPIC_NAME}
import org.apache.kafka.common.message.CreateTopicsRequestData
import org.apache.kafka.common.message.CreateTopicsRequestData.{CreatableTopic, CreateableTopicConfig, CreateableTopicConfigCollection}
import org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopic
import org.apache.kafka.common.protocol.{ApiKeys, Errors}
import org.apache.kafka.common.requests.{ApiError, CreateTopicsRequest, RequestContext, RequestHeader}

import scala.collection.{Map, Seq, Set, mutable}
import scala.jdk.CollectionConverters._

trait AutoTopicCreationManager {

  def createTopics(
    topicNames: Set[String],
    controllerMutationQuota: ControllerMutationQuota,
    metadataRequestContext: Option[RequestContext]
  ): Seq[MetadataResponseTopic]
}

object AutoTopicCreationManager {

  def apply(
    config: KafkaConfig,
    metadataCache: MetadataCache,
    threadNamePrefix: Option[String],
    channelManager: Option[BrokerToControllerChannelManager],
    adminManager: Option[ZkAdminManager],
    controller: Option[KafkaController],
    groupCoordinator: GroupCoordinator,
    txnCoordinator: TransactionCoordinator,
  ): AutoTopicCreationManager = {
    new DefaultAutoTopicCreationManager(config, channelManager, adminManager,
      controller, groupCoordinator, txnCoordinator)
  }
}

class DefaultAutoTopicCreationManager(
  config: KafkaConfig,
  channelManager: Option[BrokerToControllerChannelManager],
  adminManager: Option[ZkAdminManager],
  controller: Option[KafkaController],
  groupCoordinator: GroupCoordinator,
  txnCoordinator: TransactionCoordinator
) extends AutoTopicCreationManager with Logging {
  if (controller.isEmpty && channelManager.isEmpty) {
    throw new IllegalArgumentException("Must supply a channel manager if not supplying a controller")
  }

  private val inflightTopics = Collections.newSetFromMap(new ConcurrentHashMap[String, java.lang.Boolean]())

  /**
   * Initiate auto topic creation for the given topics.
   *
   * @param topics the topics to create
   * @param controllerMutationQuota the controller mutation quota for topic creation
   * @param metadataRequestContext defined when creating topics on behalf of the client. The goal here is to preserve
   *                               original client principal for auditing, thus needing to wrap a plain CreateTopicsRequest
   *                               inside Envelope to send to the controller when forwarding is enabled.
   * @return auto created topic metadata responses
   */
  override def createTopics(
    topics: Set[String],
    controllerMutationQuota: ControllerMutationQuota,
    metadataRequestContext: Option[RequestContext]
  ): Seq[MetadataResponseTopic] = {
    val (creatableTopics, uncreatableTopicResponses) = filterCreatableTopics(topics)

    val creatableTopicResponses = if (creatableTopics.isEmpty) {
      Seq.empty
    } else if (controller.isEmpty || !controller.get.isActive && channelManager.isDefined) {
      sendCreateTopicRequest(creatableTopics, metadataRequestContext)
    } else {
      createTopicsInZk(creatableTopics, controllerMutationQuota)
    }

    uncreatableTopicResponses ++ creatableTopicResponses
  }

  private def createTopicsInZk(
    creatableTopics: Map[String, CreatableTopic],
    controllerMutationQuota: ControllerMutationQuota
  ): Seq[MetadataResponseTopic] = {
    val topicErrors = new AtomicReference[Map[String, ApiError]]()
    try {
      // Note that we use timeout = 0 since we do not need to wait for metadata propagation
      // and we want to get the response error immediately.
      adminManager.get.createTopics(
        timeout = 0,
        validateOnly = false,
        creatableTopics,
        Map.empty,
        controllerMutationQuota,
        topicErrors.set
      )

      val creatableTopicResponses = Option(topicErrors.get) match {
        case Some(errors) =>
          errors.toSeq.map { case (topic, apiError) =>
            val error = apiError.error match {
              case Errors.TOPIC_ALREADY_EXISTS | Errors.REQUEST_TIMED_OUT =>
                // The timeout error is expected because we set timeout=0. This
                // nevertheless indicates that the topic metadata was created
                // successfully, so we return LEADER_NOT_AVAILABLE.
                Errors.LEADER_NOT_AVAILABLE
              case error => error
            }

            new MetadataResponseTopic()
              .setErrorCode(error.code)
              .setName(topic)
              .setIsInternal(Topic.isInternal(topic))
          }

        case None =>
          creatableTopics.keySet.toSeq.map { topic =>
            new MetadataResponseTopic()
              .setErrorCode(Errors.UNKNOWN_TOPIC_OR_PARTITION.code)
              .setName(topic)
              .setIsInternal(Topic.isInternal(topic))
          }
      }

      creatableTopicResponses
    } finally {
      clearInflightRequests(creatableTopics)
    }
  }

  private def sendCreateTopicRequest(
    creatableTopics: Map[String, CreatableTopic],
    metadataRequestContext: Option[RequestContext]
  ): Seq[MetadataResponseTopic] = {
    val topicsToCreate = new CreateTopicsRequestData.CreatableTopicCollection(creatableTopics.size)
    topicsToCreate.addAll(creatableTopics.values.asJavaCollection)

    val createTopicsRequest = new CreateTopicsRequest.Builder(
      new CreateTopicsRequestData()
        .setTimeoutMs(config.requestTimeoutMs)
        .setTopics(topicsToCreate)
    )

    val requestCompletionHandler = new ControllerRequestCompletionHandler {
      override def onTimeout(): Unit = {
        debug(s"Auto topic creation timed out for ${creatableTopics.keys}.")
        clearInflightRequests(creatableTopics)
      }

      override def onComplete(response: ClientResponse): Unit = {
        debug(s"Auto topic creation completed for ${creatableTopics.keys} with response ${response.responseBody.toString}.")
        clearInflightRequests(creatableTopics)
      }
    }

    val channelManager = this.channelManager.getOrElse {
      throw new IllegalStateException("Channel manager must be defined in order to send CreateTopic requests.")
    }

    val request = metadataRequestContext.map { context =>
      val requestVersion =
        channelManager.controllerApiVersions() match {
          case None =>
            // We will rely on the Metadata request to be retried in the case
            // that the latest version is not usable by the controller.
            ApiKeys.CREATE_TOPICS.latestVersion()
          case Some(nodeApiVersions) =>
            nodeApiVersions.latestUsableVersion(ApiKeys.CREATE_TOPICS)
        }

      // Borrow client information such as client id and correlation id from the original request,
      // in order to correlate the create request with the original metadata request.
      val requestHeader = new RequestHeader(ApiKeys.CREATE_TOPICS,
        requestVersion,
        context.clientId,
        context.correlationId)
      ForwardingManager.buildEnvelopeRequest(context,
        createTopicsRequest.build(requestVersion).serializeWithHeader(requestHeader))
    }.getOrElse(createTopicsRequest)

    channelManager.sendRequest(request, requestCompletionHandler)

    val creatableTopicResponses = creatableTopics.keySet.toSeq.map { topic =>
      new MetadataResponseTopic()
        .setErrorCode(Errors.UNKNOWN_TOPIC_OR_PARTITION.code)
        .setName(topic)
        .setIsInternal(Topic.isInternal(topic))
    }

    info(s"Sent auto-creation request for ${creatableTopics.keys} to the active controller.")
    creatableTopicResponses
  }

  private def clearInflightRequests(creatableTopics: Map[String, CreatableTopic]): Unit = {
    creatableTopics.keySet.foreach(inflightTopics.remove)
    debug(s"Cleared inflight topic creation state for $creatableTopics")
  }

  private def creatableTopic(topic: String): CreatableTopic = {
    topic match {
      case GROUP_METADATA_TOPIC_NAME =>
        new CreatableTopic()
          .setName(topic)
          .setNumPartitions(config.offsetsTopicPartitions)
          .setReplicationFactor(config.offsetsTopicReplicationFactor)
          .setConfigs(convertToTopicConfigCollections(groupCoordinator.offsetsTopicConfigs))
      case TRANSACTION_STATE_TOPIC_NAME =>
        new CreatableTopic()
          .setName(topic)
          .setNumPartitions(config.transactionTopicPartitions)
          .setReplicationFactor(config.transactionTopicReplicationFactor)
          .setConfigs(convertToTopicConfigCollections(
            txnCoordinator.transactionTopicConfigs))
      case topicName =>
        new CreatableTopic()
          .setName(topicName)
          .setNumPartitions(config.numPartitions)
          .setReplicationFactor(config.defaultReplicationFactor.shortValue)
    }
  }

  private def convertToTopicConfigCollections(config: Properties): CreateableTopicConfigCollection = {
    val topicConfigs = new CreateableTopicConfigCollection()
    config.forEach {
      case (name, value) =>
        topicConfigs.add(new CreateableTopicConfig()
          .setName(name.toString)
          .setValue(value.toString))
    }
    topicConfigs
  }

  private def isValidTopicName(topic: String): Boolean = {
    try {
      Topic.validate(topic)
      true
    } catch {
      case _: InvalidTopicException =>
        false
    }
  }

  private def filterCreatableTopics(
    topics: Set[String]
  ): (Map[String, CreatableTopic], Seq[MetadataResponseTopic]) = {

    val creatableTopics = mutable.Map.empty[String, CreatableTopic]
    val uncreatableTopics = mutable.Buffer.empty[MetadataResponseTopic]

    topics.foreach { topic =>
      // Attempt basic topic validation before sending any requests to the controller.
      val validationError: Option[Errors] = if (!isValidTopicName(topic)) {
        Some(Errors.INVALID_TOPIC_EXCEPTION)
      } else if (!inflightTopics.add(topic)) {
        Some(Errors.UNKNOWN_TOPIC_OR_PARTITION)
      } else {
        None
      }

      validationError match {
        case Some(error) =>
          uncreatableTopics += new MetadataResponseTopic()
            .setErrorCode(error.code)
            .setName(topic)
            .setIsInternal(Topic.isInternal(topic))
        case None =>
          creatableTopics.put(topic, creatableTopic(topic))
      }
    }

    (creatableTopics, uncreatableTopics)
  }
}


text:
layout: default
title: Workshops
---

            ⇦ Back to Cases

Workshops

Our comprehensive tutorials will walk you through step by step on how to perform different types of data analysis.

            <button class="white-text med-width sm-margin-bottom submit btn btn-main featured small">Record Linkage Tutorial</button>