text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="tool_bar" type="id"/>
</resources>

redpajama_set_name: RedPajamaGithub


text: package 'openssl'


text:
"""
This module implements a set of languages as collections of features that are
language specific.

feature collections
+++++++++++++++++++
Languages implement a subset of feature collections (e.g.
:class:`~revscoring.languages.features.Dictionary`,
:class:`~revscoring.languages.features.Stopwords`,
:class:`~revscoring.languages.features.Stemmed` and
:class:`~revscoring.languages.features.RegexMatches`) based on what
language assets are available. See :mod:`revscoring.languages.features`.

dutch
+++++
.. automodule:: revscoring.languages.arabic
    :members:

dutch
+++++
.. automodule:: revscoring.languages.dutch
    :members:

english
+++++++
.. automodule:: revscoring.languages.english
    :members:

estonian
++++++++
.. automodule:: revscoring.languages.estonian
    :members:

french
++++++
.. automodule:: revscoring.languages.french
    :members:

german
++++++
.. automodule:: revscoring.languages.german
    :members:

hebrew
++++++
.. automodule:: revscoring.languages.hebrew
    :members:

indonesian
++++++++++
.. automodule:: revscoring.languages.indonesian
    :members:

italian
+++++++
.. automodule:: revscoring.languages.italian
    :members:

japanese
+++++++
.. automodule:: revscoring.languages.japanese
    :members:

persian
+++++++
.. automodule:: revscoring.languages.persian
    :members:

portuguese
++++++++++
.. automodule:: revscoring.languages.portuguese
    :members:

spanish
+++++++
.. automodule:: revscoring.languages.spanish
    :members:

turkish
+++++++
.. automodule:: revscoring.languages.turkish
    :members:

ukrainian
+++++++++
.. automodule:: revscoring.languages.ukrainian
    :members:

vietnamese
++++++++++
.. automodule:: revscoring.languages.vietnamese
    :members:

"""


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-3851',
  templateUrl: './comp-3851.component.html',
  styleUrls: ['./comp-3851.component.css']
})
export class Comp3851Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
<?php

use yii\helpers\HtmlPurifier;

/* @var $this yii\web\View */
/* @var $model backend\models\Currencies */

$this->title = $model->name.' '.HtmlPurifier::process('—').' Валюты | '.Yii::$app->name;
$this->params['breadcrumbs'][] = ['label' => 'Валюты', 'url' => ['/currencies']];
$this->params['breadcrumbs'][] = $model->name;

$this->params['content-block'] = $model->name;
$this->params['content-additional'] = 'Редактирование существующей валюты';
?>
<div class="currencies-update">
    <?= $this->render('_form', ['model' => $model,]) ?>

</div>


text:
package com.deadpool.manager.controller.helper;

import com.deadpool.manager.domain.model.ExecutionStrategy;
import com.deadpool.manager.domain.model.ProcessDescriptor;
import com.deadpool.manager.domain.model.TestSuite;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.*;

/**
 * Created by roothema on 2015.10.08..
 */
public class HttpRequestHelper {

    public static Response callNewTestSuiteEndpoint(TestSuite testSuite) {
        return given().contentType(ContentType.JSON).body(testSuite).when().post("/test-suite");
    }

    public static Response callNewExecutionStrategyEndpoint(ExecutionStrategy executionStrategy) {
        return given().contentType(ContentType.JSON).body(executionStrategy).when().post("/execution-strategy");
    }

    public static Response callGetTestSuiteEndpoint(String testSuiteName) {
        return get("/test-suite/" + testSuiteName);
    }

    public static Response callGetExecutionStrategyEndpoint(String executionStrategyName) {
        return get("/execution-strategy/" + executionStrategyName);
    }

    public static Response callListTestSuiteEndpoint() {
        return get("/test-suite");
    }

    public static Response callRunTestSuiteEndpoint(ProcessDescriptor processDescriptor) {
        return given().contentType(ContentType.JSON).body(processDescriptor).when().post("/run/");
    }

    public static Response callDeleteTestSuiteEndpoint(String testSuiteName) {
        return delete("/test-suite/" + testSuiteName);
    }

    public static Response callDeleteExecutionStrategyEndpoint(String executionStrategyName) {
        return delete("/execution-strategy/" + executionStrategyName);
    }
}


text:
Jump
====

Bash functions to move faster with frequent directories

Installation
------------

Copy the file `jump-completion.bash` in `~/.jump-completion.bash`.

Then :

```
$ source /path/to/jump/jump.sh
```
or copy the content of jump.sh into your bashrc file.

Functions
---------

Create a mark in $MARKPATH folder:

```
$ cd my/folder
$ mark
```

List your marks:
```
$ marks
```

Move to your folder:
```
$ jump folder
```

Remove the mark:
```
$ unmark folder
```

Variables
---------

`jump.sh` includes some *export* command too. So, if you have marked the dir `/path/to/directory/foo` you can type:

```
$ mv proto.file $jfoo
```

Completion in bash will automatically expand var *$jfoo* as the full path to `foo` directory


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LambdastylePrototype;
using LambdastylePrototype.Interpreter;
using LambdastylePrototype.Interpreter.Predicates;
using LambdastylePrototype.Interpreter.Subjects;

namespace Test.input4.json._4_remove_every_key_with_value_ending_with_id
{
    class Style
    {
        void Build(Builder builder)
        {
            builder.Add(
                new Sentence(new Subject(new Equals(new Any(), new LiteralishSequence(new Any(), new Literal("&id=")))),
                    new Predicate()),
                Consts.CopyAny);
        }
    }
}


text:
require_relative 'html_parser'

module IKnowWhereYouLive
	module TemplateMetadata
		def self.included(base)
			base.class_eval do
				alias_method :original_render, :render

				def render(*args)
					output = original_render(*args)
					add_metadata(output, *args)
				end
			end
		end

		def add_metadata(output, context, options, block = nil)
		  partial = options.key?(:partial)
		  template = options.key?(:template)
		  fragment = partial ? send(:find_partial) : determine_template(options)
		  if (partial || template) && fragment.formats.include?(:html)
		    HTMLParser.add_metadata(output, fragment, partial)
		  else
			  output
		  end
		end
	end
end


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Controller;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;

use Oro\Bundle\WorkflowBundle\Entity\WorkflowItem;
use Oro\Bundle\WorkflowBundle\Model\Workflow;
use Oro\Bundle\WorkflowBundle\Model\WorkflowManager;
use Oro\Bundle\WorkflowBundle\Model\Transition;
use Oro\Bundle\WorkflowBundle\Serializer\WorkflowAwareSerializer;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\EntityBundle\Exception\NotManageableEntityException;
use Oro\Bundle\WorkflowBundle\Model\WorkflowData;

/**
 * @Route("/workflowwidget")
 */
class WidgetController extends Controller
{
    /**
     * @Route("/steps/{entityClass}/{entityId}", name="oro_workflow_widget_steps")
     * @Template
     * @AclAncestor("oro_workflow")
     */
    public function stepsAction($entityClass, $entityId)
    {
        $entity = $this->getEntityReference($entityClass, $entityId);

        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');
        $workflowItem    = $workflowManager->getWorkflowItemByEntity($entity);

        $steps = array();
        $currentStep = null;
        if ($workflowItem) {
            $workflow = $workflowManager->getWorkflow($workflowItem);

            if ($workflow->getDefinition()->isStepsDisplayOrdered()) {
                $steps = $workflow->getStepManager()->getOrderedSteps();
            } else {
                $steps = $workflow->getPassedStepsByWorkflowItem($workflowItem);
            }

            $currentStep = $workflowItem->getCurrentStep();
        }

        return array(
            'steps' => $steps,
            'currentStep' => $currentStep,
        );
    }

    /**
     * @Route(
     *      "/transition/create/attributes/{workflowName}/{transitionName}",
     *      name="oro_workflow_widget_start_transition_form"
     * )
     * @Template("OroWorkflowBundle:Widget:transitionForm.html.twig")
     * @AclAncestor("oro_workflow")
     * @param string $transitionName
     * @param string $workflowName
     * @return array
     * @throws BadRequestHttpException
     */
    public function startTransitionFormAction($transitionName, $workflowName)
    {
        $entityId = $this->getRequest()->get('entityId', 0);

        /** @var DoctrineHelper $doctrineHelper */
        $doctrineHelper = $this->get('oro_entity.doctrine_helper');

        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');
        $workflow = $workflowManager->getWorkflow($workflowName);
        $entityClass = $workflow->getDefinition()->getRelatedEntity();

        $entity = $this->getEntityReference($entityClass, $entityId);

        $workflowItem = $workflow->createWorkflowItem($entity);
        $transition = $workflow->getTransitionManager()->extractTransition($transitionName);
        $transitionForm = $this->getTransitionForm($workflowItem, $transition);

        $data = null;
        $saved = false;
        if ($this->getRequest()->isMethod('POST')) {
            $transitionForm->submit($this->getRequest());

            if ($transitionForm->isValid()) {
                // Create new WorkflowData instance with all data required to start.
                // Original WorkflowData can not be used, as some attributes may be set by reference
                // So, serialized data will not contain all required data.
                $formOptions = $transition->getFormOptions();
                $attributes = array_keys($formOptions['attribute_fields']);

                $existingAttributes = $workflowItem->getData()->getValues();
                $formAttributes = $workflowItem->getData()->getValues($attributes);
                foreach ($existingAttributes + $formAttributes as $value) {
                    // Need to persist all new entities to allow serialization
                    // and correct passing to API start method of all input data.
                    // Form validation already performed, so all these entities are valid
                    // and they can be used in workflow start action.
                    if (is_object($value) && $doctrineHelper->isManageableEntity($value)) {
                        $entityManager = $doctrineHelper->getEntityManager($value);
                        $unitOfWork = $entityManager->getUnitOfWork();
                        if (!$unitOfWork->isInIdentityMap($value) || $unitOfWork->isScheduledForInsert($value)) {
                            $entityManager->persist($value);
                            $entityManager->flush($value);
                        }
                    }
                }

                /** @var WorkflowAwareSerializer $serializer */
                $serializer = $this->get('oro_workflow.serializer.data.serializer');
                $serializer->setWorkflowName($workflow->getName());
                $data = $serializer->serialize(new WorkflowData($existingAttributes + $formAttributes), 'json');
                $saved = true;
            }
        }

        return array(
            'transition' => $transition,
            'data' => $data,
            'saved' => $saved,
            'workflowItem' => $workflowItem,
            'form' => $transitionForm->createView(),
        );
    }

    /**
     * @Route(
     *      "/transition/edit/attributes/{workflowItemId}/{transitionName}",
     *      name="oro_workflow_widget_transition_form"
     * )
     * @ParamConverter("workflowItem", options={"id"="workflowItemId"})
     * @Template("OroWorkflowBundle:Widget:transitionForm.html.twig")
     * @AclAncestor("oro_workflow")
     * @param string $transitionName
     * @param WorkflowItem $workflowItem
     * @return array
     */
    public function transitionFormAction($transitionName, WorkflowItem $workflowItem)
    {
        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');
        $workflow = $workflowManager->getWorkflow($workflowItem);

        $transition = $workflow->getTransitionManager()->extractTransition($transitionName);
        $transitionForm = $this->getTransitionForm($workflowItem, $transition);

        $saved = false;
        if ($this->getRequest()->isMethod('POST')) {
            $transitionForm->submit($this->getRequest());

            if ($transitionForm->isValid()) {
                $workflowItem->setUpdated();
                $this->getEntityManager()->flush();

                $saved = true;
            }
        }

        return array(
            'transition' => $transition,
            'saved' => $saved,
            'workflowItem' => $workflowItem,
            'form' => $transitionForm->createView(),
        );
    }

    /**
     * Get transition form.
     *
     * @param WorkflowItem $workflowItem
     * @param Transition $transition
     * @return Form
     */
    protected function getTransitionForm(WorkflowItem $workflowItem, Transition $transition)
    {
        return $this->createForm(
            $transition->getFormType(),
            $workflowItem->getData(),
            array_merge(
                $transition->getFormOptions(),
                array(
                    'workflow_item' => $workflowItem,
                    'transition_name' => $transition->getName()
                )
            )
        );
    }

    /**
     * @Route("/buttons/{entityClass}/{entityId}", name="oro_workflow_widget_buttons")
     * @Template
     * @AclAncestor("oro_workflow")
     */
    public function buttonsAction($entityClass, $entityId)
    {
        $showResetButton = false;
        $transitionsData = array();

        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');
        $entity          = $this->getEntityReference($entityClass, $entityId);
        $workflowItem    = $workflowManager->getWorkflowItemByEntity($entity);

        if (!$workflowManager->isResetAllowed($entity)) {
            if ($workflowItem) {
                $transitionsData = $this->getAvailableTransitionsDataByWorkflowItem($workflowItem);
            } else {
                $workflow = $workflowManager->getApplicableWorkflow($entity);
                $transitionsData = $this->getAvailableStartTransitionsData($workflow, $entity);
            }
        } else {
            $showResetButton = true;
        }

        return array(
            'entity_id'       => $entityId,
            'showResetButton' => $showResetButton,
            'transitionsData' => $transitionsData,
            'workflowItem'    => $workflowItem
        );
    }

    /**
     * Get transitions data for view based on workflow item.
     *
     * @param WorkflowItem $workflowItem
     * @return array
     */
    protected function getAvailableTransitionsDataByWorkflowItem(WorkflowItem $workflowItem)
    {
        $transitionsData = array();
        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');
        $transitions = $workflowManager->getTransitionsByWorkflowItem($workflowItem);
        /** @var Transition $transition */
        foreach ($transitions as $transition) {
            if (!$transition->isHidden()) {
                $errors = new ArrayCollection();
                $isAllowed = $workflowManager->isTransitionAvailable($workflowItem, $transition, $errors);
                if ($isAllowed || !$transition->isUnavailableHidden()) {
                    $transitionsData[] = array(
                        'workflow' => $workflowManager->getWorkflow($workflowItem),
                        'workflowItem' => $workflowItem,
                        'transition' => $transition,
                        'isAllowed' => $isAllowed,
                        'errors' => $errors
                    );
                }
            }
        }
        return $transitionsData;
    }

    /**
     * Get start transitions data for view based on workflow and entity.
     *
     * @param Workflow $workflow
     * @param object $entity
     * @return array
     */
    protected function getAvailableStartTransitionsData(Workflow $workflow, $entity)
    {
        $transitionsData = array();
        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');

        $transitions = $workflowManager->getStartTransitions($workflow);
        /** @var Transition $transition */
        foreach ($transitions as $transition) {
            if (!$transition->isHidden()) {
                $transitionData = $this->getStartTransitionData($workflow, $transition, $entity);
                if ($transitionData !== null) {
                    $transitionsData[] = $transitionData;
                }
            }
        }

        // extra case to show start transition
        if (empty($transitionsData) && $workflow->getStepManager()->hasStartStep()) {
            $defaultStartTransition = $workflow->getTransitionManager()->getDefaultStartTransition();
            if ($defaultStartTransition) {
                $startTransitionData = $this->getStartTransitionData($workflow, $defaultStartTransition, $entity);
                if ($startTransitionData !== null) {
                    $transitionsData[] = $startTransitionData;
                }
            }
        }

        return $transitionsData;
    }

    /**
     * @param Workflow $workflow
     * @param Transition $transition
     * @param object $entity
     * @return array|null
     */
    protected function getStartTransitionData(Workflow $workflow, Transition $transition, $entity)
    {
        /** @var WorkflowManager $workflowManager */
        $workflowManager = $this->get('oro_workflow.manager');

        $errors = new ArrayCollection();
        $isAllowed = $workflowManager
            ->isStartTransitionAvailable($workflow, $transition, $entity, array(), $errors);
        if ($isAllowed || !$transition->isUnavailableHidden()) {
            return array(
                'workflow' => $workflowManager->getWorkflow($workflow),
                'transition' => $transition,
                'isAllowed' => $isAllowed,
                'errors' => $errors
            );
        }

        return null;
    }

    /**
     * Try to get reference to entity
     *
     * @param string $entityClass
     * @param mixed $entityId
     * @throws BadRequestHttpException
     * @return mixed
     */
    protected function getEntityReference($entityClass, $entityId)
    {
        /** @var DoctrineHelper $doctrineHelper */
        $doctrineHelper = $this->get('oro_entity.doctrine_helper');
        try {
            if ($entityId) {
                $entity = $doctrineHelper->getEntityReference($entityClass, $entityId);
            } else {
                $entity = $doctrineHelper->createEntityInstance($entityClass);
            }
        } catch (NotManageableEntityException $e) {
            throw new BadRequestHttpException($e->getMessage(), $e);
        }

        return $entity;
    }

    /**
     * @return EntityManager
     */
    protected function getEntityManager()
    {
        return $this->getDoctrine()->getManagerForClass('OroWorkflowBundle:WorkflowItem');
    }
}


text:
RFC: '0061'
Author: Ilya Sazonov
Status: Rejected
Area:
Comments Due: 6/30/2018
---

# The document purpose

The purpose of this document is to establish a new policy for the creation and use of aliases to ensure:

* Reliable, predictable behavior of scripts and modules
* Increase readability and maintainability of scripts and modules
* UX enhancements in interactive sessions

# Problem description

1. Windows PowerShell has many aliases that conflict with the names of standard Unix utilities.

    These aliases was removed from PowerShell Core.
    This causes a backward compatibility issue when Windows users do not find the familiar aliases in the interactive session.
    It also disrupts the operation of custom scripts that use these aliases.

1. Now there are dozens of modules developed by MSFT and thousands of modules of third developers. This causes a name conflict.

    Developers try to create unique cmdlet names.
    They can use module prefixes to resolve name conflicts.

    On the other hand, developers of the best intentions can complement their modules cmdlet aliases.
    At the same time, users can create their own aliases.

    With a large number of existing modules and cmdlets and a wide variety of custom aliases, these short names inevitably conflict with each other.

    Moreover, the behavior becomes unpredictable because each subsequent download module or script can change any alias.
    Either the user can destroy a script behavior by creating a new alias or by deleting an existing one.

    It is even more unpredictable and dangerous to create scripts in the assumption that there are some predefined (standard) aliases because they can be changed by the user or script at any time.

    Modern versions of ScriptAnalyzer already recommend replacing aliases in scripts with their full names.

    >The definition of aliases in modules or scripts and their automatic import becomes an undesirable and dangerous practice.

1. UX in interactive sessions.

    Having many cmdlets and parameters with long names can make it difficult to enter them in interactive sessions.
    Users who typically use standard settings are typically satisfied with the ```IntellySense``` capabilities.
    On the other hand, some users actively using interactive sessions may still be annoyed by the need to type names.
    These users should be able to upload their familiar and useful aliases sets to their interactive sessions.
    Given the limited functionality of aliases, these users will also configure their environment by executing commands by importing their own functions and various modules using PowerShell profiles.
    It should be noted that we are planning to add a domain-specific language (DSL). This will provide users with much greater customization capabilities than aliases.

# PowerShell alias policy

1. PowerShell implements standard aliases in all sessions including interactive:

    * % -> ForEach-Object
    * foreach -> ForEach-Object
    * ? -> Where-Object
    * where -> Where-Object

    These aliases are actively used in interactive sessions and scripts.
    ScriptAnalyzer will continue to recommend not to use them in scripts and modules.

1. By default, PowerShell does not load aliases from modules and InitialSessionState.

    To ensure module backward compatibility:
    * ```Import-Module -Aliases``` - explicitly loads aliases from the module.
    * Global configuration option ```GlobalAliasImport``` in ```powershell.config``` turns on loading aliases from modules (and InitialSessionState). It is turned off by default.

1. Backward compatibility of standard aliases.

    To ensure backward compatibility, three sets of aliases are created:
    * ```Default``` - current alias set (from ```InitialSessionState```) in PowerShell Core. This is the minimum set of aliases that have no conflicts on UNIX systems.
    * ```Extended``` - the ```Default``` set of aliases and additional popular aliases for Windows users (which can have conflicts on Unix).
    * ```WindowsPowerShell``` - the full set of standard aliases from Windows PowerShell. This set provides full backward compatibility for Windows users.

    No alias set are loaded by default.

    Global configuration option ```GlobalAliasSet``` in ```powershell.config``` turns on loading the desired set. It is turned off by default.

1. PowerShell prevents the use of aliases in scripts and modules.

    Use of aliases is allowed only in interactive sessions.
    Global configuration option ```GlobalAliasEnable``` in ```powershell.config``` allows the use of aliases in scripts and modules. It is turned off by default.

1. Interactive session customization are delegated to users.

    It is recommended to use and develop ```IntellySense``` and other means of assistance to users including ML.
    Users can use aliases in interactive sessions but in the future it is better to use DSL.

# UX Improvements

To easily load aliases into interactive sessions, the ```Import-Alias``` cmdlet is extended by the ```GlobalAliasSet``` parameter:

* ```Import-Alias -GlobalAliasSet Default```
* ```Import-Alias -GlobalAliasSet Extended```
* ```Import-Alias -GlobalAliasSet WindowsPowerShell```

Values of the parameter is defined above.

Users can add this cmdlet to their profile to automatically import the necessary aliases.

# Transition

All elements of the current alias policy can be implemented independently and are in a state that does not change the current behavior.

Each element of the current alias policy is enabled by a decision of the PowerShell Committee.


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace Spookify
{
	[Register ("GenreTableViewCell")]
	partial class GenreTableViewCell
	{
		[Outlet]
		public UIKit.UIImageView GenereImage { get; private set; }

		[Outlet]
		public UIKit.UIImageView GenereImage2 { get; set; }

		[Outlet]
		public UIKit.UILabel GenereLabel { get; private set; }

		[Action ("onImage2Clicked:")]
		partial void onImage2Clicked (Foundation.NSObject sender);

		[Action ("onImageClicked:")]
		partial void onImageClicked (Foundation.NSObject sender);

		void ReleaseDesignerOutlets ()
		{
			if (GenereImage != null) {
				GenereImage.Dispose ();
				GenereImage = null;
			}
			if (GenereImage2 != null) {
				GenereImage2.Dispose ();
				GenereImage2 = null;
			}
			if (GenereLabel != null) {
				GenereLabel.Dispose ();
				GenereLabel = null;
			}
		}
	}
}


text:
var app = angular.module('myApp');

app.directive('filter', function(FilterService) {
	console.log("FilterService", FilterService);
    return {
        restrict: 'E',
        templateUrl: 'directives/filterDirective/filterDirectiveTemplate.html',
        scope: {
            paws: '@'
        },
        link : function(scope){
        	scope.options = FilterService.options;
        	scope.color = FilterService.options[0];
        	scope.update = function(){
        		console.log("updating. values: ", scope.color);
        	}
        }
    };
});


text:
package se.idioti.unicorns.server_java;

/**
 * A simple class representing a location.
 *
 * @author "Johan Holmberg, Malmö university"
 * @since 1.0
 */
public class Location {
	public String name;
	public double lat;
	public double lon;
}


text:
import 'zone.js'
import 'reflect-metadata'

import "bootstrap/css/bootstrap.css!"
import '@angular/material/core/theming/prebuilt/deeppurple-amber.css!';

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'
import {AppModule} from './app.module'

platformBrowserDynamic().bootstrapModule(AppModule);


text:
#ifndef _IAPPARSING_H_
#define _IAPPARSING_H_

#include "IapData.h"

namespace IapParsing {

/**
 * Converts the data from an IapData into a formated string ready to be
 * printed to the parameter file and also in a format that can be used
 * by NavServerCom module.
 *
 * Colon between host and port.
 * ----------------------------
 * Comma betwwen id and proxy |
 * -----------------          |
 *                 |          |
 * The format is id,proxy host:proxy port
 *
 * @param iapData The IapData object containing all the data to be parsed.
 * @return An allocated string containing the iap data in the format above.
 */
char* toString(isab::IapData* iapData);

/**
 * Creates and allocates an IapData object with the data from a string.
 * The string should be in the same format as when created by the toString
 * function above.
 * @param str The string containing the iap data to be parsed to an IapData
 *            object.
 * @return An allocated IapData object containing id, host and port.
 */
isab::IapData* fromString(const char* str);

} // End of namespace IapParsing

#endif /* _IAPPARSING_H_ */


text:
<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="bower_components/fontawesome/css/font-awesome.css" />

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


text:
namespace GLMatrixf {
	class GLMatrixf{
	public:
		float m[4][4] = {	1, 0, 0, 0,
							0, 1, 0, 0,
							0, 0, 1, 0,
							0, 0, 0, 1 };

		GLMatrixf();

		void translate(float dx, float dy, float dz);
		void rotate(float degrees, GLVector3f::GLVector3f axis);
		void scale(float sx, float sy, float sz);
		void transpose();
	};

	GLMatrixf multiply(const GLMatrixf& m1, const GLMatrixf& m2);
	GLVector3f::GLVector3f transformPoint(const GLMatrixf& m, const GLVector3f::GLVector3f& p);

	void print(const GLMatrixf& m);
}


text:
(function(T) {
    "use strict";

    function Decoder() {}

    Decoder.prototype.decode = function(src, onloadedmetadata, onloadeddata) {
        if (typeof src === "string") {
            if (/\.wav$/.test(src)) {
                return Decoder.wav_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.ogg_decode && /\.ogg$/.test(src)) {
                return Decoder.ogg_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.mp3_decode && /\.mp3$/.test(src)) {
                return Decoder.mp3_decode(src, onloadedmetadata, onloadeddata);
            }
        } else if (typeof src === "object") {
            if (src.type === "wav") {
                return Decoder.wav_decode(src.data, onloadedmetadata, onloadeddata);
            } else if (Decoder.ogg_decode && src.type === "ogg") {
                return Decoder.ogg_decode(src.data, onloadedmetadata, onloadeddata);
            } else if (Decoder.mp3_decode && src.type === "mp3") {
                return Decoder.mp3_decode(src.data, onloadedmetadata, onloadeddata);
            }
        }
        if (Decoder.webkit_decode) {
            if (typeof src === "object") {
                return Decoder.webkit_decode(src.data||src, onloadedmetadata, onloadeddata);
            } else {
                return Decoder.webkit_decode(src, onloadedmetadata, onloadeddata);
            }
        } else if (Decoder.moz_decode) {
            return Decoder.moz_decode(src, onloadedmetadata, onloadeddata);
        }
        onloadedmetadata(false);
    };
    T.modules.Decoder = Decoder;

    if (T.envtype === "browser") {
        Decoder.getBinaryWithPath = function(path, callback) {
            T.fn.fix_iOS6_1_problem(true);

            var xhr = new XMLHttpRequest();
            xhr.open("GET", path);
            xhr.responseType = "arraybuffer";
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.response) {
                        callback(new Uint8Array(xhr.response));
                    } else if (xhr.responseBody !== undefined) {
                        /*global VBArray:true */
                        callback(new Uint8Array(VBArray(xhr.responseBody).toArray()));
                        /*global VBArray:false */
                    }
                    T.fn.fix_iOS6_1_problem(false);
                }
            };
            xhr.send();
        };
    } else {
        Decoder.getBinaryWithPath = function(path, callback) {
            callback("no support");
        };
    }

    var _24bit_to_32bit = function(uint8) {
        var b0, b1, b2, bb, x;
        var int32 = new Int32Array(uint8.length / 3);
        for (var i = 0, imax = uint8.length, j = 0; i < imax; ) {
            b0 = uint8[i++];
            b1 = uint8[i++];
            b2 = uint8[i++];
            bb = b0 + (b1 << 8) + (b2 << 16);
            x = (bb & 0x800000) ? bb - 16777216 : bb;
            int32[j++] = x;
        }
        return int32;
    };

    Decoder.wav_decode = (function() {
        var _decode = function(data, onloadedmetadata, onloadeddata) {
            if (String.fromCharCode(data[0], data[1], data[2], data[3]) !== "RIFF") {
                return onloadedmetadata(false);
            }

            var l1 = data[4] + (data[5]<<8) + (data[6]<<16) + (data[7]<<24);
            if (l1 + 8 !== data.length) {
                return onloadedmetadata(false);
            }

            if (String.fromCharCode(data[8], data[9], data[10], data[11]) !== "WAVE") {
                return onloadedmetadata(false);
            }

            if (String.fromCharCode(data[12], data[13], data[14], data[15]) !== "fmt ") {
                return onloadedmetadata(false);
            }

            var channels   = data[22] + (data[23]<<8);
            var samplerate = data[24] + (data[25]<<8) + (data[26]<<16) + (data[27]<<24);
            var bitSize    = data[34] + (data[35]<<8);

            var i = 36;
            while (i < data.length) {
                if (String.fromCharCode(data[i], data[i+1], data[i+2], data[i+3]) === "data") {
                    break;
                }
                i += 1;
            }
            if (i >= data.length) {
                return onloadedmetadata(false);
            }
            i += 4;

            var l2 = data[i] + (data[i+1]<<8) + (data[i+2]<<16) + (data[i+3]<<24);
            var duration = ((l2 / channels) >> 1) / samplerate;
            i += 4;

            if (l2 > data.length - i) {
                return onloadedmetadata(false);
            }

            var mixdown, bufferL, bufferR;
            mixdown = new Float32Array((duration * samplerate)|0);
            if (channels === 2) {
                bufferL = new Float32Array(mixdown.length);
                bufferR = new Float32Array(mixdown.length);
            }

            onloadedmetadata({
                samplerate: samplerate,
                channels  : channels,
                buffer    : [mixdown, bufferL, bufferR],
                duration  : duration
            });

            if (bitSize === 8) {
                data = new Int8Array(data.buffer, i);
            } else if (bitSize === 16) {
                data = new Int16Array(data.buffer, i);
            } else if (bitSize === 32) {
                data = new Int32Array(data.buffer, i);
            } else if (bitSize === 24) {
                data = _24bit_to_32bit(new Uint8Array(data.buffer, i));
            }

            var imax, j, k = 1 / ((1 << (bitSize-1)) - 1), x;
            if (channels === 2) {
                for (i = j = 0, imax = mixdown.length; i < imax; ++i) {
                    x =  bufferL[i] = data[j++] * k;
                    x += bufferR[i] = data[j++] * k;
                    mixdown[i] = x * 0.5;
                }
            } else {
                for (i = 0, imax = mixdown.length; i < imax; ++i) {
                    mixdown[i] = data[i] * k;
                }
            }

            onloadeddata();
        };

        return function(src, onloadedmetadata, onloadeddata) {
            if (typeof src === "string") {
                Decoder.getBinaryWithPath(src, function(data) {
                    _decode(data, onloadedmetadata, onloadeddata);
                });
            } else {
                _decode(src, onloadedmetadata, onloadeddata);
            }
        };
    })();

    Decoder.webkit_decode = (function() {
        if (typeof T.fn._audioContext !== "undefined") {
            var ctx = T.fn._audioContext;
            var _decode = function(data, onloadedmetadata, onloadeddata) {
                var samplerate, channels, bufferL, bufferR, duration;

                if (typeof data === "string") {
                    return onloadeddata(false);
                }

                var buffer;
                try {
                    buffer = ctx.createBuffer(data.buffer, false);
                } catch (e) {
                    return onloadedmetadata(false);
                }

                samplerate = ctx.sampleRate;
                channels   = buffer.numberOfChannels;
                if (channels === 2) {
                    bufferL = buffer.getChannelData(0);
                    bufferR = buffer.getChannelData(1);
                } else {
                    bufferL = bufferR = buffer.getChannelData(0);
                }
                duration = bufferL.length / samplerate;

                var mixdown = new Float32Array(bufferL);
                for (var i = 0, imax = mixdown.length; i < imax; ++i) {
                    mixdown[i] = (mixdown[i] + bufferR[i]) * 0.5;
                }

                onloadedmetadata({
                    samplerate: samplerate,
                    channels  : channels,
                    buffer    : [mixdown, bufferL, bufferR],
                    duration  : duration
                });

                onloadeddata();
            };

            return function(src, onloadedmetadata, onloadeddata) {
                /*global File:true */
                if (src instanceof File) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        _decode(new Uint8Array(e.target.result),
                                onloadedmetadata, onloadeddata);
                    };
                    reader.readAsArrayBuffer(src);
                } else if (typeof src === "string") {
                    Decoder.getBinaryWithPath(src, function(data) {
                        _decode(data, onloadedmetadata, onloadeddata);
                    });
                } else {
                    _decode(src, onloadedmetadata, onloadeddata);
                }
                /*global File:false */
            };
        }
    })();

    Decoder.moz_decode = (function() {
        if (typeof Audio === "function" && typeof new Audio().mozSetup === "function") {
            return function(src, onloadedmetadata, onloadeddata) {
                var samplerate, channels, mixdown, bufferL, bufferR, duration;
                var writeIndex = 0;

                var audio = new Audio(src);
                audio.volume = 0.0;
                audio.addEventListener("loadedmetadata", function() {
                    samplerate = audio.mozSampleRate;
                    channels   = audio.mozChannels;
                    duration   = audio.duration;
                    mixdown = new Float32Array((audio.duration * samplerate)|0);
                    if (channels === 2) {
                        bufferL = new Float32Array((audio.duration * samplerate)|0);
                        bufferR = new Float32Array((audio.duration * samplerate)|0);
                    }
                    if (channels === 2) {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var x, samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; i += 2) {
                                x =  bufferL[writeIndex] = samples[i  ];
                                x += bufferR[writeIndex] = samples[i+1];
                                mixdown[writeIndex] = x * 0.5;
                                writeIndex += 1;
                            }
                        }, false);
                    } else {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; ++i) {
                                mixdown[i] = samples[i];
                                writeIndex += 1;
                            }
                        }, false);
                    }
                    audio.play();
                    setTimeout(function() {
                        onloadedmetadata({
                            samplerate: samplerate,
                            channels  : channels,
                            buffer    : [mixdown, bufferL, bufferR],
                            duration  : duration
                        });
                    }, 1000);
                }, false);
                audio.addEventListener("ended", function() {
                    onloadeddata();
                }, false);
                audio.load();
            };
        }
    })();
})(timbre);


text:
<?php
namespace Youkok\Rest\Endpoints\Admin\Files;

use Monolog\Logger;
use Psr\Container\ContainerInterface;
use Slim\Http\Request;
use Slim\Http\Response;

use Youkok\Biz\Exceptions\YoukokException;
use Youkok\Biz\Services\Admin\FileCreateDirectoryService;
use Youkok\Rest\Endpoints\BaseRestEndpoint;

class AdminFilesDirectoryEndpoint extends BaseRestEndpoint
{
    private FileCreateDirectoryService $fileCreateDirectoryService;
    private Logger $logger;

    public function __construct(ContainerInterface $container)
    {
        $this->fileCreateDirectoryService = $container->get(FileCreateDirectoryService::class);
        $this->logger = $container->get(Logger::class);
    }

    public function get(Request $request, Response $response): Response
    {
        try {
            $data = $this->getJsonArrayFromBody(
                $request,
                [
                    'course',
                    'directory',
                    'value'
                ]
            );

            return $this->outputJson($response, [
                'data' => $this->fileCreateDirectoryService->createDirectory(
                    (int) $data['course'],
                    (int) $data['directory'],
                    (string) $data['value'],
                )
            ]);
        } catch (YoukokException $ex) {
            $this->logger->error($ex);
            return $this->returnBadRequest($response, $ex);
        }
    }
}


text:
import {connect} from 'react-redux'

import {updateProject} from '../actions/projects'
import {
  createDeployment,
  saveDeployment,
  deleteDeployment,
  updateDeployment
} from '../actions/deployments'
import DeploymentsPanel from '../components/deployment/DeploymentsPanel'

import type {Project} from '../../types'
import type {AppState} from '../../types/reducers'

export type Props = {
  activeSubComponent: ?string,
  expanded: boolean,
  project: Project
}

const mapStateToProps = (state: AppState, ownProps: Props) => ({})

const mapDispatchToProps = {
  createDeployment,
  deleteDeployment,
  saveDeployment,
  updateDeployment,
  updateProject
}

export default connect(mapStateToProps, mapDispatchToProps)(DeploymentsPanel)


text:
var judgeCOU=(function(config,functions){
    return{
        initData:function(id){
            ZYCOUHandler.getDataDetail(config.ajaxUrls.judgeDetail.replace(":id",id),{id:id},function(data){
                $("#name").val(data.name);
                $("#email").val(data.email);
                $("#password").val(data.password);
                $("#imageUrl").val(data.headicon);
                $("#image").attr("src",data.headicon);
                $("#subTitle").val(data.subTitle);
                $("#description").val(data.description);
            });
        }
    }
})(config,functions);

$(document).ready(function(){

    var submitUrl=config.ajaxUrls.judgeCreate;

    if(id){
        judgeCOU.initData(id);
        submitUrl=config.ajaxUrls.judgeUpdate
    }
    var zyFormHandler=new ZYFormHandler({
        submitUrl:submitUrl,
        redirectUrl:config.viewUrls.judgeMgr
    });

    functions.createUploader({
        maxSize:config.uploader.sizes.img,
        filter:config.uploader.filters.img,
        uploadBtn:"uploadBtn",
        multiSelection:false,
        multipartParams:{
            fileType:config.uploader.fileType.others
        },
        uploadContainer:"uploadContainer",
        filesAddedCb:null,
        progressCb:null,
        uploadedCb:function(info,file,up){
            functions.getImageSize(config.ajaxUrls.imageGet+"?imgPath="+info.object,function(imageSizeMap){
                if(imageSizeMap.width==imageSizeMap.height){
                    $("#imageUrl").val(config.ajaxUrls.imageGet+"?imgPath="+info.object);

                    $("#image").attr("src",config.ajaxUrls.imageGet+"?imgPath="+info.object);

                    $(".error[for='imageUrl']").remove();
                }else{
                    $().toastmessage("showErrorToast",config.messages.imageSizeError);
                }
            });
        }
    });

    tinymce.init({
        selector: "#description",
        height:300,
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons',
        //image_advtab: true,
        plugins : 'link image preview fullscreen table textcolor colorpicker code',
        setup: function (ed) {
            ed.on('blur', function (e) {
                $("#description").val(ed.getContent());
                if(ed.getContent()){
                    $(".error[for='description']").remove();
                }
            });
        }
    });
    /*
    tinymce.init({
        selector: "#subTitle",
        height:300,
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons',
        //image_advtab: true,
        plugins : 'link image preview fullscreen table textcolor colorpicker code',
        setup: function (ed) {
            ed.on('blur', function (e) {
                $("#subTitle").val(ed.getContent());
                if(ed.getContent()){
                    $(".error[for='subTitle']").remove();
                }
            });
        }
    });
*/
    $("#myForm").validate({
        ignore:[],
        rules:{
            headicon:{
                required:true
            },
            subTitle:{
                required:true
            },
            description:{
                required:true
            },
            name:{
                required:true,
                maxlength:32
            },
            email:{
                required:true,
                email:true,
                maxlength:32
            },
            password:{
                required:true,
                rangelength:[6,20]
            }
        },
        messages:{
            headicon:{
                required:config.validErrors.required
            },
            subTitle:{
                required:config.validErrors.required
            },
            description:{
                required:config.validErrors.required
            },
            name:{
                required:config.validErrors.required,
                maxlength:config.validErrors.maxLength.replace("${max}",32)
            },
            email:{
                required:config.validErrors.required,
                maxlength:config.validErrors.maxLength.replace("${max}",32),
                email:config.validErrors.email
            },
            password:{
                required:config.validErrors.required,
                rangelength: config.validErrors.rangLength.replace("${min}", 6).replace("${max}", 20)
            }
        },
        submitHandler:function(form) {
            var data=null;
            if(id){
                data={
                    id:id
                }
            }
            zyFormHandler.submitFormWithJSON(form,data);
        }
    });
});


text:
package org.datasays.wes.actions;

import okhttp3.HttpUrl;
import org.datasays.wes.core.RequestInfo;
import org.datasays.wes.types.*;
// documentation: https://www.elastic.co/guide/en/elasticsearch/reference/5.x/cluster-pending.html
public class ClusterPendingTasks extends RequestInfo{

	public ClusterPendingTasks(String baseUrl){
		super(baseUrl);
	}
	public ClusterPendingTasks(HttpUrl baseUrl){
		super(baseUrl);
	}

	// param: boolean local: Return local information, do not retrieve the state from master node (default: false)
	public ClusterPendingTasks local(boolean local){
		addParams("local", local);
		return this;
	}
	// param: time masterTimeout: Specify timeout for connection to master
	public ClusterPendingTasks masterTimeout(long masterTimeout){
		addParams("masterTimeout", masterTimeout);
		return this;
	}
	// body:null
	@Override
	public void setBody(Object body) {
		super.setBody(body);
	}

	public ClusterPendingTasks setParts(){

		return this;
	}

	@Override
	public String parseUrl(String method) {
		if(!"GET".equalsIgnoreCase(method)){
			throw new IllegalArgumentException("Unsupported method:"+method);
		}
		//=>/_cluster/pending_tasks
		setUrl("_cluster", "pending_tasks");
		return super.parseUrl(method);

	}
}


text:
package fr.openwide.core.jpa.more.business.history.model.embeddable;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.SortableField;

import fr.openwide.core.commons.util.CloneUtils;

/**
 * An {@link Embeddable embeddable} for storing limited information about an event:
 *

 *
The subject, i.e. the actor of the event
 *
The date/time of the event
 *

 *
 *
This class generally used for storing information about the creation or last modification of an entity. It is
 * embedded into the entity itself, so the object of the event is implicit and doesn't have to be stored inside the
 * {@link HistoryEventSummary}.
 */
@Embeddable
public class HistoryEventSummary implements Serializable {

	private static final long serialVersionUID = 2512003373453632965L;

	public static final String DATE = "date";
	private static final String SUBJECT = "subject";
	private static final String SUBJECT_PREFIX = SUBJECT + ".";
	public static final String SUBJECT_REFERENCE = SUBJECT_PREFIX + HistoryValue.REFERENCE;

	@Basic(optional = true) // Might be defined as nullable in some places (using @AttributeOverride)
	@Column(nullable = false) // Non-nullable by default
	@Temporal(TemporalType.TIMESTAMP)
	@Field(name = DATE)
	@SortableField(forField = DATE)
	private Date date;

	@Embedded
	@IndexedEmbedded(
			prefix = SUBJECT_PREFIX,
			includePaths = {
					HistoryValue.REFERENCE
			}
	)
	private HistoryValue subject;

	public Date getDate() {
		return CloneUtils.clone(date);
	}

	public void setDate(Date date) {
		this.date = CloneUtils.clone(date);
	}

	public HistoryValue getSubject() {
		return subject;
	}

	public void setSubject(HistoryValue subject) {
		this.subject = subject;
	}

}


text:
namespace nd4j {
    namespace ops {
        OP_IMPL(scatter_div, 3, 1, true) {
            auto input = INPUT_VARIABLE(0);
            auto indices = INPUT_VARIABLE(1);
            auto updates = INPUT_VARIABLE(2);

            auto output = OUTPUT_VARIABLE(0);

            if (!block.isInplace())
                output->assign(input);

            ScatterHelper<T>::template scatter_apply<simdOps::Divide<T>>(output, indices, updates);

            return ND4J_STATUS_OK;
        }
        DECLARE_SYN(ScatterDiv, scatter_div);
    }
}

#endif


text:
#ifndef COMMON_AUDIO_BLOCKER_H_
#define COMMON_AUDIO_BLOCKER_H_

#include <memory>

#include "common_audio/audio_ring_buffer.h"
#include "common_audio/channel_buffer.h"

namespace webrtc {

// The callback function to process audio in the time domain. Input has already
// been windowed, and output will be windowed. The number of input channels
// must be >= the number of output channels.
class BlockerCallback {
 public:
  virtual ~BlockerCallback() {}

  virtual void ProcessBlock(const float* const* input,
                            size_t num_frames,
                            size_t num_input_channels,
                            size_t num_output_channels,
                            float* const* output) = 0;
};

// The main purpose of Blocker is to abstract away the fact that often we
// receive a different number of audio frames than our transform takes. For
// example, most FFTs work best when the fft-size is a power of 2, but suppose
// we receive 20ms of audio at a sample rate of 48000. That comes to 960 frames
// of audio, which is not a power of 2. Blocker allows us to specify the
// transform and all other necessary processing via the Process() callback
// function without any constraints on the transform-size
// (read: |block_size_|) or received-audio-size (read: |chunk_size_|).
// We handle this for the multichannel audio case, allowing for different
// numbers of input and output channels (for example, beamforming takes 2 or
// more input channels and returns 1 output channel). Audio signals are
// represented as deinterleaved floats in the range [-1, 1].
//
// Blocker is responsible for:
// - blocking audio while handling potential discontinuities on the edges
//   of chunks
// - windowing blocks before sending them to Process()
// - windowing processed blocks, and overlap-adding them together before
//   sending back a processed chunk
//
// To use blocker:
// 1. Impelment a BlockerCallback object |bc|.
// 2. Instantiate a Blocker object |b|, passing in |bc|.
// 3. As you receive audio, call b.ProcessChunk() to get processed audio.
//
// A small amount of delay is added to the first received chunk to deal with
// the difference in chunk/block sizes. This delay is <= chunk_size.
//
// Ownership of window is retained by the caller.  That is, Blocker makes a
// copy of window and does not attempt to delete it.
class Blocker {
 public:
  Blocker(size_t chunk_size,
          size_t block_size,
          size_t num_input_channels,
          size_t num_output_channels,
          const float* window,
          size_t shift_amount,
          BlockerCallback* callback);
  ~Blocker();

  void ProcessChunk(const float* const* input,
                    size_t chunk_size,
                    size_t num_input_channels,
                    size_t num_output_channels,
                    float* const* output);

  size_t initial_delay() const { return initial_delay_; }

 private:
  const size_t chunk_size_;
  const size_t block_size_;
  const size_t num_input_channels_;
  const size_t num_output_channels_;

  // The number of frames of delay to add at the beginning of the first chunk.
  const size_t initial_delay_;

  // The frame index into the input buffer where the first block should be read
  // from. This is necessary because shift_amount_ is not necessarily a
  // multiple of chunk_size_, so blocks won't line up at the start of the
  // buffer.
  size_t frame_offset_;

  // Since blocks nearly always overlap, there are certain blocks that require
  // frames from the end of one chunk and the beginning of the next chunk. The
  // input and output buffers are responsible for saving those frames between
  // calls to ProcessChunk().
  //
  // Both contain |initial delay| + |chunk_size| frames. The input is a fairly
  // standard FIFO, but due to the overlap-add it's harder to use an
  // AudioRingBuffer for the output.
  AudioRingBuffer input_buffer_;
  ChannelBuffer<float> output_buffer_;

  // Space for the input block (can't wrap because of windowing).
  ChannelBuffer<float> input_block_;

  // Space for the output block (can't wrap because of overlap/add).
  ChannelBuffer<float> output_block_;

  std::unique_ptr<float[]> window_;

  // The amount of frames between the start of contiguous blocks. For example,
  // |shift_amount_| = |block_size_| / 2 for a Hann window.
  size_t shift_amount_;

  BlockerCallback* callback_;
};

}  // namespace webrtc

#endif  // COMMON_AUDIO_BLOCKER_H_


text:
using System.Net.Http;
using FluentSpotifyApi.Core.Exceptions;
using FluentSpotifyApi.Core.Model;

namespace FluentSpotifyApi.Core.HttpHandlers
{
    /// <summary>
    /// The <see cref="DelegatingHandler"/> that shields exceptions thrown by <see cref="HttpClient"/>
    /// and transforms error responses with regular error content into <see cref="SpotifyRegularErrorException"/>.
    /// </summary>
    /// <typeparam name="TClient"></typeparam>
    /// <seealso cref="SpotifyErrorHandler{TClient,RegularErrorResponse,RegularError}" />
    public class SpotifyRegularErrorHandler<TClient> : SpotifyErrorHandler<TClient, RegularErrorResponse, RegularError>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SpotifyRegularErrorHandler{TClient}" /> class.
        /// </summary>
        public SpotifyRegularErrorHandler()
            : base(r => r.Error, (t, s, c, e) => new SpotifyRegularErrorException(t, s, c, e))
        {
        }
    }
}


text:
using base::ASCIIToUTF16;

namespace views {

namespace {

// An dummy implementation of MenuRunnerHandler to check if the dropdown menu is
// shown or not.
class TestMenuRunnerHandler : public MenuRunnerHandler {
 public:
  TestMenuRunnerHandler() : executed_(false) {}

  bool executed() const { return executed_; }

  virtual MenuRunner::RunResult RunMenuAt(Widget* parent,
                                          MenuButton* button,
                                          const gfx::Rect& bounds,
                                          MenuAnchorPosition anchor,
                                          ui::MenuSourceType source_type,
                                          int32 types) OVERRIDE {
    executed_ = true;
    return MenuRunner::NORMAL_EXIT;
  }

 private:
  bool executed_;

  DISALLOW_COPY_AND_ASSIGN(TestMenuRunnerHandler);
};

// A wrapper of Combobox to intercept the result of OnKeyPressed() and
// OnKeyReleased() methods.
class TestCombobox : public Combobox {
 public:
  explicit TestCombobox(ui::ComboboxModel* model)
      : Combobox(model),
        key_handled_(false),
        key_received_(false) {}

  virtual bool OnKeyPressed(const ui::KeyEvent& e) OVERRIDE {
    key_received_ = true;
    key_handled_ = Combobox::OnKeyPressed(e);
    return key_handled_;
  }

  virtual bool OnKeyReleased(const ui::KeyEvent& e) OVERRIDE {
    key_received_ = true;
    key_handled_ = Combobox::OnKeyReleased(e);
    return key_handled_;
  }

  bool key_handled() const { return key_handled_; }
  bool key_received() const { return key_received_; }

  void clear() {
    key_received_ = key_handled_ = false;
  }

 private:
  bool key_handled_;
  bool key_received_;

  DISALLOW_COPY_AND_ASSIGN(TestCombobox);
};

// A concrete class is needed to test the combobox.
class TestComboboxModel : public ui::ComboboxModel {
 public:
  TestComboboxModel() {}
  virtual ~TestComboboxModel() {}

  // ui::ComboboxModel:
  virtual int GetItemCount() const OVERRIDE {
    return 10;
  }
  virtual base::string16 GetItemAt(int index) OVERRIDE {
    if (IsItemSeparatorAt(index)) {
      NOTREACHED();
      return ASCIIToUTF16("SEPARATOR");
    }
    return ASCIIToUTF16(index % 2 == 0 ? "PEANUT BUTTER" : "JELLY");
  }
  virtual bool IsItemSeparatorAt(int index) OVERRIDE {
    return separators_.find(index) != separators_.end();
  }

  void SetSeparators(const std::set<int>& separators) {
    separators_ = separators;
  }

 private:
  std::set<int> separators_;

  DISALLOW_COPY_AND_ASSIGN(TestComboboxModel);
};

// A combobox model which refers to a vector.
class VectorComboboxModel : public ui::ComboboxModel {
 public:
  explicit VectorComboboxModel(std::vector<std::string>* values)
      : values_(values) {}
  virtual ~VectorComboboxModel() {}

  // ui::ComboboxModel:
  virtual int GetItemCount() const OVERRIDE {
    return (int)values_->size();
  }
  virtual base::string16 GetItemAt(int index) OVERRIDE {
    return ASCIIToUTF16(values_->at(index));
  }
  virtual bool IsItemSeparatorAt(int index) OVERRIDE {
    return false;
  }

 private:
  std::vector<std::string>* values_;
};

class EvilListener : public ComboboxListener {
 public:
  EvilListener() : deleted_(false) {}
  virtual ~EvilListener() {};

  // ComboboxListener:
  virtual void OnPerformAction(Combobox* combobox) OVERRIDE {
    delete combobox;
    deleted_ = true;
  }

  bool deleted() const { return deleted_; }

 private:
  bool deleted_;

  DISALLOW_COPY_AND_ASSIGN(EvilListener);
};

class TestComboboxListener : public views::ComboboxListener {
 public:
  TestComboboxListener() : perform_action_index_(-1), actions_performed_(0) {}
  virtual ~TestComboboxListener() {}

  virtual void OnPerformAction(views::Combobox* combobox) OVERRIDE {
    perform_action_index_ = combobox->selected_index();
    actions_performed_++;
  }

  int perform_action_index() const {
    return perform_action_index_;
  }

  bool on_perform_action_called() const {
    return actions_performed_ > 0;
  }

  int actions_performed() const {
    return actions_performed_;
  }

 private:
  int perform_action_index_;
  int actions_performed_;

 private:
  DISALLOW_COPY_AND_ASSIGN(TestComboboxListener);
};

}  // namespace

class ComboboxTest : public ViewsTestBase {
 public:
  ComboboxTest() : widget_(NULL), combobox_(NULL) {}

  virtual void TearDown() OVERRIDE {
    if (widget_)
      widget_->Close();
    ViewsTestBase::TearDown();
  }

  void InitCombobox() {
    model_.reset(new TestComboboxModel());

    ASSERT_FALSE(combobox_);
    combobox_ = new TestCombobox(model_.get());
    combobox_->set_id(1);

    widget_ = new Widget;
    Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
    params.bounds = gfx::Rect(200, 200, 200, 200);
    widget_->Init(params);
    View* container = new View();
    widget_->SetContentsView(container);
    container->AddChildView(combobox_);

    widget_->ReplaceInputMethod(new MockInputMethod);

    // Assumes the Widget is always focused.
    widget_->GetInputMethod()->OnFocus();

    combobox_->RequestFocus();
    combobox_->SizeToPreferredSize();
  }

 protected:
  void SendKeyEvent(ui::KeyboardCode key_code) {
    SendKeyEventWithType(key_code, ui::ET_KEY_PRESSED);
  }

  void SendKeyEventWithType(ui::KeyboardCode key_code, ui::EventType type) {
    ui::KeyEvent event(type, key_code, 0, false);
    widget_->GetInputMethod()->DispatchKeyEvent(event);
  }

  View* GetFocusedView() {
    return widget_->GetFocusManager()->GetFocusedView();
  }

  void PerformClick(const gfx::Point& point) {
    ui::MouseEvent pressed_event = ui::MouseEvent(ui::ET_MOUSE_PRESSED, point,
                                                  point,
                                                  ui::EF_LEFT_MOUSE_BUTTON,
                                                  ui::EF_LEFT_MOUSE_BUTTON);
    widget_->OnMouseEvent(&pressed_event);
    ui::MouseEvent released_event = ui::MouseEvent(ui::ET_MOUSE_RELEASED, point,
                                                   point,
                                                   ui::EF_LEFT_MOUSE_BUTTON,
                                                   ui::EF_LEFT_MOUSE_BUTTON);
    widget_->OnMouseEvent(&released_event);
  }

  // We need widget to populate wrapper class.
  Widget* widget_;

  // |combobox_| will be allocated InitCombobox() and then owned by |widget_|.
  TestCombobox* combobox_;

  // Combobox does not take ownership of the model, hence it needs to be scoped.
  scoped_ptr<TestComboboxModel> model_;
};

TEST_F(ComboboxTest, KeyTest) {
  InitCombobox();
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(combobox_->selected_index() + 1, model_->GetItemCount());
  SendKeyEvent(ui::VKEY_HOME);
  EXPECT_EQ(combobox_->selected_index(), 0);
  SendKeyEvent(ui::VKEY_DOWN);
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(combobox_->selected_index(), 2);
  SendKeyEvent(ui::VKEY_RIGHT);
  EXPECT_EQ(combobox_->selected_index(), 2);
  SendKeyEvent(ui::VKEY_LEFT);
  EXPECT_EQ(combobox_->selected_index(), 2);
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(combobox_->selected_index(), 1);
  SendKeyEvent(ui::VKEY_PRIOR);
  EXPECT_EQ(combobox_->selected_index(), 0);
  SendKeyEvent(ui::VKEY_NEXT);
  EXPECT_EQ(combobox_->selected_index(), model_->GetItemCount() - 1);
}

// Check that if a combobox is disabled before it has a native wrapper, then the
// native wrapper inherits the disabled state when it gets created.
TEST_F(ComboboxTest, DisabilityTest) {
  model_.reset(new TestComboboxModel());

  ASSERT_FALSE(combobox_);
  combobox_ = new TestCombobox(model_.get());
  combobox_->SetEnabled(false);

  widget_ = new Widget;
  Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
  params.bounds = gfx::Rect(100, 100, 100, 100);
  widget_->Init(params);
  View* container = new View();
  widget_->SetContentsView(container);
  container->AddChildView(combobox_);
  EXPECT_FALSE(combobox_->enabled());
}

// Verifies that we don't select a separator line in combobox when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipSeparatorSimple) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(2);
  model_->SetSeparators(separators);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(3, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_HOME);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_PRIOR);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(9, combobox_->selected_index());
}

// Verifies that we never select the separator that is in the beginning of the
// combobox list when navigating through keyboard.
TEST_F(ComboboxTest, SkipSeparatorBeginning) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(0);
  model_->SetSeparators(separators);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(2, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_HOME);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_PRIOR);
  EXPECT_EQ(1, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(9, combobox_->selected_index());
}

// Verifies that we never select the separator that is in the end of the
// combobox list when navigating through keyboard.
TEST_F(ComboboxTest, SkipSeparatorEnd) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(model_->GetItemCount() - 1);
  model_->SetSeparators(separators);
  combobox_->SetSelectedIndex(8);
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(8, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(7, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(8, combobox_->selected_index());
}

// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the beginning of the combobox list when
// navigating through keyboard.
TEST_F(ComboboxTest, SkipMultipleSeparatorsAtBeginning) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(0);
  separators.insert(1);
  separators.insert(2);
  model_->SetSeparators(separators);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(3, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(3, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_NEXT);
  EXPECT_EQ(9, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_HOME);
  EXPECT_EQ(3, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(9, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_PRIOR);
  EXPECT_EQ(3, combobox_->selected_index());
}

// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the middle of the combobox list when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipMultipleAdjacentSeparatorsAtMiddle) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(4);
  separators.insert(5);
  separators.insert(6);
  model_->SetSeparators(separators);
  combobox_->SetSelectedIndex(3);
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(7, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(3, combobox_->selected_index());
}

// Verifies that we never select any of the adjacent separators (multiple
// consecutive) that appear in the end of the combobox list when navigating
// through keyboard.
TEST_F(ComboboxTest, SkipMultipleSeparatorsAtEnd) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(7);
  separators.insert(8);
  separators.insert(9);
  model_->SetSeparators(separators);
  combobox_->SetSelectedIndex(6);
  SendKeyEvent(ui::VKEY_DOWN);
  EXPECT_EQ(6, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_UP);
  EXPECT_EQ(5, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_HOME);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_NEXT);
  EXPECT_EQ(6, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_PRIOR);
  EXPECT_EQ(0, combobox_->selected_index());
  SendKeyEvent(ui::VKEY_END);
  EXPECT_EQ(6, combobox_->selected_index());
}

TEST_F(ComboboxTest, GetTextForRowTest) {
  InitCombobox();
  std::set<int> separators;
  separators.insert(0);
  separators.insert(1);
  separators.insert(9);
  model_->SetSeparators(separators);
  for (int i = 0; i < combobox_->GetRowCount(); ++i) {
    if (separators.count(i) != 0) {
      EXPECT_TRUE(combobox_->GetTextForRow(i).empty()) << i;
    } else {
      EXPECT_EQ(ASCIIToUTF16(i % 2 == 0 ? "PEANUT BUTTER" : "JELLY"),
                combobox_->GetTextForRow(i)) << i;
    }
  }
}

// Verifies selecting the first matching value (and returning whether found).
TEST_F(ComboboxTest, SelectValue) {
  InitCombobox();
  ASSERT_EQ(model_->GetDefaultIndex(), combobox_->selected_index());
  EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER")));
  EXPECT_EQ(0, combobox_->selected_index());
  EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("JELLY")));
  EXPECT_EQ(1, combobox_->selected_index());
  EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS")));
  EXPECT_EQ(1, combobox_->selected_index());

  // With the action style, the selected index is always 0.
  combobox_->SetStyle(Combobox::STYLE_ACTION);
  EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER")));
  EXPECT_EQ(0, combobox_->selected_index());
  EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("JELLY")));
  EXPECT_EQ(0, combobox_->selected_index());
  EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS")));
  EXPECT_EQ(0, combobox_->selected_index());
}

TEST_F(ComboboxTest, SelectIndexActionStyle) {
  InitCombobox();

  // With the action style, the selected index is always 0.
  combobox_->SetStyle(Combobox::STYLE_ACTION);
  combobox_->SetSelectedIndex(1);
  EXPECT_EQ(0, combobox_->selected_index());
  combobox_->SetSelectedIndex(2);
  EXPECT_EQ(0, combobox_->selected_index());
  combobox_->SetSelectedIndex(3);
  EXPECT_EQ(0, combobox_->selected_index());
}

TEST_F(ComboboxTest, ListenerHandlesDelete) {
  TestComboboxModel model;

  // |combobox| will be deleted on change.
  TestCombobox* combobox = new TestCombobox(&model);
  scoped_ptr<EvilListener> evil_listener(new EvilListener());
  combobox->set_listener(evil_listener.get());
  ASSERT_NO_FATAL_FAILURE(combobox->ExecuteCommand(2));
  EXPECT_TRUE(evil_listener->deleted());

  // With STYLE_ACTION
  // |combobox| will be deleted on change.
  combobox = new TestCombobox(&model);
  evil_listener.reset(new EvilListener());
  combobox->set_listener(evil_listener.get());
  combobox->SetStyle(Combobox::STYLE_ACTION);
  ASSERT_NO_FATAL_FAILURE(combobox->ExecuteCommand(2));
  EXPECT_TRUE(evil_listener->deleted());
}

TEST_F(ComboboxTest, Click) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  combobox_->Layout();

  // Click the left side. The menu is shown.
  TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler();
  scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler);
  test::MenuRunnerTestAPI test_api(
      combobox_->dropdown_list_menu_runner_.get());
  test_api.SetMenuRunnerHandler(menu_runner_handler.Pass());
  PerformClick(gfx::Point(combobox_->x() + 1,
                          combobox_->y() + combobox_->height() / 2));
  EXPECT_FALSE(listener.on_perform_action_called());
  EXPECT_TRUE(test_menu_runner_handler->executed());
}

TEST_F(ComboboxTest, ClickButDisabled) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  combobox_->Layout();
  combobox_->SetEnabled(false);

  // Click the left side, but nothing happens since the combobox is disabled.
  TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler();
  scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler);
  test::MenuRunnerTestAPI test_api(
      combobox_->dropdown_list_menu_runner_.get());
  test_api.SetMenuRunnerHandler(menu_runner_handler.Pass());
  PerformClick(gfx::Point(combobox_->x() + 1,
                          combobox_->y() + combobox_->height() / 2));
  EXPECT_FALSE(listener.on_perform_action_called());
  EXPECT_FALSE(test_menu_runner_handler->executed());
}

TEST_F(ComboboxTest, NotifyOnClickWithReturnKey) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  // With STYLE_NORMAL, the click event is ignored.
  SendKeyEvent(ui::VKEY_RETURN);
  EXPECT_FALSE(listener.on_perform_action_called());

  // With STYLE_ACTION, the click event is notified.
  combobox_->SetStyle(Combobox::STYLE_ACTION);
  SendKeyEvent(ui::VKEY_RETURN);
  EXPECT_TRUE(listener.on_perform_action_called());
  EXPECT_EQ(0, listener.perform_action_index());
}

TEST_F(ComboboxTest, NotifyOnClickWithSpaceKey) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  // With STYLE_NORMAL, the click event is ignored.
  SendKeyEvent(ui::VKEY_SPACE);
  EXPECT_FALSE(listener.on_perform_action_called());
  SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED);
  EXPECT_FALSE(listener.on_perform_action_called());

  // With STYLE_ACTION, the click event is notified after releasing.
  combobox_->SetStyle(Combobox::STYLE_ACTION);
  SendKeyEvent(ui::VKEY_SPACE);
  EXPECT_FALSE(listener.on_perform_action_called());
  SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED);
  EXPECT_TRUE(listener.on_perform_action_called());
  EXPECT_EQ(0, listener.perform_action_index());
}

TEST_F(ComboboxTest, NotifyOnClickWithMouse) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  combobox_->SetStyle(Combobox::STYLE_ACTION);
  combobox_->Layout();

  // Click the right side (arrow button). The menu is shown.
  TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler();
  scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler);
  scoped_ptr<test::MenuRunnerTestAPI> test_api(
      new test::MenuRunnerTestAPI(combobox_->dropdown_list_menu_runner_.get()));
  test_api->SetMenuRunnerHandler(menu_runner_handler.Pass());

  PerformClick(gfx::Point(combobox_->x() + combobox_->width() - 1,
                          combobox_->y() + combobox_->height() / 2));
  EXPECT_FALSE(listener.on_perform_action_called());
  EXPECT_TRUE(test_menu_runner_handler->executed());

  // Click the left side (text button). The click event is notified.
  test_menu_runner_handler = new TestMenuRunnerHandler();
  menu_runner_handler.reset(test_menu_runner_handler);
  test_api.reset(
      new test::MenuRunnerTestAPI(combobox_->dropdown_list_menu_runner_.get()));
  test_api->SetMenuRunnerHandler(menu_runner_handler.Pass());
  PerformClick(gfx::Point(combobox_->x() + 1,
                          combobox_->y() + combobox_->height() / 2));
  EXPECT_TRUE(listener.on_perform_action_called());
  EXPECT_FALSE(test_menu_runner_handler->executed());
  EXPECT_EQ(0, listener.perform_action_index());
}

TEST_F(ComboboxTest, ConsumingPressKeyEvents) {
  InitCombobox();

  EXPECT_FALSE(combobox_->OnKeyPressed(
      ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0, false)));
  EXPECT_FALSE(combobox_->OnKeyPressed(
      ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, 0, false)));

  // When the combobox's style is STYLE_ACTION, pressing events of a space key
  // or an enter key will be consumed.
  combobox_->SetStyle(Combobox::STYLE_ACTION);
  EXPECT_TRUE(combobox_->OnKeyPressed(
      ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, 0, false)));
  EXPECT_TRUE(combobox_->OnKeyPressed(
      ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, 0, false)));
}

TEST_F(ComboboxTest, ContentWidth) {
  std::vector<std::string> values;
  VectorComboboxModel model(&values);
  TestCombobox combobox(&model);

  std::string long_item = "this is the long item";
  std::string short_item = "s";

  values.resize(1);
  values[0] = long_item;
  combobox.ModelChanged();

  const int long_item_width = combobox.content_size_.width();

  values[0] = short_item;
  combobox.ModelChanged();

  const int short_item_width = combobox.content_size_.width();

  values.resize(2);
  values[0] = short_item;
  values[1] = long_item;
  combobox.ModelChanged();

  // When the style is STYLE_NORMAL, the width will fit with the longest item.
  combobox.SetStyle(Combobox::STYLE_NORMAL);
  EXPECT_EQ(long_item_width, combobox.content_size_.width());

  // When the style is STYLE_ACTION, the width will fit with the first items'
  // width.
  combobox.SetStyle(Combobox::STYLE_ACTION);
  EXPECT_EQ(short_item_width, combobox.content_size_.width());
}

TEST_F(ComboboxTest, TypingPrefixNotifiesListener) {
  InitCombobox();

  TestComboboxListener listener;
  combobox_->set_listener(&listener);

  // Type the first character of the second menu item ("JELLY").
  combobox_->GetTextInputClient()->InsertChar('J', ui::EF_NONE);
  EXPECT_EQ(1, listener.actions_performed());
  EXPECT_EQ(1, listener.perform_action_index());

  // Type the second character of "JELLY", item shouldn't change and
  // OnPerformAction() shouldn't be re-called.
  combobox_->GetTextInputClient()->InsertChar('E', ui::EF_NONE);
  EXPECT_EQ(1, listener.actions_performed());
  EXPECT_EQ(1, listener.perform_action_index());

  // Clears the typed text.
  combobox_->OnBlur();

  // Type the first character of "PEANUT BUTTER", which should change the
  // selected index and perform an action.
  combobox_->GetTextInputClient()->InsertChar('P', ui::EF_NONE);
  EXPECT_EQ(2, listener.actions_performed());
  EXPECT_EQ(2, listener.perform_action_index());
}

}  // namespace views


text:
import json, uuid, re, time, traceback, tornado, tornado.websocket
from pprint import pprint
from construct_auth import construct_socket_auth
from construct_cmd_parser import ConstructCmdParser

CONSTRUCT_PROTOCOL_VERSION = [0,3,0]

class ConstructSocketHandler(tornado.websocket.WebSocketHandler):
  clients = []

  def on_sensor_changed(self):
    for name in ['bed', 'extruder']:
      self.send(
        sensor_changed= {'name': name, 'value': prontserve.sensors[name]},
      )

  def on_uncaught_event(self, event_name, data):
    listener = "on_%s"%event_name

    if event_name[:4] == 'job_' and event_name != "job_progress_changed":
      data = prontserve.jobs.sanitize(data)
    self.send({event_name: data})

  def _execute(self, transforms, *args, **kwargs):
    self.authorized = construct_socket_auth(self)
    super(ConstructSocketHandler, self)._execute(transforms, *args, **kwargs)

  def select_subprotocol(self, subprotocols):
    # Chooses a compatible construct protocol from the list sent by the
    # client.
    # The Construct Protocol uses semantic version v2.0.0 so any minor version
    # w/ a specific major version will be compatible with all minor versions
    # before it within that same major version.
    # The only exception to this rule is major version 0.
    # Version 0 protocols are unstable and can break compatibility more often.
    # We are only going to cause backwards incompatibility in 0.x minor version
    # See http://semver.org/
    server_v = CONSTRUCT_PROTOCOL_VERSION
    compatible_v = [-1, -1]
    for p in list(subprotocols):
      regex = '^construct\.text\.([0-9]+)\.?([0-9]+)'
      client_v = [int(s) for s in list(re.search(regex, p).groups())]
      pprint(client_v)
      if client_v[0] == server_v[0] and client_v[1] <= server_v[1]:
        if client_v[1] > compatible_v[1]: compatible_v = client_v

    print subprotocols
    print compatible_v

    # On incompatibility: Return a BS version and sending an error once the
    # connection opens.
    self.client_versions = subprotocols
    self.compatible = compatible_v[1] > -1
    pprint(self.compatible)
    print self._protocol_str(compatible_v)
    if not self.compatible: return subprotocols[0]
    return self._protocol_str(compatible_v)

  def _protocol_str(self, v):
    return "construct.text.%i.%i"%(v[0], v[1])

  def open(self):
    if not self.authorized:
      self._error(
        message= "Incorrect password or username",
        type= 'auth.sync'
      )
    if not self.compatible:
      v = self._protocol_str(CONSTRUCT_PROTOCOL_VERSION)
      msg = """
      Incompatible Construct Protocol version.

      Server version: %s
      Your version(s): %s
      """%(v, str(self.client_versions))
      self._error(message= msg, type= 'version.sync')

    if not (self.authorized and self.compatible): return self.stream.close()

    self.session_uuid = str(uuid.uuid4())
    self.application.add_client(self)
    self.send( self.application.build_initialized_event(self) )

    open_clients = len(self.application.clients)
    print "WebSocket opened. %i sockets currently open." % open_clients

  def on_message(self, msg):
    if not self.authorized: return
    # Parsing the command
    try:
      cmd = ConstructCmdParser(msg)
    except Exception as ex:
      print traceback.format_exc()
      return self._error(message= str(ex), type= 'syntax.sync')
    # Running the command
    try:
      self.send([{"type": "ack", "data": self.application.run_cmd(cmd)}])
    except Exception as ex:
      print traceback.format_exc()
      self._error(message= str(ex), type= 'runtime.sync')

  def _error(self, **kwargs):
    self.send([{"type": "error", "data": kwargs}])

  def send(self, message):
    print "sending:"
    print message
    self.write_message(json.dumps(message))

  def on_close(self):
    if self.session_uuid in self.application.clients:
      self.application.remove_client(self)
    open_clients = len(self.application.clients)
    print "WebSocket closed. %i sockets currently open." % open_clients


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 *
 * Generated from protobuf message google.cloud.compute.v1.SecurityPolicyAdvancedOptionsConfig
 */
class SecurityPolicyAdvancedOptionsConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * Custom configuration to apply the JSON parsing. Only applicable when json_parsing is set to STANDARD.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.SecurityPolicyAdvancedOptionsConfigJsonCustomConfig json_custom_config = 111570105;
     */
    private $json_custom_config = null;
    /**
     *
     * Check the JsonParsing enum for the list of possible values.
     *
     * Generated from protobuf field optional string json_parsing = 282493529;
     */
    private $json_parsing = null;
    /**
     *
     * Check the LogLevel enum for the list of possible values.
     *
     * Generated from protobuf field optional string log_level = 140582601;
     */
    private $log_level = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Compute\V1\SecurityPolicyAdvancedOptionsConfigJsonCustomConfig $json_custom_config
     *           Custom configuration to apply the JSON parsing. Only applicable when json_parsing is set to STANDARD.
     *     @type string $json_parsing
     *
     *           Check the JsonParsing enum for the list of possible values.
     *     @type string $log_level
     *
     *           Check the LogLevel enum for the list of possible values.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Custom configuration to apply the JSON parsing. Only applicable when json_parsing is set to STANDARD.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.SecurityPolicyAdvancedOptionsConfigJsonCustomConfig json_custom_config = 111570105;
     * @return \Google\Cloud\Compute\V1\SecurityPolicyAdvancedOptionsConfigJsonCustomConfig|null
     */
    public function getJsonCustomConfig()
    {
        return $this->json_custom_config;
    }

    public function hasJsonCustomConfig()
    {
        return isset($this->json_custom_config);
    }

    public function clearJsonCustomConfig()
    {
        unset($this->json_custom_config);
    }

    /**
     * Custom configuration to apply the JSON parsing. Only applicable when json_parsing is set to STANDARD.
     *
     * Generated from protobuf field optional .google.cloud.compute.v1.SecurityPolicyAdvancedOptionsConfigJsonCustomConfig json_custom_config = 111570105;
     * @param \Google\Cloud\Compute\V1\SecurityPolicyAdvancedOptionsConfigJsonCustomConfig $var
     * @return $this
     */
    public function setJsonCustomConfig($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Compute\V1\SecurityPolicyAdvancedOptionsConfigJsonCustomConfig::class);
        $this->json_custom_config = $var;

        return $this;
    }

    /**
     *
     * Check the JsonParsing enum for the list of possible values.
     *
     * Generated from protobuf field optional string json_parsing = 282493529;
     * @return string
     */
    public function getJsonParsing()
    {
        return isset($this->json_parsing) ? $this->json_parsing : '';
    }

    public function hasJsonParsing()
    {
        return isset($this->json_parsing);
    }

    public function clearJsonParsing()
    {
        unset($this->json_parsing);
    }

    /**
     *
     * Check the JsonParsing enum for the list of possible values.
     *
     * Generated from protobuf field optional string json_parsing = 282493529;
     * @param string $var
     * @return $this
     */
    public function setJsonParsing($var)
    {
        GPBUtil::checkString($var, True);
        $this->json_parsing = $var;

        return $this;
    }

    /**
     *
     * Check the LogLevel enum for the list of possible values.
     *
     * Generated from protobuf field optional string log_level = 140582601;
     * @return string
     */
    public function getLogLevel()
    {
        return isset($this->log_level) ? $this->log_level : '';
    }

    public function hasLogLevel()
    {
        return isset($this->log_level);
    }

    public function clearLogLevel()
    {
        unset($this->log_level);
    }

    /**
     *
     * Check the LogLevel enum for the list of possible values.
     *
     * Generated from protobuf field optional string log_level = 140582601;
     * @param string $var
     * @return $this
     */
    public function setLogLevel($var)
    {
        GPBUtil::checkString($var, True);
        $this->log_level = $var;

        return $this;
    }

}


text:
import string

class Notifyer:

	servingClass = None
	NOTIFY = 'NOTIFY'
	DEBUG = 'DEBUG'
	WARNING = 'WARNING'
	ERROR = 'ERROR'

	@staticmethod
	def parseString(string):
		if string == '' and len(string) == 0:
			return False

		return True

	@classmethod
	def setupClassNotify(cls, className):
		cls.servingClass = className
		return cls

	@classmethod
	def setNotifyInfo(cls, string):
		if cls.parseString(string) == False:
			return

		print ('%s: %s:: %s' % (cls.servingClass, cls.NOTIFY, string))

	@classmethod
	def setNotifyDebug(cls, string):
		if cls.parseString(string) == False:
			return

		print ('%s: %s:: %s' % (cls.servingClass, cls.DEBUG, string))

	@classmethod
	def setNotifyWarning(cls, string):
		if cls.parseString(string) == False:
			return

		print ('%s: %s:: %s' % (cls.servingClass, cls.WARNING, string))

	@classmethod
	def setNotifyError(cls, string):
		if cls.parseString(string) == False:
			return

		print ('%s: %s:: %s' % (cls.servingClass, cls.ERROR, string))


text:
#ifndef _COMPLEX_H_
#define _COMPLEX_H_

/* All the headers include this file. */
#include <_mingw.h>

/* These macros are specified by C99 standard */

#ifndef __cplusplus
#define complex _Complex
#endif

#define _Complex_I  (0.0F +  1.0iF)

/* GCC doesn't support _Imaginary type yet, so we don't
   define _Imaginary_I */

#define I _Complex_I

#ifdef __cplusplus
extern "C" {
#endif

#ifndef RC_INVOKED

double __MINGW_ATTRIB_CONST creal (double _Complex);
double __MINGW_ATTRIB_CONST cimag (double _Complex);
double __MINGW_ATTRIB_CONST carg (double _Complex);
double __MINGW_ATTRIB_CONST cabs (double _Complex);
double _Complex __MINGW_ATTRIB_CONST conj (double _Complex);
double _Complex  cacos (double _Complex);
double _Complex  casin (double _Complex);
double _Complex  catan (double _Complex);
double _Complex  ccos (double _Complex);
double _Complex  csin (double _Complex);
double _Complex  ctan (double _Complex);
double _Complex  cacosh (double _Complex);
double _Complex  casinh (double _Complex);
double _Complex  catanh (double _Complex);
double _Complex  ccosh (double _Complex);
double _Complex  csinh (double _Complex);
double _Complex  ctanh (double _Complex);
double _Complex  cexp (double _Complex);
double _Complex  clog (double _Complex);
double _Complex  cpow (double _Complex, double _Complex);
double _Complex  csqrt (double _Complex);
double _Complex __MINGW_ATTRIB_CONST cproj (double _Complex);

float __MINGW_ATTRIB_CONST crealf (float _Complex);
float __MINGW_ATTRIB_CONST cimagf (float _Complex);
float __MINGW_ATTRIB_CONST cargf (float _Complex);
float __MINGW_ATTRIB_CONST cabsf (float _Complex);
float _Complex __MINGW_ATTRIB_CONST conjf (float _Complex);
float _Complex  cacosf (float _Complex);
float _Complex  casinf (float _Complex);
float _Complex  catanf (float _Complex);
float _Complex  ccosf (float _Complex);
float _Complex  csinf (float _Complex);
float _Complex  ctanf (float _Complex);
float _Complex  cacoshf (float _Complex);
float _Complex  casinhf (float _Complex);
float _Complex  catanhf (float _Complex);
float _Complex  ccoshf (float _Complex);
float _Complex  csinhf (float _Complex);
float _Complex  ctanhf (float _Complex);
float _Complex  cexpf (float _Complex);
float _Complex  clogf (float _Complex);
float _Complex  cpowf (float _Complex, float _Complex);
float _Complex  csqrtf (float _Complex);
float _Complex __MINGW_ATTRIB_CONST cprojf (float _Complex);

long double __MINGW_ATTRIB_CONST creall (long double _Complex);
long double __MINGW_ATTRIB_CONST cimagl (long double _Complex);
long double __MINGW_ATTRIB_CONST cargl (long double _Complex);
long double __MINGW_ATTRIB_CONST cabsl (long double _Complex);
long double _Complex __MINGW_ATTRIB_CONST conjl (long double _Complex);
long double _Complex  cacosl (long double _Complex);
long double _Complex  casinl (long double _Complex);
long double _Complex  catanl (long double _Complex);
long double _Complex  ccosl (long double _Complex);
long double _Complex  csinl (long double _Complex);
long double _Complex  ctanl (long double _Complex);
long double _Complex  cacoshl (long double _Complex);
long double _Complex  casinhl (long double _Complex);
long double _Complex  catanhl (long double _Complex);
long double _Complex  ccoshl (long double _Complex);
long double _Complex  csinhl (long double _Complex);
long double _Complex  ctanhl (long double _Complex);
long double _Complex  cexpl (long double _Complex);
long double _Complex  clogl (long double _Complex);
long double _Complex  cpowl (long double _Complex, long double _Complex);
long double _Complex  csqrtl (long double _Complex);
long double _Complex __MINGW_ATTRIB_CONST cprojl (long double _Complex);

#ifdef __GNUC__

/* double */
__CRT_INLINE double __MINGW_ATTRIB_CONST creal (double _Complex _Z)
{
  return __real__ _Z;
}

__CRT_INLINE double __MINGW_ATTRIB_CONST cimag (double _Complex _Z)
{
  return __imag__ _Z;
}

__CRT_INLINE double _Complex __MINGW_ATTRIB_CONST conj (double _Complex _Z)
{
  return __extension__ ~_Z;
}

__CRT_INLINE  double __MINGW_ATTRIB_CONST carg (double _Complex _Z)
{
  double res;
  __asm__  ("fpatan;"
	   : "=t" (res) : "0" (__real__ _Z), "u" (__imag__ _Z) : "st(1)");
  return res;
}

/* float */
__CRT_INLINE float __MINGW_ATTRIB_CONST crealf (float _Complex _Z)
{
  return __real__ _Z;
}

__CRT_INLINE float __MINGW_ATTRIB_CONST cimagf (float _Complex _Z)
{
  return __imag__ _Z;
}

__CRT_INLINE float _Complex __MINGW_ATTRIB_CONST conjf (float _Complex _Z)
{
  return __extension__ ~_Z;
}

__CRT_INLINE  float __MINGW_ATTRIB_CONST cargf (float _Complex _Z)
{
  float res;
  __asm__  ("fpatan;"
	   : "=t" (res) : "0" (__real__ _Z), "u" (__imag__ _Z) : "st(1)");
  return res;
}

/* long double */
__CRT_INLINE long double __MINGW_ATTRIB_CONST creall (long double _Complex _Z)
{
  return __real__ _Z;
}

__CRT_INLINE long double __MINGW_ATTRIB_CONST cimagl (long double _Complex _Z)
{
  return __imag__ _Z;
}

__CRT_INLINE long double _Complex __MINGW_ATTRIB_CONST conjl (long double _Complex _Z)
{
  return __extension__ ~_Z;
}

__CRT_INLINE  long double __MINGW_ATTRIB_CONST cargl (long double _Complex _Z)
{
  long double res;
  __asm__  ("fpatan;"
	   : "=t" (res) : "0" (__real__ _Z), "u" (__imag__ _Z) : "st(1)");
  return res;
}

#endif /* __GNUC__ */

#endif /* RC_INVOKED */

#ifdef __cplusplus
}
#endif

#endif /* _COMPLEX_H */


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="quickContactBadgeStyle">
        <item name="android:background">@drawable/ic_action_user</item>
    </style>

</resources>


text:
!Recordemos. Para declarar una variable que almacene caracteres, hacemos lo siguiente:
!character :: nom_var
!Y para declarar cadenas de caracteres haciamos lo siguiente:
!character(len=20) :: string_var
!Además, para la declaración de constantes haciamos uso del atributo "parameter":
!real, parameter :: const

!Entonces, para declarar una variable que almacena caracteres que no permita cambios, hacemos lo siguiente:
!character, parameter :: const_char
!character(len=4), parameter :: const_string

!Además, si no se sabe el tamaño exácto de la cadena, se puede utilizar el caracter * que actua como un tipo de
!comodín para que la longitud sea autoajustable:
!character(len=*), parameter :: len_desconocido = "Hola Mundo!"
!Para que funcione esto, se debe siempre declarar como un constante com el atributo "parameter"

program const_caract
character :: nom_var
character(len=20) :: string_var
real, parameter :: const = 2.7921

character, parameter :: const_char = 'c'
character(len=4), parameter :: const_string = "Hola"

character(len=*), parameter :: len_desconocido = "Hola Mundo!"
!character(len=*) :: len_desconocido = "Hola Mundo!" !Esto produce un error

end program const_caract