text:
#include "hw/sparc/sun4m.h"
#include "qemu/timer.h"
#include "hw/ptimer.h"
#include "hw/sysbus.h"
#include "trace.h"
#include "qemu/main-loop.h"

/*
 * Registers of hardware timer in sun4m.
 *
 * This is the timer/counter part of chip STP2001 (Slave I/O), also
 * produced as NCR89C105. See
 * http://www.ibiblio.org/pub/historic-linux/early-ports/Sparc/NCR/NCR89C105.txt
 *
 * The 31-bit counter is incremented every 500ns by bit 9. Bits 8..0
 * are zero. Bit 31 is 1 when count has been reached.
 *
 * Per-CPU timers interrupt local CPU, system timer uses normal
 * interrupt routing.
 *
 */

#define MAX_CPUS 16

typedef struct CPUTimerState {
    qemu_irq irq;
    ptimer_state *timer;
    uint32_t count, counthigh, reached;
    /* processor only */
    uint32_t run;
    uint64_t limit;
} CPUTimerState;

#define TYPE_SLAVIO_TIMER "slavio_timer"
#define SLAVIO_TIMER(obj) \
    OBJECT_CHECK(SLAVIO_TIMERState, (obj), TYPE_SLAVIO_TIMER)

typedef struct SLAVIO_TIMERState {
    SysBusDevice parent_obj;

    uint32_t num_cpus;
    uint32_t cputimer_mode;
    CPUTimerState cputimer[MAX_CPUS + 1];
} SLAVIO_TIMERState;

typedef struct TimerContext {
    MemoryRegion iomem;
    SLAVIO_TIMERState *s;
    unsigned int timer_index; /* 0 for system, 1 ... MAX_CPUS for CPU timers */
} TimerContext;

#define SYS_TIMER_SIZE 0x14
#define CPU_TIMER_SIZE 0x10

#define TIMER_LIMIT         0
#define TIMER_COUNTER       1
#define TIMER_COUNTER_NORST 2
#define TIMER_STATUS        3
#define TIMER_MODE          4

#define TIMER_COUNT_MASK32 0xfffffe00
#define TIMER_LIMIT_MASK32 0x7fffffff
#define TIMER_MAX_COUNT64  0x7ffffffffffffe00ULL
#define TIMER_MAX_COUNT32  0x7ffffe00ULL
#define TIMER_REACHED      0x80000000
#define TIMER_PERIOD       500ULL // 500ns
#define LIMIT_TO_PERIODS(l) (((l) >> 9) - 1)
#define PERIODS_TO_LIMIT(l) (((l) + 1) << 9)

static int slavio_timer_is_user(TimerContext *tc)
{
    SLAVIO_TIMERState *s = tc->s;
    unsigned int timer_index = tc->timer_index;

    return timer_index != 0 && (s->cputimer_mode & (1 << (timer_index - 1)));
}

// Update count, set irq, update expire_time
// Convert from ptimer countdown units
static void slavio_timer_get_out(CPUTimerState *t)
{
    uint64_t count, limit;

    if (t->limit == 0) { /* free-run system or processor counter */
        limit = TIMER_MAX_COUNT32;
    } else {
        limit = t->limit;
    }
    count = limit - PERIODS_TO_LIMIT(ptimer_get_count(t->timer));

    trace_slavio_timer_get_out(t->limit, t->counthigh, t->count);
    t->count = count & TIMER_COUNT_MASK32;
    t->counthigh = count >> 32;
}

// timer callback
static void slavio_timer_irq(void *opaque)
{
    TimerContext *tc = opaque;
    SLAVIO_TIMERState *s = tc->s;
    CPUTimerState *t = &s->cputimer[tc->timer_index];

    slavio_timer_get_out(t);
    trace_slavio_timer_irq(t->counthigh, t->count);
    /* if limit is 0 (free-run), there will be no match */
    if (t->limit != 0) {
        t->reached = TIMER_REACHED;
    }
    /* there is no interrupt if user timer or free-run */
    if (!slavio_timer_is_user(tc) && t->limit != 0) {
        qemu_irq_raise(t->irq);
    }
}

static uint64_t slavio_timer_mem_readl(void *opaque, hwaddr addr,
                                       unsigned size)
{
    TimerContext *tc = opaque;
    SLAVIO_TIMERState *s = tc->s;
    uint32_t saddr, ret;
    unsigned int timer_index = tc->timer_index;
    CPUTimerState *t = &s->cputimer[timer_index];

    saddr = addr >> 2;
    switch (saddr) {
    case TIMER_LIMIT:
        // read limit (system counter mode) or read most signifying
        // part of counter (user mode)
        if (slavio_timer_is_user(tc)) {
            // read user timer MSW
            slavio_timer_get_out(t);
            ret = t->counthigh | t->reached;
        } else {
            // read limit
            // clear irq
            qemu_irq_lower(t->irq);
            t->reached = 0;
            ret = t->limit & TIMER_LIMIT_MASK32;
        }
        break;
    case TIMER_COUNTER:
        // read counter and reached bit (system mode) or read lsbits
        // of counter (user mode)
        slavio_timer_get_out(t);
        if (slavio_timer_is_user(tc)) { // read user timer LSW
            ret = t->count & TIMER_MAX_COUNT64;
        } else { // read limit
            ret = (t->count & TIMER_MAX_COUNT32) |
                t->reached;
        }
        break;
    case TIMER_STATUS:
        // only available in processor counter/timer
        // read start/stop status
        if (timer_index > 0) {
            ret = t->run;
        } else {
            ret = 0;
        }
        break;
    case TIMER_MODE:
        // only available in system counter
        // read user/system mode
        ret = s->cputimer_mode;
        break;
    default:
        trace_slavio_timer_mem_readl_invalid(addr);
        ret = 0;
        break;
    }
    trace_slavio_timer_mem_readl(addr, ret);
    return ret;
}

static void slavio_timer_mem_writel(void *opaque, hwaddr addr,
                                    uint64_t val, unsigned size)
{
    TimerContext *tc = opaque;
    SLAVIO_TIMERState *s = tc->s;
    uint32_t saddr;
    unsigned int timer_index = tc->timer_index;
    CPUTimerState *t = &s->cputimer[timer_index];

    trace_slavio_timer_mem_writel(addr, val);
    saddr = addr >> 2;
    switch (saddr) {
    case TIMER_LIMIT:
        if (slavio_timer_is_user(tc)) {
            uint64_t count;

            // set user counter MSW, reset counter
            t->limit = TIMER_MAX_COUNT64;
            t->counthigh = val & (TIMER_MAX_COUNT64 >> 32);
            t->reached = 0;
            count = ((uint64_t)t->counthigh << 32) | t->count;
            trace_slavio_timer_mem_writel_limit(timer_index, count);
            ptimer_set_count(t->timer, LIMIT_TO_PERIODS(t->limit - count));
        } else {
            // set limit, reset counter
            qemu_irq_lower(t->irq);
            t->limit = val & TIMER_MAX_COUNT32;
            if (t->timer) {
                if (t->limit == 0) { /* free-run */
                    ptimer_set_limit(t->timer,
                                     LIMIT_TO_PERIODS(TIMER_MAX_COUNT32), 1);
                } else {
                    ptimer_set_limit(t->timer, LIMIT_TO_PERIODS(t->limit), 1);
                }
            }
        }
        break;
    case TIMER_COUNTER:
        if (slavio_timer_is_user(tc)) {
            uint64_t count;

            // set user counter LSW, reset counter
            t->limit = TIMER_MAX_COUNT64;
            t->count = val & TIMER_MAX_COUNT64;
            t->reached = 0;
            count = ((uint64_t)t->counthigh) << 32 | t->count;
            trace_slavio_timer_mem_writel_limit(timer_index, count);
            ptimer_set_count(t->timer, LIMIT_TO_PERIODS(t->limit - count));
        } else {
            trace_slavio_timer_mem_writel_counter_invalid();
        }
        break;
    case TIMER_COUNTER_NORST:
        // set limit without resetting counter
        t->limit = val & TIMER_MAX_COUNT32;
        if (t->limit == 0) { /* free-run */
            ptimer_set_limit(t->timer, LIMIT_TO_PERIODS(TIMER_MAX_COUNT32), 0);
        } else {
            ptimer_set_limit(t->timer, LIMIT_TO_PERIODS(t->limit), 0);
        }
        break;
    case TIMER_STATUS:
        if (slavio_timer_is_user(tc)) {
            // start/stop user counter
            if (val & 1) {
                trace_slavio_timer_mem_writel_status_start(timer_index);
                ptimer_run(t->timer, 0);
            } else {
                trace_slavio_timer_mem_writel_status_stop(timer_index);
                ptimer_stop(t->timer);
            }
        }
        t->run = val & 1;
        break;
    case TIMER_MODE:
        if (timer_index == 0) {
            unsigned int i;

            for (i = 0; i < s->num_cpus; i++) {
                unsigned int processor = 1 << i;
                CPUTimerState *curr_timer = &s->cputimer[i + 1];

                // check for a change in timer mode for this processor
                if ((val & processor) != (s->cputimer_mode & processor)) {
                    if (val & processor) { // counter -> user timer
                        qemu_irq_lower(curr_timer->irq);
                        // counters are always running
                        if (!curr_timer->run) {
                            ptimer_stop(curr_timer->timer);
                        }
                        // user timer limit is always the same
                        curr_timer->limit = TIMER_MAX_COUNT64;
                        ptimer_set_limit(curr_timer->timer,
                                         LIMIT_TO_PERIODS(curr_timer->limit),
                                         1);
                        // set this processors user timer bit in config
                        // register
                        s->cputimer_mode |= processor;
                        trace_slavio_timer_mem_writel_mode_user(timer_index);
                    } else { // user timer -> counter
                        // start the counter
                        ptimer_run(curr_timer->timer, 0);
                        // clear this processors user timer bit in config
                        // register
                        s->cputimer_mode &= ~processor;
                        trace_slavio_timer_mem_writel_mode_counter(timer_index);
                    }
                }
            }
        } else {
            trace_slavio_timer_mem_writel_mode_invalid();
        }
        break;
    default:
        trace_slavio_timer_mem_writel_invalid(addr);
        break;
    }
}

static const MemoryRegionOps slavio_timer_mem_ops = {
    .read = slavio_timer_mem_readl,
    .write = slavio_timer_mem_writel,
    .endianness = DEVICE_NATIVE_ENDIAN,
    .valid = {
        .min_access_size = 4,
        .max_access_size = 4,
    },
};

static const VMStateDescription vmstate_timer = {
    .name ="timer",
    .version_id = 3,
    .minimum_version_id = 3,
    .fields = (VMStateField[]) {
        VMSTATE_UINT64(limit, CPUTimerState),
        VMSTATE_UINT32(count, CPUTimerState),
        VMSTATE_UINT32(counthigh, CPUTimerState),
        VMSTATE_UINT32(reached, CPUTimerState),
        VMSTATE_UINT32(run    , CPUTimerState),
        VMSTATE_PTIMER(timer, CPUTimerState),
        VMSTATE_END_OF_LIST()
    }
};

static const VMStateDescription vmstate_slavio_timer = {
    .name ="slavio_timer",
    .version_id = 3,
    .minimum_version_id = 3,
    .fields = (VMStateField[]) {
        VMSTATE_STRUCT_ARRAY(cputimer, SLAVIO_TIMERState, MAX_CPUS + 1, 3,
                             vmstate_timer, CPUTimerState),
        VMSTATE_END_OF_LIST()
    }
};

static void slavio_timer_reset(DeviceState *d)
{
    SLAVIO_TIMERState *s = SLAVIO_TIMER(d);
    unsigned int i;
    CPUTimerState *curr_timer;

    for (i = 0; i <= MAX_CPUS; i++) {
        curr_timer = &s->cputimer[i];
        curr_timer->limit = 0;
        curr_timer->count = 0;
        curr_timer->reached = 0;
        if (i <= s->num_cpus) {
            ptimer_set_limit(curr_timer->timer,
                             LIMIT_TO_PERIODS(TIMER_MAX_COUNT32), 1);
            ptimer_run(curr_timer->timer, 0);
            curr_timer->run = 1;
        }
    }
    s->cputimer_mode = 0;
}

static int slavio_timer_init1(SysBusDevice *dev)
{
    SLAVIO_TIMERState *s = SLAVIO_TIMER(dev);
    QEMUBH *bh;
    unsigned int i;
    TimerContext *tc;

    for (i = 0; i <= MAX_CPUS; i++) {
        uint64_t size;
        char timer_name[20];

        tc = g_malloc0(sizeof(TimerContext));
        tc->s = s;
        tc->timer_index = i;

        bh = qemu_bh_new(slavio_timer_irq, tc);
        s->cputimer[i].timer = ptimer_init(bh);
        ptimer_set_period(s->cputimer[i].timer, TIMER_PERIOD);

        size = i == 0 ? SYS_TIMER_SIZE : CPU_TIMER_SIZE;
        snprintf(timer_name, sizeof(timer_name), "timer-%i", i);
        memory_region_init_io(&tc->iomem, OBJECT(s), &slavio_timer_mem_ops, tc,
                              timer_name, size);
        sysbus_init_mmio(dev, &tc->iomem);

        sysbus_init_irq(dev, &s->cputimer[i].irq);
    }

    return 0;
}

static Property slavio_timer_properties[] = {
    DEFINE_PROP_UINT32("num_cpus",  SLAVIO_TIMERState, num_cpus,  0),
    DEFINE_PROP_END_OF_LIST(),
};

static void slavio_timer_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = slavio_timer_init1;
    dc->reset = slavio_timer_reset;
    dc->vmsd = &vmstate_slavio_timer;
    dc->props = slavio_timer_properties;
}

static const TypeInfo slavio_timer_info = {
    .name          = TYPE_SLAVIO_TIMER,
    .parent        = TYPE_SYS_BUS_DEVICE,
    .instance_size = sizeof(SLAVIO_TIMERState),
    .class_init    = slavio_timer_class_init,
};

static void slavio_timer_register_types(void)
{
    type_register_static(&slavio_timer_info);
}

type_init(slavio_timer_register_types)


text:
from .base import *

__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"]

redpajama_set_name: RedPajamaGithub


text:
using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Conversion;
using SysConvert = System.Convert;

namespace Premotion.Mansion.Web.Hosting.Security
{
	/// <summary>
	/// Handles the conversion from <see cref="string"/> to <see cref="CsrfToken"/>.
	/// </summary>
	public class Base64ToCsrfTokenConverter : ConverterBase<string, CsrfToken>
	{
		#region Overrides of ConverterBase<string,CsrfToken>
		/// <summary>
		/// Converts the object to <see cref="IConverter.TargetType"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="source">The input value.</param>
		/// <param name="sourceType">The actual type of the source.</param>
		/// <returns>Returns the converted value.</returns>
		protected override CsrfToken DoConvert(IMansionContext context, string source, Type sourceType)
		{
			var signatureBytes = SysConvert.FromBase64String(source);
			return new CsrfToken(signatureBytes);
		}
		/// <summary>
		/// Converts the object to <see cref="IConverter.TargetType"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="source">The input value.</param>
		/// <param name="sourceType">The actual type of the source.</param>
		/// <param name="defaultValue">The default value.</param>
		/// <returns>Returns the converted value.</returns>
		protected override CsrfToken DoConvert(IMansionContext context, string source, Type sourceType, CsrfToken defaultValue)
		{
			try
			{
				return DoConvert(context, source, sourceType);
			}
			catch (Exception)
			{
				return defaultValue;
			}
		}
		#endregion
	}
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<evostack flatten="False">
  <optimizer name="Adadelta" learning_rate="0.075"/>
  <layers type="image">
    <layer dropout_rate="0.5" dropout_seed="89571" relu="False">
      <image operation="conv_bias" patch_size="6" stride="1" padding="SAME" output_channels="36" l2_factor="0.01">
        <initializer distribution="truncated" mean="0" scale="0.0375" seed="23428"/>
      </image>
    </layer>
    <layer dropout_rate="0" dropout_seed="57878" relu="False">
      <image operation="avg_pool" patch_size="20" stride="2" padding="SAME" output_channels="36" l2_factor="0">
        <initializer distribution="truncated" mean="1" scale="0.0680625" seed="65115"/>
      </image>
    </layer>
    <layer dropout_rate="0" dropout_seed="95538" relu="True">
      <image operation="conv_bias" patch_size="2" stride="2" padding="SAME" output_channels="120" l2_factor="0">
        <initializer distribution="normal" mean="0" scale="0.005671875" seed="37418"/>
      </image>
    </layer>
    <layer dropout_rate="0" dropout_seed="71526" relu="False">
      <image operation="conv_bias" patch_size="2" stride="2" padding="SAME" output_channels="200" l2_factor="0">
        <initializer distribution="normal" mean="0" scale="0.12375" seed="88073"/>
      </image>
    </layer>
    <layer dropout_rate="0.5" dropout_seed="51001" relu="False">
      <image operation="conv_bias" patch_size="3" stride="2" padding="SAME" output_channels="512" l2_factor="0">
        <initializer distribution="normal" mean="0" scale="0.05" seed="74251"/>
      </image>
    </layer>
    <layer dropout_rate="0" dropout_seed="51001" relu="False">
      <image operation="conv_bias" patch_size="1" stride="1" padding="SAME" output_channels="512" l2_factor="0">
        <initializer distribution="normal" mean="0" scale="0.05" seed="74251"/>
      </image>
    </layer>
  </layers>
  <layers type="expand">
    <layer dropout_rate="0" dropout_seed="84975" relu="True">
      <expand block_size="2" patch_size="4" padding="VALID" bias="True" l2_factor="0.01">
        <initializer distribution="normal" mean="1" scale="0.0075" seed="3696"/>
      </expand>
    </layer>
    <layer dropout_rate="0" dropout_seed="84975" relu="True">
      <expand block_size="2" patch_size="4" padding="VALID" bias="True" l2_factor="0.01">
        <initializer distribution="normal" mean="1" scale="0.0075" seed="3696"/>
      </expand>
    </layer>
    <layer dropout_rate="0" dropout_seed="84975" relu="True">
      <expand block_size="2" patch_size="4" padding="VALID" bias="True" l2_factor="0.01">
        <initializer distribution="normal" mean="1" scale="0.0075" seed="3696"/>
      </expand>
    </layer>
    <layer dropout_rate="0" dropout_seed="9481" relu="True">
      <expand block_size="2" patch_size="5" padding="VALID" bias="False" l2_factor="0">
        <initializer distribution="normal" mean="1" scale="0.0055" seed="36996"/>
      </expand>
    </layer>
    <layer dropout_rate="0" dropout_seed="8083" relu="False">
      <expand block_size="2" patch_size="5" padding="VALID" bias="True" l2_factor="0">
        <initializer distribution="normal" mean="0" scale="0.005" seed="22716"/>
      </expand>
    </layer>
  </layers>
</evostack>


text:
package com.venue.web.controller;

import java.util.Collection;

import com.venue.web.common.exception.IllegalEventProperties;
import com.venue.web.common.validator.EventValidator;
import com.venue.web.security.domain.factory.AuthenticationStatus;
import com.venue.web.security.domain.factory.StatusFactory;
import com.venue.web.service.EventService;
import com.venue.web.service.domain.Event;
import com.venue.web.service.domain.EventType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * package: com.venue.web.controller
 * date: 04.11.14
 *
 * Контроллер, предоставляющий методы для работы с объектом {@link com.venue.web.service.EventService}.
 *
 * @author Skurishin Vladislav
 */
@Controller
@RequestMapping("/eventService")
public class EventController
{
    @Autowired
    private EventValidator validator;

    @Autowired
    private EventService eventService;

    @Autowired
    private StatusFactory factory;

    /**
     * Add event to event manager.
     *
     * @param lng         - longitude.
     * @param lat         - latitude.
     * @param title       - title of event.
     * @param description - description of event.
     * @param size        - size of event.
     * @param type        - type of event.
     * @return authentication status
     * @see com.venue.web.service.EventService
     */
    @RequestMapping(value = "/createEvent", method = RequestMethod.POST)
    @ResponseBody
    public AuthenticationStatus createEvent(@RequestParam Double lng,
                                            @RequestParam Double lat,
                                            @RequestParam String title,
                                            @RequestParam String description,
                                            @RequestParam String size,
                                            @RequestParam String type)
    {
        try
        {
            validator.validate(lng, lat, title, description, size, type);
            eventService.create(lng, lat, title, description, size, type);
            return factory.successAuthenticationStatus();
        }
        catch (IllegalEventProperties e)
        {
            // Catch exception about incorrect event properties
            return factory.failureAuthenticationStatus(e.getMessage());
        }
    }

    /**
     * @return all events from event service in GeoJSON format.
     * @see com.venue.web.service.EventService
     * @see com.venue.web.service.domain.Event
     */
    @RequestMapping("events.geojson")
    @ResponseBody
    public Collection<Event> getEvents()
    {
        return eventService.getEvents();
    }

    /**
     * @return event with given id from event service in GeoJSON format.
     * @param id - event id
     * @see com.venue.web.service.EventService
     * @see com.venue.web.service.domain.Event
     */
    @RequestMapping("event.geojson")
    @ResponseBody
    public Event getEvent(@RequestParam Long id)
    {
        return eventService.getEvent(id);
    }

    /**
     * @return JSON array of strings. Each string is a name of type.
     * @see com.venue.web.service.domain.EventType
     */
    @RequestMapping("types.json")
    @ResponseBody
    public EventType[] getTypes()
    {
        return EventType.values();
    }
}


text:
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;

// This is in completely the wrong place.  It needs to be put in a proper place once we create a real
// interactive services assembly.

namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive
{
    // TODO(cyrusn): Use a predefined name here.
    [ExportCompletionProvider("LoadCommandCompletionProvider", InteractiveLanguageNames.InteractiveCommand)]
    internal partial class LoadCommandCompletionProvider : CompletionListProvider
    {
        private const string NetworkPath = "\\\\";
        private static readonly Regex s_directiveRegex = new Regex(@"#load\s+(""[^""]*""?)", RegexOptions.Compiled);

        public override async Task ProduceCompletionListAsync(CompletionListContext context)
        {
            var document = context.Document;
            var position = context.Position;
            var triggerInfo = context.TriggerInfo;
            var cancellationToken = context.CancellationToken;

            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var items = GetItems(text, position, triggerInfo, cancellationToken);

            context.AddItems(items);
        }

        public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
        {
            return PathCompletionUtilities.IsTriggerCharacter(text, characterPosition);
        }

        private string GetPathThroughLastSlash(SourceText text, int position, Group quotedPathGroup)
        {
            return PathCompletionUtilities.GetPathThroughLastSlash(
                quotedPath: quotedPathGroup.Value,
                quotedPathStart: GetQuotedPathStart(text, position, quotedPathGroup),
                position: position);
        }

        private TextSpan GetTextChangeSpan(SourceText text, int position, Group quotedPathGroup)
        {
            return PathCompletionUtilities.GetTextChangeSpan(
                quotedPath: quotedPathGroup.Value,
                quotedPathStart: GetQuotedPathStart(text, position, quotedPathGroup),
                position: position);
        }

        private static int GetQuotedPathStart(SourceText text, int position, Group quotedPathGroup)
        {
            return text.Lines.GetLineFromPosition(position).Start + quotedPathGroup.Index;
        }

        private ImmutableArray<CompletionItem> GetItems(SourceText text, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
        {
            var line = text.Lines.GetLineFromPosition(position);
            var lineText = text.ToString(TextSpan.FromBounds(line.Start, position));
            var match = s_directiveRegex.Match(lineText);
            if (!match.Success)
            {
                return ImmutableArray<CompletionItem>.Empty;
            }

            var quotedPathGroup = match.Groups[1];
            var quotedPath = quotedPathGroup.Value;
            var endsWithQuote = PathCompletionUtilities.EndsWithQuote(quotedPath);
            if (endsWithQuote && (position >= line.Start + match.Length))
            {
                return ImmutableArray<CompletionItem>.Empty;
            }

            var buffer = text.Container.GetTextBuffer();
            var snapshot = text.FindCorrespondingEditorTextSnapshot();
            if (snapshot == null)
            {
                return ImmutableArray<CompletionItem>.Empty;
            }

            var fileSystem = CurrentWorkingDirectoryDiscoveryService.GetService(snapshot);

            var searchPaths = ImmutableArray.Create(fileSystem.CurrentDirectory);

            var helper = new FileSystemCompletionHelper(
                this,
                GetTextChangeSpan(text, position, quotedPathGroup),
                fileSystem,
                Glyph.OpenFolder,
                Glyph.CSharpFile,
                searchPaths: searchPaths,
                allowableExtensions: new[] { ".csx" },
                itemRules: ItemRules.Instance);

            var pathThroughLastSlash = this.GetPathThroughLastSlash(text, position, quotedPathGroup);

            return helper.GetItems(pathThroughLastSlash, documentPath: null);
        }
    }
}


text:
package com.netflix.appinfo;

/**
 * Generally indicates the unique identifier of a {@link com.netflix.appinfo.DataCenterInfo}, if applicable.
 *
 * @author rthomas@atlassian.com
 */
public interface UniqueIdentifier {
    String getId();
}


text:
package org.spongycastle.mail.smime.handlers;

import kore.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import korex.activation.ActivationDataFlavor;
import korex.activation.DataContentHandler;
import korex.activation.DataSource;
import korex.mail.MessagingException;
import korex.mail.internet.MimeBodyPart;

public class x_pkcs7_signature
    implements DataContentHandler
{

    /*
     *
     *  VARIABLES
     *
     */

    private static final ActivationDataFlavor ADF;
    private static final DataFlavor[]         ADFs;

    static
    {
        ADF  = new ActivationDataFlavor(MimeBodyPart.class, "application/x-pkcs7-signature", "Signature");
        ADFs = new DataFlavor[] { ADF };
    }

    public Object getContent(DataSource _ds)
        throws IOException
    {
        return _ds.getInputStream();
    }

    public Object getTransferData(DataFlavor _df, DataSource _ds)
        throws IOException
    {
        if (ADF.equals(_df))
        {
            return getContent(_ds);
        }
        else
        {
            return null;
        }
    }

    public DataFlavor[] getTransferDataFlavors()
    {
        return ADFs;
    }

    public void writeTo(Object _obj, String _mimeType, OutputStream _os)
        throws IOException
    {
        if (_obj instanceof MimeBodyPart)
        {
            try
            {
                ((MimeBodyPart)_obj).writeTo(_os);
            }
            catch (MessagingException ex)
            {
                throw new IOException(ex.getMessage());
            }
        }
        else if (_obj instanceof byte[])
        {
            _os.write((byte[])_obj);
        }
        else if (_obj instanceof InputStream)
        {
            int            b;
            InputStream    in = (InputStream)_obj;

            while ((b = in.read()) >= 0)
            {
                _os.write(b);
            }
        }
        else
        {
            throw new IOException("unknown object in writeTo " + _obj);
        }
    }
}


text:
class SymbolIterator {
    next() {
        return {
            value: Symbol(),
            done: false
        };
    }

    [Symbol.iterator]() {
        return this;
    }
}

var array: number[] = [0, 1];
array.concat([...new SymbolIterator]);


text:
import createBanner from 'create-banner';
import postcss from 'rollup-plugin-postcss';
import typescript from 'rollup-plugin-typescript2';
import vue from 'rollup-plugin-vue';
import { pascalCase } from 'change-case';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';

const name = pascalCase(pkg.name.replace(/^.+\//, ''));
const banner = createBanner({
  data: {
    year: '2018-present',
  },
  template: 'inline',
});

export default ['umd', 'esm'].map((format) => ({
  input: 'src/index.ts',
  output: ['development', 'production'].map((mode) => {
    const output = {
      banner,
      format,
      name,
      file: pkg.main,
      globals: {
        vue: 'Vue',
      },
    };

    if (format === 'esm') {
      output.file = pkg.module;
    }

    if (mode === 'production') {
      output.compact = true;
      output.file = output.file.replace(/(\.js)$/, '.min$1');
      output.plugins = [
        terser(),
      ];
    }

    return output;
  }),
  external: Object.keys(pkg.peerDependencies),
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          declaration: format === 'esm',
        },
        exclude: [
          'docs',
          'tests',
        ],
      },
    }),
    vue({
      preprocessStyles: true,
    }),
    postcss({
      extensions: ['.css', '.scss'],
      minimize: true,
    }),
  ],
}));


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="../css/normalize.css">
        <link rel="stylesheet" href="../css/main.css">
        <link href="https://fonts.googleapis.com/css?family=Old+Standard+TT|Space+Mono" rel="stylesheet">

Parsons the New School for Design

The New School

BFA Illustration

Senior Thesis

2017 – 2018

←

Daniel Aviles

Sin Banderas

personal website

→

A series of images based off interviews with immigrants.

As a child of immigrants, I was interested in learning about the different circumstances that cause people to leave their birth country and how their views of a national identity is formed. Because each story is so different from each other, I wanted to make sure this would translate through the images. Each piece was approached with different mediums but some are tied through the use of paper cut-outs and watercolors. I wanted to create an effect that felt like a patchwork of memory based on the conversation with each person.

66 Fifth Avenue, New York, New York, 10003

                    Twitter
                    Instagram
                    Facebook
                    <scpan>↑</scpan>


text:
name             'sssd_ldap'
maintainer       'Tim Smith'
maintainer_email 'tsmith84@gmail.com'
license          'Apache 2.0'
description      'Installs/Configures LDAP on RHEL/Ubuntu using SSSD'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '2.0.1'

%w( redhat centos amazon scientific oracle ubuntu debian ).each do |os|
  supports os
end
source_url 'https://github.com/tas50/chef-sssd_ldap' if respond_to?(:source_url)
issues_url 'https://github.com/tas50/chef-sssd_ldap/issues' if respond_to?(:source_url)


text:
<?php

/* @var $this yii\web\View */

use yii\helpers\Html;
use yii\helpers\Url;

use frontend\widgets\Rating;
use kartik\markdown\Markdown;

use frontend\assets\Top10JsAsset;

$this->title = 'Category - '. $category->title;
$this->params['breadcrumbs'][] = $this->title;

$this->registerMetaTag([
            'name'=>'keywords',
            'content' => $category->meta_keywords
        ]);

$this->registerMetaTag([
            'name'=>'description',
            'content' => $category->meta_description
        ]);

Top10JsAsset::register($this);

$backgroundImage = $category->banner_background == 'default' ? '' : cloudinary_url($category->banner_background, array("width" => 1560, "height" => 233, "crop" => "fill"));

?>

       <div class="row" id="forex-header" <?= $backgroundImage ? 'style="background-image: url('. $backgroundImage .');"' : ''?>>

<?= $category->getTableHeading() ?>

<?= $category->banner_heading ?>

                <?php if ($category->banner_subheading)  { ?>

read more ...

<?= $category->banner_subheading ?>

                <?php } ?>

                <?php
                if (count($category->regulCates) > 0) {
                ?>

                    Filter by Regulation
                    <select id="reg-filter" class="selectpicker">
                      <option value="0" <?= !$filterSelected ? 'selected' : '' ?> >None</option>
                      <?php foreach($category->regulCates as $regulCate) { ?>
                      <option <?= $filterSelected == $regulCate->regulation_id ? 'selected' : '' ?> value="<?=$regulCate->regulation_id ?>"><?= $regulCate->regulation->title ?></option>
                      <?php } ?>
                    </select>

                  <?php } ?>

<?= $this->render('../include/_table', [
    'category' => $category,
    'cateComps' => $cateComps
]) ?>

<?= $category->table_risk ?>

<?= $category->getHowToHeading() ?>

                        <?= Markdown::convert($category->how_to_choose) ?>

<?= $this->render('../include/_reviewslider', [
    'category' => $category,
    'cateComps' => $cateComps
]) ?>

<?php

$this->registerJs(
   '$(document).ready(function(){

        var currentBaseUrl = "' . Url::current(['filter'=>null]) . '";
        $(document).on("change", "#reg-filter", function(e, id) {
            var id = $("#reg-filter").val();

            if (id >0 ) {
              window.location.href = currentBaseUrl + "?filter="+id;
            } else {
              window.location.href = currentBaseUrl;
            }
        });
    });'
);

?>


text:
<?php

namespace DataObjectTest;

/**
 * Right now this is only used in DataListTest, but extending it to DataObjectTest in the future would make sense.
 * Note that it was deliberated named to include "\N" to try and trip bad code up.
 */
class NamespacedClass extends \DataObject implements \TestOnly {
	private static $db = array(
		'Name' => 'Varchar',
	);

	private static $has_many = array(
		'Relations' => 'DataObjectTest\RelationClass'
	);
}

class RelationClass extends \DataObject implements \TestOnly {

	private static $db = array(
		'Title' => 'Varchar'
	);

	private static $has_one = array(
		'Parent' => 'DataObject'
	);
}


text:
from vivo_namespace import VIVO, OBO, FOAF, VCARD
from rdflib import RDF, RDFS, XSD, Literal
from utility import add_date, add_date_interval

class FundingCrosswalk:
    def __init__(self, identifier_strategy, create_strategy):
        self.identifier_strategy = identifier_strategy
        self.create_strategy = create_strategy

    def crosswalk(self, orcid_profile, person_uri, graph):
        if "fundings" in orcid_profile["activities-summary"]:
            # Funding
            for funding_group in orcid_profile["activities-summary"]["fundings"]["group"]:
                for funding in funding_group["funding-summary"]:
                    if funding["type"] == "GRANT":

                        title = funding["title"]["title"]["value"]
                        grant_uri = self.identifier_strategy.to_uri(VIVO.Grant, {"title": title})
                        # Type
                        graph.add((grant_uri, RDF.type, VIVO.Grant))

                        # Person
                        graph.add((grant_uri, VIVO.relates, person_uri))

                        # Title
                        graph.add((grant_uri, RDFS.label, Literal(title)))

                        # Role
                        role_uri = self.identifier_strategy.to_uri(VIVO.PrincipalInvestigatorRole,
                                                                   {"grant_uri": grant_uri})
                        graph.add((role_uri, RDF.type, VIVO.PrincipalInvestigatorRole))
                        # Inheres in
                        graph.add((role_uri, OBO.RO_0000052, person_uri))
                        graph.add((role_uri, VIVO.relatedBy, grant_uri))

                        # Date interval
                        (start_year, start_month, start_day) = FundingCrosswalk._get_date_parts("start-date", funding)
                        (end_year, end_month, end_day) = FundingCrosswalk._get_date_parts("end-date", funding)

                        add_date_interval(grant_uri, graph, self.identifier_strategy,
                                          add_date(start_year, graph, self.identifier_strategy, start_month, start_day),
                                          add_date(end_year, graph, self.identifier_strategy, end_month, end_day))

                        # Award amount
                        funding_amount = funding.get("amount")
                        if funding_amount is not None:
                            value = funding_amount.get("value")
                            if value is not None:
                                award_amount = "${:,}".format(int(value))
                                graph.add((grant_uri, VIVO.totalAwardAmount, Literal(award_amount)))

                        # Awarded by
                        if "organization" in funding:
                            organization_name = funding["organization"]["name"]
                            organization_uri = self.identifier_strategy.to_uri(FOAF.Organization,
                                                                               {"name": organization_name})
                            graph.add((grant_uri, VIVO.assignedBy, organization_uri))
                            if self.create_strategy.should_create(FOAF.Organization, organization_uri):
                                graph.add((organization_uri, RDF.type, FOAF.Organization))
                                graph.add((organization_uri, RDFS.label, Literal(organization_name)))

                        # Identifiers
                        if "external-ids" in funding and funding.get("external-ids"):
                            for external_identifier in funding["external-ids"]["external-id"]:
                                if "funding-external-identifier-value" in external_identifier:
                                    graph.add((grant_uri, VIVO.sponsorAwardId,
                                               Literal(external_identifier["external-id-value"])))
                                identifier_url = (external_identifier.get("external-id-url", {}) or {}).get("value")
                                if identifier_url:
                                    vcard_uri = self.identifier_strategy.to_uri(VCARD.Kind, {"url": identifier_url})
                                    graph.add((vcard_uri, RDF.type, VCARD.Kind))
                                    # Has contact info
                                    graph.add((grant_uri, OBO.ARG_2000028, vcard_uri))
                                    # Url vcard
                                    vcard_url_uri = self.identifier_strategy.to_uri(VCARD.URL, {"vcard_uri": vcard_uri})
                                    graph.add((vcard_url_uri, RDF.type, VCARD.URL))
                                    graph.add((vcard_uri, VCARD.hasURL, vcard_url_uri))
                                    graph.add((vcard_url_uri, VCARD.url, Literal(identifier_url, datatype=XSD.anyURI)))

    @staticmethod
    def _get_date_parts(field_name, funding):
        date = funding.get(field_name, {}) or {}
        return (date.get("year", {}) or {}).get("value"), \
               (date.get("month", {}) or {}).get("value"), \
               (date.get("day", {}) or {}).get("value")


text:
package org.opensingular.form.event;

import org.opensingular.form.SIList;
import org.opensingular.form.SInstance;

public class SInstanceListElementAddedEvent extends SInstanceStructureChangeEvent {

    private final SInstance addedInstance;
    private final int       index;

    public SInstanceListElementAddedEvent(SIList<? extends SInstance> source, SInstance addedInstance, int index) {
        super(source);
        this.addedInstance = addedInstance;
        this.index = index;
    }

    public SInstance getAddedInstance() {
        return addedInstance;
    }

    public int getIndex() {
        return index;
    }

    @Override
    public String toString() {
        return super.toString() + "[" + getIndex() + "] += " + getAddedInstance();
    }
}


text:
package org.apache.tez.test;

import java.util.List;
import java.util.Map;

import org.apache.tez.dag.api.InputDescriptor;
import org.apache.tez.dag.api.VertexManagerPlugin;
import org.apache.tez.dag.api.VertexManagerPluginContext;
import org.apache.tez.runtime.api.Event;
import org.apache.tez.runtime.api.events.VertexManagerEvent;

public class VertexManagerPluginForTest extends VertexManagerPlugin {

  @Override
  public void initialize(VertexManagerPluginContext context) {}

  @Override
  public void onVertexStarted(Map<String, List<Integer>> completions) {}

  @Override
  public void onSourceTaskCompleted(String srcVertexName, Integer taskId) {}

  @Override
  public void onVertexManagerEventReceived(VertexManagerEvent vmEvent) {}

  @Override
  public void onRootVertexInitialized(String inputName,
      InputDescriptor inputDescriptor, List<Event> events) {}
}


text:
import { ISuggestionBuilder } from "./ISuggestionBuilder";
import { ISuggestionOperations } from "./ISuggestionOperations";
import { SuggestionWithTerm } from "./SuggestionWithTerm";
import { SuggestionWithTerms } from "./SuggestionWithTerms";
import { throwError } from "../../../Exceptions";
import { TypeUtil } from "../../../Utility/TypeUtil";
import { SuggestionOptions } from "./SuggestionOptions";
import { SuggestionBase } from "./SuggestionBase";
import { Field } from "../../../Types";

export class SuggestionBuilder<T> implements ISuggestionBuilder<T>, ISuggestionOperations<T> {

    private _term: SuggestionWithTerm;
    private _terms: SuggestionWithTerms;

    public withDisplayName(displayName: string): ISuggestionOperations<T> {
        this.suggestion.displayField = displayName;
        return this;
    }

    public byField(fieldName: Field<T>, term: string): ISuggestionOperations<T>;
    public byField(fieldName: Field<T>, terms: string[]): ISuggestionOperations<T>;
    public byField(fieldName: Field<T>, termOrTerms: string | string[]): ISuggestionOperations<T> {
        if (!fieldName) {
            throwError("InvalidArgumentException", "fieldName cannot be null");
        }

        if (!termOrTerms) {
            throwError("InvalidArgumentException", "term cannot be null");
        }

        if (TypeUtil.isArray(termOrTerms)) {
            if (!termOrTerms.length) {
                throwError("InvalidArgumentException", "Terms cannot be an empty collection");
            }

            this._terms = new SuggestionWithTerms(fieldName);
            this._terms.terms = termOrTerms;

        } else {
            this._term = new SuggestionWithTerm(fieldName);
            this._term.term = termOrTerms;
        }

        return this;
    }

    public withOptions(options: SuggestionOptions): ISuggestionOperations<T> {
        this.suggestion.options = options;

        return this;
    }

    public get suggestion(): SuggestionBase {
        if (this._term) {
            return this._term;
        }

        return this._terms;
    }
}


text:
function con = Uzero(m)
%UZERO Default structure for Kronecker Bio experimental conditions
%
%   This function returns a valid, empty, experiment. It is used for
%   making experiments constructed by different means consistent so that
%   their structures can be combined.
%
%   Inputs
%   m: [ Kronecker model structure scalar ]
%
%   Outputs:
%   con: [ Kronecker experimental condition structure scalar ]
%       The experiment returned by this function is pretty useless, but the
%       fields can be overwritten. Their meanings are given below.
%       .Type 'Experiment'
%       .Name [ string ]
%           An aribitrary name for the experiment
%       .tF [ nonnegative scalar ]
%           The time at which this experiment ends.
%       .s [ nonnegative vector ns ]
%           The values of the seed parameters
%       .u [ handle @(t) returns nonnegative matrix nu by numel(t) ]
%           A function handle that returns the value of the inputs at any
%           time t. This function should accept t as a vector.
%       .q [ real vector nq ]
%           The values of the input control parameters
%       .dudq [ handle @(t) returns real matrix nu by nq]
%           A function handle that returns the derivative of each input
%           with respect to each input control parameter
%       .nq [ whole scalar ]
%           The number of input control parameters
%       .nqu [ whole vector nv ]
%           The number of input control parameters associated with each
%           input
%       .SteadyState [ logical scalar ]
%           Declares if the system should be run to steady state before
%           the experiment begins
%       .Periodic [ logical scalar ]
%           Declares if the system should be run to a periodic steady state
%           for the duration of the experiment
%       .Discontinuities [ nonegative vector ]
%           Any discontinuous times in the u function must be listed here
%           in order to ensure sucessful integration of the system.
%       .Update [handle @(s,q) returns struct scalar ]
%           This function handle allows the parameter values of the
%           experiment to be changed. Each vector x0 and q must have the
%           same size as their appropriate counterparts. The structure
%           returned is identical to the one to which Update is attached
%           except that the parameter values have been changed and the
%           appropriate matrices and function handles have been updated.

% (c) 2011 David R Hagen & Bruce Tidor
% This work is released under the MIT license.

% Special case of numeric inputs
if isnumeric(m)
    con = emptystruct(m, 'Type', 'Name', 'tF', 's', 'u', 'q', 'dudq', 'nq', 'SteadyState', 'Periodic', 'Discontinuities', 'Update');
    return
end

% Constants
nu = m.nu;
s = m.s;

% Gut m
temp = m;
clear m
m.nu = temp.nu;
m.ns = temp.ns;
m.s = temp.s;
clear temp

con.Type = 'Experiment';
con.Name = 'UnnamedExperiment';
con.tF = 0;
con.s = s;
con.u  = @(t)zeros(nu,1);
con.q  = zeros(0,1);
con.dudq = @(t)zeros(nu,0);
con.nq = 0;
con.SteadyState = false;
con.Periodic = false;
con.Discontinuities = zeros(0,1);
con.Update = @Update;

    function con = Update(s, q)
        assert(numel(q) == 0, 'KroneckerBio:Experiment:Update:InvalidInputControl', 'An input control parameter vector was supplied with %i elements, but the input of this experiment is controlled by 0 input parameters. They must be the same.', numel(q))
        con = Experiment(m, 0, s, false, false, zeros(nu,1), [], q);
    end
end


text:
package biweekly.issues;

import static org.junit.Assert.assertEquals;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.junit.Test;

import biweekly.Biweekly;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import biweekly.util.com.google.ical.compat.javautil.DateIterator;

/**
 * @author Michael Angstadt
 * @see "https://github.com/mangstadt/biweekly/issues/67"
 */
public class Issue67 {
	/*
	 * These tests failed for user Dupplicate under the default timezone "CET"
	 * RRuleIteratorImplTest#dailyUntilDec4
	 * RRuleIteratorImplTest#advanceTo
	 */

	@Test
	public void carolinelane10() throws Exception {
		ICalendar ical = Biweekly.parseJson(Issue67.class.getResourceAsStream("issue67.json")).first();
		VEvent vEvent = ical.getEvents().get(0);

		TimeZone eventTimezone = TimeZone.getTimeZone("America/New_York");
		DateIterator iterator = vEvent.getDateIterator(eventTimezone);

		List<Date> actual = new ArrayList<Date>();
		while (iterator.hasNext()) {
			Date startDate = iterator.next();
			actual.add(startDate);
		}

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		df.setTimeZone(eventTimezone);

		List<Date> expected = Arrays.asList( //@formatter:off
			df.parse("2017-03-22T12:00:00"),
			df.parse("2017-03-29T12:00:00")
		); //@formatter:on

		assertEquals(expected, actual);
	}
}


text:
package jpl.ch14.ex03;

public class Number {
	private int f_num = 0;
	public synchronized void addNum(int num) {
		f_num = f_num + num;
	}
	public synchronized int getNum() {
		return f_num;
	}
}


text:
namespace base {

namespace {

absl::optional<PlatformThreadId> GetPlatformThreadIdForScope(
    SampleMetadataScope scope) {
  if (scope == SampleMetadataScope::kProcess)
    return absl::nullopt;
  return PlatformThread::CurrentId();
}

}  // namespace

SampleMetadata::SampleMetadata(StringPiece name, SampleMetadataScope scope)
    : name_hash_(HashMetricName(name)), scope_(scope) {}

void SampleMetadata::Set(int64_t value) {
  GetSampleMetadataRecorder()->Set(name_hash_, absl::nullopt,
                                   GetPlatformThreadIdForScope(scope_), value);
}

void SampleMetadata::Set(int64_t key, int64_t value) {
  GetSampleMetadataRecorder()->Set(name_hash_, key,
                                   GetPlatformThreadIdForScope(scope_), value);
}

void SampleMetadata::Remove() {
  GetSampleMetadataRecorder()->Remove(name_hash_, absl::nullopt,
                                      GetPlatformThreadIdForScope(scope_));
}

void SampleMetadata::Remove(int64_t key) {
  GetSampleMetadataRecorder()->Remove(name_hash_, key,
                                      GetPlatformThreadIdForScope(scope_));
}

ScopedSampleMetadata::ScopedSampleMetadata(StringPiece name,
                                           int64_t value,
                                           SampleMetadataScope scope)
    : name_hash_(HashMetricName(name)),
      thread_id_(GetPlatformThreadIdForScope(scope)) {
  GetSampleMetadataRecorder()->Set(name_hash_, absl::nullopt, thread_id_,
                                   value);
}

ScopedSampleMetadata::ScopedSampleMetadata(StringPiece name,
                                           int64_t key,
                                           int64_t value,
                                           SampleMetadataScope scope)
    : name_hash_(HashMetricName(name)),
      key_(key),
      thread_id_(GetPlatformThreadIdForScope(scope)) {
  GetSampleMetadataRecorder()->Set(name_hash_, key, thread_id_, value);
}

ScopedSampleMetadata::~ScopedSampleMetadata() {
  GetSampleMetadataRecorder()->Remove(name_hash_, key_, thread_id_);
}

// This function is friended by StackSamplingProfiler so must live directly in
// the base namespace.
void ApplyMetadataToPastSamplesImpl(
    TimeTicks period_start,
    TimeTicks period_end,
    uint64_t name_hash,
    absl::optional<int64_t> key,
    int64_t value,
    absl::optional<PlatformThreadId> thread_id) {
  StackSamplingProfiler::ApplyMetadataToPastSamples(
      period_start, period_end, name_hash, key, value, thread_id);
}

void ApplyMetadataToPastSamples(TimeTicks period_start,
                                TimeTicks period_end,
                                StringPiece name,
                                int64_t value,
                                SampleMetadataScope scope) {
  return ApplyMetadataToPastSamplesImpl(
      period_start, period_end, HashMetricName(name), absl::nullopt, value,
      GetPlatformThreadIdForScope(scope));
}

void ApplyMetadataToPastSamples(TimeTicks period_start,
                                TimeTicks period_end,
                                StringPiece name,
                                int64_t key,
                                int64_t value,
                                SampleMetadataScope scope) {
  return ApplyMetadataToPastSamplesImpl(period_start, period_end,
                                        HashMetricName(name), key, value,
                                        GetPlatformThreadIdForScope(scope));
}

MetadataRecorder* GetSampleMetadataRecorder() {
  static NoDestructor<MetadataRecorder> instance;
  return instance.get();
}

}  // namespace base


text:
require 'fileutils'
require 'tempfile'

module Sprockets
  # Internal: File and path related utilities. Mixed into Environment.
  #
  # Probably would be called FileUtils, but that causes namespace annoyances
  # when code actually wants to reference ::FileUtils.
  module PathUtils
    extend self

    # Internal: Like `File.stat`.
    #
    # path - String file or directory path
    #
    # Returns nil if the file does not exist.
    def stat(path)
      if File.exist?(path)
        File.stat(path.to_s)
      else
        nil
      end
    end

    # Internal: Like `File.file?`.
    #
    # path - String file path.
    #
    # Returns true path exists and is a file.
    def file?(path)
      if stat = self.stat(path)
        stat.file?
      else
        false
      end
    end

    # Internal: A version of `Dir.entries` that filters out `.` files and `~`
    # swap files.
    #
    # path - String directory path
    #
    # Returns an empty `Array` if the directory does not exist.
    def entries(path)
      if File.directory?(path)
        Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort
      else
        []
      end
    end

    # Internal: Check if path is absolute or relative.
    #
    # path - String path.
    #
    # Returns true if path is absolute, otherwise false.
    if File::ALT_SEPARATOR
      # On Windows, ALT_SEPARATOR is \
      def absolute_path?(path)
        path[0] == File::SEPARATOR || path[0] == File::ALT_SEPARATOR
      end
    else
      def absolute_path?(path)
        path[0] == File::SEPARATOR
      end
    end

    # Internal: Check if path is explicitly relative.
    # Starts with "./" or "../".
    #
    # path - String path.
    #
    # Returns true if path is relative, otherwise false.
    def relative_path?(path)
      path =~ /^\.\.?($|\/)/ ? true : false
    end

    # Internal: Get relative path for root path and subpath.
    #
    # path    - String path
    # subpath - String subpath of path
    #
    # Returns relative String path if subpath is a subpath of path, or nil if
    # subpath is outside of path.
    def split_subpath(path, subpath)
      path = File.join(path, '')
      if subpath.start_with?(path)
        subpath[path.length..-1]
      else
        nil
      end
    end

    # Internal: Detect root path and base for file in a set of paths.
    #
    # paths    - Array of String paths
    # filename - String path of file expected to be in one of the paths.
    #
    # Returns [String root, String path]
    def paths_split(paths, filename)
      paths.each do |path|
        if subpath = split_subpath(path, filename)
          return path, subpath
        end
      end
      nil
    end

    # Internal: Get path's extensions.
    #
    # path - String
    #
    # Returns an Array of String extnames.
    def path_extnames(path)
      File.basename(path).scan(/\.[^.]+/)
    end

    # Internal: Stat all the files under a directory.
    #
    # dir - A String directory
    #
    # Returns an Enumerator of [path, stat].
    def stat_directory(dir)
      return to_enum(__method__, dir) unless block_given?

      self.entries(dir).each do |entry|
        path = File.join(dir, entry)
        if stat = self.stat(path)
          yield path, stat
        end
      end

      nil
    end

    # Internal: Recursive stat all the files under a directory.
    #
    # dir - A String directory
    #
    # Returns an Enumerator of [path, stat].
    def stat_tree(dir, &block)
      return to_enum(__method__, dir) unless block_given?

      self.stat_directory(dir) do |path, stat|
        yield path, stat

        if stat.directory?
          stat_tree(path, &block)
        end
      end

      nil
    end

    # Internal: Write to a file atomically. Useful for situations where you
    # don't want other processes or threads to see half-written files.
    #
    #   Utils.atomic_write('important.file') do |file|
    #     file.write('hello')
    #   end
    #
    # If your temp directory is not on the same filesystem as the file you're
    # trying to write, you can provide a different temporary directory.
    #
    #   Utils.atomic_write('/data/something.important', '/data/tmp') do |file|
    #     file.write('hello')
    #   end
    #
    # Taken from ActiveSupport.
    #
    # https://github.com/rails/rails/blob/master/
    #   activesupport/lib/active_support/core_ext/file/atomic.rb
    def atomic_write(file_name, temp_dir = Dir.tmpdir)
      temp_file = Tempfile.new(File.basename(file_name), temp_dir)
      temp_file.binmode
      yield temp_file
      temp_file.close

      if File.exist?(file_name)
        # Get original file permissions
        old_stat = File.stat(file_name)
      else
        # If not possible, probe which are the default permissions in the
        # destination directory.
        old_stat = probe_stat_in(File.dirname(file_name))
      end

      # Overwrite original file with temp file
      FileUtils.mv(temp_file.path, file_name)

      # Set correct permissions on new file
      begin
        File.chown(old_stat.uid, old_stat.gid, file_name)
        # This operation will affect filesystem ACL's
        File.chmod(old_stat.mode, file_name)
      rescue Errno::EPERM
        # Changing file ownership failed, moving on.
      end
    end

    # Internal: Taken from ActiveSupport.
    #
    # https://github.com/rails/rails/blob/master/
    #   activesupport/lib/active_support/core_ext/file/atomic.rb
    def probe_stat_in(dir)
      basename = [
        '.permissions_check',
        Thread.current.object_id,
        Process.pid,
        rand(1000000)
      ].join('.')

      file_name = File.join(dir, basename)
      FileUtils.touch(file_name)
      File.stat(file_name)
    ensure
      FileUtils.rm_f(file_name) if file_name
    end
  end
end


text:
#ifndef __FOO_H__
#define __FOO_H__

#define NAXSI_VERSION "0.52"

#include <nginx.h>
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_event.h>
#include <ngx_md5.h>
#include <ngx_http_core_module.h>
#include <pcre.h>
#include <ctype.h>

#include <ngx_http_whitelist.h>

extern ngx_module_t ngx_http_naxsi_module;

#define UPDATE_C(js) js->c = *(js->src + js->off)

/*
** Here is globally how the structures are organized :
**
** [[ngx_http_dummy_main_conf_t]] is the main structure for the module.
** it contains the core rules and a set of ngx_http_dummy_loc_conf_t,
** for each NGINX location.
** ---
** [[ngx_http_dummy_loc_conf_t]] is the main structure for any NGINX
** locations, that is - a web site. It contains both pointers to the core
** rules, as well as whitelists, scores, denied_url and all flags. all
** the data of a nginx location is held into the loc_conf_t struct.
** The sets of rules are actually containted into [[ngx_http_rule_t]] structs.
** ---
** [[ngx_http_rule_t]] structs are used to hold any info about a rule, as well
** as whitelists. (whitelists is just a 'kind' of rule).
**
*/

enum MATCH_TYPE {
  URI_ONLY=0,
  NAME_ONLY,
  MIXED
};

enum DUMMY_MATCH_ZONE {
  HEADERS=0,
  URL,
  ARGS,
  BODY,
  FILE_EXT,
  UNKNOWN
};

/*
** struct used to store a specific match zone
** in conf : MATCH_ZONE:[GET_VAR|HEADER|POST_VAR]:VAR_NAME:
*/
typedef struct
{
  /* match in [name] var of body */
  ngx_flag_t		body_var:1;
  /* match in [name] var of headers */
  ngx_flag_t		headers_var:1;
  /* match in [name] var of args */
  ngx_flag_t		args_var:1;
  /* match on URL [name] */
  ngx_flag_t		specific_url:1;
  ngx_str_t		target;
  /* to be used for regexed match zones */
  ngx_regex_compile_t	*target_rx;
  ngx_uint_t		hash;

} ngx_http_custom_rule_location_t;

/*
** WhiteList Rules Definition :
** A whitelist contains :
** - an URI
**
** - one or several sets containing :
**	- an variable name ('foo') associated with a zone ($GET_VAR:foo)
**	- one or several rules id to whitelist
*/

#define WEIRD_REQUEST_INTERNAL_RULE_ID 1
#define BIG_BODY_INTERNAL_RULE_ID 2
typedef struct
{
  /* match in full body (POST DATA) */
  ngx_flag_t		body:1;
  /* match in [name] var of body */
  ngx_flag_t		body_var:1;
  /* match in all headers */
  ngx_flag_t		headers:1;
  /* match in [name] var of headers */
  ngx_flag_t		headers_var:1;
  /* match in URI */
  ngx_flag_t		url:1;
  /* match in args (bla.php?<ARGS>) */
  ngx_flag_t		args:1;
  /* match in [name] var of args */
  ngx_flag_t		args_var:1;
  /* match on a global flag : weird_request, big_body etc. */
  ngx_flag_t		flags:1;
  /* match on file upload extension */
  ngx_flag_t		file_ext:1;
  /* set if defined "custom" match zone (GET_VAR/POST_VAR/...)  */
  ngx_array_t		*ids;
  ngx_str_t		*name;
} ngx_http_whitelist_location_t;

/*
** this struct is used to aggregate all whitelist
** that point to the same URI or the same VARNAME
** all the "subrules" will then be stored in the "whitelist_locations"
*/
typedef struct
{
  /*ngx_http_whitelist_location_t **/
  ngx_array_t			*whitelist_locations;
  /* zone to wich the WL applies */
  enum DUMMY_MATCH_ZONE		zone;
  /* if the "name" is only an url, specify it */
  int				uri_only:1;
  /* does the rule targets the name
     instead of the content ?*/
  int				target_name;

  ngx_str_t			*name;
  ngx_int_t			hash;
  ngx_array_t			*ids;
} ngx_http_whitelist_rule_t;

/* basic rule */
typedef struct
{
  ngx_str_t		*str; // string
  ngx_regex_compile_t   *rx;  // or regex
  ngx_int_t		rx_mz;
  /* ~~~~~ match zones ~~~~~~ */
  ngx_int_t			zone;
  /* match in full body (POST DATA) */
  ngx_flag_t		body:1;
  ngx_flag_t		body_var:1;
  /* match in all headers */
  ngx_flag_t		headers:1;
  ngx_flag_t		headers_var:1;
  /* match in URI */
  ngx_flag_t		url:1;
  /* match in args (bla.php?<ARGS>) */
  ngx_flag_t		args:1;
  ngx_flag_t		args_var:1;
  /* match on flags (weird_uri, big_body etc. */
  ngx_flag_t		flags:1;
  /* match on file upload extension */
  ngx_flag_t		file_ext:1;
  /* set if defined "custom" match zone (GET_VAR/POST_VAR/...)  */
  ngx_flag_t		custom_location:1;
  ngx_int_t		custom_location_only;
  /* does the rule targets variable name instead ? */
  ngx_int_t		target_name;

  /* custom location match zones list (GET_VAR/POST_VAR ...) */
  ngx_array_t		*custom_locations;
  /* ~~~~~~~ specific flags ~~~~~~~~~ */
  ngx_flag_t		negative:1;
} ngx_http_basic_rule_t;

/* define for RULE TYPE in rule_t */
#define BR 1

/* flags used for 'custom match rules', like $XSS > 7 */
#define SUP 1
#define SUP_OR_EQUAL 2
#define INF 3
#define INF_OR_EQUAL 4

/*
** This struct is used to store custom scores at runtime.
**  ie : $XSS = 7
** tag is the $XSS and sc_score is 7
*/
typedef struct
{
  ngx_str_t	*sc_tag;
  ngx_int_t	sc_score;
  ngx_flag_t	block:1;
  ngx_flag_t	allow:1;
  ngx_flag_t	drop:1;
  ngx_flag_t	log:1;
} ngx_http_special_score_t;

/*
** This one is very related to the previous one,
** it's used to store a score rule comparison.
** ie : $XSS > 7
*/
typedef struct
{
  ngx_str_t	sc_tag;
  ngx_int_t	sc_score;
  ngx_int_t	cmp;
  ngx_flag_t	block:1;
  ngx_flag_t	allow:1;
  ngx_flag_t	drop:1;
  ngx_flag_t	log:1;
} ngx_http_check_rule_t;

/* TOP level rule structure */
typedef struct
{
  /* type of the rule */
  ngx_int_t			type;
  /* simply put a flag if it's a wlr,
     wl_id array will be used to store the whitelisted IDs */
  ngx_flag_t			whitelist:1;
  ngx_array_t			*wlid_array;
  /* "common" data for all rules */
  ngx_int_t			rule_id;
  ngx_str_t			*log_msg; // a specific log message
  ngx_int_t			score; //also handles DENY and ALLOW

  /* List of scores increased on rule match. */
  ngx_array_t			*sscores;
  ngx_flag_t			sc_block:1; //
  ngx_flag_t			sc_allow:1; //
  // end of specific score tag stuff
  ngx_flag_t			block:1;
  ngx_flag_t			allow:1;
  ngx_flag_t			drop:1;
  ngx_flag_t			log:1;
  /* pointers on specific rule stuff */
  ngx_http_basic_rule_t		*br;
} ngx_http_rule_t;

typedef struct
{
  ngx_array_t	*get_rules; /*ngx_http_rule_t*/
  ngx_array_t	*body_rules;
  ngx_array_t	*header_rules;
  ngx_array_t	*generic_rules;
  ngx_array_t	*locations; /*ngx_http_dummy_loc_conf_t*/
  ngx_log_t	*log;

} ngx_http_dummy_main_conf_t;

/* TOP level configuration structure */
typedef struct
{
  ngx_array_t	*get_rules;
  ngx_array_t	*body_rules;
  ngx_array_t	*header_rules;
  ngx_array_t	*generic_rules;
  ngx_array_t	*check_rules;
  /* raw array of whitelisted rules */
  ngx_array_t   *whitelist_rules;
  /* raw array of transformed whitelists */
  ngx_array_t	*tmp_wlr;
  /* raw array of regex-mz whitelists */
  ngx_array_t   *rxmz_wlr;
  /* hash table of whitelisted URL rules */
  ngx_hash_t	*wlr_url_hash;
  /* hash table of whitelisted ARGS rules */
  ngx_hash_t	*wlr_args_hash;
  /* hash table of whitelisted BODY rules */
  ngx_hash_t	*wlr_body_hash;
  /* hash table of whitelisted HEADERS rules */
  ngx_hash_t	*wlr_headers_hash;
  /* rules that are globally disabled in one location */
  ngx_array_t	*disabled_rules;
  /* counters for both processed requests and
     blocked requests, used in naxsi_fmt */
  size_t	request_processed;
  size_t	request_blocked;
  ngx_int_t	error;
  ngx_array_t	*persistant_data;
  ngx_flag_t	extensive:1;
  ngx_flag_t	learning:1;
  ngx_flag_t	enabled:1;
  ngx_flag_t	force_disabled:1;
  ngx_flag_t	pushed:1;
  ngx_str_t	*denied_url;
  /* precomputed hash for dynamic variable lookup,
     variable themselves are boolean */
  ngx_uint_t	flag_enable_h;
  ngx_uint_t	flag_learning_h;
  ngx_uint_t	flag_post_action_h;
  ngx_uint_t	flag_extensive_log_h;

  /* whitelist */
  ngx_http_wl_variables_t whitelist;
} ngx_http_dummy_loc_conf_t;

/*
** used to store sets of matched rules during runtime
*/
typedef struct
{
  /* matched in [name] var of body */
  ngx_flag_t		body_var:1;
  /* matched in [name] var of headers */
  ngx_flag_t		headers_var:1;
  /* matched in [name] var of args */
  ngx_flag_t		args_var:1;
  /* matched on URL */
  ngx_flag_t		url:1;
  /* matched in filename [name] of args*/
  ngx_flag_t		file_ext:1;
  /* matched within the 'NAME' */
  ngx_flag_t		target_name:1;

  ngx_str_t		*name;
  ngx_http_rule_t	*rule;
} ngx_http_matched_rule_t;

/*
** Context structure
*/
typedef struct
{
  ngx_array_t	*special_scores;
  ngx_int_t	score;
  /* blocking flags */
  ngx_flag_t	log:1;
  ngx_flag_t	block:1;
  ngx_flag_t	allow:1;
  ngx_flag_t	drop:1;
  /* state */
  ngx_flag_t	wait_for_body:1;
  ngx_flag_t	ready:1;
  ngx_flag_t	over:1;
  /* matched rules */
  ngx_array_t	*matched;
  /* runtime flags (modifiers) */
  ngx_flag_t	learning:1;
  ngx_flag_t	enabled:1;
  ngx_flag_t	post_action:1;
  ngx_flag_t	extensive_log:1;

} ngx_http_request_ctx_t;

/*
** this structure is used only for json parsing.
*/
typedef struct ngx_http_nx_json_s {
  ngx_str_t	json;
  u_char	*src;
  ngx_int_t	off, len;
  u_char	c;
  int		depth;
  ngx_http_request_t *r;
  ngx_http_request_ctx_t *ctx;
  ngx_str_t	ckey;
  ngx_http_dummy_main_conf_t	*main_cf;
  ngx_http_dummy_loc_conf_t	*loc_cf;
} ngx_json_t;

#define TOP_DENIED_URL_T	"DeniedUrl"
#define TOP_LEARNING_FLAG_T	"LearningMode"
#define TOP_ENABLED_FLAG_T	"SecRulesEnabled"
#define TOP_DISABLED_FLAG_T	"SecRulesDisabled"
#define TOP_CHECK_RULE_T	"CheckRule"
#define TOP_BASIC_RULE_T	"BasicRule"
#define TOP_MAIN_BASIC_RULE_T	"MainRule"

/* nginx-style names */
#define TOP_DENIED_URL_N	"denied_url"
#define TOP_LEARNING_FLAG_N	"learning_mode"
#define TOP_ENABLED_FLAG_N	"rules_enabled"
#define TOP_DISABLED_FLAG_N	"rules_disabled"
#define TOP_CHECK_RULE_N	"check_rule"
#define TOP_BASIC_RULE_N	"basic_rule"
#define TOP_MAIN_BASIC_RULE_N	"main_rule"

/*possible 'tokens' in rule */
#define ID_T "id:"
#define SCORE_T "s:"
#define MSG_T "msg:"
#define RX_T "rx:"
#define STR_T "str:"
#define MATCH_ZONE_T "mz:"
#define WHITELIST_T "wl:"
#define NEGATIVE_T  "negative"

/*
** name of hardcoded variables to
** change behavior of naxsi at runtime
*/
#define RT_EXTENSIVE_LOG "naxsi_extensive_log"
#define RT_ENABLE "naxsi_flag_enable"
#define RT_LEARNING "naxsi_flag_learning"
#define RT_POST_ACTION "naxsi_flag_post_action"

/*
** To avoid getting DoS'ed, define max depth
** for JSON parser, as it is recursive
*/
#define JSON_MAX_DEPTH 10

void			*ngx_http_dummy_cfg_parse_one_rule(ngx_conf_t *cf,
							   ngx_str_t	*value,
							   ngx_http_rule_t *rule,
							   ngx_int_t	nb_elem);
char			*strfaststr(unsigned char *haystack, unsigned int hl,
				    unsigned char *needle, unsigned int nl);
char			*strnchr(const char *s, int c, int len);
char			*strncasechr(const char *s, int c, int len);
ngx_int_t		ngx_http_dummy_create_hashtables(ngx_http_dummy_loc_conf_t *dlc,
							 ngx_conf_t *cf);
ngx_int_t		ngx_http_dummy_create_hashtables_n(ngx_http_dummy_loc_conf_t *dlc,
							   ngx_conf_t *cf);
void			ngx_http_dummy_data_parse(ngx_http_request_ctx_t *ctx,
						  ngx_http_request_t	 *r);
ngx_int_t		ngx_http_output_forbidden_page(ngx_http_request_ctx_t *ctx,
						       ngx_http_request_t *r);
int			naxsi_unescape_uri(u_char **dst, u_char **src, size_t size,
					   ngx_uint_t type);

int			nx_check_ids(ngx_int_t match_id, ngx_array_t *wl_ids);
int			naxsi_unescape(ngx_str_t *str);

void			ngx_http_dummy_json_parse(ngx_http_request_ctx_t *ctx,
						  ngx_http_request_t	 *r,
						  u_char		 *src,
						  u_int			 len);

/*
** JSON parsing prototypes.
*/
ngx_int_t		ngx_http_nx_json_forward(ngx_json_t *js) ;
ngx_int_t		ngx_http_nx_json_seek(ngx_json_t *js, unsigned char seek);
ngx_int_t		ngx_http_nx_json_quoted(ngx_json_t *js, ngx_str_t *ve);
ngx_int_t		ngx_http_nx_json_array(ngx_json_t *js);
ngx_int_t		ngx_http_nx_json_val(ngx_json_t *js);
ngx_int_t		ngx_http_nx_json_obj(ngx_json_t *js);

/*
** naxsi_runtime
**
*/

void			ngx_http_dummy_update_current_ctx_status(ngx_http_request_ctx_t	*ctx,
								 ngx_http_dummy_loc_conf_t *cf,
								 ngx_http_request_t *r);
int			ngx_http_process_basic_rule_buffer(ngx_str_t *str, ngx_http_rule_t *rl,
							   ngx_int_t *match);
void			ngx_http_dummy_payload_handler(ngx_http_request_t *r);
int			ngx_http_basestr_ruleset_n(ngx_pool_t *pool,
						   ngx_str_t	*name,
						   ngx_str_t	*value,
						   ngx_array_t *rules,
						   ngx_http_request_t *req,
						   ngx_http_request_ctx_t *ctx,
						   enum DUMMY_MATCH_ZONE zone);
void			ngx_http_dummy_body_parse(ngx_http_request_ctx_t *ctx,
						  ngx_http_request_t	 *r,
						  ngx_http_dummy_loc_conf_t *cf,
						  ngx_http_dummy_main_conf_t *main_cf);
void			naxsi_log_offending(ngx_str_t *name, ngx_str_t *val, ngx_http_request_t *req,
					    ngx_http_rule_t *rule, enum DUMMY_MATCH_ZONE zone);

int			ngx_http_apply_rulematch_v_n(ngx_http_rule_t *r, ngx_http_request_ctx_t *ctx,
						     ngx_http_request_t *req, ngx_str_t *name,
						     ngx_str_t *value, enum DUMMY_MATCH_ZONE zone,
						     ngx_int_t nb_match, ngx_int_t target_name);

#endif


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.youtube.model;

/**
 * Model definition for LiveChatUserBannedMessageDetails.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the YouTube Data API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class LiveChatUserBannedMessageDetails extends com.google.api.client.json.GenericJson {

  /**
   * The duration of the ban. This property is only present if the banType is temporary.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.math.BigInteger banDurationSeconds;

  /**
   * The type of ban.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String banType;

  /**
   * The details of the user that was banned.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ChannelProfileDetails bannedUserDetails;

  /**
   * The duration of the ban. This property is only present if the banType is temporary.
   * @return value or {@code null} for none
   */
  public java.math.BigInteger getBanDurationSeconds() {
    return banDurationSeconds;
  }

  /**
   * The duration of the ban. This property is only present if the banType is temporary.
   * @param banDurationSeconds banDurationSeconds or {@code null} for none
   */
  public LiveChatUserBannedMessageDetails setBanDurationSeconds(java.math.BigInteger banDurationSeconds) {
    this.banDurationSeconds = banDurationSeconds;
    return this;
  }

  /**
   * The type of ban.
   * @return value or {@code null} for none
   */
  public java.lang.String getBanType() {
    return banType;
  }

  /**
   * The type of ban.
   * @param banType banType or {@code null} for none
   */
  public LiveChatUserBannedMessageDetails setBanType(java.lang.String banType) {
    this.banType = banType;
    return this;
  }

  /**
   * The details of the user that was banned.
   * @return value or {@code null} for none
   */
  public ChannelProfileDetails getBannedUserDetails() {
    return bannedUserDetails;
  }

  /**
   * The details of the user that was banned.
   * @param bannedUserDetails bannedUserDetails or {@code null} for none
   */
  public LiveChatUserBannedMessageDetails setBannedUserDetails(ChannelProfileDetails bannedUserDetails) {
    this.bannedUserDetails = bannedUserDetails;
    return this;
  }

  @Override
  public LiveChatUserBannedMessageDetails set(String fieldName, Object value) {
    return (LiveChatUserBannedMessageDetails) super.set(fieldName, value);
  }

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

}


text:
SRTk is a collection of scripts to find the split-read alignments of sequences
using an inexact algorithm. SRTk is under active development and we hope to
release it as part of a larger package in upcoming months.

## REQUIREMENTS
STRBait should work on any standard 64 bit Linux environment with

- GCC
- Python version >= 2.7
- Cython

The following two python libraries should be installed on the system

- pysam
- numpy

## ACKNOWLEDGEMENTS
SRTk uses LASTZ (http://www.bx.psu.edu/~rsharris/lastz/newer) >= 1.03.66 to
align the sequences to the reference genome.

## INSTALLATION
python, gcc are normally pre-installed on most Linux systems. If not,
please go ahead and install them. Cython is required as well, and might need to
be installed on some systems.

Please do the following in the top level directory of the distribution:
```
make
```
This should create a `bin` folder and copy all the required binaries to it.
Please make sure that following files are in the `bin` folder:
```
align.sh
align_reads_with_lz
combine_alignments
combine_alignments.so
find_best_split
find_best_split.so
sr_sam
sr_sam.so
```

## DESCRIPTION
SRTk is a collection of scripts to output a SAM file with the split-read
alignments of sequences in a sample. The script of interest is called sr_sam

```
Find the best split alignments for reads that carry signatures of SVs.
    usage:
      sr_sam [options] reference.fa [splitters.bam] unmapped.fq.gz

    where the options are:
        -h,--help      : print usage and quit
        -d,--debug     : print debug information
        -m,--maxsplits : allow up to maxsplits primary and supplemental
                         alignments [2]
        -c,--coverage  : require at least this fraction of the read to be aligned
                         in the primary alignment [0.5]
        -l,--lastz     : the path to the LASTZ (32 bit version) binary [lastz_32]
        -t,--threads   : number of threads to use [1]
        -1,--onlylz    : only use LASTZ. default is to use both BWA and LASTZ
        -v,--version   : print version of the code and exit

    1. reference.fa is the reference sequence in fasta format.
    2. splitters.bam is a indexed BAM file with the clipped reads
    3. unmapped.fq.gz is a zipped file of sequences that did not align
       to the reference
```

This script collects all the split read alignments from BWA or some other
aligner. It also uses LASTZ to align the unmapped reads to the reference, and
outputs the best set of split alignments that cover the query. The output can
then be given as input to LUMPY to find the SVs.

## TEST-DATASET
A test dataset is provided with the distribution in the `tests` folder.

Run
```
make
```

and that should run some simple tests to make sure that the program is working
as expected.


text:
/**
 * Module dependencies.
 */
import * as express from "express";
import * as compression from "compression";  // compresses requests
import * as session from "express-session";
import * as bodyParser from "body-parser";
import * as logger from "morgan";
import * as errorHandler from "errorhandler";
import * as lusca from "lusca";
import * as dotenv from "dotenv";
import * as mongo from "connect-mongo"; // (session)
import * as flash from "express-flash";
import * as path from "path";
import * as mongoose from "mongoose";
import * as passport from "passport";
import expressValidator = require("express-validator");

import { default as ProcessManager } from './utils/processManager';

let processManager = ProcessManager.getInstance();

import Miner from './utils/miner';

const MongoStore = mongo(session);

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.config({ path: ".env" });

/**
 * Controllers
 */

import * as miningController from "./controllers/miner";
import * as dataController from "./controllers/data";

/**
 * API keys and Passport configuration.
 */
import * as passportConfig from "./config/passport";

/**
 * Create Express server
 */
const app = express();

/**
 * Connect to MongoDB.
 */
(<any>mongoose).Promise = Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);

mongoose.connection.on("error", () => {
  console.log("MongoDB connection error. Please make sure MongoDB is running.");
  process.exit();
});

/**
 * Express configuration.
 */
app.set("port", process.env.PORT || 3030);
// app.set("views", path.join(__dirname, "../views"));
// app.set("view engine", "pug");
app.use(compression());
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
// app.use(session({
//   resave: true,
//   saveUninitialized: true,
//   secret: process.env.SESSION_SECRET,
//   store: new MongoStore({
//     url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
//     autoReconnect: true
//   })
// }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(lusca.xframe("SAMEORIGIN"));
app.use(lusca.xssProtection(true));
// app.use((req, res, next) => {
//   res.locals.user = req.user;
//   next();
// });
// app.use((req, res, next) => {
//   // After successful login, redirect back to the intended page
//   if (!req.user &&
//       req.path !== "/login" &&
//       req.path !== "/signup" &&
//       !req.path.match(/^\/auth/) &&
//       !req.path.match(/\./)) {
//     req.session.returnTo = req.path;
//   } else if (req.user &&
//       req.path == "/account") {
//     req.session.returnTo = req.path;
//   }
//   next();
// });

// serve static ReactJS build
app.use(express.static(path.join(__dirname, "../../react-client/public"), { maxAge: 31557600000 }));

// Allow cross-origin requests
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'content-type');
    next();
})

// Primary app routes.

// Serve the ReactJS index.html and bundle.js files
// from the client project folder
app.get("/", (req, res) => {
  res.sendFile(path.resolve(__dirname, '../../react-client/index.html'))
});

/**
 * OAuth authentication routes. (Sign in)
 */
app.get("/auth/facebook", passport.authenticate("facebook", { scope: ["email", "public_profile"] }));
app.get("/auth/facebook/callback", passport.authenticate("facebook", { failureRedirect: "/login" }), (req, res) => {
  res.redirect(req.session.returnTo || "/");
});

// return the mapbox access token
app.get("/get_mapbox_token", dataController.getMapBoxToken);

app.get("/activate_miner", miningController.getTurnOn);
app.get("/deactivate_miner", miningController.getTurnOff);

// poll this endpoint to get realtime data on the twitter miner
app.get("/mining_status", miningController.getMiningData);

app.get("/tweet_data", dataController.getAll);
app.get("/console", dataController.getConsole);

/**
 * Error Handler. Provides full stack - remove for production
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get("port"), () => {
  console.log(("  App is running at http://localhost:%d in %s mode"), app.get("port"), app.get("env"));
  console.log("  Press CTRL-C to stop\n");
});

module.exports = app;


text:
<template name="category_item">

		<form>

          Save

<input id="name_{{_id}}" type="text" value="{{name}}" />

          Slug: /{{slug}}

      </form>

</template>


text:
<?php
declare(strict_types=1);
namespace Ivory\Type\Postgresql;

use Ivory\Exception\InternalException;
use Ivory\Exception\ParseException;
use Ivory\Type\ITotallyOrderedType;
use Ivory\Type\IType;
use Ivory\Type\TypeBase;

/**
 * Array type object.
 *
 * Note that arrays in PHP and PostgreSQL are completely different beasts. In PHP, "arrays" are in fact sorted hash maps
 * with string or integer keys, or a mixture of both, having no restrictions on the elements. In PostgreSQL, arrays are
 * much closer to other programming languages: all the elements must be of the same type and dimension (i.e.,
 * multidimensional arrays must be "rectangular") and are indexed using a continuous sequence of integers.
 *
 * Moreover, PHP arrays are zero-based by default, whereas PostgreSQL defaults to one-based arrays; in both, the bounds
 * may be explicitly specified, however.
 *
 * The array type object has two modes: *strict* and *plain*. Simply said, the strict mode converts the arrays including
 * the element indexes, whereas the plain mode ignores array indexes completely. *Strict mode is the default.*
 *
 * **Restrictions on values to be converted:**
 * - an array type object always supports just one type of array elements - the one for which the object was created;
 * - when serializing a PHP array to PostgreSQL, the array is refused if it is invalid for PostgreSQL (i.e., if the
 *   elements are of different types or dimensions, or - in the strict mode - if the array uses string keys or has gaps
 *   within the keys).
 *
 * **Behaviour according to the mode:**
 * * In the strict mode, the type object does not rebase the elements - the arrays are converted as is, including the
 *   bounds. However, when serializing a PHP array to PostgreSQL, the array gets sorted by its keys, i.e., the original
 *   order gets lost.
 * * In the plain mode, the type object merely iterates through the array and puts each item in the result, ignoring the
 *   array keys completely. The elements are not sorted by their keys. When converting arrays from PostgreSQL to PHP,
 *   zero-based arrays are created. Conversely, arrays from PHP are converted to one-based PostgreSQL arrays.
 *
 * @see https://www.postgresql.org/docs/11/arrays.html
 */
class ArrayType extends TypeBase implements ITotallyOrderedType
{
    private $elemType;
    private $delim;
    private $elemNeedsQuotesRegex;
    private $ignoreIndexes = false;

    public function __construct(IType $elemType, string $delimiter)
    {
        parent::__construct(
            $elemType->getSchemaName(),
            $elemType->getName() . '[]',
            '[]'
        );

        $this->elemType = $elemType;
        $this->delim = $delimiter;
        $this->elemNeedsQuotesRegex = '~[{}\\s"\\\\' . preg_quote($delimiter, '~') . ']|^NULL$|^$~i';
    }

    public function switchToPlainMode(): void
    {
        $this->ignoreIndexes = true;
    }

    public function switchToStrictMode(): void
    {
        $this->ignoreIndexes = false;
    }

    private function throwParseException(
        string $str,
        string $errMsg = null,
        int $offset = null,
        \Exception $cause = null
    ): void {
        $elemTypeName = $this->elemType->getSchemaName() . '.' . $this->elemType->getName();
        $msg = "Value '$str' is not valid for an array of type $elemTypeName";
        if (strlen($errMsg) > 0) {
            $msg .= ": $errMsg";
        }
        throw new ParseException($msg, $offset, 0, $cause);
    }

    public function parseValue(string $extRepr)
    {
        // OPT: The parser processes any string which is legal for the PostgreSQL input. Considering it would only be
        //      used for processing output from PostgreSQL, more limited syntax might be accepted, which would be
        //      simpler and faster; namely, in the output, there are neither whitespace nor backslash-escaped
        //      characters outside of double-quoted strings.

        $strOffset = 0;

        while (isset($extRepr[$strOffset]) && ctype_space($extRepr[$strOffset])) {
            $strOffset++;
        }

        if ($extRepr[$strOffset] == '[') { // explicit bounds specification
            $decorSepPos = strpos($extRepr, '=');
            $decoration = substr($extRepr, 0, $decorSepPos);

            preg_match_all('~\[(\d+):\d+]~', $decoration, $m);
            if ($decorSepPos === false || !$m) {
                $this->throwParseException($extRepr, 'Invalid array bounds decoration');
            }
            $strOffset = $decorSepPos + 1;
            while (isset($extRepr[$strOffset]) && ctype_space($extRepr[$strOffset])) {
                $strOffset++;
            }
            $lowerBounds = $m[1];
            unset($m);
        } else {
            if (trim($extRepr) == '{}') {
                return [];
            }
            $dims = 0;
            $len = strlen($extRepr);
            for ($i = $strOffset; $i < $len; $i++) {
                if (ctype_space($extRepr[$i])) {
                    continue;
                } elseif ($extRepr[$i] == '{') {
                    $dims++;
                } else {
                    break;
                }
            }
            if ($dims == 0) {
                $this->throwParseException($extRepr, "Expected '{'", 0);
            }
            $lowerBounds = array_fill(0, $dims, 1);
        }

        if ($this->ignoreIndexes) {
            $lowerBounds = array_fill(0, count($lowerBounds), 0);
        }

        $result = [];
        $d = preg_quote($this->delim, '~');
        $elemRegex = '~
                       "(?:[^"\\\\]|\\\\.)*"        # either a double-quoted string (backslashes used for escaping)
                       |                            # or an unquoted string of characters which do not confuse the
                                                    # parser or are backslash-escaped, leading and trailing whitespace
                                                    # being ignored:
                       (?:[^"{}\s\\\\' . $d . ']|\\\\.)+      # starting with non-special, non-whitespace characters,
                       (?:\s+(?:[^"{}\\\\' . $d . ']|\\\\.)*  # optionally followed by non-special characters,
                          (?:[^"{}\s\\\\' . $d . ']|\\\\.)+   # ending again with non-special, non-whitespace characters
                       )?
                      ~x';
        preg_match_all($elemRegex, $extRepr, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE, $strOffset);
        if (!$matches) {
            $this->throwParseException($extRepr, 'Invalid array syntax');
        }

        $strOffset++;
        // the current dimension of the input being processed
        $dim = 0;
        // map: dimension => key under which to add the next element in the dimension
        $keys = [$dim => $lowerBounds[$dim]];
        // map: dimension => reference to the array to add the next element to at the dimension
        $refs = [$dim => &$result];

        foreach ($matches[0] as [$elem, $elemOffset]) {
            for (; $strOffset < $elemOffset; $strOffset++) {
                $c = $extRepr[$strOffset];
                if (ctype_space($c)) {
                    continue;
                }
                switch ($c) {
                    case '{':
                        $dim++;
                        $keys[$dim] = $lowerBounds[$dim];
                        $refs[$dim] = &$refs[$dim - 1][$keys[$dim - 1]];
                        $refs[$dim] = [];
                        break;
                    case '}':
                        $dim--;
                        break;
                    case $this->delim:
                        $keys[$dim]++;
                        break;
                    default:
                        $this->throwParseException($extRepr, "Unexpected array decoration character '$c'", $strOffset);
                }
            }

            try {
                $k = $keys[$dim];
                if (strcasecmp($elem, 'NULL') == 0) {
                    $refs[$dim][$k] = null;
                } else {
                    $cont = ($elem[0] == '"' ? substr($elem, 1, -1) : $elem);
                    $unEsc = preg_replace('~\\\\(.)~', '$1', $cont);
                    $refs[$dim][$k] = $this->elemType->parseValue($unEsc);
                }
            } catch (ParseException $e) {
                $this->throwParseException($extRepr, 'Error parsing the element value', $strOffset, $e);
            }
            $strOffset += strlen($elem);
        }

        return $result;
    }

    /**
     * Serializes an array to the corresponding SQL literal.
     *
     * {@inheritDoc}
     *
     * Note that, in the strict mode, the `ARRAY[1,2,3]` syntax cannot be used as it does not allow for specifying
     * custom array bounds. Instead, the string representation (e.g., `'{1,2,3}'`) is employed.
     *
     * @todo eliminate recursion, process multidimensional arrays using iteration instead
     */
    public function serializeValue($val, bool $strictType = true): string
    {
        if ($val !== null && !is_array($val)) {
            throw new \InvalidArgumentException("Value '$val' is not valid for array type");
        }

        if ($this->ignoreIndexes) {
            $str = $this->serializeValuePlain($val);
        } else {
            $str = $this->serializeValueStrict($val, $bounds);

            $needsDimDecoration = false;
            foreach ($bounds as $b) {
                if ($b[0] != 1) {
                    $needsDimDecoration = true;
                    break;
                }
            }
            if ($needsDimDecoration) {
                $dimDec = '';
                foreach ($bounds as $b) {
                    $dimDec .= "[{$b[0]}:{$b[1]}]";
                }
                $str = "$dimDec=$str";
            }

            $str = "'$str'"; // NOTE: literal single quotes in serialized elements are already doubled
        }

        return $this->typeCastExpr($strictType, $str);
    }

    /**
     * @param array|null $val the value to serialize
     * @param int[] $dims list: for each dimension, the size of the array is mentioned
     * @param int $curDim the current dimension being processed (zero-based)
     * @param int $maxDim the maximal dimension discovered so far
     * @return string the PostgreSQL external representation of <tt>$val</tt>
     */
    private function serializeValuePlain(?array $val, array &$dims = [], int $curDim = 0, int &$maxDim = -1): string
    {
        if ($val === null) {
            return 'NULL';
        }

        if ($curDim > $maxDim) {
            $maxDim = $curDim;
            $expSize = count($val);
            $dims[$curDim] = $expSize;
        } else {
            $expSize = $dims[$curDim];
            if ($expSize != count($val)) {
                $itemDesc = print_r($val, true);
                $msg = "The array is not rectangular: item $itemDesc contains a wrong number of elements";
                throw new \InvalidArgumentException($msg);
            }
        }

        $out = ($curDim == 0 ? 'ARRAY[' : '[');
        $first = true;
        foreach ($val as $v) {
            if ($first) {
                $first = false;
            } else {
                $out .= $this->delim;
            }

            if (is_array($v)) {
                $out .= $this->serializeValuePlain($v, $dims, $curDim + 1, $maxDim);
            } else {
                if ($curDim != $maxDim) {
                    $msg = "Some array items do not match the dimensions of the array: " . print_r($val, true);
                    throw new \InvalidArgumentException($msg);
                }

                $out .= $this->elemType->serializeValue($v, false);
            }
        }
        $out .= ']';

        return $out;
    }

    /**
     * @param array|null $val the value to serialize
     * @param int[][] $bounds list: for each dimension, a pair of from-to subscripts is mentioned
     * @param int $curDim the current dimension being processed (zero-based)
     * @param int $maxDim the maximal dimension discovered so far
     * @return string the PostgreSQL external representation of <tt>$val</tt>
     */
    private function serializeValueStrict(?array $val, ?array &$bounds = [], int $curDim = 0, int &$maxDim = -1): string
    {
        if ($val === null) {
            return 'NULL';
        }

        $arr = $val;
        ksort($arr);
        $keys = array_keys($arr);

        if ($curDim > $maxDim) {
            $maxDim = $curDim;
            $b = ($arr ? [$keys[0], $keys[count($keys) - 1]] : [1, 0]);
            $bounds[$curDim] = $b;
        } else {
            $b = $bounds[$curDim];
            if ($keys[0] < $b[0] || $keys[count($keys) - 1] > $b[1]) {
                $msg = "Some array subscripts do not match the bounds of the array: " . print_r($val, true);
                throw new \InvalidArgumentException($msg);
            }
        }
        if (count($arr) != ($b[1] - $b[0] + 1)) {
            $msg = "The array subscripts do not form a continuous sequence: " . print_r($val, true);
            throw new \InvalidArgumentException($msg);
        }

        $out = '{';
        $first = true;
        foreach ($arr as $v) {
            if ($first) {
                $first = false;
            } else {
                $out .= $this->delim;
            }

            if (is_array($v)) {
                $out .= $this->serializeValueStrict($v, $bounds, $curDim + 1, $maxDim);
            } else {
                if ($curDim != $maxDim) { // it should have been an array
                    $msg = "Some array items do not match the dimensions of the array: " . print_r($val, true);
                    throw new \InvalidArgumentException($msg);
                }

                if ($v === null) {
                    $valOut = 'NULL';
                } else {
                    $valOut = $this->elemType->serializeValue($v, false);
                    /* Trim the single quotes and other decoration - the value will be used inside a string literal.
                       As an optimization, doubled single quotes (meaning the literal single quote) will be preserved
                       not to undo and do the job again on the whole array.
                     */
                    $beg = strpos($valOut, "'");
                    if ($beg !== false) {
                        $end = strrpos($valOut, "'");
                        if ($beg == $end) {
                            throw new InternalException("Malformed element value serialization: $valOut");
                        }
                        $valOut = substr($valOut, $beg + 1, $end - $beg - 1);
                    }
                    if (preg_match($this->elemNeedsQuotesRegex, $valOut)) {
                        $valOut = '"' . strtr($valOut, ['"' => '\\"', '\\' => '\\\\']) . '"';
                    }
                }

                $out .= $valOut;
            }
        }
        $out .= '}';

        return $out;
    }
}