text:
layout: post
title: "a javascript primer "
date: "2016-02-23"
---
Let's learn some JavaScript!
Variables

Here's how you declare a variable in JavaScript:

var a;

The var keyword lets JavaScript know that whatever comes after is a variable. Now let's assign a value to our variable:

var a = 12;

Now maybe you've seen something like this while looking at some JavaScript code:

a = 12;

JavaScript doesn't seem to mind when you ommit the var keyword. So what is it good for?

The var keyword makes our variable local. Inside a Meteor app, this means that prefixing a variable with var will restrict its scope to the function you're declaring it in (or the file, if you declare it outside of any function).

On the other hand, omitting the var keyword will make your variable available to your whole Meteor app. Sometimes that's good, but in most case it's better to try and avoid polluting the global scope.
What global scope pollution looks like.
Functions

Here's how you declare a function in JavaScript:

var myAwesomeFunction = function (myArgument) {
  // do something
}

And here's how you'd call your function:

myAwesomeFunction(something);

You'll notice function declarations follow the same var something = somethingElse pattern as variable declarations.

As they should, since in JavaScript, functions are variables too! This means that you can do stuff like using functions as arguments for other functions:

square = function (a) {
  return a*a;
}
applyOperation = function (f, a) {
  return f(a);
}
applyOperation (square, 10); // 100

Return

A return statement takes a value and returns this value as the result of a function. The key thing to remember here is that whatever comes after return will never get executed:

myFunction = function (a) {
  return a * 3;
  explodeComputer(); // will never get executed (hopefully!)
}

If Statements

Here's what an If statement looks like in JavaScript:

if (foo) {
  return bar;
}

As long as the block of code inside the if fits in one line, you can also use this shorthand syntax (note the lack of curly brackets):

if (foo)
  return bar;

If/Else Statements

Here's what an If/Else statement looks like in JavaScript:

if (foo) {
  function1();
} else {
  function2();
}

If/Else statements also have their own shorthand syntax:

foo ? function1() : function2();

This is particularly useful when assigning a value to a variable:

var n = foo ? 1 : 2;

This means "if foo is true, then set n to 1, otherwise set it to 2".

Oh and for good measure, here's an If/Else If/Else:

if (foo) {
  function1();
} else if (bar) {
  function2();
} else {
  function3();
}

JavaScript Arrays

Here's how you define an array:

a = [123, 456, 789];

And here's how you access an array item (indexes start at 0):

a[1]; // 456

JavaScript Objects

Here's how you define a JavaScript object:

myProfile = {
  name: "John Smith",
  email: "johnsmith@gmail.com",
  'zip code': 12345,
  isInvited: true
}

After the object declaration (myProfile = {…}) comes a list of comma-separated pairs. Each pair contains a key (a string, which can optionally be enclosed in quotes if it contains any spaces) and a value (any type of JavaScript item: strings, numbers, booleans, variables, arrays, objects, and even functions).

You can also nest objects, and even use arrays:

myProfile = {
  name: "John Smith",
  email: "johnsmith@gmail.com",
  city: "San Francisco",
  points: 1234,
  isInvited: true,
  friends: [
    {
      name: "John Doe",
      email: "johndoe@gmail.com"
    },
    {
      name: "Jane Doe",
      email: "janedoe@gmail.com"
    }
  ]
}

Accessing an object's property couldn't be simpler: just use the dot notation. You can even combine it with arrays:

myProfile.name; // John Smith
myProfile.friends[1].name; // Jane Doe

You'll find JavaScript objects almost everywhere in JavaScript, especially when invoking functions. For example, here's how you would search for a post in your database with Meteor:

Posts.findOne({ title: 'My First Post' });

This {title: 'My First Post'} argument is an anonymous JavaScript object. With JavaScript, you'll see that most of the time you don't actually need to assign a name to an object (or even to a function) to make use of it.
Anonymous Functions

We've seen you can declare functions using the following syntax:

myFunction = function (myArgument) {
  // do something
}

And we've seen that JavaScript treats functions just like variables, letting you pass them as arguments to other functions:

square = function (a) {
  return a*a;
}
applyOperation = function (f, a) {
  return f(a);
}
applyOperation(square, 10); // 100

And we've also seen that JavaScript loves coming up with shorter ways to write things. So here's an equivalent syntax:

applyOperation = function (f, a) {
  return f(a);
}
applyOperation(
  function(a){
    return a*a;
  },
  10
) // 100

Instead of defining the square function and passing it as an argument, we're defining it inside the argument call. This is known as using an "anonymous function", and it's one of the most common JavaScript patterns around.
The call is coming from inside the function!
Chaining

We've seen that you can pass parameters to functions. But there's another syntax that you'll often encounter for things such as array or string operations:

var myArray = [123, 456];
myArray.push(789) // 123, 456, 789

var myString = "abcdef";
myString.replace("a", "z"); // "zbcdef"

This dot notation means "call the replace function on myString with arguments "a" and "z" and return the result".

The beauty of it is that you can also chain multiple links together as long as they all return something. We won't get into how to define chainable functions, but using them is easy enough. Just follow the something.function1().function2().function3() pattern.

Each link of the chain will take a value, apply a function to it, and then pass on its result to the next link:

n = 5;
n.double().square(); //100

This

this is probably one of the hardest concept to master in all of JavaScript.

Basically, the this keyword lets you access the object on which you're currently working: just like a chameleon, this keeps changing based on its surroundings.

So instead of trying to explain this, let me give you two tools to help you figure things out yourself (what do you mean, I'm taking the easy way out?!).

The first is the good old console.log(), which prints any object to the browser's console. Adding a console.log(this) to begin a function is often the best way to figure out what's going on:

myFunction = function (a, b) {
  console.log(this);
  // do something
}

The second pattern is assigning this to another variable:

myFunction = function (a, b) {
  var myObject = this;
  // do something
}

While it might at first seem like this doesn't accomplish anything, it lets you safely re-use myObject throughout your code, since unlike this its value won't change depending on the context.
Operators

= is the assigment operator. This means that a = 12 means assign the value "12" to a.

If you want to compare two values, you would use ==, as in a == 12.

JavaScript also features the === operator, which compares both value and type (i.e. string, integer, etc.):

a = "12";
a == 12; // true
a === 12; // false

In most cases, you'll want to use the === operator whenever comparing two values, because there aren't that many cases where you'd want two variables to be equal in value but not in type.

Here's JavaScript's unequality operator:

a = 12;
a !== 11; // true

The ! operator can also be used independently to get the opposite of a boolean value:

a = true;
!a; // false

An interesting consequence of the ! operator is that it always returns a boolean value, even if what comes after is not a boolean:

a = 12;
!a; // false

This means that if you want to convert a variable to boolean you can just use the ! operator twice (once to force the variable to boolean, a second time to revert the value back):

a = 12;
!!a; // true

Or:

a = 0;
!!a; // false

Weird Random Characters

You'll often encounter stuff like this:

$('body').addClass('loaded');

Or this:

_.shuffle([1, 2, 3, 4, 5, 6])

You might think $ and _ are special JavaScript operators, but they're actually just user-defined variable names!

$() is commonly used as an alias for the jQuery function (from the jQuery library), while _ is the main object of the Underscore library.

So if you ever encounter some weird out-of-place character in your JavaScript code, make sure it's not a variable before assuming you just discovered a new, little-used syntax feature.
Style

Finally, here are a few optional style rules that will make your JavaScript code cleaner:

    Use camelCase: write myRandomVariable, not my_random_variable.
    Add a ; at the end of each line, even if it's optional.
    Separate each keyword with a space, i.e. a = b + 1, not a=b+1.

You'll find more guidelines in the Meteor Style Guide.
Putting It Together

So now that you're equipped with the basics of JavaScript syntax, let's try to put it together and understand a bit of Meteor code (adapted from Microscope, the app we'll build step by step in Discover Meteor):

Template.postEdit.events({
  'submit form': function(event) {
    event.preventDefault();

    var currentPostId = this._id;

    var postProperties = {
      url: $(event.target).find('[name=url]').val(),
      title: $(event.target).find('[name=title]').val()
    }

    Posts.update(currentPostId, {$set: postProperties}, function(error) {
      if (error) {
        // display the error to the user
        throwError(error.reason);
      } else {
        Router.go('postPage', {_id: currentPostId});
      }
    });
  }
});

This tells the app what to do when someone submits the form that lets you edit a post:

    First, prevent the default browser behavior for the submit event.
    Then, define a variable containing the current post's ID.
    Get the latest value of the text fields.
    Update the database with those values.
    Finally, either throw an error, or redirect the user.

Let's break this down (I'll highlight each syntax pattern as we go):

Template.postEdit.events({: We're diving into the Template object, accessing its postEdit property, then using dot notation to call the events() function (which is itself a property of postEdit) on an anonymous JavaScript object ({}) (chaining, JavaScript objects).

'submit form': function(e) {: The first (and only) key/value pair of the JavaScript object. Since the key (submit form) contains a space, it's enclosed in quotes. The value is an anonymous function called with one argument (event).

event.preventDefault();: We're calling the preventDefault(); function of the event object that was just passed as an argument to stop the form's default submit behavior.

var currentPostId = this._id;: In this context, this corresponds to the post being edited. We're declaring a local variable (currentPostId) whose value is that post's _id property.

var postProperties = {: We're declaring another JavaScript object and using jQuery (the $ sign is an alias for the Jquery object) to get the url and title field's value from the user interface.

Posts.update(currentPostId, {$set: postProperties}, function(error) {: We're passing three things to the update() function: the ID of the post to update, a JavaScript object containing the properties to update, and finally a callback anonymous function that will run once the update has concluded.
Going Forward

This tutorial is by no means meant to replace actually learning JavaScript. But the various patterns covered here should be enough to let you understand the vast majority of Discover Meteor's code, at least from a syntax point of view.

So if like me you prefer learning by doing, hopefully this should be enough to get you ready to start building Meteor apps!
JavaScript Resources

Here's a few good links to dig some more into JavaScript:

    Codecademy
    JavaScript Is Sexy
    SuperHero.js

Source https://www.discovermeteor.com/blog/javascript-for-meteor/


text:
This package provides all device types that are supported by the Elis platform.

Every single device is descended from the
{@link se.mah.elis.adaptor.building.api.entities.devices.Device} base
interface. They are then divided into two categories:
{@link se.mah.elis.adaptor.building.api.entities.devices.Sensor}s and
{@link se.mah.elis.adaptor.building.api.entities.devices.Actuator}s.
The key difference between the two is that a sensor device measures its
environment, whereas an actuator manipulates it. The sensor class of
devices is further divided into the two
{@link se.mah.elis.adaptor.building.api.entities.devices.Detector} and
{@link se.mah.elis.adaptor.building.api.entities.devices.Sampler} interfaces,
which provide functionality for sampling and event creation. Note that there
are some sensors that fall outside of any of those two categories. Furthermore,
a device can be both a sensor and an actuator. This is reflected in the API,
where for example the
{@link se.mah.elis.adaptor.building.api.entities.devices.Thermostat} interface
extends both the
{@link se.mah.elis.adaptor.building.api.entities.devices.Thermometer}, which is
a sensor, and the
{@link se.mah.elis.adaptor.building.api.entities.devices.Actuator} interfaces.
As is the case with all interfaces, any implementation of those interfaces can
choose freely what interfaces to implement, giving way for multi-capable
devices.

However, the above isn't entirely true. The
{@link se.mah.elis.adaptor.building.api.entities.devices.Gateway} interface,
that is used to describe a gateway device isn't considered a device on its own
merits. Instead, it is considered a special case of a
{@link se.mah.elis.adaptor.building.api.entities.devices.DeviceSet}, with some
extra information regarding addressing, identification and so on. In the case
where an actual gateway has sensory or actuating capabilities, the proper
implementation of such a gateway object would have to implement the gateway
class as both a
{@link se.mah.elis.adaptor.building.api.entities.devices.Device} and a
{@link se.mah.elis.adaptor.building.api.entities.devices.Gateway}.

Also provided in this package are various auxiliary interfaces, that can be
used as capabilities to the device objects. One such example is the
{@link se.mah.elis.adaptor.building.api.entities.devices.BatteryEquipped}
interface.

@since 1.0

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="Polymer Starter Kit">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>My App</title>
    <meta name="description" content="My App description">

    <link rel="icon" href="images/favicon.ico">

    <!-- See https://goo.gl/OOhYW5 -->
    <link rel="manifest" href="manifest.json">

    <!-- See https://goo.gl/qRE0vM -->
    <meta name="theme-color" content="#3f51b5">

    <!-- Add to homescreen for Chrome on Android. Fallback for manifest.json -->
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="My App">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="My App">

    <!-- Homescreen icons -->
    <link rel="apple-touch-icon" href="images/manifest/icon-48x48.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/manifest/icon-72x72.png">
    <link rel="apple-touch-icon" sizes="96x96" href="images/manifest/icon-96x96.png">
    <link rel="apple-touch-icon" sizes="144x144" href="images/manifest/icon-144x144.png">
    <link rel="apple-touch-icon" sizes="192x192" href="images/manifest/icon-192x192.png">

    <!-- Tile icon for Windows 8 (144x144 + tile color) -->
    <meta name="msapplication-TileImage" content="images/manifest/icon-144x144.png">
    <meta name="msapplication-TileColor" content="#3f51b5">
    <meta name="msapplication-tap-highlight" content="no">

    <script>
      // Setup Polymer options
      window.Polymer = {
        dom: 'shadow',
        lazyRegister: true,
      };

      // Load webcomponentsjs polyfill if browser does not support native
      // Web Components
      (function() {
        'use strict';

        var onload = function() {
          // For native Imports, manually fire WebComponentsReady so user code
          // can use the same code path for native and polyfill'd imports.
          if (!window.HTMLImports) {
            document.dispatchEvent(
              new CustomEvent('WebComponentsReady', {bubbles: true})
            );
          }
        };

        var webComponentsSupported = (
          'registerElement' in document
          && 'import' in document.createElement('link')
          && 'content' in document.createElement('template')
        );

        if (!webComponentsSupported) {
          var script = document.createElement('script');
          script.async = true;
          script.src = 'bower_components/webcomponentsjs/webcomponents-lite.min.js';
          script.onload = onload;
          document.head.appendChild(script);
        } else {
          onload();
        }
      })();

      // Load pre-caching Service Worker
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('service-worker.js');
        });
      }
    </script>

    <link rel="import" href="src/my-app.html">

    <style>
      body {
        margin: 0;
        font-family: 'Roboto', 'Noto', sans-serif;
        line-height: 1.5;
        min-height: 100vh;
        background-color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <my-app></my-app>
    <!-- Built with love using Polymer Starter Kit -->
  </body>
</html>


text:
package org.apache.wicket.request.mapper.info;

import junit.framework.TestCase;

import org.junit.Test;

/**
 *
 * @author Matej Knopp
 */
public class PageComponentInfoTest extends TestCase
{

	private void testPageInfoOnly(PageComponentInfo info, Integer pageId)
	{
		assertNull(info.getComponentInfo());
		assertNotNull(info.getPageInfo());

		assertEquals(pageId, info.getPageInfo().getPageId());
	}

	private void testPageComponentInfo(PageComponentInfo info, Integer pageId, String listener,
		String componentPath)
	{
		assertNotNull(info.getComponentInfo());
		assertNotNull(info.getPageInfo());

		assertEquals(pageId, info.getPageInfo().getPageId());

		assertEquals(listener, info.getComponentInfo().getListenerInterface());
		assertEquals(componentPath, info.getComponentInfo().getComponentPath());
	}

	/**
	 *
	 */
	@Test
	public void test1()
	{
		String s = "2-click-foo-bar-baz";
		PageComponentInfo info = PageComponentInfo.parse(s);
		testPageComponentInfo(info, 2, "click", "foo:bar:baz");
		assertEquals(s, info.toString());
	}

	/**
	 *
	 */
	@Test
	public void test2()
	{
		String s = "2";
		PageComponentInfo info = PageComponentInfo.parse(s);
		testPageInfoOnly(info, 2);
		assertEquals(s, info.toString());
	}

	/**
	 * WICKET-3490
	 */
	@Test
	public void parsePageInfo()
	{
		PageComponentInfo pageComponentInfo = PageComponentInfo.parse("99999999999999999999999999999999999999999999999999999999999999999999999");
		assertNull(pageComponentInfo);
	}
}


text:
  <chat-event *ngSwitchCase="hypertyResourceType.Chat" [message]="resource" [isAnEvent]="eventMode"></chat-event>
  <file-event *ngSwitchCase="hypertyResourceType.File" (downloadEvent)="onDownloadEvent($event)" (viewImageEvent)="onViewImageEvent($event)" [message]="resource" [isAnEvent]="eventMode"></file-event>
  {{ resource }}


text:
if [ "$TRAVIS_OS_NAME" = osx ]; then
  VIRTUAL_ENV="$HOME/virtualenv/python2.7"
  source "$VIRTUAL_ENV/bin/activate"
fi

eval "$@"


text:
package com.lid.intellij.translateme.configuration;

import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public final class ConfigurationComponent implements Configurable {
	public static final String COMPONENT_NAME = "Translate.ConfigurationComponent";
//  private final ImageIcon CONFIG_ICON =
//          helper.getIcon("resources/icon.png", getClass());

	//public static final String CONFIGURATION_LOCATION;
	//+"/.IntelliJIdea70/config/inspection";

	//static {
	//	CONFIGURATION_LOCATION = System.getProperty("user.home");
	//	//+"/.IntelliJIdea70/config/inspection";
	//}

	private TranslationConfigurationForm form;
	private PersistingService instance;

	@Override
	public boolean isModified() {
		return form != null && form.isModified(getState());
	}

	private ConfigurationState getState() {
		return instance.getState();
	}

	@NotNull
	public String getComponentName() {
		return COMPONENT_NAME;
	}

	@Override
	public String getDisplayName() {
		return "TranslateMe";
	}

	public Icon getIcon() {
//    return CONFIG_ICON;
		return null;
	}

	@Override
	public String getHelpTopic() {
		return null;
	}

	@Override
	public JComponent createComponent() {
		if (form == null) {
			form = new TranslationConfigurationForm();
		}
		instance = PersistingService.getInstance();
		ConfigurationState state = instance.getState();
		form.load(state);

		return form.getRootComponent();
	}

	/**
	 * Stores settings from form to configuration bean.
	 *
	 * @throws ConfigurationException
	 */
	@Override
	public void apply() throws ConfigurationException {
		if (form != null) {
			form.save(getState());
		}
	}

	/**
	 * Restores form values from configuration.
	 */
	@Override
	public void reset() {
		if (form != null) {
			form.load(getState());
		}
	}

	/**
	 * Disposes UI resource.
	 */
	@Override
	public void disposeUIResources() {
		form = null;
	}

}


text:
/**
 * save all constant always using
 * */
var app = angular.module('pkapollo',[]);
app.constant('base_url',window.location.protocol + '//' + window.location.hostname);
app.config(function ($provide) {
  $provide.value('admin_url',window.location.protocol + '//' + window.location.hostname + '/admin');
});
/** change $provide value => using encapsulation */
//app.config(function ($provide) {
//  $provide.decorator('admin_url', function ($delegate) {
//    return $delegate + ' - starring Keanu Reeves';
//  });
//});


text:
/*!
 * Module dependencies
 */
var util = require('util')
  , Resource = require('./')
  , updateMixin = require('../mixins/update')
  ;

/*!
 * Expose `Company()`.
 */
exports = module.exports = Company;

/**
 * Initialize a new `Company` with the given `parent` and `definition`.
 *
 * @param {Function} parent The parent this resource is attached to.
 * @param {Object} definition The resource definition.
 * @api private
 */
function Company(parent, definition) {
  var key;
  for (key in updateMixin) {
    this[key] = updateMixin[key];
  }
  Company.super_.apply(this, arguments);
}
util.inherits(Company, Resource);

Company.create = require('../mixins/create');


text:
package com.intellij.ui.mac.touchbar;

import com.intellij.ui.mac.foundation.ID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

class TBItemGroup extends TBItem {
  private final ItemsContainer myGroupItems;

  TBItemGroup(@NotNull String name, @Nullable ItemListener listener) {
    super("group", listener);
    myGroupItems = new ItemsContainer(name + "_group");
  }

  ItemsContainer getContainer() { return myGroupItems; }

  @Override
  protected ID _createNativePeer() {
    if (myGroupItems.isEmpty())
      return ID.NIL;

    final ID[] ids = myGroupItems.getVisibleNativePeers();
    return NST.createGroupItem(getUid(), ids);
  }

  @Override
  void releaseNativePeer() {
    myGroupItems.releaseAll();
    super.releaseNativePeer();
  }
}


text:
package com.strategicgains.restexpress.plugin.cors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.restexpress.ContentType;
import org.restexpress.Flags;
import org.restexpress.Request;
import org.restexpress.Response;
import org.restexpress.RestExpress;
import org.restexpress.common.util.StringUtils;
import org.restexpress.domain.metadata.RouteMetadata;
import org.restexpress.pipeline.Postprocessor;
import org.restexpress.plugin.AbstractPlugin;
import org.restexpress.route.RouteBuilder;
import org.restexpress.util.Callback;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;

/**
 * This RestExpress plugin supports CORS behavior by setting the
 * 'Access-Control-Allow-Origin' header.  It also, by default, sets up the
 * pre-flight CORS request by creating an OPTIONS route for all URI patterns
 * registered in the service suite.
 *

 * Usage requires passing in the appropriate domain names that are allowed to
 * perform cross-domain behaviors. To support cross-domain behavior globally
 * (not recommended) send in '*' (wildcard). Or, arguably more secure, use '{origin}',
 * which will cause the plugin to return the Access-Control-Allow-Origin set
 * to the incoming Origin header set by the browser (or exclude the header altogether, if no Origin
 * header is present).
 *

 * Usage: RestExpress server = new RestExpress(); ... new
 * CorsHeaderPlugin("{origin}").register(server);
 * or... server.registerPlugin(new CorsHeaderPlugin("{origin}"));
 *

 * You can also disable the OPTIONS route that gets automatically generated
 * to support the pre-flight CORS request by calling .noPreflightSupport()
 * before calling register() as follows:

 * new CorsHeaderPlugin("{origin}").noPreflightSupport().register();
 *

 * Additionally, you can set flag() and parameter() values on the OPTIONS
 * preflight route (just like normal RestExpress routes) by calling .flag(String)
 * and .parameter(String, Object) after before register() as follows:

 * new CorsHeaderPlugin("*").flag(NO_SECURITY).parameter("s42",Boolean.FALSE).register();
 *

 * Note that flag() and parameter() values have no effect if noPreflightSupport() is called.
 *

 * For deeper information on the CORS specification, see: http://www.w3.org/TR/cors/
 *
 * @author toddf
 * @since Jun 8, 2012
 */
public class CorsHeaderPlugin
extends AbstractPlugin
{
	private static final String CORS_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";

	private Set<String> allowedOrigins;
	private String exposeHeadersHeader;
	private String allowHeadersHeader;
	private Long maxAge;
	private Map<String, Set<HttpMethod>> methodsByPattern = new LinkedHashMap<>();
	private List<RouteBuilder> routeBuilders = new ArrayList<>();
	private boolean isPreflightSupported = true;
	private boolean shouldAllowCredentials = false;
	private List<String> flags = new ArrayList<>();
	private Map<String, Object> parameters = new HashMap<>();

	public CorsHeaderPlugin()
	{
		super();
	}

	public CorsHeaderPlugin(String... origins)
	{
		this();
		this.allowedOrigins = (origins != null ? new HashSet<>(Arrays.asList(origins)) : null);
	}

	/**
	 * Sets the maxAge for caching on the preflight OPTIONS request.
	 *
	 * @param seconds
	 * @return
	 */
	public CorsHeaderPlugin maxAge(long seconds)
	{
		if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.maxAge(long) must be called before register()");

		this.maxAge = Long.valueOf(seconds);
		return this;
	}

	/**
	 * Set the value of the 'Access-Control-Expose-Headers' header on responses.
	 *
	 * @param exposeHeaders
	 * @return
	 */
	public CorsHeaderPlugin exposeHeaders(String... exposeHeaders)
	{
		exposeHeadersHeader = StringUtils.join(",", (Object[])exposeHeaders);
		return this;
	}

	public CorsHeaderPlugin allowHeaders(String... allowHeaders)
	{
		allowHeadersHeader = StringUtils.join(",", (Object[])allowHeaders);
		return this;
	}

	public CorsHeaderPlugin allowCredentials()
	{
		shouldAllowCredentials = true;
		return this;
	}

	public CorsHeaderPlugin echoOrigin()
	{
		this.allowedOrigins = null;
		return this;
	}

	/**
	 * Disables the OPTIONS method that gets automatically generated for each URI pattern in the service suite.
	 * Must be called before register().
	 */
	public CorsHeaderPlugin noPreflightSupport()
	{
		if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.noPreflightSupport() must be called before register()");

		isPreflightSupported = false;
		return this;
	}

	/**
	 * Set a flag on the automatically generated OPTIONS route for pre-flight CORS requests.
	 *
	 * @param flagValue
	 * @return a reference to this plugin to support method chaining.
	 */
	public CorsHeaderPlugin flag(String flagValue)
	{
		if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.flag(String) must be called before register()");

		if (!flags.contains(flagValue))
		{
			flags.add(flagValue);
		}

		return this;
	}

	public CorsHeaderPlugin parameter(String name, Object value)
	{
		if (isRegistered()) throw new UnsupportedOperationException("CorsHeaderPlugin.parameter(String, Object) must be called before register()");

		parameters.put(name, value);
		return this;
	}

	@Override
	public CorsHeaderPlugin register(RestExpress server)
	{
		if (isRegistered()) return this;

		super.register(server);
		server.iterateRouteBuilders(new Callback<RouteBuilder>()
		{
			@Override
			public void process(RouteBuilder builder)
			{
				RouteMetadata rmd = builder.asMetadata();
				Set<HttpMethod> methods = new HashSet<>();

				for (String methodString : rmd.getMethods())
				{
					methods.add(HttpMethod.valueOf(methodString));
				}

				if (isPreflightSupported && !methods.contains(HttpMethod.OPTIONS))
				{
					methods.add(HttpMethod.OPTIONS);
				}

				String pathPattern = rmd.getUri().getPattern();
                updateAcceptedMethods(methods, pathPattern);

                for (String alias : rmd.getAliases())
                {
                	updateAcceptedMethods(methods, alias);
                }
			}

			private void updateAcceptedMethods(Set<HttpMethod> methods, String pathPattern)
            {
	            Set<HttpMethod> existingMethods = methodsByPattern.get(pathPattern);

                if (existingMethods != null)
				{
					existingMethods.addAll(methods);
				}
				else
				{
					existingMethods = methods;
				}

				methodsByPattern.put(pathPattern, existingMethods);
            }
		});

	    CorsOptionsController corsController = new CorsOptionsController(allowedOrigins, exposeHeadersHeader, allowHeadersHeader, maxAge, shouldAllowCredentials, methodsByPattern);

	    if (isPreflightSupported)
		{
			addPreflightOptionsRequestSupport(server, corsController);
		}

		server.addFinallyProcessor(new CorsHeaderPostprocessor(corsController));
		return this;
	}

	@Override
	public void bind(RestExpress server)
	{
		// This method intentionally left blank.
	}

    /**
     * Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request.
     *
     * @param server a RestExpress server instance.
     */
	private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController)
    {
	    RouteBuilder rb;

	    for (String pattern : methodsByPattern.keySet())
	    {
	    	rb = server.uri(pattern, corsOptionsController)
		    	.action("options", HttpMethod.OPTIONS)
		    	.noSerialization()
		    	// Disable both authentication and authorization which usually use a header such as Authorization.
		    	// When browser does CORS preflight with OPTIONS request, such headers are not included.
		    	.flag(Flags.Auth.PUBLIC_ROUTE)
		    	.flag(Flags.Auth.NO_AUTHORIZATION);

	    	for (String flag : flags)
	    	{
	    		rb.flag(flag);
	    	}

	    	for (Entry<String, Object> entry : parameters.entrySet())
	    	{
	    		rb.parameter(entry.getKey(), entry.getValue());
	    	}

	    	routeBuilders.add(rb);
	    }
    }

	public class CorsHeaderPostprocessor
	implements Postprocessor
	{
		CorsOptionsController cors;

		public CorsHeaderPostprocessor(CorsOptionsController corsController)
		{
			super();
			cors = corsController;
		}

		@Override
		public void process(Request request, Response response)
		{
			if (!HttpMethod.OPTIONS.equals(request.getEffectiveHttpMethod()))
			{
				cors.options(request, response);
			}
		}
	}

	private class CorsOptionsController
	{
		private static final String WILDCARD_ORIGIN = "*";
		private static final String CORS_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
		private static final String CORS_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
		private static final String CORS_EXPOSE_HEADERS_HEADER = "Access-Control-Expose-Headers";
		private static final String CORS_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";
		private static final String CORS_MAX_AGE_HEADER = "Access-Control-Max-Age";
		private static final String ORIGIN_PARAMETER = "{origin}";

		private Map<String, String> allowedMethodsByPattern = new HashMap<>();
		private Long maxAge;
		private Set<String> allowedOrigins;
		private String allowHeadersHeader;
		private String exposeHeadersHeader = null;
		private boolean allowCredentials = false;
		private boolean echoesOrigin;

		public CorsOptionsController(Set<String> allowedOrigins, String exposeHeadersHeader, String allowHeadersHeader, Long maxAge, boolean allowCredentials, Map<String, Set<HttpMethod>> methodsByPattern)
		{
			super();
			this.allowedOrigins = (allowedOrigins != null ? new HashSet<>(allowedOrigins) : null);
			this.exposeHeadersHeader = exposeHeadersHeader;
			this.maxAge = (maxAge == null ? null : maxAge);
			this.allowHeadersHeader = allowHeadersHeader;
			this.echoesOrigin = (allowedOrigins == null || allowedOrigins.contains(ORIGIN_PARAMETER));
			this.allowCredentials = allowCredentials;

			for (Entry<String, Set<HttpMethod>> entry : methodsByPattern.entrySet())
			{
				String pathPattern = entry.getKey().replaceFirst("\\.\\{format\\}", "");
				allowedMethodsByPattern.put(pathPattern, StringUtils.join(",", entry.getValue()));
			}
		}

        public void options(Request request, Response response)
		{
			String origin = computeOrigin(request);

			if (origin != null)
			{
				response.addHeader(CORS_ALLOW_ORIGIN_HEADER, origin);

				if (!isWildcard(origin))
				{
					response.addHeader(HttpHeaderNames.VARY.toString(), "origin");
				}
			}

			response.addHeader(CORS_ALLOW_METHODS_HEADER, allowedMethodsByPattern.get(request.getResolvedRoute().getPattern()));

			if (HttpMethod.OPTIONS.equals(request.getEffectiveHttpMethod()))
			{
				response.addHeader("Content-Length","0");
				response.setContentType(ContentType.TEXT_PLAIN);
			}

			if (maxAge != null && !response.hasHeader(CORS_MAX_AGE_HEADER))
			{
				response.addHeader(CORS_MAX_AGE_HEADER, String.valueOf(maxAge));
			}

			if (allowHeadersHeader != null)
			{
				response.addHeader(CORS_ALLOW_HEADERS_HEADER, allowHeadersHeader);
			}

			if (exposeHeadersHeader != null)
			{
				response.addHeader(CORS_EXPOSE_HEADERS_HEADER, exposeHeadersHeader);
			}

			if (allowCredentials)
			{
				response.addHeader(CORS_ALLOW_CREDENTIALS_HEADER, "true");
			}
		}

		private boolean isWildcard(String origin)
		{
			return (origin != null && origin.trim().equals(WILDCARD_ORIGIN));
		}

		private String computeOrigin(Request request)
		{
			String origin = request.getHeader(HttpHeaderNames.ORIGIN.toString());

			if (echoesOrigin || allowedOrigins.contains(origin))
			{
				return origin;
			}
			else if (allowedOrigins.contains(WILDCARD_ORIGIN))
			{
				return WILDCARD_ORIGIN;
			}

			return null;
		}
	}
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>cliche</title>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

    <link rel="stylesheet" href="/ProgressBG-TypeScript/lib/reveal.js/css/reveal.css">
    <link rel="stylesheet" href="/ProgressBG-TypeScript/lib/reveal.js/css/theme/sky.css" id="theme">

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/obsidian.min.css">

    <link rel="stylesheet" href="/ProgressBG-TypeScript/outfit/css/reveal.js.css">
    <link rel="stylesheet" type="text/css" href="/ProgressBG-TypeScript/outfit/css/custom_hljs.css">
    <link rel="stylesheet" type="text/css" href="/ProgressBG-TypeScript/outfit/css/common/themes/MatDes/text_schemes.css">
    <base target="_blank">

            White
            League
            Sky
            Beige
            Simple
            Serif
            Night
            Moon
            Solarized

PresentationTitile

Created for

            Iva E. Popova, 2016,

SectionTitle


text:
import React, { Component } from "react"
import { graphql } from "gatsby"

import ShowcaseView from "../views/showcase"

class ShowcasePage extends Component {
  render() {
    const data = this.props.data
    const location = this.props.location

    return <ShowcaseView data={data} location={location} />
  }
}

export default ShowcasePage

export const showcaseQuery = graphql`
  query {
    featured: allSitesYaml(filter: { featured: { eq: true } }) {
      edges {
        node {
          id
          title
          categories
          built_by
          fields {
            slug
          }
          childScreenshot {
            screenshotFile {
              childImageSharp {
                sizes(maxWidth: 512) {
                  ...GatsbyImageSharpSizes
                }
              }
            }
          }
        }
      }
    }
    allSitesYaml(filter: { main_url: { ne: null } }) {
      edges {
        node {
          id
          featured
          title
          categories
          built_by
          description
          main_url
          built_by_url
          source_url
          childScreenshot {
            screenshotFile {
              childImageSharp {
                resolutions(width: 282, height: 211) {
                  ...GatsbyImageSharpResolutions
                }
              }
            }
          }
          fields {
            slug
          }
        }
      }
    }
  }
`


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep11/call_cen_pll_setup.C $                 */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include    <stdint.h>

#include    <trace/interface.H>
#include    <initservice/taskargs.H>
#include    <errl/errlentry.H>

#include    <isteps/hwpisteperror.H>
#include    <errl/errludtarget.H>

#include    <initservice/isteps_trace.H>

//  targeting support
#include    <targeting/common/commontargeting.H>
#include    <targeting/common/utilFilter.H>

//Fapi Support
#include    <config.h>
#include    <fapi2.H>
#include    <fapi2/plat_hwp_invoker.H>
#include    <util/utilmbox_scratch.H>

// HWP
#include    <cen_pll_setup.H>

using   namespace   ERRORLOG;
using   namespace   ISTEP;
using   namespace   ISTEP_ERROR;
using   namespace   TARGETING;

namespace ISTEP_11
{
void* call_cen_pll_setup (void *io_pArgs)
{
    IStepError l_StepError;
    errlHndl_t l_err = NULL;

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_pll_setup entry" );

    TARGETING::TargetHandleList l_membufTargetList;
    getAllChips(l_membufTargetList, TYPE_MEMBUF);

    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_pll_setup: %d membufs found",
            l_membufTargetList.size());

    for (const auto & l_membuf_target : l_membufTargetList)
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "cen_pll_setup HWP target HUID %.8x",
            TARGETING::get_huid(l_membuf_target));

        //  call the HWP with each target
        fapi2::Target <fapi2::TARGET_TYPE_MEMBUF_CHIP> l_fapi_membuf_target
                (l_membuf_target);

        FAPI_INVOKE_HWP(l_err, cen_pll_setup, l_fapi_membuf_target);

        //  process return code.
        if ( l_err )
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "ERROR 0x%.8X:  cen_pll_setup HWP on target HUID %.8x",
                l_err->reasonCode(), TARGETING::get_huid(l_membuf_target) );

            // capture the target data in the elog
            ErrlUserDetailsTarget(l_membuf_target).addToLog( l_err );

            // Create IStep error log and cross reference to error that occurred
            l_StepError.addErrorDetails( l_err );

            // Commit Error
            errlCommit( l_err, ISTEP_COMP_ID );
        }
        else
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                     "SUCCESS :  cen_pll_setup HWP");
        }

    }

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_pll_setup exit" );

    return l_StepError.getErrorHandle();
}

};


text:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.jitsi</groupId>
    <artifactId>jitsi-universe</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../jitsi-universe/pom.xml</relativePath>
  </parent>

  <artifactId>libjitsi</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <name>libjitsi</name>
  <url>https://github.com/jitsi/libjitsi</url>

  <dependencies>
    <dependency>
      <groupId>ch.imvs</groupId>
      <artifactId>sdes4j</artifactId>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.sdp</groupId>
      <artifactId>jain-sdp</artifactId>
    </dependency>
    <dependency>
      <groupId>net.java.dev.jna</groupId>
      <artifactId>jna</artifactId>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
    </dependency>
    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
    </dependency>
    <!-- org.jitsi -->
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>bccontrib</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>fmj</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>ice4j</artifactId>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>jitsi-lgpl-dependencies</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>zrtp4j-light</artifactId>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.core</artifactId>
    </dependency>
    <!-- test -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src</sourceDirectory>
    <testSourceDirectory>test</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>org/jitsi/impl/neomedia/transform/srtp/CryptoBenchmark.java</exclude>
          </excludes>
        </configuration>
      </plugin>
      <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
         <configuration>
            <instructions>
               <Import-Package>*,sun.lwawt,sun.lwawt.macosx</Import-Package>
               <Export-Package>org.jitsi.util.*,
               org.jitsi.service.*,
               org.jitsi.sctp4j.*,
               org.jitsi.impl.neomedia,
               org.jitsi.impl.neomedia.codec,
               org.jitsi.impl.neomedia.codec.video.h264,
               org.jitsi.impl.neomedia.device,
               org.jitsi.impl.neomedia.format,
               org.jitsi.impl.neomedia.recording
               </Export-Package>
               <Private-Package>org.jitsi.examples.*,org.jitsi.impl.*</Private-Package>
               <Bundle-Activator>org.jitsi.service.libjitsi.LibJitsiActivator</Bundle-Activator>
               <Bundle-NativeCode>
                   darwin/libjnawtrenderer.jnilib;
                   darwin/libjnmaccoreaudio.jnilib;
                   darwin/libjnopus.jnilib;
                   darwin/libjnportaudio.jnilib;
                   darwin/libjnquicktime.jnilib;
                   darwin/libjnscreencapture.jnilib;
                   darwin/libjnsctp.jnilib;
                   darwin/libjnspeex.jnilib;
                   darwin/libjnvpx.jnilib;osname=Mac OS X;processor=x86-64,
                   linux-x86/libjnawtrenderer.so;
                   linux-x86/libjnopenssl.so;
                   linux-x86/libjnopus.so;
                   linux-x86/libjnportaudio.so;
                   linux-x86/libjnpulseaudio.so;
                   linux-x86/libjnscreencapture.so;
                   linux-x86/libjnsctp.so;
                   linux-x86/libjnspeex.so;
                   linux-x86/libjnvideo4linux2.so;osname=Linux;processor=x86,
                   linux-x86-64/libjnawtrenderer.so;
                   linux-x86-64/libjnopenssl.so;
                   linux-x86-64/libjnopus.so;
                   linux-x86-64/libjnportaudio.so;
                   linux-x86-64/libjnpulseaudio.so;
                   linux-x86-64/libjnscreencapture.so;
                   linux-x86-64/libjnsctp.so;
                   linux-x86-64/libjnspeex.so;
                   linux-x86-64/libjnvideo4linux2.so;
                   linux-x86-64/libjnvpx.so;osname=Linux;processor=x86-64,
                   win32-x86/jnawtrenderer.dll;
                   win32-x86/jndirectshow.dll;
                   win32-x86/jnopus.dll;
                   win32-x86/jnportaudio.dll;
                   win32-x86/jnscreencapture.dll;
                   win32-x86/jnsctp.dll;
                   win32-x86/jnspeex.dll;
                   win32-x86/jnvpx.dll;
                   win32-x86/jnwasapi.dll;osname=Win32;processor=x86,
                   win32-x86-64/jnawtrenderer.dll;
                   win32-x86-64/jndirectshow.dll;
                   win32-x86-64/jnopus.dll;
                   win32-x86-64/jnportaudio.dll;
                   win32-x86-64/jnscreencapture.dll;
                   win32-x86-64/jnsctp.dll;
                   win32-x86-64/jnspeex.dll;
                   win32-x86-64/jnvpx.dll;
                   win32-x86-64/jnwasapi.dll;
                   win32-x86-64/jnwincoreaudio.dll;osname=Win32;processor=x86-64
               </Bundle-NativeCode>
            </instructions>
         </configuration>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>lib/native</directory>
        <excludes>
          <!-- jitsi-lgpl-dependencies -->
          <exclude>**/*jnffmpeg.*</exclude>
          <exclude>**/*jng722.*</exclude>
        </excludes>
      </resource>
    </resources>
  </build>

  <repositories>
    <repository>
      <id>jitsi-maven-repository-releases</id>
      <layout>default</layout>
      <name>Jitsi Maven Repository (Releases)</name>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <url>https://github.com/jitsi/jitsi-maven-repository/raw/master/releases/</url>
    </repository>
    <repository>
      <id>jitsi-maven-repository-snapshots</id>
      <layout>default</layout>
      <name>Jitsi Maven Repository (Snapshots)</name>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
      <url>https://github.com/jitsi/jitsi-maven-repository/raw/master/snapshots/</url>
    </repository>
  </repositories>
</project>


text:
from .raw import *
from scrape import *
from parsed import *
from constants import *


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syst. mycol. (Lundae) 2(1): 106 (1822)

#### Original name
Solenia stipata Fr.

### Remarks
null


text:
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"regexp"
)

type styleWarning struct {
	code    int
	message string
}

var (
	singleBrace        = regexp.MustCompile(`^\s*\{\s*$`)
	endsWithSpaces     = regexp.MustCompile(`\s+$`)
	startsWithSpaces   = regexp.MustCompile(`^\s+`)
	fourSpacesIndented = regexp.MustCompile(`^( {4})*[^\s]+`)
	openingParenthese  = regexp.MustCompile(`[^_|\(| ]\(`)
	equalWithSpaces    = regexp.MustCompile(`[^ |!|<|>|=]=|=[^=| |>]`)
	moreThan120Chars   = regexp.MustCompile(`.{121}`)
	glibNotNecessary   = regexp.MustCompile(`GLib.print`)

	warningMessages = map[int]string{
		1: "First brace isn't on the end of the first line",
		2: "Trailing whitespaces at the end of the line",
		3: "Not indented using 4 spaces",
		4: "Opening parenthese not preceeded by a whitespace",
		5: "Equals sign not surrounded by whitespaces",
		6: "The length of the line is superior to 120 characters",
		7: "Referring to GLib is not necessary",
	}
)

func validateFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	scanner := bufio.NewScanner(reader)

	num := 0
	for scanner.Scan() {
		line := scanner.Text()
		num++

		warnings := validateLine(line)

		if len(warnings) > 0 {
			for _, warning := range warnings {
				fmt.Printf("%s:%d\t%s\n", filename, num, warningMessages[warning])
			}
		}
	}
}

func validateLine(line string) []int {
	var warnings []int
	if singleBrace.MatchString(line) {
		warnings = append(warnings, 1)
	}

	if endsWithSpaces.MatchString(line) {
		warnings = append(warnings, 2)
	}

	if startsWithSpaces.MatchString(line) && !fourSpacesIndented.MatchString(line) {
		warnings = append(warnings, 3)
	}

	if openingParenthese.MatchString(line) {
		warnings = append(warnings, 4)
	}

	if equalWithSpaces.MatchString(line) {
		warnings = append(warnings, 5)
	}

	if moreThan120Chars.MatchString(line) {
		warnings = append(warnings, 6)
	}

	if glibNotNecessary.MatchString(line) {
		warnings = append(warnings, 7)
	}

	return warnings
}


text:
	#include "dbg_enabled.h"
#else
	#include "dbg_disabled.h"
#endif
#include "dbg_common.h"

// Vertex shaders
char quad_vertex_shader_src_path[] = "vertex_shader_quad.glsl";
char segment_vertex_shader_src_path[] = "vertex_shader_segment.glsl";
char multicolor_segment_vertex_shader_src_path[] = "vertex_shader_segment_multicolor.glsl";

// Geometry shaders
char quad_geometry_shader_src_path[] = "geometry_shader_quad.glsl";
char segment_geometry_shader_src_path[] = "geometry_shader_segment.glsl";

// Fragment shader
char fragment_shader_src_path[] = "fragment_shader.glsl";

// Initialization
struct discrete_world_2D_draw* discrete_world_2D_draw_create(struct discrete_world_2D* world)
{
	struct discrete_world_2D_draw* ret = (struct discrete_world_2D_draw*) malloc(sizeof(struct discrete_world_2D_draw));
	return discrete_world_2D_draw_init(ret, world);
}

#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"DW2D_init : "
struct discrete_world_2D_draw* discrete_world_2D_draw_init(struct discrete_world_2D_draw* drawing_vars, struct discrete_world_2D* world)
{
	if(drawing_vars == NULL)
		return NULL;

	// Initializing variables
	dbg_print_f("Initializing discrete_world_2D_draw variables\n");
	drawing_vars->world = world;
	drawing_vars->model_matrix = NULL;
	drawing_vars->visualization_matrix = NULL;
	drawing_vars->projection_matrix = NULL;

	// Creating programs
	dbg_print_f("Creating OpenGL programs\n");
	dbg_print_f("Creating quad program\n");
	opengl_program_creator_init(&drawing_vars->programs[DW2D_QUADS],
		quad_vertex_shader_src_path,
		NULL,
		NULL,
		quad_geometry_shader_src_path,
		fragment_shader_src_path,
		NULL
	);

	dbg_print_f("Creating segment program\n");
	opengl_program_creator_init(&drawing_vars->programs[DW2D_SEGMENTS],
		segment_vertex_shader_src_path,
		NULL,
		NULL,
		segment_geometry_shader_src_path,
		fragment_shader_src_path,
		NULL
	);

	dbg_print_f("Creating multicolor segment program\n");
	opengl_program_creator_init(&drawing_vars->programs[DW2D_MC_SEGMENTS],
		multicolor_segment_vertex_shader_src_path,
		NULL,
		NULL,
		segment_geometry_shader_src_path,
		fragment_shader_src_path,
		NULL
	);

	// Collecting locations
	discrete_world_2D_draw_collect_locations(drawing_vars);

	// Getting necessary buffers
	dbg_print_f("Getting OpenGL buffers and VAO\n");
	glGenVertexArrays( 1, &(drawing_vars->quad_vao) );
	glGenVertexArrays( 1, &(drawing_vars->segment_vao) );
	glGenVertexArrays( 1, &(drawing_vars->multicolor_segment_vao) );
	glGenBuffers( 1, &(drawing_vars->pos_vbo) );
	glGenBuffers( 1, &(drawing_vars->data_vbo) );
	glGenBuffers( 1, &(drawing_vars->color_scale_texture) );

	// Initializing other program variables
	{
		// Saving current program if necessary
		GLint prev_program;
		glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

		struct opengl_program* progs = drawing_vars->programs;

		// Initializing things
		unsigned int i = 0;
		for(i = 0; i < NB_DW2D_DRAWING_TYPES; i++)
		{
			// Setting current program
			glUseProgram(progs[i].program);

			// Setting VAO
			glBindVertexArray(drawing_vars->quad_vao);

			// Setting color_scale on GL_TEXTURE0
			glEnable( GL_TEXTURE_2D );
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, drawing_vars->color_scale_texture);
			glUniform1i(drawing_vars->locs[i].color_scale, 0);

			// Enabling use of data input
			glEnableVertexAttribArray(drawing_vars->locs[i].data);

			// Unbinding buffers
			glBindVertexArray(0);
		}

		// Restoring program
		glUseProgram(prev_program);
	}

	return drawing_vars;
}
#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"STD : "

// Internal use
void discrete_world_2D_draw_collect_locations(struct discrete_world_2D_draw* drawing_vars)
{
	unsigned int i = 0;

	for(i = 0; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		GLint prog = drawing_vars->programs[i].program;

		// Uniform locations
		drawing_vars->locs[i].matrix[DW2D_MATRX_MODEL] = glGetUniformLocation(prog, "model_matrix");
		drawing_vars->locs[i].matrix[DW2D_MATRX_VISU] = glGetUniformLocation(prog, "visualization_matrix");
		drawing_vars->locs[i].matrix[DW2D_MATRX_PROJ] = glGetUniformLocation(prog, "projection_matrix");
		drawing_vars->locs[i].quad_half_size = glGetUniformLocation(prog, "quad_half_size");
		drawing_vars->locs[i].min = glGetUniformLocation(prog, "min");
		drawing_vars->locs[i].max = glGetUniformLocation(prog, "max");
		drawing_vars->locs[i].vector_min = glGetUniformLocation(prog, "vector_min");
		drawing_vars->locs[i].vector_max = glGetUniformLocation(prog, "vector_max");
		drawing_vars->locs[i].color_scale = glGetUniformLocation(prog, "color_scale");
		drawing_vars->locs[i].color = glGetUniformLocation(prog, "color");

		// Attrib locations
		drawing_vars->locs[i].pos = glGetAttribLocation(prog, "pos");
		drawing_vars->locs[i].data = glGetAttribLocation(prog, "data");
		drawing_vars->locs[i].vector = glGetAttribLocation(prog, "vector");
	}
}

// Configuration
// Unit sizes
void discrete_world_2D_draw_set_quad_size(struct discrete_world_2D_draw* drawing_vars, GLfloat quad_size)
{
	if(drawing_vars == NULL)
		return;

	discrete_world_2D_draw_init_pos_buffer(drawing_vars, quad_size);
	discrete_world_2D_draw_set_programs_uniform1f(drawing_vars, "quad_half_size", quad_size/2);
}

// Internal use
void discrete_world_2D_draw_init_pos_buffer(struct discrete_world_2D_draw* drawing_vars, GLfloat unit_size)
{
	if(drawing_vars == NULL || drawing_vars->world == NULL)
		return;

	// Creating position array
	GLfloat* pos = (GLfloat*) malloc(sizeof(GLfloat)*2*drawing_vars->world->world.nb_units);
	DIM_SIZE_TYPE x, y;
	for(y = 0; y < drawing_vars->world->h; y++)
		for(x = 0; x < drawing_vars->world->w; x++)
		{
			pos[(x + y*drawing_vars->world->w)*2 + 0] = (x - (float)(drawing_vars->world->w)/2 + 0.5)*unit_size;
			pos[(x + y*drawing_vars->world->w)*2 + 1] = (y - (float)(drawing_vars->world->h)/2 + 0.5)*unit_size;
		}

	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

	struct opengl_program* progs = drawing_vars->programs;

	// Filling VBO
	glUseProgram(progs[DW2D_QUADS].program);
	glBindBuffer(GL_ARRAY_BUFFER, drawing_vars->pos_vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*2*drawing_vars->world->world.nb_units, pos, GL_STATIC_DRAW);

	// Setting VAOs
	unsigned int i = 0;
	for(i = 0; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		// Setting current program
		glUseProgram(progs[i].program);

		// Setting VAO
		glBindVertexArray(drawing_vars->quad_vao);
		glBindBuffer(GL_ARRAY_BUFFER, drawing_vars->pos_vbo);
		glVertexAttribPointer(drawing_vars->locs[i].pos, 2,  GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(drawing_vars->locs[i].pos);

		// Unbinding buffers
		glBindVertexArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}

	// Restoring program
	glUseProgram(prev_program);

	// Freeing vars
	free(pos);
}

// Variable scale
void discrete_world_2D_draw_set_color_scale_limits(struct discrete_world_2D_draw* drawing_vars,
	GLfloat min, GLfloat max)
{
	if(drawing_vars == NULL)
		return;

	discrete_world_2D_draw_set_programs_uniform1f(drawing_vars, "min", min);
	discrete_world_2D_draw_set_programs_uniform1f(drawing_vars, "max", max);
}

void discrete_world_2D_draw_set_vector_scale_limits(struct discrete_world_2D_draw* drawing_vars,
	GLfloat min[2], GLfloat max[2])
{
	if(drawing_vars == NULL)
		return;

	discrete_world_2D_draw_set_programs_uniform2fv(drawing_vars, "vector_min", min);
	discrete_world_2D_draw_set_programs_uniform2fv(drawing_vars, "vector_max", max);
}

// Matrix
void discrete_world_2D_draw_set_matrices(struct discrete_world_2D_draw* drawing_vars,
	matrix_stack* model_matrix, matrix_stack* visualization_matrix, matrix_stack* projection_matrix)
{
	unsigned int i = 0;
	if(drawing_vars == NULL)
		return;

	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

	struct opengl_program* progs = drawing_vars->programs;

	// Saving the matrix in the drawing vars
	if(model_matrix != NULL)
		drawing_vars->model_matrix = model_matrix;
	if(visualization_matrix != NULL)
		drawing_vars->visualization_matrix = visualization_matrix;
	if(projection_matrix != NULL)
		drawing_vars->projection_matrix = projection_matrix;

	// Pushing matrix into the programs
	for(i = 0 ; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		glUseProgram(progs[i].program);
		glUniformMatrix4fv(drawing_vars->locs[i].matrix[DW2D_MATRX_MODEL], 1, GL_FALSE, drawing_vars->model_matrix->top);
		glUniformMatrix4fv(drawing_vars->locs[i].matrix[DW2D_MATRX_VISU], 1, GL_FALSE, drawing_vars->visualization_matrix->top);
		glUniformMatrix4fv(drawing_vars->locs[i].matrix[DW2D_MATRX_PROJ], 1, GL_FALSE, drawing_vars->projection_matrix->top);
	}

	// Restoring program
	glUseProgram(prev_program);
}

// Colors
void discrete_world_2D_draw_set_color_scale_from_rgba_uchar_array(struct discrete_world_2D_draw* drawing_vars,
	unsigned char rgba[], unsigned int nb_colors)
{
	glBindTexture( GL_TEXTURE_2D, drawing_vars->color_scale_texture );
   //glTexImage2D( GL_TEXTURE_2D, 0, 3, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );
	glTexImage2D( GL_TEXTURE_2D, 0, 3, nb_colors	, 1	, 		0, GL_RGBA, GL_UNSIGNED_BYTE, rgba );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );// au lieu de GL_NEAREST_MIPMAP_LINEAR
	glBindTexture( GL_TEXTURE_2D, 0 );
}

void discrete_world_2D_draw_set_color_scale_from_rgba_float_array(struct discrete_world_2D_draw* drawing_vars,
	float rgba[], unsigned int nb_colors)
{
	glBindTexture( GL_TEXTURE_2D, drawing_vars->color_scale_texture );
   //glTexImage2D( GL_TEXTURE_2D, 0, 3, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );
	glTexImage2D( GL_TEXTURE_2D, 0, 3, nb_colors	, 1	, 		0, GL_RGBA, GL_FLOAT, rgba );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );// au lieu de GL_NEAREST_MIPMAP_LINEAR
	glBindTexture( GL_TEXTURE_2D, 0 );
}

// Drawing functions
// 1D values
void discrete_world_2D_draw_float(struct discrete_world_2D_draw* drawing_vars, unsigned int param_index, unsigned int var_offset)
{
	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

	GLint prog = drawing_vars->programs[DW2D_QUADS].program;
	glUseProgram(prog);

	// Setting opengl env
	glEnable( GL_TEXTURE_2D );
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, drawing_vars->color_scale_texture);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

	// Refreshing matrices
	glUniformMatrix4fv(drawing_vars->locs[DW2D_QUADS].matrix[DW2D_MATRX_MODEL], 1, GL_FALSE, drawing_vars->model_matrix->top);
	glUniformMatrix4fv(drawing_vars->locs[DW2D_QUADS].matrix[DW2D_MATRX_VISU], 1, GL_FALSE, drawing_vars->visualization_matrix->top);
	glUniformMatrix4fv(drawing_vars->locs[DW2D_QUADS].matrix[DW2D_MATRX_PROJ], 1, GL_FALSE, drawing_vars->projection_matrix->top);

	// Drawing world
	glBindVertexArray(drawing_vars->quad_vao);

	glBindBuffer(GL_ARRAY_BUFFER, drawing_vars->data_vbo);
	glBufferData(GL_ARRAY_BUFFER,
		sizeof(GLfloat)*drawing_vars->world->world.nb_units,
		drawing_vars->world->world.previous_worlds[param_index*drawing_vars->world->world.nb_previous_worlds + 0],
		GL_STREAM_DRAW);
	glVertexAttribPointer(drawing_vars->locs[DW2D_QUADS].data,
		1, GL_FLOAT, GL_FALSE, drawing_vars->world->world.parameter_sizes[param_index], (GLvoid*)(unsigned long)var_offset);

	glEnableVertexAttribArray(drawing_vars->locs[DW2D_QUADS].data);

	glDrawArrays(GL_POINTS, 0, drawing_vars->world->world.nb_units);

	// Clearing bindings
	glBindVertexArray(0);

	// Restoring program
	glUseProgram(prev_program);
}

// 2D values
void discrete_world_2D_draw_vector_float(struct discrete_world_2D_draw* drawing_vars,
	unsigned int vector_offset);

// Tools
void discrete_world_2D_draw_set_program_uniform1f(GLint program, char uniform_name[], GLfloat f)
{
	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);
	glUseProgram(program);

	// Setting program uniform
	glUniform1f(glGetUniformLocation(program, uniform_name), f);

	// Restoring program
	glUseProgram(prev_program);
}

void discrete_world_2D_draw_set_program_uniform4fv(GLint program, char uniform_name[], GLfloat f[])
{
	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);
	glUseProgram(program);

	// Setting program uniform
	glUniform4fv(glGetUniformLocation(program, uniform_name), 1, f);

	// Restoring program
	glUseProgram(prev_program);
}

void discrete_world_2D_draw_set_program_uniform2fv(GLint program, char uniform_name[], GLfloat f[])
{
	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);
	glUseProgram(program);

	// Setting program uniform
	glUniform2fv(glGetUniformLocation(program, uniform_name), 1, f);

	// Restoring program
	glUseProgram(prev_program);
}

void discrete_world_2D_draw_set_programs_uniform1f(struct discrete_world_2D_draw* drawing_vars, char uniform_name[], GLfloat f)
{
	unsigned int i = 0;

	if(drawing_vars == NULL)
		return;

	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

	struct opengl_program* progs = drawing_vars->programs;

	// Pushing matrix into the programs
	for(i = 0 ; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		glUseProgram(progs[i].program);
		glUniform1f(glGetUniformLocation(progs[i].program, uniform_name), f);
	}

	// Restoring program
	glUseProgram(prev_program);
}

void discrete_world_2D_draw_set_programs_uniform2fv(struct discrete_world_2D_draw* drawing_vars, char uniform_name[], GLfloat f[])
{
	unsigned int i = 0;
	if(drawing_vars == NULL)
		return;

	// Saving current program if necessary
	GLint prev_program;
	glGetIntegerv(GL_CURRENT_PROGRAM, &prev_program);

	struct opengl_program* progs = drawing_vars->programs;

	// Pushing matrix into the programs
	for(i = 0 ; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		glUseProgram(progs[i].program);
		glUniform2fv(glGetUniformLocation(progs[i].program, uniform_name), 1, f);
	}

	// Restoring program
	glUseProgram(prev_program);
}

// Debug
#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"DW2D_print : "
void discrete_world_2D_draw_print(struct discrete_world_2D_draw* drawing_vars, int print_locs)
{
	char buf[100];
	unsigned int i = 0;

	err_print_f1(buf, "World 2D draw print (%p) :\n", (void*)(drawing_vars));

	// OpenGL program variables
	for(i = 0; i < NB_DW2D_DRAWING_TYPES; i++)
	{
		err_print_f2(buf, "\tProgram[%u] : %d\n", i, drawing_vars->programs[i].program);
		if(print_locs)	discrete_world_2D_draw_prog_locs_print(&drawing_vars->locs[i]);
	}

	// VAO (drawing code shortener)
	err_print_f1(buf, "\tQuad VAO : %d\n", drawing_vars->quad_vao);
	err_print_f1(buf, "\tSegment VAO : %d\n", drawing_vars->segment_vao);
	err_print_f1(buf, "\tMulticolor VAO : %d\n", drawing_vars->multicolor_segment_vao);

	// VBO (buffers)
	err_print_f1(buf, "\tPos VBO : %d\n", drawing_vars->pos_vbo);
	err_print_f1(buf, "\tData VBO : %d\n", drawing_vars->data_vbo);
	err_print_f1(buf, "\tColor scale texture : %d\n", drawing_vars->color_scale_texture);

	// Context variables
	err_print_f1(buf, "\tWorld : %p\n", (void*)(drawing_vars->world));
	err_print_f1(buf, "\tModel matrix : %p\n", (void*)(drawing_vars->model_matrix));
	err_print_f1(buf, "\tVisualization matrix : %p\n", (void*)(drawing_vars->visualization_matrix));
	err_print_f1(buf, "\tProjection matrix : %p\n", (void*)(drawing_vars->projection_matrix));
}
#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"STD : "

#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"DW2D_loc_print : "
void discrete_world_2D_draw_prog_locs_print(struct discrete_world_2D_draw_prog_locs* locs)
{
	char buf[100];
	unsigned int i = 0;
	err_print_f1(buf, "World 2D draw program locations print (%p) :\n", (void*)(locs));

	// Uniform locations
	for(i = 0; i < NB_DW2D_MATRICES; i++)
		err_print_f2(buf, "\tMatrix[%d] : %d\n", i, locs->matrix[i]);
	err_print_f1(buf, "\tQuad half size : %d\n", locs->quad_half_size);
	err_print_f1(buf, "\tMin : %d\n", locs->min);
	err_print_f1(buf, "\tMax : %d\n", locs->max);
	err_print_f1(buf, "\tVector min : %d\n", locs->vector_min);
	err_print_f1(buf, "\tVector max : %d\n", locs->vector_max);
	err_print_f1(buf, "\tColor scale : %d\n", locs->color_scale);
	err_print_f1(buf, "\tColor : %d\n", locs->color);

	// Attrib locations
	err_print_f1(buf, "\tPos : %d\n", locs->pos);
	err_print_f1(buf, "\tData : %d\n", locs->data);
	err_print_f1(buf, "\tVector : %d\n", locs->vector);
}
#undef dbg_print_formatted_header
#define dbg_print_formatted_header			"STD : "

// Freeing
void discrete_world_2D_draw_free(struct discrete_world_2D_draw* drawing_vars)
{
	if(drawing_vars == NULL)
		return;

	// Cleaning everything
	discrete_world_2D_draw_destroy(drawing_vars);

	// Freeing structure
	free(drawing_vars);
}
void discrete_world_2D_draw_destroy(struct discrete_world_2D_draw* drawing_vars)
{
	unsigned int i = 0;
	if(drawing_vars == NULL)
		return;

	// Cleaning buffers
	glDeleteVertexArrays( 1, &(drawing_vars->quad_vao) );
	glDeleteVertexArrays( 1, &(drawing_vars->segment_vao) );
	glDeleteVertexArrays( 1, &(drawing_vars->multicolor_segment_vao) );
	glDeleteBuffers( 1, &(drawing_vars->pos_vbo) );
	glDeleteBuffers( 1, &(drawing_vars->data_vbo) );
	glDeleteBuffers( 1, &(drawing_vars->color_scale_texture) );

	// Cleaning programs
	for(i = 0 ; i < NB_DW2D_DRAWING_TYPES; i++)
		opengl_program_destroy(&(drawing_vars->programs[i]));
}


text:
package tests_test

import (
	"flag"
	"strings"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	tests "kubevirt.io/kubevirt-ansible/tests/framework"
	ktests "kubevirt.io/kubevirt/tests"
)

const (
	invalidURL            = "https://noneexist.com"
	dataVolumeName        = "golden-data-volume"
	dstDataVolumeFilePath = "/tmp/test-data-volume.json"
	rawDataVolumeFilePath = "tests/manifests/golden-data-volume.yml"
	apiVersion            = "cdi.kubevirt.io/v1alpha1"
	timeout               = 1 * 60 * time.Second
)

var _ = Describe("Importing image using CDI with invalid URL", func() {

	flag.Parse()

	ktests.BeforeAll(func() {
		ktests.BeforeTestCleanup()
		By("Create a Data Volume with invalid image URL")
		tests.ProcessTemplateWithParameters(rawDataVolumeFilePath, dstDataVolumeFilePath, "DV_NAME="+dataVolumeName, "EP_URL="+invalidURL, "API_VERSION="+apiVersion)
		tests.CreateResourceWithFilePathTestNamespace(dstDataVolumeFilePath)
	})

	Context("Data Volume with invalid image url", func() {
		It("Importer pod should be removed once data volume is deleted", func() {
			By("Importer pod should be in CrashLoopBackOff status")
			tests.WaitUntilResourceReadyByLabelTestNamespace("pod", tests.CDI_LABEL_SELECTOR, "", "CrashLoopBackOff")

			By("Data Volume deleted successfully")
			importer_pod := GetImporterPodName(dataVolumeName)
			Expect(importer_pod).ToNot(BeEmpty())
			tests.RemoveDataVolume(dataVolumeName, tests.NamespaceTestDefault)

			By("Importer pod should be removed")
			Eventually(func() string {
				importer_pod := GetImporterPodName(dataVolumeName)
				return importer_pod
			}, timeout, 1*time.Second).Should(BeEmpty())
		})
	})
})

func GetImporterPodName(dataVolumeName string) string {
	var importer_pod string
	args := []string{"get", "pods", "-o=custom-columns=NAME:.metadata.name"}
	output, _, err := ktests.RunCommand("oc", args...)
	Expect(err).ToNot(HaveOccurred())
	Expect(output).ToNot(BeEmpty())
	pods := strings.Split(output, "\n")
	for _, pod := range pods {
		if strings.Contains(pod, dataVolumeName) && strings.Contains(pod, "importer") {
			importer_pod = pod
			break
		}
	}
	return importer_pod
}


text:
<?php
/* @var $this ZoneController */
/* @var $model Zone */

$this->breadcrumbs=array(
	Yii::t('database','Zones')=>array('index'),
	$model->id_zone=>array('view','id'=>$model->id_zone),
	Yii::t('actions','Update'),
);

$this->menu=array(
	array('label'=>Yii::t('actions','List')." ". Yii::t('database','Zone'), 'url'=>array('index')),
	array('label'=>Yii::t('actions','Create')." ". Yii::t('database','Zone'), 'url'=>array('create')),
	array('label'=>Yii::t('actions','View')." ". Yii::t('database','Zone'), 'url'=>array('view', 'id'=>$model->id_zone)),
	array('label'=>Yii::t('actions','Manage')." ". Yii::t('database','Zone'), 'url'=>array('admin')),
);
?>

<h1> <?php echo Yii::t('actions','Update')?> <?php echo Yii::t('database','Zone')?> <?php echo $model->id_zone; ?></h1>

<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
module GemPopularis

  class GemParser

    # Public: Given a line from our gem listing, parse the details from that line for use within
    # our application.
    #
    # raw_string - A single line String returned from the `gem` tool
    #
    # Returns an instance of GemParser.
    def initialize(raw_string)
      @raw_string = raw_string
    end

    # Public: Returns the name of the gem.
    #
    # Returns String name of gem or nil.
    def name
      @name ||= match_data[1]
    end

    # Public: Returns the version of the gem.
    #
    # Returns String version of gem or nil.
    def version
      @version ||= match_data[2]
    end

    # Public: Returns true/false based on if we know right away that this isn't a valid
    # gem.
    #
    # Returns true or false.
    def valid?
      !["", "*** REMOTE GEMS ***"].include?(@raw_string) && name && version
    end

    private

    # Internal: Use a regular expression to match multiple pieces of information from the given
    # gem string.
    #
    # Returns instance of MatchData.
    def match_data
      @raw_string.match(/^(.*)\s\((.*)\)$/)
    end

  end

end


text:
import constants
import pycrawl

def fetch():
  pc = pycrawl.PyCrawl(constants.USER_AGENT)
  error = pc.download(constants.PUBLIC_SUFFIX_URL, constants.DATA_PATH_PUBLIC_SUFFIX)
  if error is not None:
    print "====\nERROR:\n", error

if __name__=="__main__":
  fetch()


text:
package com.carrotsearch.randomizedtesting;

import org.junit.*;
import org.junit.runner.*;

/**
 * Test {@link Result}'s run count for ignored tests.
 */
public class TestIgnoredRunCount extends WithNestedTestClass {
  public static class Nested {
    @Test @Ignore
    public void ignored() {
    }
  }

  @Test
  public void checkIgnoredCount() throws Exception {
    assertSameExecution(Nested.class);
  }

  private void assertSameExecution(Class<?> clazz) throws Exception {
    Result result1 = JUnitCore.runClasses(clazz);
    Result result2 = new JUnitCore().run(Request.runner(new RandomizedRunner(clazz)));

    Assert.assertEquals(result1.getRunCount(), result2.getRunCount());
    Assert.assertEquals(result1.getFailureCount(), result2.getFailureCount());
    Assert.assertEquals(result1.getIgnoreCount(), result2.getIgnoreCount());
  }
}


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

@Component({
  moduleId: module.id,
  selector: 'framework',
  templateUrl: `framework.component.html`,
  styles: [`.item { margin-top: 10px; }`]
})
export class FrameworkComponent {

}


text:
<?php

namespace GeoMetadata;

/**
 * Main class for GeoMetadata.
 */
class GeoMetadata {

	protected $serviceUrl;
	protected $metadataUrl;
	protected $data;
	protected $service;
	protected $model;

	/**
	 * Constructor for the GeoMetadata class.
	 *
	 * Note: Construction is only possible with static methods withUrl() or withData() from outside of this class.
	 */
	protected function __construct() {
		// Construction only with static methods withUrl() or withData().
	}

	/**
	 * Returns a new GeoMetadata object based on an URL input as metadata source.
	 *
	 * @param string $url URL of the dataset
	 * @param string $code Code of the parser to be used for parsing.
	 * @return \GeoMetadata\GeoMetadata|null
	 */
	public static function withUrl($url, $code) {
		$instance = new self();
		$instance->service = GmRegistry::getService($code);
		if ($instance->service != null) {
			$instance->serviceUrl = $instance->service->getServiceUrl($url);
			$instance->metadataUrl = $instance->service->getMetadataUrl($url);

			$net = new GmNet();
			$instance->data = $net->get(
				$instance->metadataUrl,
				$instance->service->getMetadataRequestMethod(),
				$instance->service->getMetadataRequestData()
			);
			if ($instance->data != null && $instance->service->verify($instance->data)) {
				return $instance;
			}
		}
		return null;
	}
	/**
	 * Returns a new GeoMetadata object based on a string as metadata source.
	 *
	 * @param string $data Data to be parsed
	 * @return \GeoMetadata\GeoMetadata|null
	 */
	public static function withData($data) {
		$instance = new self();
		$instance->data = $data;
		if ($instance->detect()) {
			return $instance;
		}
		return null;
	}

	/**
	 * Returns the base URL of the service.
	 *
	 * @return string
	 */
	public function getURL() {
		return $this->serviceUrl;
	}

	/**
	 * Returns the base URL where the metadata of the service can be found.
	 *
	 * @return string
	 */
	public function getMetadataURL() {
		return $this->metadataUrl;
	}

	/**
	 * Returns the string containing the data to be parsed.
	 *
	 * @return string
	 */
	public function getData() {
		return $this->data;
	}

	/**
	 * Returns the service/parser that will be used.
	 *
	 * @return \GeoMetadata\Model\Service\Parser
	 */
	public function getService() {
		return $this->service;
	}

	/**
	 * Sets the model that should be used to store the data.
	 *
	 * @param \GeoMetadata\Model\Metadata $model
	 */
	public function setModel(\GeoMetadata\Model\Metadata $model = null) {
		$this->model = $model;
	}

	/**
	 * Creates a new model and returns it.
	 *
	 * @return \GeoMetadata\Model\Generic\GmMetadata
	 */
	protected function createModel() {
		if ($this->model == null) {
			return new \GeoMetadata\Model\Generic\GmMetadata();
		}
		else {
			return $this->model->createObject();
		}
	}

	/**
	 * Tries to detects the dataformat that is given by the data.
	 *
	 * @return boolean true on success, false on failure
	 */
	protected function detect() {
		if ($this->service == null) {
			$services = GmRegistry::getServices();
			foreach ($services as $service) {
				if ($service->verify($this->data)) {
					$this->service = $service;
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Parses the data and returns a filled instance of the given model.
	 *
	 * @return \GeoMetadata\Model\Generic\GmMetadata
	 */
	public function parse() {
		$model = $this->createModel();
		$model->setUrl($this->serviceUrl);
		$model->setServiceCode($this->service->getCode());
		if ($this->service->parse($this->data, $model)) {
			return $model;
		}
		else {
			return null;
		}
	}

}


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

<title>Uses of Interface net.sf.jasperreports.components.map.Item (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sf.jasperreports.components.map.Item

Packages that use Item

Package
Description

net.sf.jasperreports.components.map

Contains classes for the built-in Google Map component.

net.sf.jasperreports.components.map.fill

Contains fill time implementations for Google Map component related interfaces.

Uses of Item in net.sf.jasperreports.components.map

Classes in net.sf.jasperreports.components.map that implement Item

Modifier and Type
Class and Description

class
StandardItem

Methods in net.sf.jasperreports.components.map that return Item

Modifier and Type
Method and Description

Item
StandardItemData.removeItem(Item item)

Methods in net.sf.jasperreports.components.map that return types with arguments of type Item

Modifier and Type
Method and Description

java.util.List<Item>
StandardItemData.getItems()

java.util.List<Item>
ItemData.getItems()

Returns a list of Item
 objects.

Methods in net.sf.jasperreports.components.map with parameters of type Item

Modifier and Type
Method and Description

void
StandardItemData.addItem(int index,
       Item item)

void
StandardItemData.addItem(Item item)

Item
StandardItemData.removeItem(Item item)

protected void
MapCompiler.verifyItem(JRVerifier verifier,
          Item item,
          java.lang.String itemName,
          java.lang.String[] requiredNames,
          java.util.Map<java.lang.String,java.lang.String> alternativeNamesMap)

Verifies if required properties or their alternatives are present in the item properties list.

protected void
MapCompiler.verifyMarker(JRVerifier verifier,
            Item item)

Uses of Item in net.sf.jasperreports.components.map.fill

Classes in net.sf.jasperreports.components.map.fill that implement Item

Modifier and Type
Class and Description

class
FillItem

class
FillPlaceItem

class
FillStyleItem

Fields in net.sf.jasperreports.components.map.fill declared as Item

Modifier and Type
Field and Description

protected Item
FillItem.item

Methods in net.sf.jasperreports.components.map.fill with parameters of type Item

Modifier and Type
Method and Description

FillItem
FillStyleItemData.getFillItem(Item item,
           JRFillObjectFactory factory)

FillItem
FillPlaceItemData.getFillItem(Item item,
           JRFillObjectFactory factory)

abstract FillItem
FillItemData.getFillItem(Item item,
           JRFillObjectFactory factory)

Constructors in net.sf.jasperreports.components.map.fill with parameters of type Item

Constructor and Description

FillItem(Item item,
        JRFillObjectFactory factory)

FillPlaceItem(Item item,
             JRFillObjectFactory factory)

FillStyleItem(Item item,
             JRFillObjectFactory factory)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
Testing function parameter passing with a return value
--FILE--
<?php
function test ($b) {
	$b++;
	return($b);
}
$a = test(1);
echo $a;
?>
--EXPECT--
2


text:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/sendfile.h>
#include <stdlib.h>
#include <limits.h>
#include <ev.h>

#define PORT 8080
#define BUFLEN 512
#define DOCROOT "/var/www"
enum method {UNKNOWN, GET, PUT};

unsigned long g_num_clients = 0;

void stop_and_clean_up_socket_watcher(struct ev_loop *loop, struct ev_io *watcher);
void accept_callback(struct ev_loop *loop, struct ev_io *watcher, int events);
void read_callback(struct ev_loop *loop, struct ev_io *watcher, int events);
void parse_request(const char * buffer, int fd);
void send_page(char * urlpath, int fd);
void send_404(int fd);

int main(int argc, const char* argv[])
{
	int fd6;
	struct sockaddr_in6 addr6;
	struct ev_io accept_watcher;
	struct ev_loop *main_loop = ev_default_loop(0);

	/* Prep the address by zeroing it out and filling in the sockaddr_in struct */

	bzero(&addr6, sizeof(addr6));
	addr6.sin6_family = AF_INET6;
	addr6.sin6_port = htons(PORT);
	addr6.sin6_addr = in6addr_any;

	/* Create socket and assign it to fd6 */

	if( (fd6 = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP)) < 0 ) {
		perror("Socket error");
		return -1;
	}

	/* Bind the socket to the address addr */

	if (bind(fd6, (const struct sockaddr *) &addr6, sizeof(addr6)) != 0) {
		perror("Bind error");
		return -1;
	}

	/* Listen on socket fd6 */

	if (listen(fd6, 10) < 0) {
		perror("Listen error");
		return -1;
	}

	/* Init and start the main event loop */

	ev_io_init(&accept_watcher, accept_callback, fd6, EV_READ);
	ev_io_start(main_loop, &accept_watcher);
	ev_run(main_loop, 0);

	return 0;
}

void stop_and_clean_up_socket_watcher(struct ev_loop *loop, struct ev_io *watcher)
{
	shutdown(watcher->fd, SHUT_RDWR);
	ev_io_stop(loop,watcher);
	free(watcher);
}

void accept_callback(struct ev_loop *loop, struct ev_io *watcher, int events)
{
	struct sockaddr_in6 client_addr6;
	socklen_t client_len;
	struct ev_io *client_watcher;
	int client_fd;

	/* Check early on if the event is invalid */

	if(EV_ERROR & events) {
		perror("Invalid event");
		return;
	}

	client_watcher = (struct ev_io*) malloc (sizeof(struct ev_io));
	if(client_watcher == NULL) {
		perror("Could not allocate memory for client watcher.");
		return;
	}

	client_len = sizeof(client_addr6);

	client_fd = accept(watcher->fd, (struct sockaddr *)&client_addr6, &client_len);

	if (client_fd < 0) {
		perror("Accept error");
		return;
	}

	g_num_clients++;
	printf("One client connected. Total now %ld clients.\n", g_num_clients);

	/* Start watcher for this socket */
	ev_io_init(client_watcher, read_callback, client_fd, EV_READ);
	ev_io_start(loop, client_watcher);
}

/* Read client message */
void read_callback(struct ev_loop *loop, struct ev_io *watcher, int events)
{
	char buffer[BUFLEN];
	ssize_t read_bytes;

	/* Check early on if the event is invalid */

	if(EV_ERROR & events) {
		perror("Invalid event");
		return;
	}

	read_bytes = recv(watcher->fd, buffer, BUFLEN, 0);

	if(read_bytes < 0) {
		perror("Read error");

		return;
	} else if(read_bytes == 0) { /* Socket shutdown from the other end */
		if(g_num_clients > 0) {
			g_num_clients--;
			printf("One client disconnected. Total now %ld clients.\n", g_num_clients);
		} else {
			fprintf(stderr, "Number of clients dropped below zero. This should not happen.\n");
		}

		stop_and_clean_up_socket_watcher(loop, watcher);

		return;
	} else {
		parse_request(buffer, watcher->fd);
	}
}

void parse_request(const char * buffer, int fd)
{
	const char delimiters[] = " ";
	char *token, *bufcopy;
	char urlpath[PATH_MAX];
	enum method parsed_method = UNKNOWN;

	bufcopy = strdupa(buffer); /* Make working copy.  */

	token = strtok (bufcopy, delimiters);

	printf("%s\n", token);
	if(strncmp(token, "GET", 3)==0) {
        	parsed_method = GET;
	} else {
		return;
	}

	token = strtok (NULL, delimiters);
	strncpy(urlpath, token, PATH_MAX);

	token = strtok (NULL, delimiters);
	printf("%s\n", token); /* The HTTP version, only 1.0 right now */

	send_page(urlpath, fd);

	return;
}

void send_page(char * urlpath, int fd)
{
	struct stat filestat;
	char filename_recv[PATH_MAX];
	char filename[PATH_MAX];
	off_t offset = 0;
	int urlfile;

	if(urlpath[(strlen(urlpath)-1)]=='/') {
		snprintf(filename_recv, PATH_MAX, "%s/index.html", DOCROOT);
	} else {
		snprintf(filename_recv, PATH_MAX, "%s%s", DOCROOT, urlpath);
	}

	if(realpath(filename_recv, filename)==NULL) {
		send_404(fd);
		return;
	}

	if(strncmp(filename, DOCROOT, strlen(DOCROOT))!=0) {
		send_404(fd);
		printf("Access violation: Attempted %s\n", filename);
		return;
	}

	printf("Retrieving %s...\n", filename);

	urlfile = open(filename, O_RDONLY);
	if (urlfile < 0) {
	    send_404(fd);
	    return;
	}

	fstat(urlfile, &filestat);

	if(sendfile(fd, urlfile, &offset, filestat.st_size) < 0) {
		perror("sendfile error");
		exit(1);
	}

	return;
}

void send_404(int fd)
{
}


text:
<?php

namespace Pribumi\BeyondAuth\Exceptions;

use Exception;

class UserActivationDoesNotExist extends Exception
{
}


text:
//  (C) Copyright 2009-2011 Frederic Bron.
//
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.lslboost.org/LICENSE_1_0.txt).
//
//  See http://www.lslboost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_HAS_POST_INCREMENT_HPP_INCLUDED
#define BOOST_TT_HAS_POST_INCREMENT_HPP_INCLUDED

#define BOOST_TT_TRAIT_NAME has_post_increment
#define BOOST_TT_TRAIT_OP ++
#define BOOST_TT_FORBIDDEN_IF\
   ::lslboost::type_traits::ice_or<\
      /* bool */\
      ::lslboost::is_same< bool, Lhs_nocv >::value,\
      /* void* */\
      ::lslboost::type_traits::ice_and<\
         ::lslboost::is_pointer< Lhs_noref >::value,\
         ::lslboost::is_void< Lhs_noptr >::value\
      >::value,\
      /* (fundamental or pointer) and const */\
      ::lslboost::type_traits::ice_and<\
         ::lslboost::type_traits::ice_or<\
            ::lslboost::is_fundamental< Lhs_nocv >::value,\
            ::lslboost::is_pointer< Lhs_noref >::value\
         >::value,\
         ::lslboost::is_const< Lhs_noref >::value\
      >::value\
   >::value

#include <lslboost/type_traits/detail/has_postfix_operator.hpp>

#undef BOOST_TT_TRAIT_NAME
#undef BOOST_TT_TRAIT_OP
#undef BOOST_TT_FORBIDDEN_IF

#endif


text:
'use strict';

// MODULES //

var floor = require( '@stdlib/math/base/special/floor' );

// MAIN //

/**
* Computes the median value of a sorted double-precision floating-point strided array.
*
* @param {PositiveInteger} N - number of indexed elements
* @param {Float64Array} x - sorted input array
* @param {integer} stride - stride length
* @returns {number} median value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0 ] );
*
* var v = dmediansorted( x.length, x, 1 );
* // returns 2.0
*/
function dmediansorted( N, x, stride ) {
	var offset;
	var n;
	var m;

	if ( N <= 0 ) {
		return NaN;
	}
	if ( stride < 0 ) {
		offset = (1-N) * stride;
	} else {
		offset = 0;
	}
	n = N / 2;
	m = floor( n );
	if ( n === m ) {
		// Even number of elements...
		return ( x[ offset+(m*stride) ] + x[ offset+((m-1)*stride) ] ) / 2.0;
	}
	// Odd number of elements...
	return x[ offset+(m*stride) ];
}

// EXPORTS //

module.exports = dmediansorted;


text:
/**
 * Module dependencies.
 */

var express = require('./')
  , app = express()

app.get('/:foo?/:bar?', function(req, res){
  console.log(req.params);
});

app.post('/:foo?/:bar?', function(req, res){
  console.log(req.params);
});

app.listen(5555);
console.log('listening on 5555');


text:
package com.foo.servlets;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

/**
 *
 * @author Charlie
 */
@WebServlet(name = "selectBeerAction",
        urlPatterns = {"/actions/selectBeer", "/actions/selectBeer.xml"},
        initParams = {@WebInitParam(name = "darkBeers", value = "Indio,Guinness,Dark Rito"),
                        @WebInitParam(name = "lagerBeers", value = "XX,Juay Lager")})
public class BeerServlet extends HttpServlet {

}


text:
package com.flowci.core.trigger.dao;

import com.flowci.core.trigger.domain.TriggerDelivery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

public interface CustomizedTriggerDeliveryDao {

    void addDelivery(String triggerId, TriggerDelivery.Item item, int max);

    Page<TriggerDelivery.Item> listDeliveries(String triggerId, PageRequest pageRequest);
}


text:
<!DOCTYPE html>

<link rel="import" href="/components/app-route/app-location.html">
<link rel="import" href="/components/iron-form/iron-form.html">
<link rel="import" href="/components/paper-button/paper-button.html">
<link rel="import" href="/components/paper-dialog/paper-dialog.html">
<link rel="import" href="/components/paper-fab/paper-fab.html">
<link rel="import" href="/components/paper-tooltip/paper-tooltip.html">

<link rel="import" href="/elements/base-style.html">

<dom-module id="rerun-job-fab">
  <template>

    <app-location route="{{route}}"></app-location>
    <paper-fab mini id="job-fab" icon="refresh" on-tap="openDialog"></paper-fab>
    <paper-tooltip for="job-fab" position="left">Re-run this job</paper-tooltip>
    <paper-dialog id="job_dialog" entry-animation="fade-in-animation" exit-animation="fade-out-animation">

Re-run this job?

        <template is="dom-if" if="[[error]]">

[[error]]
        </template>
        <iron-form id="job_form" headers="[[authHeaders]]" on-iron-form-error="handleError" on-iron-form-response="handleResponse">
          <form action="/api/new" method="POST">
            <template is="dom-repeat" items="[[getArguments(job)]]">
              <input type="hidden" name="[[item.key]]" value="[[item.value]]">
            </template>

          </form>
        </iron-form>

        <paper-button on-tap="submit">Start</paper-button>

    </paper-dialog>
  </template>

</dom-module>


text:
var testosl = require('./testosl');

module.exports = function (app) {

	app.get ('/sl/devices', testosl.devices);
	app.get ('/sl/state', testosl.state);
	app.post ('/sl/begin', testosl.begin);
	app.post ('/sl/next', testosl.next);
};


text:
package org.jboss.pnc.messaging.spi;

import lombok.Getter;
import org.jboss.pnc.common.json.JsonOutputConverterMapper;

import java.util.List;

/**
 * @author jakubvanko
 */
@Getter
public class AnalysisStatusMessage implements Message {

    private final String attribute;
    private final String milestoneId;
    private final String status;
    private final List<String> sourcesLinks;

    public AnalysisStatusMessage(String attribute, String milestoneId, String status, List<String> sourcesLinks) {
        this.attribute = attribute;
        this.milestoneId = milestoneId;
        this.status = status;
        this.sourcesLinks = sourcesLinks;
    }

    @Override
    public String toJson() {
        return JsonOutputConverterMapper.apply(this);
    }
}


text:
var codingEditor = null;
// Where Blockly is converted to Python
var readOnlyCodingEditor = null;
// Range for ace editor line highlighting
var Range = ace.require('ace/range').Range;

window.addEventListener('load', function() {
    // Load read only ace editor
    readOnlyCodingEditor = ace.edit('readOnlyBlocklyCode');
    // Set the style
    readOnlyCodingEditor.setTheme('ace/theme/textmate');
    readOnlyCodingEditor.session.setMode('ace/mode/python');
    readOnlyCodingEditor.session.setTabSize(2);
    // Make as read only
    readOnlyCodingEditor.setReadOnly(true);
    // Disable scrolling warning
    readOnlyCodingEditor.$blockScrolling = Infinity;

    // Load ace editor
    codingEditor = ace.edit('blocklyCode');
    // Set the style
    codingEditor.setTheme('ace/theme/textmate');
    codingEditor.session.setMode('ace/mode/python');
    codingEditor.session.setTabSize(2);
    // Disable scrolling warning
    codingEditor.$blockScrolling = Infinity;
    // Enable autocomplete
    ace.require('ace/ext/language_tools');
    codingEditor.setOptions({
        enableSnippets: true,
        enableLiveAutocompletion: true,
        enableBasicAutocompletion: true
    });
    // Add autocomplete keywords
    codingEditor.completers.push({
    getCompletions: function(editor, session, pos, prefix, callback) {
            callback(null, [
                {value: 'STOP', score: 1000, meta: 'sumorobot'},
                {value: 'LEFT', score: 1000, meta: 'sumorobot'},
                {value: 'RIGHT', score: 1000, meta: 'sumorobot'},
                {value: 'SEARCH', score: 1000, meta: 'sumorobot'},
                {value: 'FORWARD', score: 1000, meta: 'sumorobot'},
                {value: 'BACKWARD', score: 1000, meta: 'sumorobot'},
                {value: 'STATUS', score: 1000, meta: 'sumorobot'},
                {value: 'OPPONENT', score: 1000, meta: 'sumorobot'},
                {value: 'LEFT_LINE', score: 1000, meta: 'sumorobot'},
                {value: 'RIGHT_LINE', score: 1000, meta: 'sumorobot'},
                {value: 'sumorobot', score: 1000, meta: 'sumorobot'},
                {value: 'move(dir)', score: 1000, meta: 'sumorobot', caption: 'move(dir)', snippet: "move(${1:dir})$0"},
                {value: 'sleep(time)', score: 1000, meta: 'sumorobot', caption: 'sleep(time)', snippet: "sleep(${1:time})$0"},
                {value: 'set_led(led, enable)', score: 1000, meta: 'sumorobot', caption: 'set_led(led, enable)', snippet: "set_led(${1:led}, ${2:enable})$0"},
                {value: 'is_line(dir)', score: 1000, meta: 'sumorobot', caption: 'is_line(dir)', snippet: "is_line(${1:dir})$0"},
                {value: 'get_line(dir)', score: 1000, meta: 'sumorobot', caption: 'get_line(dir)', snippet: "get_line(${1:dir})$0"},
                {value: 'set_servo(dir, speed)', score: 1000, meta: 'sumorobot', caption: 'set_servo(dir, speed)', snippet: "set_servo(${1:dir}, ${2:speed})$0"},
                {value: 'is_opponent()', score: 1000, meta: 'sumorobot', caption: 'is_opponent()', snippet: "move()$0"},
                {value: 'calibrate_line_value()', score: 1000, meta: 'sumorobot', caption: 'calibrate_line_value()', snippet: "calibrate_line_value()$0"},
                {value: 'calibrate_line_threshold(val)', score: 1000, meta: 'sumorobot', caption: 'calibrate_line_threshold(val)', snippet: "calibrate_line_threshold(${1:val})$0"},
                {value: 'get_battery_voltage()', score: 1000, meta: 'sumorobot', caption: 'get_battery_voltage()', snippet: "get_battery_voltage()$0"},
                {value: 'get_opponent_distance()', score: 1000, meta: 'sumorobot', caption: 'get_opponent_distance()', snippet: "get_opponent_distance()$0"}
            ]);
        }
    });
    // Set the code to the saved code from local storage or empty
    codingEditor.setValue(getLocalStorageItem('sumorobot.code') || '');
    // Clear the selection after setting the value
    codingEditor.clearSelection();
    // Add an change listener for the code editor
    codingEditor.on('change', function() {
        // When change occurs, save the new code to the localstorage
        setLocalStorageItem('sumorobot.code', codingEditor.getValue())
    });
});