text:
package com.hutong.supersdk.sdk.handler.and;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.hutong.supersdk.common.constant.DataKeys;
import com.hutong.supersdk.common.model.JsonReqObj;
import com.hutong.supersdk.common.model.JsonResObj;
import com.hutong.supersdk.common.util.EncryptUtil;
import com.hutong.supersdk.common.util.HttpUtil;
import com.hutong.supersdk.common.util.ParseJson;
import com.hutong.supersdk.sdk.IVerifyUserSDK;
import com.hutong.supersdk.sdk.modeltools.SDKVerifyRet;
import com.hutong.supersdk.sdk.modeltools.wuyou.WuYouSDKInfo;

@Component("andWuYouSDK")
public class AndWuYouSDK implements IVerifyUserSDK {

	private static final String SDK_ID = "AndWuYou";

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

	@Override
	public String getSDKId() {
		return SDK_ID;
	}

	@Override
	public Class<?> getConfigClazz() {
		return WuYouSDKInfo.class;
	}

	@Override
	public SDKVerifyRet verifyUser(JsonReqObj input, Object config) {
		SDKVerifyRet ret = new SDKVerifyRet();
		try {
			WuYouSDKInfo configInfo = (WuYouSDKInfo) config;
			// 获取参数
			String token = input.getSDKAccessToken();
			String secretKey = configInfo.getSecretKey();
			String appId = input.getExtraKey(DataKeys.Platform.APP_ID);
			String uid = input.getSdkUid();

			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put(DataKeys.Platform.PLATFORM_USER_TOKEN, token);
			paramMap.put(DataKeys.Platform.PLATFORM_USER_ID, uid);
			paramMap.put(DataKeys.Platform.APP_ID, appId);
			String sign = EncryptUtil.generateSign(paramMap, secretKey);
			// 组装请求参数
			String url = configInfo.getRequestUrl();
			JsonReqObj jsonData = new JsonReqObj();

			jsonData.setTime(String.valueOf(System.currentTimeMillis()));
			jsonData.setData(paramMap);
			jsonData.setSign(sign);

			String jsonDataStr = ParseJson.encodeJson(jsonData);
			paramMap.clear();
			paramMap.put("jsonData", jsonDataStr);

			String result = HttpUtil.postForm(url, paramMap);
			JsonResObj jsonRes = ParseJson.getJsonContentByStr(result, JsonResObj.class);
			if (jsonRes != null && jsonRes.isStatusOk()) {
				ret.setSdkUid(jsonRes.getData().get("id"));
				ret.setSdkAccessToken(token);
				return ret.success();
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		ret.setErrorMsg(this.getSDKId() + " verifyUser Error !");
		return ret.fail();
	}

}


text:
@import url('../Aqua/Stylesheet.css');

ul.tree-menu li div a.soundcloud, ul.tree-menu li div a.type_soundcloud,
	ul.tree-menu li div a.type_soundcloud_default {
	background-image: url(../../Images/Ruby/Logo/16.png);
}

redpajama_set_name: RedPajamaGithub


text:
import { ConfigurationManager } from './config/ConfigurationManager';
import { ResultsManager } from './results/ResultsManager';
import { BenchmarksManager } from './benchmarks/BenchmarksManager';
import { ParametersManager } from './parameters/ParametersManager';
import { ExecutionManager } from './execution/ExecutionManager';
import { ReportGenerator } from './reports/ReportGenerator';
import { EnvironmentManager } from './environment/EnvironmentManager';

export class BenchmarkRunner {
    private _configuration: ConfigurationManager;
    private _results: ResultsManager;
    private _parameters: ParametersManager;
    private _benchmarks: BenchmarksManager;
    private _execution: ExecutionManager;
    private _report: ReportGenerator;
    private _environment: EnvironmentManager;

    public constructor() {
        this._configuration = new ConfigurationManager();
        this._results = new ResultsManager();
        this._parameters = new ParametersManager(this._configuration);
        this._benchmarks = new BenchmarksManager(this._parameters);
        this._execution = new ExecutionManager(this._configuration, this._results);
        this._environment = new EnvironmentManager();
        this._report = new ReportGenerator(this._configuration, this._results,
            this._parameters, this._benchmarks, this._environment);
    }

    public get configuration(): ConfigurationManager {
        return this._configuration;
    }

    public get results(): ResultsManager {
        return this._results;
    }

    public get parameters(): ParametersManager {
        return this._parameters;
    }

    public get execution(): ExecutionManager {
        return this._execution;
    }

    public get benchmarks(): BenchmarksManager {
        return this._benchmarks;
    }

    public get report(): ReportGenerator {
        return this._report;
    }

    public get environment(): EnvironmentManager {
        return this._environment;
    }

    public get isRunning(): boolean {
        return this._execution.isRunning;
    }

    public start(): void {
        this._execution.start(this._benchmarks.isSelected);
    }

    public stop(): void {
        this._execution.stop();
    }

    public run(callback: (err: any) => void): void {
        this._execution.run(this._benchmarks.isSelected, callback);
    }
}


text:
package com.appglu.android.storage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import android.graphics.Bitmap;

import com.appglu.AppGluRestClientException;
import com.appglu.InputStreamCallback;
import com.appglu.StorageFile;
import com.appglu.StorageOperations;
import com.appglu.android.AppGlu;
import com.appglu.android.cache.CacheManager;
import com.appglu.android.log.Logger;
import com.appglu.android.log.LoggerFactory;
import com.appglu.android.util.AppGluUtils;
import com.appglu.impl.util.HashUtils;
import com.appglu.impl.util.IOUtils;

public class StorageService {

	private Logger logger = LoggerFactory.getLogger(AppGlu.LOG_TAG);

	private StorageOperations storageOperations;

	private CacheManager cacheManager;

	private static final long DEFAULT_CACHE_TIME_TO_LIVE_IN_MILLISECONDS = 60 * 60 * 1000; //1 hour

	private long cacheTimeToLiveInMilliseconds = DEFAULT_CACHE_TIME_TO_LIVE_IN_MILLISECONDS;

	public StorageService(StorageOperations storageOperations, CacheManager cacheManager) {
		this.storageOperations = storageOperations;
		this.cacheManager = cacheManager;
	}

	public void setCacheTimeToLiveInMilliseconds(long cacheTimeToLiveInMilliseconds) {
		if (cacheTimeToLiveInMilliseconds > 0) {
			this.cacheTimeToLiveInMilliseconds = cacheTimeToLiveInMilliseconds;
		}
	}

	protected String cacheKeyForStorageFile(StorageFile file) {
		if (file == null || !file.hasUrl()) {
			return null;
		}
		String hash = String.valueOf(file.getUrl().hashCode());
		return HashUtils.toHexString(hash);
	}

	/*
	 * Retrieve only from local cache methods
	 */

	public InputStream retrieveInputStreamFromCacheManager(StorageFile file) {
		String cacheKey = this.cacheKeyForStorageFile(file);

		if (this.cacheManager.exists(cacheKey)) {
			Date lastModifiedDate = this.cacheManager.lastModifiedDate(cacheKey);

			if (lastModifiedDate != null) {
				long now = System.currentTimeMillis();
				long lastModified = lastModifiedDate.getTime();

				if ( (lastModified + this.cacheTimeToLiveInMilliseconds) >= now ) {
					return this.cacheManager.retrieve(cacheKey);
				}
			}
		}

		return null;
	}

	public byte[] retrieveByteArrayFromCacheManager(StorageFile file) {
		InputStream inputStream = this.retrieveInputStreamFromCacheManager(file);

		if (inputStream == null) {
			return null;
		}

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try {
			IOUtils.copy(inputStream, outputStream);
		} catch (IOException e) {
			return null;
		}

		return outputStream.toByteArray();
	}

	public Bitmap retrieveBitmapFromCacheManager(StorageFile file) {
		InputStream inputStream = this.retrieveInputStreamFromCacheManager(file);

		if (inputStream == null) {
			return null;
		}

		return AppGluUtils.decodeBitmapFromInputStream(inputStream);
	}

	public Bitmap retrieveBitmapFromCacheManager(StorageFile file, int inSampleSize) {
		InputStream inputStream = this.retrieveInputStreamFromCacheManager(file);

		if (inputStream == null) {
			return null;
		}

		return AppGluUtils.decodeSampledBitmapFromInputStream(inputStream, inSampleSize);
	}

	public Bitmap retrieveBitmapFromCacheManager(StorageFile file, int requestedWidth, int requestedHeight) {
		byte[] imageBytes = this.retrieveByteArrayFromCacheManager(file);

		if (imageBytes == null) {
			return null;
		}

		return AppGluUtils.decodeSampledBitmapFromByteArray(imageBytes, requestedWidth, requestedHeight);
	}

	/*
	 * Download from network methods
	 */

	public InputStream downloadAsInputStream(final StorageFile file) {
		final String cacheKey = this.cacheKeyForStorageFile(file);

		if (this.cacheManager.exists(cacheKey)) {
			Date lastModifiedDate = this.cacheManager.lastModifiedDate(cacheKey);

			if (lastModifiedDate != null) {
				long now = System.currentTimeMillis();
				long lastModified = lastModifiedDate.getTime();

				if ( (lastModified + this.cacheTimeToLiveInMilliseconds) >= now ) {
					if (logger.isVerboseEnabled()) {
						logger.verbose("Retrieving '" + cacheKey + "' from cache");
					}
					return this.cacheManager.retrieve(cacheKey);
				}

				file.setLastModified(lastModifiedDate);
			}
		}

		try {
			boolean wasModified = this.storageOperations.streamStorageFileIfModifiedSince(file, new InputStreamCallback() {
				public void doWithInputStream(InputStream inputStream) throws IOException {
					if (logger.isVerboseEnabled()) {
						logger.verbose("Downloading '" + cacheKey + "' from network");
					}
					cacheManager.store(cacheKey, inputStream);
				}
			});

			if (!wasModified) {
				if (logger.isVerboseEnabled()) {
					logger.verbose("Updating '" + cacheKey + "' last modified date");
				}
				this.cacheManager.updateLastModifiedDate(cacheKey);
			}
		} catch (AppGluRestClientException e) {

			if (this.cacheManager.exists(cacheKey)) {
				if (logger.isErrorEnabled()) {
					logger.error("Error while loading '" + cacheKey + "' from network, loading from cache instead", e);
				}

				return this.cacheManager.retrieve(cacheKey);
			}

			throw e;
		}

		return this.cacheManager.retrieve(cacheKey);
	}

	public byte[] downloadAsByteArray(StorageFile file) {
		InputStream inputStream = this.downloadAsInputStream(file);

		if (inputStream == null) {
			return null;
		}

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try {
			IOUtils.copy(inputStream, outputStream);
		} catch (IOException e) {
			return null;
		}

		return outputStream.toByteArray();
	}

	public Bitmap downloadAsBitmap(StorageFile file) {
		InputStream inputStream = this.downloadAsInputStream(file);

		if (inputStream == null) {
			return null;
		}

		return AppGluUtils.decodeBitmapFromInputStream(inputStream);
	}

	public Bitmap downloadAsBitmap(StorageFile file, int inSampleSize) {
		InputStream inputStream = this.downloadAsInputStream(file);

		if (inputStream == null) {
			return null;
		}

		return AppGluUtils.decodeSampledBitmapFromInputStream(inputStream, inSampleSize);
	}

	public Bitmap downloadAsBitmap(StorageFile file, int requestedWidth, int requestedHeight) {
		byte[] imageBytes = this.downloadAsByteArray(file);

		if (imageBytes == null) {
			return null;
		}

		return AppGluUtils.decodeSampledBitmapFromByteArray(imageBytes, requestedWidth, requestedHeight);
	}

}


text:
using NRets.Models;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace NRets.Parsers
{
    public interface IReplyParser
    {
        RetsReply Parse(string replyText);
    }

    public class ReplyParser : IReplyParser
    {
        public RetsReply Parse(string replyText)
        {
            var textReader = new StringReader(replyText);
            var document = XDocument.Load(textReader);
            var ns = document.Root.GetDefaultNamespace();
            var root = document.Root;
            var retsResponse = root.Descendants(ns + "RETS-RESPONSE").FirstOrDefault();

            return new RetsReply
            {
                ReplyCode = root.Attribute("ReplyCode")?.Value,
                ReplyText = root.Attribute("ReplyText")?.Value,
                RetsResponse = retsResponse?.Value
            };
        }
    }
}


text:
namespace Microsoft.Azure.Management.Kusto.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// A class that contains database statistics information.
    /// </summary>
    public partial class DatabaseStatistics
    {
        /// <summary>
        /// Initializes a new instance of the DatabaseStatistics class.
        /// </summary>
        public DatabaseStatistics()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the DatabaseStatistics class.
        /// </summary>
        /// <param name="size">The database size - the total size of compressed
        /// data and index in bytes.</param>
        public DatabaseStatistics(double? size = default(double?))
        {
            Size = size;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the database size - the total size of compressed data
        /// and index in bytes.
        /// </summary>
        [JsonProperty(PropertyName = "size")]
        public double? Size { get; set; }

    }
}


text:
from __future__ import absolute_import

from changes.api.base import APIView
import changes.lib.snapshot_garbage_collection as gc

class CachedSnapshotClusterDetailsAPIView(APIView):
    def get(self, cluster):
        images = gc.get_cached_snapshot_images(cluster)
        return self.respond([image.id for image in images])


text:
package godo

import (
	"context"
	"fmt"
	"net/http"
)

const domainsBasePath = "v2/domains"

// DomainsService is an interface for managing DNS with the DigitalOcean API.
// See: https://developers.digitalocean.com/documentation/v2#domains and
// https://developers.digitalocean.com/documentation/v2#domain-records
type DomainsService interface {
	List(context.Context, *ListOptions) ([]Domain, *Response, error)
	Get(context.Context, string) (*Domain, *Response, error)
	Create(context.Context, *DomainCreateRequest) (*Domain, *Response, error)
	Delete(context.Context, string) (*Response, error)

	Records(context.Context, string, *ListOptions) ([]DomainRecord, *Response, error)
	RecordsByType(context.Context, string, string, *ListOptions) ([]DomainRecord, *Response, error)
	RecordsByName(context.Context, string, string, *ListOptions) ([]DomainRecord, *Response, error)
	RecordsByTypeAndName(context.Context, string, string, string, *ListOptions) ([]DomainRecord, *Response, error)
	Record(context.Context, string, int) (*DomainRecord, *Response, error)
	DeleteRecord(context.Context, string, int) (*Response, error)
	EditRecord(context.Context, string, int, *DomainRecordEditRequest) (*DomainRecord, *Response, error)
	CreateRecord(context.Context, string, *DomainRecordEditRequest) (*DomainRecord, *Response, error)
}

// DomainsServiceOp handles communication with the domain related methods of the
// DigitalOcean API.
type DomainsServiceOp struct {
	client *Client
}

var _ DomainsService = &DomainsServiceOp{}

// Domain represents a DigitalOcean domain
type Domain struct {
	Name     string `json:"name"`
	TTL      int    `json:"ttl"`
	ZoneFile string `json:"zone_file"`
}

// domainRoot represents a response from the DigitalOcean API
type domainRoot struct {
	Domain *Domain `json:"domain"`
}

type domainsRoot struct {
	Domains []Domain `json:"domains"`
	Links   *Links   `json:"links"`
	Meta    *Meta    `json:"meta"`
}

// DomainCreateRequest respresents a request to create a domain.
type DomainCreateRequest struct {
	Name      string `json:"name"`
	IPAddress string `json:"ip_address,omitempty"`
}

// DomainRecordRoot is the root of an individual Domain Record response
type domainRecordRoot struct {
	DomainRecord *DomainRecord `json:"domain_record"`
}

// DomainRecordsRoot is the root of a group of Domain Record responses
type domainRecordsRoot struct {
	DomainRecords []DomainRecord `json:"domain_records"`
	Links         *Links         `json:"links"`
}

// DomainRecord represents a DigitalOcean DomainRecord
type DomainRecord struct {
	ID       int    `json:"id,float64,omitempty"`
	Type     string `json:"type,omitempty"`
	Name     string `json:"name,omitempty"`
	Data     string `json:"data,omitempty"`
	Priority int    `json:"priority"`
	Port     int    `json:"port,omitempty"`
	TTL      int    `json:"ttl,omitempty"`
	Weight   int    `json:"weight"`
	Flags    int    `json:"flags"`
	Tag      string `json:"tag,omitempty"`
}

// DomainRecordEditRequest represents a request to update a domain record.
type DomainRecordEditRequest struct {
	Type     string `json:"type,omitempty"`
	Name     string `json:"name,omitempty"`
	Data     string `json:"data,omitempty"`
	Priority int    `json:"priority"`
	Port     int    `json:"port,omitempty"`
	TTL      int    `json:"ttl,omitempty"`
	Weight   int    `json:"weight"`
	Flags    int    `json:"flags"`
	Tag      string `json:"tag,omitempty"`
}

func (d Domain) String() string {
	return Stringify(d)
}

func (d Domain) URN() string {
	return ToURN("Domain", d.Name)
}

// List all domains.
func (s DomainsServiceOp) List(ctx context.Context, opt *ListOptions) ([]Domain, *Response, error) {
	path := domainsBasePath
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(domainsRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}
	if l := root.Links; l != nil {
		resp.Links = l
	}
	if m := root.Meta; m != nil {
		resp.Meta = m
	}

	return root.Domains, resp, err
}

// Get individual domain. It requires a non-empty domain name.
func (s *DomainsServiceOp) Get(ctx context.Context, name string) (*Domain, *Response, error) {
	if len(name) < 1 {
		return nil, nil, NewArgError("name", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s", domainsBasePath, name)

	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(domainRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Domain, resp, err
}

// Create a new domain
func (s *DomainsServiceOp) Create(ctx context.Context, createRequest *DomainCreateRequest) (*Domain, *Response, error) {
	if createRequest == nil {
		return nil, nil, NewArgError("createRequest", "cannot be nil")
	}

	path := domainsBasePath

	req, err := s.client.NewRequest(ctx, http.MethodPost, path, createRequest)
	if err != nil {
		return nil, nil, err
	}

	root := new(domainRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}
	return root.Domain, resp, err
}

// Delete domain
func (s *DomainsServiceOp) Delete(ctx context.Context, name string) (*Response, error) {
	if len(name) < 1 {
		return nil, NewArgError("name", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s", domainsBasePath, name)

	req, err := s.client.NewRequest(ctx, http.MethodDelete, path, nil)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(ctx, req, nil)

	return resp, err
}

// Converts a DomainRecord to a string.
func (d DomainRecord) String() string {
	return Stringify(d)
}

// Converts a DomainRecordEditRequest to a string.
func (d DomainRecordEditRequest) String() string {
	return Stringify(d)
}

// Records returns a slice of DomainRecord for a domain.
func (s *DomainsServiceOp) Records(ctx context.Context, domain string, opt *ListOptions) ([]DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s/records", domainsBasePath, domain)
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}

	return s.records(ctx, path)
}

// RecordsByType returns a slice of DomainRecord for a domain matched by record type.
func (s *DomainsServiceOp) RecordsByType(ctx context.Context, domain, ofType string, opt *ListOptions) ([]DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	if len(ofType) < 1 {
		return nil, nil, NewArgError("type", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s/records?type=%s", domainsBasePath, domain, ofType)
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}

	return s.records(ctx, path)
}

// RecordsByName returns a slice of DomainRecord for a domain matched by record name.
func (s *DomainsServiceOp) RecordsByName(ctx context.Context, domain, name string, opt *ListOptions) ([]DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	if len(name) < 1 {
		return nil, nil, NewArgError("name", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s/records?name=%s", domainsBasePath, domain, name)
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}

	return s.records(ctx, path)
}

// RecordsByTypeAndName returns a slice of DomainRecord for a domain matched by record type and name.
func (s *DomainsServiceOp) RecordsByTypeAndName(ctx context.Context, domain, ofType, name string, opt *ListOptions) ([]DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	if len(ofType) < 1 {
		return nil, nil, NewArgError("type", "cannot be an empty string")
	}

	if len(name) < 1 {
		return nil, nil, NewArgError("name", "cannot be an empty string")
	}

	path := fmt.Sprintf("%s/%s/records?type=%s&name=%s", domainsBasePath, domain, ofType, name)
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}

	return s.records(ctx, path)
}

// Record returns the record id from a domain
func (s *DomainsServiceOp) Record(ctx context.Context, domain string, id int) (*DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	if id < 1 {
		return nil, nil, NewArgError("id", "cannot be less than 1")
	}

	path := fmt.Sprintf("%s/%s/records/%d", domainsBasePath, domain, id)

	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	record := new(domainRecordRoot)
	resp, err := s.client.Do(ctx, req, record)
	if err != nil {
		return nil, resp, err
	}

	return record.DomainRecord, resp, err
}

// DeleteRecord deletes a record from a domain identified by id
func (s *DomainsServiceOp) DeleteRecord(ctx context.Context, domain string, id int) (*Response, error) {
	if len(domain) < 1 {
		return nil, NewArgError("domain", "cannot be an empty string")
	}

	if id < 1 {
		return nil, NewArgError("id", "cannot be less than 1")
	}

	path := fmt.Sprintf("%s/%s/records/%d", domainsBasePath, domain, id)

	req, err := s.client.NewRequest(ctx, http.MethodDelete, path, nil)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(ctx, req, nil)

	return resp, err
}

// EditRecord edits a record using a DomainRecordEditRequest
func (s *DomainsServiceOp) EditRecord(ctx context.Context,
	domain string,
	id int,
	editRequest *DomainRecordEditRequest,
) (*DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be an empty string")
	}

	if id < 1 {
		return nil, nil, NewArgError("id", "cannot be less than 1")
	}

	if editRequest == nil {
		return nil, nil, NewArgError("editRequest", "cannot be nil")
	}

	path := fmt.Sprintf("%s/%s/records/%d", domainsBasePath, domain, id)

	req, err := s.client.NewRequest(ctx, http.MethodPut, path, editRequest)
	if err != nil {
		return nil, nil, err
	}

	root := new(domainRecordRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.DomainRecord, resp, err
}

// CreateRecord creates a record using a DomainRecordEditRequest
func (s *DomainsServiceOp) CreateRecord(ctx context.Context,
	domain string,
	createRequest *DomainRecordEditRequest) (*DomainRecord, *Response, error) {
	if len(domain) < 1 {
		return nil, nil, NewArgError("domain", "cannot be empty string")
	}

	if createRequest == nil {
		return nil, nil, NewArgError("createRequest", "cannot be nil")
	}

	path := fmt.Sprintf("%s/%s/records", domainsBasePath, domain)
	req, err := s.client.NewRequest(ctx, http.MethodPost, path, createRequest)

	if err != nil {
		return nil, nil, err
	}

	d := new(domainRecordRoot)
	resp, err := s.client.Do(ctx, req, d)
	if err != nil {
		return nil, resp, err
	}

	return d.DomainRecord, resp, err
}

// Performs a domain records request given a path.
func (s *DomainsServiceOp) records(ctx context.Context, path string) ([]DomainRecord, *Response, error) {
	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(domainRecordsRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}
	if l := root.Links; l != nil {
		resp.Links = l
	}

	return root.DomainRecords, resp, err
}


text:
AccountConfiguration.ResourceClassKey Property
==============================================
The name of the resource file (class key) in App_GlobalResources that contains localized string values.

**Namespace:** [MvcAccount][1]
**Assembly:** MvcAccount (in MvcAccount.dll)

Syntax
------

```csharp
public string ResourceClassKey { get; set; }
```

#### Property Value
Type: [String][2]

See Also
--------

#### Reference
[AccountConfiguration Class][3]
[MvcAccount Namespace][1]

[1]: ../README.md
[2]: http://msdn.microsoft.com/en-us/library/s1wwdcbf
[3]: README.md


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:binding="http://www.gueei.com/android-binding/"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center"
    >
    <ProgressBar
		android:indeterminateOnly="false"
		style="?android:attr/progressBarStyleHorizontal"
		android:layout_height="wrap_content"
		android:layout_width="fill_parent"
		binding:max="Max"
		binding:progress="PrimaryProgress"
		binding:secondaryProgress="SecondaryProgress"
		/>
	<TextView
		android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	binding:text="CONCAT('Primary: ',PrimaryProgress)"
    />
	<TextView
		android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	binding:text="CONCAT('Seconary: ',SecondaryProgress)"
    />
</LinearLayout>


text:
<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

<link rel="stylesheet" type="text/css" href="system/style/library.css"/>
<link rel="stylesheet" type="text/css" href="system/style/glyphicons.css"/>
<link rel="stylesheet" type="text/css" href="system/style/tooltips.css"/>

<object type="application/x-netcast-info" id="device" width="0" height="0"></object>


text:
require 'active_support/core_ext/array/wrap'

module SolandraObject
  module Validations
    class UniquenessValidator < ActiveModel::EachValidator
      def initialize(options)
        super
      end

      def validate_each(record, attribute, value)
        # XXX: The following will break if/when abstract base classes
        #      are implemented in solandra object (such as STI)
        finder_class = record.class

        count = finder_class.search_ids do
          with attribute, value
          Array.wrap(options[:scope]).each do |scope_item|
            scope_value = record.send(scope_item)
            scope_value = nil if scope_value.blank?
            with scope_item, scope_value
          end
        end.reject {|id| id == record.id}.size
        if count > 0
          record.errors.add(attribute, "has already been taken", options.except(:case_sensitive, :scope).merge(:value => value))
        end
      end

      # def check_validity!
#
      # end
    end

    module ClassMethods
      def validates_uniqueness_of(*attr_names)
        validates_with UniquenessValidator, _merge_attributes(attr_names)
      end
    end
  end
end


text:
/* Preferred */

// > Consistent
// > Syntax is always '// TODO:'
// > Easy to look up for

- (void)someMethod {
    // ...
    theater.tribuneTheaterID = 10955; // TODO: Remove hardcoded value
    // ...
}

- (void)someOtherMethod {
    // ...

    // TODO: this is a temporary fix to #809.
    // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
    //        self.cancelBlock = nil;
    _cancelBlock = nil;

    // ...
}

- (void)yetAnotherMethod {
    // ...

    // TODO: Remove hardcoded credentials!!! Just for testing.
    self.username = @"inaka";
    self.password = @"123456";

    // ...
}

/* Not Preferred */

// > Inconsistent
// > Syntax is always different
// > Hard to find, easy to forget

- (void)someMethod {
    // ...
    theater.tribuneTheaterID = 10955; //TODO: Remove hardcoded value
    // ...
}

- (void)someOtherMethod {
    // ...

    // TODO: this is a temporary fix to #809.
    // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
    //        self.cancelBlock = nil;
    _cancelBlock = nil;

    // ...
}

- (void)yetAnotherMethod {
    // ...

    // Warning: Remove hardcoded credentials!!! Just for testing.
    self.username = @"inaka";
    self.password = @"123456";

    // ...
}


text:
import * as Types from './types'
import { DISMISS_REQUEST } from './constants'

export const dismissRequest = (
  requestId: string
): Types.DismissRequestAction => {
  return {
    type: DISMISS_REQUEST,
    payload: { requestId },
  }
}


text:
package com.auto.test.dao;

import java.util.List;
import com.auto.test.common.dao.IBaseDao;
import com.auto.test.entity.AVersion;

public interface IApiVersionDao extends IBaseDao<AVersion> {

	List<AVersion> findByProject(Integer pid);

	public List<AVersion> findByVersionProject(String version, Integer pid);

}


text:
package com.nano.movies.data.movie;

import java.util.Date;

import android.database.Cursor;
import android.support.annotation.Nullable;

import com.nano.movies.data.base.AbstractCursor;

/**
 * Cursor wrapper for the {@code movie} table.
 */
public class MovieCursor extends AbstractCursor implements MovieModel {
    public MovieCursor(Cursor cursor) {
        super(cursor);
    }

    /**
     * Primary key.
     */
    public long getId() {
        Long res = getLongOrNull(MovieColumns._ID);
        if (res == null)
            throw new NullPointerException("The value of '_id' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Movie's unique tmdb.org id, used to identify the movie in api calls.
     */
    public int getTmdbId() {
        Integer res = getIntegerOrNull(MovieColumns.TMDB_ID);
        if (res == null)
            throw new NullPointerException("The value of 'tmdb_id' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Movie's homepage url
     * Can be {@code null}.
     */
    @Nullable
    public String getHomepage() {
        String res = getStringOrNull(MovieColumns.HOMEPAGE);
        return res;
    }

    /**
     * Movie's original title.
     * Can be {@code null}.
     */
    @Nullable
    public String getOriginalTitle() {
        String res = getStringOrNull(MovieColumns.ORIGINAL_TITLE);
        return res;
    }

    /**
     * Movie synopsis.
     * Can be {@code null}.
     */
    @Nullable
    public String getOverview() {
        String res = getStringOrNull(MovieColumns.OVERVIEW);
        return res;
    }

    /**
     * Movie's popularity value.
     * Can be {@code null}.
     */
    @Nullable
    public Double getPopularity() {
        Double res = getDoubleOrNull(MovieColumns.POPULARITY);
        return res;
    }

    /**
     * Path to movie's image file, relative to http://image.tmdb.org/t/p/<imageSize>.
     * Can be {@code null}.
     */
    @Nullable
    public String getPosterPath() {
        String res = getStringOrNull(MovieColumns.POSTER_PATH);
        return res;
    }

    /**
     * Movie's release date, eg., 2015-03-13.
     * Can be {@code null}.
     */
    @Nullable
    public Date getReleaseDate() {
        Date res = getDateOrNull(MovieColumns.RELEASE_DATE);
        return res;
    }

    /**
     * Running time in minutes.
     * Can be {@code null}.
     */
    @Nullable
    public Integer getRuntime() {
        Integer res = getIntegerOrNull(MovieColumns.RUNTIME);
        return res;
    }

    /**
     * Tagline.
     * Can be {@code null}.
     */
    @Nullable
    public String getTagline() {
        String res = getStringOrNull(MovieColumns.TAGLINE);
        return res;
    }

    /**
     * Movie's title.
     * Can be {@code null}.
     */
    @Nullable
    public String getTitle() {
        String res = getStringOrNull(MovieColumns.TITLE);
        return res;
    }

    /**
     * Average voter rating, from 1 to 10.
     */
    public double getVoteAverage() {
        Double res = getDoubleOrNull(MovieColumns.VOTE_AVERAGE);
        if (res == null)
            throw new NullPointerException("The value of 'vote_average' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Total votes cast for the movie.
     */
    public int getVoteCount() {
        Integer res = getIntegerOrNull(MovieColumns.VOTE_COUNT);
        if (res == null)
            throw new NullPointerException("The value of 'vote_count' in the database was null, which is not allowed according to the model definition");
        return res;
    }
}


text:
<?php
namespace WotWrap\Exception;

final class NoValidLimitInterfaceException extends \Exception {}


text:
//
//  SA_BufferManager.h
//  Spectrum Analyser
//
//  Created by Adland Lee on 7/25/14.
//  Copyright (c) 2014 Adland Lee. All rights reserved.
//

#ifndef __Spectrum_Analyser__SA_BufferManager__
#define __Spectrum_Analyser__SA_BufferManager__

#include <AudioToolbox/AudioToolbox.h>
#include <libkern/OSAtomic.h>

#include "SA_FFTHelper.h"

const UInt32 kNumDrawBuffers = 12;
const UInt32 kDefaultDrawSamples = 512;

const UInt32 kDisplayModeOscilloscopeWaveForm = 0;

class BufferManager
{
private:
    UInt32 _displayMode;

    Float32* _drawBuffers[kNumDrawBuffers];
    UInt32 _drawBufferIndex;
    UInt32 _currentDrawBufferLength;

    Float32* _FFTInputBuffer;
    UInt32 _FFTInputBufferFrameIndex;
    UInt32 _FFTInputBufferLength;
    volatile int32_t _hasNewFFTData;
    volatile int32_t _needsNewFFTData;

    FFTHelper*  _FFTHelper;

public:
    BufferManager (UInt32 inMaxFramesPerSlice);
    ~BufferManager ();

    void SetDisplayMode (UInt32 inDisplayMode);
    UInt32 GetDisplayMode ();

    Float32** GetDrawBuffers ();
    void CopyAudioDataToDrawBuffer (Float32* inData, UInt32 numberOfFrames);
    void CycleDrawBuffers ();

    void SetCurrentDrawBufferLength (UInt32 inDrawBufferLength);
    UInt32 GetCurrentDrawBufferLength ();

    bool HasNewFFTData ();
    bool NeedsNewFFTData ();

    void CopyAudioDataToFFTInputBuffer (Float32* inData, UInt32 numberOfFrames);
    UInt32 GetFFTOutputBufferLength ();
    void GetFFTOutput (Float32* outFFTData);
};

#endif /* defined(__Spectrum_Analyser__SA_BufferManager__) */


text:
use rustzx_core::host::Stopwatch;
use std::time::{Duration, Instant};

pub struct InstantStopwatch {
    timestamp: Instant,
}

impl Default for InstantStopwatch {
    fn default() -> Self {
        Self {
            timestamp: Instant::now(),
        }
    }
}

impl Stopwatch for InstantStopwatch {
    fn new() -> Self {
        Self::default()
    }

    fn measure(&self) -> Duration {
        self.timestamp.elapsed()
    }
}


text:
/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: /home/zhoukan/Code_Review/QuickLauncher/src/com/jide/QuickLauncher/RemoteService.aidl
 */
package com.jide.QuickLauncher;
public interface RemoteService extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.jide.QuickLauncher.RemoteService
{
private static final java.lang.String DESCRIPTOR = "com.jide.QuickLauncher.RemoteService";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
 * Cast an IBinder object into an com.jide.QuickLauncher.RemoteService interface,
 * generating a proxy if needed.
 */
public static com.jide.QuickLauncher.RemoteService asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.jide.QuickLauncher.RemoteService))) {
return ((com.jide.QuickLauncher.RemoteService)iin);
}
return new com.jide.QuickLauncher.RemoteService.Stub.Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_suffixTreeInsert:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
java.util.Map _arg2;
java.lang.ClassLoader cl = (java.lang.ClassLoader)this.getClass().getClassLoader();
_arg2 = data.readHashMap(cl);
java.lang.String _arg3;
_arg3 = data.readString();
this.suffixTreeInsert(_arg0, _arg1, _arg2, _arg3);
reply.writeNoException();
return true;
}
case TRANSACTION_suffixTreeDelete:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
this.suffixTreeDelete(_arg0, _arg1);
reply.writeNoException();
return true;
}
case TRANSACTION_indexEngineDelete:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
this.indexEngineDelete(_arg0, _arg1);
reply.writeNoException();
return true;
}
case TRANSACTION_indexEngineInsert:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
java.util.Map _arg2;
java.lang.ClassLoader cl = (java.lang.ClassLoader)this.getClass().getClassLoader();
_arg2 = data.readHashMap(cl);
java.lang.String _arg3;
_arg3 = data.readString();
this.indexEngineInsert(_arg0, _arg1, _arg2, _arg3);
reply.writeNoException();
return true;
}
case TRANSACTION_suffixTreeQuery:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
int _arg1;
_arg1 = data.readInt();
java.lang.String _arg2;
_arg2 = data.readString();
int _result = this.suffixTreeQuery(_arg0, _arg1, _arg2);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_indexEngineQuery:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
int _arg1;
_arg1 = data.readInt();
int _arg2;
_arg2 = data.readInt();
java.util.List<java.lang.String> _arg3;
_arg3 = data.createStringArrayList();
java.lang.String _arg4;
_arg4 = data.readString();
int _result = this.indexEngineQuery(_arg0, _arg1, _arg2, _arg3, _arg4);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_registerAttrs:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.util.Map _arg1;
java.lang.ClassLoader cl = (java.lang.ClassLoader)this.getClass().getClassLoader();
_arg1 = data.readHashMap(cl);
this.registerAttrs(_arg0, _arg1);
reply.writeNoException();
return true;
}
case TRANSACTION_ifDataReady:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
boolean _result = this.ifDataReady(_arg0);
reply.writeNoException();
reply.writeInt(((_result)?(1):(0)));
return true;
}
case TRANSACTION_getResults:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
java.util.List _result = this.getResults(_arg0);
reply.writeNoException();
reply.writeList(_result);
return true;
}
case TRANSACTION_computeSnippetAndHighLight:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.util.List<java.lang.String> _arg1;
_arg1 = data.createStringArrayList();
java.util.List<java.lang.String> _arg2;
_arg2 = data.createStringArrayList();
int _result = this.computeSnippetAndHighLight(_arg0, _arg1, _arg2);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_getSnippetResult:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
java.util.List _result = this.getSnippetResult(_arg0);
reply.writeNoException();
reply.writeList(_result);
return true;
}
case TRANSACTION_ifSnippetReady:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
boolean _result = this.ifSnippetReady(_arg0);
reply.writeNoException();
reply.writeInt(((_result)?(1):(0)));
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.jide.QuickLauncher.RemoteService
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override public void suffixTreeInsert(java.lang.String id, java.lang.String content, java.util.Map fields, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(id);
_data.writeString(content);
_data.writeMap(fields);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_suffixTreeInsert, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
@Override public void suffixTreeDelete(java.lang.String id, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(id);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_suffixTreeDelete, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
@Override public void indexEngineDelete(java.lang.String id, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(id);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_indexEngineDelete, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
@Override public void indexEngineInsert(java.lang.String id, java.lang.String content, java.util.Map fields, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(id);
_data.writeString(content);
_data.writeMap(fields);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_indexEngineInsert, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
@Override public int suffixTreeQuery(java.lang.String searchKey, int limit, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(searchKey);
_data.writeInt(limit);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_suffixTreeQuery, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public int indexEngineQuery(java.lang.String searchKey, int offset, int limit, java.util.List<java.lang.String> fetchFields, java.lang.String appName) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(searchKey);
_data.writeInt(offset);
_data.writeInt(limit);
_data.writeStringList(fetchFields);
_data.writeString(appName);
mRemote.transact(Stub.TRANSACTION_indexEngineQuery, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public void registerAttrs(java.lang.String appName, java.util.Map attrsAndBoost) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(appName);
_data.writeMap(attrsAndBoost);
mRemote.transact(Stub.TRANSACTION_registerAttrs, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
@Override public boolean ifDataReady(int transactionId) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(transactionId);
mRemote.transact(Stub.TRANSACTION_ifDataReady, _data, _reply, 0);
_reply.readException();
_result = (0!=_reply.readInt());
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public java.util.List getResults(int transactionId) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(transactionId);
mRemote.transact(Stub.TRANSACTION_getResults, _data, _reply, 0);
_reply.readException();
java.lang.ClassLoader cl = (java.lang.ClassLoader)this.getClass().getClassLoader();
_result = _reply.readArrayList(cl);
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public int computeSnippetAndHighLight(java.lang.String docId, java.util.List<java.lang.String> field, java.util.List<java.lang.String> terms) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(docId);
_data.writeStringList(field);
_data.writeStringList(terms);
mRemote.transact(Stub.TRANSACTION_computeSnippetAndHighLight, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public java.util.List getSnippetResult(int snippetTransactionId) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(snippetTransactionId);
mRemote.transact(Stub.TRANSACTION_getSnippetResult, _data, _reply, 0);
_reply.readException();
java.lang.ClassLoader cl = (java.lang.ClassLoader)this.getClass().getClassLoader();
_result = _reply.readArrayList(cl);
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public boolean ifSnippetReady(int snippetTransactionId) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(snippetTransactionId);
mRemote.transact(Stub.TRANSACTION_ifSnippetReady, _data, _reply, 0);
_reply.readException();
_result = (0!=_reply.readInt());
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_suffixTreeInsert = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_suffixTreeDelete = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_indexEngineDelete = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
static final int TRANSACTION_indexEngineInsert = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3);
static final int TRANSACTION_suffixTreeQuery = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4);
static final int TRANSACTION_indexEngineQuery = (android.os.IBinder.FIRST_CALL_TRANSACTION + 5);
static final int TRANSACTION_registerAttrs = (android.os.IBinder.FIRST_CALL_TRANSACTION + 6);
static final int TRANSACTION_ifDataReady = (android.os.IBinder.FIRST_CALL_TRANSACTION + 7);
static final int TRANSACTION_getResults = (android.os.IBinder.FIRST_CALL_TRANSACTION + 8);
static final int TRANSACTION_computeSnippetAndHighLight = (android.os.IBinder.FIRST_CALL_TRANSACTION + 9);
static final int TRANSACTION_getSnippetResult = (android.os.IBinder.FIRST_CALL_TRANSACTION + 10);
static final int TRANSACTION_ifSnippetReady = (android.os.IBinder.FIRST_CALL_TRANSACTION + 11);
}
public void suffixTreeInsert(java.lang.String id, java.lang.String content, java.util.Map fields, java.lang.String appName) throws android.os.RemoteException;
public void suffixTreeDelete(java.lang.String id, java.lang.String appName) throws android.os.RemoteException;
public void indexEngineDelete(java.lang.String id, java.lang.String appName) throws android.os.RemoteException;
public void indexEngineInsert(java.lang.String id, java.lang.String content, java.util.Map fields, java.lang.String appName) throws android.os.RemoteException;
public int suffixTreeQuery(java.lang.String searchKey, int limit, java.lang.String appName) throws android.os.RemoteException;
public int indexEngineQuery(java.lang.String searchKey, int offset, int limit, java.util.List<java.lang.String> fetchFields, java.lang.String appName) throws android.os.RemoteException;
public void registerAttrs(java.lang.String appName, java.util.Map attrsAndBoost) throws android.os.RemoteException;
public boolean ifDataReady(int transactionId) throws android.os.RemoteException;
public java.util.List getResults(int transactionId) throws android.os.RemoteException;
public int computeSnippetAndHighLight(java.lang.String docId, java.util.List<java.lang.String> field, java.util.List<java.lang.String> terms) throws android.os.RemoteException;
public java.util.List getSnippetResult(int snippetTransactionId) throws android.os.RemoteException;
public boolean ifSnippetReady(int snippetTransactionId) throws android.os.RemoteException;
}


text:
namespace llvm {
namespace exegesis {

static SmallVector<const Variable *, 8>
getVariablesWithTiedOperands(const Instruction &Instr) {
  SmallVector<const Variable *, 8> Result;
  for (const auto &Var : Instr.Variables)
    if (Var.hasTiedOperands())
      Result.push_back(&Var);
  return Result;
}

UopsBenchmarkRunner::~UopsBenchmarkRunner() = default;

UopsSnippetGenerator::~UopsSnippetGenerator() = default;

void UopsSnippetGenerator::instantiateMemoryOperands(
    const unsigned ScratchSpacePointerInReg,
    std::vector<InstructionTemplate> &Instructions) const {
  if (ScratchSpacePointerInReg == 0)
    return; // no memory operands.
  const auto &ET = State.getExegesisTarget();
  const unsigned MemStep = ET.getMaxMemoryAccessSize();
  const size_t OriginalInstructionsSize = Instructions.size();
  size_t I = 0;
  for (InstructionTemplate &IT : Instructions) {
    ET.fillMemoryOperands(IT, ScratchSpacePointerInReg, I * MemStep);
    ++I;
  }

  while (Instructions.size() < kMinNumDifferentAddresses) {
    InstructionTemplate IT = Instructions[I % OriginalInstructionsSize];
    ET.fillMemoryOperands(IT, ScratchSpacePointerInReg, I * MemStep);
    ++I;
    Instructions.push_back(std::move(IT));
  }
  assert(I * MemStep < BenchmarkRunner::ScratchSpace::kSize &&
         "not enough scratch space");
}

static std::vector<InstructionTemplate> generateSnippetUsingStaticRenaming(
    const LLVMState &State, const InstructionTemplate &IT,
    const ArrayRef<const Variable *> TiedVariables,
    const BitVector &ForbiddenRegisters) {
  std::vector<InstructionTemplate> Instructions;
  // Assign registers to variables in a round-robin manner. This is simple but
  // ensures that the most register-constrained variable does not get starved.
  std::vector<BitVector> PossibleRegsForVar;
  for (const Variable *Var : TiedVariables) {
    assert(Var);
    const Operand &Op = IT.Instr.getPrimaryOperand(*Var);
    assert(Op.isReg());
    BitVector PossibleRegs = Op.getRegisterAliasing().sourceBits();
    remove(PossibleRegs, ForbiddenRegisters);
    PossibleRegsForVar.push_back(std::move(PossibleRegs));
  }
  SmallVector<int, 2> Iterators(TiedVariables.size(), 0);
  while (true) {
    InstructionTemplate TmpIT = IT;
    // Find a possible register for each variable in turn, marking the
    // register as taken.
    for (size_t VarId = 0; VarId < TiedVariables.size(); ++VarId) {
      const int NextPossibleReg =
          PossibleRegsForVar[VarId].find_next(Iterators[VarId]);
      if (NextPossibleReg <= 0) {
        return Instructions;
      }
      TmpIT.getValueFor(*TiedVariables[VarId]) =
          MCOperand::createReg(NextPossibleReg);
      // Bump iterator.
      Iterators[VarId] = NextPossibleReg;
      // Prevent other variables from using the register.
      for (BitVector &OtherPossibleRegs : PossibleRegsForVar) {
        OtherPossibleRegs.reset(NextPossibleReg);
      }
    }
    Instructions.push_back(std::move(TmpIT));
  }
}

Expected<std::vector<CodeTemplate>> UopsSnippetGenerator::generateCodeTemplates(
    const Instruction &Instr, const BitVector &ForbiddenRegisters) const {
  CodeTemplate CT;
  CT.ScratchSpacePointerInReg =
      Instr.hasMemoryOperands()
          ? State.getExegesisTarget().getScratchMemoryRegister(
                State.getTargetMachine().getTargetTriple())
          : 0;
  const AliasingConfigurations SelfAliasing(Instr, Instr);
  InstructionTemplate IT(Instr);
  if (SelfAliasing.empty()) {
    CT.Info = "instruction is parallel, repeating a random one.";
    CT.Instructions.push_back(std::move(IT));
    instantiateMemoryOperands(CT.ScratchSpacePointerInReg, CT.Instructions);
    return getSingleton(std::move(CT));
  }
  if (SelfAliasing.hasImplicitAliasing()) {
    CT.Info = "instruction is serial, repeating a random one.";
    CT.Instructions.push_back(std::move(IT));
    instantiateMemoryOperands(CT.ScratchSpacePointerInReg, CT.Instructions);
    return getSingleton(std::move(CT));
  }
  const auto TiedVariables = getVariablesWithTiedOperands(Instr);
  if (!TiedVariables.empty()) {
    CT.Info = "instruction has tied variables, using static renaming.";
    CT.Instructions = generateSnippetUsingStaticRenaming(
        State, IT, TiedVariables, ForbiddenRegisters);
    instantiateMemoryOperands(CT.ScratchSpacePointerInReg, CT.Instructions);
    return getSingleton(std::move(CT));
  }
  // No tied variables, we pick random values for defs.
  BitVector Defs(State.getRegInfo().getNumRegs());
  for (const auto &Op : Instr.Operands) {
    if (Op.isReg() && Op.isExplicit() && Op.isDef() && !Op.isMemory()) {
      auto PossibleRegisters = Op.getRegisterAliasing().sourceBits();
      // Do not use forbidden registers.
      remove(PossibleRegisters, ForbiddenRegisters);
      assert(PossibleRegisters.any() && "No register left to choose from");
      const auto RandomReg = randomBit(PossibleRegisters);
      Defs.set(RandomReg);
      IT.getValueFor(Op) = MCOperand::createReg(RandomReg);
    }
  }
  // And pick random use values that are not reserved and don't alias with defs.
  const auto DefAliases = getAliasedBits(State.getRegInfo(), Defs);
  for (const auto &Op : Instr.Operands) {
    if (Op.isReg() && Op.isExplicit() && Op.isUse() && !Op.isMemory()) {
      auto PossibleRegisters = Op.getRegisterAliasing().sourceBits();
      remove(PossibleRegisters, ForbiddenRegisters);
      remove(PossibleRegisters, DefAliases);
      assert(PossibleRegisters.any() && "No register left to choose from");
      const auto RandomReg = randomBit(PossibleRegisters);
      IT.getValueFor(Op) = MCOperand::createReg(RandomReg);
    }
  }
  CT.Info =
      "instruction has no tied variables picking Uses different from defs";
  CT.Instructions.push_back(std::move(IT));
  instantiateMemoryOperands(CT.ScratchSpacePointerInReg, CT.Instructions);
  return getSingleton(std::move(CT));
}

Expected<std::vector<BenchmarkMeasure>>
UopsBenchmarkRunner::runMeasurements(const FunctionExecutor &Executor) const {
  std::vector<BenchmarkMeasure> Result;
  const PfmCountersInfo &PCI = State.getPfmCounters();
  // Uops per port.
  for (const auto *IssueCounter = PCI.IssueCounters,
                  *IssueCounterEnd = PCI.IssueCounters + PCI.NumIssueCounters;
       IssueCounter != IssueCounterEnd; ++IssueCounter) {
    if (!IssueCounter->Counter)
      continue;
    auto ExpectedCounterValue = Executor.runAndMeasure(IssueCounter->Counter);
    if (!ExpectedCounterValue)
      return ExpectedCounterValue.takeError();
    Result.push_back(BenchmarkMeasure::Create(IssueCounter->ProcResName,
                                              *ExpectedCounterValue));
  }
  // NumMicroOps.
  if (const char *const UopsCounter = PCI.UopsCounter) {
    auto ExpectedCounterValue = Executor.runAndMeasure(UopsCounter);
    if (!ExpectedCounterValue)
      return ExpectedCounterValue.takeError();
    Result.push_back(
        BenchmarkMeasure::Create("NumMicroOps", *ExpectedCounterValue));
  }
  return std::move(Result);
}

constexpr const size_t UopsSnippetGenerator::kMinNumDifferentAddresses;

} // namespace exegesis
} // namespace llvm


text:
module DropletKit
  class SizeResource < ResourceKit::Resource
    include ErrorHandlingResourcable

    resources do
      action :all, 'GET /v2/sizes' do
        query_keys :per_page, :page
        handler(200) { |r| SizeMapping.extract_collection(r.body, :read) }
      end
    end

    def all(*args)
      PaginatedResource.new(action(:all), self, *args)
    end
  end
end


text:
package org.cipango.console.printer.logs;

import java.io.IOException;
import java.io.Writer;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.servlet.http.HttpServletRequest;

import org.cipango.console.Action;
import org.cipango.console.Action.StartAction;
import org.cipango.console.Action.StopAction;
import org.cipango.console.Page;
import org.cipango.console.Parameters;
import org.cipango.console.printer.generic.HtmlPrinter;
import org.cipango.console.printer.generic.PrinterUtil;

public abstract class AbstractLogPrinter implements HtmlPrinter
{
	protected static final int[] NB_MESSAGES =
	{ 4, 10, 20, 50, 200 };

	public static final int DEFAULT_MAX_MESSAGES = 20;

	public static enum Output
	{
		TEXT, HTML;
	}

	protected MBeanServerConnection _connection;
	protected int _maxMessages;
	protected String _msgFilter;

	public AbstractLogPrinter(MBeanServerConnection connection, HttpServletRequest request) throws Exception
	{
		_connection = connection;
		String maxMsg = request.getParameter(Parameters.MAX_MESSAGES);
		if (maxMsg == null)
			maxMsg = (String) request.getSession().getAttribute(Parameters.MAX_MESSAGES);
		else
			request.getSession().setAttribute(Parameters.MAX_MESSAGES, maxMsg);

		_maxMessages = PrinterUtil.getInt(maxMsg, DEFAULT_MAX_MESSAGES);
	}

	public void printHeaders(Writer out) throws Exception
	{
		if (!_connection.isRegistered(getObjectName()))
		{
			out.write("Console logger is not registered");
			return;
		}

		boolean on = ((Boolean) _connection.getAttribute(getObjectName(), "running")).booleanValue();
		if (on)
		{
			out.write("
");
			out.write("<form method=\"get\" action=\"" + getPage().getName() + "\">" + "Show  "
					+ "<SELECT name=\"" + Parameters.MAX_MESSAGES + "\">");
			int maxSavedMsg = (Integer) _connection.getAttribute(getObjectName(), "maxMessages");
			for (int i = 0; i < NB_MESSAGES.length; i++)
			{
				if (NB_MESSAGES[i] <= maxSavedMsg)
				{
					out.write("<OPTION ");
					if (_maxMessages == NB_MESSAGES[i])
						out.write(" selected");
					out.write(">" + NB_MESSAGES[i] + "</OPTION>");
				}
			}
			out.write("</SELECT>");
			out.write(" last filtered messages. | ");

			printCommonFilters(out);

			out.write("  <input type=\"submit\" name=\"submit\" value=\"Apply\"/></FORM>");

			new ClearConsoleLoggerAction(getPage()).print(out);
			out.write(" | ");
			new StopConsoleLoggerAction(getPage(), getObjectName()).print(out);

			out.write(" | Display as log file\n");

			new MessageInMemoryAction(getPage(), getObjectName()).print(out, maxSavedMsg);
		}
		else
		{
			new StartConsoleLoggerAction(getPage(), getObjectName()).print(out);
		}
	}

	public abstract Page getPage();

	public abstract String getLogFile();

	protected abstract void printCommonFilters(Writer out) throws Exception;

	public abstract ObjectName getObjectName();

	public boolean isLoggerRunning()
	{
		try
		{
			return _connection.isRegistered(getObjectName()) && ((Boolean) _connection.getAttribute(getObjectName(), "running"));
		}
		catch (Exception e)
		{
			return false;
		}
	}

	protected void replaceAll(StringBuilder sb, String toFind, Object toSet)
	{
		int index = 0;
		while ((index = sb.indexOf(toFind)) != -1)
			sb.replace(index, index + toFind.length(), toSet.toString());
	}

	protected void replaceOnce(StringBuilder sb, String toFind, Object toSet)
	{
		int index = 0;
		if ((index = sb.indexOf(toFind)) != -1)
			sb.replace(index, index + toFind.length(), toSet.toString());
	}

	protected void replaceOnce(StringBuilder sb, int index, String toFind, Object toSet)
	{
		if ((index = sb.indexOf(toFind, index)) != -1)
			sb.replace(index, index + toFind.length(), toSet.toString());
	}

	public static class StartConsoleLoggerAction extends StartAction
	{
		public StartConsoleLoggerAction(Page page, ObjectName objectName)
		{
			super(page, "activate-console-message-log", objectName);
		}
	}

	public static class StopConsoleLoggerAction extends StopAction
	{
		public StopConsoleLoggerAction(Page page, ObjectName objectName)
		{
			super(page, "deactivate-console-message-log", objectName);
		}
	}

	public static class ClearConsoleLoggerAction extends Action
	{
		public ClearConsoleLoggerAction(Page page)
		{
			super(page, "clear-logs");
		}

		@Override
		protected void doProcess(HttpServletRequest request) throws Exception
		{
			throw new UnsupportedOperationException();
		}
	}

	public static class MessageInMemoryAction extends Action
	{
		private ObjectName _objectName;

		public MessageInMemoryAction(Page page, ObjectName objectName)
		{
			super(page, "msg-in-memory");
			_objectName = objectName;
		}

		@Override
		protected void doProcess(HttpServletRequest request) throws Exception
		{
			String maxMsg = request.getParameter(Parameters.MAX_SAVED_MESSAGES);
			if (maxMsg != null)
			{
				getConnection().setAttribute(_objectName, new Attribute("maxMessages", Integer.parseInt(maxMsg)));
			}
		}

		public void print(Writer out, int maxSavedMsg) throws IOException
		{
			out.write("<form method=\"get\" action=\"" + getPage().getName() + "\">" + "Server keeps in memory the "
					+ "<input type=\"text\" name=\"" + Parameters.MAX_SAVED_MESSAGES
					+ "\" value=\"" + maxSavedMsg + "\" size=\"1\" maxlength=\"5\"/>");
			out.write("<input type=\"hidden\" name=\"" + Parameters.ACTION+ "\" value=\"" + getParameter() + "\"/>");
			out.write(" last messages. <input type=\"submit\" value=\"Apply\"/></FORM>");
			out.write("
\n");
		}
	}
}


text:
from ..base import HaravanResource

class Option(HaravanResource):
    pass


text:
<?php
namespace RealPadConnector\CMS\GetAllProjects;

use RealPadConnector\CMS\AbstractExport;
use RealPadConnector\CMS\Project;
use RealPadConnector\CMS\Project\Building;
use RealPadConnector\CMS\Project\Floor;
use RealPadConnector\CMS\Project\Flat;

class Export extends AbstractExport implements \Countable,\Iterator {

    /**
     * @var Project[]|Building[][]|Floor[][][]|Flat[][][][]
     */
    protected $projects = array();

    /**
     * @param \SimpleXMLElement $element
     * @return Export
     */
    public static function createFromXML(\SimpleXMLElement $element)
    {
        /** @var Export $export */
        $export = parent::createFromXML($element);

        if(isset($element->project)){
            foreach($element->project as $project_element){
                $project = Project::createFromXML($project_element);
                $export->addProject($project);
            }
        }

        return $export;
    }

    /**
     * @param Project $project
     */
    function addProject(Project $project)
    {
        $this->projects[$project->getID()] = $project;
    }

    /**
     * @param int $ID
     * @return bool
     */
    function hasProject($ID)
    {
        return isset($this->projects[$ID]);
    }

    /**
     * @param int $ID
     */
    function removeProject($ID)
    {
        if(isset($this->projects[$ID])){
            unset($this->projects[$ID]);
        }
    }

    /**
     * @param int $ID
     * @return null|Project
     */
    function getProject($ID)
    {
        return isset($this->projects[$ID])
                ? $this->projects[$ID]
                : null;
    }

    /**
     * @return Project[]
     */
    public function getProjects()
    {
        return $this->projects;
    }

    /**
     * @param Project[] $projects
     */
    public function setProjects(array $projects)
    {
        $this->projects = array();
        foreach($projects as $project){
            $this->addProject($project);
        }
    }

    /**
     * @return Project|bool
     */
    public function current()
    {
        return current($this->projects);
    }

    public function next()
    {
        next($this->projects);
    }

    /**
     * @return int|null
     */
    public function key()
    {
        return key($this->projects);
    }

    /**
     * @return bool
     */
    public function valid()
    {
        return key($this->projects) !== null;
    }

    public function rewind()
    {
        reset($this->projects);
    }

    /**
     * @return int
     */
    public function count()
    {
        return count($this->projects);
    }
}


text:
[
  "./modules/ToastPage",
  "./modules/BadgePage",
  "./modules/MotionPage",
  "./modules/DialogPage",
  "./modules/NetworkPage",
  "./modules/CameraPage",
  "./modules/BarcodeScannerPage"
].forEach(function(page) {
  require(page).create();
});

tabris.create("Drawer").append(tabris.create("PageSelector"));
tabris.ui.children("Page")[0].open();


text:
if (require.extensions) {
    // The tests are running from the command line, so add
    // extensions for css/less since we can't use null-loader
    const overrideStylesheet = (module, filename) => {
        module.exports = null;
    };

    require.extensions['.css'] = overrideStylesheet;
    require.extensions['.less'] = overrideStylesheet;
}

let chai = require('chai');
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;

global.sinon = require('sinon');

global.React = require('react/addons');
global.TestUtils = React.addons.TestUtils;

// Shorter function aliases for React TestUtils functions
global.TestUtils.scryWithClass = TestUtils.scryRenderedDOMComponentsWithClass;
global.TestUtils.findWithClass = TestUtils.findRenderedDOMComponentWithClass;
global.TestUtils.scryWithTag = TestUtils.scryRenderedDOMComponentsWithTag;
global.TestUtils.findWithTag = TestUtils.findRenderedDOMComponentWithTag;
global.TestUtils.scryWithType = TestUtils.scryRenderedComponentsWithType;
global.TestUtils.findWithType = TestUtils.findRenderedComponentWithType;


text:
from django.core.management import call_command
from django.db import migrations, models

from corehq.util.django_migrations import skip_on_fresh_install

@skip_on_fresh_install
def _populate_app_id(apps, schema_editor):
    call_command('populate_app_id_for_scheduling')

class Migration(migrations.Migration):

    dependencies = [
        ('scheduling', '0023_add_remaining_content_models'),
    ]

    operations = [
        migrations.AddField(
            model_name='ivrsurveycontent',
            name='app_id',
            field=models.CharField(max_length=126, null=True),
        ),
        migrations.AddField(
            model_name='smssurveycontent',
            name='app_id',
            field=models.CharField(max_length=126, null=True),
        ),
        migrations.RunPython(_populate_app_id,
                             reverse_code=migrations.RunPython.noop,
                             elidable=True),
    ]


text:
Google I/O 2014 Codelab Source Code
=============

This is the beginning and solution code for the Google I/O 2014 Codelabs. A
separate subdirectory is defined for each codelab. Navigate
[here](https://io2014codelabs.appspot.com/) for instructions on how to complete
the codelabs or navigate to the codelabs /end directory for finished sample code.

If you believe a codelab has a bug please file it on the
[issues page](https://github.com/googlesamples/io2014-codelabs/issues)


text:
'use strict';

// __mocks__/commander.js

const commanderMock = {

    mocks: {
        command: jest.genMockFunction(),
        description: jest.genMockFunction(),
        action: jest.genMockFunction(),
        version: jest.genMockFunction(),
        parse: jest.genMockFunction(),
    },

    options: [{
        flags: '-V, --version',
        required: 0,
        optional: 0,
        bool: true,
        short: '-V',
        long: '--version',
        description: 'output the version number',
    },],

    command(value) {
        this.mocks.command(value);
        return this;
    },

    description(value) {
        this.mocks.description(value);
        return this;
    },

    action(value) {
        this.mocks.action(value);
        return this;
    },

    version(value) {
        this.mocks.version(value);
        return this;
    },

    parse(value) {
        this.mocks.parse(value);
        return this;
    },

    reset: function() {
        for (const mock in this.mocks) {
            this.mocks[mock].mockClear();
        }

        this.args = [];
    },

    args: [],
};

module.exports = commanderMock;


text:
<?php

// Heading
$_['lang_heading_title']  = 'Products Viewed Report';

// Text
$_['lang_text_success']   = 'Success: You have reset the product viewed report.';

// Column
$_['lang_column_name']    = 'Product Name';
$_['lang_column_model']   = 'Model';
$_['lang_column_viewed']  = 'Viewed';
$_['lang_column_percent'] = 'Percent';


text:
.lm_close {
    display: list-item !important;
    opacity: 0.6 !important;
}

.widget-configuration-button {
    float: left;
    color: #929292;
    margin-right: 5px;
    cursor: pointer;
    opacity: 0.6;
}

.widget-configuration-button:hover {
    opacity: 1;
}


text:
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
    namespace io
    {
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
    } // io

    namespace lang
    {
typedef ::SubArray< ::java::lang::Cloneable, ObjectArray > CloneableArray;
typedef ::SubArray< ::java::lang::ObjectArray, CloneableArray, ::java::io::SerializableArray > ObjectArrayArray;
    } // lang
} // java

template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::ddf::EscherClientDataRecord::EscherClientDataRecord(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::ddf::EscherClientDataRecord::EscherClientDataRecord()
    : EscherClientDataRecord(*static_cast< ::default_init_tag* >(0))
{
    ctor();
}

constexpr int16_t poi::ddf::EscherClientDataRecord::RECORD_ID;

java::lang::String*& poi::ddf::EscherClientDataRecord::RECORD_DESCRIPTION()
{
    clinit();
    return RECORD_DESCRIPTION_;
}
java::lang::String* poi::ddf::EscherClientDataRecord::RECORD_DESCRIPTION_;

int32_t poi::ddf::EscherClientDataRecord::fillFields(::int8_tArray* data, int32_t offset, EscherRecordFactory* recordFactory)
{
    auto bytesRemaining = readHeader(data, offset);
    auto pos = offset + int32_t(8);
    remainingData = new ::int8_tArray(bytesRemaining);
    ::java::lang::System::arraycopy(data, pos, remainingData, 0, bytesRemaining);
    return int32_t(8) + bytesRemaining;
}

int32_t poi::ddf::EscherClientDataRecord::serialize(int32_t offset, ::int8_tArray* data, EscherSerializationListener* listener)
{
    npc(listener)->beforeRecordSerialize(offset, getRecordId(), this);
    if(remainingData == nullptr) {
        remainingData = new ::int8_tArray(int32_t(0));
    }
    ::poi::util::LittleEndian::putShort(data, offset, getOptions());
    ::poi::util::LittleEndian::putShort(data, offset + int32_t(2), getRecordId());
    ::poi::util::LittleEndian::putInt(data, offset + int32_t(4), npc(remainingData)->length);
    ::java::lang::System::arraycopy(remainingData, 0, data, offset + int32_t(8), npc(remainingData)->length);
    auto pos = offset + int32_t(8) + npc(remainingData)->length;
    npc(listener)->afterRecordSerialize(pos, getRecordId(), pos - offset, this);
    return pos - offset;
}

int32_t poi::ddf::EscherClientDataRecord::getRecordSize()
{
    return int32_t(8) + (remainingData == nullptr ? int32_t(0) : npc(remainingData)->length);
}

int16_t poi::ddf::EscherClientDataRecord::getRecordId()
{
    return RECORD_ID;
}

java::lang::String* poi::ddf::EscherClientDataRecord::getRecordName()
{
    return u"ClientData"_j;
}

int8_tArray* poi::ddf::EscherClientDataRecord::getRemainingData()
{
    return remainingData;
}

void poi::ddf::EscherClientDataRecord::setRemainingData(::int8_tArray* remainingData)
{
    this->remainingData = (remainingData == nullptr) ? new ::int8_tArray(int32_t(0)) : npc(remainingData)->clone();
}

java::lang::ObjectArrayArray* poi::ddf::EscherClientDataRecord::getAttributeMap()
{
    return new ::java::lang::ObjectArrayArray({(new ::java::lang::ObjectArray({
        static_cast< ::java::lang::Object* >(u"Extra Data"_j)
        , static_cast< ::java::lang::Object* >(getRemainingData())
    }))});
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::ddf::EscherClientDataRecord::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.ddf.EscherClientDataRecord", 41);
    return c;
}

void poi::ddf::EscherClientDataRecord::clinit()
{
struct string_init_ {
    string_init_() {
    RECORD_DESCRIPTION_ = u"MsofbtClientData"_j;
    }
};

    static string_init_ string_init_instance;

    super::clinit();
}

int32_t poi::ddf::EscherClientDataRecord::fillFields(::int8_tArray* data, EscherRecordFactory* f)
{
    return super::fillFields(data, f);
}

int8_tArray* poi::ddf::EscherClientDataRecord::serialize()
{
    return super::serialize();
}

int32_t poi::ddf::EscherClientDataRecord::serialize(int32_t offset, ::int8_tArray* data)
{
    return super::serialize(offset, data);
}

java::lang::Class* poi::ddf::EscherClientDataRecord::getClass0()
{
    return class_();
}


text:
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Orcid < OmniAuth::Strategies::OAuth2

      DEFAULT_SCOPE = '/orcid-bio/read-limited'

      def self.options
        { site:        "http://#{api_host}",
        authorize_url: "http://#{site_host}/oauth/authorize",
        token_url:     "https://#{api_host}/oauth/token",
        scope:         "/orcid-bio/read-limited",
        response_type: "code",
        mode:          :header }
      end

      # Customize the parameters passed to the OAuth provider in the authorization phase
      def authorize_params
        super.tap do |params|
          %w(scope).each { |v| params[v.to_sym] = request.params[v] if request.params[v] }
          params[:scope] ||= DEFAULT_SCOPE # ensure that we're always request *some* default scope
        end
      end

      def self.api_host
        if Rails.env.production?
          "api.orcid.org"
        else
          "api.sandbox.orcid.org"
        end
      end

      def self.site_host
        if Rails.env.production?
          "orcid.org"
        else
          "sandbox.orcid.org"
        end
      end

      def profile
        url = "https://#{self.class.api_host}/v1.1/#{uid}/orcid-profile"
        conn = Faraday.new(url: url) do |faraday|
          faraday.response :xml
          faraday.request  :url_encoded
          faraday.adapter  Faraday.default_adapter
        end
        response = conn.get do |req|
          req.headers['Content-Type']  = "application/vdn.orcid+xml"
          req.headers['Authorization'] = "Bearer #{access_token.token}"
        end
        response.body['orcid_message']['orcid_profile']
      end

      option :client_options, options
      uid { access_token.params["orcid"] }
      info { profile }

    end
  end
end


text:
namespace SampleApplication.ConsoleApp
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using Autofac;
    using Ewancoder.DDD;
    using Ewancoder.DDD.Autofac;
    using Ewancoder.DDD.Interfaces;
    using Domain.Notes.Commands;
    using SampleApplication.ReadModel.Notes;

    public class EventIdentifierFactory : IEventIdentifierFactory
    {
        public string GetIdentifier(Type eventType)
        {
            return eventType.AssemblyQualifiedName;
        }

        public Type ResolveType(string eventTypeIdentifier)
        {
            return Type.GetType(eventTypeIdentifier);
        }
    }

    public class SnapshotIdentifierFactory : ISnapshotIdentifierFactory
    {
        public string GetIdentifier(Type snapshotType)
        {
            return snapshotType.AssemblyQualifiedName;
        }

        public Type ResolveType(string snapshotTypeIdentifier)
        {
            return Type.GetType(snapshotTypeIdentifier);
        }
    }

    static class Program
    {
        static void Main()
        {
            ICommandDispatcher commandDispatcher;
            IQueryDispatcher queryDispatcher;

            {
                var builder = new ContainerBuilder();

                // Setup DDD injection.
                Injector.Setup(builder, GetDomainAssemblies(), 10, 2);

                // Setup EFEventStore injection.
                Ewancoder.DDD.EFEventStore.Autofac.Injector.Setup(builder);

                // Inject identifier factories.
                builder.RegisterType<EventIdentifierFactory>()
                    .As<IEventIdentifierFactory>();

                builder.RegisterType<SnapshotIdentifierFactory>()
                    .As<ISnapshotIdentifierFactory>();

                // Setup read models.
                builder.RegisterType<NoteStore>()
                    .AsSelf().SingleInstance(); // This is in-memory cache.

                // Switch to synchronous event dispatching if you don't want
                // to tackle with eventual consistency.
                builder.RegisterType<SyncOrderedEventDispatcher>()
                    .As<IOrderedEventDispatcher>();

                var container = builder.Build();

                commandDispatcher = container.Resolve<ICommandDispatcher>();
                queryDispatcher = container.Resolve<IQueryDispatcher>();
            }

            var noteId = Guid.NewGuid();
            var secondNoteId = Guid.NewGuid();

            // Sends some commands to the domain.
            {
                //var createCommand = new CreateNote(noteId, "some note name");
                var createCommand = new CreateNoteWithBody(noteId, "some note name", string.Empty);
                commandDispatcher.Dispatch(createCommand); // Creates new Note.

                var updateCommand = new UpdateNoteInformation(noteId, "another note name", "note body");
                commandDispatcher.Dispatch(updateCommand); // Updates note information.

                var archiveCommand = new ArchiveNote(noteId);
                commandDispatcher.Dispatch(archiveCommand); // Archives note.

                var createWithBodyCommand = new CreateNoteWithBody(secondNoteId, "note with body", "body");
                commandDispatcher.Dispatch(createWithBodyCommand); // Creates new Note with body.
            }

            // Queries some read models from the domain.
            {
                var notesQuery = new Notes();
                var notes = queryDispatcher.Dispatch<Notes, IEnumerable<INote>>(notesQuery);

                foreach (var n in notes)
                {
                    Console.WriteLine(n.Id + " - " + n.Name + " - " + n.Body);
                }

                var noteByIdQuery = new NoteById(secondNoteId);
                var note = queryDispatcher.Dispatch<NoteById, INote>(noteByIdQuery);

                Console.WriteLine("Single note with Id " + secondNoteId + " is " + note.Name);
            }

            Console.ReadLine();
        }

        private static Assembly[] GetDomainAssemblies()
        {
            return new[]
            {
                Assembly.LoadFrom("SampleApplication.Domain.dll"),
                Assembly.LoadFrom("SampleApplication.ReadModel.dll")
            };
        }
    }
}


text:
'''
Created on Feb 18, 2017

@author: julien
'''
from genericpath import isfile
from os.path import join
import tempfile
import unittest

from minos.experiment.experiment import ExperimentParameters, Experiment,\
    _assert_valid_training_parameters
from minos.experiment.training import Training, EpochStoppingCondition,\
    AccuracyDecreaseStoppingCondition
from minos.model.build import ModelBuilder
from minos.model.design import create_random_blueprint
from minos.model.model import Layout, Objective, Optimizer, Metric
from minos.tf_utils import default_device, cpu_device
from minos.train.trainer import ModelTrainer
from minos.train.utils import CpuEnvironment
from minos.utils import disable_sysout
from tests.fixtures import get_reuters_dataset

class TrainTest(unittest.TestCase):

    def test_train(self):
        disable_sysout()
        with tempfile.TemporaryDirectory() as tmp_dir:
            batch_size = 50
            batch_iterator, test_batch_iterator, nb_classes = get_reuters_dataset(batch_size, 1000)
            layout = Layout(
                input_size=1000,
                output_size=nb_classes,
                output_activation='softmax')
            training = Training(
                objective=Objective('categorical_crossentropy'),
                optimizer=Optimizer(optimizer='Adam'),
                metric=Metric('categorical_accuracy'),
                stopping=EpochStoppingCondition(10),
                batch_size=batch_size)
            experiment_parameters = ExperimentParameters(use_default_values=True)
            experiment_parameters.layout_parameter('rows', 1)
            experiment_parameters.layout_parameter('blocks', 1)
            experiment_parameters.layout_parameter('layers', 1)
            experiment = Experiment(
                'test__reuters_experiment',
                layout,
                training,
                batch_iterator,
                test_batch_iterator,
                CpuEnvironment(n_jobs=1, data_dir=tmp_dir),
                parameters=experiment_parameters)

            blueprint = create_random_blueprint(experiment)
            model = ModelBuilder().build(blueprint, default_device())
            result = model.fit_generator(
                generator=batch_iterator,
                samples_per_epoch=batch_iterator.samples_per_epoch,
                nb_epoch=10,
                validation_data=test_batch_iterator,
                nb_val_samples=test_batch_iterator.sample_count)
            self.assertIsNotNone(
                result,
                'should have fit the model')
            score = model.evaluate_generator(
                test_batch_iterator,
                val_samples=test_batch_iterator.sample_count)
            self.assertIsNotNone(
                score,
                'should have evaluated the model')

    def test_model_trainer(self):
        disable_sysout()
        with tempfile.TemporaryDirectory() as tmp_dir:
            batch_size = 50
            batch_iterator, test_batch_iterator, nb_classes = get_reuters_dataset(batch_size, 1000)
            layout = Layout(
                input_size=1000,
                output_size=nb_classes,
                output_activation='softmax')
            training = Training(
                objective=Objective('categorical_crossentropy'),
                optimizer=Optimizer(optimizer='Adam'),
                metric=Metric('categorical_accuracy'),
                stopping=EpochStoppingCondition(10),
                batch_size=batch_size)
            experiment_parameters = ExperimentParameters(use_default_values=True)
            experiment_parameters.layout_parameter('rows', 1)
            experiment_parameters.layout_parameter('blocks', 1)
            experiment_parameters.layout_parameter('layers', 1)
            experiment = Experiment(
                'test__reuters_experiment',
                layout,
                training,
                batch_iterator,
                test_batch_iterator,
                CpuEnvironment(n_jobs=1, data_dir=tmp_dir),
                parameters=experiment_parameters)

            blueprint = create_random_blueprint(experiment)
            trainer = ModelTrainer(batch_iterator, test_batch_iterator)
            model_filename = join(tmp_dir, 'model')
            model, history, _duration = trainer.train(
                blueprint,
                cpu_device(),
                save_best_model=True,
                model_filename=model_filename)
            self.assertIsNotNone(
                model,
                'should have fit the model')
            self.assertTrue(isfile(model_filename), 'Should have saved the model')
            self.assertIsNotNone(history, 'Should have the training history')

    def test_early_stopping_condition_test(self):
        disable_sysout()
        with tempfile.TemporaryDirectory() as tmp_dir:
            batch_size = 50
            min_epoch = 10
            max_epoch = 15
            batch_iterator, test_batch_iterator, nb_classes = get_reuters_dataset(batch_size, 1000)
            layout = Layout(
                input_size=1000,
                output_size=nb_classes,
                output_activation='softmax')
            training = Training(
                objective=Objective('categorical_crossentropy'),
                optimizer=Optimizer(optimizer='Adam'),
                metric=Metric('categorical_accuracy'),
                stopping=AccuracyDecreaseStoppingCondition(
                    metric='categorical_accuracy',
                    noprogress_count=2,
                    min_epoch=min_epoch,
                    max_epoch=max_epoch),
                batch_size=batch_size)
            experiment_parameters = ExperimentParameters(use_default_values=True)
            experiment_parameters.layout_parameter('rows', 1)
            experiment_parameters.layout_parameter('blocks', 1)
            experiment_parameters.layout_parameter('layers', 1)
            experiment = Experiment(
                'test__reuters_experiment',
                layout,
                training,
                batch_iterator,
                test_batch_iterator,
                CpuEnvironment(n_jobs=1, data_dir=tmp_dir),
                parameters=experiment_parameters)
            _assert_valid_training_parameters(experiment)

            blueprint = create_random_blueprint(experiment)
            trainer = ModelTrainer(batch_iterator, test_batch_iterator)
            model, history, _duration = trainer.train(blueprint, cpu_device(), save_best_model=False)
            self.assertTrue(len(history.epoch) >= min_epoch, 'Should have trained for at least min epoch')
            self.assertTrue(len(history.epoch) <= max_epoch, 'Should have trained for max epoch')
            self.assertIsNotNone(
                model,
                'should have fit the model')
            score = model.evaluate_generator(
                test_batch_iterator,
                val_samples=test_batch_iterator.sample_count)
            self.assertIsNotNone(
                score,
                'should have evaluated the model')

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
package org.apache.hive.spark.client;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.Future;

import org.apache.hadoop.hive.common.classification.InterfaceAudience;

import org.apache.hive.spark.counter.SparkCounters;

/**
 * A handle to a submitted job. Allows for monitoring and controlling of the running remote job.
 */
@InterfaceAudience.Private
public interface JobHandle<T extends Serializable> extends Future<T> {

  /**
   * The client job ID. This is unrelated to any Spark jobs that might be triggered by the
   * submitted job.
   */
  String getClientJobId();

  /**
   * A collection of metrics collected from the Spark jobs triggered by this job.
   *
   * To collect job metrics on the client, Spark jobs must be registered with JobContext::monitor()
   * on the remote end.
   */
  MetricsCollection getMetrics();

  /**
   * Get corresponding spark job IDs for this job.
   */
  List<Integer> getSparkJobIds();

  /**
   * Get the SparkCounters for this job.
   */
  SparkCounters getSparkCounters();

  /**
   * Return the current state of the job.
   */
  State getState();

  /**
   * Add a listener to the job handle. If the job's state is not SENT, a callback for the
   * corresponding state will be invoked immediately.
   *
   * @param l The listener to add.
   */
  void addListener(Listener<T> l);

  /**
   * The current state of the submitted job.
   */
  static enum State {
    SENT,
    QUEUED,
    STARTED,
    CANCELLED,
    FAILED,
    SUCCEEDED;
  }

  /**
   * A listener for monitoring the state of the job in the remote context. Callbacks are called
   * when the corresponding state change occurs.
   */
  static interface Listener<T extends Serializable> {

    void onJobQueued(JobHandle<T> job);

    void onJobStarted(JobHandle<T> job);

    void onJobCancelled(JobHandle<T> job);

    void onJobFailed(JobHandle<T> job, Throwable cause);

    void onJobSucceeded(JobHandle<T> job, T result);

    /**
     * Called when a monitored Spark job is started on the remote context. This callback
     * does not indicate a state change in the client job's status.
     */
    void onSparkJobStarted(JobHandle<T> job, int sparkJobId);

  }

}


text:
require "chef/chef_fs/file_system/repository/chef_repository_file_system_entry"
require "chef/chef_fs/file_system/repository/chef_repository_file_system_cookbooks_dir"
require "chef/chef_fs/file_system/not_found_error"

class Chef
  module ChefFS
    module FileSystem
      module Repository
        class ChefRepositoryFileSystemCookbookEntry < ChefRepositoryFileSystemEntry
          def initialize(name, parent, file_path = nil, ruby_only = false, recursive = false)
            super(name, parent, file_path)
            @ruby_only = ruby_only
            @recursive = recursive
          end

          attr_reader :ruby_only
          attr_reader :recursive

          def children
            super.select { |entry| !(entry.dir? && entry.children.size == 0 ) }
          end

          def can_have_child?(name, is_dir)
            if is_dir
              return recursive && name != "." && name != ".."
            elsif ruby_only
              return false if name[-3..-1] != ".rb"
            end

            # Check chefignore
            ignorer = parent
            loop do
              if ignorer.is_a?(ChefRepositoryFileSystemCookbooksDir)
                # Grab the path from entry to child
                path_to_child = name
                child = self
                while child.parent != ignorer
                  path_to_child = PathUtils.join(child.name, path_to_child)
                  child = child.parent
                end
                # Check whether that relative path is ignored
                return !ignorer.chefignore || !ignorer.chefignore.ignored?(path_to_child)
              end
              ignorer = ignorer.parent
              break unless ignorer
            end

            true
          end

          def write_pretty_json
            false
          end

          protected

          def make_child_entry(child_name)
            ChefRepositoryFileSystemCookbookEntry.new(child_name, self, nil, ruby_only, recursive)
          end
        end
      end
    end
  end
end


text:
/**
Dependencies:
- dotenv : Needed to load parameter values from .env => already loaded
- winston: Needed for logging
- request: Needed to access the Pocket API
*/

const winston = require('winston');
var request = require('request');

if (process.env.LOG_LEVEL == 'debug'){
	require('request').debug = true;
}

module.exports = {
  archiveInPocket:function(consumer_key,access_token,callback){
	/**
	Get bookmark list from Pocket
	*/

	winston.log('info', {
		"Getting bookmark list from Pocket": "..."
	});

	request.post({
		url: process.env.POCKET_API_URL_GET,
		json: true,
		strictSSL: false,
		headers: {
			"content-type": "application/json",
			"Accept" : "*/*"
		},
		body : {
			consumer_key:consumer_key,
			access_token:access_token
		}
	},function (err, httpResponse, body) {

		if (err != null){
			winston.log('error', {
				"Accesing Pocket Retrieve API": err,
				"Ending process":new Date()
			});
			callback(-1);
			//process.exit(1);
		}

		if (httpResponse.statusCode != 200){
			winston.log('info', {
				"Response different than 200": httpResponse.statusCode,
				"Ending process":new Date()
			});
			callback(httpResponse.statusCode);
		}

		winston.log('info', {
			"Pocket bookmarks retrieved": "OK"
		})

		/*
		Obtain the list of actions with the
		IDs that we want to archive
		*/
		var bookmarks = new Array();
		var number_of_bookmarks = 0;

		for(var attributename in body.list){

			bookmarks.push({
				action : "archive",
				item_id : body.list[attributename].item_id
			});
			number_of_bookmarks++;
		}

		winston.log('info', {
			"Bookmarks retrieved": number_of_bookmarks
		})

		var modify_api_json = {
			consumer_key : consumer_key,
			access_token : access_token,
			actions : bookmarks
		};

		winston.log('debug', {
			"JSON about to be send to Poclet Modify API": modify_api_json
		})

		/*
		Call the modify API to archive all items
		*/

		winston.log('info', {
			"Archiving bookmark list in Pocket": "..."
		});

		request.post({
			url: process.env.POCKET_API_URL_MODIFY,
			json: true,
			strictSSL: false,
			headers: {
				"content-type": "application/json",
				"Accept" : "*/*"
			},
			body : modify_api_json
		},function (errModify, httpResponseModify, bodyModify) {

			if (errModify != null){
				winston.log('error', {
					"Accesing Pocket Modify API": errModify,
					"Ending process":new Date()
				})
				callback(-1)
				//process.exit(1);
			}

			if (httpResponse.statusCode != 200){
				winston.log('info', {
					"Response different than 200": httpResponse.statusCode,
					"Ending process":new Date()
				});
				callback(httpResponse.statusCode);
			}

			winston.log('info', {
				"Pocket bookmarks archived": "OK",
				"Ending process":new Date()
			});

			callback(200);
		});
	});
}
};


text:
import lodash from 'lodash';
import semver from 'semver';

import sdkVersion from './sdkVersion';
import { RGBAOutputFormat } from '@fitbit/image-codec-txi';

export interface BuildTargetDescriptor {
  displayName: string;
  platform: string[];
  resourceFilterTag: string;
  specs: {
    screenSize: {
      width: number;
      height: number;
    };
  };
  maxDeviceBundleSize?: number; // in bytes
  minSDKVersion?: string;
  defaultTXIOutputFormat?: RGBAOutputFormat;
}

const baseBuildTargets: { [platform: string]: BuildTargetDescriptor } = {
  atlas: {
    displayName: 'Fitbit Versa 3',
    minSDKVersion: '5.0.0',
    platform: ['128.1.1+'],
    resourceFilterTag: '336x336',
    specs: {
      screenSize: {
        width: 336,
        height: 336,
      },
    },
  },
  vulcan: {
    displayName: 'Fitbit Sense',
    minSDKVersion: '5.0.0',
    platform: ['128.1.1+'],
    resourceFilterTag: '336x336',
    specs: {
      screenSize: {
        width: 336,
        height: 336,
      },
    },
  },
};

let extraBuildTargets: typeof baseBuildTargets | undefined;
try {
  extraBuildTargets = require('@fitbit/sdk-build-targets').default;
} catch {}

export function generateBuildTargets() {
  return lodash.pickBy(
    {
      ...baseBuildTargets,
      ...extraBuildTargets,
    },
    ({ minSDKVersion }) =>
      minSDKVersion === undefined ||
      semver.gte(sdkVersion().format(), minSDKVersion),
  );
}

const buildTargets = generateBuildTargets();
export default buildTargets;


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.util.bin.format.pdb2.pdbreader;

import java.io.IOException;
import java.io.Writer;

import ghidra.util.task.TaskMonitor;

/**
 * Abstract class for C13 Sections which do not yet have a good implementation.
 * Class exists to output the fact (in a dump) that data of this type has been encountered.
 */
abstract class AbstractUnimplementedC13Section extends C13Section {

	private PdbByteReader myReader = null;

	protected AbstractUnimplementedC13Section(PdbByteReader reader, boolean ignore,
			TaskMonitor monitor) {
		super(ignore);
		myReader = reader;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName();
	}

	@Override
	void dump(Writer writer) throws IOException {
		String n = getClass().getSimpleName();
		int len = n.length();
		writer.write(n + dashes.substring(len));
		writer.write("***NOT IMPLEMENTED***  Bytes follow...\n");
		writer.write(myReader.dump());
		writer.write("\n");
		writer.write("End " + n + dashes.substring(len + 4));
	}
}