text:
<?php

namespace gg\Bundle\DiscussionBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * gg\Bundle\DiscussionBundle\Entity\Comment
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="gg\Bundle\DiscussionBundle\Entity\CommentRepository")
 */
class Comment
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $content
     *
     * @ORM\Column(name="content", type="string", length=2048)
     */
    private $content;

    /**
     * @var string $authorpseudo
     *
     * @ORM\Column(name="authorpseudo", type="string", length=255)
     */
    private $authorpseudo;

    /**
     * @var string $authoremail
     *
     * @ORM\Column(name="authoremail", type="string", length=255)
     */
    private $authoremail;

    /**
     * @var date $datemod
     *
     * @ORM\Column(name="datemod", type="date")
     */
    private $datemod;

    /**
     * @var date $datecrea
     *
     * @ORM\Column(name="datecrea", type="date")
     */
    private $datecrea;

    /**
     * @ORM\ManyToOne(targetEntity="Discussion")
     * @ORM\JoinColumn(name="discussion_id", referencedColumnName="id")
     */
    private $discussion;

    function __construct(){
        $this->datecrea = new \DateTime();
        $this->datemod = new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set content
     *
     * @param string $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set authorpseudo
     *
     * @param string $authorpseudo
     */
    public function setAuthorpseudo($authorpseudo)
    {
        $this->authorpseudo = $authorpseudo;
    }

    /**
     * Get authorpseudo
     *
     * @return string
     */
    public function getAuthorpseudo()
    {
        return $this->authorpseudo;
    }

    /**
     * Set authoremail
     *
     * @param string $authoremail
     */
    public function setAuthoremail($authoremail)
    {
        $this->authoremail = $authoremail;
    }

    /**
     * Get authoremail
     *
     * @return string
     */
    public function getAuthoremail()
    {
        return $this->authoremail;
    }

    /**
     * Set datemod
     *
     * @param date $datemod
     */
    public function setDatemod($datemod)
    {
        $this->datemod = $datemod;
    }

    /**
     * Get datemod
     *
     * @return date
     */
    public function getDatemod()
    {
        return $this->datemod;
    }

    /**
     * Set datecrea
     *
     * @param date $datecrea
     */
    public function setDatecrea($datecrea)
    {
        $this->datecrea = $datecrea;
    }

    /**
     * Get datecrea
     *
     * @return date
     */
    public function getDatecrea()
    {
        return $this->datecrea;
    }

    /**
     * Set discussion
     *
     * @param gg\Bundle\DiscussionBundle\Entity\Discussion $discussion
     */
    public function setDiscussion(\gg\Bundle\DiscussionBundle\Entity\Discussion $discussion)
    {
        $this->discussion = $discussion;
    }

    /**
     * Get discussion
     *
     * @return gg\Bundle\DiscussionBundle\Entity\Discussion
     */
    public function getDiscussion()
    {
        return $this->discussion;
    }
}


text:
Astro.createValidator({
  name: 'choice',
  validate: function(fieldValue, fieldName, choices) {
    return _.contains(choices, fieldValue);
  },
  events: {
    validationerror: function(e) {
      var fieldName = e.data.fieldName;
      var choices = e.data.param;

      e.setMessage(
        'The value of the "' + fieldName +
        '" field has to be one of "' + choices.join('", "') + '"'
      );
    }
  }
});

redpajama_set_name: RedPajamaGithub


text:
package de.madcyph3r.example.example.menu;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import de.madcyph3r.example.example.FragmentDummy;
import de.madcyph3r.example.example.FragmentInstruction;
import de.madcyph3r.materialnavigationdrawer.MaterialNavigationDrawer;
import de.madcyph3r.materialnavigationdrawer.activity.MaterialNavNoHeaderActivity;
import de.madcyph3r.materialnavigationdrawer.menu.MaterialMenu;
import de.madcyph3r.materialnavigationdrawer.menu.item.section.MaterialItemSectionFragment;

public class SectionFragmentTitleActivity extends MaterialNavNoHeaderActivity {

    MaterialNavigationDrawer drawer = null;

    @Override
    protected boolean finishActivityOnNewIntent() {
        return false;
    }

    @Override
    protected int getNewIntentRequestCode(Class clazz) {
        return 0;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        drawer = this;

        // information text for the fragment
        Bundle bundle = new Bundle();
        bundle.putString("instruction", "Press on the section 'section title' and see the fragment title bar." +
                " It has another title.");

        Fragment fragmentInstruction = new FragmentInstruction();
        fragmentInstruction.setArguments(bundle);

        // create menu
        MaterialMenu menu = new MaterialMenu();
        menu.add(new MaterialItemSectionFragment(this, "Instruction", fragmentInstruction, "Section With Custom Fragment Title"));
        menu.add(new MaterialItemSectionFragment(this, "section title", new FragmentDummy(), "Fragment title 1"));

        // load menu
        this.loadMenu(menu);

        // load the MaterialItemSectionFragment, from the given startIndex
        this.loadStartFragmentFromMenu(menu);
    }

    @Override
    public void afterInit(Bundle savedInstanceState) {

    }
}


text:
using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.ApplicationInsights.Extensibility;

using System.Linq;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Channel;

namespace Microsoft.ApplicationInsights.Metrics.Extensibility
{
    /// <summary />
    [TestClass]
    public class AggregationPeriodSummaryTests
    {
        /// <summary />
        [TestMethod]
        public void Ctor()
        {
            {
                var period = new AggregationPeriodSummary(null, null);
                Assert.IsNotNull(period);
            }
        }

        /// <summary />
        [TestMethod]
        public void PersistentAggregates()
        {
            {
                MetricAggregate[] p = new MetricAggregate[0];
                var period = new AggregationPeriodSummary(p, null);

                Assert.IsNull(period.NonpersistentAggregates);

                Assert.IsNotNull(period.PersistentAggregates);
                Assert.AreSame(p, period.PersistentAggregates);
                Assert.AreEqual(0, period.PersistentAggregates.Count);
            }
            {
                MetricAggregate[] p = new MetricAggregate[] { new MetricAggregate("mns1", "mid1", "KindA"),
                                                              new MetricAggregate("mns2", "mid2", "KindB"),
                                                              new MetricAggregate("mns3", "mid3", "KindC") };
                var period = new AggregationPeriodSummary(p, null);

                Assert.IsNull(period.NonpersistentAggregates);

                Assert.IsNotNull(period.PersistentAggregates);
                Assert.AreSame(p, period.PersistentAggregates);
                Assert.AreEqual(3, period.PersistentAggregates.Count);

                Assert.AreEqual("mns1", period.PersistentAggregates[0].MetricNamespace);
                Assert.AreEqual("mid1", period.PersistentAggregates[0].MetricId);
                Assert.AreEqual("KindA", period.PersistentAggregates[0].AggregationKindMoniker);

                Assert.AreEqual("mns2", period.PersistentAggregates[1].MetricNamespace);
                Assert.AreEqual("mid2", period.PersistentAggregates[1].MetricId);
                Assert.AreEqual("KindB", period.PersistentAggregates[1].AggregationKindMoniker);

                Assert.AreEqual("mns3", period.PersistentAggregates[2].MetricNamespace);
                Assert.AreEqual("mid3", period.PersistentAggregates[2].MetricId);
                Assert.AreEqual("KindC", period.PersistentAggregates[2].AggregationKindMoniker);
            }
            {
                MetricAggregate[] np = new MetricAggregate[] { new MetricAggregate("MNS1", "mid1", "KindA"),
                                                               new MetricAggregate("MNS2", "mid2", "KindB"),
                                                               new MetricAggregate("MNS3", "mid3", "KindC") };
                var period = new AggregationPeriodSummary(null, np);

                Assert.IsNull(period.PersistentAggregates);

                Assert.IsNotNull(period.NonpersistentAggregates);
                Assert.AreSame(np, period.NonpersistentAggregates);
                Assert.AreEqual(3, period.NonpersistentAggregates.Count);

                Assert.AreEqual("MNS1", period.NonpersistentAggregates[0].MetricNamespace);
                Assert.AreEqual("mid1", period.NonpersistentAggregates[0].MetricId);
                Assert.AreEqual("KindA", period.NonpersistentAggregates[0].AggregationKindMoniker);

                Assert.AreEqual("MNS2", period.NonpersistentAggregates[1].MetricNamespace);
                Assert.AreEqual("mid2", period.NonpersistentAggregates[1].MetricId);
                Assert.AreEqual("KindB", period.NonpersistentAggregates[1].AggregationKindMoniker);

                Assert.AreEqual("MNS3", period.NonpersistentAggregates[2].MetricNamespace);
                Assert.AreEqual("mid3", period.NonpersistentAggregates[2].MetricId);
                Assert.AreEqual("KindC", period.NonpersistentAggregates[2].AggregationKindMoniker);
            }

        }
    }
}


text:
/*
 *  name         CSRF Grabber
 *  namespace    pxgamer
 *  version      0.2
 *  description  A library for getting the current csrf token for POSTs on Kickass Torrents.
 *  author       pxgamer
 */

function csrf() {
    'use strict';

    return $('form input[name="csrf_token"]').val();
}


text:
START_ATF_NAMESPACE
    #pragma pack(push, 1)
    struct  _uilock_update_request_wrac
    {
        unsigned __int16 wUserIndex;
        unsigned int dwAccountSerial;
        char uszUILockPW[13];
        char byHintIndex;
        char uszHintAnswer[17];
    };
    #pragma pack(pop)
END_ATF_NAMESPACE


text: Aegims::Application.config.session_store :cookie_store, key: '_aegims_session'


text:
<?php
// This is a simple class that sends send an email when posted to.
// Its main use is as a back-end for our popup email form

$to = 'support@timetom.com';

class MailPost {
  private $mailTo;
  private $timestamp;
  private $ip;
  private $host;

  private $mailFrom = '';
  private $subject = '';
  private $text = '';

  function MailPost($array, $mailTo) {
    $this->mailTo = $mailTo;
    $this->timestamp = date("F jS Y, h:iA.", time());
    $this->ip = $_SERVER['REMOTE_ADDR'];
    $this->host = gethostbyaddr($this->ip);

    if(isset($array['from']) && $array['from']) {
      $this->mailFrom = $array['from'];
    }
    if(isset($array['subject']) && $array['subject']) {
      $this->subject = $array['subject'];
    }
    if(isset($array['text']) && $array['text']) {
      $this->text = $array['text'];
    }
  }

  function send() {
    $body = "

$this->text

This mail was sent on $this->timestamp by $this->ip ($this->host)

    ";
    $headers = "From: $this->mailFrom \r\n";
    $headers .= "Reply-To: $this->mailFrom \r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $message = "$body";
    $result = array();
    // error_log("sending mail to $this->mailTo");
    if (mail($this->mailTo, $this->subject, $message, $headers)) {
      $result['status'] = 'success';
    } else {
      $error = error_get_last();
      $result['status'] = 'failure';
      $result['error'] = $error;
    }
    return $result;
  }
}

$mailPost = new MailPost($_POST, $to);
$result = $mailPost->send();
if(isset($_POST['then'])) {
  header('Location: '.$_POST['then']);
} else {
  echo(json_encode($result));
}
?>


text:
package com.achep.ringlocker.locker;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.widget.TextView;

import com.achep.ringlocker.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LockerActivity extends Activity {

    private TextView mTimeView;
    private TextView mDateView;

    private Calendar mCalendar;
    private ContentObserver mFormatChangeObserver;
    private boolean mAttached;

    /* called by system on minute ticks */
    private final Handler mHandler = new Handler();
    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                mCalendar = Calendar.getInstance();
            }
            // Post a runnable to avoid blocking the broadcast.
            mHandler.post(new Runnable() {
                public void run() {
                    updateClock();
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_locker);

        mTimeView = (TextView) findViewById(R.id.time);
        mDateView = (TextView) findViewById(R.id.date);

        final LockerSurfaceView lv = (LockerSurfaceView) findViewById(R.id.locker);
        lv.setOnUnlockListener(new LockerSurfaceView.OnUnlockListener() {
            @Override
            public void unlock() {
                finish();
            }

            @Override
            public void progress(float value) {
                float alpha = 1 - value * 2;
                if (alpha < 0) alpha = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    mTimeView.setAlpha(alpha);
                    mDateView.setAlpha(alpha);
                } else {
                    final int color = Color.argb((int) (255 * alpha), 255, 255, 255);
                    mTimeView.setTextColor(color);
                    mDateView.setTextColor(color);
                }
            }
        });

        mCalendar = Calendar.getInstance();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mAttached) {
            return;
        }
        mAttached = true;

		/* monitor time ticks, time changed, timezone */
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        registerReceiver(mIntentReceiver, filter);

		/* monitor 12/24-hour display preference */
        mFormatChangeObserver = new FormatChangeObserver();
        getContentResolver().registerContentObserver(
                Settings.System.CONTENT_URI, true, mFormatChangeObserver);

        updateClock();
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if (!mAttached)
            return;
        mAttached = false;

        unregisterReceiver(mIntentReceiver);
        getContentResolver().unregisterContentObserver(
                mFormatChangeObserver);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return true;
    }

    private class FormatChangeObserver extends ContentObserver {
        public FormatChangeObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(boolean selfChange) {
            updateClock();
        }
    }

    private void updateClock() {
        mCalendar.setTimeInMillis(System.currentTimeMillis());

        boolean hour24Mode = get24HourMode();
        int mins = mCalendar.get(Calendar.MINUTE);
        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);

        mTimeView.setText((hour > 12 && !hour24Mode ? hour - 12 : hour) + ":" + (mins > 9 ? mins : "0" + mins));
        mDateView.setText(new SimpleDateFormat("EEE, d MMMM").format(
                mCalendar.getTime()).toUpperCase());
    }

    private boolean get24HourMode() {
        return DateFormat.is24HourFormat(this);
    }

}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Javascript for ObjectFieldSet, a UI element for displaying the properties
 * of a given Javascript object. These properties are displayed in a fieldset
 * as a series of rows for each key-value pair.
 * Served from chrome://bluetooth-internals/.
 */

cr.define('object_fieldset', function() {

  /**
   * A fieldset that lists the properties of a given object. These properties
   * are displayed as a series of rows for each key-value pair.
   * Only the object's own properties are displayed. Boolean values are
   * displayed using images: a green check for 'true', and a red cancel 'x' for
   * 'false'. All other types are converted to their string representation for
   * display.
   * @constructor
   * @extends {HTMLFieldSetElement}
   */
  const ObjectFieldSet = cr.ui.define('fieldset');

  ObjectFieldSet.prototype = {
    __proto__: HTMLFieldSetElement.prototype,

    set showAll(showAll) {
      this.showAll_ = showAll;
    },

    get showAll() {
      return this.showAll_;
    },

    /**
     * Decorates the element as an ObjectFieldset.
     */
    decorate() {
      this.classList.add('object-fieldset');

      /** @type {?Object} */
      this.value = null;
      /** @private {?Object<string, string>} */
      this.nameMap_ = null;
      this.showAll_ = true;
    },

    /**
     * Sets the object data to be displayed in the fieldset.
     * @param {!Object} value
     */
    setObject(value) {
      this.value = value;
      this.redraw();
    },

    /**
     * Sets the object used to map property names to display names. If a display
     * name is not provided, the default property name will be used.
     * @param {!Object<string, string>} nameMap
     */
    setPropertyDisplayNames(nameMap) {
      this.nameMap_ = nameMap;
    },

    /**
     * Deletes and recreates the table structure with current object data.
     */
    redraw() {
      this.innerHTML = trustedTypes.emptyHTML;

      Object.keys(assert(this.value)).forEach(function(propName) {
        const value = this.value[propName];
        if (value === false && !this.showAll_) {
          return;
        }

        const name = this.nameMap_[propName] || propName;
        const newField = document.createElement('div');
        newField.classList.add('status');

        const nameDiv = document.createElement('div');
        nameDiv.textContent = name + ':';
        newField.appendChild(nameDiv);

        const valueDiv = document.createElement('div');
        valueDiv.dataset.field = propName;

        if (typeof(value) === 'boolean') {
          valueDiv.classList.add('toggle-status');
          valueDiv.classList.toggle('checked', value);
        } else {
          valueDiv.textContent = String(value);
        }

        newField.appendChild(valueDiv);
        this.appendChild(newField);
      }, this);
    },
  };

  return {
    ObjectFieldSet: ObjectFieldSet,
  };
});


text:
using System;
using System.Windows.Forms;
using SIL.WritingSystems;

namespace SIL.Windows.Forms.WritingSystems
{
	public partial class LanguageLookupDialog : Form
	{
		public LanguageLookupDialog()
		{
			InitializeComponent();
		}

		/// <summary>
		/// If you wouldn't be paying attention to their requested name, and are only going to look at the code, then
		/// set this to default so that they aren't fooled into thinking they can modify the name they'll see in your application.
		/// </summary>
		public bool IsDesiredLanguageNameFieldVisible
		{
			set { _languageLookupControl.IsDesiredLanguageNameFieldVisible = value; }
		}

		public bool IsShowRegionalDialectsCheckBoxVisible
		{
			set { _languageLookupControl.IsShowRegionalDialectsCheckBoxVisible = value; }
		}

		public Func<LanguageInfo, bool> MatchingLanguageFilter
		{
			set { _languageLookupControl.MatchingLanguageFilter = value; }
		}

		protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
		{
			_languageLookupControl.StopTimer();
			base.OnClosing(e);
		}

		private void _okButton_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.OK;
			Close();
		}

		public void LoadLanguages()
		{
			_languageLookupControl.LoadLanguages();
		}

		public LanguageInfo SelectedLanguage
		{
			get { return _languageLookupControl.SelectedLanguage; }
			set { _languageLookupControl.SelectedLanguage = value; }
		}

		public string DesiredLanguageName
		{
			get { return _languageLookupControl.DesiredLanguageName; }
		}

		public string SearchText
		{
			get { return _languageLookupControl.SearchText; }
			set { _languageLookupControl.SearchText = value; }
		}

		private void OnChooserDoubleClicked(object sender, EventArgs e)
		{
			_okButton_Click(sender, e);
		}

		private void _lookupLanguageControl_Changed(object sender, EventArgs e)
		{
			_okButton.Enabled = _languageLookupControl.HaveSufficientInformation;
		}

		private void _cancelButton_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;
			Close();
		}
	}
}


text:
A throw-away prototype to explore replacing these 3 frontend tool dependencies with a single package:

- [govuk_frontend_toolkit](https://github.com/alphagov/govuk_frontend_toolkit) - Generic tools and helpers for building GDS front-end apps
- [govuk_template](https://github.com/alphagov/govuk_template) - Packaging of a template containing the GOV.UK header and footer, and associated assets
- [govuk_elements](https://github.com/alphagov/govuk_elements) - SASS/assets for common GOV.UK Design Patterns

It's an exploration of combining the assets from those repos, and framework integration code (in this case rails) to expose it.

## Why is it inside another app?

- Speed of prototyping and simplicity of deploying
- A separate repo would require publishing/linking it to the host app
- As a single repo changes to the host app (an example frontend app) can be shown along side this repo, for better context
- If it gets big enough it can be split out into it's own repo/gem


text:
This page was generated with Wiki Builder. Do not change the format!

## Info

## Schema
* **Schema Type:** Enum
* **Type:** integer
* **Format:** byte

## Enum Values
Identifier | Value | Description
---------- | ----- | -----------
Trending | 0 |
Latest | 1 |
HighestRated | 2 |

## References
1. https://bungie-net.github.io/multi/schema_Forum-CommunityContentSortMode.html#schema_Forum-CommunityContentSortMode


text:
/**
 * Provides the base implementation of the Data API for entities.
 *
Data Base Entity

 * This package contains the base implementation of
 * {@link net.sf.mmm.data.api.entity Data API Entity}.
 */
package net.sf.mmm.data.base.entity;


text:
require('coffee-script/register');
module.exports = require('./src/pass-through-unless-blocked');


text:
@import libextobjc;
@import MAKVONotificationCenter;
@import SRGMediaPlayer;

@interface SimplePlayerViewController ()

@property (nonatomic) IBOutlet SRGMediaPlayerController *mediaPlayerController;     // top-level object, retained

@property (nonatomic) Media *media;

@property (nonatomic, weak) IBOutlet UIView *videoView;
@property (nonatomic, weak) IBOutlet SRGTimeSlider *timeSlider;
@property (nonatomic, weak) IBOutlet UIButton *liveButton;

@property (nonatomic, weak) id periodicTimeObserver;

@end

@implementation SimplePlayerViewController

#pragma mark Object lifecycle

- (instancetype)initWithMedia:(Media *)media
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:ResourceNameForUIClass(self.class) bundle:nil];
    SimplePlayerViewController *viewController = [storyboard instantiateInitialViewController];
    viewController.media = media;
    return viewController;
}

#pragma mark View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.liveButton setTitle:NSLocalizedString(@"Back to live", nil) forState:UIControlStateNormal];
    self.liveButton.alpha = 0.f;

    self.liveButton.layer.borderColor = UIColor.whiteColor.CGColor;
    self.liveButton.layer.borderWidth = 1.f;

    self.mediaPlayerController.view.viewMode = self.media.is360 ? SRGMediaPlayerViewModeMonoscopic : SRGMediaPlayerViewModeFlat;

    @weakify(self)
    [self.mediaPlayerController addObserver:self keyPath:@keypath(SRGMediaPlayerController.new, live) options:0 block:^(MAKVONotification *notification) {
        @strongify(self)
        [self updateLiveButton];
    }];
    [self updateLiveButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.movingToParentViewController || self.beingPresented) {
        [self.mediaPlayerController playURL:self.media.URL];
    }
}

#pragma mark Status bar

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

#pragma mark UI

- (void)updateLiveButton
{
    if (self.mediaPlayerController.streamType == SRGMediaPlayerStreamTypeDVR) {
        [UIView animateWithDuration:0.2 animations:^{
            self.liveButton.alpha = self.mediaPlayerController.live ? 0.f : 1.f;
        }];
    }
    else {
        self.liveButton.alpha = 0.f;
    }
}

#pragma mark Actions

- (IBAction)dismiss:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)goToLive:(id)sender
{
    [UIView animateWithDuration:0.2 animations:^{
        self.liveButton.alpha = 0.f;
    }];

    CMTimeRange timeRange = self.mediaPlayerController.timeRange;
    if (CMTIMERANGE_IS_INDEFINITE(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange)) {
        return;
    }

    [self.mediaPlayerController seekToPosition:[SRGPosition positionAroundTime:CMTimeRangeGetEnd(timeRange)] withCompletionHandler:nil];
}

@end


text:
package cst

import (
	"io"
)

// Fragment is a component of a cst that is backed by a token.
// This includes Nodes and all forms of space and comment.
type Fragment interface {
	// Tok returns the underlying token of this fragment.
	Tok() Token
	// Write is used to write the underlying token out to the writer.
	Write(io.Writer) error
}

// Separator is a list type to manage fragments that were skipped.
type Separator []Fragment

// Write is used to write the list of separators to the writer.
func (s Separator) Write(w io.Writer) error {
	for _, n := range s {
		if err := n.Write(w); err != nil {
			return err
		}
	}
	return nil
}


text:
package com.sun.tools.javac.parser;

import com.sun.tools.javac.parser.Tokens.*;
import com.sun.tools.javac.util.Position.LineMap;

/**
 * The lexical analyzer maps an input stream consisting of ASCII
 * characters and Unicode escapes into a token sequence.
 *
 *
This is NOT part of any supported API.
 * If you write code that depends on this, you do so at your own risk.
 * This code and its internal interfaces are subject to change or
 * deletion without notice.
 */
public interface Lexer {

    /**
     * Consume the next token.
     */
    void nextToken();

    /**
     * Return current token.
     */
    Token token();

    /**
     * Return token with given lookahead.
     */
    Token token(int lookahead);

    /**
     * Return the last character position of the previous token.
     */
    Token prevToken();

    /**
     * Splits the current token in two and return the first (splitted) token.
     * For instance {@literal '<<<'} is split into two tokens
     * {@literal '<'} and {@literal '<<'} respectively,
     * and the latter is returned.
     */
    Token split();

    /**
     * Return the position where a lexical error occurred;
     */
    int errPos();

    /**
     * Set the position where a lexical error occurred;
     */
    void errPos(int pos);

    /**
     * Build a map for translating between line numbers and
     * positions in the input.
     *
     * @return a LineMap
     */
    LineMap getLineMap();
}


text:
# FCXSafeCollections
支持使用pod:(pod 'FCXSafeCollections', '~> 0.2.0')
##解决NSArray、NSMutableArray、NSDictionary、NSMutableDictionary引起的闪退
使用了MethodSwizzle解决项目中经常遇到的数组越界、字典键值对为空操作等闪退问题,
在Debug模式会在控制台输出相应的错误原因,并且不会导致程序闪退
```objc
+ (void)load {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        //        NSArray
        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSArrayI") originalSelector:@selector(objectAtIndex:) swizzledMethod:@selector(fcx_safeObjectAtIndex:)];

        //        NSMutableArray
        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSArrayM") originalSelector:@selector(objectAtIndex:) swizzledMethod:@selector(fcx_safeObjectAtIndex:)];
        //        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSArrayM") originalSelector:@selector(addObject:) swizzledMethod:@selector(fcx_safeAddObject:)];
        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSArrayM") originalSelector:@selector(replaceObjectAtIndex:withObject:) swizzledMethod:@selector(fcx_safeReplaceObjectAtIndex:withObject:)];
        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSArrayM") originalSelector:@selector(insertObject:atIndex:) swizzledMethod:@selector(fcx_safeInsertObject:atIndex:)];

        //        NSDictionary
        //        [self swizzleClassMethodWithClass:[NSDictionary class] originalSelector:@selector(dictionaryWithObjects:forKeys:count:) swizzledMethod:@selector(fcx_safeDictionaryWithObjects:forKeys:count:)];

        //        NSMutableDictionary
        [self swizzleInstanceMethodWithClass:NSClassFromString(@"__NSDictionaryM") originalSelector:@selector(setObject:forKey:) swizzledMethod:@selector(fcx_safeSetObject:forKey:)];

    });
}

- (void)testSafe {
    //Array
    NSArray *array  = @[@1, @2];

    NSLog(@"index==== %@", array[2]);

    NSMutableArray *muArray = [[NSMutableArray alloc] initWithObjects:@"1", nil];
    NSLog(@"****");
    NSLog(@"=======muarray %@", muArray[2]);

    [muArray replaceObjectAtIndex:3 withObject:@""];
    [muArray replaceObjectAtIndex:0 withObject:nil];
    [muArray insertObject:@2 atIndex:2];

    //Dict
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"obj", @"key", nil];

    [muDict setObject:nil forKey:@"1"];
    [muDict setObject:@"1" forKey:nil];
}

```

##解决KeyValue引起的程序闪退
```objc
//当对一个非类对象属性设置nil时,就会执行setNilValueForKey:方法,setNilValueForKey:方法的默认实现,是产生一个NSInvalidArgumentException的异常,但是你可以重写这个方法.
- (void)setNilValueForKey:(NSString *)key {

    FCXSCLOG(@"[%@ %@]: could not set nil as the value for the key %@.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), key);
}

//如果没有对应的访问器方法(setter方法),如果接受者的类的+accessInstanceVariablesDirectly方法返回YES,那么就查找这个接受者的与key相匹配的实例变量(匹配模式为_<key>,_is<Key>,<key>,is<Key>):比如:key为age,只要属性存在_age,_isAge,age,isAge中的其中一个就认为匹配上了,如果找到这样的一个实例变量,并且的类型是一个对象指针类型,首先released对象上的旧值,然后把传入的新值retain后的传入的值赋值该成员变量,如果方法的参数类型是NSNumber或NSValue的对应的基本类型,先把它转换为基本数据类,再执行方法,传入转换后的数据.
//+ (BOOL)accessInstanceVariablesDirectly {
//    return YES;
//}

//对于数据模型中缺少的、不能与任何键配对的属性的时候,系统会自动调用setValue:forUndefinedKey:这个方法,该方法默认的实现会引发一个NSUndefinedKeyExceptiony异常,但是我们可以重写setValue:forUndefinedKey:方法让程序在运行过程中不引发任何异常信息且正常工作
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {

    FCXSCLOG(@"[%@ %@]: this class is not key value coding-compliant for the key %@.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), key);
}

//通过valueForKey获取对象属性值的方法时,如果代码中的key值不存在,系统会自动调用valueForUndefinedKey:这个方法,该方法默认的实现会引发一个NSUndefinedKeyExceptiony异常,但是我们可以重写valueForUndefinedKey:方法让程序在运行过程中不引发任何异常信息且正常工作
/**
 *  通过valueForKey获取对象属性值的方法时,如果代码中的key值不存在,系统会自动调用valueForUndefinedKey:这个方法,该方法默认的实现会引发一个NSUndefinedKeyExceptiony异常,但是我们可以重写valueForUndefinedKey:方法让程序在运行过程中不引发任何异常信息且正常工作
 *
 *  @return nil
 *
 *  @notice 虽然这步可以返回nil不闪退,但是后续操作依然可能有问题
 */
- (id)valueForUndefinedKey:(NSString *)key {

    FCXSCLOG(@"[%@ %@]: this class is not key value coding-compliant for the key %@.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), key);
    return nil;
}

- (void)testKeyValue {

    Person *xiaoming = [[Person alloc] init];
    [xiaoming setValue:@"xiaoming" forKey:@"name"];
    NSLog(@"name %@", xiaoming.name);
    [xiaoming setValue:nil forKey:@"name"];
    [xiaoming setValue:nil forKey:@"array"];
    //    [xiaoming setValue:nil forKey:@"person1"];
    [xiaoming setValue:@"aa" forKey:@"age"];
    //    [xiaoming setValue:nil forKey:@"age"];
    //    [xiaoming setNilValueForKey:@"age"];
    NSLog(@"name %@ age %ld", xiaoming.name, xiaoming.age);

    //    [xiaoming setValue:@"xiaoming" forKey:@"person1"];
    [xiaoming valueForKey:@"person1"];
    [xiaoming valueForKey:@"age1"];
}

```


text:
module Euchre {

    export class Game extends Phaser.Game {

        constructor() {

            super(800, 600, Phaser.AUTO, 'content', null);

            this.state.add('Boot', Boot, false);
            this.state.add('Preloader', Preloader, false);
            this.state.add('MainMenu', MainMenu, false);
            this.state.add('GameBoard', GameBoard, false);

            this.state.start('Boot');
        }
    }
}


text:
void nimbus_event_definition_init(nimbus_event_definition* self, struct tyran_symbol_table* symbol_table, const char* name,
								  u8t event_type_id, u8t unspawn_event_type_id)
{
	self->symbol_table = symbol_table;
	self->properties_count = 0;
	self->name = name;
	self->event_type_id = event_type_id;
	self->unspawn_event_type_id = unspawn_event_type_id;
	self->has_index = TYRAN_TRUE;
	self->is_module_to_script = TYRAN_FALSE;
	tyran_symbol_table_add(self->symbol_table, &self->type_symbol, name);
}

static nimbus_event_definition_property* add_property(nimbus_event_definition* self, const char* name,
													  nimbus_event_definition_type type)
{
	nimbus_event_definition_property* property = &self->properties[self->properties_count++];
	tyran_symbol_table_add(self->symbol_table, &property->symbol, name);
	property->type = type;

	return property;
}

void nimbus_event_definition_add_property(nimbus_event_definition* self, const char* name, nimbus_event_definition_type type)
{
	add_property(self, name, type);
}

nimbus_event_definition_property* nimbus_event_definition_add_property_ex(nimbus_event_definition* self, const char* name,
																		  nimbus_event_definition_type type)
{
	return add_property(self, name, type);
}

void nimbus_event_definition_add_property_array(nimbus_event_definition* self, const char* name,
												nimbus_event_definition_type type)
{
	nimbus_event_definition_property* property = add_property(self, name, type);
	property->is_array = TYRAN_TRUE;
}

void nimbus_event_definition_add_property_struct(nimbus_event_definition* self, const char* name,
												 nimbus_event_definition_type type, size_t offset)
{
	nimbus_event_definition_property* property = add_property(self, name, type);
	property->offset_in_struct = offset;
}


text:
StartTest(function(t) {

    t.expectPass(function(t) {
        t.$('body').append('

');

        t.elementIsEmpty('#div')

        t.waitForElementEmpty('#div', function() {
            t.pass('waitForElementEmpty')
        })

        t.$('#div')[0].innerHTML = "   ";
        t.elementIsEmpty('#div');

    })

    t.expectFail(function(t) {
        t.$('body').append('
a
');

        t.elementIsEmpty('#div2')
    })

    t.expectPass(function(t) {
        t.$('body').append('

asf

');
        t.elementIsNotEmpty('#div3', 'elementIsNotEmpty PASS');

        t.waitForElementNotEmpty('#div3', function() {
            t.pass('waitForElementNotEmpty')
        })

        t.isInView('#div3', 'isInView PASS');

        t.waitForScrollChange('#div3', 'left', function() {
            t.pass('waitForScrollChange PASS')
        });

        document.getElementById('div3').scrollLeft = 20;
    })

    t.expectFail(function(t) {
        t.waitForTimeout = 300;

        t.$('body').append('

');
        t.$('body').append('

');

//        t.isInView('#div5', 'isInView FAIL');

        t.elementIsNotEmpty('#div4', 'elementIsNotEmpty FAIL');

        t.waitForScrollChange('#div4', 'left', function() {
            t.pass('waitForScrollChange FAIL')
        })

    })
});


text:
package org.apache.spark.ui

import java.net.{URI, URL}
import javax.servlet.DispatcherType
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import scala.collection.mutable.ArrayBuffer
import scala.language.implicitConversions
import scala.xml.Node

import org.eclipse.jetty.client.api.Response
import org.eclipse.jetty.proxy.ProxyServlet
import org.eclipse.jetty.server.{HttpConnectionFactory, Request, Server, ServerConnector}
import org.eclipse.jetty.server.handler._
import org.eclipse.jetty.servlet._
import org.eclipse.jetty.servlets.gzip.GzipHandler
import org.eclipse.jetty.util.component.LifeCycle
import org.eclipse.jetty.util.thread.{QueuedThreadPool, ScheduledExecutorScheduler}
import org.json4s.JValue
import org.json4s.jackson.JsonMethods.{pretty, render}

import org.apache.spark.{SecurityManager, SparkConf, SSLOptions}
import org.apache.spark.internal.Logging
import org.apache.spark.util.Utils

/**
 * Utilities for launching a web server using Jetty's HTTP Server class
 */
private[spark] object JettyUtils extends Logging {

  // Base type for a function that returns something based on an HTTP request. Allows for
  // implicit conversion from many types of functions to jetty Handlers.
  type Responder[T] = HttpServletRequest => T

  class ServletParams[T <% AnyRef](val responder: Responder[T],
    val contentType: String,
    val extractFn: T => String = (in: Any) => in.toString) {}

  // Conversions from various types of Responder's to appropriate servlet parameters
  implicit def jsonResponderToServlet(responder: Responder[JValue]): ServletParams[JValue] =
    new ServletParams(responder, "text/json", (in: JValue) => pretty(render(in)))

  implicit def htmlResponderToServlet(responder: Responder[Seq[Node]]): ServletParams[Seq[Node]] =
    new ServletParams(responder, "text/html", (in: Seq[Node]) => "<!DOCTYPE html>" + in.toString)

  implicit def textResponderToServlet(responder: Responder[String]): ServletParams[String] =
    new ServletParams(responder, "text/plain")

  def createServlet[T <% AnyRef](
      servletParams: ServletParams[T],
      securityMgr: SecurityManager,
      conf: SparkConf): HttpServlet = {

    // SPARK-10589 avoid frame-related click-jacking vulnerability, using X-Frame-Options
    // (see http://tools.ietf.org/html/rfc7034). By default allow framing only from the
    // same origin, but allow framing for a specific named URI.
    // Example: spark.ui.allowFramingFrom = https://example.com/
    val allowFramingFrom = conf.getOption("spark.ui.allowFramingFrom")
    val xFrameOptionsValue =
      allowFramingFrom.map(uri => s"ALLOW-FROM $uri").getOrElse("SAMEORIGIN")

    new HttpServlet {
      override def doGet(request: HttpServletRequest, response: HttpServletResponse) {
        try {
          if (securityMgr.checkUIViewPermissions(request.getRemoteUser)) {
            response.setContentType("%s;charset=utf-8".format(servletParams.contentType))
            response.setStatus(HttpServletResponse.SC_OK)
            val result = servletParams.responder(request)
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate")
            response.setHeader("X-Frame-Options", xFrameOptionsValue)
            response.getWriter.print(servletParams.extractFn(result))
          } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED)
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate")
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
              "User is not authorized to access this page.")
          }
        } catch {
          case e: IllegalArgumentException =>
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage)
          case e: Exception =>
            logWarning(s"GET ${request.getRequestURI} failed: $e", e)
            throw e
        }
      }
      // SPARK-5983 ensure TRACE is not supported
      protected override def doTrace(req: HttpServletRequest, res: HttpServletResponse): Unit = {
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED)
      }
    }
  }

  /** Create a context handler that responds to a request with the given path prefix */
  def createServletHandler[T <% AnyRef](
      path: String,
      servletParams: ServletParams[T],
      securityMgr: SecurityManager,
      conf: SparkConf,
      basePath: String = ""): ServletContextHandler = {
    createServletHandler(path, createServlet(servletParams, securityMgr, conf), basePath)
  }

  /** Create a context handler that responds to a request with the given path prefix */
  def createServletHandler(
      path: String,
      servlet: HttpServlet,
      basePath: String): ServletContextHandler = {
    val prefixedPath = if (basePath == "" && path == "/") {
      path
    } else {
      (basePath + path).stripSuffix("/")
    }
    val contextHandler = new ServletContextHandler
    val holder = new ServletHolder(servlet)
    contextHandler.setContextPath(prefixedPath)
    contextHandler.addServlet(holder, "/")
    contextHandler
  }

  /** Create a handler that always redirects the user to the given path */
  def createRedirectHandler(
      srcPath: String,
      destPath: String,
      beforeRedirect: HttpServletRequest => Unit = x => (),
      basePath: String = "",
      httpMethods: Set[String] = Set("GET")): ServletContextHandler = {
    val prefixedDestPath = basePath + destPath
    val servlet = new HttpServlet {
      override def doGet(request: HttpServletRequest, response: HttpServletResponse): Unit = {
        if (httpMethods.contains("GET")) {
          doRequest(request, response)
        } else {
          response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED)
        }
      }
      override def doPost(request: HttpServletRequest, response: HttpServletResponse): Unit = {
        if (httpMethods.contains("POST")) {
          doRequest(request, response)
        } else {
          response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED)
        }
      }
      private def doRequest(request: HttpServletRequest, response: HttpServletResponse): Unit = {
        beforeRedirect(request)
        // Make sure we don't end up with "//" in the middle
        val newUrl = new URL(new URL(request.getRequestURL.toString), prefixedDestPath).toString
        response.sendRedirect(newUrl)
      }
      // SPARK-5983 ensure TRACE is not supported
      protected override def doTrace(req: HttpServletRequest, res: HttpServletResponse): Unit = {
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED)
      }
    }
    createServletHandler(srcPath, servlet, basePath)
  }

  /** Create a handler for serving files from a static directory */
  def createStaticHandler(resourceBase: String, path: String): ServletContextHandler = {
    val contextHandler = new ServletContextHandler
    contextHandler.setInitParameter("org.eclipse.jetty.servlet.Default.gzip", "false")
    val staticHandler = new DefaultServlet
    val holder = new ServletHolder(staticHandler)
    Option(Utils.getSparkClassLoader.getResource(resourceBase)) match {
      case Some(res) =>
        holder.setInitParameter("resourceBase", res.toString)
      case None =>
        throw new Exception("Could not find resource path for Web UI: " + resourceBase)
    }
    contextHandler.setContextPath(path)
    contextHandler.addServlet(holder, "/")
    contextHandler
  }

  /** Create a handler for proxying request to Workers and Application Drivers */
  def createProxyHandler(
      prefix: String,
      target: String): ServletContextHandler = {
    val servlet = new ProxyServlet {
      override def rewriteTarget(request: HttpServletRequest): String = {
        val rewrittenURI = createProxyURI(
          prefix, target, request.getRequestURI(), request.getQueryString())
        if (rewrittenURI == null) {
          return null
        }
        if (!validateDestination(rewrittenURI.getHost(), rewrittenURI.getPort())) {
          return null
        }
        rewrittenURI.toString()
      }

      override def filterServerResponseHeader(
          clientRequest: HttpServletRequest,
          serverResponse: Response,
          headerName: String,
          headerValue: String): String = {
        if (headerName.equalsIgnoreCase("location")) {
          val newHeader = createProxyLocationHeader(
            prefix, headerValue, clientRequest, serverResponse.getRequest().getURI())
          if (newHeader != null) {
            return newHeader
          }
        }
        super.filterServerResponseHeader(
          clientRequest, serverResponse, headerName, headerValue)
      }
    }

    val contextHandler = new ServletContextHandler
    val holder = new ServletHolder(servlet)
    contextHandler.setContextPath(prefix)
    contextHandler.addServlet(holder, "/")
    contextHandler
  }

  /** Add filters, if any, to the given list of ServletContextHandlers */
  def addFilters(handlers: Seq[ServletContextHandler], conf: SparkConf) {
    val filters: Array[String] = conf.get("spark.ui.filters", "").split(',').map(_.trim())
    filters.foreach {
      case filter : String =>
        if (!filter.isEmpty) {
          logInfo("Adding filter: " + filter)
          val holder : FilterHolder = new FilterHolder()
          holder.setClassName(filter)
          // Get any parameters for each filter
          conf.get("spark." + filter + ".params", "").split(',').map(_.trim()).toSet.foreach {
            param: String =>
              if (!param.isEmpty) {
                val parts = param.split("=")
                if (parts.length == 2) holder.setInitParameter(parts(0), parts(1))
             }
          }

          val prefix = s"spark.$filter.param."
          conf.getAll
            .filter { case (k, v) => k.length() > prefix.length() && k.startsWith(prefix) }
            .foreach { case (k, v) => holder.setInitParameter(k.substring(prefix.length()), v) }

          val enumDispatcher = java.util.EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR,
            DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST)
          handlers.foreach { case(handler) => handler.addFilter(holder, "/*", enumDispatcher) }
        }
    }
  }

  /**
   * Attempt to start a Jetty server bound to the supplied hostName:port using the given
   * context handlers.
   *
   * If the desired port number is contended, continues incrementing ports until a free port is
   * found. Return the jetty Server object, the chosen port, and a mutable collection of handlers.
   */
  def startJettyServer(
      hostName: String,
      port: Int,
      sslOptions: SSLOptions,
      handlers: Seq[ServletContextHandler],
      conf: SparkConf,
      serverName: String = ""): ServerInfo = {

    val collection = new ContextHandlerCollection
    addFilters(handlers, conf)

    val gzipHandlers = handlers.map { h =>
      val gzipHandler = new GzipHandler
      gzipHandler.setHandler(h)
      gzipHandler
    }

    // Bind to the given port, or throw a java.net.BindException if the port is occupied
    def connect(currentPort: Int): (Server, Int) = {
      val pool = new QueuedThreadPool
      if (serverName.nonEmpty) {
        pool.setName(serverName)
      }
      pool.setDaemon(true)

      val server = new Server(pool)
      val connectors = new ArrayBuffer[ServerConnector]
      // Create a connector on port currentPort to listen for HTTP requests
      val httpConnector = new ServerConnector(
        server,
        null,
        // Call this full constructor to set this, which forces daemon threads:
        new ScheduledExecutorScheduler(s"$serverName-JettyScheduler", true),
        null,
        -1,
        -1,
        new HttpConnectionFactory())
      httpConnector.setPort(currentPort)
      connectors += httpConnector

      sslOptions.createJettySslContextFactory().foreach { factory =>
        // If the new port wraps around, do not try a privileged port.
        val securePort =
          if (currentPort != 0) {
            (currentPort + 400 - 1024) % (65536 - 1024) + 1024
          } else {
            0
          }
        val scheme = "https"
        // Create a connector on port securePort to listen for HTTPS requests
        val connector = new ServerConnector(server, factory)
        connector.setPort(securePort)

        connectors += connector

        // redirect the HTTP requests to HTTPS port
        collection.addHandler(createRedirectHttpsHandler(securePort, scheme))
      }

      gzipHandlers.foreach(collection.addHandler)
      // As each acceptor and each selector will use one thread, the number of threads should at
      // least be the number of acceptors and selectors plus 1. (See SPARK-13776)
      var minThreads = 1
      connectors.foreach { connector =>
        // Currently we only use "SelectChannelConnector"
        // Limit the max acceptor number to 8 so that we don't waste a lot of threads
        connector.setAcceptQueueSize(math.min(connector.getAcceptors, 8))
        connector.setHost(hostName)
        // The number of selectors always equals to the number of acceptors
        minThreads += connector.getAcceptors * 2
      }
      server.setConnectors(connectors.toArray)
      pool.setMaxThreads(math.max(pool.getMaxThreads, minThreads))

      val errorHandler = new ErrorHandler()
      errorHandler.setShowStacks(true)
      errorHandler.setServer(server)
      server.addBean(errorHandler)
      server.setHandler(collection)
      try {
        server.start()
        (server, httpConnector.getLocalPort)
      } catch {
        case e: Exception =>
          server.stop()
          pool.stop()
          throw e
      }
    }

    val (server, boundPort) = Utils.startServiceOnPort[Server](port, connect, conf, serverName)
    ServerInfo(server, boundPort, collection)
  }

  private def createRedirectHttpsHandler(securePort: Int, scheme: String): ContextHandler = {
    val redirectHandler: ContextHandler = new ContextHandler
    redirectHandler.setContextPath("/")
    redirectHandler.setHandler(new AbstractHandler {
      override def handle(
          target: String,
          baseRequest: Request,
          request: HttpServletRequest,
          response: HttpServletResponse): Unit = {
        if (baseRequest.isSecure) {
          return
        }
        val httpsURI = createRedirectURI(scheme, baseRequest.getServerName, securePort,
          baseRequest.getRequestURI, baseRequest.getQueryString)
        response.setContentLength(0)
        response.encodeRedirectURL(httpsURI)
        response.sendRedirect(httpsURI)
        baseRequest.setHandled(true)
      }
    })
    redirectHandler
  }

  def createProxyURI(prefix: String, target: String, path: String, query: String): URI = {
    if (!path.startsWith(prefix)) {
      return null
    }

    val uri = new StringBuilder(target)
    val rest = path.substring(prefix.length())

    if (!rest.isEmpty()) {
      if (!rest.startsWith("/")) {
        uri.append("/")
      }
      uri.append(rest)
    }

    val rewrittenURI = URI.create(uri.toString())
    if (query != null) {
      return new URI(
          rewrittenURI.getScheme(),
          rewrittenURI.getAuthority(),
          rewrittenURI.getPath(),
          query,
          rewrittenURI.getFragment()
        ).normalize()
    }
    rewrittenURI.normalize()
  }

  def createProxyLocationHeader(
      prefix: String,
      headerValue: String,
      clientRequest: HttpServletRequest,
      targetUri: URI): String = {
    val toReplace = targetUri.getScheme() + "://" + targetUri.getAuthority()
    if (headerValue.startsWith(toReplace)) {
      clientRequest.getScheme() + "://" + clientRequest.getHeader("host") +
          prefix + headerValue.substring(toReplace.length())
    } else {
      null
    }
  }

  // Create a new URI from the arguments, handling IPv6 host encoding and default ports.
  private def createRedirectURI(
      scheme: String, server: String, port: Int, path: String, query: String) = {
    val redirectServer = if (server.contains(":") && !server.startsWith("[")) {
      s"[${server}]"
    } else {
      server
    }
    val authority = s"$redirectServer:$port"
    new URI(scheme, authority, path, query, null).toString
  }

}

private[spark] case class ServerInfo(
    server: Server,
    boundPort: Int,
    rootHandler: ContextHandlerCollection) {

  def stop(): Unit = {
    server.stop()
    // Stop the ThreadPool if it supports stop() method (through LifeCycle).
    // It is needed because stopping the Server won't stop the ThreadPool it uses.
    val threadPool = server.getThreadPool
    if (threadPool != null && threadPool.isInstanceOf[LifeCycle]) {
      threadPool.asInstanceOf[LifeCycle].stop
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>CustomTag-00-HolaMundo</display-name>
</web-app>


text:
from flask.ext.flails import FlailsView
from flask import render_template, redirect, url_for, request
#from config import db
import models
import forms

class AppView(FlailsView):
    def app_index(self):
        object_list = models.Post.query.all()
        return render_template('post/index.slim', object_list=object_list)

    def app_show(self, ident):
        post = models.Post.query.get(ident)
        form = forms.CommentForm()
        return render_template('post/show.slim', post=post, form=form)

    def app_new(self):
        form = forms.PostForm()
        if form.validate_on_submit():
            post = models.Post(form.name.data, form.title.data, form.content.data)
            #db.session.add(post)
            #db.session.commit()
            return redirect(url_for('post.index'))
        return render_template('post/new.slim', form=form)

    def app_edit(self, ident):
        post = models.Post.query.get(ident)
        form = forms.PostForm(request.form, post)
        if form.validate_on_submit():
            post.name = form.name.data
            post.title = form.title.data
            post.content = form.content.data
            #db.session.add(post)
            #db.session.commit()
            return redirect(url_for('post.show', ident=ident))
        return render_template('post/edit.slim', form=form, post=post)

    def app_delete(self, ident):
        post = models.Post.query.get(ident)
        db.session.delete(post)
        db.session.commit()
        return redirect(url_for('post.index'))

    def app_comment_new(self, post_id):
        post = models.Post.query.get(post_id)
        form = forms.CommentForm()
        if form.validate_on_submit():
            comment = models.Comment(form.commenter.data, form.body.data, post_id)
            #db.session.add(comment)
            #db.session.commit()
            return redirect(url_for('.show', ident=post_id))
        return render_template('post/show.slim', post=post, form=form)

    def app_comment_delete(self, post_id, ident):
        comment = models.Comment.query.get(ident)
        #db.session.delete(comment)
        #db.session.commit()
        return redirect(url_for('.show', ident=post_id))


text:
[@cspell/cspell-types](../README.md) / [Exports](../modules.md) / ReportingConfiguration

# Interface: ReportingConfiguration

## Hierarchy

- [`SuggestionsConfiguration`](SuggestionsConfiguration.md)

  ↳ **`ReportingConfiguration`**

  ↳↳ [`Settings`](Settings.md)

## Table of contents

### Properties

- [maxDuplicateProblems](ReportingConfiguration.md#maxduplicateproblems)
- [maxNumberOfProblems](ReportingConfiguration.md#maxnumberofproblems)
- [minWordLength](ReportingConfiguration.md#minwordlength)
- [numSuggestions](ReportingConfiguration.md#numsuggestions)
- [suggestionNumChanges](ReportingConfiguration.md#suggestionnumchanges)
- [suggestionsTimeout](ReportingConfiguration.md#suggestionstimeout)

## Properties

### maxDuplicateProblems

• `Optional` **maxDuplicateProblems**: `number`

The maximum number of times the same word can be flagged as an error in a file.

**`default`** 5

#### Defined in

[CSpellSettingsDef.ts:155](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L155)

___

### maxNumberOfProblems

• `Optional` **maxNumberOfProblems**: `number`

The maximum number of problems to report in a file.

**`default`** 100

#### Defined in

[CSpellSettingsDef.ts:149](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L149)

___

### minWordLength

• `Optional` **minWordLength**: `number`

The minimum length of a word before checking it against a dictionary.

**`default`** 4

#### Defined in

[CSpellSettingsDef.ts:161](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L161)

___

### numSuggestions

• `Optional` **numSuggestions**: `number`

Number of suggestions to make

**`default`** 10

#### Inherited from

[SuggestionsConfiguration](SuggestionsConfiguration.md).[numSuggestions](SuggestionsConfiguration.md#numsuggestions)

#### Defined in

[CSpellSettingsDef.ts:169](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L169)

___

### suggestionNumChanges

• `Optional` **suggestionNumChanges**: `number`

The maximum number of changes allowed on a word to be considered a suggestions.

For example, appending an `s` onto `example` -> `examples` is considered 1 change.

Range: between 1 and 5.

**`default`** 3

#### Inherited from

[SuggestionsConfiguration](SuggestionsConfiguration.md).[suggestionNumChanges](SuggestionsConfiguration.md#suggestionnumchanges)

#### Defined in

[CSpellSettingsDef.ts:185](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L185)

___

### suggestionsTimeout

• `Optional` **suggestionsTimeout**: `number`

The maximum amount of time in milliseconds to generate suggestions for a word.

**`default`** 500

#### Inherited from

[SuggestionsConfiguration](SuggestionsConfiguration.md).[suggestionsTimeout](SuggestionsConfiguration.md#suggestionstimeout)

#### Defined in

[CSpellSettingsDef.ts:175](https://github.com/streetsidesoftware/cspell/blob/34586d56/packages/cspell-types/src/CSpellSettingsDef.ts#L175)


text:
package org.jboss.pnc.integration_new.endpoint.notifications;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import java.util.function.Consumer;

@ClientEndpoint
public class UpdatesMessageHandler {

    private Logger logger = LoggerFactory.getLogger(UpdatesMessageHandler.class);

    private Consumer<String> onMessage;

    public UpdatesMessageHandler(Consumer<String> onMessage) {
        this.onMessage = onMessage;
    }

    @OnMessage
    public void onMessage(String message) {
        logger.debug("Received notification {}.", message);
        onMessage.accept(message);
    }

}


text:
<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

/**
 * 使用者
 *
 * @property-read int id
 * @property string name
 * @property string email
 * @property string confirm_code
 * @property \Carbon\Carbon|null confirm_at
 * @property bool isConfirmed
 * @property \Carbon\Carbon|null register_at
 * @property string register_ip
 * @property \Carbon\Carbon|null last_login_at
 * @property string last_login_ip
 *
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Role[] roles
 *
 * @property \Carbon\Carbon|null created_at
 * @property \Carbon\Carbon|null updated_at
 * @mixin \Eloquent
 */
class User extends Authenticatable
{
    use EntrustUserTrait;

    /** @var array $fillable 可大量指派的屬性 */
    protected $fillable = [
        'name',
        'email',
        'password',
        'confirm_code',
        'confirm_at',
        'register_at',
        'register_ip',
        'last_login_at',
        'last_login_ip',
    ];

    /** @var array $hidden 於JSON隱藏的屬性 */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /** @var array $dates 自動轉換為Carbon的屬性 */
    protected $dates = ['confirm_at', 'register_at', 'last_login_at'];

    /** @var int $perPage 分頁時的每頁數量 */
    protected $perPage = 20;

    /**
     * 帳號是否完成驗證
     *
     * @return bool
     */
    public function getIsConfirmedAttribute()
    {
        return !empty($this->confirm_at);
    }
}


text:
	<title>Leszek Kolakowski's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Leszek Kolakowski's panel show appearances

Leszek Kolakowski (born 1927-10-23[ref]) has appeared in 1 episodes between 1999-1999.  Leszek Kolakowski on Wikipedia.

1999

1999-04-01 / In Our Time


text:
/*	$NetBSD: fish.c,v 1.22 2011/09/01 07:18:50 plunky Exp $	*/

/*-
 * Copyright (c) 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Muffy Barkocy.
 *
 * 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 distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1990, 1993\
 The Regents of the University of California.  All rights reserved.");
#endif /* not lint */

#ifndef lint
#if 0
static char sccsid[] = "@(#)fish.c	8.1 (Berkeley) 5/31/93";
#else
__RCSID("$NetBSD: fish.c,v 1.22 2011/09/01 07:18:50 plunky Exp $");
#endif
#endif /* not lint */

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <err.h>
#include "pathnames.h"

#define	RANKS		13
#define	HANDSIZE	7
#define	CARDS		4
#define	TOTCARDS	RANKS * CARDS

#define	USER		1
#define	COMPUTER	0
#define	OTHER(a)	(1 - (a))

static const char *const cards[] = {
	"A", "2", "3", "4", "5", "6", "7",
	"8", "9", "10", "J", "Q", "K", NULL,
};
#define	PRC(card)	(void)printf(" %s", cards[card])

static int promode;
static int asked[RANKS], comphand[RANKS], deck[TOTCARDS];
static int userasked[RANKS], userhand[RANKS];
static int curcard = TOTCARDS;

static void chkwinner(int, const int *);
static int compmove(void);
static int countbooks(const int *);
static int countcards(const int *);
static int drawcard(int, int *);
static int gofish(int, int, int *);
static void goodmove(int, int, int *, int *);
static void init(void);
static void instructions(void);
static int nrandom(int);
static void printhand(const int *);
static void printplayer(int);
static int promove(void);
static void usage(void) __dead;
static int usermove(void);

int
main(int argc, char **argv)
{
	int ch, move;

	/* Revoke setgid privileges */
	setgid(getgid());

	while ((ch = getopt(argc, argv, "p")) != -1)
		switch(ch) {
		case 'p':
			promode = 1;
			break;
		case '?':
		default:
			usage();
		}

	srandom(time(NULL));
	instructions();
	init();

	if (nrandom(2) == 1) {
		printplayer(COMPUTER);
		(void)printf("get to start.\n");
		goto istart;
	}
	printplayer(USER);
	(void)printf("get to start.\n");

	for (;;) {
		move = usermove();
		if (!comphand[move]) {
			if (gofish(move, USER, userhand))
				continue;
		} else {
			goodmove(USER, move, userhand, comphand);
			continue;
		}

istart:		for (;;) {
			move = compmove();
			if (!userhand[move]) {
				if (!gofish(move, COMPUTER, comphand))
					break;
			} else
				goodmove(COMPUTER, move, comphand, userhand);
		}
	}
	/* NOTREACHED */
}

static int
usermove(void)
{
	int n;
	const char *const *p;
	char buf[256];

	(void)printf("\nYour hand is:");
	printhand(userhand);

	for (;;) {
		(void)printf("You ask me for: ");
		(void)fflush(stdout);
		if (fgets(buf, sizeof(buf), stdin) == NULL)
			exit(0);
		if (buf[0] == '\0')
			continue;
		if (buf[0] == '\n') {
			(void)printf("%d cards in my hand, %d in the pool.\n",
			    countcards(comphand), curcard);
			(void)printf("My books:");
			(void)countbooks(comphand);
			continue;
		}
		buf[strlen(buf) - 1] = '\0';
		if (!strcasecmp(buf, "p") && !promode) {
			promode = 1;
			(void)printf("Entering pro mode.\n");
			continue;
		}
		if (!strcasecmp(buf, "quit"))
			exit(0);
		for (p = cards; *p; ++p)
			if (!strcasecmp(*p, buf))
				break;
		if (!*p) {
			(void)printf("I don't understand!\n");
			continue;
		}
		n = p - cards;
		if (userhand[n]) {
			userasked[n] = 1;
			return(n);
		}
		if (nrandom(3) == 1)
			(void)printf("You don't have any of those!\n");
		else
			(void)printf("You don't have any %s's!\n", cards[n]);
		if (nrandom(4) == 1)
			(void)printf("No cheating!\n");
		(void)printf("Guess again.\n");
	}
	/* NOTREACHED */
}

static int
compmove(void)
{
	static int lmove;

	if (promode)
		lmove = promove();
	else {
		do {
			lmove = (lmove + 1) % RANKS;
		} while (!comphand[lmove] || comphand[lmove] == CARDS);
	}
	asked[lmove] = 1;

	(void)printf("I ask you for: %s.\n", cards[lmove]);
	return(lmove);
}

static int
promove(void)
{
	int i, max;

	for (i = 0; i < RANKS; ++i)
		if (userasked[i] &&
		    comphand[i] > 0 && comphand[i] < CARDS) {
			userasked[i] = 0;
			return(i);
		}
	if (nrandom(3) == 1) {
		for (i = 0;; ++i)
			if (comphand[i] && comphand[i] != CARDS) {
				max = i;
				break;
			}
		while (++i < RANKS)
			if (comphand[i] != CARDS &&
			    comphand[i] > comphand[max])
				max = i;
		return(max);
	}
	if (nrandom(1024) == 0723) {
		for (i = 0; i < RANKS; ++i)
			if (userhand[i] && comphand[i])
				return(i);
	}
	for (;;) {
		for (i = 0; i < RANKS; ++i)
			if (comphand[i] && comphand[i] != CARDS &&
			    !asked[i])
				return(i);
		for (i = 0; i < RANKS; ++i)
			asked[i] = 0;
	}
	/* NOTREACHED */
}

static int
drawcard(int player, int *hand)
{
	int card;

	++hand[card = deck[--curcard]];
	if (player == USER || hand[card] == CARDS) {
		printplayer(player);
		(void)printf("drew %s", cards[card]);
		if (hand[card] == CARDS) {
			(void)printf(" and made a book of %s's!\n",
			     cards[card]);
			chkwinner(player, hand);
		} else
			(void)printf(".\n");
	}
	return(card);
}

static int
gofish(int askedfor, int player, int *hand)
{
	printplayer(OTHER(player));
	(void)printf("say \"GO FISH!\"\n");
	if (askedfor == drawcard(player, hand)) {
		printplayer(player);
		(void)printf("drew the guess!\n");
		printplayer(player);
		(void)printf("get to ask again!\n");
		return(1);
	}
	return(0);
}

static void
goodmove(int player, int move, int *hand, int *opphand)
{
	printplayer(OTHER(player));
	(void)printf("have %d %s%s.\n",
	    opphand[move], cards[move], opphand[move] == 1 ? "": "'s");

	hand[move] += opphand[move];
	opphand[move] = 0;

	if (hand[move] == CARDS) {
		printplayer(player);
		(void)printf("made a book of %s's!\n", cards[move]);
		chkwinner(player, hand);
	}

	chkwinner(OTHER(player), opphand);

	printplayer(player);
	(void)printf("get another guess!\n");
}

static void
chkwinner(int player, const int *hand)
{
	int cb, i, ub;

	for (i = 0; i < RANKS; ++i)
		if (hand[i] > 0 && hand[i] < CARDS)
			return;
	printplayer(player);
	(void)printf("don't have any more cards!\n");
	(void)printf("My books:");
	cb = countbooks(comphand);
	(void)printf("Your books:");
	ub = countbooks(userhand);
	(void)printf("\nI have %d, you have %d.\n", cb, ub);
	if (ub > cb) {
		(void)printf("\nYou win!!!\n");
		if (nrandom(1024) == 0723)
			(void)printf("Cheater, cheater, pumpkin eater!\n");
	} else if (cb > ub) {
		(void)printf("\nI win!!!\n");
		if (nrandom(1024) == 0723)
			(void)printf("Hah!  Stupid peasant!\n");
	} else
		(void)printf("\nTie!\n");
	exit(0);
}

static void
printplayer(int player)
{
	switch (player) {
	case COMPUTER:
		(void)printf("I ");
		break;
	case USER:
		(void)printf("You ");
		break;
	}
}

static void
printhand(const int *hand)
{
	int book, i, j;

	for (book = i = 0; i < RANKS; i++)
		if (hand[i] < CARDS)
			for (j = hand[i]; --j >= 0;)
				PRC(i);
		else
			++book;
	if (book) {
		(void)printf(" + Book%s of", book > 1 ? "s" : "");
		for (i = 0; i < RANKS; i++)
			if (hand[i] == CARDS)
				PRC(i);
	}
	(void)putchar('\n');
}

static int
countcards(const int *hand)
{
	int i, count;

	for (count = i = 0; i < RANKS; i++)
		count += *hand++;
	return(count);
}

static int
countbooks(const int *hand)
{
	int i, count;

	for (count = i = 0; i < RANKS; i++)
		if (hand[i] == CARDS) {
			++count;
			PRC(i);
		}
	if (!count)
		(void)printf(" none");
	(void)putchar('\n');
	return(count);
}

static void
init(void)
{
	int i, j, temp;

	for (i = 0; i < TOTCARDS; ++i)
		deck[i] = i % RANKS;
	for (i = 0; i < TOTCARDS - 1; ++i) {
		j = nrandom(TOTCARDS-i);
		if (j == 0)
			continue;
		temp = deck[i];
		deck[i] = deck[i+j];
		deck[i+j] = temp;
	}
	for (i = 0; i < HANDSIZE; ++i) {
		++userhand[deck[--curcard]];
		++comphand[deck[--curcard]];
	}
}

static int
nrandom(int n)
{

	return((int)random() % n);
}

static void
instructions(void)
{
	int input;
	pid_t pid;
	int fd;
	const char *pager;
	int status;

	(void)printf("Would you like instructions (y or n)? ");
	input = getchar();
	while (getchar() != '\n');
	if (input != 'y')
		return;

	switch (pid = fork()) {
	case 0: /* child */
		if (!isatty(1))
			pager = "cat";
		else {
			if (!(pager = getenv("PAGER")) || (*pager == 0))
				pager = _PATH_MORE;
		}
		if ((fd = open(_PATH_INSTR, O_RDONLY)) == -1)
			err(1, "open %s", _PATH_INSTR);
		if (dup2(fd, 0) == -1)
			err(1, "dup2");
		(void)execl("/bin/sh", "sh", "-c", pager, (char *) NULL);
		err(1, "exec sh -c %s", pager);
		/*NOTREACHED*/
	case -1:
		err(1, "fork");
		/*NOTREACHED*/
	default:
		(void)waitpid(pid, &status, 0);
		break;
	}
	(void)printf("Hit return to continue...\n");
	while ((input = getchar()) != EOF && input != '\n');
}

static void
usage(void)
{
	(void)fprintf(stderr, "usage: fish [-p]\n");
	exit(1);
}


text:
class CreateExistingBlogAppSchema < ActiveRecord::Migration
  def up

    # posts
    if ActiveRecord::Base.connection.table_exists? 'posts'
      rename_table :posts, :blog_app_posts
    else
      create_table :blog_app_posts, :force => true do |t|
        t.string   "title"
        t.string   "slug"
        t.string   "author"
        t.string   "old_tags"
        t.text     "body"
        t.text     "html"
        t.datetime "published_at"
        t.datetime "created_at",                          null: false
        t.datetime "updated_at",                          null: false
        t.string   "audio_url"
        t.text     "description"
        t.integer  "external_comments_count", default: 0
      end
      add_index :blog_app_posts, :slug
    end

    # alias_tags
    if ActiveRecord::Base.connection.table_exists? 'alias_tags'
      rename_table :alias_tags, :blog_app_alias_tags
    else
      create_table "blog_app_alias_tags", id: false, force: true do |t|
        t.integer "tag_id"
        t.integer "alias_id"
      end
      add_index :blog_app_alias_tags, :tag_id
      add_index :blog_app_alias_tags, :alias_id
    end

    # old_slugs
    if ActiveRecord::Base.connection.table_exists? 'old_slugs'
      rename_table :old_slugs, :blog_app_old_slugs
    else
      create_table "blog_app_old_slugs", force: true do |t|
        t.string   "old_slug"
        t.string   "new_slug"
        t.integer  "post_id"
        t.datetime "created_at"
        t.datetime "updated_at"
      end
      add_index :blog_app_old_slugs, :old_slug
    end

    # taggings
    if ActiveRecord::Base.connection.table_exists? 'taggings'
      # had to specify a name since the default exceeded 63 characters
      rename_index :taggings, 'index_taggings_on_taggable_id_and_taggable_type_and_context', 'index_taggings_on_taggable_id_and_type_and_context'
      rename_table :taggings, :blog_app_taggings
    else
      create_table "blog_app_taggings", force: true do |t|
        t.integer  "tag_id"
        t.integer  "taggable_id"
        t.string   "taggable_type"
        t.integer  "tagger_id"
        t.string   "tagger_type"
        t.string   "context"
        t.datetime "created_at"
      end
      add_index :blog_app_taggings, :tag_id

      # had to specify a name since the default exceeded 63 characters
      add_index :blog_app_taggings, [:taggable_id, :taggable_type, :context], name: "index_blog_app_taggings_on_taggable_id_and_type_and_context"
    end

    # tags
    if ActiveRecord::Base.connection.table_exists? 'tags'
      rename_table :tags, :blog_app_tags
    else
      create_table "blog_app_tags", force: true do |t|
        t.string "name"
      end
    end
  end

  def down
    rename_table :blog_app_posts, :posts
    rename_table :blog_app_alias_tags, :alias_tags
    rename_table :blog_app_old_slugs, :old_slugs
    rename_table :blog_app_taggings, :taggings
    rename_table :blog_app_tags, :tags

    rename_index :taggings, "index_taggings_on_taggable_id_and_type_and_context", "index_taggings_on_taggable_id_and_taggable_type_and_context"
  end
end


text:
package esapi

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

func newIndicesPromoteDataStreamFunc(t Transport) IndicesPromoteDataStream {
	return func(name string, o ...func(*IndicesPromoteDataStreamRequest)) (*Response, error) {
		var r = IndicesPromoteDataStreamRequest{Name: name}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// IndicesPromoteDataStream - Promotes a data stream from a replicated data stream managed by CCR to a regular data stream
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/master/data-streams.html.
//
type IndicesPromoteDataStream func(name string, o ...func(*IndicesPromoteDataStreamRequest)) (*Response, error)

// IndicesPromoteDataStreamRequest configures the Indices Promote Data Stream API request.
//
type IndicesPromoteDataStreamRequest struct {
	Name string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
//
func (r IndicesPromoteDataStreamRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "POST"

	path.Grow(1 + len("_data_stream") + 1 + len("_promote") + 1 + len(r.Name))
	path.WriteString("/")
	path.WriteString("_data_stream")
	path.WriteString("/")
	path.WriteString("_promote")
	path.WriteString("/")
	path.WriteString(r.Name)

	params = make(map[string]string)

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), nil)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
//
func (f IndicesPromoteDataStream) WithContext(v context.Context) func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		r.ctx = v
	}
}

// WithPretty makes the response body pretty-printed.
//
func (f IndicesPromoteDataStream) WithPretty() func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
//
func (f IndicesPromoteDataStream) WithHuman() func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f IndicesPromoteDataStream) WithErrorTrace() func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
//
func (f IndicesPromoteDataStream) WithFilterPath(v ...string) func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
//
func (f IndicesPromoteDataStream) WithHeader(h map[string]string) func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f IndicesPromoteDataStream) WithOpaqueID(s string) func(*IndicesPromoteDataStreamRequest) {
	return func(r *IndicesPromoteDataStreamRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
var bcrypt = require('bcrypt');
var cuid = require('cuid');
import models from '../models/index';

const UserModel = (sequelize, Sequelize) => {
    const User = sequelize.define('user', {
        cuid: {
            type: Sequelize.STRING,
            primaryKey: true,
            validate: {
                notEmpty: true,
            }
        },
	facebook_id: {
		type: Sequelize.BIGINT,
		allowNull: true,
	},
  avatar: {
      type: Sequelize.BLOB,
      allowNull: true,
      /*
       validate: {
       notEmpty: true
       }
       */
  },
	firstname: {
		type: Sequelize.STRING,
		allowNull: true,
	},
	lastname: {
		type: Sequelize.STRING,
		allowNull: true,
	},
	isGuide: {
		type: Sequelize.BOOLEAN,
		defaultValue: false,
    allowNull: false,
	},
	last_seen: {
		type: Sequelize.DATE,
		allowNull: false,
    defaultValue: new Date(),
	},
	birthdate: {
		type: Sequelize.DATE,
		allowNull: true,
	},
	email: {
		type: Sequelize.STRING,
                unique: true,
		allowNull: true,
	},
	password_digest: {
		type: Sequelize.STRING,
	},
	password: {
		type: Sequelize.VIRTUAL,
		allowNull: true,
	},
	password_confirmation: {
		type: Sequelize.VIRTUAL
	},
  }, {
	tableName: 'users',
	freezeTableName: true,
	indexes: [{unique: true, fields: ['email']}],
	instanceMethods: {
		authenticate: function(value) {
			if (bcrypt.compareSync(value, this.password_digest))
				return this;
			else
				return false;
		}
	}
  });

    let hasSecurePassword = function (user, options, callback) {
        if (user.password != user.password_confirmation) {
            throw new Error("Password confirmation doesn't match Password");
        }

        //hash pw with 10 iterations
        bcrypt.hash(user.get('password'), 10, function (err, hash) {
            if (err) return callback(err);
            user.set('password_digest', hash);
            return callback(null, options);
        });
    };

  User.beforeCreate(function(user, options, callback) {
          if(user.email) {
            user.email = user.email.toLowerCase();
          }

          if (!user.cuid) {
            user.cuid = cuid();
          }

          if (user.password)
              hasSecurePassword(user, options, callback);
          else
              return callback(null, options);
    });

    User.beforeUpdate(function (user, options, callback) {
        user.email = user.email.toLowerCase();
        if (user.password)
            hasSecurePassword(user, options, callback);
        else
            return callback(null, options);
    });

  // User.sync({force: true}).then(function () {
  //     // Table created, add a test user when the server starts
  //     return User.create({
  //         //cuid: cuid(),
  //         cuid: '123',
  //         firstname: 'John',
  //         lastname: 'Hancock',
  //         email: 'hancock@gmail.com',
  //         password: 'plain1234',
  //         password_confirmation: 'plain1234',
  //         avatar: null,
  //         birthdate: new Date(1980, 6, 20),
  //         isGuide: true
  //     });
  // });

    return User;
}

export default UserModel;


text:
var main = {
  preload: function() {
    // Load all our assets
    game.load.image('paddle', 'assets/paddle.png');
    game.load.image('ball', 'assets/ball.png');
    game.load.image('brik', 'assets/brick.png');
  },

  create: function() {
    // Init some variables
    game.physics.startSystem(Phaser.Physics.ARCADE);
    this.cursor = game.input.keyboard.createCursorKeys()

    // Create the paddle
    this.paddle = game.add.sprite(200, 400, 'paddle');
    game.physics.arcade.enable(this.paddle);
    this.paddle.body.immovable = true;

    // Create the bouncy ball
    this.ball = game.add.sprite(200, 300, 'ball');
    game.physics.arcade.enable(this.ball);
    this.ball.body.collideWorldBounds = true;
    this.ball.body.velocity.x = 200;
    this.ball.body.velocity.y = 200;
    this.ball.body.bounce.x = 1;
    this.ball.body.bounce.y = 1;

    // Create all the briks
    this.bricks = game.add.group();
    this.bricks.enableBody = true;
    for (var i = 0; i < 5; i++)
      for (var j = 0; j < 5; j++)
        game.add.sprite(55 + i * 60, 55 + j * 35, 'brik', 0, this.bricks);
    this.bricks.setAll('body.immovable', true);
  },

  update: function() {
    // Handle collisions
    game.physics.arcade.collide(this.paddle, this.ball);
    game.physics.arcade.collide(this.ball, this.bricks, this.hit, null, this);

    // Move the paddle when the right or left arrow is pressed
    if (this.cursor.right.isDown)
      this.paddle.body.velocity.x = 350;
    else if (this.cursor.left.isDown)
      this.paddle.body.velocity.x = -350;
    else
      this.paddle.body.velocity.x = 0;
  },

  hit: function(ball, brik) {
    // When the ball hits a brick, kill the brick
    brik.kill();
  }
};

var game = new Phaser.Game(400, 450, Phaser.AUTO, 'gameDiv');
game.state.add('main', main);
game.state.start('main');


text:
from ...Helpers.commands import Label, Jz, Jump

def repeat_statement(commands, data, node):
    """ Компиляция repeat-until цикла """
    continue_label = data.label()
    commands.add(Label, continue_label)
    node.body.compile_vm(commands, data)
    node.condition.compile_vm(commands, data)
    commands.clean_type()
    # Если после очередной итерации условие останова не выполнилось, делаем следующую итерацию
    commands.add(Jz, continue_label)

def while_statement(commands, data, node):
    """ Компиляция while цикла """
    start_label = data.label()
    commands.add(Label, start_label)
    finish_label = data.label()
    node.condition.compile_vm(commands, data)
    commands.clean_type()
    # Если перед очередной итерации условие останова не выполнилось, завершаем цикл
    commands.add(Jz, finish_label)
    node.body.compile_vm(commands, data)
    # Делаем следующую итерацию
    commands.add(Jump, start_label)\
        .add(Label, finish_label)

def for_statement(commands, data, node):
    """ Компиляция цикла for """
    start_label = data.label()
    finish_label = data.label()

    node.stmt1.compile_vm(commands, data)
    commands.add(Label, start_label)
    node.stmt2.compile_vm(commands, data)
    commands.clean_type()
    # Если условия цикла не выполнилось, завешаем цикл
    commands.add(Jz, finish_label)
    node.body.compile_vm(commands, data)
    node.stmt3.compile_vm(commands, data)
    commands.add(Jump, start_label)\
        .add(Label, finish_label)


text:
import actionTypes from './action-types';
import { callApi } from '../api';

import { actions as entityActions } from '../entity';
import { actions as serviceActions } from '../service';
import { actions as eventActions } from '../event';
import { actions as configActions } from '../config';
import { actions as navigationActions } from '../navigation';

export function fetchAll(reactor) {
  reactor.dispatch(actionTypes.API_FETCH_ALL_START, {});

  return callApi(reactor, 'GET', 'bootstrap').then((data) => {
    reactor.batch(() => {
      entityActions.replaceData(reactor, data.states);
      serviceActions.replaceData(reactor, data.services);
      eventActions.replaceData(reactor, data.events);
      configActions.configLoaded(reactor, data.config);
      navigationActions.panelsLoaded(reactor, data.panels);

      reactor.dispatch(actionTypes.API_FETCH_ALL_SUCCESS, {});
    });
  }, (message) => {
    reactor.dispatch(actionTypes.API_FETCH_ALL_FAIL, { message });

    return Promise.reject(message);
  });
}


text:
package com.brightgenerous.datasource;

import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.brightgenerous.lang.Args;
import com.google.inject.Injector;

public abstract class DataSource {

    private static volatile Class<? extends DataSource> dataSourceClazz;

    private static volatile DataSource instance;

    private static final Map<Class<? extends DataSource>, SoftReference<? extends DataSource>> cache = new ConcurrentHashMap<>();

    private transient volatile InjectorFactory injectorFactory;

    private transient volatile Initializer initializer;

    private transient volatile Destroyer destroyer;

    protected DataSource() {
    }

    public static void set(Class<? extends DataSource> clazz) {
        Args.notNull(clazz, "clazz");

        if (dataSourceClazz != clazz) {
            synchronized (DataSource.class) {
                if (dataSourceClazz != clazz) {

                    checkAndGetConstructor(clazz);

                    dataSourceClazz = clazz;
                    instance = null;
                }
            }
        }
    }

    public static DataSource get() {
        DataSource ret = instance;
        if (ret == null) {
            synchronized (DataSource.class) {
                ret = instance;
                if (ret == null) {

                    if (dataSourceClazz == null) {
                        throw new IllegalStateException(
                                "the Data Source Class yet has not been set.");
                    }

                    instance = get(dataSourceClazz);
                    ret = instance;
                }
            }
        }
        return ret;
    }

    public static DataSource get(Class<? extends DataSource> clazz) {
        if (clazz == null) {
            return get();
        }
        DataSource ret = null;
        {
            SoftReference<? extends DataSource> ref = cache.get(clazz);
            if (ref != null) {
                ret = ref.get();
            }
        }
        if (ret == null) {
            synchronized (cache) {
                SoftReference<? extends DataSource> ref = cache.get(clazz);
                if (ref != null) {
                    ret = ref.get();
                }
                if (ret == null) {
                    cache.remove(clazz);
                    Set<Class<? extends DataSource>> dels = new HashSet<>();
                    for (Entry<Class<? extends DataSource>, SoftReference<? extends DataSource>> entry : cache
                            .entrySet()) {
                        if (entry.getValue().get() == null) {
                            dels.add(entry.getKey());
                        }
                    }
                    if (!dels.isEmpty()) {
                        for (Class<? extends DataSource> del : dels) {
                            cache.remove(del);
                        }
                    }
                    ret = newInstance(clazz);
                    cache.put(clazz, new SoftReference<>(ret));
                }
            }
        }
        return ret;
    }

    private static DataSource newInstance(Class<? extends DataSource> clazz) {
        try {
            Constructor<? extends DataSource> cons = checkAndGetConstructor(clazz);
            return cons.newInstance();
        } catch (SecurityException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    private static Constructor<? extends DataSource> checkAndGetConstructor(
            Class<? extends DataSource> clazz) {
        try {
            Constructor<? extends DataSource> cons = clazz.getDeclaredConstructor();
            if (!Modifier.isPublic(cons.getModifiers()) && !cons.isAccessible()) {
                cons.setAccessible(true);
            }
            return cons;
        } catch (NoSuchMethodException | SecurityException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract InjectorFactory createInjectorFactory();

    protected Initializer createInitializer() {
        return null;
    }

    protected Destroyer createDestroyer() {
        return null;
    }

    protected InjectorFactory getInjectorFactory() {
        if (injectorFactory == null) {
            synchronized (this) {
                if (injectorFactory == null) {
                    injectorFactory = createInjectorFactory();
                }
            }
        }
        return injectorFactory;
    }

    public void initialize() {
        getInjectorFactory().initialize();

        if (initializer == null) {
            synchronized (this) {
                if (initializer == null) {
                    initializer = createInitializer();
                }
            }
        }
        if (initializer != null) {
            initializer.initialize(getInjector());
        }

        getInjectorFactory().verify();
    }

    public void destroy() {
        if (destroyer == null) {
            synchronized (this) {
                if (destroyer == null) {
                    destroyer = createDestroyer();
                }
            }
        }
        if (destroyer != null) {
            destroyer.destroy(getInjector());
        }

        getInjectorFactory().destroy();
    }

    public <T> T instance(Class<T> clazz) {
        return instance(clazz, false);
    }

    public <T> T instance(Class<T> clazz, boolean rollback) {
        return getInjector(rollback).getInstance(clazz);
    }

    protected Injector getInjector() {
        return getInjector(false);
    }

    protected Injector getInjector(boolean rollback) {
        return getInjectorFactory().getInjector(rollback);
    }
}


text:
<FindbugsPlugin xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="findbugsplugin.xsd" pluginid="com.google.api.client.findbugs"
  provider="Google APIs Client Library" website="https://code.google.com/p/google-http-java-client/">

  <Detector class="com.google.api.client.findbugs.BetaDetector"
    speed="fast"
    reports="BETA_CLASS_USAGE,BETA_METHOD_USAGE,BETA_FIELD_USAGE" />
  <BugPattern type="BETA_CLASS_USAGE" abbrev="GABU" category="BAD_PRACTICICE" />
  <BugPattern type="BETA_METHOD_USAGE" abbrev="GABU"
    category="BAD_PRACTICICE" />
  <BugPattern type="BETA_FIELD_USAGE" abbrev="GABU" category="BAD_PRACTICICE" />
</FindbugsPlugin>


text:
package com.cube.storm.content.lib.listener;

/**
 * Listener interface for when a delta or bundle is being downloaded.
 * <p/>
 * Use this interface to display a progress whilst the files are being downloaded
 *
 * @author Callum Taylor
 * @project LightningContent
 */
public interface DownloadListener
{
	/**
	 * Method called when a chunk has been downloaded
	 *
	 * @param downloaded the amount downloaded
	 * @param total the total amount to download
	 */
	public void onDownloadProgress(long downloaded, long total);
}


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Kap10: All Systems Nominal</title>
    <link rel="stylesheet" href="/static/css/foundation.min.css" />
    <link rel="stylesheet" href="/static/css/app.css" />

    {% set locked = db.is_locked() %}

          Kap10:
          {% if locked %}
          System Locked
          {% else %}
          System Unlocked
          {% endif %}

    {% for triplet in projects %}

      {% for id, project in triplet %}
      {% set commit = db.get_commit(id) %}

{{ project["name"] }}

              {% if project["gh_url"] %}
              {{ commit }}
              {% else %}
              {{ db.get_commit(id) }}
              {% endif %}

Last Updated: {% if project["last_updated"] %}{{ project["last_updated"] }}{% else %}Never{% endif %}

Deployer: {% if project["last_updated_by"] %}{{ project["last_updated_by"] }}{% else %}Never{% endif %}

            {% if not locked %}

              Deploy

            {% endif %}

      {% endfor %}

    {% endfor %}


text:
extern const struct IFBKIdentityAttributes {
	__unsafe_unretained NSString *emailAddress;
	__unsafe_unretained NSString *firstName;
	__unsafe_unretained NSString *identifier;
	__unsafe_unretained NSString *lastName;
} IFBKIdentityAttributes;

extern const struct IFBKIdentityRelationships {
} IFBKIdentityRelationships;

extern const struct IFBKIdentityFetchedProperties {
} IFBKIdentityFetchedProperties;

@interface IFBKIdentityID : NSManagedObjectID {}
@end

@interface _IFBKIdentity : IFBKModel {}
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_;
+ (NSString*)entityName;
+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_;
- (IFBKIdentityID*)objectID;

@property (nonatomic, strong) NSString* emailAddress;

//- (BOOL)validateEmailAddress:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* firstName;

//- (BOOL)validateFirstName:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSNumber* identifier;

@property int32_t identifierValue;
- (int32_t)identifierValue;
- (void)setIdentifierValue:(int32_t)value_;

//- (BOOL)validateIdentifier:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* lastName;

//- (BOOL)validateLastName:(id*)value_ error:(NSError**)error_;

@end

@interface _IFBKIdentity (CoreDataGeneratedAccessors)

@end

@interface _IFBKIdentity (CoreDataGeneratedPrimitiveAccessors)

- (NSString*)primitiveEmailAddress;
- (void)setPrimitiveEmailAddress:(NSString*)value;

- (NSString*)primitiveFirstName;
- (void)setPrimitiveFirstName:(NSString*)value;

- (NSNumber*)primitiveIdentifier;
- (void)setPrimitiveIdentifier:(NSNumber*)value;

- (int32_t)primitiveIdentifierValue;
- (void)setPrimitiveIdentifierValue:(int32_t)value_;

- (NSString*)primitiveLastName;
- (void)setPrimitiveLastName:(NSString*)value;

@end


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import memoize from 'memoize-one';

class ClippedLink extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    link: PropTypes.string
  };

  static defaultProps = {
    className: ''
  };

  constructor(props) {
    super(props);

    this.handle = null;
    this.state = {
      show: false
    };
  }

  componentWillUnmount() {
    clearTimeout(this.handle);
  }

  clearActions = () => clearTimeout(this.handle)

  clippedLink = memoize(link => link.split('?')[0])

  furl = () => {
    clearTimeout(this.handle);
    this.handle = setTimeout(() => this.setState({ show: false }), 350);
  }

  unfurl = () => {
    clearTimeout(this.handle);
    this.handle = setTimeout(() => this.setState({ show: true }), 150);
  }

  render() {
    const { className, link } = this.props;
    const { show } = this.state;

    if (!link.includes('?')) {
      return {link};
    }

    const clipped = this.clippedLink(link);

    return (

        {
          show ?
            link :
            <React.Fragment>
              {clipped}<button className="button-link" onMouseEnter={this.unfurl} type="button">...</button>
            </React.Fragment>
        }

    );
  }
}

export default ClippedLink;