text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.core.validators
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Allele',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('sequence', models.TextField(validators=[django.core.validators.RegexValidator(regex='^[ACTGN]*$', message='Should ony contain nucleotide letters A,C,T, or G, and N for masked bases.')], verbose_name='allele sequence', help_text='Allele sequence should only contain A,C,T or G, and N for masked bases', max_length=1000)),
                ('length', models.PositiveIntegerField()),
                ('creationDate', models.DateField(auto_now_add=True)),
                ('validation', models.NullBooleanField(default=False)),
                ('doi', models.CharField(null=True, max_length=200)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='FLADkey',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('FLADkey', models.CharField(max_length=50)),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Locus',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=100)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='TestAllele',
            fields=[
                ('allele_ptr', models.OneToOneField(parent_link=True, serialize=False, to='flad.Allele', auto_created=True, primary_key=True)),
            ],
            options={
            },
            bases=('flad.allele',),
        ),
        migrations.AddField(
            model_name='allele',
            name='locus',
            field=models.ForeignKey(to='flad.Locus'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='allele',
            name='users',
            field=models.ManyToManyField(to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TIS.Imaging;
using TIS.Imaging.VCDHelpers;

namespace RCCM
{
    /// <summary>
    /// Class representing DMK Z12G445 camera for the RCCM WFOV
    /// </summary>
    public class WFOV : ICamera
    {
        /// <summary>
        /// Height in pixels of image
        /// </summary>
        public static int IMG_HEIGHT = 960;
        /// <summary>
        /// Width in pixels of image
        /// </summary>
        public static int IMG_WIDTH = 1280;
        /// <summary>
        /// Flag to indicate connection status of WFOV camera
        /// </summary>
        public bool Available { get; private set; }
        /// <summary>
        /// Camera units / pixel calibration
        /// </summary>
        public double Scale { get; protected set; }
        /// <summary>
        /// Height in mm of image
        /// </summary>
        public double Height
        {
            get { return this.Scale * WFOV.IMG_HEIGHT; }
        }
        /// <summary>
        /// Height in mm of image
        /// </summary>
        public double Width
        {
            get { return this.Scale * WFOV.IMG_WIDTH; }
        }
        /// <summary>
        /// Zoom level of the camera, an integer between 0 and 100
        /// </summary>
        public int Zoom
        {
            get { return VCDProp.RangeValue[VCDIDs.VCDID_Zoom]; }
            set { VCDProp.RangeValue[VCDIDs.VCDID_Zoom] = value; }
        }
        /// <summary>
        /// Focal distance of the camera, roughly equating to distance in mm
        /// </summary>
        public int Focus
        {
            get { return VCDProp.RangeValue[VCDIDs.VCDID_Focus]; }
            set { VCDProp.RangeValue[VCDIDs.VCDID_Focus] = value; }
        }
        /// <summary>
        /// Minimum focal distance of the camera
        /// </summary>
        public int FocusMin
        {
            get { return this.VCDProp.RangeMin(VCDIDs.VCDID_Focus); }
        }
        /// <summary>
        /// Maximum focal distance of the camera
        /// </summary>
        public int FocusMax
        {
            get { return this.VCDProp.RangeMax(VCDIDs.VCDID_Focus); }
        }
        /// <summary>
        /// Minimum zoom level of the camera
        /// </summary>
        public int ZoomMin
        {
            get { return this.VCDProp.RangeMin(VCDIDs.VCDID_Zoom); }
        }
        /// <summary>
        /// Maximum zoom level of the camera
        /// </summary>
        public int ZoomMax
        {
            get { return this.VCDProp.RangeMax(VCDIDs.VCDID_Zoom); }
        }
        /// <summary>
        /// Imaging user control for displaying the live image
        /// </summary>
        protected ICImagingControl ic;
        /// <summary>
        /// Camera properties accessor
        /// </summary>
        protected VCDSimpleProperty VCDProp;
        /// <summary>
        /// Flag to indicate if a video is being recorded
        /// </summary>
        public bool Recording { get; private set; }
        /// <summary>
        /// File path to configuration file from which camera is initialized
        /// </summary>
        public string configFile { get; set; }
        /// <summary>
        /// File path to configuration file from which camera is initialized
        /// </summary>
        public double CalibrationHeight { get; protected set; }
        /// <summary>
        /// File path to configuration file from which camera is initialized
        /// </summary>
        public double CalibrationZoom { get; protected set; }
        /// <summary>
        /// File path to configuration file from which camera is initialized
        /// </summary>
        public double CalibrationFocus { get; protected set; }

        /// <summary>
        /// Create WFOV camera from configuration file
        /// </summary>
        /// <param name="name">Name of camera in settings</param>
        public WFOV(string name)
        {
            this.configFile = (string)Program.Settings.json[name]["configuration file"];
            this.Scale = (double)Program.Settings.json[name]["units / pixel"];
            this.CalibrationHeight = (double)Program.Settings.json[name]["calibration height"];
            this.CalibrationZoom = (int)Program.Settings.json[name]["calibration zoom"];
            this.CalibrationFocus = (int)Program.Settings.json[name]["calibration focus"];
            this.Recording = false;
        }

        /// <summary>
        /// Connect to camera. Will fail if configuration file referred to invalid or disconnected camera
        /// </summary>
        /// <returns>True if initialization is successful</returns>
        public bool Initialize(ICImagingControl ic)
        {
            this.ic = ic;
            try
            {
                this.ic.LoadDeviceStateFromFile(this.configFile, true);
                this.Available = true;
            }
            catch (TIS.Imaging.ICException err)
            {
                System.Windows.Forms.MessageBox.Show("Error occurred while initializing WFOV camera. WFOV will be unavailable.\n\n" + err.ToString());
                Logger.Out(err.ToString());
                this.Available = false;
                return false;
            }
            catch (System.IO.IOException err)
            {
                System.Windows.Forms.MessageBox.Show("WFOV configuration file missing or invalid.");
                Logger.Out(err.ToString());
                this.Available = false;
                return false;
            }

            if (this.ic.DeviceValid)
            {
                this.ic.LivePrepare();
                this.VCDProp = VCDSimpleModule.GetSimplePropertyContainer(this.ic.VCDPropertyItems);
                this.ic.DeviceLost += this.handleDisconnect;
                return true;
            }
            System.Windows.Forms.MessageBox.Show("Failed to initialize WFOV camera");
            return false;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void handleDisconnect(object sender, ICImagingControl.DeviceLostEventArgs e)
        {
            this.Available = false;
        }

        /// <summary>
        /// Begin displaying live image
        /// </summary>
        public void Start()
        {
            if (this.Available && this.ic.DeviceValid && !this.ic.LiveVideoRunning)
            {
                // Device suspended, start it
                try
                {
                    this.ic.LiveStart();
                    this.ic.LiveDisplayDefault = false;
                    this.ic.LiveDisplayHeight = this.ic.ImageHeight / 2;
                    this.ic.LiveDisplayWidth = this.ic.ImageWidth / 2;
                    this.ic.ScrollbarsEnabled = true;
                }
                catch (TIS.Imaging.ICException err)
                {
                    throw err;
                }
            }
            else
            {
                MessageBox.Show("Camera disconnected");
            }
        }

        /// <summary>
        /// Stop displaying live image. Will also cease video recording, if active
        /// </summary>
        public void Stop()
        {
            if (this.Available && this.ic.LiveVideoRunning && this.ic.DeviceValid)
            {
                if (this.Recording)
                {
                    this.StopRecord();
                }
                try
                {
                    this.ic.LiveStop();
                    this.ic.SaveDeviceStateToFile(this.configFile);
                }
                catch (Exception ex)
                {
                }
            }
        }

        /// <summary>
        /// Capture live image to file
        /// </summary>
        /// <param name="filename">Filename to save image to. Should have .png extension</param>
        public void Snap(string filename)
        {
            try
            {
                if (this.Available && this.ic.DeviceValid)
                {
                    this.ic.MemorySnapImage();
                    this.ic.MemorySaveImage(filename);
                }
                else
                {
                    MessageBox.Show("Camera disconnected");
                }
            }
            catch (TIS.Imaging.ICException err)
            {
                Logger.Out(err.ToString());
            }
            catch (Exception err)
            {
                Logger.Out(err.ToString());
            }
        }

        /// <summary>
        /// Start recording video to specified path
        /// </summary>
        /// <param name="filename"></param>
        public void Record(string filename)
        {
            if (this.Available && this.ic.LiveVideoRunning && this.ic.DeviceValid)
            {
                if (this.Recording == false)
                {
                    this.ic.AviStartCapture(filename, this.ic.AviCompressors[0]);
                    this.Recording = true;
                }
            }
            else
            {
                MessageBox.Show("Camera disconnected");
            }
        }

        /// <summary>
        /// Stop recording video. Will resume live display after stopping recording
        /// </summary>
        public void StopRecord()
        {
            if (this.Available && this.ic.DeviceValid)
            {
                this.ic.AviStopCapture();
                this.Recording = false;
                this.ic.LiveStart();
            }
            else
            {
                MessageBox.Show("Camera disconnected");
            }
        }

        /// <summary>
        /// Set image scale and save current height, zoom, and focus
        /// </summary>
        /// <param name="rccm"></param>
        /// <param name="scale">New calibration</param>
        public void SetScale(RCCMSystem rccm, double scale)
        {
            // Get z motor for this stage
            Motor z = this == rccm.WFOV1 ? rccm.motors["fine 1 Z"] : rccm.motors["fine 2 Z"];
            this.CalibrationHeight = z.GetPos();
            this.CalibrationZoom = this.Zoom;
            this.CalibrationFocus = this.Focus;

            string camera = this == rccm.WFOV1 ? "wfov 1" : "wfov 2";
            Program.Settings.json[camera]["calibration height"] = this.CalibrationHeight;
            Program.Settings.json[camera]["calibration zoom"] = this.CalibrationZoom;
            Program.Settings.json[camera]["calibration focus"] = this.CalibrationFocus;
            this.Scale = scale;
        }

        /// <summary>
        /// Check if measurement conditions match calibration conditions
        /// </summary>
        /// <param name="rccm"></param>
        /// <returns>True if measurement conditions match calibration</returns>
        public bool CheckFOV(RCCMSystem rccm)
        {
            // Get z motor for this stage
            Motor z = this == rccm.WFOV1 ? rccm.motors["fine 1 Z"] : rccm.motors["fine 2 Z"];
            // Get curernt height
            double h = z.GetPos();
            // Check that calibration height and current height are within a tolerance
            return Math.Abs(this.CalibrationHeight - h) < 3 * TrioStepperZMotor.ERROR &&
                   this.CalibrationZoom == this.Zoom &&
                   Math.Abs(this.CalibrationFocus - this.Focus) < 10;
        }

        /// <summary>
        /// Show device property dialog
        /// <warning>Will cause device to crash if "Cancel" button is pressed from property dialog</warning>
        /// </summary>
        public void EditProperties()
        {
            if (this.Available && this.ic.DeviceValid)
            {
                this.ic.ShowPropertyDialog();
            }
            else
            {
                MessageBox.Show("Camera disconnected");
            }
        }

        /// <summary>
        /// Activate built-in camera autofocus. Requires 2 second sleep to allow autofocus to complete
        /// </summary>
        /// <returns>New focus level</returns>
        public int AutoFocus()
        {
            if (this.Available && this.ic.DeviceValid)
            {
                VCDProp.OnePush(VCDIDs.VCDID_Focus);
                // Stupid work-around recommended by TIS:
                // Wait two seconds and assume autofocus will complete by then
                System.Threading.Thread.Sleep(2000);
                return VCDProp.RangeValue[VCDIDs.VCDID_Focus];
            }
            else
            {
                MessageBox.Show("Camera disconnected");
                return 0;
            }
        }
    }
}


text:
#ifndef HSEARCH_H
#define HSEARCH_H

/*
 * Hash functions must have this signature.
 */
typedef uint32 (*HashValueFunc) (const void *key, Size keysize);

/*
 * Key comparison functions must have this signature.  Comparison functions
 * return zero for match, nonzero for no match.  (The comparison function
 * definition is designed to allow memcmp() and strncmp() to be used directly
 * as key comparison functions.)
 */
typedef int (*HashCompareFunc) (const void *key1, const void *key2,
											Size keysize);

/*
 * Key copying functions must have this signature.	The return value is not
 * used.  (The definition is set up to allow memcpy() and strncpy() to be
 * used directly.)
 */
typedef void *(*HashCopyFunc) (void *dest, const void *src, Size keysize);

/*
 * Space allocation function for a hashtable --- designed to match malloc().
 * Note: there is no free function API; can't destroy a hashtable unless you
 * use the default allocator.
 */
typedef void *(*HashAllocFunc) (Size request);

/*
 * HASHELEMENT is the private part of a hashtable entry.  The caller's data
 * follows the HASHELEMENT structure (on a MAXALIGN'd boundary).  The hash key
 * is expected to be at the start of the caller's hash entry data structure.
 */
typedef struct HASHELEMENT
{
	struct HASHELEMENT *link;	/* link to next entry in same bucket */
	uint32		hashvalue;		/* hash function result for this entry */
} HASHELEMENT;

/* Hash table header struct is an opaque type known only within dynahash.c */
typedef struct HASHHDR HASHHDR;

/* Hash table control struct is an opaque type known only within dynahash.c */
typedef struct HTAB HTAB;

/* Parameter data structure for hash_create */
/* Only those fields indicated by hash_flags need be set */
typedef struct HASHCTL
{
	long		num_partitions; /* # partitions (must be power of 2) */
	long		ssize;			/* segment size */
	long		dsize;			/* (initial) directory size */
	long		max_dsize;		/* limit to dsize if dir size is limited */
	long		ffactor;		/* fill factor */
	Size		keysize;		/* hash key length in bytes */
	Size		entrysize;		/* total user element size in bytes */
	HashValueFunc hash;			/* hash function */
	HashCompareFunc match;		/* key comparison function */
	HashCopyFunc keycopy;		/* key copying function */
	HashAllocFunc alloc;		/* memory allocator */
	MemoryContext hcxt;			/* memory context to use for allocations */
	HASHHDR    *hctl;			/* location of header in shared mem */
} HASHCTL;

/* Flags to indicate which parameters are supplied */
#define HASH_PARTITION	0x001	/* Hashtable is used w/partitioned locking */
#define HASH_SEGMENT	0x002	/* Set segment size */
#define HASH_DIRSIZE	0x004	/* Set directory size (initial and max) */
#define HASH_FFACTOR	0x008	/* Set fill factor */
#define HASH_FUNCTION	0x010	/* Set user defined hash function */
#define HASH_ELEM		0x020	/* Set keysize and entrysize */
#define HASH_SHARED_MEM 0x040	/* Hashtable is in shared memory */
#define HASH_ATTACH		0x080	/* Do not initialize hctl */
#define HASH_ALLOC		0x100	/* Set memory allocator */
#define HASH_CONTEXT	0x200	/* Set memory allocation context */
#define HASH_COMPARE	0x400	/* Set user defined comparison function */
#define HASH_KEYCOPY	0x800	/* Set user defined key-copying function */

/* max_dsize value to indicate expansible directory */
#define NO_MAX_DSIZE			(-1)

/* hash_search operations */
typedef enum
{
	HASH_FIND,
	HASH_ENTER,
	HASH_REMOVE,
	HASH_ENTER_NULL
} HASHACTION;

/* hash_seq status (should be considered an opaque type by callers) */
typedef struct
{
	HTAB	   *hashp;
	uint32		curBucket;		/* index of current bucket */
	HASHELEMENT *curEntry;		/* current entry in bucket */
} HASH_SEQ_STATUS;

/*
 * prototypes for functions in dynahash.c
 */
extern HTAB *hash_create(const char *tabname, long nelem,
			HASHCTL *info, int flags);
extern void hash_destroy(HTAB *hashp);
extern void hash_stats(const char *where, HTAB *hashp);
extern void *hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action,
			bool *foundPtr);
extern uint32 get_hash_value(HTAB *hashp, const void *keyPtr);
extern void *hash_search_with_hash_value(HTAB *hashp, const void *keyPtr,
							uint32 hashvalue, HASHACTION action,
							bool *foundPtr);
extern long hash_get_num_entries(HTAB *hashp);
extern void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp);
extern void *hash_seq_search(HASH_SEQ_STATUS *status);
extern void hash_seq_term(HASH_SEQ_STATUS *status);
extern void hash_freeze(HTAB *hashp);
extern Size hash_estimate_size(long num_entries, Size entrysize);
extern long hash_select_dirsize(long num_entries);
extern Size hash_get_shared_size(HASHCTL *info, int flags);
extern void AtEOXact_HashTables(bool isCommit);
extern void AtEOSubXact_HashTables(bool isCommit, int nestDepth);

/*
 * prototypes for functions in hashfn.c
 */
extern uint32 string_hash(const void *key, Size keysize);
extern uint32 tag_hash(const void *key, Size keysize);
extern uint32 oid_hash(const void *key, Size keysize);
extern uint32 bitmap_hash(const void *key, Size keysize);
extern int	bitmap_match(const void *key1, const void *key2, Size keysize);

#endif   /* HSEARCH_H */


text:
import supriya

from .. import project_settings, synthdefs
from ..materials import libretto_x

class SessionFactory(supriya.nonrealtime.SessionFactory):

    ### CLASS VARIABLES ###

    release_time = 15

    ### SESSION ###

    def __session__(self, initial_seed=0, layer_count=10, minutes=2, **kwargs):
        self.buffers = []
        session = supriya.Session(
            input_bus_channel_count=self.input_bus_channel_count,
            output_bus_channel_count=self.output_bus_channel_count,
        )
        with session.at(0):
            for say in libretto_x:
                buffer_ = session.add_buffer(channel_count=1, file_path=say)
                self.buffers.append(buffer_)
        for i in range(layer_count):
            with session.at(i * 10):
                session.inscribe(
                    self.global_pattern, duration=60 * minutes, seed=initial_seed + i
                )
        with session.at(0):
            session.add_synth(
                synthdef=synthdefs.compressor_synthdef,
                add_action="ADD_TO_TAIL",
                duration=session.duration + self.release_time,
                pregain=0,
            )
            session.set_rand_seed(initial_seed)
        return session

    ### GLOBAL PATTERN ###

    @property
    def global_pattern(self):
        global_pattern = supriya.patterns.Pgpar(
            [self.source_pattern, self.effect_pattern], release_time=self.release_time
        )
        global_pattern = global_pattern.with_bus(release_time=self.release_time)
        return global_pattern

    ### SOURCE PATTERNS ###

    @property
    def source_pattern(self):
        source_pattern = self.one_shot_player_pattern
        source_pattern = source_pattern.with_group(release_time=self.release_time)
        source_pattern = source_pattern.with_effect(
            synthdef=synthdefs.compressor_synthdef,
            release_time=self.release_time,
            pregain=12,
        )
        return source_pattern

    @property
    def one_shot_player_pattern(self):
        return supriya.patterns.Pbind(
            synthdef=synthdefs.one_shot_player_synthdef,
            add_action=supriya.AddAction.ADD_TO_HEAD,
            buffer_id=supriya.patterns.Prand(self.buffers, repetitions=None),
            delta=supriya.patterns.Pwhite(0, 10),
            duration=0,
            gain=supriya.patterns.Pwhite(-12, 12),
            pan=supriya.patterns.Pwhite(-1, 1.0),
            rate=2 ** supriya.patterns.Pwhite(-1.5, 0.5),
        )

    ### EFFECT PATTERNS ###

    @property
    def allpass_pattern(self):
        return supriya.patterns.Pbindf(
            self.fx_pattern, synthdef=synthdefs.windowed_allpass_synthdef, gain=0
        )

    @property
    def chorus_pattern(self):
        return supriya.patterns.Pbindf(
            self.fx_pattern,
            synthdef=synthdefs.windowed_chorus_factory.build(
                name="chorus8", iterations=8
            ),
            frequency=supriya.patterns.Pwhite() * 2,
            gain=3,
        )

    @property
    def effect_pattern(self):
        effect_pattern = supriya.patterns.Ppar(
            [
                self.allpass_pattern,
                self.chorus_pattern,
                self.freeverb_pattern,
                self.freqshift_pattern,
                self.allpass_pattern,
            ]
        )
        effect_pattern = effect_pattern.with_group(release_time=self.release_time)
        effect_pattern = effect_pattern.with_effect(
            synthdef=synthdefs.compressor_synthdef,
            release_time=self.release_time,
            pregain=3,
        )
        return effect_pattern

    @property
    def freeverb_pattern(self):
        return supriya.patterns.Pbindf(
            self.fx_pattern,
            synthdef=synthdefs.windowed_freeverb_synthdef,
            damping=supriya.patterns.Pwhite() ** 0.25,
            gain=3,
            level=supriya.patterns.Pwhite(0.125, 0.5),
            room_size=supriya.patterns.Pwhite() ** 0.25,
        )

    @property
    def freqshift_pattern(self):
        return supriya.patterns.Pbindf(
            self.fx_pattern,
            level=2 ** supriya.patterns.Pwhite(-4, -2),
            synthdef=synthdefs.windowed_freqshift_synthdef,
            sign=supriya.patterns.Prand([-1, 1]),
        )

    @property
    def fx_pattern(self):
        return supriya.patterns.Pbind(
            add_action=supriya.AddAction.ADD_TO_TAIL,
            delta=supriya.patterns.Pwhite(0, 10),
            duration=supriya.patterns.Pwhite(5, 30),
            level=supriya.patterns.Pwhite(0.25, 1.0),
        )

lost_and_found = SessionFactory.from_project_settings(project_settings)


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="135"
        android:centerColor="#7EA7D9"
        android:endColor="#7fb0ea"
        android:startColor="#a0bde1"
        android:type="linear" />
</shape>


text:
require 'set'

# This is a hack that I don't want to ever use anywhere else or repeat EVER, but we need enums to be
# an Array to pass schema validation. But we also want fast lookup!

class ArraySet < Array
  def include?(obj)
    if !defined? @values
      @values = Set.new
      self.each { |x| @values << convert_to_float_if_numeric(x) }
    end
    @values.include?(convert_to_float_if_numeric(obj))
  end

  private

  def convert_to_float_if_numeric(value)
    value.is_a?(Numeric) ? value.to_f : value
  end
end


text:
@import XCTest;

#import "Stripe.h"

@interface STPCardFunctionalTest : XCTestCase
@end

@implementation STPCardFunctionalTest

- (void)testCreateCardToken {
    STPCardParams *card = [[STPCardParams alloc] init];

    card.number = @"4242 4242 4242 4242";
    card.expMonth = 6;
    card.expYear = 2018;
    card.currency = @"usd";

    STPAPIClient *client = [[STPAPIClient alloc] initWithPublishableKey:@"pk_test_5fhKkYDKKNr4Fp6q7Mq9CwJd"];

    XCTestExpectation *expectation = [self expectationWithDescription:@"Card creation"];

    [client createTokenWithCard:card
                     completion:^(STPToken *token, NSError *error) {
                         [expectation fulfill];

                         XCTAssertNil(error, @"error should be nil %@", error.localizedDescription);
                         XCTAssertNotNil(token, @"token should not be nil");

                         XCTAssertNotNil(token.tokenId);
                         XCTAssertEqual(6U, token.card.expMonth);
                         XCTAssertEqual(2018U, token.card.expYear);
                         XCTAssertEqualObjects(@"4242", token.card.last4);
                         XCTAssertEqualObjects(@"usd", token.card.currency);
                     }];
    [self waitForExpectationsWithTimeout:5.0f handler:nil];
}

- (void)testCardTokenCreationWithInvalidParams {
    STPCardParams *card = [[STPCardParams alloc] init];

    card.number = @"4242 4242 4242 4241";
    card.expMonth = 6;
    card.expYear = 2018;

    STPAPIClient *client = [[STPAPIClient alloc] initWithPublishableKey:@"pk_test_5fhKkYDKKNr4Fp6q7Mq9CwJd"];

    XCTestExpectation *expectation = [self expectationWithDescription:@"Card creation"];

    [client createTokenWithCard:card
                     completion:^(STPToken *token, NSError *error) {
                         [expectation fulfill];

                         XCTAssertNotNil(error, @"error should not be nil");
                         XCTAssertEqual(error.code, 70);
                         XCTAssertEqualObjects(error.domain, StripeDomain);
                         XCTAssertEqualObjects(error.userInfo[STPErrorParameterKey], @"number");
                         XCTAssertNil(token, @"token should not be nil: %@", token.description);
                     }];
    [self waitForExpectationsWithTimeout:5.0f handler:nil];
}

- (void)testInvalidKey {
    STPCardParams *card = [[STPCardParams alloc] init];

    card.number = @"4242 4242 4242 4242";
    card.expMonth = 6;
    card.expYear = 2018;

    STPAPIClient *client = [[STPAPIClient alloc] initWithPublishableKey:@"not_a_valid_key_asdf"];

    XCTestExpectation *expectation = [self expectationWithDescription:@"Card failure"];
    [client createTokenWithCard:card
                     completion:^(STPToken *token, NSError *error) {
                         [expectation fulfill];
                         XCTAssertNil(token, @"token should be nil");
                         XCTAssertNotNil(error, @"error should not be nil");
                         XCTAssert([error.localizedDescription rangeOfString:@"asdf"].location != NSNotFound, @"error should contain last 4 of key");
                     }];
    [self waitForExpectationsWithTimeout:5.0f handler:nil];
}

@end


text:
function myVeil() {
    var veil = null, state = 'off', snapObj = null, reveal = null;
    veil = document.getElementById('veilVeil');

    //************************************************
    // do we already exist ?
    //************************************************

    if (veil) {
        return veil.selfFunctions;
    }
    //************************************************
    // create the div
    //************************************************

    if (veil === null) {
        veil = document.createElement('DIV');
        veil.tabIndex = 1;
        veil.id = 'veilVeil';
        veil.style.width = '100%';
        veil.style.zIndex = -1;
        veil.style.background = 'rgba(255, 255, 255, 0.18)';
        veil.style.visibility = 'hidden';
        veil.style.display = 'nones';
        veil.style.position = 'fixed';
        veil.style.top = '0px';
        veil.style.left = '0px';
        veil.style.opacity = 0.2;
        veil.style.background = '';
        veil.style.height = window.innerHeight + 'px';
        document.body.appendChild(veil);
    }

    function veilOn() {
        //************************************************
        // turn on
        //************************************************
        veil.style.visibility = 'visible';
        veil.style.display = 'block';
        veil.style.height = window.innerHeight + 'px';
        veil.style.zIndex = 55;
        state = 'on';
        window.addEventListener('resize', trackInnerHeight, false);
    }

    function veilOff() {
        //************************************************
        // turn off
        //************************************************
        veil.style.visibility = 'hidden';
        veil.style.display = 'none';
        veil.style.height = window.innerHeight + 'px';
        veil.style.zIndex = -1;
        state = 'off';
        window.removeEventListener('resize', trackInnerHeight, false);
        snapObj = null;
    }
    function veilSnapToCenter(obj) {
        //************************************************
        // snap given object, usualy a dialogbox,  to the
        //  center of the vail and above itself
        //************************************************
        var ow, oh, ww, wh;
        if (state === 'off') {
            return;
        }
        ow = obj.clientWidth;
        oh = obj.clientHeight;
        ww = veil.style.height = window.innerWidth;
        wh = veil.style.height = window.innerHeight;
        obj.style.position = 'absolute';
        obj.style.top = (wh / 2 - oh / 2) + 'px';
        obj.style.left = (ww / 2 - ow / 2) + 'px';
        obj.style.zIndex = veil.style.zIndex + 1;
        snapObj = obj;

    }
    //
    //************************************************
    // function to  take care of window resize event
    //************************************************

    function trackInnerHeight() {
        if (state === 'on') {
            veil.style.height = window.innerHeight + 'px';
        }
        veilSnapToCenter(snapObj);
    }
    window.onfocus = function (e) {
        var h = e;
    };
    reveal = {
        veil: function () {// expose the veil object
            return veil;
        }(),
        veilOn: veilOn, //()
        veilOff: veilOff, //()
        veilSnapToCenter: veilSnapToCenter //(obj)
    };
    veil.selfFunctions = reveal;
    return reveal;
}


text:
package native

import (
	"debug/elf"
	"syscall"
	"unsafe"

	sys "golang.org/x/sys/unix"

	"github.com/go-delve/delve/pkg/dwarf/op"
	"github.com/go-delve/delve/pkg/proc"
	"github.com/go-delve/delve/pkg/proc/linutil"
)

const (
	_AARCH64_GREGS_SIZE  = 34 * 8
	_AARCH64_FPREGS_SIZE = 32*16 + 8
	_NT_ARM_TLS          = 0x401 // used in PTRACE_GETREGSET on ARM64 to retrieve the value of TPIDR_EL0, see source/include/uapi/linux/elf.h and source/arch/arm64/kernel/ptrace.c
)

func ptraceGetGRegs(pid int, regs *linutil.ARM64PtraceRegs) (err error) {
	iov := sys.Iovec{Base: (*byte)(unsafe.Pointer(regs)), Len: _AARCH64_GREGS_SIZE}
	_, _, err = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_GETREGSET, uintptr(pid), uintptr(elf.NT_PRSTATUS), uintptr(unsafe.Pointer(&iov)), 0, 0)
	if err == syscall.Errno(0) {
		err = nil
	}
	return
}

func ptraceGetTpidr_el0(pid int, tpidr_el0 *uint64) (err error) {
	iov := sys.Iovec{Base: (*byte)(unsafe.Pointer(tpidr_el0)), Len: uint64(unsafe.Sizeof(*tpidr_el0))}
	_, _, err = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_GETREGSET, uintptr(pid), uintptr(_NT_ARM_TLS), uintptr(unsafe.Pointer(&iov)), 0, 0)
	if err == syscall.Errno(0) {
		err = nil
	}
	return
}

func ptraceSetGRegs(pid int, regs *linutil.ARM64PtraceRegs) (err error) {
	iov := sys.Iovec{Base: (*byte)(unsafe.Pointer(regs)), Len: _AARCH64_GREGS_SIZE}
	_, _, err = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_SETREGSET, uintptr(pid), uintptr(elf.NT_PRSTATUS), uintptr(unsafe.Pointer(&iov)), 0, 0)
	if err == syscall.Errno(0) {
		err = nil
	}
	return
}

// ptraceGetFpRegset returns floating point registers of the specified thread
// using PTRACE.
func ptraceGetFpRegset(tid int) (fpregset []byte, err error) {
	var arm64_fpregs [_AARCH64_FPREGS_SIZE]byte
	iov := sys.Iovec{Base: &arm64_fpregs[0], Len: _AARCH64_FPREGS_SIZE}
	_, _, err = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_GETREGSET, uintptr(tid), uintptr(elf.NT_FPREGSET), uintptr(unsafe.Pointer(&iov)), 0, 0)
	if err != syscall.Errno(0) {
		if err == syscall.ENODEV {
			err = nil
		}
		return
	} else {
		err = nil
	}

	fpregset = arm64_fpregs[:iov.Len-8]
	return fpregset, err
}

// setPC sets PC to the value specified by 'pc'.
func (thread *nativeThread) setPC(pc uint64) error {
	ir, err := registers(thread)
	if err != nil {
		return err
	}
	r := ir.(*linutil.ARM64Registers)
	r.Regs.Pc = pc
	thread.dbp.execPtraceFunc(func() { err = ptraceSetGRegs(thread.ID, r.Regs) })
	return err
}

func (thread *nativeThread) SetReg(regNum uint64, reg *op.DwarfRegister) error {
	ir, err := registers(thread)
	if err != nil {
		return err
	}
	r := ir.(*linutil.ARM64Registers)
	fpchanged, err := r.SetReg(regNum, reg)
	if err != nil {
		return err
	}

	thread.dbp.execPtraceFunc(func() {
		err = ptraceSetGRegs(thread.ID, r.Regs)
		if err != syscall.Errno(0) && err != nil {
			return
		}
		if fpchanged && r.Fpregset != nil {
			iov := sys.Iovec{Base: &r.Fpregset[0], Len: uint64(len(r.Fpregset))}
			_, _, err = syscall.Syscall6(syscall.SYS_PTRACE, sys.PTRACE_SETREGSET, uintptr(thread.ID), uintptr(elf.NT_FPREGSET), uintptr(unsafe.Pointer(&iov)), 0, 0)
		}
	})
	if err == syscall.Errno(0) {
		err = nil
	}
	return err
}

func registers(thread *nativeThread) (proc.Registers, error) {
	var (
		regs linutil.ARM64PtraceRegs
		err  error
	)
	thread.dbp.execPtraceFunc(func() { err = ptraceGetGRegs(thread.ID, &regs) })
	if err != nil {
		return nil, err
	}
	var tpidr_el0 uint64
	if thread.dbp.iscgo {
		thread.dbp.execPtraceFunc(func() { err = ptraceGetTpidr_el0(thread.ID, &tpidr_el0) })
		if err != nil {
			return nil, err
		}
	}
	r := linutil.NewARM64Registers(&regs, thread.dbp.iscgo, tpidr_el0, func(r *linutil.ARM64Registers) error {
		var floatLoadError error
		r.Fpregs, r.Fpregset, floatLoadError = thread.fpRegisters()
		return floatLoadError
	})
	return r, nil
}


text:
package wsstream

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"
	"reflect"
	"strings"
	"testing"
	"time"

	"golang.org/x/net/websocket"
)

func TestStream(t *testing.T) {
	input := "some random text"
	r := NewReader(bytes.NewBuffer([]byte(input)), true)
	r.SetIdleTimeout(time.Second)
	data, err := readWebSocket(r, t, nil)
	if !reflect.DeepEqual(data, []byte(input)) {
		t.Errorf("unexpected server read: %v", data)
	}
	if err != nil {
		t.Fatal(err)
	}
}

func TestStreamPing(t *testing.T) {
	input := "some random text"
	r := NewReader(bytes.NewBuffer([]byte(input)), true)
	r.SetIdleTimeout(time.Second)
	err := expectWebSocketFrames(r, t, nil, [][]byte{
		{},
		[]byte(input),
	})
	if err != nil {
		t.Fatal(err)
	}
}

func TestStreamBase64(t *testing.T) {
	input := "some random text"
	encoded := base64.StdEncoding.EncodeToString([]byte(input))
	r := NewReader(bytes.NewBuffer([]byte(input)), true)
	data, err := readWebSocket(r, t, nil, base64BinaryWebSocketProtocol)
	if !reflect.DeepEqual(data, []byte(encoded)) {
		t.Errorf("unexpected server read: %v\n%v", data, []byte(encoded))
	}
	if err != nil {
		t.Fatal(err)
	}
}

func TestStreamError(t *testing.T) {
	input := "some random text"
	errs := &errorReader{
		reads: [][]byte{
			[]byte("some random"),
			[]byte(" text"),
		},
		err: fmt.Errorf("bad read"),
	}
	r := NewReader(errs, false)

	data, err := readWebSocket(r, t, nil)
	if !reflect.DeepEqual(data, []byte(input)) {
		t.Errorf("unexpected server read: %v", data)
	}
	if err == nil || err.Error() != "bad read" {
		t.Fatal(err)
	}
}

func TestStreamSurvivesPanic(t *testing.T) {
	input := "some random text"
	errs := &errorReader{
		reads: [][]byte{
			[]byte("some random"),
			[]byte(" text"),
		},
		panicMessage: "bad read",
	}
	r := NewReader(errs, false)

	data, err := readWebSocket(r, t, nil)
	if !reflect.DeepEqual(data, []byte(input)) {
		t.Errorf("unexpected server read: %v", data)
	}
	if err != nil {
		t.Fatal(err)
	}
}

func TestStreamClosedDuringRead(t *testing.T) {
	for i := 0; i < 25; i++ {
		ch := make(chan struct{})
		input := "some random text"
		errs := &errorReader{
			reads: [][]byte{
				[]byte("some random"),
				[]byte(" text"),
			},
			err:   fmt.Errorf("stuff"),
			pause: ch,
		}
		r := NewReader(errs, false)

		data, err := readWebSocket(r, t, func(c *websocket.Conn) {
			c.Close()
			close(ch)
		})
		// verify that the data returned by the server on an early close always has a specific error
		if err == nil || !strings.Contains(err.Error(), "use of closed network connection") {
			t.Fatal(err)
		}
		// verify that the data returned is a strict subset of the input
		if !bytes.HasPrefix([]byte(input), data) && len(data) != 0 {
			t.Fatalf("unexpected server read: %q", string(data))
		}
	}
}

type errorReader struct {
	reads        [][]byte
	err          error
	panicMessage string
	pause        chan struct{}
}

func (r *errorReader) Read(p []byte) (int, error) {
	if len(r.reads) == 0 {
		if r.pause != nil {
			<-r.pause
		}
		if len(r.panicMessage) != 0 {
			panic(r.panicMessage)
		}
		return 0, r.err
	}
	next := r.reads[0]
	r.reads = r.reads[1:]
	copy(p, next)
	return len(next), nil
}

func readWebSocket(r *Reader, t *testing.T, fn func(*websocket.Conn), protocols ...string) ([]byte, error) {
	errCh := make(chan error, 1)
	s, addr := newServer(func(ws *websocket.Conn) {
		cfg := ws.Config()
		cfg.Protocol = protocols
		go ignoreReceives(ws, 0)
		go func() {
			err := <-r.err
			errCh <- err
		}()
		r.handle(ws)
	})
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	client, err := websocket.DialConfig(config)
	if err != nil {
		return nil, err
	}
	defer client.Close()

	if fn != nil {
		fn(client)
	}

	data, err := ioutil.ReadAll(client)
	if err != nil {
		return data, err
	}
	return data, <-errCh
}

func expectWebSocketFrames(r *Reader, t *testing.T, fn func(*websocket.Conn), frames [][]byte, protocols ...string) error {
	errCh := make(chan error, 1)
	s, addr := newServer(func(ws *websocket.Conn) {
		cfg := ws.Config()
		cfg.Protocol = protocols
		go ignoreReceives(ws, 0)
		go func() {
			err := <-r.err
			errCh <- err
		}()
		r.handle(ws)
	})
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	ws, err := websocket.DialConfig(config)
	if err != nil {
		return err
	}
	defer ws.Close()

	if fn != nil {
		fn(ws)
	}

	for i := range frames {
		var data []byte
		if err := websocket.Message.Receive(ws, &data); err != nil {
			return err
		}
		if !reflect.DeepEqual(frames[i], data) {
			return fmt.Errorf("frame %d did not match expected: %v", data, err)
		}
	}
	var data []byte
	if err := websocket.Message.Receive(ws, &data); err != io.EOF {
		return fmt.Errorf("expected no more frames: %v (%v)", err, data)
	}
	return <-errCh
}


text:
<?php
// module/Blog/Module.php
namespace Blog;

use Blog\Model\Post;
use Blog\Model\Block;
use Blog\Model\Category;
use Blog\Model\PostTable;
use Blog\Model\BlockTable;
use Blog\Model\CategoryTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

use Zend\ModuleManager\ModuleManager;
// added for Acl  ###################################
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
// end: added for Acl   ###################################

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    	// added for Acl   ###################################
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $eventManager->attach('route', array($this, 'loadConfiguration'), 2);
        //you can attach other function need here...
    }

    public function loadConfiguration(MvcEvent $e)
    {
    $application   = $e->getApplication();
	$sm            = $application->getServiceManager();
	$sharedManager = $application->getEventManager()->getSharedManager();

    $router = $sm->get('router');
	$request = $sm->get('request');

	$matchedRoute = $router->match($request);
	if (null !== $matchedRoute) {
           $sharedManager->attach('Zend\Mvc\Controller\AbstractActionController','dispatch',
                function($e) use ($sm) {
		   $sm->get('ControllerPluginManager')->get('MyAclPlugin')
                      ->doAuthorization($e); //pass to the plugin...
	       },2
           );
        }
    }

	// end: added for Acl   ###################################
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
            // This event will only be fired when an ActionController under the MyModule namespace is dispatched.
            $controller = $e->getTarget();
            //$controller->layout('layout/zfcommons'); // points to module/Album/view/layout/album.phtml
        }, 100);
    }

    public function getServiceConfig()
    {
     return array(
         'initializers' => array(
             function ($instance, $sm) {
                 if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
                     $instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
                 }
             }
         ),
         'invokables' => array(
              'menu' => 'Blog\Model\MenuTable'
         ),

         'factories' => array(
             'myMenus' => 'Blog\Navigation\MyNavigationFactory',
             'Blog\Model\PostTable' =>  function($sm) {
                 $tableGateway = $sm->get('PostTableGateway');
                 $table = new PostTable($tableGateway);
                 return $table;
             },
             'PostTableGateway' => function ($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $resultSetPrototype = new ResultSet();
                 $resultSetPrototype->setArrayObjectPrototype(new Post());
                 return new TableGateway('tbl_post', $dbAdapter, null, $resultSetPrototype);
             },
             'Blog\Model\BlockTable' =>  function($sm) {
                 $tableGateway = $sm->get('BlockTableGateway');
                 $table = new BlockTable($tableGateway);
                 return $table;
             },
             'BlockTableGateway' => function ($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $resultSetPrototype = new ResultSet();
                 $resultSetPrototype->setArrayObjectPrototype(new Block());
                 return new TableGateway('tbl_block', $dbAdapter, null, $resultSetPrototype);
             },
             'Blog\Model\CategoryTable' =>  function($sm) {
                 $tableGateway = $sm->get('CategoryTableGateway');
                 $table = new CategoryTable($tableGateway);
                 return $table;
             },
             'CategoryTableGateway' => function ($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $resultSetPrototype = new ResultSet();
                 $resultSetPrototype->setArrayObjectPrototype(new Category());
                 return new TableGateway('tbl_category', $dbAdapter, null, $resultSetPrototype);
             },
             'Blog\Model\MyAuthStorage' => function ($sm) {
                return new \Blog\Model\MyAuthStorage('blog_ses');
             },
             'AuthService' => function ($sm) {
                $dbAdapter      = $sm->get('Zend\Db\Adapter\Adapter');
                        $dbTableAuthAdapter  = new DbTableAuthAdapter($dbAdapter, 'tbl_user','name','pass', 'MD5(?)');

                $authService = new AuthenticationService();
                $authService->setAdapter($dbTableAuthAdapter);
                $authService->setStorage($sm->get('Blog\Model\MyAuthStorage'));

                return $authService;
             },

         ),
     );
    }
}


text:
/* ==========================================================================
   Author's custom styles
   ========================================================================== */

.customTagBackground {
  background: #B4C8FF !important;
  color: #000 !important;
}

.ms-sel-text {
  background: #fff !important;
  color: #000 !important;
}


text:
/**
 * Exemplo de como um visitor funciona
 * @author mateus
 */

public class VisitorExample {

	interface ComputingVisitor {
		int visit(Expression e);
		int visit(PlusExpression e);
		int visit(MinusExpression e);
		int visit(IntegerTerminal e);
	}

	static abstract class Expression {
		abstract void accept(ComputingVisitor v);
	}

	static class PlusExpression extends Expression {
		Expression a;
		Expression b;

		public PlusExpression(Expression a, Expression b) {
			this.a = a; this.b = b;
		}

		void accept(ComputingVisitor v) {
			v.visit(this);
		}
	}

	static class MinusExpression extends Expression {
		Expression a;
		Expression b;

		public MinusExpression(Expression a, Expression b) {
			this.a = a; this.b = b;
		}

		void accept(ComputingVisitor v) {
			v.visit(this);
		}
	}

	static class IntegerTerminal extends Expression {
		int value;

		public IntegerTerminal(int value) {
			this.value = value;
		}

		void accept(ComputingVisitor v) {
			v.visit(this);
		}
	}

	static class ConcreteComputingVisitor implements ComputingVisitor {

		@Override
		public int visit(Expression e) {
			int ret;
			if(e instanceof PlusExpression) {
				ret = this.visit((PlusExpression) e);
			} else if (e instanceof MinusExpression) {
				ret = this.visit((MinusExpression) e);
			} else if (e instanceof IntegerTerminal) {
				ret = this.visit((IntegerTerminal) e);
			} else {
				throw new UnsupportedOperationException(e.getClass().toString());
			}

			return ret;
		}

		@Override
		public int visit(PlusExpression e) {
			int resultA = this.visit(e.a);
			int resultB = this.visit(e.b);
			return resultA + resultB;
		}

		@Override
		public int visit(MinusExpression e) {
			int resultA = this.visit(e.a);
			int resultB = this.visit(e.b);
			return resultA - resultB;
		}

		@Override
		public int visit(IntegerTerminal e) {
			return e.value;
		}

	}

	public static void main(String[] args) {
		//15 + 30
		Expression sum = new PlusExpression(new IntegerTerminal(15),
				new IntegerTerminal(30));
		//10 - 90
		Expression minus = new MinusExpression(new IntegerTerminal(10),
				new IntegerTerminal(90));
		//(15 + 30) + (10 - 90)
		Expression total = new PlusExpression(sum, minus);

		ComputingVisitor visitor = new ConcreteComputingVisitor();

		System.out.println(visitor.visit(total));
	}

	public int paraNoooooooooooooooooooosaAlegria() {
		return 0;
	}
}