text:
<?php

namespace OzdemirBurak\SkyScanner;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7;
use OzdemirBurak\SkyScanner\Traits\ConsoleTrait;

abstract class TravelService
{
    use ConsoleTrait;

    /**
     * The API Key to identify the customer
     *
     * @link http://portal.business.skyscanner.net/en-gb/accounts/profile/
     *
     * @var string
     */
    protected $apiKey;

    /**
     * @var \GuzzleHttp\Client
     */
    protected $client;

    /**
     * ISO country code, or specified location schema
     *
     * @link https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes
     *
     * @var string
     */
    protected $country = 'GB';

    /**
     * ISO currency code
     *
     * @link https://en.wikipedia.org/wiki/ISO_4217#Active_codes
     *
     * @var string
     */
    protected $currency = 'GBP';

    /**
     * Data returned by SkyScanner API Request
     *
     * @var mixed
     */
    protected $data;

    /**
     * SkyScanner Service Endpoint
     *
     * @var string
     */
    protected $endpoint;

    /**
     * Instead of declaring some parameters, one can use this variable to assign parameter value by function.
     * Example: ['ip' => getIpAddress] => assigns the value of getIpAddress to ip in getParameters(), getUri() methods.
     *
     * @var array
     */
    protected $extraParameters = [];

    /**
     * Client IP, needed for X-Forwarded-For value
     *
     * @var string
     */
    protected $ip;

    /**
     * ISO locale code (language and country)
     *
     * @link https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
     *
     * @var string
     */
    protected $locale = 'en-GB';

    /**
     * Keep or remove IDs after being used to find the given relations such as Carrier Information
     *
     * @var bool
     */
    protected $removeIds = false;

    /**
     * @var \Psr\Http\Message\ResponseInterface
     */
    protected $response;

    /**
     * SkyScanner Request Provider
     *
     * @var string
     */
    protected $url = 'https://partners.api.skyscanner.net/apiservices/';

    /**
     * SkyScanner Service URI
     *
     * @var string
     */
    protected $uri;

    /**
     * Main data properties that contains information about Travel Services like "cars", "Itineraries" etc.
     *
     * @var string
     */
    protected $property;

    /**
     * URL to make the query
     *
     * @return string
     */
    abstract public function getUrl(): string;

    /**
     * Auth constructor.
     *
     * @param string $apiKey
     */
    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = $this->getClient();
    }

    /**
     * @param $parameters
     */
    public function setParameters(array $parameters): void
    {
        foreach ($parameters as $property => $value) {
            if (property_exists($this, $property)) {
                $this->$property = $value;
            } else {
                $this->printErrorMessage('Invalid property name: ' . $property);
            }
        }
    }

    /**
     * @param string $url
     * @param string $method
     *
     * @return bool|mixed|\Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function makeRequest($url, $method = 'GET')
    {
        try {
            [$url, $parameters] = $this->getRequestUrlAndParameters($url, $method === 'GET');
            return $this->response = $this->client->request($method, $url, $parameters);
        } catch (RequestException $e) {
            $this->printErrorMessage(Psr7\str($e->getRequest()), false);
            if ($e->hasResponse()) {
                $this->response = $e->getResponse();
                $this->printErrorMessage(Psr7\str($e->getResponse()), false);
            }
        }
        return false;
    }

    /**
     * Just return data property without doing any modifications to the original one
     *
     * @param string $property
     * @param bool   $reset
     *
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function get($property = null, $reset = false)
    {
        if (empty($this->data) || $reset === true) {
            $this->makeRequest($this->getUrl(), 'GET');
            $this->data = $this->getResponseBody();
        }
        if ($property !== null) {
            return $this->data->{$property} ?? [];
        }
        return $this->data;
    }

    /**
     * Initialize and store data
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function init(): bool
    {
        $this->get();
        return !empty($this->data->{$this->property});
    }

    /**
     * @param $key
     *
     * @return mixed|null
     */
    public function getParameter($key)
    {
        return $this->$key ?? null;
    }

    /**
     * Get Response Status
     *
     * @return integer
     */
    public function getResponseStatus(): int
    {
        return $this->response->getStatusCode();
    }

    /**
     * @param bool $withStatusCode
     *
     * @return string
     */
    public function getResponseMessage($withStatusCode = true): string
    {
        $message = array_key_exists($status = $this->getResponseStatus(), $messages = $this->getResponseMessages()) ?
            $messages[$status] : 'Unknown response';
        return $withStatusCode ? implode(' - ', [$status, $message]) : $message;
    }

    /**
     * Response headers
     *
     * @return mixed
     */
    public function getResponseHeaders()
    {
        return $this->response->getHeaders();
    }

    /**
     * Response body, in JSON format if the Accept header is set as 'application/json'
     *
     * @param bool $decode
     *
     * @return mixed
     */
    public function getResponseBody($decode = true)
    {
        $data = $this->response->getBody();
        return $decode === true ? json_decode($data) : $data;
    }

    /**
     * Returns specific response header defined by key
     *
     * @param      $key
     * @param bool $first
     *
     * @return string
     */
    public function getResponseHeader($key, $first = true): string
    {
        $header = $this->response->getHeader($key);
        $headerFirst = $header[0] ?? '';
        return $first ? $headerFirst : $header;
    }

    /**
     * Create a client
     *
     * @return \GuzzleHttp\Client
     */
    public function getClient(): Client
    {
        return $this->client ?? new Client();
    }

    /**
     * If you make too many requests, then you will probably have issues on rate limiting.
     * So, until a non-empty location is received, it will make a request to get a session key.
     *
     * In other words, until the rate limit is reset, it will make a request to obtain a session key
     *
     * @param string $url
     * @param string $method
     *
     * Message: Rate limit has been exceeded: 100 PerMinute for PricingSession
     *
     * @return bool|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function getSessionId($url, $method = 'POST')
    {
        if ($this->makeRequest($url, $method) === false) {
            $this->printErrorMessage('Could not fetch a valid session id.');
            return false;
        }
        $location = $this->getResponseHeader('Location');
        $locationParameters = explode('/', $location);
        $id = end($locationParameters);
        if (strpos($id, '?') !== false) {
            // cars live pricing return apikey within the session for some reason.
            [$id, $others] = explode('?', $id, 2);
        }
        return $id;
    }

    /**
     * @param string $url
     * @param bool  $isGet
     *
     * @return array
     */
    public function getRequestUrlAndParameters($url, $isGet): array
    {
        if ($isGet === true) {
            return [$url . $this->getUri(), $this->getDefaultParameters()];
        }
        return [$url, array_merge($this->getDefaultParameters(), ['form_params' => $this->getParameters()])];
    }

    /**
     * Default parameters for requests
     *
     * @return array
     */
    protected function getDefaultParameters(): array
    {
        return ['Accept' => 'application/json'];
    }

    /**
     * Create direct query link via replacing uri
     *
     * @return string
     */
    public function getUri(): string
    {
        foreach ($this->getParameterArray() as $parameter) {
            if (property_exists($this, $parameter)) {
                if (isset($this->$parameter)) {
                    $this->uri = str_replace('{' . $parameter . '}', $this->$parameter, $this->uri);
                } else {
                    $this->uri = str_replace('&'. $parameter . '={' . $parameter . '}', '', $this->uri);
                }
            }
        }
        foreach ($this->extraParameters as $parameter => $function) {
            $this->uri = str_replace('{' . $parameter . '}', $this->$function(), $this->uri);
        }
        return $this->uri;
    }

    /**
     * Get parameter array to create query string from parameters
     *
     * @param array $parameters
     *
     * @return array
     */
    public function getParameters(array $parameters = []): array
    {
        foreach (array_merge($parameters, $this->getParameterArray()) as $parameter) {
            if (isset($this->$parameter)) {
                $parameters[$parameter] = $this->$parameter;
            }
        }
        foreach ($this->extraParameters as $parameter => $function) {
            $parameters[$parameter] = $this->$function();
        }
        return $this->filterArray($parameters);
    }

    /**
     * Get everything between {curly braces} in uri string
     *
     * @return array
     */
    protected function getParameterArray(): array
    {
        preg_match_all('/{(.*?)}/', $this->uri, $parameters);
        return $parameters[1];
    }

    /**
     * Filter array and return not empty ones (allows 0 and false)
     *
     * @param array $array
     *
     * @return array
     */
    protected function filterArray(array $array): array
    {
        return array_filter($array, function ($value) {
            return $value !== null && $value !== '';
        });
    }

    /**
     * Helper method for array search to locate the property with the given property
     *
     * @param $needle
     * @param $haystack
     * @param $property
     *
     * @return false|int|string
     */
    protected function arraySearch($needle, $haystack, $property)
    {
        return array_search($needle, array_map(function ($value) use ($property) {
            return \is_object($value) ? $value->$property : $value[$property];
        }, $haystack), true);
    }

    /**
     * Get IP Address
     *
     * @link https://gist.github.com/cballou/2201933
     * @return string
     */
    public function getIpAddress(): string
    {
        if ($this->ip !== null) {
            return $this->ip;
        }
        $keys = [
            'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'
        ];
        foreach ($keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    if ($this->validateIp($ip = trim($ip))) {
                        return $ip;
                    }
                }
            }
        }
        return '127.0.0.1';
    }

    /**
     * @param $ip
     *
     * @return mixed
     */
    protected function validateIp($ip)
    {
        $filter = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
        return filter_var($ip, FILTER_VALIDATE_IP, $filter);
    }

    /**
     * Messages returned by the Skyscanner API
     *
     * @return array
     */
    protected function getResponseMessages(): array
    {
        return [
            200 => 'Success',
            201 => 'Created – The session has been created.',
            204 => 'No Content – The session is still being created (wait and try again).',
            304 => 'Not Modified – The results have not been modified since the last poll.',
            400 => 'Bad Request – Input validation failed.',
            403 => 'Forbidden – The API Key was not supplied, or it was invalid, or it is not authorized to access.',
            410 => 'Gone – The session has expired. A new session must be created.',
            429 => 'Too Many Requests – There have been too many requests in the last minute.',
            500 => 'Server Error – An internal server error has occurred which has been logged.'
        ];
    }
}


text:
#include "atomic.h"
#include "cache.h"
#include "common.h"
#include "console.h"
#include "hooks.h"
#include "hostcmd.h"
#include "ipi_chip.h"
#include "registers.h"
#include "system.h"
#include "task.h"
#include "util.h"
#include "video.h"

#define CPRINTF(format, args...) cprintf(CC_IPI, format, ##args)
#define CPRINTS(format, args...) cprints(CC_IPI, format, ##args)

static uint8_t init_done;

static struct mutex ipi_lock;
static struct ipc_shared_obj *const ipi_send_buf =
	(struct ipc_shared_obj *)CONFIG_IPC_SHARED_OBJ_ADDR;
static struct ipc_shared_obj *const ipi_recv_buf =
	(struct ipc_shared_obj *)(CONFIG_IPC_SHARED_OBJ_ADDR +
				  sizeof(struct ipc_shared_obj));

static atomic_t disable_irq_count, saved_int_mask;

void ipi_disable_irq(void)
{
	if (atomic_read_add(&disable_irq_count, 1) == 0)
		saved_int_mask = read_clear_int_mask();
}

void ipi_enable_irq(void)
{
	if (atomic_read_sub(&disable_irq_count, 1) == 1)
		set_int_mask(saved_int_mask);
}

static int ipi_is_busy(void)
{
	return SCP_SCP2APMCU_IPC_SET & IPC_SCP2HOST;
}

static void ipi_wake_ap(int32_t id)
{
	if (id >= IPI_COUNT)
		return;

	if (*ipi_wakeup_table[id])
		SCP_SCP2SPM_IPC_SET = IPC_SCP2HOST;
}

int ipi_send(int32_t id, const void *buf, uint32_t len, int wait)
{
	int ret;

	if (!init_done) {
		CPRINTS("IPI has not initialized");
		return EC_ERROR_BUSY;
	}

	if (in_interrupt_context()) {
		CPRINTS("invoke %s() in ISR context", __func__);
		return EC_ERROR_BUSY;
	}

	if (len > sizeof(ipi_send_buf->buffer)) {
		CPRINTS("data length exceeds limitation");
		return EC_ERROR_INVAL;
	}

	ipi_disable_irq();
	mutex_lock(&ipi_lock);

	if (ipi_is_busy()) {
		/*
		 * If the following conditions meet,
		 *   1) There is an IPI pending in AP.
		 *   2) The incoming IPI is a wakeup IPI.
		 * then it assumes that AP is in suspend state.
		 * Send a AP wakeup request to SPM.
		 *
		 * The incoming IPI will be checked if it's a wakeup source.
		 */
		ipi_wake_ap(id);

		CPRINTS("IPI busy, id=%d", id);
		ret = EC_ERROR_BUSY;
		goto error;
	}

	ipi_send_buf->id = id;
	ipi_send_buf->len = len;
	memcpy(ipi_send_buf->buffer, buf, len);

	/* flush memory cache (if any) */
	cache_flush_dcache_range((uintptr_t)ipi_send_buf,
				 sizeof(*ipi_send_buf));

	/* interrupt AP to handle the message */
	ipi_wake_ap(id);
	SCP_SCP2APMCU_IPC_SET = IPC_SCP2HOST;

	if (wait)
		while (ipi_is_busy())
			;

	ret = EC_SUCCESS;
error:
	mutex_unlock(&ipi_lock);
	ipi_enable_irq();
	return ret;
}

static void ipi_enable_deferred(void)
{
	struct scp_run_t scp_run;
	int ret;

	init_done = 1;

	/* inform AP that SCP is up */
	scp_run.signaled = 1;
	strncpy(scp_run.fw_ver, system_get_version(EC_IMAGE_RW),
		SCP_FW_VERSION_LEN);
	scp_run.dec_capability = video_get_dec_capability();
	scp_run.enc_capability = video_get_enc_capability();

	ret = ipi_send(SCP_IPI_INIT, (void *)&scp_run, sizeof(scp_run), 1);
	if (ret) {
		CPRINTS("failed to send initialization IPC messages");
		init_done = 0;
		return;
	}

#ifdef HAS_TASK_HOSTCMD
	hostcmd_init();
#endif

	task_enable_irq(SCP_IRQ_GIPC_IN0);
}
DECLARE_DEFERRED(ipi_enable_deferred);

static void ipi_init(void)
{
	memset(ipi_send_buf, 0, sizeof(struct ipc_shared_obj));
	memset(ipi_recv_buf, 0, sizeof(struct ipc_shared_obj));

	/* enable IRQ after all tasks are up */
	hook_call_deferred(&ipi_enable_deferred_data, 0);
}
DECLARE_HOOK(HOOK_INIT, ipi_init, HOOK_PRIO_DEFAULT);

static void ipi_handler(void)
{
	if (ipi_recv_buf->id >= IPI_COUNT) {
		CPRINTS("invalid IPI, id=%d", ipi_recv_buf->id);
		return;
	}

	CPRINTS("IPI %d", ipi_recv_buf->id);

	ipi_handler_table[ipi_recv_buf->id](
		ipi_recv_buf->id, ipi_recv_buf->buffer, ipi_recv_buf->len);
}

static void irq_group7_handler(void)
{
	extern volatile int ec_int;

	if (SCP_GIPC_IN_SET & GIPC_IN(0)) {
		ipi_handler();
		SCP_GIPC_IN_CLR = GIPC_IN(0);
		asm volatile("fence.i" ::: "memory");
		task_clear_pending_irq(ec_int);
	}
}
DECLARE_IRQ(7, irq_group7_handler, 0);

redpajama_set_name: RedPajamaGithub


text:
#region S# License

#endregion S# License
namespace StockSharp.Messages
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Runtime.Serialization;
	using System.Xml.Serialization;

	using Ecng.Common;
	using Ecng.ComponentModel;
	using Ecng.Serialization;
	using Ecng.Collections;

	using StockSharp.Localization;

	/// <summary>
	/// Schedule validity period.
	/// </summary>
	[Serializable]
	[DataContract]
	[DisplayNameLoc(LocalizedStrings.Str416Key)]
	[DescriptionLoc(LocalizedStrings.Str417Key)]
	public class WorkingTimePeriod : Cloneable<WorkingTimePeriod>, IPersistable
	{
		/// <summary>
		/// Schedule expiration date.
		/// </summary>
		[DataMember]
		[CategoryLoc(LocalizedStrings.GeneralKey)]
		[DisplayNameLoc(LocalizedStrings.Str418Key)]
		[DescriptionLoc(LocalizedStrings.Str419Key)]
		public DateTime Till { get; set; }

		private List<Range<TimeSpan>> _times = new();

		/// <summary>
		/// Work schedule within day.
		/// </summary>
		[DataMember]
		[CategoryLoc(LocalizedStrings.GeneralKey)]
		[DisplayNameLoc(LocalizedStrings.Str416Key)]
		[DescriptionLoc(LocalizedStrings.Str420Key)]
		public List<Range<TimeSpan>> Times
		{
			get => _times;
			set => _times = value ?? throw new ArgumentNullException(nameof(value));
		}

		private IDictionary<DayOfWeek, Range<TimeSpan>[]> _specialDays = new Dictionary<DayOfWeek, Range<TimeSpan>[]>();

		/// <summary>
		/// Work schedule for days with different from <see cref="Times"/> schedules.
		/// </summary>
		[XmlIgnore]
		public IDictionary<DayOfWeek, Range<TimeSpan>[]> SpecialDays
		{
			get => _specialDays;
			set => _specialDays = value ?? throw new ArgumentNullException(nameof(value));
		}

		/// <summary>
		/// Create a copy of <see cref="WorkingTimePeriod"/>.
		/// </summary>
		/// <returns>Copy.</returns>
		public override WorkingTimePeriod Clone()
		{
			return new WorkingTimePeriod
			{
				Till = Till,
				Times = Times.Select(t => t.Clone()).ToList(),
				SpecialDays = SpecialDays.ToDictionary(p => p.Key, p => p.Value.ToArray()),
			};
		}

		/// <summary>
		/// Load settings.
		/// </summary>
		/// <param name="storage">Settings storage.</param>
		public void Load(SettingsStorage storage)
		{
			Times = storage.GetValue<IEnumerable<SettingsStorage>>(nameof(Times)).Select(s => s.ToRange<TimeSpan>()).ToList();
			Till = storage.GetValue<DateTime>(nameof(Till));
			SpecialDays = storage.GetValue<IEnumerable<SettingsStorage>>(nameof(SpecialDays)).Select(s =>
				new KeyValuePair<DayOfWeek, Range<TimeSpan>[]>(
					s.GetValue<DayOfWeek>("Day"),
					s.GetValue<IEnumerable<SettingsStorage>>("Periods").Select(s1 => s1.ToRange<TimeSpan>()).ToArray()))
			.ToDictionary();
		}

		/// <summary>
		/// Save settings.
		/// </summary>
		/// <param name="storage">Settings storage.</param>
		public void Save(SettingsStorage storage)
		{
			storage.SetValue(nameof(Times), Times.Select(r => r.ToStorage()).ToArray());
			storage.SetValue(nameof(Till), Till);
			storage.SetValue(nameof(SpecialDays), SpecialDays.Select(p => new SettingsStorage()
				.Set("Day", p.Key)
				.Set("Periods", p.Value.Select(r => r.ToStorage()).ToArray())
			).ToArray());
		}

		/// <inheritdoc />
		public override string ToString()
		{
			return Times.Select(t => t.ToString()).JoinComma();
		}
	}
}


text:
First-time setup
================

1. Install `conda`.

`lcdb-workflows` depends heavily on the `conda` package manager to ensure
reproducible environments. If you don't already have `conda`, install
`miniconda <http://conda.pydata.org/miniconda.html>`_ (Python 3 version
recommended).

2. Clone the repository::

   git clone https://github.com/lcdb/lcdb-workflows.git

3. Run the tests. Set `--threads` to as many cores as you have on your machine.
With 8 cores, this takes about 6 min::

   test/run_test.py workflows/mapping/Snakefile --clean --build-env --threads 8

The output will be in `workflows/mapping/pasilla`.

Subsequent setup
================

The `lcdb/lcdb-init.py` script can be used to initialize a working repo in
a new working directory.


text:
/*
 * Author: John Tsiombikas <nuclear@member.fsf.org>
 *
 * I place this piece of code in the public domain. Feel free to use as you see
 * fit.  I'd appreciate it if you keep my name at the top of the code somehwere,
 * but whatever.
 *
 * Main project site: https://github.com/jtsiomb/c11threads
 */

/* TODO: port to MacOSX: no timed mutexes under macosx...
 * just delete that bit if you don't care about timed mutexes
 */

#ifndef C11THREADS_H_
#define C11THREADS_H_

// Needed for the bullshit license issues - Justasic
#define _POSIX_C_SOURCE 200809L
#define __USE_XOPEN2K8 1
#define __USE_XOPEN2K 1

#include <time.h>
#include <errno.h>
#include <pthread.h>
#include <sched.h>	/* for sched_yield */
#include <sys/time.h>
#include <unistd.h>

#define ONCE_FLAG_INIT	PTHREAD_ONCE_INIT

/* types */
typedef pthread_t thrd_t;
typedef pthread_mutex_t mtx_t;
typedef pthread_cond_t cnd_t;
typedef pthread_key_t tss_t;
typedef pthread_once_t once_flag;

typedef void (*thrd_start_t)(void*);
typedef void (*tss_dtor_t)(void*);

typedef struct {
	time_t sec;
	long nsec;
} xtime;

enum {
	mtx_plain		= 0,
	mtx_recursive	= 1,
	mtx_timed		= 2,
	mtx_try			= 4
};

enum {
	thrd_success,
	thrd_busy,
	thrd_error,
	thrd_nomem
};

/* ---- thread management ---- */

static inline int thrd_create(thrd_t *thr, thrd_start_t func, void *arg)
{
	/* XXX there's a third possible value returned according to the standard:
	 * thrd_nomem. but it doesn't seem to correspond to any pthread_create errors.
	 */
	return pthread_create(thr, 0, (void*(*)(void*))func, arg) == 0 ? thrd_success : thrd_error;
}

static inline void thrd_exit(int res)
{
	pthread_exit((void*)(long)res);
}

static inline int thrd_join(thrd_t thr, int *res)
{
	void *retval;

	if(pthread_join(thr, &retval) != 0) {
		return thrd_error;
	}
	if(res) {
		*res = (long)retval;
	}
	return thrd_success;
}

static inline int thrd_detatch(thrd_t thr)
{
	return pthread_detach(thr) == 0 ? thrd_success : thrd_error;
}

static inline thrd_t thrd_current(void)
{
	return pthread_self();
}

static inline int thrd_equal(thrd_t a, thrd_t b)
{
	return pthread_equal(a, b);
}

static inline void thrd_sleep(const xtime *xt)
{
	int res;
	struct timespec ts;
	ts.tv_sec = (long)xt->sec;
	ts.tv_nsec = xt->nsec;

	do {
		struct timespec rem;
		res = nanosleep(&ts, &rem);
		ts = rem;
	} while(res == -1 && errno == EINTR);
}

static inline void thrd_yield(void)
{
	sched_yield();
}

/* ---- mutexes ---- */

static inline int mtx_init(mtx_t *mtx, int type)
{
	int res;
	pthread_mutexattr_t attr;

	pthread_mutexattr_init(&attr);

	/* XXX I don't think these are exactly correct semantics */
	if(type & mtx_try) {
		pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
	}
	if(type & mtx_timed) {
		pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_TIMED_NP);
	}
	if(type & mtx_recursive) {
		pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	}

	res = pthread_mutex_init(mtx, &attr) == 0 ? thrd_success : thrd_error;
	pthread_mutexattr_destroy(&attr);
	return res;
}

static inline void mtx_destroy(mtx_t *mtx)
{
	pthread_mutex_destroy(mtx);
}

static inline int mtx_lock(mtx_t *mtx)
{
	int res = pthread_mutex_lock(mtx);
	if(res == EDEADLK) {
		return thrd_busy;
	}
	return res == 0 ? thrd_success : thrd_error;
}

static inline int mtx_trylock(mtx_t *mtx)
{
	int res = pthread_mutex_trylock(mtx);
	if(res == EBUSY) {
		return thrd_busy;
	}
	return res == 0 ? thrd_success : thrd_error;
}

static inline int mtx_timedlock(mtx_t *mtx, const xtime *xt)
{
	int res;
	struct timespec ts;

	ts.tv_sec = (long)xt->sec;
	ts.tv_nsec = xt->nsec;

	if((res = pthread_mutex_timedlock(mtx, &ts)) == EBUSY) {
		return thrd_busy;
	}
	return res == 0 ? thrd_success : thrd_error;
}

static inline int mtx_unlock(mtx_t *mtx)
{
	return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;
}

/* ---- condition variables ---- */

static inline int cnd_init(cnd_t *cond)
{
	return pthread_cond_init(cond, 0) == 0 ? thrd_success : thrd_error;
}

static inline void cnd_destroy(cnd_t *cond)
{
	pthread_cond_destroy(cond);
}

static inline int cnd_signal(cnd_t *cond)
{
	return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
}

static inline int cnd_broadcast(cnd_t *cond)
{
	return pthread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error;
}

static inline int cnd_wait(cnd_t *cond, mtx_t *mtx)
{
	return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error;
}

static inline int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const xtime *xt)
{
	int res;
	struct timespec ts;

	ts.tv_sec = (long)xt->sec;
	ts.tv_nsec = xt->nsec;

	if((res = pthread_cond_timedwait(cond, mtx, &ts)) != 0) {
		return res == ETIMEDOUT ? thrd_busy : thrd_error;
	}
	return thrd_success;
}

/* ---- thread-specific data ---- */

static inline int tss_create(tss_t *key, tss_dtor_t dtor)
{
	return pthread_key_create(key, dtor) == 0 ? thrd_success : thrd_error;
}

static inline void tss_delete(tss_t key)
{
	pthread_key_delete(key);
}

static inline int tss_set(tss_t key, void *val)
{
	return pthread_setspecific(key, val) == 0 ? thrd_success : thrd_error;
}

static inline void *tss_get(tss_t key)
{
	return pthread_getspecific(key);
}

/* ---- misc ---- */

static inline void call_once(once_flag *flag, void (*func)(void))
{
	pthread_once(flag, func);
}

/* TODO take base into account */
static inline int xtime_get(xtime *xt, int base)
{
	struct timeval tv;

	gettimeofday(&tv, 0);

	xt->sec = tv.tv_sec;
	xt->nsec = tv.tv_usec * 1000;
	return base;
}

#endif	/* C11THREADS_H_ */


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
    <ScrollView
        android:id="@+id/sLayout_content"
        android:layout_width="match_parent"
        android:layout_margin="20dp"
        android:minWidth="280dp"
        android:layout_height="wrap_content"
        android:fadingEdge="none" >

        <LinearLayout
            android:id="@+id/lLayout_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

/******************************************************************************
 * system includes
 *****************************************************************************/

#include <stdio.h>

/*
 * display.h
 *
 *  Created on: Jul 28, 2017
 *      Author: la5
 */

#ifndef _SAMPLE_SOURCES_DISPLAY_H_
#define _SAMPLE_SOURCES_DISPLAY_H_

void display_line_single(FILE *output);

void display_line_double(FILE *output);

void display_header(FILE *output, const char *title);

void display_header_event(FILE *output);

void display_event_info(FILE *output, const char *event, const char *desc);

#endif /* _SAMPLE_SOURCES_DISPLAY_H_ */


text:
package com.ToxicBakery.app.screenshot_redaction.recycler;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.ToxicBakery.app.screenshot_redaction.R;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentInitialize;
import com.ToxicBakery.app.screenshot_redaction.fragment.FragmentTutorial;

public class TutorialAdapter extends FragmentPagerAdapter {

    private static final Fragment[] fragments = {
            FragmentTutorial.createInstance(R.string.tutorial_screenshot, R.drawable.tutorial_frame_screenshot),
            FragmentTutorial.createInstance(R.string.tutorial_redact, R.drawable.tutorial_frame_redact),
            FragmentTutorial.createInstance(R.string.tutorial_share, R.drawable.tutorial_frame_share),
            new FragmentInitialize()
    };

    public TutorialAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }

}


text:
package com.amazonaws.services.kms.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 */
public class RetireGrantRequest extends AmazonWebServiceRequest implements
        Serializable, Cloneable {

    /**
     *

     * Token that identifies the grant to be retired.
     *

     */
    private String grantToken;
    /**
     *

     * A unique identifier for the customer master key associated with the
     * grant. This value can be a globally unique identifier or a fully
     * specified ARN of the key.
     *

     *
Key ARN Example -
     * arn:aws:kms:us-east-1:123456789012:key/12345678-1234
     * -1234-1234-123456789012

     *
Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
     *

     *

     *

     */
    private String keyId;
    /**
     *

     * Unique identifier of the grant to be retired. The grant ID is returned by
     * the CreateGrant function.
     *

     *
Grant ID Example -
     * 0123456789012345678901234567890123456789012345678901234567890123

     *

     *

     */
    private String grantId;

    /**
     *

     * Token that identifies the grant to be retired.
     *

     *
     * @param grantToken
     *        Token that identifies the grant to be retired.
     */
    public void setGrantToken(String grantToken) {
        this.grantToken = grantToken;
    }

    /**
     *

     * Token that identifies the grant to be retired.
     *

     *
     * @return Token that identifies the grant to be retired.
     */
    public String getGrantToken() {
        return this.grantToken;
    }

    /**
     *

     * Token that identifies the grant to be retired.
     *

     *
     * @param grantToken
     *        Token that identifies the grant to be retired.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public RetireGrantRequest withGrantToken(String grantToken) {
        setGrantToken(grantToken);
        return this;
    }

    /**
     *

     * A unique identifier for the customer master key associated with the
     * grant. This value can be a globally unique identifier or a fully
     * specified ARN of the key.
     *

     *
Key ARN Example -
     * arn:aws:kms:us-east-1:123456789012:key/12345678-1234
     * -1234-1234-123456789012

     *
Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
     *

     *

     *

     *
     * @param keyId
     *        A unique identifier for the customer master key associated with
     *        the grant. This value can be a globally unique identifier or a
     *        fully specified ARN of the key.
     *

     *
Key ARN Example -
     *        arn:aws:kms:us-east-1:123456789012:key/12345678
     *        -1234-1234-1234-123456789012

     *
Globally Unique Key ID Example -
     *        12345678-1234-1234-1234-123456789012

     *

     */
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    /**
     *

     * A unique identifier for the customer master key associated with the
     * grant. This value can be a globally unique identifier or a fully
     * specified ARN of the key.
     *

     *
Key ARN Example -
     * arn:aws:kms:us-east-1:123456789012:key/12345678-1234
     * -1234-1234-123456789012

     *
Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
     *

     *

     *

     *
     * @return A unique identifier for the customer master key associated with
     *         the grant. This value can be a globally unique identifier or a
     *         fully specified ARN of the key.
     *

     *
Key ARN Example -
     *         arn:aws:kms:us-east-1:123456789012:key/12345678
     *         -1234-1234-1234-123456789012

     *
Globally Unique Key ID Example -
     *         12345678-1234-1234-1234-123456789012

     *

     */
    public String getKeyId() {
        return this.keyId;
    }

    /**
     *

     * A unique identifier for the customer master key associated with the
     * grant. This value can be a globally unique identifier or a fully
     * specified ARN of the key.
     *

     *
Key ARN Example -
     * arn:aws:kms:us-east-1:123456789012:key/12345678-1234
     * -1234-1234-123456789012

     *
Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
     *

     *

     *

     *
     * @param keyId
     *        A unique identifier for the customer master key associated with
     *        the grant. This value can be a globally unique identifier or a
     *        fully specified ARN of the key.
     *

     *
Key ARN Example -
     *        arn:aws:kms:us-east-1:123456789012:key/12345678
     *        -1234-1234-1234-123456789012

     *
Globally Unique Key ID Example -
     *        12345678-1234-1234-1234-123456789012

     *

     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public RetireGrantRequest withKeyId(String keyId) {
        setKeyId(keyId);
        return this;
    }

    /**
     *

     * Unique identifier of the grant to be retired. The grant ID is returned by
     * the CreateGrant function.
     *

     *
Grant ID Example -
     * 0123456789012345678901234567890123456789012345678901234567890123

     *

     *

     *
     * @param grantId
     *        Unique identifier of the grant to be retired. The grant ID is
     *        returned by the CreateGrant function.
     *

     *
Grant ID Example -
     *        0123456789012345678901234567890123456789012345678901234567890123

     *

     */
    public void setGrantId(String grantId) {
        this.grantId = grantId;
    }

    /**
     *

     * Unique identifier of the grant to be retired. The grant ID is returned by
     * the CreateGrant function.
     *

     *
Grant ID Example -
     * 0123456789012345678901234567890123456789012345678901234567890123

     *

     *

     *
     * @return Unique identifier of the grant to be retired. The grant ID is
     *         returned by the CreateGrant function.
     *

     *
Grant ID Example -
     *         0123456789012345678901234567890123456789012345678901234567890123

     *

     */
    public String getGrantId() {
        return this.grantId;
    }

    /**
     *

     * Unique identifier of the grant to be retired. The grant ID is returned by
     * the CreateGrant function.
     *

     *
Grant ID Example -
     * 0123456789012345678901234567890123456789012345678901234567890123

     *

     *

     *
     * @param grantId
     *        Unique identifier of the grant to be retired. The grant ID is
     *        returned by the CreateGrant function.
     *

     *
Grant ID Example -
     *        0123456789012345678901234567890123456789012345678901234567890123

     *

     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public RetireGrantRequest withGrantId(String grantId) {
        setGrantId(grantId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGrantToken() != null)
            sb.append("GrantToken: " + getGrantToken() + ",");
        if (getKeyId() != null)
            sb.append("KeyId: " + getKeyId() + ",");
        if (getGrantId() != null)
            sb.append("GrantId: " + getGrantId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof RetireGrantRequest == false)
            return false;
        RetireGrantRequest other = (RetireGrantRequest) obj;
        if (other.getGrantToken() == null ^ this.getGrantToken() == null)
            return false;
        if (other.getGrantToken() != null
                && other.getGrantToken().equals(this.getGrantToken()) == false)
            return false;
        if (other.getKeyId() == null ^ this.getKeyId() == null)
            return false;
        if (other.getKeyId() != null
                && other.getKeyId().equals(this.getKeyId()) == false)
            return false;
        if (other.getGrantId() == null ^ this.getGrantId() == null)
            return false;
        if (other.getGrantId() != null
                && other.getGrantId().equals(this.getGrantId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getGrantToken() == null) ? 0 : getGrantToken().hashCode());
        hashCode = prime * hashCode
                + ((getKeyId() == null) ? 0 : getKeyId().hashCode());
        hashCode = prime * hashCode
                + ((getGrantId() == null) ? 0 : getGrantId().hashCode());
        return hashCode;
    }

    @Override
    public RetireGrantRequest clone() {
        return (RetireGrantRequest) super.clone();
    }
}


text:
import cv2
import io
import base64
import numpy as np
import pandas as pd
from subprocess import Popen, PIPE

class VideoAnalysis(object):
    """

    TODO:
    - Define common interfaces on similar functions
    - Define what format video will come in as
    - Probably want a preprocessed dataframe with image, time, (and maybe features)
    """

    def __init__(self):
        """
        Default constructor
        """
        self.features = pd.DataFrame()

    @staticmethod
    def detect_cut(video_file_path, time_pd_series):
        """
        Detect where the scene boundaries ("cuts") are in the video.
        Uses FFMPEG utility.

        Args:
            video_file_path: Path to video file
            time_pd_series: pandas series with timestamps for every frame
        Returns:
            A dataframe of with each frame labeled as whether it is a
            scene boundary.
        """
        ## Create output array, initialize with all zeros
        time_df = pd.DataFrame(time_pd_series)
        time_df.columns = ["time"]
        out_df = time_df.copy()
        out_df['is_scene_transition'] = 0

        ## Use the bash script to call ffprobe, a utility for detecting scene changes
        p = Popen(["bash", "ffprobe_script.bash", video_file_path], stdout=PIPE, stderr=PIPE)
        output, err = p.communicate()

        # Create a dataframe of scene change times
        #import pdb; pdb.set_trace()

        scene_trans_df = pd.DataFrame(output.split()[2:])
        ## Check that scene transitions occur
        if not scene_trans_df.empty:
            scene_trans_df.columns = ["time"]
            scene_trans_df.time = scene_trans_df.time.apply(lambda x: float(x))

            for scene_time in scene_trans_df.time:
                closest_pt = out_df.ix[(time_df.time - scene_time).abs().argsort()[:1]]
                index = int(closest_pt.index[0])
                out_df['is_scene_transition'][index] = 1

        return out_df

    @staticmethod
    def detect_shake(video):
        '''
        Shake detection
        '''
        pass

    @staticmethod
    def detect_blur(video):
        '''
        Detect blur
        '''
        pass

    @staticmethod
    def optical_flow(video):
        '''
        Optical flow - useful for preprocessing
        Should this go here? Or should this be in preprocessing???
        '''
        pass

    @staticmethod
    def synchrony(video):
        '''
        Audio/Visual Synchrony
        '''
        pass

    @staticmethod
    def find_faces(video):
        '''
        Find faces in the images
        '''
        pass


text:
@class AddonData;

@interface AddonsCell : KMCheckboxTableCell
@property (nonatomic) AddonData *addon;

@property (nonatomic) IBOutlet UIImageView *addonIconView;
@property (nonatomic) IBOutlet UILabel *addonNameLabel;
@end


text:
/* global jQuery */

'use strict';

/**
 * Bolster
 * @library Bolster
 * @desc Easily create and manage Backbone Marionette applications with Backbone Relational & Backbone Radio integration, module runner and more
 * @requires backbone
 * @requires jQuery
 * @requires backbone.marionette
 * @requires backbone-relational
 * @requires backbone.radio
 */

// Backbone
var Backbone = require('backbone');
// Backbone.$ = jQuery;
// Underscore
var _ = require('underscore');
// Backbone Marionette
var Mn = require('backbone.marionette');
// Backbone Relational
require('backbone-relational');
// Backbone Radio
require('backbone.radio');

// Core utilities
var utils = require('./libs/utils');
// Logging (like the Spanish Olé! Also the "ole" in "console")
var ole = require('./libs/ole');
// Url helper
var url = require('./libs/url');
// Ui helper
var ui = require('./libs/ui');

// Custom entity definitions
var Model = require('./src/model');
var Collection = require('./src/collection');
var Module = require('./src/module');
var Base = require('./src/base');

module.exports = {

  // Attributes
  // --------------------------

  // Turn on/off Olé logging
  verbose: false,

  // Keep a local copy of the created channels
  radio: {},

  // Keep a local list of app module names
  modules: [],

  // Inherited objects
  // --------------------------

  // Backbone Relational relationship types
  HasOne: Backbone.HasOne,
  HasMany: Backbone.HasMany,

  // Backbone Radio
  Radio: Backbone.Radio,

  // Backbone History
  history: Backbone.history,

  // The url helper
  url: url,

  // The ui helper
  ui: ui,

  // Protected Functions
  // --------------------------

  /**
   * initialize
   * @description Initialize Bolster by enabling logging and setting up the core entities
   * @param  {Object} options Initialization parameters, including custom entity definitions
   */
  initialize: function(options) {
    // Add logging cability to Bolster itself (how ironic)!
    ole.assimilate(this);

    if (options.mixins) {
      _.mixin(options.mixins);
    }

    if (options.enableCookieAuth) {
      utils.enableCookieAuth();
    }

    this.initializeRadio(options);

    var extend = function(Root, Factory) {
      utils._extends(Root, Factory);
      return Root;
    };

    var extendBase = function(Parent) {
      var base = Base();
      return extend(base, Parent);
    };

    var extendObject = function(Root, Parent) {
      return extend(Root, extendBase(Parent));
    }

    // Backbone Relational entities
    this.Model = (extendObject)(Model, Backbone.RelationalModel);
    this.Collection = options.Collection ? (extendObject)(options.Collection, Backbone.Collection) : (extendBase)(Backbone.Collection);

    // Backbone Marionette entities
    this.CollectionView = (extendBase)(Mn.CollectionView);
    this.CompositeView = (extendBase)(Mn.CompositeView);
    this.ItemView = (extendBase)(Mn.ItemView);
    this.LayoutView = (extendBase)(Mn.LayoutView);
    this.Module = (extendObject)(Module, Mn.Module);
    this.Object = (extendBase)(Mn.Object);

    if (options.Model) {
      this.Model = (extendObject)(options.Model, this.Model);
    }
    // For some reason extending the Collection twice causes issues
    // if (options.Collection) {
    //   this.Collection = (extendObject)(options.Collection, Backbone.Collection);
    // }
  },

  // Public Functions
  // --------------------------

  addModelScope: function(scope) {
    Backbone.Relational.store.addModelScope(scope);
  },

  /**
   * createApplication
   * Create a Backbone Marionette applicaiton with all the Bolster trimmings
   */
  createApp: function(config) {
    this.traffic = config.traffic;

    if (config.enableMarionetteInspector) {
      utils.enableMarionetteInspector();
    }
    if (config.logVersion) {
      utils.logVersion(config.name, options.version);
    }
    if (config.resetWindowOnRoute) {
      ui.resetWindowOnRoute();
    }

    this.app = new Mn.Application();
    this.loadRegions(config.regions);
    this.loadModules(config.modules);

    // this.app.radio = this.radio;

    return this.app;
  },

  /**
   * ignition
   * Start & stop modules
   */
  ignition: function(modules, route) {
    var that = this;
    return function() {
      var state = that.getState(),
        start = _.difference(_.union(that.traffic.always_on, modules), state.started),
        stop = _.difference(that.modules, that.traffic.always_on, that.traffic.dont_stop, modules, state.stopped);

      that.log('Needed', modules);
      that.log('Already started', state.started);
      that.log('Already stopped', state.stopped);

      that.log('Stopping', stop);
      _.each(stop, function(name) {
        that.stopModule(name);
      });

      that.log('Starting', start);
      _.each(start, function(name) {
        that.startModule(name);
      });

      route.apply(that, arguments);
    };
  },

  // Private Functions
  // --------------------------

  initializeRadio: function(options) {
    // Set the development mode
    Backbone.Radio.DEBUG = options.debug;

    // Create the required radio channels
    _.each(options.channels, function(id) {
      this.radio[id] = Backbone.Radio.channel(id);
    }, this);
  },

  /**
   * loadRegions
   * @desc Load regions into the app scope
   */
  loadRegions: function(regions) {
    this.app.addRegions(regions);
  },

  /**
   * loadModules
   * @desc Load modules into the app scope
   */
  loadModules: function(modules) {
    // this.app.module('Store', require('modules/store'));
    // this.app.module('Bootstrap', require('modules/bootstrap'));

    _.each(modules, function(value, key) {
      this.app.module(key, value);
      this.modules.push(key);
    }, this);

    // Compile a list of all modules
    // _.each(this.app.submodules, function(module) {
    //   // if (!_.isUndefined(module.moduleName)) {
    //     this.modules.push(module.moduleName);
    //   // }
    // }, this);
    // console.log(this.modules);
  },

  stopModule: function(name) {
    var module = this.getModule(name);
    if (module) {
      module.stop();
    }
  },

  startModule: function(name) {
    var module = this.getModule(name);
    if (module) {
      module.start();
    }
  },

  getModule: function(name) {
    var module;
    if (_.contains(this.modules, name)) {
      module = this.app.module(name);
    } else if (window.console) {
      console.error('Module', '\'' + name + '\'', 'does not exist.');
    }
    return module;
  },

  getState: function() {
    var started = [],
      stopped = [];

    _.each(this.app.submodules, function(module) {
      if (module.hasStarted()) {
        started.push(module.moduleName);
      } else {
        stopped.push(module.moduleName);
      }
    });

    return {
      started: started,
      stopped: stopped
    };
  },

};


text:
namespace sh
{

namespace
{

constexpr const ImmutableString kEmulatedGLDrawIDName("angle_DrawID");

class FindGLDrawIDTraverser : public TIntermTraverser
{
  public:
    FindGLDrawIDTraverser() : TIntermTraverser(true, false, false), mVariable(nullptr) {}

    const TVariable *getGLDrawIDBuiltinVariable() { return mVariable; }

  protected:
    void visitSymbol(TIntermSymbol *node) override
    {
        if (&node->variable() == BuiltInVariable::gl_DrawID())
        {
            mVariable = &node->variable();
        }
    }

  private:
    const TVariable *mVariable;
};

class AddBaseVertexToGLVertexIDTraverser : public TIntermTraverser
{
  public:
    AddBaseVertexToGLVertexIDTraverser() : TIntermTraverser(true, false, false) {}

  protected:
    void visitSymbol(TIntermSymbol *node) override
    {
        if (&node->variable() == BuiltInVariable::gl_VertexID())
        {

            TIntermSymbol *baseVertexRef = new TIntermSymbol(BuiltInVariable::gl_BaseVertex());

            TIntermBinary *addBaseVertex = new TIntermBinary(EOpAdd, node, baseVertexRef);
            queueReplacement(addBaseVertex, OriginalNode::BECOMES_CHILD);
        }
    }
};

constexpr const ImmutableString kEmulatedGLBaseVertexName("angle_BaseVertex");

class FindGLBaseVertexTraverser : public TIntermTraverser
{
  public:
    FindGLBaseVertexTraverser() : TIntermTraverser(true, false, false), mVariable(nullptr) {}

    const TVariable *getGLBaseVertexBuiltinVariable() { return mVariable; }

  protected:
    void visitSymbol(TIntermSymbol *node) override
    {
        if (&node->variable() == BuiltInVariable::gl_BaseVertex())
        {
            mVariable = &node->variable();
        }
    }

  private:
    const TVariable *mVariable;
};

constexpr const ImmutableString kEmulatedGLBaseInstanceName("angle_BaseInstance");

class FindGLBaseInstanceTraverser : public TIntermTraverser
{
  public:
    FindGLBaseInstanceTraverser() : TIntermTraverser(true, false, false), mVariable(nullptr) {}

    const TVariable *getGLBaseInstanceBuiltinVariable() { return mVariable; }

  protected:
    void visitSymbol(TIntermSymbol *node) override
    {
        if (&node->variable() == BuiltInVariable::gl_BaseInstance())
        {
            mVariable = &node->variable();
        }
    }

  private:
    const TVariable *mVariable;
};

}  // namespace

bool EmulateGLDrawID(TCompiler *compiler,
                     TIntermBlock *root,
                     TSymbolTable *symbolTable,
                     std::vector<sh::ShaderVariable> *uniforms,
                     bool shouldCollect)
{
    FindGLDrawIDTraverser traverser;
    root->traverse(&traverser);
    const TVariable *builtInVariable = traverser.getGLDrawIDBuiltinVariable();
    if (builtInVariable)
    {
        const TType *type = StaticType::Get<EbtInt, EbpHigh, EvqUniform, 1, 1>();
        const TVariable *drawID =
            new TVariable(symbolTable, kEmulatedGLDrawIDName, type, SymbolType::AngleInternal);
        const TIntermSymbol *drawIDSymbol = new TIntermSymbol(drawID);

        // AngleInternal variables don't get collected
        if (shouldCollect)
        {
            ShaderVariable uniform;
            uniform.name       = kEmulatedGLDrawIDName.data();
            uniform.mappedName = kEmulatedGLDrawIDName.data();
            uniform.type       = GLVariableType(*type);
            uniform.precision  = GLVariablePrecision(*type);
            uniform.staticUse  = symbolTable->isStaticallyUsed(*builtInVariable);
            uniform.active     = true;
            uniform.binding    = type->getLayoutQualifier().binding;
            uniform.location   = type->getLayoutQualifier().location;
            uniform.offset     = type->getLayoutQualifier().offset;
            uniform.readonly   = type->getMemoryQualifier().readonly;
            uniform.writeonly  = type->getMemoryQualifier().writeonly;
            uniforms->push_back(uniform);
        }

        DeclareGlobalVariable(root, drawID);
        if (!ReplaceVariableWithTyped(compiler, root, builtInVariable, drawIDSymbol))
        {
            return false;
        }
    }

    return true;
}

bool EmulateGLBaseVertexBaseInstance(TCompiler *compiler,
                                     TIntermBlock *root,
                                     TSymbolTable *symbolTable,
                                     std::vector<sh::ShaderVariable> *uniforms,
                                     bool shouldCollect,
                                     bool addBaseVertexToVertexID)
{
    bool addBaseVertex = false, addBaseInstance = false;
    ShaderVariable uniformBaseVertex, uniformBaseInstance;

    if (addBaseVertexToVertexID)
    {
        // This is a workaround for Mac AMD GPU
        // Replace gl_VertexID with (gl_VertexID + gl_BaseVertex)
        AddBaseVertexToGLVertexIDTraverser traverserVertexID;
        root->traverse(&traverserVertexID);
        if (!traverserVertexID.updateTree(compiler, root))
        {
            return false;
        }
    }

    FindGLBaseVertexTraverser traverserBaseVertex;
    root->traverse(&traverserBaseVertex);
    const TVariable *builtInVariableBaseVertex =
        traverserBaseVertex.getGLBaseVertexBuiltinVariable();

    if (builtInVariableBaseVertex)
    {
        const TType *type = StaticType::Get<EbtInt, EbpHigh, EvqUniform, 1, 1>();
        const TVariable *baseVertex =
            new TVariable(symbolTable, kEmulatedGLBaseVertexName, type, SymbolType::AngleInternal);
        const TIntermSymbol *baseVertexSymbol = new TIntermSymbol(baseVertex);

        // AngleInternal variables don't get collected
        if (shouldCollect)
        {
            uniformBaseVertex.name       = kEmulatedGLBaseVertexName.data();
            uniformBaseVertex.mappedName = kEmulatedGLBaseVertexName.data();
            uniformBaseVertex.type       = GLVariableType(*type);
            uniformBaseVertex.precision  = GLVariablePrecision(*type);
            uniformBaseVertex.staticUse = symbolTable->isStaticallyUsed(*builtInVariableBaseVertex);
            uniformBaseVertex.active    = true;
            uniformBaseVertex.binding   = type->getLayoutQualifier().binding;
            uniformBaseVertex.location  = type->getLayoutQualifier().location;
            uniformBaseVertex.offset    = type->getLayoutQualifier().offset;
            uniformBaseVertex.readonly  = type->getMemoryQualifier().readonly;
            uniformBaseVertex.writeonly = type->getMemoryQualifier().writeonly;
            addBaseVertex               = true;
        }

        DeclareGlobalVariable(root, baseVertex);
        if (!ReplaceVariableWithTyped(compiler, root, builtInVariableBaseVertex, baseVertexSymbol))
        {
            return false;
        }
    }

    FindGLBaseInstanceTraverser traverserInstance;
    root->traverse(&traverserInstance);
    const TVariable *builtInVariableBaseInstance =
        traverserInstance.getGLBaseInstanceBuiltinVariable();

    if (builtInVariableBaseInstance)
    {
        const TType *type             = StaticType::Get<EbtInt, EbpHigh, EvqUniform, 1, 1>();
        const TVariable *baseInstance = new TVariable(symbolTable, kEmulatedGLBaseInstanceName,
                                                      type, SymbolType::AngleInternal);
        const TIntermSymbol *baseInstanceSymbol = new TIntermSymbol(baseInstance);

        // AngleInternal variables don't get collected
        if (shouldCollect)
        {
            uniformBaseInstance.name       = kEmulatedGLBaseInstanceName.data();
            uniformBaseInstance.mappedName = kEmulatedGLBaseInstanceName.data();
            uniformBaseInstance.type       = GLVariableType(*type);
            uniformBaseInstance.precision  = GLVariablePrecision(*type);
            uniformBaseInstance.staticUse =
                symbolTable->isStaticallyUsed(*builtInVariableBaseInstance);
            uniformBaseInstance.active    = true;
            uniformBaseInstance.binding   = type->getLayoutQualifier().binding;
            uniformBaseInstance.location  = type->getLayoutQualifier().location;
            uniformBaseInstance.offset    = type->getLayoutQualifier().offset;
            uniformBaseInstance.readonly  = type->getMemoryQualifier().readonly;
            uniformBaseInstance.writeonly = type->getMemoryQualifier().writeonly;
            addBaseInstance               = true;
        }

        DeclareGlobalVariable(root, baseInstance);
        if (!ReplaceVariableWithTyped(compiler, root, builtInVariableBaseInstance,
                                      baseInstanceSymbol))
        {
            return false;
        }
    }

    // Make sure the order in uniforms is the same as the traverse order
    if (addBaseInstance)
    {
        uniforms->push_back(uniformBaseInstance);
    }
    if (addBaseVertex)
    {
        uniforms->push_back(uniformBaseVertex);
    }

    return true;
}

}  // namespace sh


text:
using namespace std;

string str = "GET / HTTP/1.1\nHost: www.example.com\nConnection: keep-alive\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 S\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Encoding: gzip,deflate,sdch\nAccept-Language: en-US,en;q=0.8\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n";

class Parser {
public:
  map<string, string> headers;
  int done;
  string current_header_field;
  string request_url;
  http_parser parser;

  inline Parser() {
    done = 0;
    http_parser_init(&parser, HTTP_REQUEST);
    parser.data = (void*)this;
  }

  inline void push(http_parser_settings *settings, string str) {
    int res = http_parser_execute(&parser, settings, str.c_str(), str.length());
  }

  inline void on_header_field(string s) {
    current_header_field = s;
  }

  inline void on_header_value(string s) {
    headers[current_header_field] = s;
  }

  inline void on_url(string url) {
    request_url = url;
  }

  inline void on_message_complete() {
    done = 1;
  }
};

inline Parser* get_parser(http_parser* p) {
  return (Parser*)p->data;
}

int on_header_field(http_parser* s, const char* at, size_t length) {
  get_parser(s)->on_header_field(string(at, length));
  return 0;
}

int on_header_value(http_parser* s, const char* at, size_t length) {
  get_parser(s)->on_header_value(string(at, length));
  return 0;
}

int on_message_complete(http_parser* s) {
  get_parser(s)->on_message_complete();
  return 0;
}

int on_url(http_parser* s, const char* at, size_t length) {
  get_parser(s)->on_url(string(at, length));
  return 0;
}

int main(){
  http_parser_settings* settings = new http_parser_settings();
  settings->on_message_begin = NULL;
  settings->on_url = on_url;
  settings->on_header_field = on_header_field;
  settings->on_header_value = on_header_value;
  settings->on_headers_complete = NULL;
  settings->on_body = NULL;
  settings->on_message_complete = on_message_complete;

  int s = 0;

  for (int i = 0; i < 100000; ++i) {
    Parser p = Parser();
    p.push(settings, str);
    s += p.headers.size();
  }

  printf("s = %d\n", s);
}


text:
title: Network Policy (Docker Containerizer)
canonical_url: 'https://docs.projectcalico.org/v2.6/getting-started/mesos/tutorials/policy/docker-containerizer'
---

The Docker Containerizer uses Docker directly to launch tasks.
When using {{site.prodname}} with Mesos, it uses the standard {{site.prodname}} Docker networking
and IPAM plugins.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.impala</groupId>
    <artifactId>impala-data-source</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <groupId>org.apache.impala</groupId>
  <artifactId>impala-data-source-test</artifactId>
  <version>0.1-SNAPSHOT</version>
  <name>Apache Impala External Data Source Test Library</name>
  <description>Test External Data Source</description>
  <packaging>jar</packaging>
  <url>.</url>

  <properties>
    <impala.extdatasrc.api.version>1.0-SNAPSHOT</impala.extdatasrc.api.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.impala</groupId>
      <artifactId>impala-data-source-api</artifactId>
      <version>${impala.extdatasrc.api.version}</version>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
package io.github.luizgrp.sectionedrecyclerviewadapter.demo.example5;

import android.content.Context;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.ArrayRes;
import androidx.annotation.NonNull;

final class LoadMoviesUseCase {

    List<Movie> execute(@NonNull final Context context, @ArrayRes final int stringArray) {
        final List<String> arrayList = new ArrayList<>(Arrays.asList(
                context.getResources().getStringArray(stringArray)));

        final List<Movie> movieList = new ArrayList<>();

        for (String str : arrayList) {
            String[] array = str.split("\\|");
            movieList.add(new Movie(array[0], array[1]));
        }

        return movieList;
    }
}


text:
import { browser, element, by, promise, ElementFinder, ExpectedConditions } from 'protractor';

const githubRegex = /https:\/\/github.com\/angular\/angular\//;

export class SitePage {

  links = element.all(by.css('md-toolbar a'));
  docsMenuLink = element(by.cssContainingText('aio-top-menu a', 'Docs'));
  docViewer = element(by.css('aio-doc-viewer'));
  codeExample = element.all(by.css('aio-doc-viewer pre > code'));
  ghLink = this.docViewer
    .all(by.css('a'))
    .filter((a: ElementFinder) => a.getAttribute('href').then(href => githubRegex.test(href)))
    .first();
  gaReady: promise.Promise<any>;

  static setWindowWidth(newWidth: number) {
    const win = browser.driver.manage().window();
    return win.getSize().then(oldSize => win.setSize(newWidth, oldSize.height));
  }

  getNavItem(pattern: RegExp) {
    return element.all(by.css('aio-nav-item .vertical-menu-item'))
                  .filter(element => element.getText().then(text => pattern.test(text)))
                  .first();
  }
  getLink(path) { return element(by.css(`a[href="${path}"]`)); }
  ga() { return browser.executeScript('return window["gaCalls"]') as promise.Promise<any[][]>; }
  locationPath() { return browser.executeScript('return document.location.pathname') as promise.Promise<string>; }

  navigateTo(pageUrl = '') {
    return browser.get('/' + pageUrl).then(_ => this.replaceGa(_));
  }

  getDocViewerText() {
    return this.docViewer.getText();
  }

  getInnerHtml(element) {
    // `getInnerHtml` was removed from webDriver and this is the workaround.
    // See https://github.com/angular/protractor/blob/master/CHANGELOG.md#breaking-changes
    return browser.executeScript('return arguments[0].innerHTML;', element);
  }

  getScrollTop() {
    return browser.executeScript('return window.pageYOffset');
  }

  scrollToBottom() {
    return browser.executeScript('window.scrollTo(0, document.body.scrollHeight)');
  }

  enterSearch(query: string) {
    const input = element(by.css('.search-container input[type=search]'));
    input.clear();
    input.sendKeys(query);
  }

  getSearchResults() {
    const results = element.all(by.css('.search-results li'));
    browser.wait(ExpectedConditions.presenceOf(results.first()), 8000);
    return results;
  }

  /**
   * Replace the ambient Google Analytics tracker with homebrew spy
   * don't send commands to GA during e2e testing!
   * @param _ - forward's anything passed in
   */
  private replaceGa(_: any) {

    this.gaReady = browser.driver.executeScript(() => {
      // Give ga() a "ready" callback:
      // https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference
      window['ga'](() => {
        window['gaCalls'] = [];
        window['ga'] = function() { window['gaCalls'].push(arguments); };
      });

    })
    .then(() => {
      // wait for GaService to start using window.ga after analytics lib loads.
      const d =  promise.defer();
      setTimeout(() => d.fulfill(), 1000); // GaService.initializeDelay
      return d.promise;
    });

    return _;
  }
}


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

<TITLE>
apollo.gui.synteny
</TITLE>

<META NAME="keywords" CONTENT="apollo.gui.synteny package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package apollo.gui.synteny

Class Summary

CompositeApolloFrame
The synteny panels need to display many stranded-zoomable-apollo-panels at once,
 (unlike the standard apollo frame).

CompositeApolloFrame.MacApplicationSupport

CurationManager
Holds CurationState objects.

GuiCurationState
Holds stuff needed for each curation-set/apollo-panel/szap/"species".

SyntenyLayout

SyntenyLinkPanel

SyntenyPanel
JPanel that holds szaps and link panels(if multi species).

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
<span class="yes-no no" ng-show="actual < target">×
<span class="yes-no yes" ng-hide="actual < target">✓


text:
// placeholder
{/*<Fetch method="GET"
  url={`www.example.com/avatar/${this.state.userId}`}
  onSuccess={(data) => { this.setState({avatar : data.path()}) }}
  onError={this.showError}>
  <Fetch.before>
		<Image souce="images/placeholder.png"/>
	</Fetch.before>
  <Fetch.success>
		<Image souce={this.state.avatar}/>
	</Fetch.success>
  <Fetch.error>
		<Image souce="images/error.png"/>
	</Fetch.error>
</LoginAction.onPress>*/}


text:
package com.xaut.yld10.app.OnClick;

import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

import com.xaut.yld10.app.R;

/**
 * Created by youker on 2017/6/8 0008.
 */

public class SuggestClick {
    private static ImageButton imageButton;
    private static DrawerLayout drawerLayout;
    //private static Context context;

    public SuggestClick(final AppCompatActivity act){
        setImageButton((ImageButton) act.findViewById(R.id.image_bt));
        setDrawerLayout((DrawerLayout)act.findViewById(R.id.drawer_layout));
        clickListener();
    }

    public void clickListener(){
        getImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(view.getId() == R.id.image_bt){
                    getDrawerLayout().openDrawer(GravityCompat.START);
                }
            }
        });
    }

    public static ImageButton getImageButton() {
        return imageButton;
    }

    public static void setImageButton(ImageButton imageButton) {
        SuggestClick.imageButton = imageButton;
    }

    public static DrawerLayout getDrawerLayout() {
        return drawerLayout;
    }

    public static void setDrawerLayout(DrawerLayout drawerLayout) {
        SuggestClick.drawerLayout = drawerLayout;
    }

}


text:
| # | Column Name | Nullable | Data Type | Max Length | Description |
| --- | --- | --- | --- | --- | --- |
| 1 | log_id | [ ] | bigint | 0 |  |
| 2 | user_id | [ ] | integer | 0 |  |
| 3 | tran_type | [x] | character varying | 20 |  |
| 4 | action | [x] | character varying | 20 |  |
| 5 | invoice_number | [x] | bigint | 0 |  |
| 6 | tran_date | [ ] | date | 0 |  |
| 7 | amount | [x] | numeric | 1966086 |  |
| 8 | remarks | [x] | character varying | 4000 |  |
| 9 | audit_ts | [ ] | timestamp with time zone | 0 |  |

**Foreign Keys**

| # | Column Name | Key Name | References |
| --- | --- | --- | --- |
| 2 | [user_id](../account/users.md) | transaction_log_user_id_fkey | account.users.user_id |

**Indices**

| Index Name | Owner | Access Method | Definition | Description |
| --- | --- | --- | --- | --- |
| transaction_log_pkey | frapid_db_user | btree | log_id |  |

**Check Constraints**

| Constraint Name | Description |
| --- | --- |

**Default Values**

| # | Column Name | Default |
| --- | --- | --- |
| 1 | log_id | nextval('audit.transaction_log_log_id_seq'::regclass) |
| 9 | audit_ts | now() |

**Triggers**

| Trigger Name | Targets | On Event | Timing | Condition | Order | Orientation | Description |
| --- | --- | --- | --- | --- | --- | --- | --- |
| audit.disable_update_transaction_log | [audit.disable_update_transaction_log](../../functions/audit/disable_update_transaction_log-4458111.md) | UPDATE | AFTER |  | 0 | ROW |  |
| audit.disable_update_transaction_log | [audit.disable_update_transaction_log](../../functions/audit/disable_update_transaction_log-4458111.md) | DELETE | AFTER |  | 0 | ROW |  |

### Related Contents
* [Schema List](../../schemas.md)
* [Table List](../../tables.md)
* [Sequence List](../../sequences.md)
* [Table of Contents](../../README.md)


text:
namespace cds { namespace urcu { namespace details {

    template<> CDS_EXPORT_API singleton_vtbl * gp_singleton_instance< general_instant_tag >::s_pRCU = nullptr;
    template<> CDS_EXPORT_API singleton_vtbl * gp_singleton_instance< general_buffered_tag >::s_pRCU = nullptr;
    template<> CDS_EXPORT_API singleton_vtbl * gp_singleton_instance< general_threaded_tag >::s_pRCU = nullptr;

}}} // namespace cds::urcu::details


text:
package com.sabre.oss.conf4j.converter;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * This class converts {@link Short} to/from string.
 * <p>
 * It supports {@value #FORMAT} and {@value #LOCALE} meta-attributes, for more details see {@link AbstractNumberConverter}.
 */
public class ShortConverter extends AbstractNumberConverter<Short> {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isApplicable(Type type, Map<String, String> attributes) {
        return isApplicable(type, Short.class, Short.TYPE);
    }

    @Override
    protected Short parseWithoutFormat(String value) {
        return Short.valueOf(value);
    }

    @Override
    protected Short convertResult(Number value) {
        long longValue = value.longValue();
        if (longValue > Short.MAX_VALUE || longValue < Short.MIN_VALUE) {
            throw new IllegalArgumentException(String.format("Provided value: %d is out of Short type range.", longValue));
        }
        return value.shortValue();
    }
}


text:
id: administration-dashboard
title: Pulsar dashboard
sidebar_label: "Dashboard"
original_id: administration-dashboard
---

:::note

Pulsar dashboard is deprecated. We recommend you use [Pulsar Manager](administration-pulsar-manager) to manage and monitor the stats of your topics.

:::

Pulsar dashboard is a web application that enables users to monitor current stats for all [topics](reference-terminology.md#topic) in tabular form.

The dashboard is a data collector that polls stats from all the brokers in a Pulsar instance (across multiple clusters) and stores all the information in a [PostgreSQL](https://www.postgresql.org/) database.

You can use the [Django](https://www.djangoproject.com) web app to render the collected data.

## Install

The easiest way to use the dashboard is to run it inside a [Docker](https://www.docker.com/products/docker) container.

```shell

$ SERVICE_URL=http://broker.example.com:8080/
$ docker run -p 80:80 \
  -e SERVICE_URL=$SERVICE_URL \
  apachepulsar/pulsar-dashboard:@pulsar:version@

```

You can find the {@inject: github:Dockerfile:/dashboard/Dockerfile} in the `dashboard` directory and build an image from scratch as well:

```shell

$ docker build -t apachepulsar/pulsar-dashboard dashboard

```

If token authentication is enabled:
> Provided token should have super-user access.

```shell

$ SERVICE_URL=http://broker.example.com:8080/
$ JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
$ docker run -p 80:80 \
  -e SERVICE_URL=$SERVICE_URL \
  -e JWT_TOKEN=$JWT_TOKEN \
  apachepulsar/pulsar-dashboard

```

You need to specify only one service URL for a Pulsar cluster. Internally, the collector figures out all the existing clusters and the brokers from where it needs to pull the metrics. If you connect the dashboard to Pulsar running in standalone mode, the URL is `http://<broker-ip>:8080` by default. `<broker-ip>` is the IP address or hostname of the machine that runs Pulsar standalone. The IP address or hostname should be accessible from the running dashboard in the docker instance.

Once the Docker container starts, the web dashboard is accessible via `localhost` or whichever host that Docker uses.

> The `SERVICE_URL` that the dashboard uses needs to be reachable from inside the Docker container.

If the Pulsar service runs in standalone mode in `localhost`, the `SERVICE_URL` has to
be the IP address of the machine.

Similarly, given the Pulsar standalone advertises itself with localhost by default, you need to
explicitly set the advertise address to the host IP address. For example:

```shell

$ bin/pulsar standalone --advertised-address 1.2.3.4

```

### Known issues

Currently, only Pulsar Token [authentication](security-overview.md#authentication-providers) is supported.


text:
require 'serverspec'

include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS

describe service('supervisor') do
  it { should be_enabled }
  it { should be_running }
end

describe command('supervisorctl status') do
  it { should return_exit_status 0 }
end


text:
<?php

namespace App\Vdm;

// Composer lib used to extract contents from HTML pages
use Sunra\PhpSimple\HtmlDomParser;
// Post model
use App\Post;
use Underscore\Types\Arrays;
use Carbon\Carbon;

/**
* Fetches, extracts, formats and saves www.viedemerde.fr articles into Post models
*
* @package App\Vdm
*/

class Scraper
{
	/**
	* Base website url for specific Vdm page
	*
	* @var string
	*/
	private $baseUrl = "http://www.viedemerde.fr?page=%d";

	/**
	* Getter for baseUrl
	*
	* @return string
	*/
	public function getBaseUrl(){return $this->baseUrl;}

	/**
	* Setter for baseUrl
	*
	* @param string $url
	* @return       $this
	*/
	public function setBaseUrl($url){
		$this->baseUrl=$url;
		return $this;
	}

	/**
	* Retrieves the last $postCount articles from vdm and saves them into the database
	*
	* @param  int $postCount : the number of entries to retrieve
	* @return array<Post>
	*/
	public function scrap($postCount)
	{
		$articles = Scraper::getLatestPosts($postCount);

		return Arrays::each($articles, function($article){ return Scraper::persistPost($article); });
	}

	/**
	* Creates corresponding Post model for given DOM object
	*
	* @param  $article : the DOM object
	* @return $post    : Properly formated Post entity
	*/
	protected function persistPost($article)
	{
		$post = new Post();
		$post->content = Scraper::parseContent($article);
		$post->date = Scraper::parseDate($article);
		$post->author = Scraper::parseAuthor($article);
		$post->vdm_id = Scraper::parseVdmId($article);

		return $post;
	}

	/**
	* Crawls a DOM object to retrieve its content
	*
	* @param  $article : the DOM object
	* @return String
	*/
	protected function parseContent($article)
	{
		return trim($article->find('p',0)->plaintext);
	}

	/**
	* Crawls a DOM object to retrieve its date and formats it properly
	*
	* @param  $article : the DOM object
	* @return String
	*/
	protected function parseDate($article)
	{
		$dateDiv = $article->find('.date',0)->plaintext;
		// 2 digits followed by a / followed by 2 digits...
		preg_match("/(\d{2}[\/]{1}\d{2}[\/]{1}\d{4})(.*)(\d{2}[:]{1}\d{2})/i", $dateDiv, $matches);

		return Carbon::createFromFormat('d/m/Y à H:i', $matches[0])->toDateTimeString();
	}

	/**
	* Crawls a DOM object to retrieve its author
	*
	* @param  $article : the DOM object
	* @return String
	*/
	protected function parseAuthor($article)
	{
		$dateDiv = $article->find('.date',0)->find('p',1)->plaintext;
		// String starting by 'par', followed by a space, composed by a combinaison of any amount of the listed characters
		preg_match("/par\s+([a-zA-Z0-9_\-\.\s\#áàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸ]+)/i", $dateDiv, $matches);

		return trim($matches[1]);
	}

	/**
	* Crawls a DOM object to retrieve its vdm_id
	*
	* @param  $article : the DOM object
	* @return String
	*/
	protected function parseVdmId($article)
	{
		return $article->id;
	}

	/**
	* Retrieves the last $postCount from vdm
	*
	* @param  int $postCount : the number of entries to retrieve
	* @return mixed
	*/
	protected function getLatestPosts($postCount)
	{
		// posts array is empty
		$posts = [];
		// starting at page 0 (source achitecture)
		$pageId = 0;

		// fetching until enough posts are retrieved
		while (Arrays::size($posts) < $postCount)
		{
			$dom = HtmlDomParser::file_get_html(sprintf($this->getBaseUrl(), $pageId));
			$domPosts = $dom->find('.article');
			$posts = Arrays::merge($posts, $domPosts);

			$pageId++;
		}

		// sorting by descending date and keeping only the $postCount first entries
		return Arrays::from($posts)
				->sort('date', 'desc')
				->first($postCount)
				->obtain();
	}
}

?>


text:
/*
 */

#include "malattributes.h"

// MAL strings have to be allocated
mal_string_t *mal_string_new(char *char_content) {
  // Add final '\0'
  size_t bytes_count = strlen(char_content) + 1;
  char *self = (char *) calloc(bytes_count, sizeof(char));
  if (!self)
    return NULL;
  strncpy(self, char_content, bytes_count);
  return self;
}

void mal_string_destroy(mal_string_t **self_p) {
  if (*self_p != NULL) {
    free((*self_p));
    (*self_p) = NULL;
  }
}

size_t mal_string_get_char_count(mal_string_t *self) {
  return strlen(self);
}

void mal_string_test(bool verbose) {
  printf(" * mal_string: ");
  if (verbose)
    printf("\n");

  //  @selftest
  // ...
  //  @end
  printf("OK\n");
}


text:
// TypeScript Version: 2.0

/**
* Tests if an object's own property is configurable.
*
* @param value - value to test
* @param property - property to test
* @returns boolean indicating if an object property is configurable
*
* @example
* var defineProperty = require( `@stdlib/utils/define-property` );
*
* var obj = {
*     'boop': true
* };
*
* defineProperty( obj, 'beep', {
*     'configurable': false,
*     'enumerable': true,
*     'writable': true,
*     'value': true
* });
*
* var bool = isConfigurableProperty( obj, 'boop' );
* // returns true
*
* bool = isConfigurableProperty( obj, 'beep' );
* // returns false
*/
declare function isConfigurableProperty( value: any, property: any ): boolean;

// EXPORTS //

export = isConfigurableProperty;


text:
import {Component} from '@angular/core';
import {BaThemeSpinner} from '../../theme/services'
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html'
})
export class Dashboard {

  constructor(private _spinner:BaThemeSpinner) {
    this._spinner.hide();
  }

}


text:
  * Google [How to Read a Paper](https://www.google.com/search?q=how+to+read+a+paper) and read that paper. ETA: 10mins
  * Google [The Status of the P Versus NP Problem By Lance Fortnow](https://www.google.com/search?q=The+Status+of+the+P+Versus+NP+Problem+By+Lance+Fortnow) and do a "first pass" as described in "How to Read a Paper". ETA: 14mins

I don't expect you to know what this paper is about; don't get bogged down in details. Just see what you can get in the 14 minute skim.

For example:
> The discovery of the now-celebrated Code of Hammurabi (hereinafter simply termed "the Code") has made possible a more systematic study than could have resulted from just the classification and interpretation of other material. Fragments of other Ancient codes exist and have been published, but there still remain many points whereof evidence is still lacking. There survive legal texts from the earliest writings through the Hellenistic period, but evidence on a particular point may be very full for one period and almost entirely lacking for another.

I don't know anything about this subject, but we can tell a few things.
  * "The Code" is a pretty big deal
  * it's unusually complete or thorough
  * it relates to many other ancient texts

Just try to get a handle on the big picture: what's important, how the important things relate, and why we care.


text:
package com.rodrigodev.xgen4j.test.code.codeIdAndNameAreGeneratedWhenSpecified.code_9_name_c1.code_9_name_c2;

import com.rodrigodev.xgen4j.test.code.codeIdAndNameAreGeneratedWhenSpecified.code_9_name_c1.C1Error;

import com.rodrigodev.xgen4j.test.code.codeIdAndNameAreGeneratedWhenSpecified.ErrorCode;
import com.rodrigodev.xgen4j.test.code.codeIdAndNameAreGeneratedWhenSpecified.RootException;
import com.rodrigodev.xgen4j.test.code.codeIdAndNameAreGeneratedWhenSpecified.RootException.ExceptionType;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public abstract class C2Error extends C1Error {

    public static final ErrorCode CODE = new ErrorCode("code-9-name-c2", C1Error.CODE);

}


text:
namespace crashpad {

#pragma pack(push, 1)

//! \brief Structure read out of the client process by the crash handler when an
//!     exception occurs.
struct ExceptionInformation {
  //! \brief The address of the `siginfo_t` passed to the signal handler in the
  //!     crashed process.
  LinuxVMAddress siginfo_address;

  //! \brief The address of the `ucontext_t` passed to the signal handler in the
  //!     crashed process.
  LinuxVMAddress context_address;

  //! \brief The thread ID of the thread which received the signal.
  pid_t thread_id;
};

#pragma pack(pop)

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_LINUX_EXCEPTION_INFORMATION_H_