text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\web\UploadedFile;

/**
 * This is the model class for table "{{%books}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $date_create
 * @property string $date_update
 * @property string $preview
 * @property string $date
 * @property integer $author_id
 * @property Authors $author
 */
class Books extends \yii\db\ActiveRecord
{
    const IMAGE_DIR = '@webroot/images/books';
    const WEB_IMAGE_DIR = '@web/images/books';

    public $file;//Файл для картинки
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%books}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'date', 'author_id'], 'required'],
            [['date_create', 'date_update', 'date'], 'safe'],
            [['author_id'], 'integer'],
            [['name', 'preview','preview'], 'string', 'max' => 255],
            ['file','file','extensions'=>['jpg','png','gif'],'skipOnEmpty'=>$this->isNewRecord ? false : true],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Название'),
            'date_create' => Yii::t('app', 'Дата создания записи'),
            'date_update' => Yii::t('app', 'Дата обновления записи'),
            'preview' => Yii::t('app', 'Обложка'),
            'file' => Yii::t('app', 'Картинка'),
            'date' => Yii::t('app', 'Дата выхода книги'),
            'author_id' => Yii::t('app', 'Автор книги'),
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_create',
                'updatedAtAttribute' => 'date_update',
                'value' => new Expression('NOW()'),
            ],
        ];
    }

    public function beforeValidate()
    {
        $this->file = UploadedFile::getInstance($this, 'file');
        return parent::beforeValidate();
    }

    public function beforeSave($insert)
    {
        if($this->file)
        {
            $filename = time() . '.' . $this->file->extension;
            $this->preview = $filename;
            $this->file->saveAs(\Yii::getAlias(self::IMAGE_DIR . '/' . $filename));
        }

        $this->date = date(DATE_DBFORMAT,strtotime($this->date));
        return parent::beforeSave($insert);
    }

    public function getAuthor()
    {
        return $this->hasOne(Authors::className(),['id'=>'author_id']);
    }

    public function afterDelete()
    {
        $filename = \Yii::getAlias(self::IMAGE_DIR.'/'.$this->preview);
        if(is_file($filename))
            unlink($filename);
        return parent::afterDelete();
    }

    public function image($size)
    {
        $path = \Yii::getAlias(self::IMAGE_DIR);
        $filename = $this->preview;

        if(!is_file($path.'/'.$filename))
            return 'http://placehold.it/'.$size;

        if(is_file($path.'/'.$size.'/'.$this->preview))
            return \Yii::getAlias(self::WEB_IMAGE_DIR).'/'.$size.'/'.$this->preview;

        if(!is_dir($path.'/'.$size))
            mkdir($path.'/'.$size);

        $image = \Yii::$app->image->load($path.'/'.$filename);
        $image->resize($size);
        $image->save($path.'/'.$size.'/'.$filename);
        return $this->image($size);
    }
}


text:
using ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
using ClosedXML_Tests.Utils;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ClosedXML_Tests.Excel
{
    // Tests in this fixture test only the successful loading of existing Excel files,
    // i.e. we test that ClosedXML doesn't choke on a given input file
    // These tests DO NOT test that ClosedXML successfully recognises all the Excel parts or that it can successfully save those parts again.
    [TestFixture]
    public class LoadingTests
    {
        [Test]
        public void CanSuccessfullyLoadFiles()
        {
            var files = new List<string>()
            {
                @"Misc\TableWithCustomTheme.xlsx",
                @"Misc\EmptyTable.xlsx",
                @"Misc\LoadPivotTables.xlsx",
                @"Misc\LoadFileWithCustomSheetViews.xlsx",
                @"Misc\LoadSheetsWithCommas.xlsx",
                @"Misc\ExcelProducedWorkbookWithImages.xlsx",
                @"Misc\InvalidPrintTitles.xlsx",
                @"Misc\ExcelProducedWorkbookWithImages.xlsx",
                @"Misc\EmptyCellValue.xlsx",
                @"Misc\AllShapes.xlsx",
                @"Misc\TableHeadersWithLineBreaks.xlsx",
                @"Misc\TableWithNameNull.xlsx",
                @"Misc\DuplicateImageNames.xlsx",
                @"Misc\InvalidPrintArea.xlsx",
                @"Misc\Date1904System.xlsx",
                @"Misc\LoadImageWithoutTransform2D.xlsx"
            };

            foreach (var file in files)
            {
                TestHelper.LoadFile(file);
            }
        }

        [Test]
        public void CanSuccessfullyLoadLOFiles()
        {
            // TODO: unpark all files
            var parkedForLater = new[]
            {
                "Misc.LO.xlsx.formats.xlsx",
                "Misc.LO.xlsx.pivot_table.shared-group-field.xlsx",
                "Misc.LO.xlsx.pivot_table.shared-nested-dategroup.xlsx",
                "Misc.LO.xlsx.pivottable_bool_field_filter.xlsx",
                "Misc.LO.xlsx.pivottable_date_field_filter.xlsx",
                "Misc.LO.xlsx.pivottable_double_field_filter.xlsx",
                "Misc.LO.xlsx.pivottable_duplicated_member_filter.xlsx",
                "Misc.LO.xlsx.pivottable_rowcolpage_field_filter.xlsx",
                "Misc.LO.xlsx.pivottable_string_field_filter.xlsx",
                "Misc.LO.xlsx.pivottable_tabular_mode.xlsx",
                "Misc.LO.xlsx.pivot_table_first_header_row.xlsx",
                "Misc.LO.xlsx.tdf100709.xlsx",
                "Misc.LO.xlsx.tdf89139_pivot_table.xlsx",
                "Misc.LO.xlsx.universal-content-strict.xlsx",
                "Misc.LO.xlsx.universal-content.xlsx",
                "Misc.LO.xlsx.xf_default_values.xlsx"
            };

            var files = TestHelper.ListResourceFiles(s => s.Contains(".LO.") && !parkedForLater.Any(i => s.Contains(i))).ToArray();

            foreach (var file in files)
            {
                TestHelper.LoadFile(file);
            }
        }

        [Test]
        public void CanLoadAndManipulateFileWithEmptyTable()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\EmptyTable.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheets.First();
                var table = ws.Tables.First();
                table.DataRange.InsertRowsBelow(5);
            }
        }

        [Test]
        public void CanLoadDate1904SystemCorrectly()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\Date1904System.xlsx")))
            using (var ms = new MemoryStream())
            {
                using (var wb = new XLWorkbook(stream))
                {
                    var ws = wb.Worksheets.First();
                    var c = ws.Cell("A2");
                    Assert.AreEqual(XLDataType.DateTime, c.DataType);
                    Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime());
                    wb.SaveAs(ms);
                }

                ms.Seek(0, SeekOrigin.Begin);

                using (var wb = new XLWorkbook(ms))
                {
                    var ws = wb.Worksheets.First();
                    var c = ws.Cell("A2");
                    Assert.AreEqual(XLDataType.DateTime, c.DataType);
                    Assert.AreEqual(new DateTime(2017, 10, 27, 21, 0, 0), c.GetDateTime());
                    wb.SaveAs(ms);
                }
            }
        }

        [Test]
        public void CanLoadAndSaveFileWithMismatchingSheetIdAndRelId()
        {
            // This file's workbook.xml contains:
            // <x:sheet name="Data" sheetId="13" r:id="rId1" />
            // and the mismatch between the sheetId and r:id can create problems.
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\FileWithMismatchSheetIdAndRelId.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                using (var ms = new MemoryStream())
                {
                    wb.SaveAs(ms, true);
                }
            }
        }

        [Test]
        public void CanLoadBasicPivotTable()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheet("PivotTable1");
                var pt = ws.PivotTable("PivotTable1");
                Assert.AreEqual("PivotTable1", pt.Name);

                Assert.AreEqual(1, pt.RowLabels.Count());
                Assert.AreEqual("Name", pt.RowLabels.Single().SourceName);

                Assert.AreEqual(1, pt.ColumnLabels.Count());
                Assert.AreEqual("Month", pt.ColumnLabels.Single().SourceName);

                var pv = pt.Values.Single();
                Assert.AreEqual("Sum of NumberOfOrders", pv.CustomName);
                Assert.AreEqual("NumberOfOrders", pv.SourceName);
            }
        }

        [Test]
        public void CanLoadOrderedPivotTable()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheet("OrderedPivotTable");
                var pt = ws.PivotTable("OrderedPivotTable");

                Assert.AreEqual(XLPivotSortType.Ascending, pt.RowLabels.Single().SortType);
                Assert.AreEqual(XLPivotSortType.Descending, pt.ColumnLabels.Single().SortType);
            }
        }

        [Test]
        public void CanLoadPivotTableSubtotals()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LoadPivotTables.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheet("PivotTableSubtotals");
                var pt = ws.PivotTable("PivotTableSubtotals");

                var subtotals = pt.RowLabels.Get("Group").Subtotals.ToArray();
                Assert.AreEqual(3, subtotals.Length);
                Assert.AreEqual(XLSubtotalFunction.Average, subtotals[0]);
                Assert.AreEqual(XLSubtotalFunction.Count, subtotals[1]);
                Assert.AreEqual(XLSubtotalFunction.Sum, subtotals[2]);
            }
        }

        /// <summary>
        /// For non-English locales, the default style ("Normal" in English) can be
        /// another piece of text (e.g. ??????? in Russian).
        /// This test ensures that the default style is correctly detected and
        /// no style conflicts occur on save.
        /// </summary>
        [Test]
        public void CanSaveFileWithDefaultStyleNameNotInEnglish()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\FileWithDefaultStyleNameNotInEnglish.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                using (var ms = new MemoryStream())
                {
                    wb.SaveAs(ms, true);
                }
            }
        }

        /// <summary>
        /// As per https://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.cellvalues(v=office.15).aspx
        /// the 'Date' DataType is available only in files saved with Microsoft Office
        /// In other files, the data type will be saved as numeric
        /// ClosedXML then deduces the data type by inspecting the number format string
        /// </summary>
        [Test]
        public void CanLoadLibreOfficeFileWithDates()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\LibreOfficeFileWithDates.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheets.First();
                foreach (var cell in ws.CellsUsed())
                {
                    Assert.AreEqual(XLDataType.DateTime, cell.DataType);
                }
            }
        }

        [Test]
        public void CanLoadFileWithImagesWithCorrectAnchorTypes()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheets.First();
                Assert.AreEqual(2, ws.Pictures.Count);
                Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Pictures.First().Placement);
                Assert.AreEqual(XLPicturePlacement.Move, ws.Pictures.Skip(1).First().Placement);

                var ws2 = wb.Worksheets.Skip(1).First();
                Assert.AreEqual(1, ws2.Pictures.Count);
                Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws2.Pictures.First().Placement);
            }
        }

        [Test]
        public void CanLoadFileWithImagesWithCorrectImageType()
        {
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageFormats.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheets.First();
                Assert.AreEqual(1, ws.Pictures.Count);
                Assert.AreEqual(XLPictureFormat.Jpeg, ws.Pictures.First().Format);

                var ws2 = wb.Worksheets.Skip(1).First();
                Assert.AreEqual(1, ws2.Pictures.Count);
                Assert.AreEqual(XLPictureFormat.Png, ws2.Pictures.First().Format);
            }
        }

        [Test]
        public void CanLoadAndDeduceAnchorsFromExcelGeneratedFile()
        {
            // This file was produced by Excel. It contains 3 images, but the latter 2 were copied from the first.
            // There is actually only 1 embedded image if you inspect the file's internals.
            // Additionally, Excel saves all image anchors as TwoCellAnchor, but uses the EditAs attribute to distinguish the types
            using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\ExcelProducedWorkbookWithImages.xlsx")))
            using (var wb = new XLWorkbook(stream))
            {
                var ws = wb.Worksheets.First();
                Assert.AreEqual(3, ws.Pictures.Count);

                Assert.AreEqual(XLPicturePlacement.MoveAndSize, ws.Picture("Picture 1").Placement);
                Assert.AreEqual(XLPicturePlacement.Move, ws.Picture("Picture 2").Placement);
                Assert.AreEqual(XLPicturePlacement.FreeFloating, ws.Picture("Picture 3").Placement);

                using (var ms = new MemoryStream())
                    wb.SaveAs(ms, true);
            }
        }

        [Test]
        public void CanLoadFromTemplate()
        {
            using (var tf1 = new TemporaryFile())
            using (var tf2 = new TemporaryFile())
            {
                using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\AllShapes.xlsx")))
                using (var wb = new XLWorkbook(stream))
                {
                    // Save as temporary file
                    wb.SaveAs(tf1.Path);
                }

                var workbook = XLWorkbook.OpenFromTemplate(tf1.Path);
                Assert.True(workbook.Worksheets.Any());
                Assert.Throws<InvalidOperationException>(() => workbook.Save());

                workbook.SaveAs(tf2.Path);
            }
        }

        /// <summary>
        /// Excel escapes symbol ' in worksheet title so we have to process this correctly.
        /// </summary>
        [Test]
        public void CanOpenWorksheetWithEscapedApostrophe()
        {
            string title = "";
            TestDelegate openWorkbook = () =>
            {
                using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Misc\EscapedApostrophe.xlsx")))
                using (var wb = new XLWorkbook(stream))
                {
                    var ws = wb.Worksheets.First();
                    title = ws.Name;
                }
            };

            Assert.DoesNotThrow(openWorkbook);
            Assert.AreEqual("L'E", title);
        }

        [Test]
        public void CanRoundTripSheetProtectionForObjects()
        {
            using (var book = new XLWorkbook())
            {
                var sheet = book.AddWorksheet("TestSheet");
                sheet.Protect()
                    .SetObjects(true)
                    .SetScenarios(true);

                using (var xlStream = new MemoryStream())
                {
                    book.SaveAs(xlStream);

                    using (var persistedBook = new XLWorkbook(xlStream))
                    {
                        var persistedSheet = persistedBook.Worksheets.Worksheet(1);

                        Assert.AreEqual(sheet.Protection.Objects, persistedSheet.Protection.Objects);
                    }
                }
            }
        }

        [Test]
        [TestCase("A1*10", "1230", 1230)]
        [TestCase("A1/10", "12.3", 12.3)]
        [TestCase("A1&\" cells\"", "123 cells", "123 cells")]
        [TestCase("A1&\"000\"", "123000", "123000")]
        [TestCase("ISNUMBER(A1)", "True", true)]
        [TestCase("ISBLANK(A1)", "False", false)]
        [TestCase("DATE(2018,1,28)", "43128", null)]
        public void LoadFormulaCachedValue(string formula, object expectedValueCached, object expectedCachedValue)
        {
            using (var ms = new MemoryStream())
            {
                using (XLWorkbook book1 = new XLWorkbook())
                {
                    var sheet = book1.AddWorksheet("sheet1");
                    sheet.Cell("A1").Value = 123;
                    sheet.Cell("A2").FormulaA1 = formula;
                    var options = new SaveOptions { EvaluateFormulasBeforeSaving = true };

                    book1.SaveAs(ms, options);
                }
                ms.Position = 0;

                using (XLWorkbook book2 = new XLWorkbook(ms))
                {
                    var ws = book2.Worksheet(1);
                    Assert.IsTrue(ws.Cell("A2").NeedsRecalculation);
                    Assert.AreEqual(expectedValueCached, ws.Cell("A2").ValueCached);

                    if (expectedCachedValue != null)
                        Assert.AreEqual(expectedCachedValue, ws.Cell("A2").CachedValue);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace EaToGliffy.Gliffy.Model.Graphics
{
    public class GliffyGraphicShape : GliffyGraphic
    {
        public GliffyShape Shape { get; set; }

        public GliffyGraphicShape()
        {
            Type = "Shape";
        }
    }
}


text:
<?php

namespace Symfony\Component\Security\Core\Tests\Role;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\Role;

class RoleTest extends TestCase
{
    public function testGetRole()
    {
        $role = new Role('FOO');

        $this->assertEquals('FOO', $role->getRole());
    }
}


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

<TITLE>
ParseFilter (apache-nutch 2.2.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-06-27">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.nutch.parse

Interface ParseFilter

All Superinterfaces:
org.apache.hadoop.conf.Configurable, FieldPluggable, Pluggable

All Known Implementing Classes:
CCParseFilter, HTMLLanguageParser, JSParseFilter, RelTagParser

public interface ParseFilter
extends FieldPluggable, org.apache.hadoop.conf.Configurable

Extension point for DOM-based parsers.  Permits one to add additional
 metadata to parses provided by the html or tika plugins.  All plugins found which implement this extension
 point are run sequentially on the parse.

Field Summary

static String
X_POINT_ID

          The name of the extension point.

Method Summary

 Parse
filter(String url,
       WebPage page,
       Parse parse,
       HTMLMetaTags metaTags,
       DocumentFragment doc)

          Adds metadata or otherwise modifies a parse, given
 the DOM tree of a page.

Methods inherited from interface org.apache.nutch.plugin.FieldPluggable

getFields

Methods inherited from interface org.apache.hadoop.conf.Configurable

getConf, setConf

Field Detail

X_POINT_ID

static final String X_POINT_ID

The name of the extension point.

Method Detail

filter

Parse filter(String url,
             WebPage page,
             Parse parse,
             HTMLMetaTags metaTags,
             DocumentFragment doc)

Adds metadata or otherwise modifies a parse, given
 the DOM tree of a page.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2013 The Apache Software Foundation


text:
class acEXRTool : public QDialog {
    Q_OBJECT

  public:
    acEXRTool(QWidget *parent = 0);
    void Init(const QString& title, const QString& productName);
    ~acEXRTool();

    QDoubleSpinBox *exrExposureBox;
    QDoubleSpinBox *exrDefogBox;
    QDoubleSpinBox *exrKneeLowBox;
    QDoubleSpinBox *exrKneeHighBox;
    QDoubleSpinBox *exrGammaBox;

  public slots:
    void onClose();

  private:
    QPushButton      *m_PBClose;
};

#endif // ACEXRTOOL_H


text:
<!doctype html>

  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>stroke.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <meta charset="utf8">

      Closure Library API Documentation

        Go to class or file:
        <input type="text" id="ac">

stroke.js

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Copyright 2007 Google Inc. All Rights Reserved.

/**
 * @fileoverview Represents a stroke object for goog.graphics.
 */

goog.provide('goog.graphics.Stroke');

/**
 * Creates an immutable stroke object.
 *
 * @param {number|string} width The width of the stroke.
 * @param {string} color The color of the stroke.
 * @constructor
 */
goog.graphics.Stroke = function(width, color) {
  /**
   * The width of the stroke.
   * @type {number|string}
   * @private
   */
  this.width_ = width;

  /**
   * The color with which to fill.
   * @type {string}
   * @private
   */
  this.color_ = color;
};

/**
 * @return {number|string} The width of this stroke.
 */
goog.graphics.Stroke.prototype.getWidth = function() {
  return this.width_;
};

/**
 * @return {string} The color of this stroke.
 */
goog.graphics.Stroke.prototype.getColor = function() {
  return this.color_;
};


text:
const { TimeLimiter } = require('../');

describe('PIXI.TimeLimiter', function ()
{
    it('should limit to stop after time from beginFrame()', function (done)
    {
        this.slow(500);

        const limit = new TimeLimiter(100);

        limit.beginFrame();
        for (let i = 0; i < 20; ++i)
        {
            expect(limit.allowedToUpload()).to.be.true;
        }

        setTimeout(function ()
        {
            expect(limit.allowedToUpload()).to.be.false;

            limit.beginFrame();

            expect(limit.allowedToUpload()).to.be.true;

            done();
        }, 200);
    });
});


text:
package org.activiti.engine.impl.event;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SubProcess;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.bpmn.helper.ScopeUtil;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.CompensateEventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

import java.util.List;

/**

 */
public class CompensationEventHandler implements EventHandler {

  public String getEventHandlerType() {
    return CompensateEventSubscriptionEntity.EVENT_TYPE;
  }

  public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {

    String configuration = eventSubscription.getConfiguration();
    if (configuration == null) {
      throw new ActivitiException("Compensating execution not set for compensate event subscription with id " + eventSubscription.getId());
    }

    ExecutionEntity compensatingExecution = commandContext.getExecutionEntityManager().findById(configuration);

    String processDefinitionId = compensatingExecution.getProcessDefinitionId();
    Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
    if (process == null) {
      throw new ActivitiException("Cannot start process instance. Process model (id = " + processDefinitionId + ") could not be found");
    }

    FlowElement flowElement = process.getFlowElement(eventSubscription.getActivityId(), true);

    if (flowElement instanceof SubProcess && !((SubProcess) flowElement).isForCompensation()) {

      // descend into scope:
      compensatingExecution.setScope(true);
      List<CompensateEventSubscriptionEntity> eventsForThisScope = commandContext.getEventSubscriptionEntityManager().findCompensateEventSubscriptionsByExecutionId(compensatingExecution.getId());
      ScopeUtil.throwCompensationEvent(eventsForThisScope, compensatingExecution, false);

    } else {

      try {

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
          commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
                ActivitiEventBuilder.createActivityEvent(ActivitiEventType.ACTIVITY_COMPENSATE, compensatingExecution, flowElement));
        }
        compensatingExecution.setCurrentFlowElement(flowElement);
        Context.getAgenda().planContinueProcessInCompensation(compensatingExecution);

      } catch (Exception e) {
        throw new ActivitiException("Error while handling compensation event " + eventSubscription, e);
      }

    }
  }

}


text:
(function($){  //$-safe plugin

/**
 * GearsImageUploader class
 *
 * Classes for uploading images using Google's Gears plugin.
 *
 * They can display upload status, progress bar and emulate
 * classic html form uploads so server-side changes are not required.
 *
 * Do client-side resizing before upload.
 *
 * Depends on GearsUploader.js, GearsMultipartForm.js
 * (optionally - on ProgressBar.js).
 *
 * Author: Mikhail Korobov
 * License: MIT
 *
 */

this.GearsImageUtilsMixin = new Class({

    canvasFromBlob: function(blob, maxWidth){
        var canvas = google.gears.factory.create('beta.canvas');
        canvas.decode(blob);
        if (maxWidth)
            this.makeThumbnail(canvas, maxWidth);
        return canvas;
    },

    makeThumbnail: function(canvas, maxWidth){
        var w = canvas.width;
        var h = canvas.height;
        var ratio = h / w;

        if (maxWidth < w) {
            w = maxWidth;
            h = w * ratio;
        }
        canvas.resize(parseInt(w), parseInt(h));
    },

    blobFromCanvas: function(canvas, quality)
    {
        return canvas.encode("image/jpeg", {quality: quality});
    },

    imgFromBlob: function(blob, imgElement)
    {
        var localServer = google.gears.factory.create('beta.localserver');
        var store = localServer.createStore('store');
        var url = url ? url: '/image'+Math.random()+'.jpg?';
        store.captureBlob(blob, url, "image/jpeg");
        $(imgElement).setProperty('src', url);
        setTimeout(function (){store.remove(url)}, 1000);
    }
});

this.GearsImageUploader = new Class({
    Extends: GearsUploader,
    Implements: GearsImageUtilsMixin,

    options :{
        statuses: {},

        maxWidth: 600,
        previewWidth: null,
        quality: 0.9,
        fileOpenOptions: {
            filter : ['image/jpeg', 'image/png'],
            singleFile: false
        },
        previewsElement: 'gears-previews',
        fileElementName: 'image',
        onUploadComplete: function(){
            this.files.each(function(file){
                file.img.dispose();
            });
            this.files = [];
            this.setStatus('stateComplete');
        }
    },

    injectImage: function(img){
        var elem = $(this.options.previewsElement);
        if (elem)
            img.inject(elem, 'top');
        return img;
    },

    handleFile: function(file){
        var canvas = this.canvasFromBlob(file.blob, this.options.maxWidth);
        var blob = this.blobFromCanvas(canvas);

        var previewCanvas = canvas;
        var previewBlob = blob;

        if (this.options.previewWidth) {
            this.makeThumbnail(previewCanvas, this.options.previewWidth);
            previewBlob = this.blobFromCanvas(previewCanvas);
        }

        var self = this;
        var img = new Element('img', {
            'events':{
                'click': function(){
                    self.files = self.files.filter(function(item){
                        return item.img != img;
                    });
                    img.dispose();
                    if (!self.files.length)
                        self.setStatus('noFiles');
                }
            }
        });
        img = this.injectImage(img);
        this.imgFromBlob(previewBlob, img);
        this.files.push({'name':file.name, 'blob':blob, 'img': img});
    }
});

this.GearsSingleImageUploader = new Class({

    Extends: GearsImageUploader,

    options: {
        verboseProcessing: false,
        fileElementName: 'image',
        statuses: {},
        fileOpenOptions: {
            filter : ['image/jpeg', 'image/png'],
            singleFile: true
        },
        onUploadComplete: function(){
            this.files = [];
            this.setStatus('stateComplete');
        }
    },

    getFileElementName: function(index){
        return this.options.fileElementName;
    },

    injectImage: function(img){
        var elem = $(this.options.previewsElement);
        if (elem) {
            elem.src = img.src;
            return $(this.options.previewsElement);
        }
        return img;
    }
});

})(document.id); // end $-safe plugin


text:
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using Microsoft.Diagnostics.Tracing.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

/* README FIRST */
// This shows you how to listen to both Kernel and non-Kernel (in this case the CLR) events on Windows 8.
// This is significantly easier than on Win7 (which is shown in 33_KernelAndClrMonitorWin7.cs) because
// a single session can have both kernel and non-kernel providers.
//
namespace TraceEventSamples
{
    public class KernelAndClrMonitor
    {
        /// <summary>
        /// Where all the output goes.
        /// </summary>
        static TextWriter Out = AllSamples.Out;

        public static void Run()
        {
            var monitoringTimeSec = 10;

            if (Environment.OSVersion.Version.Major * 10 + Environment.OSVersion.Version.Minor < 62)
            {
                Out.WriteLine("This demo only works on Win8 / Win 2012 an above)");
                return;
            }

            Out.WriteLine("******************** KernelAndClrMonitor DEMO (Win 8) ********************");
            Out.WriteLine("Printing both Kernel and CLR (user mode) events simultaneously");
            Out.WriteLine("The monitor will run for a maximum of {0} seconds", monitoringTimeSec);
            Out.WriteLine("Press Ctrl-C to stop monitoring early.");
            Out.WriteLine();
            Out.WriteLine("Start a .NET program to see some events!");
            Out.WriteLine();
            if (TraceEventSession.IsElevated() != true)
            {
                Out.WriteLine("Must be elevated (Admin) to run this program.");
                Debugger.Break();
                return;
            }

            TraceEventSession session = null;

            // Set up Ctrl-C to stop both user mode and kernel mode sessions
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs cancelArgs) =>
            {
                if (session != null)
                    session.Dispose();
                cancelArgs.Cancel = true;
            };

            // Set up a timer to stop processing after monitoringTimeSec
            var timer = new Timer(delegate(object state)
            {
                Out.WriteLine("Stopped Monitoring after {0} sec", monitoringTimeSec);
                if (session != null)
                    session.Dispose();
            }, null, monitoringTimeSec * 1000, Timeout.Infinite);

            // Create the new session to receive the events.
            // Because we are on Win 8 this single session can handle both kernel and non-kernel providers.
            using (session = new TraceEventSession("MonitorKernelAndClrEventsSession"))
            {
                // Enable the events we care about for the kernel
                // For this instant the session will buffer any incoming events.
                // Enabling kernel events must be done before anything else.
                // This will fail on Win7.
                Out.WriteLine("Enabling Image load, Process and Thread events.");
                session.EnableKernelProvider(
                    KernelTraceEventParser.Keywords.ImageLoad |
                    KernelTraceEventParser.Keywords.Process |
                    KernelTraceEventParser.Keywords.Thread);

                // Subscribe the events of interest.   In this case we just print all events.
                session.Source.Kernel.All += Print;

                Out.WriteLine("Enabling CLR GC and Exception events.");
                // Enable the events we care about for the CLR (in the user session).
                // unlike the kernel session, you can call EnableProvider on other things too.
                // For this instant the ;session will buffer any incoming events.
                session.EnableProvider(
                    ClrTraceEventParser.ProviderGuid,
                    TraceEventLevel.Informational,
                    (ulong)(ClrTraceEventParser.Keywords.GC | ClrTraceEventParser.Keywords.Exception));

                session.Source.Clr.All += Print;
#if DEBUG
                // in debug builds it is useful to see any unhandled events because they could be bugs.
                session.Source.UnhandledEvents += Print;
#endif
                // process events until Ctrl-C is pressed or timeout expires
                Out.WriteLine("Waiting for Events.");
                session.Source.Process();
            }

            timer.Dispose();    // Turn off the timer.
        }

        /// <summary>
        /// Print data.  Note that this method is called FROM DIFFERENT THREADS which means you need to properly
        /// lock any read-write data you access.   It turns out Out.WriteLine is already thread safe so
        /// there is nothing I have to do in this case.
        /// </summary>
        static void Print(TraceEvent data)
        {
            // There are a lot of data collection start on entry that I don't want to see (but often they are quite handy
            if (data.Opcode == TraceEventOpcode.DataCollectionStart)
                return;

            Out.WriteLine(data.ToString());
            if (data is UnhandledTraceEvent)
                Out.WriteLine(data.Dump());
        }
    }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Class SWException | simpleWorkflow</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?260161822" />
	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2015443609" />

				simpleWorkflow

Class

							Tree

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="" />
			<input type="hidden" name="ie" value="UTF-8" />
			<input type="text" name="q" class="search-query" placeholder="Search" />
		</form>

Classes

SWActiveRecord

SWActiveRecordBehavior

SWComponent

SWEvent

SWException

SWHelper

SWNode

SWPhpWorkflowSource

SWValidator

SWWorkflowSource

SWyEdConverter

SWyEdConverterDOM

Class SWException

Exception thrown by the simpleWorkflow behavior.

CException

SWException

		Located at SWException.php

Constants summary

			integer

					SW_ERR_ATTR_NOT_FOUND

			01

				#

			integer

					SW_ERR_REETRANCE

			02

				#

			integer

					SW_ERR_WRONG_TYPE

			03

				#

			integer

					SW_ERR_IN_WORKFLOW

			04

				#

			integer

					SW_ERR_CREATE_FAILS

			05

				#

			integer

					SW_ERR_WRONG_STATUS

			06

				#

			integer

					SW_ERR_WORKFLOW_NOT_FOUND

			07

				#

			integer

					SW_ERR_WORKFLOW_ID

			08

				#

			integer

					SW_ERR_NODE_NOT_FOUND

			09

				#

			integer

					SW_ERR_STATUS_UNREACHABLE

			10

				#

			integer

					SW_ERR_CREATE_NODE

			11

				#

			integer

					SW_ERR_MISSING_NODE_ID

			12

				#

		simpleWorkflow API documentation generated by ApiGen 2.8.0


text:
'use strict';

/**
 * @ngdoc function
 * @name app.controller:PlaySummaryCtrl
 * @description
 * # PlaySummaryCtrl
 * Controller of the app
 */
angular.module('app').controller('PlaySummaryCtrl', function (daoLottery, $routeParams, daoPlayer) {
  var vm = this;
  vm.lottery = daoLottery;
  vm.awardId = +$routeParams.awardId;
  vm.awardCount = daoLottery.awards.length;
  vm.luckyPlayers = _.filter(daoPlayer.items, function(player) {
    return !player.givenUp && player.awardId === vm.awardId;
  });
});


text:
package io.codearcs.candlestack.aws.rds;

import com.amazonaws.services.cloudwatch.model.Dimension;

import io.codearcs.candlestack.aws.cloudwatch.CloudWatchDimensions;

public class RDSCloudWatchDimensions extends CloudWatchDimensions {

	public void setClusterDimension( String value ) {
		dimensions.add( new Dimension().withName( "DBClusterIdentifier" ).withValue( value ) );
	}

	public void setInstanceDimension( String value ) {
		dimensions.add( new Dimension().withName( "DBInstanceIdentifier" ).withValue( value ) );
	}

	public void setEngineDimension( String value ) {
		dimensions.add( new Dimension().withName( "EngineName" ).withValue( value ) );
	}

}


text:
import $add from './add/index.js';
import $drop from './drop/index.js';
import $override from './override/index.js';
import $pop from './pop/index.js';
import $remove from './remove/index.js';
import $set from './set/index.js';
import $shift from './shift/index.js';
import $unshift from './unshift/index.js';

export {
    $add,
    $drop,
    $override,
    $pop,
    $remove,
    $set,
    $shift,
    $unshift
};


text:
This web part lists all the automated Flows associated with a SharePoint List/ Library. Basic flow information like Flow Name, Flow Trigger, Flow shared Type and Flow URL are displayed.

![Check List Flows](./assets/CheckFlows.gif)

**Note:**
The web part only displays the flows which are shared with the current user and reside in the default environment.

## Used SharePoint Framework Version

![version](https://img.shields.io/badge/version-1.9.1-green.svg)

## Minimal Path to Awesome

- git clone the repo
- npm i
- gulp bundle --ship
- gulp package-solution --ship
- Add to Site Collection App Catalog and Install the App
- Add the web part to any page in the Site Collection

## Solution

Solution|Author(s)
--------|---------
react-check-flows|Aakash Bhardwaj

## Disclaimer

**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

---
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-check-flows" />


text:
public class Test {
    public Object foo() {
        Object result = null;       // line1
        <selection>if (test1()) return result;
        if (test2()) return result;</selection>
        if (test3()) return result;  // line4
        return result;
    }

    public int foo1() {
        Object result = null;       // line1
        if (test1()) return 1; // ssss
        if (test2()) return 1; //eee
        if (test3()) return 2;  // line4
        return 3;
    }

    private boolean test1() {
        return false;
    }

    private boolean test2() {
        return false;
    }

    private boolean test3() {
        return false;
    }
}


text:
title:
  "Setting Up your Development Environment for Building a Genetic Adversarial
  Network"
date: 2019-01-19T11:11:06Z
desc:
  Learn what it takes to set up the development environment you need to get
  started with Generative Adversarial Networks
author: Josh Kalin
twitter: https://amzn.to/2SYiQrA
series: python
image: python.svg
tags:
  - data-science
authorImage: https://images.tutorialedge.net/images/logo.svg
---

What's a development environment? Everyone thinks setting up
a development environment needs to be this incredibly arduous process. The
installation process could be worse. It's actually quite simple and this article
intends to show you the basics.

# Getting ready

Let's lay out the requirements for the equipment you'll need:

- GPU: 10 series CUDA-enabled Nidea GPU
- Operating system: Ubuntu Linux 16.04+
- CPU/RAM: i5 or i7 with at least 8 GB of RAM

First and foremost, the GPU is a requirement. Although these algorithms can
technically train on a CPU, it could take days in some cases for a single model
to converge. It can take a GPU a day or more to converge in some instances. GPUs
offer an immense computational power increase over CPUs and are hence a
necessity. It's easy today to find a laptop with a 1,060 or better in it for
around \$900.

Ubuntu is the typical operating system for this type of development. This
article will assume Ubuntu and Bash as the default interaction with the
operating system.

# How to do it...

There are a few common steps that will need to be for each new developer—these
steps will be addressed in the following subsections.

# Installing the NVIDIA driver for your GPU

Installing the correct NVIDIA driver is incredibly important. A key component
is the usage of CUDA in TensorFlow. NVIDIA has this description for
the CUDA library:

> **"CUDA®** is a parallel computing platform and programming model developed by
> NVIDIA for general computing on graphical processing units (GPUs). With CUDA,
> developers are able to dramatically speed up computing applications by
> harnessing the power of GPUs."
> (Source: `https://developer.nvidia.com/cuda-zone`).

Using CUDA, TensorFlow can achieve drastic speedups in terms of processing
power. In order to make this happen, we need to have a certain type of GPU and
driver installed on the host machine.

So, let's start installing the things that we require.

In this section, a recommended driver will be specified and a few options for
installation will be proposed. It's hard to ensure that the installation will be
the same for each developer because the installation can vary for each machine
it's installed on. Instead, we'll show some methods on how to get it done but
will rely on you to figure out the nitty-gritties for their application.

You can run the nvidia-smi command to know which version of driver is installed
on your system.

The following is an example of the nvidia-smi command:

![nvidia-smi-command](https://images.tutorialedge.net/images/python/data-science/setting-dev-env-building-gan/image1-17.png)

The output of nvidia-smi will show your GPU any processes you have running and
the current driver version installed.

# Installing Nvidia-Docker

The following is an Nvidia-Docker hierarchy that you need to understand before
installing it:

![nvidia-docker](https://images.tutorialedge.net/images/python/data-science/setting-dev-env-building-gan/image2-19.png)

What is Docker? According to the Docker website, the keyword for it
is lightweight. Docker containers running on a single machine share that
machine's operating system kernel; they start instantly and use less compute and
RAM. Images are constructed from filesystem layers and share common files
(source: https://www.docker.com/what-container).

Essentially, Docker allows us to create a lightweight Virtual Machine (VM) in a
container where we can house all of our applications and guarantee that the
environment is going to be the same every time we enter this container.

NVIDIA-Docker goes one step further and provides the appropriate linkage for our
Docker containers to be able to interact with a GPU. This is a critical piece
for our development environment. Once we have NVIDIA-Docker set up, the rest of
the environment is fairly straightforward to integrate.

The installation is easy. It's recommended that you visit the website and ensure
that the directions haven't changed since
publication: https://github.com/NVIDIA/nvidia-docker. At this time,
NVIDIA-Docker2 is the latest version of development. When you install the
NVIDIA-Docker2 system with these steps, it should allow you to upgrade
periodically with  sudo apt upgrade.

When going to the website, you should see a set of instructions similar to this
one:

```dockerfile
Ubuntu 14.04/16.04/18.04, Debian Jessie/Stretch
# If you have nvidia-docker 1.0 installed: we need to remove it and all existing GPU containers
docker volume ls -q -f driver=nvidia-docker | xargs -r -I{} -n1 docker ps -q -a -f volume={} | xargs -r docker rm -f
sudo apt-get purge -y nvidia-docker

# Add the package repositories
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \
  sudo apt-key add -
distribution=$(. /etc/os-release;echo$ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
  sudo tee /etc/apt/sources.list.d/nvidia-docker.list
sudo apt-get update

# Install nvidia-docker2 and reload the Docker daemon configuration
sudo apt-get install -y nvidia-docker2
sudo pkill -SIGHUP dockerd

# Test nvidia-smi with the latest official CUDA image
docker run --runtime=nvidia --rm nvidia/cuda nvidia-smi
```

> **Note -** The instructions source is found
> at: https://github.com/NVIDIA/nvidia-docker.

Now, let's go over each of these commands in detail.

# Purging all older versions of Docker

First things first—you have to wipe out all the old versions of Docker prior to
this installation. The folks maintaining this repository conveniently provided a
few commands. The first command removes all old versions of Docker:

```s
$ docker volume ls -q -f driver=nvidia-docker | xargs -r -I{} -n1 docker ps -q -a -f volume={} | xargs -r docker rm -f
```

After completing this command, the next step is to use the purge method
in apt-get to remove any previous installations of NVIDIA-Docker from your
previous work:

```s
$ sudo apt-get purge -y nvidia-docker
```

Here, we've completed our step 1 installation!

# Adding package repositories

Now that you've removed all of the older versions of NVIDIA-Docker, it's time to
add the keys and repository to the typical apt-get repositories that you can
pull from. First, in the Installing NVIDIA-Docker recipe, you need to add the
appropriate key for apt-get to communicate with the NVIDIA-Docker repository:

```s
$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \
  sudo apt-key add -
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
```

After adding the key, add the repo to the sources that apt-get can pull from
when installing packages:

```s
$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
  sudo tee /etc/apt/sources.list.d/nvidia-docker.list
```

Finally, an apt-get update allows apt-get to update its list of installable
packages. Since we just added a new repository, the update will allow us to
install the NVIDIA-Docker repository in the next step:

```s
sudo apt-get update
```

Now we move on to the next step.

# Installing NVIDIA-Docker2 and reloading the daemon

This is the point you've been waiting for! (Probably not.) Use apt-get to
install the nvidia-docker2 package:

```s
sudo apt-get install -y nvidia-docker2
```

Next, use pkill to restart the Docker daemon after the installation:

```s
$ sudo pkill -SIGHUP dockerd
```

Now, you're ready for a simple test of the installation.

# Testing nvidia-smi through the Docker container

This is the moment of truth—if this command runs correctly, you should see
the nvidia-smi output that you see on your machine outside of the container:
docker run --runtime=nvidia --rm nvidia/cuda nvidia-smi Your output should look
similar to the nvidia-smi command example we showed in the Installing NVIDIA
driver for your GPU section:

![](https://images.tutorialedge.net/images/python/data-science/setting-dev-env-building-gan/image3-21.png)

Now you're ready to move onto actually building a development environment.

# Building a container for development

What's a container? A container is Docker's name for a VM with a certain
configuration of operating system and software. Docker containers allow you the
flexibility to have a different development environment for every new project
with minimal downtime.

This section will simply explain a small example Dockerfile to give you an idea
of how powerful these particular tools are. Here's the example we are going to
cover:

```dockerfile
FROM nvidia/cuda:9.0-cudnn7-devel-ubuntu16.04
ARG KERAS=2.2.0
ARG TENSORFLOW=1.8.0

# Update the repositories within the container

RUN apt-get update

# Install Python 2 and 3 + our basic dev tools

RUN apt-get install -y \
          python-dev \
          python3-dev \
          curl \
          git \
          vim

# Install pip

RUN curl -O https://bootstrap.pypa.io/get-pip.py && \
         python get-pip.py && \
         rm get-pip.py

# Install Tensorflow and Keras

RUN pip --no-cache-dir install \
         tensorflow_gpu==${TENSORFLOW} \
         keras==${KERAS}
```

This is the basics of how you will build a basic image, called base_image.

> **Note -** Here are a few topics to cover in case you are curious about how
> the RUN commands work in
> Dockerfiles: https://docs.docker.com/engine/reference/run/.

# Conclusion

If you enjoyed reading this article and are curious about building GANs, you can
explore [Generative Adversarial Networks Cookbook](https://amzn.to/2SYiQrA).
With over 100 recipes to build generative models using Python, TensorFlow, and
Keras, Generative Adversarial Networks Cookbook is a must-read for data
scientists, machine learning developers, and deep learning practitioners looking
for a quick reference to tackle challenges and tasks in the GAN domain.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>get_cmake_property — CMake 3.8.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="get_directory_property" href="get_directory_property.html" />
    <link rel="prev" title="function" href="function.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-commands(7) »

get_cmake_property¶

Get a global property of the CMake instance.

get_cmake_property(VAR property)

Get a global property from the CMake instance.  The value of the property is
stored in the variable VAR.  If the property is not found, VAR
will be  set to “NOTFOUND”.  See the cmake-properties(7) manual
for available properties.

See also the get_property() command GLOBAL option.

In addition to global properties, this command (for historical reasons)
also supports the VARIABLES and MACROS directory
properties.  It also supports a special COMPONENTS global property that
lists the components given to the install() command.

Previous topic

function

Next topic

get_directory_property

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-commands(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
<?php

/**
 * PEAR_Sniffs_NamingConventions_ValidClassNameSniff.
 *
 * Ensures class and interface names start with a capital letter
 * and use _ separators.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   Release: 1.3.3
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class PEAR_Sniffs_NamingConventions_ValidClassNameSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(
                T_CLASS,
                T_INTERFACE,
               );

    }//end register()

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The current file being processed.
     * @param int                  $stackPtr  The position of the current token
     *                                        in the stack passed in $tokens.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $className = $phpcsFile->findNext(T_STRING, $stackPtr);
        $name      = trim($tokens[$className]['content']);
        $errorData = array(ucfirst($tokens[$stackPtr]['content']));

        // Make sure the first letter is a capital.
        if (preg_match('|^[A-Z]|', $name) === 0) {
            $error = '%s name must begin with a capital letter';
            $phpcsFile->addError($error, $stackPtr, 'StartWithCaptial', $errorData);
        }

        // Check that each new word starts with a capital as well, but don't
        // check the first word, as it is checked above.
        $validName = true;
        $nameBits  = explode('_', $name);
        $firstBit  = array_shift($nameBits);
        foreach ($nameBits as $bit) {
            if ($bit === '' || $bit{0} !== strtoupper($bit{0})) {
                $validName = false;
                break;
            }
        }

        if ($validName === false) {
            // Strip underscores because they cause the suggested name
            // to be incorrect.
            $nameBits = explode('_', trim($name, '_'));
            $firstBit = array_shift($nameBits);
            if ($firstBit === '') {
                $error = '%s name is not valid';
                $phpcsFile->addError($error, $stackPtr, 'Invalid', $errorData);
            } else {
                $newName = strtoupper($firstBit{0}).substr($firstBit, 1).'_';
                foreach ($nameBits as $bit) {
                    if ($bit !== '') {
                        $newName .= strtoupper($bit{0}).substr($bit, 1).'_';
                    }
                }

                $newName = rtrim($newName, '_');
                $error   = '%s name is not valid; consider %s instead';
                $data    = $errorData;
                $data[]  = $newName;
                $phpcsFile->addError($error, $stackPtr, 'Invalid', $data);
            }
        }//end if

    }//end process()

}//end class

?>


text:
package syslinux

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/url"
	"path"
	"path/filepath"
	"strings"

	"github.com/u-root/u-root/pkg/boot"
	"github.com/u-root/u-root/pkg/boot/multiboot"
	"github.com/u-root/u-root/pkg/curl"
	"github.com/u-root/u-root/pkg/uio"
)

func probeIsolinuxFiles() []string {
	files := make([]string, 0, 10)
	// search order from the syslinux wiki
	// http://wiki.syslinux.org/wiki/index.php?title=Config
	// TODO: do we want to handle extlinux too ?
	dirs := []string{
		"boot/isolinux",
		"isolinux",
		"boot/syslinux",
		"syslinux",
		"",
	}
	confs := []string{
		"isolinux.cfg",
		"syslinux.cfg",
	}
	for _, dir := range dirs {
		for _, conf := range confs {
			if dir == "" {
				files = append(files, conf)
			} else {
				files = append(files, filepath.Join(dir, conf))
			}
		}
	}
	return files
}

// ParseLocalConfig treats diskDir like a mount point on the local file system
// and finds an isolinux config under there.
func ParseLocalConfig(ctx context.Context, diskDir string) ([]boot.OSImage, error) {
	rootdir := &url.URL{
		Scheme: "file",
		Path:   diskDir,
	}

	for _, relname := range probeIsolinuxFiles() {
		dir, name := filepath.Split(relname)

		// "When booting, the initial working directory for SYSLINUX /
		// ISOLINUX will be the directory containing the initial
		// configuration file."
		//
		// https://wiki.syslinux.org/wiki/index.php?title=Config#Working_directory
		imgs, err := ParseConfigFile(ctx, curl.DefaultSchemes, name, rootdir, dir)
		if curl.IsURLError(err) {
			continue
		}
		return imgs, err
	}
	return nil, fmt.Errorf("no valid syslinux config found on %s", diskDir)
}

// ParseConfigFile parses a Syslinux configuration as specified in
// http://www.syslinux.org/wiki/index.php?title=Config
//
// Currently, only the APPEND, INCLUDE, KERNEL, LABEL, DEFAULT, and INITRD
// directives are partially supported.
//
// `s` is used to fetch any files that must be parsed or provided.
//
// rootdir is the partition mount point that syslinux is operating under.
// Parsed absolute paths will be interpreted relative to the rootdir.
//
// wd is a directory within rootdir that is the current working directory.
// Parsed relative paths will be interpreted relative to rootdir + "/" + wd.
//
// For PXE clients, rootdir will be the the URL without the path, and wd the
// path component of the URL (e.g. rootdir = http://foobar.com, wd =
// barfoo/pxelinux.cfg/).
func ParseConfigFile(ctx context.Context, s curl.Schemes, configFile string, rootdir *url.URL, wd string) ([]boot.OSImage, error) {
	p := newParser(rootdir, wd, s)
	if err := p.appendFile(ctx, configFile); err != nil {
		return nil, err
	}

	// Assign the right label to display to users.
	for label, displayLabel := range p.menuLabel {
		if e, ok := p.linuxEntries[label]; ok {
			e.Name = displayLabel
		}
		if e, ok := p.mbEntries[label]; ok {
			e.Name = displayLabel
		}
	}

	// Intended order:
	//
	// 1. nerfDefaultEntry
	// 2. defaultEntry
	// 3. labels in order they appeared in config
	if len(p.labelOrder) == 0 {
		return nil, nil
	}
	if len(p.defaultEntry) > 0 {
		p.labelOrder = append([]string{p.defaultEntry}, p.labelOrder...)
	}
	if len(p.nerfDefaultEntry) > 0 {
		p.labelOrder = append([]string{p.nerfDefaultEntry}, p.labelOrder...)
	}
	p.labelOrder = dedupStrings(p.labelOrder)

	var images []boot.OSImage
	for _, label := range p.labelOrder {
		if img, ok := p.linuxEntries[label]; ok && img.Kernel != nil {
			images = append(images, img)
		}
		if img, ok := p.mbEntries[label]; ok && img.Kernel != nil {
			images = append(images, img)
		}
	}
	return images, nil
}

func dedupStrings(list []string) []string {
	var newList []string
	seen := make(map[string]struct{})
	for _, s := range list {
		if _, ok := seen[s]; !ok {
			seen[s] = struct{}{}
			newList = append(newList, s)
		}
	}
	return newList
}

type parser struct {
	// linuxEntries is a map of label name -> label configuration.
	linuxEntries map[string]*boot.LinuxImage
	mbEntries    map[string]*boot.MultibootImage

	// labelOrder is the order of label entries in linuxEntries.
	labelOrder []string

	// menuLabel are human-readable labels defined by the "menu label" directive.
	menuLabel map[string]string

	defaultEntry     string
	nerfDefaultEntry string

	// parser internals.
	globalAppend string
	scope        scope
	curEntry     string
	wd           string
	rootdir      *url.URL
	schemes      curl.Schemes
}

type scope uint8

const (
	scopeGlobal scope = iota
	scopeEntry
)

// newParser returns a new PXE parser using working directory `wd`
// and schemes `s`.
//
// If a path encountered in a configuration file is relative instead of a full
// URL, `wd` is used as the "working directory" of that relative path; the
// resulting URL is roughly `wd.String()/path`.
//
// `s` is used to get files referred to by URLs.
func newParser(rootdir *url.URL, wd string, s curl.Schemes) *parser {
	return &parser{
		linuxEntries: make(map[string]*boot.LinuxImage),
		mbEntries:    make(map[string]*boot.MultibootImage),
		scope:        scopeGlobal,
		wd:           wd,
		rootdir:      rootdir,
		schemes:      s,
		menuLabel:    make(map[string]string),
	}
}

func parseURL(name string, rootdir *url.URL, wd string) (*url.URL, error) {
	u, err := url.Parse(name)
	if err != nil {
		return nil, fmt.Errorf("could not parse URL %q: %v", name, err)
	}

	// If it parsed, but it didn't have a Scheme or Host, use the working
	// directory's values.
	if len(u.Scheme) == 0 && rootdir != nil {
		u.Scheme = rootdir.Scheme

		if len(u.Host) == 0 {
			// If this is not there, it was likely just a path.
			u.Host = rootdir.Host

			// Absolute file names don't get the parent
			// directories, just the host and scheme.
			//
			// "All (paths to) file names inside the configuration
			// file are relative to the Working Directory, unless
			// preceded with a slash."
			//
			// https://wiki.syslinux.org/wiki/index.php?title=Config#Working_directory
			if path.IsAbs(name) {
				u.Path = path.Join(rootdir.Path, path.Clean(u.Path))
			} else {
				u.Path = path.Join(rootdir.Path, wd, path.Clean(u.Path))
			}
		}
	}
	return u, nil
}

// getFile parses `url` relative to the config's working directory and returns
// an io.Reader for the requested url.
//
// If url is just a relative path and not a full URL, c.wd is used as the
// "working directory" of that relative path; the resulting URL is roughly
// path.Join(wd.String(), url).
func (c *parser) getFile(url string) (io.ReaderAt, error) {
	u, err := parseURL(url, c.rootdir, c.wd)
	if err != nil {
		return nil, err
	}

	return c.schemes.LazyFetch(u)
}

// appendFile parses the config file downloaded from `url` and adds it to `c`.
func (c *parser) appendFile(ctx context.Context, url string) error {
	u, err := parseURL(url, c.rootdir, c.wd)
	if err != nil {
		return err
	}

	r, err := c.schemes.Fetch(ctx, u)
	if err != nil {
		return err
	}
	config, err := uio.ReadAll(r)
	if err != nil {
		return err
	}
	log.Printf("Got config file %s:\n%s\n", r, string(config))
	return c.append(ctx, string(config))
}

// Append parses `config` and adds the respective configuration to `c`.
func (c *parser) append(ctx context.Context, config string) error {
	// Here's a shitty parser.
	for _, line := range strings.Split(config, "\n") {
		// This is stupid. There should be a FieldsN(...).
		kv := strings.Fields(line)
		if len(kv) <= 1 {
			continue
		}
		directive := strings.ToLower(kv[0])
		var arg string
		if len(kv) == 2 {
			arg = kv[1]
		} else {
			arg = strings.Join(kv[1:], " ")
		}

		switch directive {
		case "default":
			c.defaultEntry = arg

		case "nerfdefault":
			c.nerfDefaultEntry = arg

		case "include":
			if err := c.appendFile(ctx, arg); curl.IsURLError(err) {
				log.Printf("failed to parse %s: %v", arg, err)
				// Means we didn't find the file. Just ignore
				// it.
				// TODO(hugelgupf): plumb a logger through here.
				continue
			} else if err != nil {
				return err
			}

		case "menu":
			opt := strings.Fields(arg)
			if len(opt) < 1 {
				continue
			}
			switch strings.ToLower(opt[0]) {
			case "label":
				// Note that "menu label" only changes the
				// displayed label, not the identifier for this
				// entry.
				//
				// We track these separately because "menu
				// label" directives may happen before we know
				// whether this is a Linux or Multiboot entry.
				c.menuLabel[c.curEntry] = strings.Join(opt[1:], " ")

			case "default":
				// Are we in label scope?
				//
				// "Only valid after a LABEL statement" -syslinux wiki.
				if c.scope == scopeEntry {
					c.defaultEntry = c.curEntry
				}
			}

		case "label":
			// We forever enter label scope.
			c.scope = scopeEntry
			c.curEntry = arg
			c.linuxEntries[c.curEntry] = &boot.LinuxImage{
				Cmdline: c.globalAppend,
				Name:    c.curEntry,
			}
			c.labelOrder = append(c.labelOrder, c.curEntry)

		case "kernel":
			// I hate special cases like these, but we aren't gonna
			// implement syslinux modules.
			if arg == "mboot.c32" {
				// Prepare for a multiboot kernel.
				delete(c.linuxEntries, c.curEntry)
				c.mbEntries[c.curEntry] = &boot.MultibootImage{
					Name: c.curEntry,
				}
			}
			fallthrough

		case "linux":
			if e, ok := c.linuxEntries[c.curEntry]; ok {
				k, err := c.getFile(arg)
				if err != nil {
					return err
				}
				e.Kernel = k
			}

		case "initrd":
			if e, ok := c.linuxEntries[c.curEntry]; ok {
				// TODO: append "initrd=$arg" to the cmdline.
				//
				// For how this interacts with global appends,
				// read
				// https://wiki.syslinux.org/wiki/index.php?title=Directives/append
				// Multiple initrds are comma-separated
				var initrds []io.ReaderAt
				for _, f := range strings.Split(arg, ",") {
					i, err := c.getFile(f)
					if err != nil {
						return err
					}
					initrds = append(initrds, i)
				}
				e.Initrd = boot.CatInitrds(initrds...)
			}

		case "append":
			switch c.scope {
			case scopeGlobal:
				c.globalAppend = arg

			case scopeEntry:
				if e, ok := c.mbEntries[c.curEntry]; ok {
					modules := strings.Split(arg, "---")
					// The first module is special -- the kernel.
					if len(modules) > 0 {
						kernel := strings.Fields(modules[0])
						k, err := c.getFile(kernel[0])
						if err != nil {
							return err
						}
						e.Kernel = k
						if len(kernel) > 1 {
							e.Cmdline = strings.Join(kernel[1:], " ")
						}
						modules = modules[1:]
					}
					for _, cmdline := range modules {
						m := strings.Fields(cmdline)
						if len(m) == 0 {
							continue
						}
						file, err := c.getFile(m[0])
						if err != nil {
							return err
						}
						e.Modules = append(e.Modules, multiboot.Module{
							Cmdline: strings.TrimSpace(cmdline),
							Module:  file,
						})
					}
				}
				if e, ok := c.linuxEntries[c.curEntry]; ok {
					if arg == "-" {
						e.Cmdline = ""
					} else {
						// Yes, we explicitly _override_, not
						// concatenate. If a specific append
						// directive is present, a global
						// append directive is ignored.
						//
						// Also, "If you enter multiple APPEND
						// statements in a single LABEL entry,
						// only the last one will be used".
						//
						// https://wiki.syslinux.org/wiki/index.php?title=Directives/append
						e.Cmdline = arg
					}
				}
			}
		}
	}

	// Go through all labels and download the initrds.
	for _, label := range c.linuxEntries {
		// If the initrd was set via the INITRD directive, don't
		// overwrite that.
		//
		// TODO(hugelgupf): Is this really what syslinux does? Does
		// INITRD trump cmdline? Does it trump global? What if both the
		// directive and cmdline initrd= are set? Does it depend on the
		// order in the config file? (My current best guess: order.)
		//
		// Answer: Normally, the INITRD directive appends to the
		// cmdline, and the _last_ effective initrd= parameter is used
		// for loading initrd files.
		if label.Initrd != nil {
			continue
		}

		for _, opt := range strings.Fields(label.Cmdline) {
			optkv := strings.Split(opt, "=")
			if optkv[0] != "initrd" {
				continue
			}

			i, err := c.getFile(optkv[1])
			if err != nil {
				return err
			}
			label.Initrd = i
		}
	}
	return nil

}


text:
module Angular
  class FactoryGenerator < RailsAngularCreator::FileGenerator
  end
end


text:
Fetch Glass Timeline Items
=============================
This code shows how to fetch shared timeline cards from your user's Glass

It is intended as a complement to my tutorial:
http://20missionglass.tumblr.com/post/70635819823/fetch-glass-timeline-items

Configuration
--------------
Set up an OAuth2 Client App in the Google Code Console:
https://code.google.com/apis/console/

Once you register an app, create  you will get a client id and client secret.
You will also need to create a Browser API Key for the Google Maps API.

Edit your settings.php to reflect your oauth2 client app's settings.

$settings['oauth2']['oauth2_client_id'] = 'YOURCLIENTID.apps.googleusercontent.com';
$settings['oauth2']['oauth2_secret'] = 'YOURCLIENTSECRET';
$settings['oauth2']['oauth2_redirect'] = 'https://example.com/oauth2callback';

Now you should be good to go.


text:
<?php
/**
 * VehicleTypeDeleteNotFoundResponseTest
 *
 * PHP version 5
 *
 * @category Class
 * @package  BumbalClient
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Bumbal Client Api
 *
 * Bumbal API documentation
 *
 * OpenAPI spec version: 2.0
 * Contact: gerb@bumbal.eu
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace BumbalClient;

/**
 * VehicleTypeDeleteNotFoundResponseTest Class Doc Comment
 *
 * @category    Class */
// * @description VehicleTypeDeleteNotFoundResponse
/**
 * @package     BumbalClient
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class VehicleTypeDeleteNotFoundResponseTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass()
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {
    }

    /**
     * Test "VehicleTypeDeleteNotFoundResponse"
     */
    public function testVehicleTypeDeleteNotFoundResponse()
    {
    }

    /**
     * Test attribute "code"
     */
    public function testPropertyCode()
    {
    }

    /**
     * Test attribute "message"
     */
    public function testPropertyMessage()
    {
    }
}


text:
package dao;

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

import models.Article;
import models.ArticleDto;
import models.ArticlesDto;
import models.User;

import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.googlecode.objectify.Objectify;

public class ArticleDao {

    @Inject
    Provider<Objectify> objectify;

    public ArticlesDto getAllArticles() {

        ArticlesDto articlesDto = new ArticlesDto();
        articlesDto.articles = objectify.get().load().type(Article.class).list();

        return articlesDto;

    }

    public Article getFirstArticleForFrontPage() {

        Article frontPost = objectify.get().load().type(Article.class).order("-postedAt").first()
                .now();
        return frontPost;

    }

    public List<Article> getOlderArticlesForFrontPage() {

        List<Article> olderPosts = objectify.get().load().type(Article.class).order("-postedAt")
                .offset(1).limit(10).list();

        return olderPosts;

    }

    public Article getArticle(Long id) {

        Article article = objectify.get().load().type(Article.class).id(id).now();

        return article;

    }

    /**
     * Returns false if user cannot be found in database.
     */
    public boolean postArticle(String username, ArticleDto articleDto) {

        User user = objectify.get().load().type(User.class).filter("username", username).first().now();

        if (user == null) {
            return false;
        }

        Article article = new Article(user, articleDto.title, articleDto.content);
        objectify.get().save().entity(article);

        return true;

    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sem. hort. bot. hamburg. 1825:17. 1825

#### Original name
null

### Remarks
null


text:
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
	var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

	return {
		x: centerX + (radius * Math.cos(angleInRadians)),
		y: centerY + (radius * Math.sin(angleInRadians))
	};
}

function describeArc(x, y, radius, startAngle, endAngle) {

	var start = polarToCartesian(x, y, radius, endAngle);
	var end = polarToCartesian(x, y, radius, startAngle);

	var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";

	return [
		"M", start.x, start.y,
		"A", radius, radius, 0, arcSweep, 0, end.x, end.y
	].join(" ");
}

//===============================================================

var RadialMenu = React.createClass({
	displayName: "RadialMenu",
	propTypes: {
		list: React.PropTypes.object,
		onClick: React.PropTypes.func,
		onClickOutside: React.PropTypes.func,
		selectedIndex: React.PropTypes.number
	},
	getDefaultProps() {
		return {
			selectedIndex: undefined
		}
	},
	onClickItem(item, index) {
		this.props.onClick(item, index);
	},
	onClickOutside() {
		this.props.onClickOutside && this.props.onClickOutside();
	},
	buildArcParams(list, item, index) {
		var centralAngle = 360 / list.size;
		centralAngle = centralAngle > 90 ? 90 : centralAngle;
		return {
			startAngle: index * centralAngle,
			endAngle: (index + 1) * centralAngle
		}
	},
	buildMenuCenter(props, state) {
		var item = props.list.get(props.selectedIndex);
		return item ? (

				{item.get("img") && }

					{item.get("title")}

		) : (

					{"Please select an option"}

		)
	},
	buildRadialMenu(props, state) {
		return (

					{this.buildMenuCenter(this.props, this.state)}
					<svg xmlSpace="http://www.w3.org/2000/svg" width="100%" height="100%" className="b-radialmenu-core">
						<defs>
							<clipPath id="circleMask">
								<circle cx="50" cy="50" r="50"/>
							</clipPath>
						</defs>
						<svg x="0" y="0" viewBox="0 0 100 100" width="100%" height="100%">
							<rect width="100" height="100" opacity="0" onClick={this.onClickOutside}/>
							<g className="item-list">
								{
									props.list.map((item, index)=> {
										let itemClass = cx({
											"item-svg": true,
											"-active": index == props.selectedIndex
										});
										let arcParams = this.buildArcParams(props.list, item, index);
										return (
											<g className={itemClass} key={index}>
												<defs>
													<pattern id={"thumb-" + index} patternUnits="objectBoundingBox" width="100%"
																	 height="100%">
														<image xlinkHref={item.get("img")} width="50" height="50"/>
													</pattern>
												</defs>
												<path className="item-shape" onClick={(e)=>{this.onClickItem(item,index)}}
															d={[describeArc(50,50,50,arcParams.startAngle,arcParams.endAngle),"L", 50, 50,"Z"].join(" ")}
															fill={`url(#${"thumb-" + index})`} stroke="white" strokeWidth="0.5">
												</path>
											</g>
										)
									})
								}
							</g>
						</svg>
					</svg>

		)
	},
	render() {
		return this.buildRadialMenu(this.props, this.state);
	}
});

module.exports = RadialMenu;


text:
import numpy as np

from pynitefields import *

class LatinSquare():
    """ Class to hold a Latin square.

        A Latin square L is computed from a curve :math:`c` according to:

        .. math::
                    L(\\alpha, \\beta) = \\alpha + c(\\beta)

        Args:
            curve (Curve): The curve with which to create the Latin square.

        Attributes:
            p (int): Prime dimension
            n (int): Power of prime
            dim (int): The dimension of the system :math:`p^n`
            curve (Curve): The curve with which this square was made
            square (array): The actual square (stored as a numpy array)
    """

    def __init__(self, curve):
        # Set some obvious parameters
        self.dim = self.field.dim
        self.curve = curve

        self.square = np.zeros((self.dim, self.dim), dtype=np.int)

        for row in range(self.dim):
            for column in range(self.dim):
                row_el = curve[row][1]
                col_el = curve[column][0]
                self.square[row][column] = (row_el + col_el).prim_power

    def print(self):
        """ Prints the Latin square.
        """
        print(self.square)


text:
package com.siyeh.igtest.style.unnecessary_enum_modifier;

public enum UnnecessaryEnumModifier {
    Red, Green, Blue;

    private UnnecessaryEnumModifier() {
    }

    static enum X {
      A, B, C
    }
}


text:
module.exports = class Twitter {
    constructor(requestBody) {
        this.requestBody = requestBody;
    }

    getDirectory() {
        return "source/_twitter";
    }

    getData() {
        const {
            text,
            createdAt,
            type,
            url,
            username,
            embedCode
        } = this.requestBody;

        return {
            frontmatter: {
                title: `Twitter: ${createdAt}`,
                text,
                createdAt,
                type,
                url,
                username,
                collectionName: "twitter"
            },
            body: embedCode
        };
    }
};


text:
define(['./htmlUnescapes'], function(htmlUnescapes) {

  /**
   * Used by `unescape` to convert HTML entities to characters.
   *
   * @private
   * @param {string} match The matched character to unescape.
   * @returns {string} Returns the unescaped character.
   */
  function unescapeHtmlChar(match) {
    return htmlUnescapes[match];
  }

  return unescapeHtmlChar;
});


text:
__doc__ = """

  bloombox: CLI tool

"""

from bloombox import Bloombox; Bloombox(autorun=True)


text:
#include "..\NuiRGBDDeviceManagerImpl.h"
#include "NuiKinectV1Grabber.h"
#include "NuiKinectV1FaceTracker.h"
#include "NuiKinectV1FusionGrabber.h"

// PCEKinectManager thread class
class NuiKinectV1Manager : public NuiRGBDDeviceManagerImpl
{
	static const NUI_IMAGE_RESOLUTION   cDepthResolution = NUI_IMAGE_RESOLUTION_640x480;
	static const NUI_IMAGE_RESOLUTION   cColorResolution = NUI_IMAGE_RESOLUTION_640x480;
public:
	NuiKinectV1Manager(NuiRGBDDeviceBufferImpl* pBuffer);
	virtual ~NuiKinectV1Manager();

	virtual bool		InitializeDevice(DWORD deviceFlag) override;
	virtual bool		IsDeviceOn() const override;
	virtual bool		StartDevice() override;
	virtual void		PauseDevice() override;
	virtual void		ShutdownDevice() override;

	virtual bool		UpdateNearMode(bool bNearMode) override;
	virtual void		UpdateElevationAngle(long tiltAngle) override;
	virtual void		UpdateSkeletonSmoothParams(float smoothing, float correction, float prediction, float jitterRadius, float maxDeviationRadius) override;

protected:
	/// <summary>
	/// Create the first connected Kinect found
	/// </summary>
	/// <returns>S_OK on success, otherwise failure code</returns>
	HRESULT				CreateFirstConnected();
	/// <summary>
	/// Coerce the requested elevation angle to a valid angle
	/// </summary>
	/// <param name="tiltAngle">The requested angle</param>
	/// <returns>The angle after coerced</returns>
	inline long			CoerceElevationAngle(long tiltAngle)
	{
		return std::min(std::max((long)NUI_CAMERA_ELEVATION_MINIMUM, tiltAngle), (long)NUI_CAMERA_ELEVATION_MAXIMUM);
	}

	void				updateCacheStatus();

	/// <summary>
	/// Called on Kinect device status changed. It will update the sensor chooser UI control
	/// based on the new sensor status. It may also updates the sensor instance if needed
	/// </summary>
	static void CALLBACK StatusChangeCallback(HRESULT hrStatus, const OLECHAR* instancename, const OLECHAR* uniqueDeviceName, void* pUserData);

private:
	INuiSensor*							m_pNuiSensor;
	NuiRGBDDeviceBufferImpl*				m_pBuffer;

	NuiKinectV1Grabber*					m_pGrabber;
	NuiKinectV1FaceTracker*				m_pFaceTracker;
	NuiKinectV1FusionGrabber*			m_pFusion;
};


text:
function [h ,theta, rho]=hough(f,dtheta,drho)
%compute the Hough transform of f. dtheta is spacing in degrees and drho is
%the spacing along rho axis. h is the hough transform, theta is a vector
%containing the values for theta and rho the value for rho for the matrix
%elements in h. If dtheta and drho are not specified 1 is used.

%check the number of arguments used
if nargin<3
    drho=1;
end
if nargin<2
    dtheta=1;
end
%generate the theta and rho vectors
f=double(f);
[M,N]=size(f);
theta=linspace(-90,0,ceil(90/dtheta)+1);
theta=[theta ,-fliplr(theta(2:end-1))];
ntheta=length(theta);

D=sqrt((M-1)^2+(N-1)^2);
q=ceil(D/drho);
nrho=2*q-1;
rho=linspace(-q*drho,q*drho,nrho);

%transform input into sparse array.
[x,y,val]=find(f);
x=x-1;
y=y-1;

%init output
h=zeros(nrho,length(theta));

%to save RAM process 1000 pixels at once
for k=1:ceil(length(val)/1000);
    first=(k-1)*1000+1;
    last=min(first+999,length(x));

    x_matrix =repmat(x(first:last),1,ntheta);
    y_matrix=repmat(y(first:last),1,ntheta);
    val_matrix=repmat(val(first:last),1,ntheta);
    theta_matrix=repmat(theta,size(x_matrix,1),1)*pi/180;
    rho_matrix=x_matrix.*cos(theta_matrix)+y_matrix.*sin(theta_matrix);
    slope=(nrho-1)/(rho(end)-rho(1));
    rho_bin_index=round(slope*(rho_matrix-rho(1))+1);
    theta_bin_index=repmat(1:ntheta,size(x_matrix,1),1);
    %Note that sparse accumulates values when the indices are repeated
    %full converts back to full matrix
    h=h+full(sparse(rho_bin_index(:), theta_bin_index(:),val_matrix(:),nrho,ntheta));
end


text:
import includes from 'lodash/includes'

class ContextMenuService {
  MENU_RATE_LIMIT = 'rateLimit'
  MENU_APPLY_ON_GITHUB_ISSUES = 'applyOnGithubIssues'

  constructor (ctx) {
    this.menuIds = []
  }

  upsert (id, options) {
    if (!includes(this.menuIds, id)) {
      chrome.contextMenus.create({id, ...options})
      this.menuIds.push(id)
    }
    chrome.contextMenus.update(id, options)
  }
}

export default ContextMenuService


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/automl/v1beta1/service.proto

package com.google.cloud.automl.v1beta1;

public interface ListModelEvaluationsResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.automl.v1beta1.ListModelEvaluationsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * List of model evaluations in the requested page.
   *

   *
   * repeated .google.cloud.automl.v1beta1.ModelEvaluation model_evaluation = 1;
   */
  java.util.List<com.google.cloud.automl.v1beta1.ModelEvaluation> getModelEvaluationList();
  /**
   *
   *
   *

   * List of model evaluations in the requested page.
   *

   *
   * repeated .google.cloud.automl.v1beta1.ModelEvaluation model_evaluation = 1;
   */
  com.google.cloud.automl.v1beta1.ModelEvaluation getModelEvaluation(int index);
  /**
   *
   *
   *

   * List of model evaluations in the requested page.
   *

   *
   * repeated .google.cloud.automl.v1beta1.ModelEvaluation model_evaluation = 1;
   */
  int getModelEvaluationCount();
  /**
   *
   *
   *

   * List of model evaluations in the requested page.
   *

   *
   * repeated .google.cloud.automl.v1beta1.ModelEvaluation model_evaluation = 1;
   */
  java.util.List<? extends com.google.cloud.automl.v1beta1.ModelEvaluationOrBuilder>
      getModelEvaluationOrBuilderList();
  /**
   *
   *
   *

   * List of model evaluations in the requested page.
   *

   *
   * repeated .google.cloud.automl.v1beta1.ModelEvaluation model_evaluation = 1;
   */
  com.google.cloud.automl.v1beta1.ModelEvaluationOrBuilder getModelEvaluationOrBuilder(int index);

  /**
   *
   *
   *

   * A token to retrieve next page of results.
   * Pass to the [ListModelEvaluationsRequest.page_token][google.cloud.automl.v1beta1.ListModelEvaluationsRequest.page_token] field of a new
   * [AutoMl.ListModelEvaluations][google.cloud.automl.v1beta1.AutoMl.ListModelEvaluations] request to obtain that page.
   *

   *
   * string next_page_token = 2;
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * A token to retrieve next page of results.
   * Pass to the [ListModelEvaluationsRequest.page_token][google.cloud.automl.v1beta1.ListModelEvaluationsRequest.page_token] field of a new
   * [AutoMl.ListModelEvaluations][google.cloud.automl.v1beta1.AutoMl.ListModelEvaluations] request to obtain that page.
   *

   *
   * string next_page_token = 2;
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Enumeratio plantarum 736. 1809

#### Original name
null

### Remarks
null


text:
<?php namespace App\Http\Controllers;

use App\Util\Access;
use App\Util\AppCodeGen;
use App\Util\MtHttp;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Auth;

class PermController extends Controller
{
    public function __construct(Request $request)
	{
		$this->request = $request;
		$this->middleware('auth');
	}

	public function index(Request $request)
	{
		$appcode = session('appcode');
		if ($appcode == null)
			return redirect('app');
		else
			return redirect('dashboard/' . $appcode);
	}

	public function app(Request $request)
	{
		$userid = Auth::user()->id;
		$apps = DB::table('apps')->join('user_app', 'apps.id', '=', 'user_app.appid')
			->where('user_app.userid', $userid)->get();

		foreach ($apps as $ap) {
			$ap->owner = \App\User::find($ap->ownerid);
			$ap->agencies = DB::table('user_app')->join('users', 'users.id', '=', 'user_app.userid')->where('user_app.appid', $ap->id)->get();
//			$ap->count = MtHttp::get('app/count_traffic/' . $ap->code);
		}

		return view('app/index', [
			'apps' => $apps
		]);
	}

	public function traffic14(Request $request, $appcode)
	{
        if(Access::can_view(Auth::user()->id, $appcode)==false) abort(500, "Access denied");
		$traffic = MtHttp::get('app/traffic14/' . $appcode);
		return $traffic;
	}

	public function setup_status(Request $request, $appcode)
	{
        if(Access::can_view(Auth::user()->id, $appcode)==false) abort(500, "Access denied");
		$res = MtHttp::getRaw('app/status/' . $appcode);
		return $res . '';
	}

	public function getPageview(Request $request, $appcode)
	{
        if(Access::can_view(Auth::user()->id, $appcode)==false) abort(500, "Access denied");
		$res = MtHttp::getRaw('app/getpageview/' . $appcode);
		return $res . '';
	}

	public function getSignup(Request $request, $appcode,$startime, $endtime)
	{
        if(Access::can_view(Auth::user()->id, $appcode)==false) abort(500, "Access denied");
		$queryurl = 'app/getsignup/' . $appcode;
			$pieces = explode("-", $startime);
			$sts = strtotime($pieces[1] . '/' . $pieces[2] . '/' . $pieces[0]);

			$pieces = explode("-", $endtime);
			$ets = strtotime($pieces[1] . '/' . $pieces[2] . '/' . $pieces[0]);
			$queryurl .= '/' . $sts . '/' . $ets;

		$res = MtHttp::getRaw($queryurl);
		return $res . '';
	}

	public function count_traffic(Request $request, $appcode)
	{
		$res = MtHttp::get('app/count_traffic/' . $appcode);
		return $res . '';
	}

	public function getedit(Request $request, $appcode)
	{
		$ap = DB::table('apps')->where('code', $appcode)->first();
		if ($ap == null) abort(500, 'cannot find app: ' . $appcode);

		$ap->owner = \App\User::find($ap->ownerid);
		$ap->agencies = DB::table('user_app')->join('users', 'users.id', '=', 'user_app.userid')->where('user_app.appid', $ap->id)->get();

		return view('app/edit', ['ap' => $ap, 'appcode' => $appcode]);
	}

	public function postedit(Request $request, $appcode)
	{
        if(Access::can_editStruct(Auth::user()->id, $appcode)==false) abort(500, "Access denied");
		$name = $request->input('name');
		$url = $request->input('url');

		if ($name == null || $name == '')
			abort(500, 'name must not be empty');

		$ap = DB::table('apps')->where('apps.code', $appcode)->first();
		if ($ap == null) abort(500, 'cannot find app: ' . $appcode);

		DB::table('apps')->where('id', $ap->id)->update(['name' => $name, 'url'=>$url]);

		return redirect('/');
	}

	public function set(Request $request, $appcode, $userid)
	{
		$uid = Auth::user()->id;
        if(Access::can_editPerm($uid, $appcode)==false) abort(500, "Access denied");
		$status = Access::setPerm($uid, $userid, $appcode, $request->input('can_perm'), $request->input('can_struct'), $request->input('can_report'));
		if ($status == 0)
			return new Response();
		else abort(403, 'Unauthorized action');
	}

	public static function createApp($uid, $name, $url ='')
	{
		if ($name == null || $name == '') abort(500, 'name must not be empty');

		// lock thread
		$out = AppCodeGen::alloc($name);
		$code = $out['code'];
		$mutex = $out['lock'];
		DB::table('apps')->insert(array(
				'name' => $name,
				'code' => $code,
				'ownerid' => $uid,
				'url'=>$url,
				'created_at'=>time()
			)
		);

		// unlock thread
		AppCodeGen::used($mutex);

		// create role for owner
		Access::setPerm($uid, $uid, $code, 1, 1, 1);
		// init app in backend
		MtHttp::get('app/init/' . $code);
		return $code;
	}

	public function create(Request $request)
	{
		$uid = \Auth::user()->id;
		$name = $request->input('name');
		$url = $request->input('url');
		$code = self::createApp($uid, $name,$url);
		return new Response($code);
	}

	public function delete(Request $request, $appcode, $userid)
	{
		$uid = \Auth::user()->id;
		if(Access::can_editPerm($uid, $appcode) == false) abort(500, "Permission denied");
        $status = Access::deletePerm($uid, $userid, $appcode);
		if ($status == 0)
			return new Response();
		else abort(403, 'Unauthorized action');
	}

	public function add(Request $request, $appcode)
	{
		$email = $request->input('email');
		$uid = \Auth::user()->id;
		if(Access::can_editPerm($uid, $appcode) == false) abort(300, "Permission denied");
		//get userid from email
		$user = DB::table('users')->where('email', $email)->first();
		if ($user == null) abort(300, 'user not found: ' . $email);
		$userid = $user->id;
		if ($userid == null)
			abort(300, 'cannot find user with email ' . $email);

		$status = Access::setPerm($uid, $userid, $appcode, null, null, null);
		if ($status == 0)
			return new Response();
		else abort(403, 'Unauthorized action');
	}

    public function manage(Request $request, $appcode){
        $ap = DB::table('apps')->where('code', $appcode)->first();
        if ($ap == null) abort(500, 'cannot find app: ' . $appcode);

        $ap->owner = \App\User::find($ap->ownerid);
        $ap->agencies = DB::table('user_app')->join('users', 'users.id', '=', 'user_app.userid')->where('user_app.appid', $ap->id)->get();
        $your_role = '';
        if($ap->agencies){
            foreach($ap->agencies as $ag){
                if($ag->appid != $ap->id || $ag->userid != $ap->ownerid){
                    continue;
                }
                if($ag->can_perm){
                    $your_role = 'Full control';
                    continue;
                }
                if($ag->can_struct){
                    $your_role = 'Edit app structure';
                    continue;
                }
                if($ag->can_report){
                    $your_role = 'Create or edit reports';
                    continue;
                }
            }
        }
        $status = $this->setup_status($request, $appcode) ? 'Connected' : 'Not connected';
        $traffic = $this->count_traffic($request, $appcode);
        return view('app/manage', [
            'ap' => $ap,
            'appcode' => $appcode,
            'status' => $status,
            'traffic' => $traffic,
            'your_role' => $your_role,
        ]);
    }

    public function postadd(Request $request, $appcode)
    {
        $name = $request->input('name');
        $url = $request->input('url');

        if ($name == null || $name == '')
            abort(500, 'name must not be empty');

        $ap = DB::table('apps')->where('apps.code', $appcode)->first();
        if ($ap == null) abort(500, 'cannot find app: ' . $appcode);

        DB::table('apps')->where('id', $ap->id)->update(['name' => $name, 'url'=>$url]);
        return json_encode([
            'success' => true,
            'name' => $name,
            'url' => $url
        ]);
    }
}


text:
package io.netty.handler.codec.memcache.binary;

import io.netty.util.internal.UnstableApi;

/**
 * Represents a full {@link BinaryMemcacheResponse}, which contains the header and optional key and extras.
 */
@UnstableApi
public interface BinaryMemcacheResponse extends BinaryMemcacheMessage {

    /**
     * Returns the status of the response.
     *
     * @return the status of the response.
     */
    short status();

    /**
     * Sets the status of the response.
     *
     * @param status the status to set.
     */
    BinaryMemcacheResponse setStatus(short status);

    @Override
    BinaryMemcacheResponse retain();

    @Override
    BinaryMemcacheResponse retain(int increment);

    @Override
    BinaryMemcacheResponse touch();

    @Override
    BinaryMemcacheResponse touch(Object hint);
}