text:
extern const NSString *kKRMusicPlayerAlbumIdentifier; //NSNumber
extern const NSString *kKRMusicPlayerAlbumName;       //NSString
extern const NSString *kKRMusicPlayerAlbumImage;      //UIImage
extern const NSString *kKRMusicPlayerSongerName;      //NSString
extern const NSString *kKRMusicPlayerSongIdentifier;  //NSNumber
extern const NSString *kKRMusicPlayerSongName;        //NSString

typedef void(^PlaybackChangeHandler)(BOOL stop, MPMusicPlaybackState playbackState);
typedef void(^PlayingItemChangeHandler)(NSNumber *itemPersistentId, NSUInteger songIndex);
typedef void(^VolumeChangeHandler)(CGFloat volume);
typedef void(^PlayingTimeChangeHandler)(CGFloat playingTime, NSString *timeString);

typedef enum PlaybackStates
{
    //初始狀態
    PlaybackStateNone = 0,
    //準備播放
    PlaybackStatePrepared,
    //第一首歌
    PlaybackStateBeginning,
    //下一首
    PlaybackStateNext,
    //上一首
    PlaybackStatePrevious,
    //播放
    PlaybackStatePlay,
    //停止
    PlaybackStateStop,
    //暫停
    PlaybackStatePause,
    //快轉
    PlaybackStateForward,
    //倒轉
    PlaybackStateBackward,
    //停止快倒轉
    PlaybackStateStopSeeking
}PlaybackStates;

@interface KRMusicPlayer : NSObject
{
@public
    MPMusicPlayerController *musicPlayer;
    BOOL isPlaying;
    BOOL isPause;
    BOOL isStop;
    BOOL isPlayerWoken;
    CGFloat volume;
    NSUInteger songIndex;
    PlaybackStates playbackState;
    UISlider *playbackSlider;
    MPMusicRepeatMode repeatMode;
}

@property (nonatomic, strong) MPMusicPlayerController *musicPlayer;
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, assign) BOOL isPause;
@property (nonatomic, assign) BOOL isStop;
//播放器是否已被喚醒準備好播音樂
@property (nonatomic, assign) BOOL isPlayerWoken;
@property (nonatomic, assign) CGFloat volume;
//當前歌曲是第幾首歌
@property (nonatomic, assign) NSUInteger songIndex;
@property (nonatomic, assign) PlaybackStates playbackState;
@property (nonatomic, assign) MPMusicRepeatMode repeatMode;
//音樂播放進度列
//Playback Slider
@property (nonatomic, strong) UISlider *playbackSlider;
//音樂播放進度列的重更新時間
@property (nonatomic, assign) NSTimeInterval playbackSliderRefreshInterval;

// Posted when the playback state changes, either programatically or by the user.
// 當播放狀態的變化,無論是編程或由用戶發表。
@property (nonatomic, copy) PlaybackChangeHandler playbackChangeHandler;

// Posted when the currently playing media item changes.
// 發布時,當前播放的媒體項目的變化。
@property (nonatomic, copy) PlayingItemChangeHandler playingItemChangeHandler;
@property (nonatomic, copy) PlayingItemChangeHandler startPlayCompletion;
@property (nonatomic, copy) PlayingItemChangeHandler nextSongChangeCompletion;
@property (nonatomic, copy) PlayingItemChangeHandler previousSongChangeCompletion;

// Posted when the current volume changes.
// 發布當前的音量變化。
@property (nonatomic, copy) VolumeChangeHandler volumeChangeHandler;

// 播放時間改變時
@property (nonatomic, copy) PlayingTimeChangeHandler playingTimeChangeHandler;

+(instancetype)sharedPlayer;
-(id)init;
-(void)initialize;

#pragma --mark Player
-(void)preparedToPlay;
-(void)play;
-(void)playAndKeepNotifications;
-(void)playSavedSongLists;
-(void)playSongWithPersistenId:(NSString *)_persistenId;
-(void)pause;
-(void)stop;
-(void)stopAndClearNotifications;

#pragma --mark Changes Song
-(void)nextSong;
-(void)nextSongWithCompletion:(PlayingItemChangeHandler)_completion;
-(void)previousSong;
-(void)previousSongWithCompletion:(PlayingItemChangeHandler)_completion;
-(void)turnToBegining;

#pragma --mark Gets Any Infomation
-(NSString *)getPlayingSongName;
-(NSString *)getPlayingAlbumName;
-(CGFloat)getPlayingSongDuration;
-(NSString *)getConvertedPlayingSongDuration;
-(NSString *)getConvertedPlayingSongCurrentTime;
-(NSString *)convertPlayingTime:(CGFloat)_playingTime;
-(CGFloat)getPlayingSongCurrentTime;
-(NSString *)getPlayingSonger;

#pragma --mark Saving Songs
-(BOOL)savePlaylistWithPersistentId:(NSString *)_persistenId;
-(BOOL)savePlaylistWithPersistentId:(NSString *)_persistenId songInfo:(NSDictionary *)_songInfo;
-(NSDictionary *)fetchtSavedSongLists;

#pragma --mark Playing Repeat Modes
-(void)turnOnRepeatModeForAll;
-(void)turnOnRepeatModeForOne;
-(void)turnOffRepeatMode;
-(void)turnOnRepeatModeForDefault;

#pragma --mark Playing Shuffle Modes
-(void)turnOnShuffleModeForSongs;
-(void)turnOnShuffleModeForAlbums;
-(void)turnOffShuffleMode;
-(void)turnOnShuffleModeForDefault;

#pragma --mark Playing State Methods
-(void)setCurrentSongWithSongId:(NSNumber *)_songId;
-(void)setCurrentPlaybackTime:(CGFloat)_playbackTime;
-(void)slideToPlaybackTime:(CGFloat)_playbackTime;
-(CGFloat)getCurrentPlaybackTime;
-(void)playSeekingForward;
-(void)playSeekingBackward;
-(void)stopSeeking;

#pragma --mark Playback Sliders
-(void)setPlaybackSliderParameters;
-(void)continuePlaybackSliderEvents;
-(void)removePlaybackSliderEvents;

#pragma --mark Blocks
-(void)setPlaybackChangeHandler:(PlaybackChangeHandler)_thePlaybackChangeHandler;
-(void)setPlayingItemChangeHandler:(PlayingItemChangeHandler)_thePlayingItemChangeHandler;
-(void)setNextSongChangeCompletion:(PlayingItemChangeHandler)_theNextSongChangeCompletion;
-(void)setPreviousSongChangeCompletion:(PlayingItemChangeHandler)_thePreviousSongChangeCompletion;
-(void)setVolumeChangeHandler:(VolumeChangeHandler)_theVolumeChangeHandler;
-(void)setPlayingTimeChangeHandler:(PlayingTimeChangeHandler)_thePlayingTimeChangeHandler;

@end

@interface KRMusicPlayer (PlayerFetchs)

-(void)awakePlayer;
-(NSArray *)fetchAllAlbums;
-(NSArray *)fetchAllAlbumsWithinImageSize:(CGSize)_imageSize;
-(NSArray *)fetchSongsWithQuery:(MPMediaQuery *)_query;
-(NSArray *)fetchSongsWithAlbumId:(NSNumber *)_albumId;
-(MPMediaItem *)fetchSongItemWithSongId:(NSNumber *)_songId;
-(NSDictionary *)fetchSongInfoWithSongId:(NSNumber *)_songId;
-(NSArray *)fetchAllSongs;
-(NSDictionary *)fetchAlbumInfoWithAlbumId:(NSNumber *)_albumId imageSize:(CGSize)_imageSize;
-(NSDictionary *)fetchAlbumInfoWithAlbumId:(NSNumber *)_albumId;

@end

@interface KRMusicPlayer (IdentifierConvert)

-(NSNumber *)convertAlbumIdOfString:(NSString *)_idString;

@end

@interface KRMusicPlayer (PlayerQueueQuery)

-(void)setQueueWithQuery:(MPMediaQuery *)_mediaQuery;
-(void)setQueueWithItemCollection:(MPMediaItemCollection *)_itemCollection;
-(void)setQueueWithAlbumId:(NSNumber *)_albumId;

@end


text:
div.body {
    text-align: left;
}
div.document p, div.document ul {
    margin-top: 0;
    margin-bottom: 1em;
}
div.document ul ul {
    margin-top: 0;
    margin-bottom: .5em;
}
.field-name {
    padding-right: .5em;
}
table.field-list p, table.field-list ul {
    margin-bottom: .5em;
}
table {
    border-collapse: collapse;
    margin-bottom: 1em;
}
table.docutils td, table.docutils th {
    padding: .2em .5em;
}

redpajama_set_name: RedPajamaGithub


text:
Parallax.js
===========

Simple parallax scrolling effect inspired by [Spotify.com](http://spotify.com/) implemented as a jQuery plugin
[http://pixelcog.com/parallax.js/](http://pixelcog.com/parallax.js/)

## Installation

### NPM

```bash
npm i --save jquery-parallax.js
```

### Yarn

```bash
yarn add jquery-parallax.js
```

### Bower

Please note that although Bower is still maintained, they recommend Yarn for new projects.

```bash
$ bower i --save parallax.js
```

### Setup

Include `parallax.min.js` in your document after including jQuery (compatible with jQuery >= 1.7).

```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/path/to/parallax.min.js"></script>
```

Use these CDN links, provided by jsDelivr.com
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/parallax.js/1.4.2/parallax.min.js"></script>
```

## Usage

Please note, that `<!DOCTYPE html>` on top of your document is required!

### Via data attributes

To easily add a parallax effect behind an element, add `data-parallax="scroll"` to the element you want to use, and specify an image with `data-image-src="/path/to/image.jpg"`.

```html
<div class="parallax-window" data-parallax="scroll" data-image-src="/path/to/image.jpg"></div>
```

### Via JavaScript

To call the parallax plugin manually, simply select your target element with jQuery and do the following:

```javascript
$('.parallax-window').parallax({imageSrc: '/path/to/image.jpg'});
```

### Notes

What parallax.js will do is create a fixed-position element for each parallax image at the start of the document's body (or another configurable container). This mirror element will sit behind the other elements and match the position and dimensions of its target object.

Due to the nature of this implementation, you must ensure that these parallax objects and any layers below them are transparent so that you can see the parallax effect underneath.  Also, if there is no other content in this element, you will need to ensure that it has some fixed dimensions otherwise you won't see anything.

```css
.parallax-window {
	min-height: 400px;
	background: transparent;
}
```

Also, keep in mind that once initialized, the parallax plugin presumes a fixed page layout unless it encounters a `scroll` or `resize` event.  If you have a dynamic page in which another javascript method may alter the DOM, you must manually refresh the parallax effect with the following commands:

```javascript
jQuery(window).trigger('resize').trigger('scroll');
```

### Using inner HTML for complex content

You can use the following syntax to enable complex content for the parallax:

```html
<div class="parallax-window">
  <div class="parallax-slider">
    <span style="position:absolute; top: 400px; left: 400px;">Some Text</span>
	<p>Some other Content</p>
  </div>
</div>
```
Please note, that the div with class "parallax-slider" is essential here.

You then need to initialize it through JS and provide the naturalWidth and naturalHeight options in order to be rendered correctly.

```
$('.parallax-window').parallax({
    naturalWidth: 600,
    naturalHeight: 400
  });
```

This also makes it possible to use responsive images in the slider:

```html
<div class="parallax-window">
  <div class="parallax-slider">
    <img src="/path/to/image.jpg" srcset="/path/to/image-400px.jpg 400w, /path/to/image-800px.jpg 800w, /path/to/image-1200px.jpg 1200w" sizes="100vw">
  </div>
</div>
```

## Options

Options can be passed in via data attributes of JavaScript.  For data attributes, append the option name to `data-`, as in `data-image-src=""`.

Note that when specifying these options as html data-attributes, you should convert "camelCased" variable names into "dash-separated" lower-case names (e.g. `zIndex` would be `data-z-index=""`).

			Name
			type
			default
			description

			imageSrc
			path
			null
			You must provide a path to the image you wish to apply to the parallax effect.

			naturalWidth
			number
			auto
			You can provide the natural width and natural height of an image to speed up loading and reduce error when determining the correct aspect ratio of the image.

			naturalHeight
			number
			auto

			position
			xPos yPos
			center center
			This is analogous to the background-position css property. Specify coordinates as top, bottom, right, left, center, or pixel values (e.g. -10px 0px). The parallax image will be positioned as close to these values as possible while still covering the target element.

			positionX
			xPos
			center

			positionY
			yPos
			center

			speed
			float
			0.2
			The speed at which the parallax effect runs. 0.0 means the image will appear fixed in place, and 1.0 the image will flow at the same speed as the page content.

			zIndex
			number
			-100
			The z-index value of the fixed-position elements.  By default these will be behind everything else on the page.

			bleed
			number
			0
			You can optionally set the parallax mirror element to extend a few pixels above and below the mirrored element.  This can hide slow or stuttering scroll events in certain browsers.

			iosFix
			boolean
			true
			iOS devices are incompatable with this plugin. If true, this option will set the parallax image as a static, centered background image whenever it detects an iOS user agent. Disable this if you wish to implement your own graceful degradation.

			androidFix
			boolean
			true
			If true, this option will set the parallax image as a static, centered background image whenever it detects an Android user agent. Disable this if you wish to enable the parallax scrolling effect on Android devices.

			overScrollFix
			boolean
			false
			(Experimental) If true, will freeze the parallax effect when "over scrolling" in browsers like Safari to prevent unexpected gaps caused by negative scroll positions.

			mirrorContainer
			jQuery Selector
			body
			The parallax mirror will be prepended into this container.

## Contributing

If you have a pull request you would like to submit, please ensure that you update the minified version of the library along with your code changes.  This project uses [uglifyjs](https://www.npmjs.com/package/uglify-js) to perform code compression.

Please use the following command:

	uglifyjs parallax.js --comments -m -c -o parallax.min.js

LICENSE
=======

The MIT License (MIT)

Copyright (c) 2016 PixelCog Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
require 'rails_helper'

RSpec.describe Api::RootController, type: :controller do
end


text:
using System;

namespace OhmSharp.Mapping
{
    /// <summary>
    /// Specifies that the value of this property or field should be indexed for better query performance
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public sealed class MappingIndexAttribute : Attribute
    {
        /// <summary>
        /// Constructs a new MappingIndexAttribute attribute
        /// </summary>
        public MappingIndexAttribute()
        { }
    }

    internal class MappingIndexAttributeParser : MemberAttributeParser<MappingIndexAttribute>
    {
        protected override void Parse(MappingIndexAttribute attribute, TypeMetadata typeMetadata, MemberMetadata memberMetadata)
        {
            if (attribute != null)
            {
                if ((memberMetadata.Attributes & MemberAttributes.Unmappable) == MemberAttributes.Unmappable)
                    throw new OhmSharpInvalidSchemaException(typeMetadata.Type, memberMetadata.Name,
                        string.Format("Member {0} of {1} cannot be marked with MappingIndex.", memberMetadata.Name, typeMetadata.Type.FullName));
                if ((memberMetadata.Attributes & MemberAttributes.Ignored) == MemberAttributes.Ignored)
                    throw new OhmSharpInvalidSchemaException(typeMetadata.Type, memberMetadata.Name,
                        string.Format("Member {0} of {1} cannot be marked with both MappingIndex and MappingIgnore.", memberMetadata.Name, typeMetadata.Type.FullName));

                // TODO: check for index type

                memberMetadata.Attributes |= MemberAttributes.Mapped;
                typeMetadata.IndexedMembers.Add(memberMetadata);
            }
        }
    }
}


text:
"""Database models."""
from __future__ import absolute_import, unicode_literals

from datetime import timedelta

import timezone_field
from celery import schedules
from celery.five import python_2_unicode_compatible
from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned, ValidationError
from django.core.validators import MaxValueValidator
from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _

from . import managers, validators
from .tzcrontab import TzAwareCrontab
from .utils import make_aware, now

DAYS = 'days'
HOURS = 'hours'
MINUTES = 'minutes'
SECONDS = 'seconds'
MICROSECONDS = 'microseconds'

PERIOD_CHOICES = (
    (DAYS, _('Days')),
    (HOURS, _('Hours')),
    (MINUTES, _('Minutes')),
    (SECONDS, _('Seconds')),
    (MICROSECONDS, _('Microseconds')),
)

SOLAR_SCHEDULES = [(x, _(x)) for x in sorted(schedules.solar._all_events)]

def cronexp(field):
    """Representation of cron expression."""
    return field and str(field).replace(' ', '') or '*'

@python_2_unicode_compatible
class SolarSchedule(models.Model):
    """Schedule following astronomical patterns."""

    event = models.CharField(
        _('event'), max_length=24, choices=SOLAR_SCHEDULES
    )
    latitude = models.DecimalField(
        _('latitude'), max_digits=9, decimal_places=6
    )
    longitude = models.DecimalField(
        _('longitude'), max_digits=9, decimal_places=6
    )

    class Meta:
        """Table information."""

        verbose_name = _('solar event')
        verbose_name_plural = _('solar events')
        ordering = ('event', 'latitude', 'longitude')
        unique_together = ('event', 'latitude', 'longitude')

    @property
    def schedule(self):
        return schedules.solar(self.event,
                               self.latitude,
                               self.longitude,
                               nowfun=lambda: make_aware(now()))

    @classmethod
    def from_schedule(cls, schedule):
        spec = {'event': schedule.event,
                'latitude': schedule.lat,
                'longitude': schedule.lon}
        try:
            return cls.objects.get(**spec)
        except cls.DoesNotExist:
            return cls(**spec)
        except MultipleObjectsReturned:
            cls.objects.filter(**spec).delete()
            return cls(**spec)

    def __str__(self):
        return '{0} ({1}, {2})'.format(
            self.get_event_display(),
            self.latitude,
            self.longitude
        )

@python_2_unicode_compatible
class IntervalSchedule(models.Model):
    """Schedule executing every n seconds."""

    DAYS = DAYS
    HOURS = HOURS
    MINUTES = MINUTES
    SECONDS = SECONDS
    MICROSECONDS = MICROSECONDS

    PERIOD_CHOICES = PERIOD_CHOICES

    every = models.IntegerField(_('every'), null=False)
    period = models.CharField(
        _('period'), max_length=24, choices=PERIOD_CHOICES,
    )

    class Meta:
        """Table information."""

        verbose_name = _('interval')
        verbose_name_plural = _('intervals')
        ordering = ['period', 'every']

    @property
    def schedule(self):
        return schedules.schedule(
            timedelta(**{self.period: self.every}),
            nowfun=lambda: make_aware(now())
        )

    @classmethod
    def from_schedule(cls, schedule, period=SECONDS):
        every = max(schedule.run_every.total_seconds(), 0)
        try:
            return cls.objects.get(every=every, period=period)
        except cls.DoesNotExist:
            return cls(every=every, period=period)
        except MultipleObjectsReturned:
            cls.objects.filter(every=every, period=period).delete()
            return cls(every=every, period=period)

    def __str__(self):
        if self.every == 1:
            return _('every {0.period_singular}').format(self)
        return _('every {0.every} {0.period}').format(self)

    @property
    def period_singular(self):
        return self.period[:-1]

@python_2_unicode_compatible
class CrontabSchedule(models.Model):
    """Timezone Aware Crontab-like schedule."""

    #
    # The worst case scenario for day of month is a list of all 31 day numbers
    # '[1, 2, ..., 31]' which has a length of 115. Likewise, minute can be
    # 0..59 and hour can be 0..23. Ensure we can accomodate these by allowing
    # 4 chars for each value (what we save on 0-9 accomodates the []).
    # We leave the other fields at their historical length.
    #
    minute = models.CharField(
        _('minute'), max_length=60 * 4, default='*',
        validators=[validators.minute_validator],
    )
    hour = models.CharField(
        _('hour'), max_length=24 * 4, default='*',
        validators=[validators.hour_validator],
    )
    day_of_week = models.CharField(
        _('day of week'), max_length=64, default='*',
        validators=[validators.day_of_week_validator],
    )
    day_of_month = models.CharField(
        _('day of month'), max_length=31 * 4, default='*',
        validators=[validators.day_of_month_validator],
    )
    month_of_year = models.CharField(
        _('month of year'), max_length=64, default='*',
        validators=[validators.month_of_year_validator],
    )

    timezone = timezone_field.TimeZoneField(default='UTC')

    class Meta:
        """Table information."""

        verbose_name = _('crontab')
        verbose_name_plural = _('crontabs')
        ordering = ['month_of_year', 'day_of_month',
                    'day_of_week', 'hour', 'minute', 'timezone']

    def __str__(self):
        return '{0} {1} {2} {3} {4} (m/h/d/dM/MY) {5}'.format(
            cronexp(self.minute), cronexp(self.hour),
            cronexp(self.day_of_week), cronexp(self.day_of_month),
            cronexp(self.month_of_year), str(self.timezone)
        )

    @property
    def schedule(self):
        crontab = schedules.crontab(
            minute=self.minute,
            hour=self.hour,
            day_of_week=self.day_of_week,
            day_of_month=self.day_of_month,
            month_of_year=self.month_of_year,
        )
        if getattr(settings, 'DJANGO_CELERY_BEAT_TZ_AWARE', True):
            crontab = TzAwareCrontab(
                minute=self.minute,
                hour=self.hour,
                day_of_week=self.day_of_week,
                day_of_month=self.day_of_month,
                month_of_year=self.month_of_year,
                tz=self.timezone
            )
        return crontab

    @classmethod
    def from_schedule(cls, schedule):
        spec = {'minute': schedule._orig_minute,
                'hour': schedule._orig_hour,
                'day_of_week': schedule._orig_day_of_week,
                'day_of_month': schedule._orig_day_of_month,
                'month_of_year': schedule._orig_month_of_year,
                'timezone': schedule.tz
                }
        try:
            return cls.objects.get(**spec)
        except cls.DoesNotExist:
            return cls(**spec)
        except MultipleObjectsReturned:
            cls.objects.filter(**spec).delete()
            return cls(**spec)

class PeriodicTasks(models.Model):
    """Helper table for tracking updates to periodic tasks."""

    ident = models.SmallIntegerField(default=1, primary_key=True, unique=True)
    last_update = models.DateTimeField(null=False)

    objects = managers.ExtendedManager()

    @classmethod
    def changed(cls, instance, **kwargs):
        if not instance.no_changes:
            cls.update_changed()

    @classmethod
    def update_changed(cls, **kwargs):
        cls.objects.update_or_create(ident=1, defaults={'last_update': now()})

    @classmethod
    def last_change(cls):
        try:
            return cls.objects.get(ident=1).last_update
        except cls.DoesNotExist:
            pass

@python_2_unicode_compatible
class PeriodicTask(models.Model):
    """Model representing a periodic task."""

    name = models.CharField(
        _('name'), max_length=200, unique=True,
        help_text=_('Useful description'),
    )
    task = models.CharField(_('task name'), max_length=200)
    interval = models.ForeignKey(
        IntervalSchedule, on_delete=models.CASCADE,
        null=True, blank=True, verbose_name=_('interval'),
    )
    crontab = models.ForeignKey(
        CrontabSchedule, on_delete=models.CASCADE, null=True, blank=True,
        verbose_name=_('crontab'), help_text=_('Use one of interval/crontab'),
    )
    solar = models.ForeignKey(
        SolarSchedule, on_delete=models.CASCADE, null=True, blank=True,
        verbose_name=_('solar'), help_text=_('Use a solar schedule')
    )
    args = models.TextField(
        _('Arguments'), blank=True, default='[]',
        help_text=_('JSON encoded positional arguments'),
    )
    kwargs = models.TextField(
        _('Keyword arguments'), blank=True, default='{}',
        help_text=_('JSON encoded keyword arguments'),
    )
    queue = models.CharField(
        _('queue'), max_length=200, blank=True, null=True, default=None,
        help_text=_('Queue defined in CELERY_TASK_QUEUES'),
    )
    exchange = models.CharField(
        _('exchange'), max_length=200, blank=True, null=True, default=None,
    )
    routing_key = models.CharField(
        _('routing key'), max_length=200, blank=True, null=True, default=None,
    )
    priority = models.PositiveIntegerField(
        _('priority'), default=None, validators=[MaxValueValidator(255)],
        blank=True, null=True
    )
    expires = models.DateTimeField(
        _('expires'), blank=True, null=True,
    )
    one_off = models.BooleanField(
        _('one-off task'), default=False,
    )
    start_time = models.DateTimeField(
        _('start_time'), blank=True, null=True,
    )
    enabled = models.BooleanField(
        _('enabled'), default=True,
    )
    last_run_at = models.DateTimeField(
        auto_now=False, auto_now_add=False,
        editable=False, blank=True, null=True,
    )
    total_run_count = models.PositiveIntegerField(
        default=0, editable=False,
    )
    date_changed = models.DateTimeField(auto_now=True)
    description = models.TextField(_('description'), blank=True)

    objects = managers.PeriodicTaskManager()
    no_changes = False

    class Meta:
        """Table information."""

        verbose_name = _('periodic task')
        verbose_name_plural = _('periodic tasks')

    def validate_unique(self, *args, **kwargs):
        super(PeriodicTask, self).validate_unique(*args, **kwargs)

        schedule_types = ['interval', 'crontab', 'solar']
        selected_schedule_types = [s for s in schedule_types
                                   if getattr(self, s)]

        if len(selected_schedule_types) == 0:
            raise ValidationError({
                'interval': [
                    'One of interval, crontab, or solar must be set.'
                ]
            })

        err_msg = 'Only one of interval, crontab, or solar must be set'
        if len(selected_schedule_types) > 1:
            error_info = {}
            for selected_schedule_type in selected_schedule_types:
                error_info[selected_schedule_type] = [err_msg]
            raise ValidationError(error_info)

    def save(self, *args, **kwargs):
        self.exchange = self.exchange or None
        self.routing_key = self.routing_key or None
        self.queue = self.queue or None
        if not self.enabled:
            self.last_run_at = None
        super(PeriodicTask, self).save(*args, **kwargs)

    def __str__(self):
        fmt = '{0.name}: {{no schedule}}'
        if self.interval:
            fmt = '{0.name}: {0.interval}'
        if self.crontab:
            fmt = '{0.name}: {0.crontab}'
        if self.solar:
            fmt = '{0.name}: {0.solar}'
        return fmt.format(self)

    @property
    def schedule(self):
        if self.interval:
            return self.interval.schedule
        if self.crontab:
            return self.crontab.schedule
        if self.solar:
            return self.solar.schedule

signals.pre_delete.connect(PeriodicTasks.changed, sender=PeriodicTask)
signals.pre_save.connect(PeriodicTasks.changed, sender=PeriodicTask)
signals.pre_delete.connect(
    PeriodicTasks.update_changed, sender=IntervalSchedule)
signals.post_save.connect(
    PeriodicTasks.update_changed, sender=IntervalSchedule)
signals.post_delete.connect(
    PeriodicTasks.update_changed, sender=CrontabSchedule)
signals.post_save.connect(
    PeriodicTasks.update_changed, sender=CrontabSchedule)
signals.post_delete.connect(
    PeriodicTasks.update_changed, sender=SolarSchedule)
signals.post_save.connect(
    PeriodicTasks.update_changed, sender=SolarSchedule)


text:
using System.Reflection;
using Xunit;

namespace System.Linq.Expressions.Tests
{
    public static class LiftedSubtractCheckedNullableTests
    {
        #region Test methods

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableByteTest(bool useInterpreter)
        {
            byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableByte(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableCharTest(bool useInterpreter)
        {
            char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableChar(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableDecimalTest(bool useInterpreter)
        {
            decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableDecimal(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableDoubleTest(bool useInterpreter)
        {
            double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableDouble(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableFloatTest(bool useInterpreter)
        {
            float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableFloat(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableIntTest(bool useInterpreter)
        {
            int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableInt(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableLongTest(bool useInterpreter)
        {
            long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableLong(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableSByteTest(bool useInterpreter)
        {
            sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableSByte(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableShortTest(bool useInterpreter)
        {
            short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableShort(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableUIntTest(bool useInterpreter)
        {
            uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableUInt(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableULongTest(bool useInterpreter)
        {
            ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableULong(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableUShortTest(bool useInterpreter)
        {
            ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableUShort(values[i], values[j], useInterpreter);
                }
            }
        }

        [Theory, ClassData(typeof(CompilationTypes))]
        public static void CheckLiftedSubtractCheckedNullableNumberTest(bool useInterpreter)
        {
            Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue };
            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j < values.Length; j++)
                {
                    VerifySubtractCheckedNullableNumber(values[i], values[j], useInterpreter);
                }
            }
        }

        #endregion

        #region Helpers

        public static byte SubtractCheckedNullableByte(byte a, byte b)
        {
            return checked((byte)(a - b));
        }

        public static char SubtractCheckedNullableChar(char a, char b)
        {
            return checked((char)(a - b));
        }

        public static decimal SubtractCheckedNullableDecimal(decimal a, decimal b)
        {
            return checked(a - b);
        }

        public static double SubtractCheckedNullableDouble(double a, double b)
        {
            return checked(a - b);
        }

        public static float SubtractCheckedNullableFloat(float a, float b)
        {
            return checked(a - b);
        }

        public static int SubtractCheckedNullableInt(int a, int b)
        {
            return checked(a - b);
        }

        public static long SubtractCheckedNullableLong(long a, long b)
        {
            return checked(a - b);
        }

        public static sbyte SubtractCheckedNullableSByte(sbyte a, sbyte b)
        {
            return checked((sbyte)(a - b));
        }

        public static short SubtractCheckedNullableShort(short a, short b)
        {
            return checked((short)(a - b));
        }

        public static uint SubtractCheckedNullableUInt(uint a, uint b)
        {
            return checked(a - b);
        }

        public static ulong SubtractCheckedNullableULong(ulong a, ulong b)
        {
            return checked(a - b);
        }

        public static ushort SubtractCheckedNullableUShort(ushort a, ushort b)
        {
            return checked((ushort)(a - b));
        }

        #endregion

        #region Test verifiers

        private static void VerifySubtractCheckedNullableByte(byte? a, byte? b, bool useInterpreter)
        {
            Expression<Func<byte?>> e =
                Expression.Lambda<Func<byte?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(byte?)),
                        Expression.Constant(b, typeof(byte?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableByte")));
            Func<byte?> f = e.Compile(useInterpreter);

            if (a < b)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(checked((byte?)(a - b)), f());
        }

        private static void VerifySubtractCheckedNullableChar(char? a, char? b, bool useInterpreter)
        {
            Expression<Func<char?>> e =
                Expression.Lambda<Func<char?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(char?)),
                        Expression.Constant(b, typeof(char?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableChar")));
            Func<char?> f = e.Compile(useInterpreter);

            if (a < b)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(checked((char?)(a - b)), f());
        }

        private static void VerifySubtractCheckedNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
        {
            Expression<Func<decimal?>> e =
                Expression.Lambda<Func<decimal?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(decimal?)),
                        Expression.Constant(b, typeof(decimal?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDecimal")));
            Func<decimal?> f = e.Compile(useInterpreter);

            decimal? expected = default(decimal);
            try
            {
                expected = checked(a - b);
            }
            catch (OverflowException)
            {
                Assert.Throws<OverflowException>(() => f());
                return;
            }

            Assert.Equal(expected, f());
        }

        private static void VerifySubtractCheckedNullableDouble(double? a, double? b, bool useInterpreter)
        {
            Expression<Func<double?>> e =
                Expression.Lambda<Func<double?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(double?)),
                        Expression.Constant(b, typeof(double?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDouble")));
            Func<double?> f = e.Compile(useInterpreter);

            Assert.Equal(a - b, f());
        }

        private static void VerifySubtractCheckedNullableFloat(float? a, float? b, bool useInterpreter)
        {
            Expression<Func<float?>> e =
                Expression.Lambda<Func<float?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(float?)),
                        Expression.Constant(b, typeof(float?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableFloat")));
            Func<float?> f = e.Compile(useInterpreter);

            Assert.Equal(a - b, f());
        }

        private static void VerifySubtractCheckedNullableInt(int? a, int? b, bool useInterpreter)
        {
            Expression<Func<int?>> e =
                Expression.Lambda<Func<int?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(int?)),
                        Expression.Constant(b, typeof(int?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableInt")));
            Func<int?> f = e.Compile(useInterpreter);

            long? expected = (long?)a - b;
            if (expected < int.MinValue | expected > int.MaxValue)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal((int?)expected, f());
        }

        private static void VerifySubtractCheckedNullableLong(long? a, long? b, bool useInterpreter)
        {
            Expression<Func<long?>> e =
                Expression.Lambda<Func<long?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(long?)),
                        Expression.Constant(b, typeof(long?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableLong")));
            Func<long?> f = e.Compile(useInterpreter);

            long? expected = null;
            try
            {
                expected = checked(a - b);
            }
            catch (OverflowException)
            {
                Assert.Throws<OverflowException>(() => f());
                return;
            }

            Assert.Equal(expected, f());
        }

        private static void VerifySubtractCheckedNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
        {
            Expression<Func<sbyte?>> e =
                Expression.Lambda<Func<sbyte?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(sbyte?)),
                        Expression.Constant(b, typeof(sbyte?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableSByte")));
            Func<sbyte?> f = e.Compile(useInterpreter);

            int? expected = a - b;

            if (expected < sbyte.MinValue | expected > sbyte.MaxValue)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(expected, f());
        }

        private static void VerifySubtractCheckedNullableShort(short? a, short? b, bool useInterpreter)
        {
            Expression<Func<short?>> e =
                Expression.Lambda<Func<short?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(short?)),
                        Expression.Constant(b, typeof(short?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableShort")));
            Func<short?> f = e.Compile(useInterpreter);

            int? expected = a - b;
            if (expected < short.MinValue | expected > short.MaxValue)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(expected, f());
        }

        private static void VerifySubtractCheckedNullableUInt(uint? a, uint? b, bool useInterpreter)
        {
            Expression<Func<uint?>> e =
                Expression.Lambda<Func<uint?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(uint?)),
                        Expression.Constant(b, typeof(uint?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUInt")));
            Func<uint?> f = e.Compile(useInterpreter);

            if (a < b)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(a - b, f());
        }

        private static void VerifySubtractCheckedNullableULong(ulong? a, ulong? b, bool useInterpreter)
        {
            Expression<Func<ulong?>> e =
                Expression.Lambda<Func<ulong?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(ulong?)),
                        Expression.Constant(b, typeof(ulong?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableULong")));
            Func<ulong?> f = e.Compile(useInterpreter);

            if (a < b)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(a - b, f());
        }

        private static void VerifySubtractCheckedNullableUShort(ushort? a, ushort? b, bool useInterpreter)
        {
            Expression<Func<ushort?>> e =
                Expression.Lambda<Func<ushort?>>(
                    Expression.SubtractChecked(
                        Expression.Constant(a, typeof(ushort?)),
                        Expression.Constant(b, typeof(ushort?)),
                        typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUShort")));
            Func<ushort?> f = e.Compile(useInterpreter);

            if (a < b)
                Assert.Throws<OverflowException>(() => f());
            else
                Assert.Equal(a - b, f());
        }

        private static void VerifySubtractCheckedNullableNumber(Number? a, Number? b, bool useInterpreter)
        {
            Expression<Func<Number?>> e =
                Expression.Lambda<Func<Number?>>(
                    Expression.Subtract(
                        Expression.Constant(a, typeof(Number?)),
                        Expression.Constant(b, typeof(Number?))));
            Assert.Equal(typeof(Number?), e.Body.Type);
            Func<Number?> f = e.Compile(useInterpreter);

            Number? expected = a - b;
            Assert.Equal(expected, f()); // NB: checked behavior doesn't apply to non-primitive types
        }

        #endregion
    }
}


text:
export interface Template {
    id?: string;
    name?: string;
    description?: string;
    templateType?: Template.TemplateTypeEnum;
    version?: number;
    titleTemplate?: string;
    bodyTemplate?: string;
    variables?: Array<string>;
    fallbackLanguageCode?: string;
    translations?: any;
    customData?: any;
}
export declare namespace Template {
    enum TemplateTypeEnum {
        EMAIL,
        PUSH,
        SMS,
        WEBHOOK,
        HTML,
        EMAILVERIFICATION,
        PASSWORDRESET,
    }
}


text:
package ctf;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import robocode.BattleResults;
import robocode.control.events.BattleCompletedEvent;
import robocode.control.testing.RobotTestBed;

/**
 * Tests the {@link Orthogonobot} against the RamFire sample robot.
 *
 * @author Christopher Foo
 */
public class TestOrthogonobotVersusRamFire extends RobotTestBed {

  /**
   * Specifies that RamFire and {@link Orthogonobot} are to be matched up in this test case.
   *
   * @return The comma-delimited list of robots in this match.
   */
  @Override
  public String getRobotNames() {
    return "sample.RamFire,ctf.Orthogonobot";
  }

  /**
   * This test runs for 50 rounds.
   *
   * @return The number of rounds.
   */
  @Override
  public int getNumRounds() {
    return 50;
  }

  /**
   * The actual test, which asserts that {@link Orthogonobot} has won at least 90% of the rounds
   * against RamFire.
   *
   * @param event Details about the completed battle.
   */
  @Override
  public void onBattleCompleted(BattleCompletedEvent event) {
    // Return the results in order of getRobotNames.
    BattleResults[] battleResults = event.getIndexedResults();
    // Sanity check that results[0] is Orthogonobot.
    BattleResults OrthogonobotResults = battleResults[0];

    String robotName = OrthogonobotResults.getTeamLeaderName();
    assertEquals("Check that results[0] is Orthogonobot", "ctf.Orthogonobot*", robotName);

    // Check to make sure Orthogonobot won at least 90% of the rounds.
    assertTrue("Check Orthogonobot winner", OrthogonobotResults.getFirsts() > getNumRounds() * 0.9);
  }
}


text:
import os

from google.cloud.sql.connector import Connector, IPTypes
import pytds

import sqlalchemy

# connect_with_connector initializes a connection pool for a
# Cloud SQL instance of SQL Server using the Cloud SQL Python Connector.
def connect_with_connector() -> sqlalchemy.engine.base.Engine:
    # Note: Saving credentials in environment variables is convenient, but not
    # secure - consider a more secure solution such as
    # Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
    # keep secrets safe.

    instance_connection_name = os.environ["INSTANCE_CONNECTION_NAME"]  # e.g. 'project:region:instance'
    db_user = os.environ.get("DB_USER", "")  # e.g. 'my-db-user'
    db_pass = os.environ["DB_PASS"]  # e.g. 'my-db-password'
    db_name = os.environ["DB_NAME"]  # e.g. 'my-database'

    ip_type = IPTypes.PRIVATE if os.environ.get("PRIVATE_IP") else IPTypes.PUBLIC

    connector = Connector(ip_type)

    def getconn() -> pytds.Connection:
        conn = connector.connect(
            instance_connection_name,
            "pytds",
            user=db_user,
            password=db_pass,
            db=db_name,
        )
        return conn

    pool = sqlalchemy.create_engine(
        "mssql+pytds://localhost",
        creator=getconn,
        # [START_EXCLUDE]
        # Pool size is the maximum number of permanent connections to keep.
        pool_size=5,

        # Temporarily exceeds the set pool_size if no connections are available.
        max_overflow=2,

        # The total number of concurrent connections for your application will be
        # a total of pool_size and max_overflow.

        # 'pool_timeout' is the maximum number of seconds to wait when retrieving a
        # new connection from the pool. After the specified amount of time, an
        # exception will be thrown.
        pool_timeout=30,  # 30 seconds

        # 'pool_recycle' is the maximum number of seconds a connection can persist.
        # Connections that live longer than the specified amount of time will be
        # re-established
        pool_recycle=1800,  # 30 minutes
        # [END_EXCLUDE]
    )
    return pool

# [END cloud_sql_sqlserver_sqlalchemy_connect_connector]


text:
RocketChat.Migrations.add({
	version: 40,
	up: function() {
		RocketChat.models.Settings.find({ _id: /Accounts_OAuth_Custom_/, i18nLabel: 'Accounts_OAuth_Custom_Enable' }).forEach(function(customOauth) {
			var parts = customOauth._id.split('_');
			var name = parts[3];
			var id = 'Accounts_OAuth_Custom_' + name + '_token_sent_via';
			if (!RocketChat.models.Settings.findOne( { _id: id } )) {
				RocketChat.models.Settings.insert({
					'_id': id,
					'type': 'select',
					'group': 'OAuth',
					'section': 'Custom OAuth: ' +  name,
					'i18nLabel': 'Accounts_OAuth_Custom_Token_Sent_Via',
					'persistent': true,
					'values': [
					{
						'key': 'header',
						'i18nLabel': 'Header'
					},
					{
						'key': 'payload',
						'i18nLabel': 'Payload'
					}
					],
					'packageValue': 'payload',
					'valueSource': 'packageValue',
					'ts': new Date(),
					'hidden': false,
					'blocked': false,
					'sorter': 255,
					'i18nDescription': 'Accounts_OAuth_Custom_' + name + '_token_sent_via_Description',
					'createdAt': new Date(),
					'value': 'payload'
				});
			}
		});
	}
});


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Dom = require('./../util/Dom');

var _Dom2 = _interopRequireDefault(_Dom);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var classnames = require('classnames');

var DEFAULT_URL = '#',
    DEFAULT_TARGET = '_self';

var LinkRenderer = function (_Component) {
    _inherits(LinkRenderer, _Component);

    function LinkRenderer() {
        _classCallCheck(this, LinkRenderer);

        return _possibleConstructorReturn(this, (LinkRenderer.__proto__ || Object.getPrototypeOf(LinkRenderer)).apply(this, arguments));
    }

    _createClass(LinkRenderer, [{
        key: 'render',
        value: function render() {
            var className = classnames(this.props.className, _Dom2.default.buildClassNames(this.props.classPrefix, ['menu-item-link'])),
                data = this.props.data;

            return _react2.default.createElement(
                'div',
                { key: data.key, id: data.id, className: className },
                _react2.default.createElement(
                    'a',
                    { href: data.url || DEFAULT_URL, target: data.target || DEFAULT_TARGET },
                    data.title
                )
            );
        }
    }]);

    return LinkRenderer;
}(_react.Component);

exports.default = LinkRenderer;


text:
@implementation NSAttributedString (LHSAdditions)

- (NSRange)lhs_range {
    return NSMakeRange(0, self.length);
}

@end


text:
package org.pageseeder.diffx.algorithm;

import org.pageseeder.diffx.api.DiffAlgorithm;
import org.pageseeder.diffx.api.DiffHandler;
import org.pageseeder.diffx.api.Operator;

import java.util.List;
import java.util.Objects;

/**
 * An implementation of the S. Kiran Kumar and C. Pandu Rangan algorithm to find the longest
 * common subsequence (LCS).
 *
 *
For S. Kiran Kumar and C. Pandu Rangan. A linear space algorithm for the LCS problem,
 * Acta Informatica. Volume 24 ,  Issue 3  (June 1987); Copyright Springer-Verlag 1987
 *
 *
The algorithm has been adjusted to generate the shortest edit script (SES)

 *
 * @author Christophe Lauret
 * @version 0.9.0
 * @implNote this algorithm effectively detects the correct changes in the sequences, but cannot be used on
 * XML sequences as it cannot always produce well-formed XML.
 */
public final class KumarRanganAlgorithm<T> implements DiffAlgorithm<T> {

  /**
   * Set to true to show debug info.
   */
  private static final boolean DEBUG = false;

  @Override
  public void diff(List<? extends T> from, List<? extends T> to, DiffHandler<T> handler) {
    Instance<T> instance = new Instance<>(from, to);
    instance.process(handler);
  }

  /**
   * Copies the first array into the second one up to the specified index (included).
   *
   * @param a   The first array.
   * @param b   The second array.
   * @param len The 0-based index of the last copied value.
   */
  private static void copyUpTo(int[] a, int[] b, int len) {
    System.arraycopy(a, 0, b, 0, len + 1);
  }

  /**
   * A stateful instance.
   *

   * Where possible, the name of the variables match the names used in the algorithm published in
   * "A Linear Space Algorithm for the LCS Problem".
   */
  private static class Instance<T> {

    // Global integer arrays needed in the computation of the LCS
    private int[] R1, R2;
    private int[] LL, LL1, LL2;

    // Global integer variables needed in the computation of the LCS.
    private int R;
    private int S;

    /**
     * A counter for the index of the second sequence when generating the diff.
     */
    private int J = 0;

    private final List<? extends T> A;
    private final List<? extends T> B;

    /**
     * Events are reported here.
     */
    private DiffHandler<T> handler;

    Instance(List<? extends T> from, List<? extends T> to) {
      this.A = Objects.requireNonNull(from);
      this.B = Objects.requireNonNull(to);
    }

    /**
     * Writes the diff sequence using the specified handler.
     *
     * @param handler The handler for the output.
     */
    public void process(DiffHandler<T> handler) {
      final int m = this.A.size();
      final int n = this.B.size();
      int p = calculateLength(m, n);
      this.handler = handler;

      // Execute the LCS algorithm for the complete sequences
      computeLCS(0, m - 1, 0, n - 1, m, n, p);
    }

    // helpers ------------------------------------------------------------------------------------

    /**
     * Initialises the state variables.
     *
     * @param n The length of the second sequence
     */
    private void init(int n) {
      this.R1 = new int[n + 1];
      this.R2 = new int[n + 1];
      this.LL = new int[n + 1];
      this.LL1 = new int[n + 1];
      this.LL2 = new int[n + 1];
      this.J = 0;
    }

    /**
     * An implementation of the LCS algorithm as defined by Kumar and Rangan.
     *
     *
Given A and B are strings of length m and n respectively, and p, the length of the LCS of A and B,
     * algorithm LCS calculates the longest common subsequence of A and B.

     *
     *
We assume that A and B are stored globally and that substrings of these strings can be passed as
     * arguments by passing two numbers, namely the left and right end indices of the substring.

     *
     *
The divide and conquer technique is used in solving the problem.

     *
     *
The algorithm finds a perfect cut for the string pair (A, B), solves the subproblems of finding the
     * LCS of A1 and B1, and A2 and B2, and combines the solutions.

     *
     *

     *  CS (A, B, m, n, p, C)
     *     if m-p<2 1
     *        then solve the base case
     *  2     else begin
     *  2.1      find a perfect cut (u, v), for A and B;
     *  2.2      LCS(A(1 :u), B(l:v), u, v, u-w, C1);
     *           LCS(A(u+ 1 :m), B(v+ 1 :n), m-u, n-v, m-u-w', C2);
     *  2.3      C=C1C2
     *        end
     *

     *
     * @param startA The start index of the first sequence.
     * @param endA   The last index of the first sequence.
     * @param startB The start index of the second sequence.
     * @param endB   The last index of the second sequence.
     * @param m      The length of the first sequence.
     * @param n      The length of the second sequence.
     * @param p      The length of LCS between indexes startA and endA.
     *               Similarly, between indexes b_start and b_end
     */
    private void computeLCS(int startA, int endA, int startB, int endB, int m, int n, int p) {
      if (m - p < 2) {
        // (i) Step 1, or the base case (waste is less than 2 characters)
        computeLCSBaseCase(startA, endA, startB, endB, m, n, p);
      } else {
        // (ii) Step 2.1, or finding the perfect cut (waste is more than 1 character, process recursively)
        computeLCSMoreWaste(startA, endA, startB, endB, m, n, p);
      }
    }

    /**
     * An implementation of the fillone procedure as defined by Kumar and Rangan.
     *
     *
This is used to find the index from where the longest common subsequence so far can
     * be found.

     *
     *
We use two arrays R1(0:n) and R2(0:n) to store the given and the calculated values respectively.
     *
Assume m >= s >= length of the LCS of A and B.

     *
     *
Given Ls+1(1), Ls(2), Ls+1(3)... in the array elements R1(1), R1(2), R1(3)... the procedure calculates
     * Ls+1(0) (=n+ 1), Ls(1), Ls-1(2)... and returns them in the array elements R2(0),R2(1), R2(2)...

     *
     *
Variable r is used to indicate the largest k such that Ls+2-k(k) is defined.
     * At the end of the computation, r is updated to indicate the largest k such that Ls+1-k(k) is defined.

     *
     *

     *   fillone (A, b, m, n, R 1, R 2, r, s)
     *      begin
     *   1.    j := 1; i := s;
     *         over := false; R2(O) := n+1;
     *   2.    while i > 0 and not over do
     *         begin
     *   2.1     if j > r then lower B := O else lower B := R1(j);
     *           pos B := R2(j-1) - 1;
     *   2.2     while pos B > lower B and A(i) != B(pos B) do
     *           pos B := pos B - 1;
     *   2.3     temp := max(pos B, lower B);
     *           if temp = 0 then over := true
     *           else begin
     *              R2(j) := temp;
     *              i := i-1; j := j+l
     *           end
     *        end;
     *   3.   r=j-1
     *      end
     *

     *
     *
In step 2.2, all the symbols of string B are compared sequentially from the last symbol to the first symbol.

     *
Hence step 2.2 is executed at most n times. It is obvious that other steps are not executed more than n times.

     *
Hence, time complexity is O(n).

     *
The procedure uses only linear arrays R1, R2, so the space complexity is O(n+m).

     *
     * @param startA The start index of the first sequence.
     * @param endA   The last index of the first sequence.
     * @param startB The start index of the second sequence.
     * @param endB   The last index of the second sequence.
     * @param m      The length of the first sequence.
     * @param n      The length of the second sequence.
     * @param sign   This is used to mark whether to start from the beginning of the string
     *               or from the end of the string.
     */
    private void fillOne(int startA, int endA, int startB, int endB, int m, int n, int sign) {
      int i = this.S;
      int j = 1;
      boolean over = false;
      this.R2[0] = n + 1;

      while (i > 0 & !over) {
        int lowerB = (j > this.R) ? 0 : this.R1[j];
        int posB = this.R2[j - 1] - 1;

        // The real index in the global char table is:
        // current_index * sign + beginning index of the sub-char array
        while (posB > lowerB && !this.A.get((i - 1) * sign + startA)
            .equals(this.B.get((posB - 1) * sign + startB))) {
          posB--;
        }
        int temp = Math.max(posB, lowerB);
        if (temp == 0) {
          over = true;
        } else {
          this.R2[j] = temp;
          i--;
          j++;
        }
      }
      this.R = j - 1;
    }

    /**
     * Implements procedure calmid from the Kumar-Rangan algorithm.
     *
     *
This procedure calculates Lm-x+1-j(j) values and store them in LL(j) (j>0).

     *
r is set to the largest j such that Lm-x+1-j(j) is defined.

     *
     *

     *   calmid (A, B, m, n, x, LL, r)
     *      begin
     *  1.     r:=0;
     *  2.     for s:=m down to m-x do
     *         begin
     *            fillone(A, B, m, n, R1, R2, r, s);
     *            R1(j) := R2(j) [j:=0...r]
     *         end;
     *  3.     LL(j) := R1(j) [j:=0...r]
     *      end
     *

     *
     *
The loop body is executed exactly (x + 1) times.

     *
     *
In each iteration of the loop, a call to fillone and copying of R2(j) into R1(j) is done, which take O(n)
     * and O(r) (< O(n)) time respectively. Hence, the time complexity is O(n(x + 1)).

     *
     *
The procedure uses only linear arrays R1, R2, LL, so the space complexity is O(n+m).

     *
     *
Implementation note: we use integer arrays to keep track where the longest common subsequence can be found.

     *
     * @param startA The start index of the first sequence.
     * @param endA   The last index of the first sequence.
     * @param startB The start index of the second sequence.
     * @param endB   The last index of the second sequence.
     * @param m      The length of the first sequence.
     * @param n      The length of the second sequence.
     * @param sign   This is used to mark whether to start from the beginning of the string
     *               or from the end of the string.
     * @param x      The length of characters not included in the LCS between indexes startA and endA.
     *               Similarly, between indexes startB and endB.
     *
     * @return Array of 1-indexes of B in LCS
     */
    private int[] calMid(int startA, int endA, int startB, int endB, int m, int n, int sign, int x) {
      this.LL = new int[n + 1];
      this.R = 0;
      for (this.S = m; this.S >= m - x; this.S--) {
        fillOne(startA, endA, startB, endB, m, n, sign);
        copyUpTo(this.R2, this.R1, this.R);
      }
      copyUpTo(this.R1, this.LL, this.R);
      return this.LL;
    }

    /**
     * Computes the longest common subsequence for the specified boundaries when the waste
     * is (strictly) less than 2 tokens.
     *
     *
This method is iterative; NOT recursive.
     *
     *
This is an implementation of Step 1 (or base case) as described by Kumar-Rangan:

     *
     *

     *   (i) Step 1, or the base case:
     *   1. calmid (A, B, m, n, m--p, LL, r);
     *      i := 1;
     *   2. while i < p and A(i) = B(LL(p-i+1)) do
     *         begin
     *            C(i) := A(i);
     *            i := i+1
     *         end;
     *   3. i := i+1;
     *   4. while i < m do
     *         begin
     *            C(i-1) := A(i);
     *            i := i+1
     *         end
     *

     *
     *
When p = m, the statements in step 4 are not executed at all and A is copied into C in step 2.

     *
     *
When p=m-1, the step 3 can be seen as the statement that drops out one character from A to get C.

     *
     *
It is easy to verify that the wrong character is not dropped.

     *
     * @param startA The start 0-based index of the first sequence.
     * @param endA   The last 0-based index of the first sequence.
     * @param startB The start 0-based index of the second sequence.
     * @param endB   The last 0-based index of the second sequence.
     * @param m      The length of the first sequence.
     * @param n      The length of the second sequence.
     * @param p      The length of LCS between indexes startA and endA.
     */
    private void computeLCSBaseCase(int startA, int endA, int startB, int endB, int m, int n, int p) {

      // 1. Compute LL
      // `LL` contains the relative 1-based index of the token in the second sequence in reverse order
      // `m - p` is number of diffs with the first subsequence
      this.LL = calMid(startA, endA, startB, endB, m, n, 1, m - p);
      if (DEBUG) {
        System.err.println("SEQ1={" + startA + " -> " + endA + "} SEQ2={" + startB + " -> " + endB + "}  M=" + m + " n=" + n + " p=" + p);
        printLL();
      }

      // Inserted elements from B
      // `LL[p] - 1 + startB` contains index of the first item in the second subsequence matching the first subsequence
      insertUpTo(this.LL[p] - 1 + startB);

      int i = 0;

      // 2. Start in order for the A subsequence and get the index of the B subsequence
      while (i < p && this.A.get(i + startA).equals(this.B.get(this.LL[p - i] - 1 + startB))) {
        this.handler.handle(Operator.MATCH, this.A.get(i + startA));
        this.J++;
        i++;
        if (i < p) {
          // Inserted tokens from B
          insertUpTo(this.LL[p - i] - 1 + startB);
        }
      }

      // possibly a token from the A subsequence to delete
      if (i < m) {
        this.handler.handle(Operator.DEL, this.A.get(i + startA));
      }

      // 3.
      i++;

      // 4. The second part of the A subsequence
      while (i < m) {
        this.handler.handle(Operator.MATCH, this.A.get(i + startA));
        this.J++;
        i++;

        while (i < m && this.J < endB && !this.A.get(i + startA).equals(this.B.get(this.J))) {
          insertUpTo(this.J + 1);
        }
      }

      // finish writing the missing tokens from the B subsequence
      insertUpTo(this.LL[0] - 1 + startB);
    }

    /**
     * Computes the longest common subsequence for the specified boundaries when the waste
     * is more than 1 character.
     *
     *
This method is recursive and will process each subsequence with the LCS algorithm.
     *
     *
This is an implementation of Step 2.1 (finding the perfect cut of the LCS algorithm by Kumar-Rangan

     *
     *

     *   (ii) Step 2.1, or finding the perfect cut:
     *   2.1.1 calmid(^A^, ^B^, m, n, w, LL1, rl);
     *         LLI(j) := n+1-LL1(j) [j:=0...r1];
     *   2.1.2 calmid(A, B, m, n, w', LL2, r2);
     *   2.1.3 u := k + w:k <= r1 and p-k <= r2 and LL1(k) < LL2(p-k);
     *         v := LL1(k)
     *

     *
     * @param startA The start 0-based index of the first sequence.
     * @param endA   The last 0-based index of the first sequence.
     * @param startB The start 0-based index of the second sequence.
     * @param endB   The last 0-based index of the second sequence.
     * @param m      The length of the first sequence.
     * @param n      The length of the second sequence.
     * @param p      The length of LCS between indexes startA and endA.
     */
    private void computeLCSMoreWaste(int startA, int endA, int startB, int endB, int m, int n, int p) {
      // The indexes of the perfect cut
      int u, v;

      int r1, r2;

      int waste1 = (int) Math.ceil((m - p) / 2.0f);
      this.LL1 = calMid(endA, startA, endB, startB, m, n, -1, waste1);

      // Saves the value changed in calmid from global variable R to variable r1
      r1 = this.R;
      for (int j = 0; j <= r1; j++) {
        this.LL1[j] = n + 1 - this.LL1[j];
      }

      int waste2 = (int) Math.floor((m - p) / 2.0f);
      this.LL2 = calMid(startA, endA, startB, endB, m, n, 1, waste2);

      // Saves the value changed in calmid from global variable R to variable r2
      r2 = this.R;

      int k = Math.max(r1, r2);

      while (k > 0) {
        if (k <= r1 && p - k <= r2 && this.LL1[k] < this.LL2[p - k]) {
          break;
        } else {
          k--;
        }
      }

      u = k + waste1;
      v = this.LL1[k];

      // recursively call the LCS method to process the two subsequences
      computeLCS(startA, startA + u - 1, startB, startB + v - 1, u - 1 + 1, v - 1 + 1, u - waste1);
      computeLCS(startA + u, endA, startB + v, endB, endA - startA + 1 - u, endB - startB + 1 - v, m - u - waste2);
    }

    /**
     * Calculates the LCS length as described by Kumar-Rangan.
     *
     *

     *  (iii) Calculation of p:
     *  length(A, B, m, n, p);
     *     begin
     *  1.    r := O; s := m+l;
     *  2.    while s > r do
     *           begin
     *           s := s-1;
     *           fillone(A, B, m, n, R1, R2, r, s);
     *           R1(j) := R2(j) [j:=0...r] end;
     *  3.    p := s;
     *     end
     *

     *
     * @param m The length of the first sequence.
     * @param n The length of the second sequence.
     *
     * @return The LCS length.
     */
    private int calculateLength(int m, int n) {
      init(n);
      this.R = 0;
      this.S = m + 1;
      // iterate for every difference with the first sequence
      while (this.S > this.R) {
        this.S--;
        // fill up R2 up to the first difference using the entire sequences
        fillOne(0, m - 1, 0, n - 1, m, n, 1);
        // copy the content of R2 to R1 up to R
        copyUpTo(this.R2, this.R1, this.R);
      }
      // both R1 and R2 now contain the indexes(+1) of the first sequence that forms the LCS
      if (DEBUG) {
        System.err.println("LCS length=" + this.S);
      }
      return this.S;
    }

    /**
     * Write the deleted tokens to the formatter.
     *
     * @param jSeq2 The index of the LL array for the next token of the second sequence.
     */
    private void insertUpTo(int jSeq2) {
      while (jSeq2 > this.J) {
        this.handler.handle(Operator.INS, this.B.get(this.J++));
      }
    }

    private void printLL() {
      System.err.print(" LL={");
      for (int element : this.LL) {
        System.err.print(" " + element);
      }
      System.err.println(" }");
      System.err.print("  J={");
      for (int i = this.LL.length - 1; i >= 0; i--) {
        System.err.print(" " + (this.LL[i] - 1));
      }
      System.err.println(" }");
    }

  }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83.h
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-83.tmpl.h
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: environment Read input from an environment variable
 * GoodSource: Copy a fixed string into data
 * Sinks: vprintf
 *    GoodSink: vwprintf with a format string
 *    BadSink : vwprintf without a format string
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

namespace CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83
{

#ifndef OMITBAD

class CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_bad
{
public:
    CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_bad(wchar_t * dataCopy);
    ~CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_bad();

private:
    wchar_t * data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodG2B
{
public:
    CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodG2B(wchar_t * dataCopy);
    ~CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodG2B();

private:
    wchar_t * data;
};

class CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodB2G
{
public:
    CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodB2G(wchar_t * dataCopy);
    ~CWE134_Uncontrolled_Format_String__wchar_t_environment_vprintf_83_goodB2G();

private:
    wchar_t * data;
};

#endif /* OMITGOOD */

}


text:
title: "Lineman vs Yeoman"
category: "questions-answers"
slug: "lineman-vs-yeoman"
ordinal: 1
---

We are commonly asked, "How does Lineman differ from Yeoman?". Firstly, Lineman is a tool designed primarily to ease the creation of modern-client web applications. It is client-side framework agnostic, but opinionated about the workflow and tools developers use to _build_ any modern-client apps. However, given there is _some_ overlap between the two tools we thought it best to lay things out with a feature grid:

| Feature | Lineman | Yeoman |
|:--|:--|:--|
| Generators                | 1 builtin scaffold, clonable templates, no sub-generators       | No builtin scaffolds, installable generators, many sub-generators |
| Command Line Interface    | Wrapped utilities that are accessed via CLI ie: `lineman grunt` | Unwrapped utilities that are accessed via their CLI ie: `grunt`   |
| HTML5 pushState Simulator | builtin and enabled via `config/application` | - |
| API Stubbing Prototyping | builtin and enabled via `config/server` | - |
| API Proxy | builtin and enabled via `config/application` | - |
| Test Runner | testem, configured for dev and ci mode with `lineman spec`<br /> and `lineman spec-ci` | - |
| Grunt Task Lifecycle | preconfigured phases: `common, dev, dist`, split into `config/files` and `config/application` | generator specific |
| Dependency Graph | intentionally shallow and lightweight | generator specific, often deep and heavy |
| Cute ASCII Text Greeter | - | snazzy wizard based CLI |
| Package Management | none builtin but supports various, including bower, via extensions | bower |
| SourceMap Generation | builtin, defaults to `grunt-concat-sourcemap` | - |
| Dev Server | `lineman run`, spins up express.js | generator specific |
| Directory Structure | common across project templates | generator specific |
| License | [MIT](http://choosealicense.com/licenses/mit/) | [BSD](http://choosealicense.com/licenses/bsd/) |


text:
/* crypto/bn/bn_gf2m.c */
/* ====================================================================
 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
 *
 * The Elliptic Curve Public-Key Crypto Library (ECC Code) included
 * and may be modified; but after modifications, the above covenant
 * may no longer apply!  In such cases, the corresponding paragraph
 * ["In addition, Sun covenants ... causes the infringement."] and
 * this note can be edited out; but please keep the Sun copyright
 * notice and attribution. */

/* ====================================================================
 * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the


text:
<?php

namespace Mr5\Bayes\Tests\Tokenizer\Storage;

use Mr5\Bayes\Storage\ArrayStorage;
use Mr5\Bayes\Storage\StorageInterface;

abstract class AbstractStorageTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var StorageInterface
     */
    protected $storage;

    public function testCategoryFeaturesCount()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseCategoryFeaturesCount('testCategory');
            $this->assertEquals(
                $i,
                $this->storage->getCategoryFeaturesCount('testCategory')
            );
        }

        $this->storage->increaseCategoryFeaturesCount('testCategory2');
        $this->assertEquals(
            1,
            $this->storage->getCategoryFeaturesCount('testCategory2')
        );
    }

    public function testFeatureCountInCategory()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseFeatureCountInCategory(
                'testCategory',
                'testFeature'
            );
            $this->assertEquals(
                $i,
                $this->storage->getFeatureCountInCategory(
                    'testCategory',
                    'testFeature'
                )
            );
        }

        $this->storage->increaseFeatureCountInCategory(
            'testCategory',
            'testFeature2'
        );
        $this->assertEquals(
            1,
            $this->storage->getFeatureCountInCategory('testCategory', 'testFeature2')
        );

        $this->storage->increaseFeatureCountInCategory(
            'testCategory2',
            'testFeature'
        );
        $this->assertEquals(
            1,
            $this->storage->getFeatureCountInCategory('testCategory2', 'testFeature')
        );
    }

    public function testDocumentsCount()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseDocumentsCount();
            $this->assertEquals(
                $i,
                $this->storage->getDocumentsCount()
            );
        }
    }

    public function testCategoryDocumentsCount()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseCategoryDocumentsCount('testCategory');
            $this->assertEquals(
                $i,
                $this->storage->getCategoryDocumentsCount('testCategory')
            );
        }

        $this->storage->increaseCategoryDocumentsCount('testCategory2');
        $this->assertEquals(
            1,
            $this->storage->getCategoryDocumentsCount('testCategory2')
        );
    }

    public function testFeaturesCount()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseFeaturesCount();
            $this->assertEquals(
                $i,
                $this->storage->getFeaturesCount()
            );
        }
    }

    public function testFeatureCount()
    {
        for ($i = 1; $i < 4; $i++) {
            $this->storage->increaseFeatureCount('testFeature');
            $this->assertEquals(
                $i,
                $this->storage->getFeatureCount('testFeature')
            );
        }
        $this->storage->increaseFeatureCount('testFeature2');
        $this->assertEquals(
            1,
            $this->storage->getFeatureCount('testFeature2')
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace GymFitnessOlympic.Models.Util
{
    class FileUpload
    {
        public static string uploadImage(string fileName) {
            string dest =Directory.GetCurrentDirectory()+"\\image\\"+RandomString(20)+".jpg";

            var output = File.Open(dest, FileMode.OpenOrCreate);
            Stream outputStream = new FileStream(dest, FileMode.Create);
            StreamUtil.CopyFromFile(fileName, outputStream);
            StreamUtil.CopyToFile(outputStream, output.Name);

            return dest;
        }

        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }
    }
}


text:
<?php

namespace Illuminated\Console\Tests\Loggable\Notifications\EmailChannel;

use DateTime;
use Illuminated\Console\Loggable\Notifications\EmailChannel\MonologHtmlFormatter;
use Illuminated\Console\Tests\TestCase;
use Monolog\Logger;

class MonologHtmlFormatterTest extends TestCase
{
    /** @test */
    public function it_properly_formats_debug_records()
    {
        $record = $this->generateRecord('Debug!', Logger::DEBUG);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_info_records()
    {
        $record = $this->generateRecord('Info!', Logger::INFO);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_notice_records()
    {
        $record = $this->generateRecord('Notice!', Logger::NOTICE);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_warning_records()
    {
        $record = $this->generateRecord('Warning!', Logger::WARNING);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_error_records()
    {
        $record = $this->generateRecord('Error!', Logger::ERROR);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_critical_records()
    {
        $record = $this->generateRecord('Critical!', Logger::CRITICAL);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_alert_records()
    {
        $record = $this->generateRecord('Alert!', Logger::ALERT);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_emergency_records()
    {
        $record = $this->generateRecord('Emergency!', Logger::EMERGENCY);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_records_with_array_context()
    {
        $record = $this->generateRecord('Record with array context!', Logger::WARNING, [
            'foo' => 'bar',
            'baz' => 123,
            'faz' => true,
            'daz' => null,
        ]);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_properly_formats_records_with_non_array_context()
    {
        $record = $this->generateRecord('Record with non array context!', Logger::WARNING, 'Non array context');

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /** @test */
    public function it_has_no_environment_subtitle_for_production()
    {
        $this->emulateProduction();
        $record = $this->generateRecord('Notice!', Logger::NOTICE);

        $this->assertFormatterGeneratesExpectedOutput($record);
    }

    /**
     * Generate the record.
     */
    protected function generateRecord(string $message, int $level, array|string $context = []): array
    {
        return [
            'message' => $message,
            'context' => $context,
            'level' => $level,
            'level_name' => Logger::getLevelName($level),
            'channel' => 'ICLogger',
            'datetime' => new DateTime('2016-11-11 11:12:13'),
            'extra' => [],
        ];
    }

    /**
     * Assert that formatter generates expected output.
     */
    protected function assertFormatterGeneratesExpectedOutput(array $record): void
    {
        $expected = $this->composeExpectedOutput($record);
        $actual = (new MonologHtmlFormatter)->format($record);

        $this->assertEquals(
            $this->normalizeOutput($expected),
            $this->normalizeOutput($actual),
            'Generated html formatter output is not expected.'
        );
    }

    /**
     * Normalize the given output.
     */
    private function normalizeOutput(string $output): string
    {
        return preg_replace('/\s+/m', '', $output);
    }

    /**
     * Compose expected output by the given record.
     */
    private function composeExpectedOutput(array $record): string
    {
        $color = (new MonologHtmlFormatter)->getLevelColor($record['level']);

        $subtitle =
            "

This notification has been sent from the `TESTING` environment!
";
        if ($this->app->environment('production')) {
            $subtitle = '';
        }

        $context = '';
        if (!empty($record['context'])) {
            $dump = is_array($record['context']) ? get_dump($record['context']) : $record['context'];
            $dump = e($dump);
            $dump = str_replace(' ', ' ', $dump);
            $dump = nl2br($dump);

            $context = "

                Context:
                {$dump}

";
        }

        /** @noinspection HtmlRequiredTitleElement */
        return "<!DOCTYPE html>

                    <meta charset=\"utf-8\">
                    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

{$record['level_name']}

                    {$subtitle}

                            Message:
                            {$record['message']}

                        {$context}

                            Time:
                            {$record['datetime']->format('Y-m-d H:i:s')}

            ";
    }
}


text:
#ifndef NRF_LOG_DEFAULT_BACKENDS_H__
#define NRF_LOG_DEFAULT_BACKENDS_H__

/**@file
 * @addtogroup nrf_log Logger module
 * @ingroup    app_common
 *
 * @defgroup nrf_log_default_backends Functions for initializing and adding default backends
 * @{
 * @ingroup  nrf_log
 * @brief    The nrf_log default backends.
 */

#include "sdk_config.h"
#include "sdk_errors.h"
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @def NRF_LOG_DEFAULT_BACKENDS_INIT
 * @brief Macro for initializing default backends.
 *
 * Each backend enabled in configuration is initialized and added as a backend to the logger.
 */
#if NRF_LOG_ENABLED
#define NRF_LOG_DEFAULT_BACKENDS_INIT() nrf_log_default_backends_init()
#else
#define NRF_LOG_DEFAULT_BACKENDS_INIT()
#endif

void nrf_log_default_backends_init(void);

#ifdef __cplusplus
}
#endif

/** @} */

#endif // NRF_LOG_DEFAULT_BACKENDS_H__


text:
from concurrent import futures
import grpc
import logging
import os
import subprocess
import sys

# if the current directory is in scripts (pwd), then we need to
# add plugin in order to import from that directory
if os.path.split(os.path.dirname(__file__))[1] != 'plugin':
  sys.path.append(
      os.path.join(os.path.abspath(os.path.dirname(__file__)), 'plugin'))
from plugin_constants import PLUGIN_PROTOS_PATH, PLUGIN_SERVICE_WORKER_COUNT, PLUGIN_SERVICE_ADDRESS

sys.path.append(PLUGIN_PROTOS_PATH)
import test_plugin_service_pb2
import test_plugin_service_pb2_grpc

LOGGER = logging.getLogger(__name__)

class TestPluginServicer(test_plugin_service_pb2_grpc.TestPluginServiceServicer
                        ):
  """
  Implementation of test plugin service for communication between
  iOS test runner and EG tests
  """

  def __init__(self, enabled_plugins):
    """ Initializes a new instance of this class.

    Args:
      enabled_plugins: a list of initialized plugins to be used during
      different lifecycle stages of test execution. See the list of available
      test plugins in test_plugins.py

    """
    self.plugins = enabled_plugins

  def TestCaseWillStart(self, request, context):
    """ Executes plugin tasks when a test case is about to start """
    LOGGER.info('Received request for TestCaseWillStart %s', request)
    for plugin in self.plugins:
      plugin.test_case_will_start(request)
    return test_plugin_service_pb2.TestCaseWillStartResponse()

  def TestCaseDidFinish(self, request, context):
    """ Executes plugin tasks when a test case just finished executing """
    LOGGER.info('Received request for TestCaseDidFinish %s', request)
    for plugin in self.plugins:
      plugin.test_case_did_finish(request)
    return test_plugin_service_pb2.TestCaseDidFinishResponse()

  def TestCaseDidFail(self, request, context):
    """ Executes plugin tasks when a test case failed unexpectedly """
    LOGGER.info('Received request for TestCaseDidFail %s', request)
    for plugin in self.plugins:
      plugin.test_case_did_fail(request)
    return test_plugin_service_pb2.TestCaseDidFailResponse()

  def ListEnabledPlugins(self, request, context):
    """ Returns the list of enabled plugins """
    LOGGER.info('Received request for ListEnabledPlugins %s', request)
    plugins_str = [str(p) for p in self.plugins]
    return test_plugin_service_pb2.ListEnabledPluginsResponse(
        enabled_plugins=plugins_str)

  def reset(self):
    """
    Runs reset tasks for each plugin. This might be useful between
    each attempt of test runs
    """
    for plugin in self.plugins:
      LOGGER.info('Resetting %s', plugin)
      plugin.reset()

class TestPluginServicerWrapper:
  """ Wrapper for the test plugin service above.

  This class is useful for
  managing the plugin service such as start, tear_down, etc...
  """

  def __init__(self, servicer):
    """Initializes a new instance of this class.

    Args:
      servicer: an initialized test plugin service above

    """
    self.servicer = servicer
    self.server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=PLUGIN_SERVICE_WORKER_COUNT))

  def start_server(self):
    """ Starts a test plugin service, so it can receive gRPC requests """
    LOGGER.info('Starting test plugin server...')
    test_plugin_service_pb2_grpc.add_TestPluginServiceServicer_to_server(
        self.servicer, self.server)
    self.server.add_insecure_port(PLUGIN_SERVICE_ADDRESS)
    self.server.start()
    LOGGER.info('Test plugin server is running!')

  def wait_for_termination(self):
    """ Block current thread until the test plugin service stops """
    self.server.wait_for_termination()

  def tear_down(self):
    """ Resets and stop the test plugin service """
    LOGGER.info('Tearing down plugin service...')
    self.reset()
    self.server.stop(grace=None)

  def reset(self):
    """ Resets the test plugin service. This might be useful between
    each attempt of test runs """
    LOGGER.info('Resetting plugin service')
    self.servicer.reset()

# for testing purpose only when running locally
if __name__ == '__main__':
  server = TestPluginServicerWrapper(TestPluginServicer([]))
  server.start_server()
  server.wait_for_termination()