text:
// <auto-generated/>
#pragma warning disable 1591
namespace Microsoft.AspNetCore.Hosting.Views
{
    #line hidden
    using System.Threading.Tasks;
#nullable restore
#line 1 "Views/ErrorPage.cshtml"
using System;

#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "Views/ErrorPage.cshtml"
using System.Globalization;

#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "Views/ErrorPage.cshtml"
using System.Linq;

#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "Views/ErrorPage.cshtml"
using System.Net;

#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "Views/ErrorPage.cshtml"
using System.Reflection;

#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "Views/ErrorPage.cshtml"
using Microsoft.AspNetCore.Hosting.Views;

#line default
#line hidden
#nullable disable
    internal sealed class ErrorPage : Microsoft.Extensions.RazorViews.BaseView
    {
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            WriteLiteral("\r\n");
#nullable restore
#line 17 "Views/ErrorPage.cshtml"

    var location = string.Empty;

#line default
#line hidden
#nullable disable
            WriteLiteral("<!DOCTYPE html>\r\n

        <meta charset=""utf-8"" />
        <title>Internal Server Error</title>

An error occurred while starting the application.

");
#nullable restore
#line 232 "Views/ErrorPage.cshtml"
         foreach (var errorDetail in Model.ErrorDetails)
        {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 234 "Views/ErrorPage.cshtml"
                               Write(errorDetail.Error!.GetType().Name);

#line default
#line hidden
#nullable disable
            WriteLiteral(": ");
#nullable restore
#line 234 "Views/ErrorPage.cshtml"
                                                                           Output.Write(HtmlEncodeAndReplaceLineBreaks(errorDetail.Error!.Message));

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 235 "Views/ErrorPage.cshtml"

            var firstFrame = errorDetail.StackFrames.FirstOrDefault();
            if (firstFrame != null)
            {
                location = firstFrame.Function;
            }
            if (!string.IsNullOrEmpty(location) && firstFrame != null && !string.IsNullOrEmpty(firstFrame.File))
            {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 243 "Views/ErrorPage.cshtml"
                               Write(location);

#line default
#line hidden
#nullable disable
            WriteLiteral(" in ");
#nullable restore
#line 243 "Views/ErrorPage.cshtml"
                                                                           Write(System.IO.Path.GetFileName(firstFrame.File));

#line default
#line hidden
#nullable disable
            WriteLiteral(", line ");
#nullable restore
#line 243 "Views/ErrorPage.cshtml"
                                                                                Write(firstFrame.Line);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 244 "Views/ErrorPage.cshtml"
            }
            else if (!string.IsNullOrEmpty(location))
            {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 247 "Views/ErrorPage.cshtml"
                               Write(location);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 248 "Views/ErrorPage.cshtml"
            }
            else
            {

#line default
#line hidden
#nullable disable
            WriteLiteral("
Unknown location
\r\n");
#nullable restore
#line 252 "Views/ErrorPage.cshtml"
            }

            var reflectionTypeLoadException = errorDetail.Error as ReflectionTypeLoadException;
            if (reflectionTypeLoadException != null)
            {
                if (reflectionTypeLoadException.LoaderExceptions.Length > 0)
                {

#line default
#line hidden
#nullable disable
            WriteLiteral("
Loader Exceptions:
\r\n
\r\n");
#nullable restore
#line 261 "Views/ErrorPage.cshtml"
                         foreach (var ex in reflectionTypeLoadException.LoaderExceptions)
                        {
                            if (ex != null)
                            {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 265 "Views/ErrorPage.cshtml"
                               Write(ex.Message);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 266 "Views/ErrorPage.cshtml"
                            }
                        }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 269 "Views/ErrorPage.cshtml"
                }
            }
        }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n
\r\n");
#nullable restore
#line 274 "Views/ErrorPage.cshtml"

                    var exceptionCount = 0;
                    var stackFrameCount = 0;
                    var exceptionDetailId = "";
                    var frameId = "";

#line default
#line hidden
#nullable disable
#nullable restore
#line 280 "Views/ErrorPage.cshtml"
                 foreach (var errorDetail in Model.ErrorDetails)
                {
                    exceptionCount++;
                    exceptionDetailId = "exceptionDetail" + exceptionCount;

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n
");
#nullable restore
#line 285 "Views/ErrorPage.cshtml"
                                          Write(errorDetail.Error!.GetType().Name);

#line default
#line hidden
#nullable disable
            WriteLiteral(": ");
#nullable restore
#line 285 "Views/ErrorPage.cshtml"
                                                                              Write(errorDetail.Error!.Message);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n
\r\n");
#nullable restore
#line 287 "Views/ErrorPage.cshtml"
                         foreach (var frame in errorDetail.StackFrames)
                        {
                            stackFrameCount++;
                            frameId = "frame" + stackFrameCount;

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 292 "Views/ErrorPage.cshtml"
                                 if (string.IsNullOrEmpty(frame.File))
                                {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 294 "Views/ErrorPage.cshtml"
                                   Write(frame.Function);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 295 "Views/ErrorPage.cshtml"
                                }
                                else
                                {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 298 "Views/ErrorPage.cshtml"
                                   Write(frame.Function);

#line default
#line hidden
#nullable disable
            WriteLiteral(" in ");
#nullable restore
#line 298 "Views/ErrorPage.cshtml"
                                                                                Write(System.IO.Path.GetFileName(frame.File));

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 299 "Views/ErrorPage.cshtml"
                                }

#line default
#line hidden
#nullable disable
            WriteLiteral("\r\n");
#nullable restore
#line 301 "Views/ErrorPage.cshtml"
                                 if (frame.Line != 0 && frame.ContextCode.Any())
                                {

#line default
#line hidden
#nullable disable
            WriteLiteral("                                    <button class=\"expandCollapseButton\" data-frameId=\"");
#nullable restore
#line 303 "Views/ErrorPage.cshtml"
                                                                                Write(frameId);

#line default
#line hidden
#nullable disable
            WriteLiteral("\">+</button>\r\n
\r\n");
#nullable restore
#line 305 "Views/ErrorPage.cshtml"
                                         if (frame.PreContextCode.Any())
                                        {

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 308 "Views/ErrorPage.cshtml"
                                                 foreach (var line in frame.PreContextCode)
                                                {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 310 "Views/ErrorPage.cshtml"
                                                         Write(line);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 311 "Views/ErrorPage.cshtml"
                                                }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 313 "Views/ErrorPage.cshtml"
                                        }

#line default
#line hidden
#nullable disable
            WriteLiteral("\r\n
\r\n");
#nullable restore
#line 316 "Views/ErrorPage.cshtml"
                                             foreach (var line in frame.ContextCode)
                                            {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 318 "Views/ErrorPage.cshtml"
                                                     Write(line);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 319 "Views/ErrorPage.cshtml"
                                            }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n\r\n");
#nullable restore
#line 322 "Views/ErrorPage.cshtml"
                                         if (frame.PostContextCode.Any())
                                        {

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 325 "Views/ErrorPage.cshtml"
                                                 foreach (var line in frame.PostContextCode)
                                                {

#line default
#line hidden
#nullable disable
            WriteLiteral("
");
#nullable restore
#line 327 "Views/ErrorPage.cshtml"
                                                         Write(line);

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 328 "Views/ErrorPage.cshtml"
                                                }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 330 "Views/ErrorPage.cshtml"
                                        }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 332 "Views/ErrorPage.cshtml"
                                }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n");
#nullable restore
#line 334 "Views/ErrorPage.cshtml"
                        }

#line default
#line hidden
#nullable disable
            WriteLiteral(@"

                                <button class=""showRawException"" data-exceptionDetailId=""");
#nullable restore
#line 341 "Views/ErrorPage.cshtml"
                                                                                Write(exceptionDetailId);

#line default
#line hidden
#nullable disable
            WriteLiteral("\">Show raw exception details</button>\r\n
\r\n
\r\n
");
#nullable restore
#line 344 "Views/ErrorPage.cshtml"
                                                               Write(errorDetail.Error!.ToString());

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n
\r\n
\r\n
\r\n");
#nullable restore
#line 348 "Views/ErrorPage.cshtml"
                }

#line default
#line hidden
#nullable disable
            WriteLiteral("
\r\n
\r\n");
#nullable restore
#line 351 "Views/ErrorPage.cshtml"
         if (Model.ShowRuntimeDetails) {

#line default
#line hidden
#nullable disable
            WriteLiteral("            \r\n                ");
#nullable restore
#line 353 "Views/ErrorPage.cshtml"
           Write(Model.RuntimeDisplayName);

#line default
#line hidden
#nullable disable
            WriteLiteral(" ");
#nullable restore
#line 353 "Views/ErrorPage.cshtml"
                                     Write(Model.RuntimeArchitecture);

#line default
#line hidden
#nullable disable
            WriteLiteral(" v");
#nullable restore
#line 353 "Views/ErrorPage.cshtml"
                                                                  Write(Model.ClrVersion);

#line default
#line hidden
#nullable disable
            WriteLiteral("    |   Microsoft.AspNetCore.Hosting version ");
#nullable restore
#line 353 "Views/ErrorPage.cshtml"
                                                                                Write(Model.CurrentAssemblyVesion);

#line default
#line hidden
#nullable disable
            WriteLiteral("    |    ");
#nullable restore
#line 353 "Views/ErrorPage.cshtml"
                                                                                Write(Model.OperatingSystemDescription);

#line default
#line hidden
#nullable disable
            WriteLiteral("    |   Need help?\r\n            \r\n");
#nullable restore
#line 355 "Views/ErrorPage.cshtml"
        }

#line default
#line hidden
#nullable disable
            WriteLiteral(@"

");
        }
        #pragma warning restore 1998
#nullable restore
#line 9 "Views/ErrorPage.cshtml"

    public ErrorPage(ErrorPageModel model)
    {
        Model = model;
    }

    public ErrorPageModel Model { get; set; }

#line default
#line hidden
#nullable disable
    }
}
#pragma warning restore 1591


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_rand_add_83.h
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-83.tmpl.h
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: rand Set data to result of rand()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */

#include "std_testcase.h"

namespace CWE190_Integer_Overflow__int64_t_rand_add_83
{

#ifndef OMITBAD

class CWE190_Integer_Overflow__int64_t_rand_add_83_bad
{
public:
    CWE190_Integer_Overflow__int64_t_rand_add_83_bad(int64_t dataCopy);
    ~CWE190_Integer_Overflow__int64_t_rand_add_83_bad();

private:
    int64_t data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE190_Integer_Overflow__int64_t_rand_add_83_goodG2B
{
public:
    CWE190_Integer_Overflow__int64_t_rand_add_83_goodG2B(int64_t dataCopy);
    ~CWE190_Integer_Overflow__int64_t_rand_add_83_goodG2B();

private:
    int64_t data;
};

class CWE190_Integer_Overflow__int64_t_rand_add_83_goodB2G
{
public:
    CWE190_Integer_Overflow__int64_t_rand_add_83_goodB2G(int64_t dataCopy);
    ~CWE190_Integer_Overflow__int64_t_rand_add_83_goodB2G();

private:
    int64_t data;
};

#endif /* OMITGOOD */

}

redpajama_set_name: RedPajamaGithub


text:
<?php
class Mail {
	protected $_config = false;

	/**
	 * @param  array $config
	 * @access public
	 * @return void
	**/
	public function __construct($config) {
		$this->_config = $config;
	}

	/**
	 * Sets the cache expiration limit (IMPORTANT NOTE: seconds, NOT ms!).
	 *
	 * @param  string $to, string $title, string $text, string $accname
	 * @access public
	 * @return boolean
	**/
	public function sendMail($to, $title, $text, $accname = '') {
		//SMTP needs accurate times, and the PHP time zone MUST be set
		//This should be done in your php.ini, but this is how to do it if you don't have access to that
		//date_default_timezone_set('Etc/UTC');

		require 'PHPMailer/PHPMailerAutoload.php';

		//Create a new PHPMailer instance
		$mail = new PHPMailer();

		//Tell PHPMailer to use SMTP
		$mail->isSMTP();

		//Enable SMTP debugging
		// 0 = off (for production use)
		// 1 = client messages
		// 2 = client and server messages
		$mail->SMTPDebug = ($this->_config['debug']) ? 2 : 0;

		//Ask for HTML-friendly debug output
		$mail->Debugoutput = 'html';

		//Set the hostname of the mail server
		$mail->Host = $this->_config['host'];

		//Set the SMTP port number - likely to be 25, 465 or 587
		$mail->Port = $this->_config['port'];

		//Whether to use SMTP authentication
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = $this->_config['securityType'];

		//Username to use for SMTP authentication
		$mail->Username = $this->_config['username'];

		//Password to use for SMTP authentication
		$mail->Password = $this->_config['password'];

		//Set who the message is to be sent from
		$mail->setFrom($this->_config['username'], $this->_config['fromName']);

		//Set who the message is to be sent to
		$mail->addAddress($to, $accname);

		//Set the subject line
		$mail->Subject = $title;

		// Body
		$mail->Body = $text;

		// Convert HTML -> plain for legacy mail recievers
		// Create new lines instead of
 html tags.
		$text = str_replace("
", "\n", $text);
		$text = str_replace("
", "\n", $text);
		$text = str_replace("
", "\n", $text);
		// Then get rid of the rest of the html tags.
		$text = strip_tags($text);

		//Replace the plain text body with one created manually
		$mail->AltBody = $text;

		//send the message, check for errors
		$status = false;
		if (!$mail->send()) {
		    echo "Mailer Error: " . $mail->ErrorInfo;
		    exit();
		} else {
		    $status = true;
		}
		return $status;
	}
}


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

using System.Diagnostics.Contracts;

namespace Microsoft.Z3
{
    /// <summary>
    /// Array expressions
    /// </summary>
    public class ArrayExpr : Expr
    {
        #region Internal
        /// <summary> Constructor for ArrayExpr </summary>
        internal ArrayExpr(Context ctx, IntPtr obj)
            : base(ctx, obj)
        {
            Contract.Requires(ctx != null);
        }
        #endregion
    }
}


text:
package com.thread.custom.producer;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class MyPriorityTransferQueue<E> extends PriorityBlockingQueue<E> implements TransferQueue<E> {

	//声明一个私有 AtomicInteger 属性,名为 counter,用来储存正在等待元素的消费者的数量
	private AtomicInteger counter;

	//声明一个私有 LinkedBlockingQueue 属性,名为 transferred。
	private LinkedBlockingQueue<E> transfered;

	private ReentrantLock lock;

	public MyPriorityTransferQueue() {
		this.counter = new AtomicInteger(0);
		this.transfered = new LinkedBlockingQueue<>();
		this.lock = new ReentrantLock();
	}

	/**
	 * 实现 take() 方法。此方法是当消费者需要元素时被消费者调用的。首先,获取之前定义的锁并增加在等待的消费者数量。
	 */
	@Override
	public E take() throws InterruptedException {
		lock.lock();
		counter.incrementAndGet();
		//如果在 transferred queue 中无任何元素。释放锁并使用 take() 方法尝试从queue中获取元素,此方法将让线程进入睡眠直到有元素可以消耗。
		E value = transfered.poll();
		if(value==null){
			lock.unlock();
			value = super.take();
			lock.lock();
		}else{
			//否则,从transferred queue 中取走元素并唤醒正在等待要消耗元素的线程(如果有的话)。
			synchronized(value){
				value.notify();
			}
			System.out.println("value notify..");
		}
		counter.decrementAndGet();
		lock.unlock();
		return value;
	}

	@Override
	public E poll(long timeout, TimeUnit unit) throws InterruptedException {
		return null;
	}

	@Override
	public E element() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public E peek() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public E poll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public E remove() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getWaitingConsumerCount() {
		return counter.get();
	}

	@Override
	public boolean hasWaitingConsumer() {
		return (counter.get()!=0);
	}

	/**
	 * 此方法尝试立刻发送元素给正在等待的消费者(如果可能)。如果没有任何消费者在等待,
	 * 此方法把元素存入一个特殊queue,为了发送给第一个尝试获取一个元素的消费者并阻塞线程直到元素被消耗。
	 */
	@Override
	public void transfer(E e) throws InterruptedException {
		lock.lock();
		if(counter.get()!=0){
			put(e);
			lock.unlock();
		}else{
			transfered.add(e);
			lock.unlock();
			synchronized(e){
				e.wait();
			}
			System.out.println("e ..wait");
		}
	}

	/**
	 * 此方法尝试立刻发送元素给正在等待的消费者(如果可能)。如果没有任何消费者在等待,此方法返回 false 值。
	 */
	@Override
	public boolean tryTransfer(E e) {
		lock.lock();
		boolean value;
		if(counter.get()==0){
			value=false;
		}else{
			put(e);
			value=true;
		}
		lock.unlock();
		return value;
	}

	/**
	 * 实现 tryTransfer() 方法,它接收3个参数: 元素,和需要等待消费者的时间(如果没有消费者的话),和用来注明时间的单位。
	 * 如果有消费者在等待,立刻发送元素。否则,转化时间到毫秒并使用 wait() 方法让线程进入休眠。
	 * 当消费者取走元素时,如果线程在 wait() 方法里休眠,你将使用 notify() 方法唤醒它。
	 */
	@Override
	public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException {
		lock.lock();
		if(counter.get()!=0){
			put(e);
			lock.unlock();
			return true;
		}else{
			transfered.add(e);
			long newTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
			lock.unlock();
			e.wait(newTimeout);
			lock.lock();
			if(transfered.contains(e)){
				transfered.remove(e);
				lock.unlock();
				return false;
			}else{
				lock.unlock();
				return true;
			}
		}
	}

}


text:
package eu.ydp.empiria.player.client.module.selection.view;

import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.peterfranza.gwt.jaxb.client.parser.utils.XMLContent;
import eu.ydp.empiria.player.client.controller.body.InlineBodyGeneratorSocket;
import eu.ydp.empiria.player.client.module.selection.model.SelectionGridElementPosition;
import eu.ydp.empiria.player.client.module.selection.model.UserAnswerType;

public interface SelectionModuleView extends IsWidget {

    void initialize(InlineBodyGeneratorSocket inlineBodyGeneratorSocket);

    void setItemDisplayedName(XMLContent itemName, SelectionGridElementPosition gridElementPosition);

    void setChoiceOptionDisplayedName(XMLContent choiceName, SelectionGridElementPosition gridElementPosition);

    void createButtonForItemChoicePair(SelectionGridElementPosition gridElementPosition, String moduleStyleName);

    void selectButton(SelectionGridElementPosition gridElementPosition);

    void unselectButton(SelectionGridElementPosition gridElementPosition);

    void lockButton(SelectionGridElementPosition gridElementPosition, boolean lock);

    void updateButtonStyle(SelectionGridElementPosition gridElementPosition, UserAnswerType styleState);

    void addClickHandlerToButton(SelectionGridElementPosition gridElementPosition, ClickHandler clickHandler);

    void setGridSize(int amountOfItems, int amountOfChoices);
}


text:
This repository contains pre-compiled form files using the default themes. This is intended for use in projects that do not need all the bells and whistles of Semantic UI, and want to keep file size to a minimum.

For the latest changes please see the [Release Notes](https://github.com/Semantic-Org/UI-Form/blob/master/RELEASE-NOTES.md)

**Special Note**
An update in `2.0.8` has fixed an issue which may have prevented some single component modules from working correctly. Please see notes in [this pull request](https://github.com/Semantic-Org/Semantic-UI/pull/2816).

If you're looking for the full version of Semantic including all components and build tools [check out the main project repository](https://github.com/Semantic-Org/Semantic-UI/tree/1.0)

#### To install with Bower
```
bower install semantic-ui-form
```

#### To install with NPM
```
npm install semantic-ui-form
```

#### To install with Meteor
```
meteor add semantic:ui-form
```

## Addendum

This element's definitions (required class names, html structures) are available in the [UI Docs](http://www.semantic-ui.com)

Please consider checking out [all the benefits to theming](http://www.learnsemantic.com/guide/expert.html) before using these stand-alone releases.


text:
namespace WebKit { class WebGraphicsContext3D; }

namespace cc {

class CC_EXPORT SyncPointHelper {
 public:
  // Requests a callback to |closure| when the |sync_point| is reached by the
  // |context3d|.
  //
  // If the |context3d| is destroyed or lost before the callback fires, then
  // AbortBecauseDidLoseOrDestroyContext() must be called to clean up the
  // callback's resources.
  static void SignalSyncPoint(WebKit::WebGraphicsContext3D* context3d,
                              unsigned sync_point,
                              const base::Closure& closure);

  // Requests a callback to |closure| when the results for |query| is available.
  //
  // If the |context3d| is destroyed or lost before the callback fires, then
  // AbortBecauseDidLoseOrDestroyContext() must be called to clean up the
  // callback's resources.
  static void SignalQuery(WebKit::WebGraphicsContext3D* context3d,
                          unsigned int query,
                          const base::Closure& closure);

 private:
  SyncPointHelper();

  DISALLOW_COPY_AND_ASSIGN(SyncPointHelper);
};

}  // namespace cc

#endif  // CC_RESOURCES_SYNC_POINT_HELPER_H_


text:
#import "NSArrayController.h"

@interface DeliveryAccountArrayController : NSArrayController
{
}

- (id)newObject;

@end


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class TemporalPositionIdentifier extends AbstractTag
{

    protected $Id = '0020,0100';

    protected $Name = 'TemporalPositionIdentifier';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Temporal Position Identifier';
}


text:
## Windows Setup (Windows 10)

1. Device Manager -> Select `Network Adapters`
2. Click `Action` -> `Add legacy hardware`
3. Click `Next`, Select `Install the hardware that I manually install from a list(Advanced)`
4. Select `Network adapters`
5. Choose `Microsoft` from the vendors list and `Microsoft KM-TEST Loopback Adapter` from the model section
6. Click next
7. Install adapter
8. Click on network icon on status bar, click `Open Network and Sharing Center`
9. Click `Change adapter settings` on left hand menu
10. Right click on `Microsoft KM-Test Loopback Adapter` and click 'Properties'
11. Highlight `Internet Protocol Version 4 (TCP/IPv4)`, click Properties
12. Toggle `Use the following IP Address`
13. IP Address: `169.254.169.254`
14. Netmask: `255.255.255.254`
15. Click `ok`


text:
import { round } from "lodash";
export = round;


text:
/*
 *  sqMacHostWindow.h
 *  SqueakVMForCarbon
 *
 *  Created by John M McIntosh on Tue Jul 20 2004.
 *

   3.8.15b3  Feb 19th, 2007 JMM add cursor set logic

 */

#include <Carbon/Carbon.h>
#include "HostWindowPlugin.h"

/* window handle type */
#define wHandleType WindowPtr
#define wIndexType int

typedef struct windowDescriptorBlock {
	struct windowDescriptorBlock * next;
	wHandleType		handle;
	wIndexType		windowIndex;
	/* extra fields to support your platform needs */
	CGContextRef context;
	MouseTrackingRef windowTrackingRef;
	int rememberTicker;
	int dirty;
	int sync;
	int locked;
	int	width;
	int	height;
	int isInvisible;
} windowDescriptorBlock;

windowDescriptorBlock *windowBlockFromHandle(wHandleType windowHandle);
int windowIndexFromBlock( windowDescriptorBlock * thisWindow);
int windowIndexFromHandle(wHandleType windowHandle);
wHandleType windowHandleFromIndex(wIndexType windowIndex);
windowDescriptorBlock *AddWindowBlock(void);
windowDescriptorBlock *windowBlockFromIndex(int windowIndex);
int getCurrentIndexInUse(void);
void SetUpCarbonEventForWindowIndex(int index);
void setWindowTrackingRgn(int windowIndex);


text:
import unittest
import sys
sys.path.append('.')
from defensio import *

class TestDefensio(unittest.TestCase):

  def is_python3(self):
    return sys.version_info[0] == 3

  def setUp(self):
    # Set this to an actual key before running tests
    self.api_key  = 'retrainer_key'
    self.client = Defensio(self.api_key)

  def testGenerateUrls(self):
    self.assertEqual("/2.0/users/" + self.api_key + ".json", self.client._generate_url_path())
    self.assertEqual("/2.0/users/" + self.api_key + "/action1.json"%locals(), self.client._generate_url_path('action1'))
    self.assertEqual("/2.0/users/" + self.api_key + "/action1/id1.json"%locals(), self.client._generate_url_path('action1', 'id1'))

  def testGetUser(self):
    status, result =  self.client.get_user()
    self.assertEqual(200, status)
    self.assertEqual(dict, type(result['defensio-result']))
    result_body = result['defensio-result']
    self.assertEqual('success', result_body['status'])
    self.assertEqual('',        result_body['message'])
    self.assertEqual('2.0',     result_body['api-version'])

    if self.is_python3():
      self.assertEqual(str, type(result_body['owner-url']))
    else:
      self.assertEqual(unicode, type(result_body['owner-url']))

    self.assertTrue(len(result_body['owner-url']) > 0 )

  def testPostDocumentWhenFail(self):
    doc = {'content': 'Hi Hola Salut'}
    status, result = self.client.post_document(doc)
    self.assertEqual(200, status)
    self.assertEqual(dict, type(result['defensio-result']))
    result_body = result['defensio-result']
    self.assertEqual('fail', result_body['status'])
    self.assertEqual('The following fields are missing but required: platform, type', result_body['message'])
    self.assertEqual('2.0', str(result_body['api-version']))

  def testPostDocumentWhenSuccessThenPutThenGet(self):
    doc = {'content': 'Hi Hola Salut', 'type' : 'comment', 'platform' : 'python-test'}
    status, result = self.client.post_document(doc)
    self.assertEqual(200, status)
    self.assertEqual(dict, type(result['defensio-result']))

    result_body = result['defensio-result']
    self.assertEqual('success', result_body['status'])
    self.assertEqual('', result_body['message'])
    self.assertEqual('2.0', str(result_body['api-version']))
    self.assertAlmostEqual(0.05, result_body['spaminess'])
    self.assertEqual('legitimate', result_body['classification'])
    self.assert_(result_body['profanity-match'] == False or result_body['profanity-match'] == None)
    self.assertTrue(result_body['allow'])

    if self.is_python3():
      self.assertEqual(str, type( result_body['signature'] ))
    else:
      self.assertEqual(unicode, type( result_body['signature'] ))

    signature = result_body['signature']

    status, put_result = self.client.put_document(signature, {'allow' : 'false'})
    self.assertEqual(200, status)
    put_result_body = put_result['defensio-result']
    self.assertEqual('success', put_result_body['status'])

    status, get_result = self.client.get_document(signature)
    self.assertFalse(get_result['defensio-result']['allow'])

  def testProfanityFilter(self):
    doc = {'bad' : 'some fucking cursing here', 'good' : 'Hey... how is it going?'}
    status, res = self.client.post_profanity_filter(doc)
    self.failIfEqual(403, status, "Seems like the profanity filter is not enabled for key: " + self.api_key  + " ")
    self.assertEqual(200, status)
    self.assertEqual('Hey... how is it going?', res['defensio-result']['filtered']['good'])
    self.assertEqual('some ****ing cursing here', res['defensio-result']['filtered']['bad'])

  def testBasicStats(self):
    status, res = self.client.get_basic_stats()
    self.assertEqual(200, status)
    result_body = res['defensio-result']
    self.assertEqual('success', result_body['status'])
    self.assertEqual(set(['status', 'false-positives', 'false-negatives', 'unwanted', 'legitimate', 'learning', 'api-version', 'learning-status', 'message', 'accuracy']), set(result_body.keys()))

  def testExtendedStats(self):
    data = {'from' : '2010-01-01', 'to' : '2010-01-04'}
    status, res = self.client.get_extended_stats(data)
    self.assertEqual(200, status)
    result_body = res['defensio-result']
    self.assertEqual('success', res['defensio-result']['status'])

  def testHandlePostDocumentAsyncCallback(self):
    if self.is_python3():
      handle_post_document_async_callback( b'{"defensio-result": {"status": "success"}}' )
    else:
      handle_post_document_async_callback( '{"defensio-result": {"status": "success"}}' )

if __name__ == '__main__':
  unittest.main()


text:
  Mareuil-la-Motte est
       un village
       localisé dans le département de l'Oise en Picardie. Elle comptait 591 habitants en 2008.

Si vous pensez emmenager à Mareuil-la-Motte, vous pourrez aisément trouver une maison à acheter.

La ville propose quelques  équipements, elle propose entre autres un terrain de sport et une boucle de randonnée.

À Mareuil-la-Motte, la valeur moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2 055 € du m². À la location le prix moyen se situe à 0 € du m² par mois.

Le nombre de logements, à Mareuil-la-Motte, se décomposait en 2011 en quatre appartements et 239 maisons soit
 un marché plutôt équilibré.

À coté de Mareuil-la-Motte sont situées les communes de
La Neuville-sur-Ressons localisée à 2 km, 214 habitants,
Élincourt-Sainte-Marguerite localisée à 2 km, 824 habitants,
Ressons-sur-Matz localisée à 3 km, 1 561 habitants,
Vandélicourt localisée à 3 km, 224 habitants,
Marest-sur-Matz située à 4 km, 393 habitants,
Ricquebourg à 2 km, 206 habitants,
 entre autres. De plus, Mareuil-la-Motte est située à seulement quatorze km de Compiègne.


text:
using UnityEngine;

namespace QFramework
{
    /// <summary>
    /// 专门用来为音频做设置
    /// </summary>
    public class AudioKitSettings
    {
        // 用来存储的Key
        const string KEY_AUDIO_MANAGER_SOUND_ON = "KEY_AUDIO_MANAGER_SOUND_ON";

        const string KEY_AUDIO_MANAGER_MUSIC_ON = "KEY_AUDIO_MANAGER_MUSIC_ON";
        const string KEY_AUDIO_MANAGER_VOICE_ON = "KEY_AUDIO_MANAGER_VOICE_ON";

        const string KEY_AUDIO_MANAGER_VOICE_VOLUME = "KEY_AUDIO_MANAGER_VOICE_VOLUME";
        const string KEY_AUDIO_MANAGER_SOUND_VOLUME = "KEY_AUDIO_MANAGER_SOUND_VOLUME";
        const string KEY_AUDIO_MANAGER_MUSIC_VOLUME = "KEY_AUDIO_MANAGER_MUSIC_VOLUME";

        public AudioKitSettings()
        {
            IsSoundOn = new PlayerPrefsBooleanProperty(KEY_AUDIO_MANAGER_SOUND_ON, true);

            IsMusicOn = new PlayerPrefsBooleanProperty(KEY_AUDIO_MANAGER_MUSIC_ON, true);

            IsVoiceOn = new PlayerPrefsBooleanProperty(KEY_AUDIO_MANAGER_VOICE_ON, true);

            IsOn = new CustomProperty<bool>(
                () => IsSoundOn.Value && IsMusicOn.Value && IsVoiceOn.Value,
                isOn =>
                {
                    Debug.Log(isOn);
                    IsSoundOn.Value = isOn;
                    IsMusicOn.Value = isOn;
                    IsVoiceOn.Value = isOn;
                }
            );

            SoundVolume = new PlayerPrefsFloatProperty(KEY_AUDIO_MANAGER_SOUND_VOLUME, 1.0f);

            MusicVolume = new PlayerPrefsFloatProperty(KEY_AUDIO_MANAGER_VOICE_VOLUME, 1.0f);

            VoiceVolume = new PlayerPrefsFloatProperty(KEY_AUDIO_MANAGER_MUSIC_VOLUME, 1.0f);

        }

        public PlayerPrefsBooleanProperty IsSoundOn { get; private set; }

        public PlayerPrefsBooleanProperty IsMusicOn { get; private set; }

        public PlayerPrefsBooleanProperty IsVoiceOn { get; private set; }

        public PlayerPrefsFloatProperty SoundVolume { get; private set; }

        public PlayerPrefsFloatProperty MusicVolume { get; private set; }

        public PlayerPrefsFloatProperty VoiceVolume { get; private set; }

        public CustomProperty<bool> IsOn { get; private set; }
    }
}


text:
package org.jetbrains.plugins.groovy.lang.completion;

import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiJavaPatterns;
import com.intellij.patterns.StandardPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.util.ProcessingContext;
import consulo.codeInsight.completion.CompletionProvider;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;

import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.Set;

/**
 * @author ilyas
 */
public class GroovyCompletionContributor extends CompletionContributor {

  private static final ElementPattern<PsiElement> AFTER_NUMBER_LITERAL = PlatformPatterns.psiElement().afterLeafSkipping(
    StandardPatterns.alwaysFalse(),
    PlatformPatterns.psiElement().withElementType(PsiJavaPatterns
                                                    .elementType().oneOf(GroovyTokenTypes.mNUM_DOUBLE, GroovyTokenTypes.mNUM_INT,
                                                                         GroovyTokenTypes.mNUM_LONG, GroovyTokenTypes.mNUM_FLOAT,
                                                                         GroovyTokenTypes.mNUM_BIG_INT, GroovyTokenTypes.mNUM_BIG_DECIMAL)));

  public GroovyCompletionContributor() {
    GrMethodOverrideCompletionProvider.register(this);
    GrThisSuperCompletionProvider.register(this);
    MapArgumentCompletionProvider.register(this);
    GroovyConfigSlurperCompletionProvider.register(this);
    MapKeysCompletionProvider.register(this);
    GroovyDocCompletionProvider.register(this);
    GrStatementStartCompletionProvider.register(this);
    GrMainCompletionProvider.register(this);
    GrAnnotationAttributeCompletionProvider.register(this);

    extend(CompletionType.BASIC, PlatformPatterns.psiElement().withParent(GrLiteral.class), new CompletionProvider() {
      @Override
	  public void addCompletions(@Nonnull CompletionParameters parameters,
                                    ProcessingContext context,
                                    @Nonnull final CompletionResultSet result) {
        final Set<String> usedWords = new HashSet<String>();
        for (CompletionResult element : result.runRemainingContributors(parameters, true)) {
          usedWords.add(element.getLookupElement().getLookupString());
        }

        PsiReference reference = parameters.getPosition().getContainingFile().findReferenceAt(parameters.getOffset());
        if (reference == null || reference.isSoft()) {
          WordCompletionContributor.addWordCompletionVariants(result, parameters, usedWords);
        }
      }
    });

  }

  @Override
  public void fillCompletionVariants(@Nonnull CompletionParameters parameters, @Nonnull CompletionResultSet result) {
    if (!AFTER_NUMBER_LITERAL.accepts(parameters.getPosition())) {
      super.fillCompletionVariants(parameters, result);
    }
  }

  @Override
  public void beforeCompletion(@Nonnull final CompletionInitializationContext context) {
    final String identifier = new GrDummyIdentifierProvider(context).getIdentifier();
    if (identifier != null) {
      context.setDummyIdentifier(identifier);
    }

    //don't eat $ from gstrings when completing previous injection ref. see IDEA-110369
    PsiElement position = context.getFile().findElementAt(context.getStartOffset());
    if (position!= null && position.getNode().getElementType() == GroovyTokenTypes.mDOLLAR) {
      context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, context.getStartOffset());
    }
  }
}


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Visit\Spec;

use Happyr\DoctrineSpecification\Spec;
use Happyr\DoctrineSpecification\Specification\BaseSpecification;
use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Core\Spec\InDateRange;
use Shlinkio\Shlink\Core\Visit\Persistence\VisitsCountFiltering;
use Shlinkio\Shlink\Rest\ApiKey\Spec\WithApiKeySpecsEnsuringJoin;

class CountOfNonOrphanVisits extends BaseSpecification
{
    public function __construct(private VisitsCountFiltering $filtering)
    {
        parent::__construct();
    }

    protected function getSpec(): Specification
    {
        $conditions = [
            Spec::isNotNull('shortUrl'),
            new InDateRange($this->filtering->dateRange),
        ];

        if ($this->filtering->excludeBots) {
            $conditions[] = Spec::eq('potentialBot', false);
        }

        $apiKey = $this->filtering->apiKey;
        if ($apiKey !== null) {
            $conditions[] = new WithApiKeySpecsEnsuringJoin($apiKey, 'shortUrl');
        }

        return Spec::countOf(Spec::andX(...$conditions));
    }
}


text: def ruby2_keywords(*) end if RUBY_VERSION < '2.7'


text:
package org.apache.camel.processor;

import org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Producer;
import org.apache.camel.support.DefaultAsyncProducer;
import org.apache.camel.support.service.ServiceHelper;

/**
 * Ensures a {@link Producer} is executed within an {@link org.apache.camel.spi.UnitOfWork}.
 */
public final class UnitOfWorkProducer extends DefaultAsyncProducer {

    private final Producer producer;
    private final AsyncProcessor processor;

    /**
     * The producer which should be executed within an {@link org.apache.camel.spi.UnitOfWork}.
     *
     * @param producer the producer
     */
    public UnitOfWorkProducer(Producer producer) {
        super(producer.getEndpoint());
        this.producer = producer;
        // wrap in unit of work
        CamelInternalProcessor internal = new CamelInternalProcessor(producer);
        internal.addAdvice(new CamelInternalProcessor.UnitOfWorkProcessorAdvice(null));
        this.processor = internal;
    }

    @Override
    public Endpoint getEndpoint() {
        return producer.getEndpoint();
    }

    @Override
    public boolean process(Exchange exchange, AsyncCallback callback) {
        return processor.process(exchange, callback);
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        ServiceHelper.startService(processor);
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();
        ServiceHelper.stopService(processor);
    }

    @Override
    public boolean isSingleton() {
        return producer.isSingleton();
    }

    @Override
    public String toString() {
        return "UnitOfWork(" + producer + ")";
    }
}


text:
#pragma once

#include <qrkernel/ids.h>

#include "kitBase/interpreterControlInterface.h"

namespace kitBase {

/// Interface that allows interpreter to communicate with other parts of a system.
class ROBOTS_KIT_BASE_EXPORT InterpreterInterface : public kitBase::InterpreterControlInterface
{
	Q_OBJECT

public:
	virtual ~InterpreterInterface() {}

	/// Returns time in ms that passed from the moment of last intepretation start.
	/// @warning: may return unreal time (for example when 2D model is being interpreted).
	virtual int timeElapsed() const = 0;

	/// Returns a list of diagram types that can be interpreted by this instance.
	virtual qReal::IdList supportedDiagrams() const = 0;

signals:
	/// Emitted when connection to robot established or was broken.
	void connected(bool isConnected);

public slots:
	/// Called when establishing connection to a robot is requested. If connection is already established must
	/// disconnect from robot. May do nothing if interpretation is running, to avoid leaving robot in with motors
	/// turned on and without connection to stop it.
	virtual void connectToRobot() = 0;
};

}


text:
if (typeof babel != 'undefined')
  System.transpiler = 'babel';

var ie = typeof window != 'undefined' && window.navigator.userAgent.match(/Trident/);

describe('System', function () {

  describe('prerequisite', function () {

    it('should be a instance of Loader', function () {
      expect(System).to.be.a(Reflect.Loader);
    });

  });

  describe('#import', function () {

    describe('an ES5 script', function () {

      it('should import a ES5 script', function (done) {
        System.import('test/syntax/script.js')
          .then(function (m) {
            expect(!!m).to.be.ok();
          })
          .then(done, done);
      });

      it('should import a ES5 script once loaded', function (done) {
        System.import('test/syntax/script.js')
          .then(function () {
            return System.import('test/syntax/script.js').
              then(function (m) {
                expect(!!m).to.be.ok();
              });
          })
          .then(done, done);
      });

    });

    describe('System registry methods', function() {

      it('should support set, get and delete', function(done) {

        var testPath = baseURL + 'test/loader/module.js';

        System.import(testPath).then(function(m) {
          expect(m.run).to.equal('first');
          System.delete(testPath);
          return System.import(testPath);
        })
        .then(function(m) {
          expect(m.run).to.equal('second');
          System.delete('loader.module');
          System.set(testPath, System.newModule({ custom: 'module' }));
          return System.import(testPath);
        })
        .then(function(m) {
          expect(m.custom).to.equal('module');
        })
        .then(done, done);
      });
    });

    describe('an ES6 script', function () {

      it('should import an ES6 script', function (done) {
        System.import('test/syntax/es6.js')
          .then(function (m) {
            expect(m.p).to.equal('p');
          })
          .then(done, done);
      });

      it('should import an ES6 script with its dependencies', function (done) {
        System.import('test/syntax/es6-withdep.js')
          .then(function (m) {
            expect(m.p).to.equal('p');
          })
          .then(done, done);
      });

      // typescript does not support generators yet
      (ie || System.transpiler === 'typescript' ? it.skip : it)('should import an ES6 script with a generator', function (done) {
        System.import('test/syntax/es6-generator.js')
          .then(function (m) {
            expect(!!m.generator).to.be.ok();
          })
          .then(done, done);
      });

      it('should import without bindings', function (done) {
        System.import('test/syntax/direct.js')
          .then(function (m) {
            expect(!!m).to.be.ok();
          })
          .then(done, done);
      });

      it('should support es6 various syntax', function (done) {
        System.import('test/syntax/es6-file.js')
          .then(function (m) {

            expect(m.q).to.be.a('function');

            expect(function () { (new m.q()).foo(); })
              .to.throwException(function (e) {
                expect(e).to.equal('g');
              });

          })
          .then(done, done);
      });

    });

    describe('with circular dependencies', function () {

      (System.transpiler == 'traceur' ? it : it.skip)('should resolve circular dependencies', function (done) {
        System.import('test/syntax/circular1.js')
          .then(function (m1) {
            return System.import('test/syntax/circular2.js').then(function (m2) {
              expect(m1.variable1).to.equal('test circular 1');
              expect(m2.variable2).to.equal('test circular 2');

              expect(m2.output, 'The module 2 output is the module 1 variable')
                .to.equal('test circular 1');
              expect(m1.output, 'The module 1 output is the module 2 variable')
                .to.equal('test circular 2');
              expect(m2.output1, 'The module 2 output1 is the module 1 output')
                .to.equal('test circular 2');
              expect(m1.output2, 'The module 1 output2 is the module 2 output')
                .to.equal('test circular 1');
            });
          })
          .then(done, done);
      });

      it('should update circular dependencies', function (done) {
        System.import('test/syntax/even.js')
          .then(function (m) {
            expect(m.counter, 'Counter initially at 1').to.be.equal(1);
            expect(m.even(10), 'Must be an even number').to.be.ok();
            expect(m.counter, 'Counter sould now be at 7').to.be.equal(7);
            expect(m.even(15), 'Must be an odd number').to.not.be.ok();
            expect(m.counter, 'Counter sould now be at 15').to.be.equal(15);
          })
          .then(done, done);

      });

    });

    describe('loading order', function () {

      function expectedOrder(file, order, done) {
        System.import('test/loads/' + file)
          .then(function (m) {
            order.forEach(function (letter) {
              expect(m[letter], 'The "' + letter + '" file wasn\'t loaded')
                .to.equal(letter);
            });

          })
          .then(done, done);
      }

      it('should load in order (a)', function (done) {
        expectedOrder('a.js', ['a', 'b'], done)
      });

      it('should load in order (c)', function (done) {
        expectedOrder('c.js', ['c', 'a', 'b'], done)
      });

      it('should load in order (s)', function (done) {
        expectedOrder('s.js', ['s', 'c', 'a', 'b'], done)
      });

      it('should load in order (_a)', function (done) {
        expectedOrder('_a.js', ['b', 'd', 'g', 'a'], done)
      });

      it('should load in order (_e)', function (done) {
        expectedOrder('_e.js', ['c', 'e'], done)
      });

      it('should load in order (_f)', function (done) {
        expectedOrder('_f.js', ['g', 'f'], done)
      });

      it('should load in order (_h)', function (done) {
        expectedOrder('_h.js', ['i', 'a', 'h'], done)
      });

    });

    //

    describe('errors', function () {

      function supposedToFail() {
        expect(false, 'should not be successful').to.be.ok();
      }

      it('should throw if on syntax error', function (done) {
        System.import('test/loads/main.js')
          .then(supposedToFail)
          .catch(function (e) {
            expect(e)
              .to.be.equal('Error evaluating ' + baseURL + 'test/loads/deperror.js\n\tdep error');
          })
          .then(done, done);
      });

      it('should throw what the script throws', function (done) {
        System.import('test/loads/deperror.js')
          .then(supposedToFail)
          .catch(function(e) {
            expect(e == 'dep error');
          })
          .then(done, done);
      });

      it('Unhandled rejection test', function (done) {
        System.import('test/loads/load-non-existent.js')
          .then(supposedToFail)
          .catch(function (e) {
            expect(typeof window != 'undefined' ? e.toString() : e.stack).to.be.match(/Error loading \S+/);
          })
          .then(done, done);
      });

    });

    //

    describe('es6 export syntax overview', function () {
      it('should resolve different export syntax', function (done) {
        System.import('test/syntax/export.js')
          .then(function (m) {
            expect(m.p, 'should export a number').to.be.equal(5);
            expect(m.foo, 'should export a function').to.be.a('function');
            expect(m.q, 'should export an object').to.be.an('object');
            expect(m.default, 'should export a default function')
              .to.be.a('function');
            expect(m.s, 'should export a set of variable').to.be.equal(4);
            expect(m.t, 'should export a specifier number').to.be.equal(4);
            expect(m.m, 'should export a specifier object ').to.be.an('object');
          })
          .then(done, done);
      });
    });

    describe('es6 export default syntax', function () {
      it('should resolve "export default"', function (done) {
        System.import('test/syntax/export-default.js')
          .then(function (m) {
            expect(m.default()).to.be.equal('test');
          })
          .then(done, done);
      });
    });

    describe('es6 export re-exporting', function () {
      it('should support simple re-exporting', function (done) {
        System.import('test/syntax/reexport1.js')
          .then(function (m) {
            expect(m.p, 'should export 5 from the "./export"').to.be.equal(5);
          })
          .then(done, done);
      });

      it('should support re-exporting binding', function (done) {
        System.import('test/syntax/reexport-binding.js')
          .then(function () {
            return System.import('test/syntax/rebinding.js').then(function (m) {
              expect(m.p, 'should export "p" from the "./rebinding"')
                .to.be.equal(4);
            });
          })
          .then(done, done);
      });

      it('should support re-exporting with a new name', function (done) {
        System.import('test/syntax/reexport2.js')
          .then(function (m) {
            expect(m.q, 'should export "t" as "q" from the "./export"')
              .to.be.equal(4);
            expect(m.z, 'should export "q" as "z" from the "./export"')
              .to.be.equal(5);
          })
          .then(done, done);
      });

      it('should support re-exporting', function (done) {
        System.import('test/syntax/export-star.js')
          .then(function (m) {
            expect(m.foo, 'should export a function').to.be.equal('foo');
            expect(m.bar, 'should re-export export-star bar variable')
              .to.be.equal('bar');
          })
          .then(done, done);
      });

      (System.transpiler != 'traceur' ? it.skip : it)('should support re-exporting overwriting', function (done) {
        System.import('test/syntax/export-star2.js')
          .then(function (m) {
            expect(m.bar, 'should re-export "./export-star" bar variable')
              .to.be.equal('bar');
            expect(m.foo, 'should overwrite "./star-dep" foo variable with a function')
              .to.be.a('function');
          })
          .then(done, done);
      });
    });

    //

    describe('es6 import syntax overview', function () {
      it('should resolve different import syntax', function (done) {
        System.import('test/syntax/import.js')
          .then(function (m) {
            expect(m.a, 'should export "d" as "a" from the "./export"')
              .to.be.a('function');
            expect(m.b, 'should export "p" as "b" for "s" as "p" from "./reexport1"')
              .to.be.equal(4);
            expect(m.c, 'should export "z" as "c" with "z" from "./reexport2"')
              .to.be.equal(5);
            expect(m.d, 'should export "r" as "d" for "q" as "r" from the "./reexport2"')
              .to.be.equal(4);
            expect(m.q, 'should export "q" as "*" from the "./reexport1"')
              .to.be.an('object');
            expect(m.q.foo, 'should access the "foo" function of "./reexport1" through "q" ad "*" ')
              .to.be.a('function');
          })
          .then(done, done);
      });
    });

    //

    describe('a script with metas', function () {
      it('should support module name meta', function (done) {
        System.import('test/loader/moduleName.js')
          .then(function (m) {
            expect(m.name).to.be.equal(m.name);
          })
          .then(done, done);
      });
    });

  });

  describe('#paths', function () {

    it('should support custom paths', function (done) {
      System.paths['bar'] = baseURL + 'test/loader/custom-path.js';
      System.import('bar')
        .then(function (m) {
          expect(m.bar).to.be.equal('bar');
          delete System.paths['bar'];
        })
        .then(done, done);
    });

    it('should support path wildcard', function (done) {
      System.paths['bar/*'] = baseURL + 'test/loader/custom-folder/*.js';
      System.import('bar/path')
        .then(function (m) {
          expect(m.bar).to.be.equal('baa');
          delete System.paths['bar/*'];
        })
        .then(done, done);
    });

    it('should support most specific paths', function (done) {
      System.paths['bar/bar'] = baseURL + 'test/loader/specific-path.js';
      System.paths['bar/*'] = baseURL + 'test/loader/custom-folder/*.js';
      System.import('bar/bar')
        .then(function (m) {
          expect(m.path).to.be.ok();
          delete System.paths['bar/bar'];
          delete System.paths['bar/*'];
        })
        .then(done, done);
    });

  });

  describe('#System.define', function () {

    it.skip('should load System.define', function(done) {
      var oldLocate = System.locate;
      var slaveLocatePromise = new Promise(function(resolve, reject) {

        System.locate = function(load) {
          if(load.name === 'slave') {
            setTimeout(function() {
              System.define('slave', 'var double = [1,2,3].map(i => i * 2);');
              resolve('slave.js');
            }, 1);
            return slaveLocatePromise;
          }
          return oldLocate.apply(this, arguments);
        };

      });

      System.import('test/loader/master.js').then(function(m) {
        done()
      }, done).then(reset, reset);

      function reset() {
        System.locate = oldLocate;
      }
    });

  });

  describeIf(
    typeof window != 'undefined' && window.Worker,
    'with Web Worker', function () {
      (ie ? it.skip : it)('should loading inside of a Web Worker', function (done) {
        var worker = new Worker(baseURL + 'test/worker/worker-' + System.transpiler + '.js');

        worker.onmessage = function (e) {
          expect(e.data).to.be.equal('p');
          done();
        };

      });

    });

  describeIf(
    typeof window != 'undefined',
    'with script type "module"', function () {
      it('should load the module on the document "load" event', function (done) {
        setTimeout(function(){ // wait for script processing first
          expect(window.anon).to.be.a('function');
          done();
        }, 0);
      });

    });
});


text:
module PirateBay
  class ResultSet < Array
    attr_accessor :total_results, :search

    def initialize(initializer)
      self.search = initializer
      self.total_results = 1.0/0 #Infinity
    end

    def retrieved_results
      self.size
    end

    def more
      search.next_page
    end
  end
end


text:
import React from 'react';
import styled from 'react-emotion';
import {storiesOf} from '@storybook/react';
import {withInfo} from '@storybook/addon-info';

import PlatformIcon from 'app/components/platformIcon';

const StyledPlatformIcon = styled(PlatformIcon)`
  margin: 0 15px 15px 0;
`;

storiesOf('Style|Icons', module).add(
  'PlatformIcon',
  withInfo('Scalable platform and framework icons')(() => (
    <div>
      <StyledPlatformIcon platform="generic" size="24" />
      <StyledPlatformIcon platform="javascript-angular" size="24" />
      <StyledPlatformIcon platform="java-appengine" size="24" />
      <StyledPlatformIcon platform="apple" size="24" />
      <StyledPlatformIcon platform="python-bottle" size="24" />
      <StyledPlatformIcon platform="cordova" size="24" />
      <StyledPlatformIcon platform="csharp" size="24" />
      <StyledPlatformIcon platform="python-django" size="24" />
      <StyledPlatformIcon platform="electron" size="24" />
      <StyledPlatformIcon platform="elixir" size="24" />
      <StyledPlatformIcon platform="javascript-ember" size="24" />
      <StyledPlatformIcon platform="python-flask" size="24" />
      <StyledPlatformIcon platform="go" size="24" />
      <StyledPlatformIcon platform="java" size="24" />
      <StyledPlatformIcon platform="node" size="24" />
      <StyledPlatformIcon platform="php" size="24" />
      <StyledPlatformIcon platform="perl" size="24" />
      <StyledPlatformIcon platform="python" size="24" />
      <StyledPlatformIcon platform="ruby-rails" size="24" />
      <StyledPlatformIcon platform="javascript-react" size="24" />
      <StyledPlatformIcon platform="ruby" size="24" />
      <StyledPlatformIcon platform="rust" size="24" />
      <StyledPlatformIcon platform="swift" size="24" />
      <StyledPlatformIcon platform="javascript-vue" size="24" />
    </div>
  ))
);


text:
// Note: This code was derived from the TCG TPM 2.0 Library Specification at
// http://www.trustedcomputinggroup.org/resources/tpm_library_specification

#include    "stdafx.h"

UINT16
TPM2_FlushContext_Marshal(
    SESSION *sessionTable,
    UINT32 sessionCnt,
    Marshal_Parms *parms,
    BYTE **buffer,
    INT32 *size
)
{
    if((parms == NULL) ||
        (parms->objectCntIn < TPM2_FlushContext_HdlCntIn) ||
//        (parms->objectCntOut < TPM2_FlushContext_HdlCntOut) ||
        (parms->parmIn == NULL) ||
        (parms->parmOut == NULL))
    {
        return TPM_RC_FAILURE;
    }
    return Command_Marshal(
        TPM_CC_FlushContext,
        sessionTable,
        sessionCnt,
        TPM2_FlushContext_Parameter_Marshal,
        parms,
        buffer,
        size);
}

TPM_RC
TPM2_FlushContext_Unmarshal(
    SESSION *sessionTable,
    UINT32 sessionCnt,
    Marshal_Parms *parms,
    BYTE **buffer,
    INT32 *size
)
{
    TPM_RC result = TPM_RC_SUCCESS;
//    FlushContext_In *in = (FlushContext_In *)parms->parmIn;
//    FlushContext_Out *out = (FlushContext_Out *)parms->parmOut;

    if((parms == NULL) ||
        (parms->objectCntIn < TPM2_FlushContext_HdlCntIn) ||
//        (parms->objectCntOut < TPM2_FlushContext_HdlCntOut) ||
        (parms->parmIn == NULL) ||
        (parms->parmOut == NULL))
    {
        return TPM_RC_FAILURE;
    }
    if((result = Command_Unmarshal(
        TPM_CC_FlushContext,
        sessionTable,
        sessionCnt,
        TPM2_FlushContext_Parameter_Unmarshal,
        parms,
        buffer,
        size)) == TPM_RC_SUCCESS)
    {
        parms->objectTableIn[TPM2_FlushContext_HdlIn_FlushHandle].generic.handle = TPM_RH_NULL;
    }
    return result;
}

UINT16
TPM2_FlushContext_Parameter_Marshal(
    Marshal_Parms *parms,
    BYTE **buffer,
    INT32 *size
)
{
//    FlushContext_In *in = (FlushContext_In *)parms->parmIn;
//    FlushContext_Out *out = (FlushContext_Out *)parms->parmOut;
    UINT16 parameterSize = 0;

    UNREFERENCED_PARAMETER(parms);
    UNREFERENCED_PARAMETER(buffer);
    UNREFERENCED_PARAMETER(size);

    // Marshal the parameters
    return parameterSize;
}

TPM_RC
TPM2_FlushContext_Parameter_Unmarshal(
    Marshal_Parms *parms,
    BYTE **buffer,
    INT32 *size
)
{
//    FlushContext_In *in = (FlushContext_In *)parms->parmIn;
//    FlushContext_Out *out = (FlushContext_Out *)parms->parmOut;
    TPM_RC result = TPM_RC_SUCCESS;

    UNREFERENCED_PARAMETER(parms);
    UNREFERENCED_PARAMETER(buffer);
    UNREFERENCED_PARAMETER(size);

    // Unmarshal the parameters
    return result;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">

    <title>My Udacity Projects</title>

    <link rel="stylesheet" href="styles.css">

Udacity Project Submissions

Movie Trailer Website

Log Analysis

Note: This page will get prettier evenctually.


text:
const { loadPass, pkPassHasValue } = require('./utils.js');

test('a converted offer pkpass has a title field', async () => {
  const { pkPass, pass } = await loadPass('offer.json');
  expect(pkPassHasValue(pkPass.coupon, pass.title)).toBe(true);
});

test('a converted offer Google pass has a title field', async () => {
  const { googlePass, pass } = await loadPass('offer.pkpass');
  expect(googlePass.offerClasses[0].localizedTitle.defaultValue.value).toBe(pass.title);
});


text:
SELECT RUN_METRIC('chrome/chrome_tasks.sql');

SELECT full_name, task_type, count() as count
FROM chrome_tasks
WHERE full_name GLOB 'FrameHost::BeginNavigation*'
  OR full_name GLOB 'FrameHost::DidCommitProvisionalLoad*'
  OR full_name GLOB 'FrameHost::DidCommitSameDocumentNavigation*'
  OR full_name GLOB 'FrameHost::DidStopLoading*'
GROUP BY full_name, task_type
ORDER BY count DESC
LIMIT 50;


text:
package eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp;

import java.util.LinkedHashMap;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;

public class HyvalidityformulaBuilderAdapter extends IncrementalProjectBuilder {

	private static class ResourceCollector implements IResourceDeltaVisitor, IResourceVisitor {

		private Map<IResource, Boolean> resourceMap = new LinkedHashMap<IResource, Boolean>();

		public boolean visit(IResourceDelta delta) throws CoreException {
			IResource resource = delta.getResource();
			return doVisit(resource, delta.getKind() == IResourceDelta.REMOVED);
		}

		public boolean visit(IResource resource) throws CoreException {
			return doVisit(resource, false);
		}

		private boolean doVisit(IResource resource, boolean removed) throws CoreException {
			resourceMap.put(resource, removed);
			return true;
		}

		private Map<IResource, Boolean> getResourceMap() {
			return resourceMap;
		}

	}

	/**
	 * The ID of the default, generated builder.
	 */
	public final static String BUILDER_ID = "eu.hyvar.context.contextValidity.resource.hyvalidityformula.builder";

	private eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaBuilder defaultBuilder = new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaBuilder();

	public IProject[] build(int kind, Map<String, String> args, final IProgressMonitor monitor) throws CoreException {
		// Collect resources that must be built
		ResourceCollector resourceCollector = new ResourceCollector();
		IResourceDelta delta = getDelta(getProject());
		if (delta != null) {
			// This is an incremental build
			delta.accept(resourceCollector);
		} else {
			// This is a full build
			getProject().accept(resourceCollector);
		}

		// This resource set is used during the whole build.
		ResourceSet resourceSet = new ResourceSetImpl();
		Map<IResource, Boolean> resourceMap = resourceCollector.getResourceMap();
		monitor.beginTask(eu.hyvar.context.contextValidity.resource.hyvalidityformula.HyvalidityformulaResourceBundle.BUILDER_ADAPTER_TASK_NAME, resourceMap.size() * 2);
		for (IResource resource : resourceMap.keySet()) {
			doVisit(resource, resourceMap.get(resource), monitor, resourceSet);
		}
		monitor.done();
		return null;
	}

	public void build(IFile resource, ResourceSet resourceSet, IProgressMonitor monitor) {
		URI uri = URI.createPlatformResourceURI(resource.getFullPath().toString(), true);
		eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaBuilder builder = getBuilder();
		if (builder.isBuildingNeeded(uri)) {
			eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource customResource = (eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource) resourceSet.getResource(uri, true);
			new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaMarkerHelper().removeAllMarkers(resource, getBuilderMarkerId());
			builder.build(customResource, monitor);
		}
	}

	/**
	 * Returns the builder that shall be used by this adapter. This allows subclasses
	 * to perform builds with different builders.
	 */
	public eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaBuilder getBuilder() {
		return defaultBuilder;
	}

	/**
	 * Returns the id for the markers that are created by this builder. This allows
	 * subclasses to produce different kinds of markers.
	 */
	public String getBuilderMarkerId() {
		return new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaMarkerHelper().getMarkerID(eu.hyvar.context.contextValidity.resource.hyvalidityformula.HyvalidityformulaEProblemType.BUILDER_ERROR);
	}

	/**
	 * Runs the task item builder to search for new task items in changed resources.
	 */
	public void runTaskItemBuilder(IFile resource, ResourceSet resourceSet, IProgressMonitor monitor) {
		eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaTaskItemBuilder taskItemBuilder = new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaTaskItemBuilder();
		taskItemBuilder.build(resource, resourceSet, monitor);
	}

	protected boolean doVisit(IResource resource, boolean removed, IProgressMonitor monitor, ResourceSet resourceSet) throws CoreException {
		if (removed) {
			URI uri = URI.createPlatformResourceURI(resource.getFullPath().toString(), true);
			eu.hyvar.context.contextValidity.resource.hyvalidityformula.IHyvalidityformulaBuilder builder = getBuilder();
			if (builder.isBuildingNeeded(uri)) {
				builder.handleDeletion(uri, monitor);
			}
			new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaMarkerHelper().removeAllMarkers(resource, getBuilderMarkerId());
			return false;
		}

		if (resource instanceof IFile && resource.getName().endsWith("." + new eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaMetaInformation().getSyntaxName())) {
			// Calling the default generated builder is disabled because of syntax option
			// 'disableBuilder'.
			monitor.worked(1);
			// Second, call the task item builder that searches for task items in DSL
			// documents and creates task markers. The TaskItemBuilder may consume one tick
			// from the progress monitor.
			runTaskItemBuilder((IFile) resource, resourceSet, monitor);
			return false;
		}

		return true;
	}

}


text:
package apple.coreservices;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;

/*<javadoc>*/
/*</javadoc>*/
@Mapping("CFHTTPAuthenticationRef") @Library("CFNetwork/CFNetwork.h")
public class CFHTTPAuthentication
    extends CFType
     {

    protected CFHTTPAuthentication() {}

    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationGetTypeID")
    public static native @MachineSizedUInt long getClassTypeID();
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationCreateFromResponse")
    public static native CFHTTPAuthentication create(CFAllocator alloc, CFHTTPMessage response);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationIsValid")
    public static native boolean isValid(CFHTTPAuthentication auth, Todo error);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationAppliesToRequest")
    public static native boolean appliesToRequest(CFHTTPAuthentication auth, CFHTTPMessage request);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationRequiresOrderedRequests")
    public static native boolean requiresOrderedRequests(CFHTTPAuthentication auth);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationCopyRealm")
    public static native CFString getRealm(CFHTTPAuthentication auth);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationCopyDomains")
    public static native NSArray<NSURL> getDomains(CFHTTPAuthentication auth);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationCopyMethod")
    public static native CFString getMethod(CFHTTPAuthentication auth);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationRequiresUserNameAndPassword")
    public static native boolean requiresUserNameAndPassword(CFHTTPAuthentication auth);
    /**
     * @since Available in iOS 2.0 and later.
     */
    @GlobalFunction("CFHTTPAuthenticationRequiresAccountDomain")
    public static native boolean requiresAccountDomain(CFHTTPAuthentication auth);

}


text:
<?php

$view->extend('MauticCoreBundle:Default:content.html.php');
$view['slots']->set('mauticContent', 'monitoring');
$view['slots']->set("headerTitle", $activeMonitoring->getTitle());

// @todo finish ACL here
$view['slots']->set('actions', $view->render('MauticCoreBundle:Helper:page_actions.html.php', array(
            'item'       => $activeMonitoring,
            'templateButtons' => array(
                'edit'       => $view['security']->isGranted('plugin:mauticSocial:monitoring:edit'),
                'delete'     => $view['security']->isGranted('plugin:mauticSocial:monitoring:delete'),
                'close'      => $view['security']->isGranted('plugin:mauticSocial:monitoring:view')
            ),
            'routeBase'  => 'social',
            'langVar'    => 'monitoring',
            'nameGetter' => 'getTitle'
        )));
echo $view['assets']->includeScript('plugins/MauticSocialBundle/Assets/js/social.js');
?>

<?php echo $activeMonitoring->getDescription(); ?>

                        <?php echo $view->render('MauticCoreBundle:Helper:publishstatus_badge.html.php', array('entity' => $activeMonitoring)); ?>

                                <?php echo $view->render('MauticCoreBundle:Helper:details.html.php', array('entity' => $activeMonitoring)); ?>

                                        <?php echo $view['translator']->trans('mautic.social.monitoring.' . $activeMonitoring->getNetworkType() . '.popularity'); ?>

                                    <?php echo $view->render('MauticCoreBundle:Helper:graph_dateselect.html.php', array('dateRangeForm' => $dateRangeForm, 'class' => 'pull-right')); ?>

                                <?php echo $view->render('MauticCoreBundle:Helper:chart.html.php', array('chartData' => $leadStats, 'chartType' => 'line', 'chartHeight' => 300)); ?>

                        <?php echo $view['translator']->trans('mautic.lead.leads'); ?>

                <?php echo $monitorLeads; ?>

                    <?php echo $view->render('MauticCoreBundle:Helper:recentactivity.html.php', array('logs' => $logs)); ?>

    <input id="itemId" type="hidden" value="<?php echo $activeMonitoring->getId(); ?>" />


text:
package org.compass.core.lucene.engine.manager;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.Lock;
import org.compass.core.engine.SearchEngineException;
import org.compass.core.engine.SearchEngineIndexManager;
import org.compass.core.lucene.LuceneEnvironment;
import org.compass.core.lucene.engine.LuceneSearchEngineFactory;
import org.compass.core.lucene.engine.LuceneSettings;
import org.compass.core.lucene.engine.store.LuceneSearchEngineStore;
import org.compass.core.lucene.util.LuceneUtils;
import org.compass.core.util.concurrent.SingleThreadThreadFactory;

/**
 * @author kimchy
 */
public class DefaultLuceneSearchEngineIndexManager implements LuceneSearchEngineIndexManager {

    private static Log log = LogFactory.getLog(DefaultLuceneSearchEngineIndexManager.class);

    public static final String CLEAR_CACHE_NAME = "clearcache";

    private LuceneSearchEngineFactory searchEngineFactory;

    private LuceneSearchEngineStore searchEngineStore;

    private LuceneSettings luceneSettings;

    // holds the index cache per sub index
    private HashMap indexHolders = new HashMap();

    private HashMap indexHoldersLocks = new HashMap();

    private long[] lastModifiled;

    private long waitForCacheInvalidationBeforeSecondStep = 0;

    private boolean isRunning = false;

    private ExecutorService commitExecutorService;

    private int concurrentCommitThreshold;

    public DefaultLuceneSearchEngineIndexManager(LuceneSearchEngineFactory searchEngineFactory,
                                                 final LuceneSearchEngineStore searchEngineStore) {
        this.searchEngineFactory = searchEngineFactory;
        this.searchEngineStore = searchEngineStore;
        this.luceneSettings = searchEngineFactory.getLuceneSettings();
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            indexHoldersLocks.put(subIndexes[i], new Object());
        }
        if (searchEngineStore.allowConcurrentCommit() &&
                searchEngineFactory.getSettings().getSettingAsBoolean(LuceneEnvironment.Transaction.ENABLE_CONCURRENT_COMMIT, true)) {
            concurrentCommitThreshold = searchEngineFactory.getSettings().getSettingAsInt(LuceneEnvironment.Transaction.CONCURRENT_COMMIT_THRESHOLD, 1);
            int maxThreads = searchEngineFactory.getSettings().getSettingAsInt(LuceneEnvironment.Transaction.MAX_CONCURRENT_COMMIT_THREADS, 10);
            if (searchEngineStore.getSubIndexes().length < maxThreads) {
                maxThreads = searchEngineStore.getSubIndexes().length;
            }
            if (maxThreads > 0) {
                commitExecutorService = Executors.newFixedThreadPool(maxThreads, new SingleThreadThreadFactory("Compass Concurrent Commit", false));
                if (log.isDebugEnabled()) {
                    log.debug("Concurrent commit is enabled with max threads of [" + maxThreads + "]");
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Concurrent commit is disabled since maxThreads is set to 0 (might be there are no sub indexes, i.e. no mappings?)");
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Concurrent commit is disabled (either due to setting or store not supporting it)");
            }
        }
    }

    public void createIndex() throws SearchEngineException {
        if (log.isDebugEnabled()) {
            log.debug("Creating index " + searchEngineStore);
        }
        clearCache();
        searchEngineStore.createIndex();
    }

    public void deleteIndex() throws SearchEngineException {
        if (log.isDebugEnabled()) {
            log.debug("Deleting index " + searchEngineStore);
        }
        clearCache();
        searchEngineStore.deleteIndex();
    }

    public boolean verifyIndex() throws SearchEngineException {
        clearCache();
        boolean result = searchEngineStore.verifyIndex();
        if (luceneSettings.isUseCompoundFile() && !isIndexCompound()) {
            log.info("Setting using compound file, but the index is not in compound form, compounding the index...");
            compoundIndex();
        } else if (!luceneSettings.isUseCompoundFile() && !isIndexUnCompound()) {
            log.info("Setting not using compound file, but the index is in compound form, un-compounding the index...");
            unCompoundIndex();
        }
        return result;
    }

    public boolean indexExists() throws SearchEngineException {
        return searchEngineStore.indexExists();
    }

    public void operate(final IndexOperationCallback callback) throws SearchEngineException {
        // first aquire write lock for all the sub-indexes
        final String[] subIndexes = searchEngineStore.getSubIndexes();
        final Lock[] writerLocks = new Lock[subIndexes.length];

        try {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Trying to obtain write locks");
                }
                for (int i = 0; i < subIndexes.length; i++) {
                    Directory dir = getDirectory(subIndexes[i]);
                    writerLocks[i] = dir.makeLock(IndexWriter.WRITE_LOCK_NAME);
                    writerLocks[i].obtain(luceneSettings.getTransactionLockTimout());
                }
                if (log.isDebugEnabled()) {
                    log.debug("Obtained write locks");
                }
            } catch (Exception e) {
                throw new SearchEngineException("Failed to retrieve dirty transaction locks", e);
            }
            if (log.isDebugEnabled()) {
                log.debug("Calling callback first step");
            }
            // call the first step
            boolean continueToSecondStep = callback.firstStep();
            if (!continueToSecondStep) {
                return;
            }

            // perform the replace operation

            // TODO here we need to make sure that no read operations will happen as well

            // tell eveybody that are using the index, to clear the cache
            clearCache();
            notifyAllToClearCache();

            if (waitForCacheInvalidationBeforeSecondStep != 0 && luceneSettings.isWaitForCacheInvalidationOnIndexOperation()) {
                // now wait for the cache invalidation
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Waiting [" + waitForCacheInvalidationBeforeSecondStep + "ms] for global cache invalidation");
                    }
                    Thread.sleep(waitForCacheInvalidationBeforeSecondStep);
                } catch (InterruptedException e) {
                    log.debug("Interrupted while waiting for cache invalidation", e);
                    throw new SearchEngineException("Interrupted while waiting for cache invalidation", e);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("Calling callback second step");
            }
            // call the second step
            callback.secondStep();
        } finally {
            LuceneUtils.clearLocks(writerLocks);
        }
    }

    public void replaceIndex(SearchEngineIndexManager indexManager, final ReplaceIndexCallback callback) throws SearchEngineException {
        final LuceneSearchEngineIndexManager luceneIndexManager = (LuceneSearchEngineIndexManager) indexManager;

        operate(new IndexOperationCallback() {
            public boolean firstStep() throws SearchEngineException {
                callback.buildIndexIfNeeded();
                return true;
            }

            public void secondStep() throws SearchEngineException {
                if (log.isDebugEnabled()) {
                    log.debug("[Replace Index] Replacing index [" + searchEngineStore + "] with ["
                            + luceneIndexManager.getStore() + "]");
                }
                // copy over the index by renaming the original one, and copy the new one
                searchEngineStore.copyFrom(luceneIndexManager.getStore());
                if (log.isDebugEnabled()) {
                    log.debug("[Replace Index] Index [" + searchEngineStore + "] replaced from ["
                            + luceneIndexManager.getStore() + "]");
                }
            }
        });
    }

    public void notifyAllToClearCache() throws SearchEngineException {
        if (log.isDebugEnabled()) {
            log.debug("Global notification to clear cache");
        }
        String[] subIndexes = searchEngineStore.getSubIndexes();
        // just update the last modified time, others will see the change and update
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            try {
                if (!dir.fileExists(CLEAR_CACHE_NAME)) {
                    dir.createOutput(CLEAR_CACHE_NAME).close();
                } else {
                    dir.touchFile(CLEAR_CACHE_NAME);
                }
            } catch (IOException e) {
                throw new SearchEngineException("Failed to update/generate global invalidation cahce", e);
            }
        }
    }

    public boolean isCached(String subIndex) throws SearchEngineException {
        synchronized (indexHoldersLocks.get(subIndex)) {
            return indexHolders.containsKey(subIndex);
        }
    }

    public boolean isCached() throws SearchEngineException {
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            if (isCached(subIndexes[i])) {
                return true;
            }
        }
        return false;
    }

    public void clearCache() throws SearchEngineException {
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            clearCache(subIndexes[i]);
        }
    }

    public void clearCache(String subIndex) throws SearchEngineException {
        synchronized (indexHoldersLocks.get(subIndex)) {
            LuceneIndexHolder indexHolder = (LuceneIndexHolder) indexHolders.remove(subIndex);
            if (indexHolder != null) {
                indexHolder.markForClose();
            }
        }
    }

    public void refreshCache(String subIndex, IndexSearcher indexSearcher) throws SearchEngineException {
        synchronized (indexHoldersLocks.get(subIndex)) {
            LuceneIndexHolder indexHolder = (LuceneIndexHolder) indexHolders.remove(subIndex);
            if (indexHolder != null) {
                indexHolder.markForClose();
            }
            indexHolder = new LuceneIndexHolder(subIndex, indexSearcher, getDirectory(subIndex));
            indexHolders.put(subIndex, indexHolder);
        }
    }

    public LuceneIndexHolder openIndexHolderBySubIndex(String subIndex) throws SearchEngineException {
        synchronized (indexHoldersLocks.get(subIndex)) {
            try {
                Directory dir = getDirectory(subIndex);
                LuceneIndexHolder indexHolder = (LuceneIndexHolder) indexHolders.get(subIndex);
                if (shouldInvalidateCache(dir, indexHolder)) {
                    clearCache(subIndex);
                    // get a new directory and put it in the cache
                    dir = getDirectory(subIndex);
                    // do the same with index holder
                    indexHolder = new LuceneIndexHolder(subIndex, dir);
                    indexHolders.put(subIndex, indexHolder);
                }
                indexHolder.acquire();
                return indexHolder;
            } catch (Exception e) {
                throw new SearchEngineException("Failed to open index searcher for sub-index [" + subIndex + "]", e);
            }
        }
    }

    protected boolean shouldInvalidateCache(Directory dir, LuceneIndexHolder indexHolder) throws IOException, IllegalAccessException {
        long currentTime = System.currentTimeMillis();
        // we have not created an index holder, invalidated by default
        if (indexHolder == null) {
            return true;
        }
        // configured to perform no cache invalidation
        if (luceneSettings.getCacheInvalidationInterval() == -1) {
            return false;
        }
        if ((currentTime - indexHolder.getLastCacheInvalidation()) > luceneSettings.getCacheInvalidationInterval()) {
            indexHolder.setLastCacheInvalidation(currentTime);
            if (!indexHolder.getIndexReader().isCurrent()) {
                return true;
            }
        }
        return false;
    }

    public synchronized void close() {
        if (commitExecutorService != null) {
            commitExecutorService.shutdown();
        }
        clearCache();
        searchEngineStore.close();
    }

    public IndexWriter openIndexWriter(Directory dir, boolean create) throws IOException {
        IndexWriter indexWriter = new IndexWriter(dir, true, searchEngineFactory.getAnalyzerManager().getDefaultAnalyzer(),
                create, searchEngineFactory.getIndexDeletionPolicyManager().createIndexDeletionPolicy(dir));
        indexWriter.setMaxMergeDocs(luceneSettings.getMaxMergeDocs());
        indexWriter.setMergeFactor(luceneSettings.getMergeFactor());
        indexWriter.setUseCompoundFile(luceneSettings.isUseCompoundFile());
        indexWriter.setMaxFieldLength(luceneSettings.getMaxFieldLength());
        indexWriter.setMaxBufferedDocs(luceneSettings.getMaxBufferedDocs());
        return indexWriter;
    }

    public void closeIndexWriter(String subIndex, IndexWriter indexWriter, Directory dir) throws SearchEngineException {
        Exception ex = null;
        try {
            closeIndexWriter(indexWriter);
        } catch (Exception e) {
            ex = e;
        }
        try {
            searchEngineStore.closeDirectory(subIndex, dir);
        } catch (Exception e) {
            if (ex == null) {
                ex = e;
            } else {
                log.warn("Caught an exception trying to close the lucene directory "
                        + "with other exception pending, logging and ignoring", e);
            }
        }
        if (ex != null) {
            if (ex instanceof SearchEngineException) {
                throw (SearchEngineException) ex;
            }
            throw new SearchEngineException("Failed while executing a lucene directory based operation", ex);
        }
    }

    protected void closeIndexWriter(IndexWriter indexWriter) throws SearchEngineException {
        try {
            if (indexWriter != null) {
                indexWriter.close();
            }
        } catch (IOException e) {
            throw new SearchEngineException("Failed to close index reader", e);
        }
    }

    public LuceneSearchEngineStore getStore() {
        return searchEngineStore;
    }

    protected Directory getDirectory(String subIndex) {
        return searchEngineStore.getDirectoryBySubIndex(subIndex, false);
    }

    public void start() {
        isRunning = true;
    }

    public void stop() {
        isRunning = false;
    }

    public boolean isRunning() {
        return isRunning;
    }

    public synchronized void checkAndClearIfNotifiedAllToClearCache() throws SearchEngineException {
        if (lastModifiled == null) {
            String[] subIndexes = searchEngineStore.getSubIndexes();
            // just update the last modified time, others will see the change and update
            for (int i = 0; i < subIndexes.length; i++) {
                Directory dir = getDirectory(subIndexes[i]);
                try {
                    if (dir.fileExists(CLEAR_CACHE_NAME)) {
                        continue;
                    }
                } catch (IOException e) {
                    throw new SearchEngineException("Failed to check if global clear cache exists", e);
                }
                try {
                    dir.createOutput(CLEAR_CACHE_NAME).close();
                } catch (IOException e) {
                    throw new SearchEngineException("Failed to update/generate global invalidation cahce", e);
                }
            }
            lastModifiled = new long[subIndexes.length];
            for (int i = 0; i < subIndexes.length; i++) {
                Directory dir = getDirectory(subIndexes[i]);
                try {
                    lastModifiled[i] = dir.fileModified(CLEAR_CACHE_NAME);
                } catch (IOException e) {
                    // do nothing
                }
            }
        }
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            long lastMod;
            try {
                lastMod = dir.fileModified(CLEAR_CACHE_NAME);
            } catch (IOException e) {
                throw new SearchEngineException("Failed to check last modified on global index chache on sub index ["
                        + subIndexes[i] + "]", e);
            }
            if (lastModifiled[i] < lastMod) {
                if (log.isDebugEnabled()) {
                    log.debug("Global notification to clear cache detected on sub index [" + subIndexes[i] + "]");
                }
                lastModifiled[i] = lastMod;
                clearCache(subIndexes[i]);
            }
        }
    }

    public boolean isIndexCompound() throws SearchEngineException {
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            try {
                if (!org.apache.lucene.index.LuceneUtils.isCompound(dir)) {
                    return false;
                }
            } catch (IOException e) {
                throw new SearchEngineException("Failed to check if index is compound", e);
            }
        }
        return true;
    }

    public boolean isIndexUnCompound() throws SearchEngineException {
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            try {
                if (!org.apache.lucene.index.LuceneUtils.isUnCompound(dir)) {
                    return false;
                }
            } catch (IOException e) {
                throw new SearchEngineException("Failed to check if index is unCompound", e);
            }
        }
        return true;
    }

    public void compoundIndex() throws SearchEngineException {
        if (log.isDebugEnabled()) {
            log.debug("Compounding index " + searchEngineStore);
        }
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            try {
                org.apache.lucene.index.LuceneUtils.compoundDirectory(dir, luceneSettings.getTransactionLockTimout());
            } catch (IOException e) {
                throw new SearchEngineException("Failed to compound index", e);
            }
        }
    }

    public void unCompoundIndex() throws SearchEngineException {
        if (log.isDebugEnabled()) {
            log.debug("UnCompounding index " + searchEngineStore);
        }
        String[] subIndexes = searchEngineStore.getSubIndexes();
        for (int i = 0; i < subIndexes.length; i++) {
            Directory dir = getDirectory(subIndexes[i]);
            try {
                org.apache.lucene.index.LuceneUtils.unCompoundDirectory(dir, luceneSettings.getTransactionLockTimout());
            } catch (IOException e) {
                throw new SearchEngineException("Failed to unCompuond index", e);
            }
        }
    }

    public void performScheduledTasks() throws SearchEngineException {
        checkAndClearIfNotifiedAllToClearCache();
        getStore().performScheduledTasks();
    }

    public String[] getSubIndexes() {
        return searchEngineStore.getSubIndexes();
    }

    public boolean isLocked() throws SearchEngineException {
        return searchEngineStore.isLocked();
    }

    public boolean isLocked(String subIndex) throws SearchEngineException {
        return searchEngineStore.isLocked(subIndex);
    }

    public void releaseLocks() throws SearchEngineException {
        searchEngineStore.releaseLocks();
    }

    public void releaseLock(String subIndex) throws SearchEngineException {
        searchEngineStore.releaseLock(subIndex);
    }

    public void executeCommit(Callable[] commits) throws SearchEngineException {
        if (commits.length == 0) {
            return;
        }
        // if the commit executor is created, we can do concurrent commits
        // if not, serialize it by callling it one after the other
        if (commitExecutorService != null && commits.length > concurrentCommitThreshold) {
            List futures;
            try {
                Collection commitsCol = Arrays.asList(commits);
                futures = commitExecutorService.invokeAll(commitsCol);
            } catch (InterruptedException e) {
                throw new SearchEngineException("Failed to concurrent commit, interrupted", e);
            }

            for (Iterator it = futures.iterator(); it.hasNext();) {
                Future future = (Future) it.next();
                try {
                    future.get();
                } catch (InterruptedException e) {
                    throw new SearchEngineException("Failed to concurrent commit, interrupted", e);
                } catch (ExecutionException e) {
                    if (e.getCause() instanceof SearchEngineException) {
                        throw (SearchEngineException) e.getCause();
                    }
                    throw new SearchEngineException("Failed to execute commit", e.getCause());
                }
            }
        } else {
            for (int i = 0; i < commits.length; i++) {
                try {
                    commits[i].call();
                } catch (Exception e) {
                    if (e instanceof SearchEngineException) {
                        throw (SearchEngineException) e;
                    }
                    throw new SearchEngineException("Failed to execute commit", e);
                }
            }
        }
    }

    public void setWaitForCacheInvalidationBeforeSecondStep(long timeToWaitInMillis) {
        this.waitForCacheInvalidationBeforeSecondStep = timeToWaitInMillis;
    }

    public LuceneSettings getSettings() {
        return luceneSettings;
    }
}