text:
use std::{
    borrow::Cow,
    convert::{TryFrom, TryInto},
};

use quick_protobuf::{BytesReader, MessageRead};

use super::test_owned_pb::*;

#[test]
fn test_owned() {
    let t = trybuild::TestCases::new();
    t.compile_fail("tests/rust_protobuf/v3/test_owned_must_compile_error.rs");
}

#[test]
fn test_owned_basic_functionality() {
    let encoded: Vec<u8> = vec![
        0x0au8, 0x07u8, 0x74u8, 0x65u8, 0x73u8, 0x74u8, 0x69u8, 0x6eu8, 0x67u8,
    ]; // s = "testing"

    let foo_owned = FooOwned::try_from(encoded.clone()).unwrap();

    let foo_owned_temp = FooOwned::try_from(encoded.clone()).unwrap();
    let mut foo_owned_temp_mut = FooOwned::try_from(encoded.clone()).unwrap();
    let reencoded: Vec<u8> = foo_owned_temp.try_into().unwrap();

    let mut br_temp = BytesReader::from_bytes(&encoded);
    let foo = Foo::from_reader(&mut br_temp, &encoded).unwrap();

    let buf = foo_owned.buf().clone();
    let proto = foo_owned.proto().clone();
    let proto_mut = foo_owned_temp_mut.proto_mut();
    proto_mut.s = Some(Cow::from("the secret cow level"));

    let static_foo = Foo {
        s: Some(Cow::from("the moo moo farm")),
    };
    let from_static_foo = FooOwned::from(static_foo);

    assert_eq!(Some(Cow::from("testing")), foo_owned.proto().s); // test decoding and `proto()`

    assert_eq!(encoded, buf); // test `buf()`
    assert_eq!(foo, proto); // test `proto()`
    assert_eq!(
        foo_owned_temp_mut.proto().s,
        Some(Cow::from("the secret cow level"))
    ); // test `proto_mut()`
    assert_eq!(format!("{:?}", foo_owned), format!("{:?}", foo)); // test `try_from()` and `Debug`
    assert_eq!(encoded, reencoded); // test `try_into()`
    assert_eq!(
        Some(Cow::from("the moo moo farm")),
        from_static_foo.proto().s
    ); // test `from()`
}


text:
@*
 * Copyright 2022 HM Revenue & Customs
 *
 * 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.
 *@

@import config.FrontendAppConfig

@this(
    layout: layouts.layout,
    h1: components.h1,
    p: components.p,
    bullets: components.bullets,
    errorSummary: components.errorSummary,
    yesNoRadio: components.yesNoRadio,
    formWithCSRF: FormWithCSRF,
    inputCurrency: components.inputCurrency,
    button: components.button
)

@(form: Form[(Boolean, Option[BigDecimal])])(implicit request: Request[_], messages: Messages, appConfig: FrontendAppConfig)

@layout(pageTitle = Some(title(form, "nip.sellOrMove.heading")), backLink = true) {

  @errorSummary(form.errors)
  @h1(messages("nip.sellOrMove.heading"))
  @p{ @messages("nip.sellOrMove.para") }
  @bullets(
    messages("nip.sellOrMove.bullet1"),
    messages("nip.sellOrMove.bullet2")
  )

  @formWithCSRF(action = controllers.vatapplication.routes.SellOrMoveNipController.submit) {
    @yesNoRadio(
      form = form,
      headingKey = messages("nip.sellOrMove.heading"),
      isPageHeading = false,
      inline = false,
      classes = "govuk-visually-hidden",
      hiddenYesContent = Some(hiddenYesContent)
    )

    @button(messages("app.common.continue"))
  }
}

@hiddenYesContent = {
  @inputCurrency(
    form,
    id = "sellOrMoveNip",
    name = "sellOrMoveNip",
    label = Some(messages("nip.sellOrMove.label")),
    isPageHeading = false,
    hint = Some(Html(messages("nip.sellOrMove.hint")))
  )
}

redpajama_set_name: RedPajamaGithub


text:
=pod

=head1 NAME

SSL_SESSION_is_resumable
- determine whether an SSL_SESSION object can be used for resumption

=head1 SYNOPSIS

 #include <openssl/ssl.h>

 int SSL_SESSION_is_resumable(const SSL_SESSION *s);

=head1 DESCRIPTION

SSL_SESSION_is_resumable() determines whether an SSL_SESSION object can be used
to resume a session or not. Returns 1 if it can or 0 if not. Note that
attempting to resume with a non-resumable session will result in a full
handshake.

=head1 RETURN VALUES

SSL_SESSION_is_resumable() returns 1 if the session is resumable or 0 otherwise.

=head1 SEE ALSO

L<ssl(7)>,
L<SSL_get_session(3)>,
L<SSL_CTX_sess_set_new_cb(3)>

=head1 HISTORY

The SSL_SESSION_is_resumable() function was added in OpenSSL 1.1.1.

=head1 COPYRIGHT

Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the Apache License 2.0 (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
from __future__ import print_function
import base64
import hashlib
import hmac
import json
import sys
import time
import datetime
import urllib
import urllib2
from socket import error as SocketError
import errno

class VDCApiCall(object):
    """
        Class for making signed API calls to the Interoute VDC.
    """
    def __init__(self, api_url, apiKey, secret):
        """
            Initialise the signed API call object with the URL and the
            required API key and Secret key.
        """
        self.api_url = api_url
        self.apiKey = apiKey
        self.secret = secret

    def request(self, args):
        """
            Form the request based on the provided args and using the apikey
            and secret. This ensures the request has the correct signature
            calculated.
        """
        args['apiKey'] = self.apiKey

        request = zip(args.keys(), args.values())
        request.sort(key=lambda x: x[0].lower())
        request_data = "&".join(["=".join([r[0], urllib.quote_plus(str(r[1]),safe='*')])
                                for r in request])
        hashStr = "&".join(
            [
                "=".join(
                    [r[0].lower(),
                     str.lower(urllib.quote_plus(str(r[1]),safe='*')).replace(
                         "+", "%20"
                     )]
                ) for r in request
            ]
        )

        sig = urllib.quote_plus(base64.b64encode(
            hmac.new(
                self.secret,
                hashStr,
                hashlib.sha1
            ).digest()
        ).strip())

        request_data += "&signature=%s" % sig
        # print the URL string for debug
        ###print(request_data)
        ###print(self.api_url + "?" + request_data)

        try:
            connection = urllib2.urlopen(self.api_url + "?" + request_data ) # GET request
            ##connection = urllib2.urlopen(self.api_url, request_data) # POST request
            response = connection.read()
        except SocketError as e:
            if e.errno != errno.ECONNRESET:
                # not a RESET error so report it and exit
                print('Socket error: %s' % e.errno)
                sys.exit()
            # ignore a RESET error and carry on by returning an empty response
            error_timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+0000")
            print("\n%s Exception for socket error 104 for request:\n%s" % (error_timestamp,self.api_url + "?" + request_data))
            return '{"CONNECTIONERRORresponse":{}}'
        except urllib2.HTTPError as error:
            print('HTTP Error: %s' % error.code)
            description = str(error.info())
            description = description.split('\n')
            description = [line
                           for line
                           in description
                           if line.startswith('X-Description: ')]

            if len(description) > 0:
                description = description[0].split(':', 1)[-1].lstrip()
            else:
                description = '(No extended error message.)'

            print(description)
            sys.exit()
        return response

    def wait_for_job(self, job_id, delay=2, display_progress=True):
        """
            Wait for the given job ID to return a result.
            Sleeps for 'delay' seconds between each check for the job
            finishing- default 2.
            Will output a '.' for every 'delay' if 'display_progress' is true.
        """
        request = {
            'jobid': job_id,
        }

        while(True):
            result = self.queryAsyncJobResult(request)
            if display_progress:
                print('.', end='')
                sys.stdout.flush()
            if 'jobresult' in result:
                print('')
                return result['jobresult']
            time.sleep(delay)

    def __getattr__(self, name):
        def handlerFunction(*args, **kwargs):
            if kwargs:
                return self._make_request(name, kwargs)
            return self._make_request(name, args[0])
        return handlerFunction

    def _make_request(self, command, args):
        args['response'] = 'json'
        args['command'] = command
        data = self.request(args)
        # The response is of the format {commandresponse: actual-data}
        ##key = command.lower() + "response"
        ##  Temporary change due to incompatible behaviour of the new network commands
        ##return json.loads(data)[key]
        ##print("DEBUG data: %s" % data)
        return json.loads(data).values()[0]


text:
class Website::Font < ApplicationRecord
  belongs_to :website

  has_one_attached :file

  validates :file, :name, presence: true

  scope :primary, -> { where(primary: true) }
  scope :secondary, -> { where(secondary: true) }
end

# == Schema Information
#
# Table name: website_fonts
#
#  id         :bigint(8)        not null, primary key
#  name       :string
#  primary    :boolean
#  secondary  :boolean
#  website_id :bigint(8)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_website_fonts_on_website_id  (website_id)
#


text:
package org.studio.maizi.ripened.anno;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * set the adapter of adapter view.

 * Powered by Maizi-Studio.

 * Design by maizi.

 * Created on 15-11-5.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Adapter {
    /**
     * the class of adapter
     *
     * @return ...
     */
    Class<? extends android.widget.Adapter> value();
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /Users/gregor/PhpstormProjects/siesta/src/Siesta/Driver/MySQL/MySQLEmptyResult.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../css/style.css" rel="stylesheet">

/Users/gregor/PhpstormProjects/siesta/src/Siesta

Driver

MySQL

MySQLEmptyResult.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 10

      CRAP

           0.00% covered (danger)

0.00%

0 / 10

      MySQLEmptyResult

           0.00% covered (danger)

0.00%

0 / 1

           0.00% covered (danger)

0.00%

0 / 10

      110

           0.00% covered (danger)

0.00%

0 / 10

       hasNext

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getNext

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       close

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getBooleanValue

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getIntegerValue

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getFloatValue

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getStringValue

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getDateTime

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getObject

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

       getArray

           0.00% covered (danger)

0.00%

0 / 1

      2

           0.00% covered (danger)

0.00%

0 / 1

1
	<?php

2
	declare(strict_types = 1);

3
	namespace Siesta\Driver\MySQL;

4

5
	use Siesta\Database\ResultSet;

6

7
	/**

8
	 * @author Gregor Müller

9
	 */

10
	class MySQLEmptyResult implements ResultSet

11
	{

12
	    public function hasNext() : bool

13
	    {

14
	        return false;

15
	    }

16

17
	    public function getNext() : array

18
	    {

19
	        return [];

20
	    }

21

22
	    public function close()

23
	    {

24

25
	    }

26

27
	    public function getBooleanValue(string $key)

28
	    {

29
	        return null;

30
	    }

31

32
	    public function getIntegerValue(string $key)

33
	    {

34
	        return null;

35
	    }

36

37
	    public function getFloatValue(string $key)

38
	    {

39
	        return null;

40
	    }

41

42
	    public function getStringValue(string $key)

43
	    {

44
	        return null;

45
	    }

46

47
	    public function getDateTime(string $key)

48
	    {

49
	        return null;

50
	    }

51

52
	    public function getObject(string $key)

53
	    {

54
	        return null;

55
	    }

56

57
	    public function getArray(string $key)

58
	    {

59
	        return null;

60
	    }

61

62
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by php-code-coverage 4.0.0 using PHP 7.0.4 with Xdebug 2.4.0RC3, Codeception and PHPUnit 5.4.7 at Thu Jul 21 16:45:12 CEST 2016.


text:
<?php

namespace NetworkHeartbeat\Job;

abstract class Base
{
	private $_config;
	private $_Emitter;
	private $_events;

	public function __construct()
	{
		$this->_Emitter = new \NetworkHeartbeat\Event\Emitter();
	}

	protected function getConfig()
	{
		return $this->_config;
	}

	public function setConfig(\NetworkHeartbeat\Config $Config){
		$this->_config = $Config;
	}

	public function triggerEvent($triggeredEvent, $meta = '')
	{
		$event = new \StdClass();

		if (array_key_exists($triggeredEvent, $this->_events)) {
			$event->event = $triggeredEvent;
			$event->message = $this->_config->events->$triggeredEvent . $meta;
			$this->_Emitter->transmit($event);
		} else {
			$event->event = 'Unknown Event';
			$event->message = 'An unknown event has been triggered.';
			$this->_Emitter->transmit($event);
		}
	}

	protected function registerEvents()
	{
		$this->_events = $this->getConfig()->events;
	}
}


text:
using std::ostream;
using std::cout;

//This is the basic constructor, it set's the link to NULL
List<T>::List<T>()
  {
  headptr = 0;
  }

//This constructor creates a new link and adds a value to its data
//section
List<T>::List<T>(const T & c)
  {
  Link<T> *a = new Link;
  a->data = c;
  a->next = NULL;
  headptr = a;
  }

//this is the copy constructor.  It does what it says it does,
//copy an existing list into a new one.
List<T>::List<T>(const List<T> & l)
  {
  Copy(l.headptr, headptr);
  }

//this is the deconstructor, which frees up an entire linked list
//in memory
List<T>::~List<T>()
  {
  Demolish(headptr);
  }

//this is the output operator overloader.  it displays each link's data
//one by one.
ostream & operator << (ostream & cout, const List<T> & l)
  {
  Link<T> *temp = l.headptr;
  while (temp != NULL)
    {
    cout << temp->data << " ";
    temp = temp->next;
    }
  return cout;
  }

//This function calls the private function to grab
//the link's length
int List<T>::Length() const
  {
  return ListLength(headptr);
  }

//this inserts the passed character into the beginning
//of the list
void List<T>::Insert(const T & c)
  {
  Link<T> *temp = new Link;
  temp->data = c;
  temp->next = headptr;
  headptr = temp;
  }

//This checks to see if the passed character is shown
//in the list at least once.
bool List<T>::IsPresent(const T & c) const
  {
  if (Search(c) != 0 || headptr->data == c)
    return true;
  return false;
  }

//This deletes the first instance of the passed character, and returns
//true, if it is not found, it returns false.
bool List<T>::Delete(const T & c)
  {
  Link<T>	*temp1,
			*temp2;
  temp1 = Search(c);
  temp2 = temp1->next;
  if (temp1 == NULL)
    {
    if (temp1->data == c)
      {
      temp2 = headptr;
      temp1->next = temp2->next;
      delete temp2;
      return true;
      }
    return false;
    }
  temp1->next = temp2->next;
  delete temp2;
  return true;
  }

//This deletes all instances of the passed character in the list
void List<T>::DeleteAll(const T & c)
  {
  while (IsPresent(c))
    Delete(c);
  }

//This calles the private function to print the list in reverse order
void List<T>::PrintReverse() const
  {
  ReversePrint(headptr);
  }

//This is the equality operator overloader.  It checks to see if
//both lists have the same elements in the exact same order.
//If so, return true, if not, return false.
bool List<T>::operator==(const List<T> & l) const
  {
  Link<T> *temp1 = headptr,
       *temp2 = headptr;
  if (Length() == l.Length())
    {
    while (temp1 != NULL && temp2 != NULL)
      {
      if (temp1->data == temp2->data)
        {
        temp1 = temp1->next;
        temp2 = temp2->next;
        }
      else return false;
      }
    return true;
    }
  return false;
  }

//This is the assignment operator overloader.  It deletes the current
//list, allocates new memory for a list as big as the one passed in,
//and sets each link in the new list to the respective character in
//the passed list.
List<T> & List<T>::operator=(const List<T> & l)
  {
  Demolish(headptr);
  Copy(l.headptr, headptr);
  return *this;
  }

//This copies each link from the second list into the first recursively
void List<T>::Copy(const Link<T> * l1, Link<T> *& l2)
  {
  if (l1 != NULL)
    {
    l2 = new Link;
    l2->data = l1->data;
    Copy(l1->next, l2->next);
    }
  else
    l2 = NULL;
  }

//This recursively goes through the list first, then deletes each link
//from the end to the front.
void List<T>::Demolish(Link<T> *& l)
  {
  if (l != NULL)
    {
    Demolish(l->next);
    delete l;
    }
  }

//This counts each list, as long as it exists, and returns the number of
//links in the list.
int List<T>::ListLength(const Link<T> * l) const
  {
  int count = 0;
  Link<T> *temp = headptr;
  while (temp != NULL)
    {
    count++;
    temp = temp->next;
    }
  return count;
  }

//This searches the list for the passed character, and returns the
//pointer to the link before it occured.
Link<T> * List<T>::Search(const T & c) const
  {
  Link<T> *temp1 = headptr,
       *temp2 = headptr;

  if (temp1->data == c)
    return NULL;
  while (temp1 != NULL)
    {
    if (temp1->data != c)
      {
      temp2 = temp1;
      temp1 = temp1->next;
      }
    else
      return temp2;
    }
  return NULL;
  }

//this recursively travels to the end of teh list, then prints each link
//back to the front.
void List<T>::ReversePrint(const Link<T> * l) const
  {
  if (l != NULL)
    {
    ReversePrint(l->next);
    cout << l->data << " ";
    }
  }


text:
- Fixed an issue where the colon in the error message was causing issues

# 1.5.1
- Fixed a case where arguments on the newline that started with def (like 'default') where recognised as a method definition.

# 1.5.0
- PEP8 specifies only methods need a surrounding blank line, therefore class arguments are allowed on the newline.

# 1.4.0
- Went from physical lines to logical lines, since classes with multiple line base classes do not need to be flagged.

# 1.2.1
- Fixed an issue where the line numbers of one file would bleed into the second file, therefore eventually producing errors on every line

# 1.2.0
- For simplicity, completely rewrote the line checker into a function
- Removed the docstrings configuration option previously added in 1.1.0, will add this again in the future.

# 1.1.0
- Added configuration setting to ignore docstrings on a newline

# 1.0.0
- Added new line checker


text:
using System;
using DNX.Helpers.Maths;
using DNX.Helpers.Validation;
using NUnit.Framework;
using Shouldly;
using Test.DNX.Helpers.Validation.TestsDataSource;

namespace Test.DNX.Helpers.Validation
{
    [TestFixture]
    public class GuardDecimalTests
    {
        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsBetween_Default")]
        public bool Guard_IsBetween_Default(decimal value, decimal min, decimal max, string messageText)
        {
            try
            {
                // Act
                Guard.IsBetween(() => value, min, max);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsBetween_BoundsType")]
        public bool Guard_IsBetween_BoundsType(decimal value, decimal min, decimal max, IsBetweenBoundsType boundsType, string messageText)
        {
            try
            {
                // Act
                Guard.IsBetween(() => value, min, max, boundsType);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsBetween")]
        public bool Guard_IsBetween(decimal value, decimal min, decimal max, bool allowEitherOrder, IsBetweenBoundsType boundsType, string messageText)
        {
            try
            {
                // Act
                Guard.IsBetween(() => value, min, max, allowEitherOrder, boundsType);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsGreaterThan")]
        public bool Guard_IsGreaterThan_Expr(decimal value, decimal min, string messageText)
        {
            try
            {
                // Act
                Guard.IsGreaterThan(() => value, min);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsGreaterThan")]
        public bool Guard_IsGreaterThan_Value(decimal actualValue, decimal min, string messageText)
        {
            try
            {
                // Act
                decimal value = min;
                Guard.IsGreaterThan(() => value, actualValue, min);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsGreaterThanOrEqualTo")]
        public bool Guard_IsGreaterThanOrEqualTo_Expr(decimal value, decimal min, string messageText)
        {
            try
            {
                // Act
                Guard.IsGreaterThanOrEqualTo(() => value, min);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsGreaterThanOrEqualTo")]
        public bool Guard_IsGreaterThanOrEqualTo_Value(decimal actualValue, decimal min, string messageText)
        {
            try
            {
                // Act
                decimal value = min;
                Guard.IsGreaterThanOrEqualTo(() => value, actualValue, min);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsLessThan")]
        public bool Guard_IsLessThan_Expr(decimal value, decimal max, string messageText)
        {
            try
            {
                // Act
                Guard.IsLessThan(() => value, max);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsLessThan")]
        public bool Guard_IsLessThan_Value(decimal actualValue, decimal max, string messageText)
        {
            try
            {
                // Act
                decimal value = max;
                Guard.IsLessThan(() => value, actualValue, max);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsLessThanOrEqualTo")]
        public bool Guard_IsLessThanOrEqualTo_Expr(decimal value, decimal max, string messageText)
        {
            try
            {
                // Act
                Guard.IsLessThanOrEqualTo(() => value, max);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }

        [TestCaseSource(typeof(GuardDecimalTestsSource), "IsLessThanOrEqualTo")]
        public bool Guard_IsLessThanOrEqualTo_Value(decimal actualValue, decimal max, string messageText)
        {
            try
            {
                // Act
                decimal value = max;
                Guard.IsLessThanOrEqualTo(() => value, actualValue, max);

                return true;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNotNull(messageText);
                Assert.IsNotEmpty(messageText);
                ex.Message.ShouldStartWith(messageText);
                return false;
            }
            catch (Exception ex)
            {
                // Assert
                Assert.Fail(ex.Message);
                return false;
            }
        }
    }
}


text:
import React, { PropTypes, Component } from 'react';
import {Tabs, Tab, TabList, TabPanel} from 'react-tabs';
import {connect} from 'react-redux';
import JCProfile from './JCProfile.js';
import JCLayers from './JCLayers.js';
import JCFeatures from './JCFeatures.js';
import {fetchJCProfile, editJCProfile} from '../../../actions/JCProfiles.js';
import {fetchJCLayersIfNeeded, editJCLayer, createJCLayer, deleteJCLayer} from '../../../actions/JCLayers.js';
import {fetchJCFeaturesIfNeed} from '../../../actions/JCFeatures.js';

class MapEditPage extends Component {
    static propTypes = {
        params: PropTypes.object.isRequired,
        dispatch: PropTypes.func.isRequired,
        profile: PropTypes.object,
        layers: PropTypes.arrayOf(PropTypes.object),
    }

    static defaultProps = {
        profile: {},
        layers: [],
    }

    componentDidMount = () => {
        const {dispatch, params} = this.props;
        dispatch(fetchJCProfile(params._id)).then((profile) => {
            dispatch(fetchJCLayersIfNeeded(profile));
        });
    }

    onSaveJCProfile = (profile) => {
        const {dispatch} = this.props;
        dispatch(editJCProfile(profile));
    }

    onSaveJCLayer = (layer) => {
        const {dispatch} = this.props;
        dispatch(editJCLayer(layer));
    }

    onCreateJCLayer = (profile) => {
        const {dispatch} = this.props;
        return (layer) => {
            dispatch(createJCLayer(layer, profile));
        };
    }

    onDeleteJCLayer = (layerID) => {
        const {dispatch} = this.props;
        dispatch(deleteJCLayer(layerID));
    }

    onSelectJCFeatures = (layer) => {
        const {dispatch} = this.props;
        return dispatch(fetchJCFeaturesIfNeed(layer));
    }

    onSaveJCFeature = () => {
    }

    onDeleteJCFeature = () => {
    }

    renderTabs = () => {
        const {profile, layers, dispatch} = this.props;
        return (
            <Tabs forceRenderTabPanel={Boolean(false)}>
                <TabList>
                    <Tab>profile</Tab>
                    <Tab>layer</Tab>
                    <Tab>feature</Tab>
                </TabList>
                <TabPanel>
                    <JCProfile
                        profile={profile}
                        onSaveJCProfile={this.onSaveJCProfile}
                        />
                </TabPanel>
                <TabPanel>
                    <JCLayers
                        layers={layers}
                        dispatch={dispatch}
                        onSaveJCLayer={this.onSaveJCLayer}
                        onCreateJCLayer={this.onCreateJCLayer(profile)}
                        onDeleteJCLayer={this.onDeleteJCLayer}
                         />
                </TabPanel>
                <TabPanel>
                    <JCFeatures
                        layers={layers}
                        onSelectJCFeatures={this.onSelectJCFeatures}
                        onSaveJCFeature={this.onSaveJCFeature}
                        onDeleteJCFeature={this.onDeleteJCFeature}
                        />
                </TabPanel>
            </Tabs>
        );
    }

    render() {
        return (

                    {this.renderTabs()}

        );
    }
}

function selectCurrentJCProfile(state) {
    const profile = state.JCProfiles.find(Profile => Profile._id === state.currentJCProfile);
    const layers = state.JCLayers.filter(layer => profile.JCLayers.includes(layer._id));
    return {profile, layers};
}

export default connect(selectCurrentJCProfile)(MapEditPage);


text:
SYNONYM

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

#### Published in
null

#### Original name
Fusidium torulosum Berk. & M.A. Curtis, 1875

### Remarks
null


text:
require 'net/imap'
class ReceivedEmail < Email
  def self.parse_address(e)
    if e =~ EDIT_ADDRESS_REGEX
      {:id => $1, :key => $2 }
    end
  end

  EDIT_ADDRESS_REGEX = /copypasta\+edit-(\d+)-?(([a-z0-9]+))?@credibl\.es/
  STATUS_REGEX = /^[^\n]*\[\s*x\s*\]\s(\w+)/mi
  INSTRUCTIONS_REGEX = /(.*)^[^\n]*\*{3}copypasta\sinstructions\*{3}[^\n]*\n(.*)/m
  EMAIL_SANITIZE_REGEX = /copypasta(\+|%2B)edit-(\d+)-\w+\@credibl\.es/
  def self.parse_body(body, key)
    result = {}
    ins = false
    if body =~ INSTRUCTIONS_REGEX
      ins = result[:instructions] = $2
      body = $1
    end
    if ins && ins =~ STATUS_REGEX
      result[:status] = $1 + 'ed'
    end
    if key
      result[:message] = body.gsub(/-?#{key}/, '')
    end
    result
  end

  def self.check_mail
    # make a connection to imap account
    imap = Net::IMAP.new('imap.gmail.com', 993, true)
    imap.login(Email.config[:username], Email.config[:password])
    # select inbox as our mailbox to process
    imap.select('Inbox')

    # get all emails that are in inbox that have not been deleted
    imap.uid_search(["NOT", "DELETED"]).each do |uid|
      # fetches the straight up source of the email for tmail to parse
      source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']

      receive(source)

      # there isn't move in imap so we copy to new mailbox and then delete from inbox
      imap.uid_copy(uid, "[Gmail]/All Mail")
      imap.uid_store(uid, "+FLAGS", [:Deleted])
    end

    # expunge removes the deleted emails
    imap.expunge
    imap.logout
    imap.disconnect
  end

  def self.receive(source)
    e = new(:raw => source)
    if e.save
      EditorMailer.receive(source)
    end
  end
end


text:
SYNONYM

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

#### Published in
Bol. Secr. Agric. (Pernambuco) 15: 130 (1948)

#### Original name
Catacauma torrendiella Bat., 1948

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <groupId>pt.davidafsilva.slacker</groupId>
        <artifactId>slacker</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>slacker-server</artifactId>

    <dependencies>
        <dependency>
            <groupId>pt.davidafsilva.slacker</groupId>
            <artifactId>slacker-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.zafarkhaja</groupId>
            <artifactId>java-semver</artifactId>
            <version>${java-semver.version}</version>
        </dependency>

        <!-- test -->
        <dependency>
            <groupId>pt.davidafsilva.slacker</groupId>
            <artifactId>slacker-api</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
            <type>test-jar</type>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-unit</artifactId>
            <version>${vertx.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
require('./logger.js');

import path from 'path';
import express from 'express';
import request from 'request';
import historyApiFallback from 'connect-history-api-fallback';

import Database from '../graphql/Database';
import createGraphQlServer from './graphQlServer';

const IMAGE_PORT = 9000;
const GRAPHQL_PORT = 8080;
const RELAY_PORT = 4444;

createGraphQlServer(GRAPHQL_PORT, new Database());

// __dirname is {projectRoot}/server, so we have to step one directory up
const pathBase = path.resolve(__dirname, '../');

const imageServer = express();
imageServer.use('/images', express.static(pathBase + '/graphql/testData/images'));

imageServer.listen(IMAGE_PORT);

const app = express();

app.use(historyApiFallback());
app.use('/', express.static(pathBase + '/build'));

app.use('/graphql',  function(req, res) {
  req.pipe(request(`http://localhost:${GRAPHQL_PORT}/graphql`)).pipe(res);
});

app.get(/images\/.{1,}/i, function(req, res) {
  req.pipe(request(`http://localhost:${IMAGE_PORT}${req.originalUrl}`)).pipe(res);
});

if (!process.env.PRODUCTION) {
  /*************************************************************
   *
   * Webpack Dev Middleware with hot reload
   *
   *************************************************************/

  const webpack = require('webpack');
  const config = require('../webpack.local.config.js');
  const webpackDevMiddleware = require("webpack-dev-middleware");
  const webpackHotMiddleware = require("webpack-hot-middleware");

  const compiler = webpack(config);
  const options = {
    noInfo: true,
    stats: {colors: true},
  };

  app.use(webpackDevMiddleware(compiler, options));
  app.use(webpackHotMiddleware(compiler));
  app.use(express.static(config.output.publicPath));

  app.listen(RELAY_PORT, (err, result) => {
    if (err) {
      log(err);
    }
    else {
      log(`App is now running on http://localhost:${RELAY_PORT}`)
    }
  });

}
else {
  /******************
   *
   * Express server
   *
   *****************/

  const port = process.env.PORT || 4444;
  const server = app.listen(port, () => {
    const host = server.address().address;
    const port = server.address().port;

    log('Essential React listening at http://%s:%s', host, port);
  });
}


text:
var cli = require.resolve('gitbook-cli')
console.log('node ' + cli + ' ' + process.argv.slice(2).join(' '))
var proc = require('child_process').exec('node ' + cli + ' ' + process.argv.slice(2).join(' '))
proc.stdout.on('data', (info) => {
  process.stdout.write(info)
})
proc.stderr.on('data', (err) => {
  process.stdout.write(err)
})


text:
package com.bang4.sdk.i;

import java.util.Map;

public interface ISDK {
	public void call(String cmd,Map<String,Object>param,ICallback callback);
	public int version();
	public void init(IHolder holder);
	public void destory();
}


text:
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Nerdle.Hydra.Simulator
{
    public static class ParallelAsync
    {
        public static async Task For(int fromInclusive, int toExclusive, int maxDegreeOfParallelism, Func<int, Task> operation)
        {
            var currentTasks = Enumerable.Range(fromInclusive, maxDegreeOfParallelism)
                .Select(i => Task.Run(() => operation(i)))
                .ToList();

            var taskCounter = currentTasks.Count;

            while (currentTasks.Count > 0)
            {
                var completed = await Task.WhenAny(currentTasks);
                var index = currentTasks.IndexOf(completed);

                if (taskCounter < toExclusive)
                {
                    var iteration = taskCounter;
                    currentTasks[index] = Task.Run(() => operation(iteration));
                    taskCounter++;
                }
                else
                {
                    currentTasks.RemoveAt(index);
                }
            }
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class CInitialize extends CI_Controller {
	function __construct() {
		parent::__construct();
	 	$this->load->library('session');
	 	$this->load->model('user/MEvent');
	}

	public function index()
	{
		if ($this->session->userdata('userSession')) {
			redirect('cLogin/viewDashBoard');
		} else {
			//////////////////////////////////////////////////////////////////////////////
			//================INTERFACE MODULE - SPRINT 3 Implementation============//
			/////////////////////////////////////////////////////////////////////////////
			$stringSelect = "*, DATE_FORMAT(event_info.event_date_start,'%d-%b-%y %H:%m') as dateStart, DATE_FORMAT(event_info.event_date_end,'%d-%b-%y %H:%m') as dateEnd";
			$stringWhere = "event_info.event_status = 'Approved'";
			$data['events'] = $this->MEvent->select_certain_where_isDistinct_hasOrderBy_hasGroupBy_isArray($stringSelect,$stringWhere,false,false,false,false);
			////////////STOPS HERE///////////////////////////////////////////////////

			$this->load->view('imports/vHeaderHomePage');
			$this->load->view('vHomePage',$data);
			$this->load->view('imports/vFooterHomePage');
			// $this->load->view('vLogin');
			//redirect('cInitialize');
		}
	}

	public function viewAboutUs(){
		$this->load->view('vAboutUs');
	}

	public function viewEventsHomepage(){
		$this->load->view('vEvents');
	}
}


text:
components: Link
githubLabel: 'component: Link'
waiAria: 'https://www.w3.org/TR/wai-aria-practices/#link'
---

# Enlaces

Los Enlaces permiten personalizar fácilmente los enlaces con los colores de su Tema y estilos de tipografía.

{{"component": "modules/components/ComponentLinkHeader.js"}}

## Enlaces simples

The Link component is built on top of the [Typography](/api/typography/) component. You can leverage its properties.

{{"demo": "pages/components/links/Links.js"}}

However, the Link component has different default properties than the Typography component:

- `color="primary"` as the link needs to stand out.
- `variant="inherit"` as the link will, most of the time, be used as a child of a Typography component.

## Underline

The `underline` prop can be used to set the underline behavior. The default is `hover`.

{{"demo": "pages/components/links/UnderlineLink.js"}}

## Seguridad

When you use `target="_blank"` with Links, it is [recommended](https://developers.google.com/web/tools/lighthouse/audits/noopener) to always set `rel="noopener"` or `rel="noreferrer"` when linking to third party content.

- `rel="noopener"` prevents the new page from being able to access the `window.opener` property and ensures it runs in a separate process. Without this, the target page can potentially redirect your page to a malicious URL.
- `rel="noreferrer"` has the same effect, but also prevents the *Referer* header from being sent to the new page. ⚠ Removing the referrer header will affect analytics.

## Librería externa de routing

One frequent use case is to perform navigation on the client only, without an HTTP round-trip to the server. The `Link` component provides a property to handle this use case: `component`. Here is a [more detailed guide](/guides/routing/#link).

## Accesibilidad

(WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#link)

- Al proporcionar el contenido del enlace, evitar descripciones genéricas como "haga clic aquí" o "ir a". En su lugar, utilice [descripciones específicas](https://developers.google.com/web/tools/lighthouse/audits/descriptive-link-text).
- Para una mejor experiencia de usuario, los enlaces deben sobresalir del texto en la página. For instance, you can keep the default `underline="always"` behavior.
- Si un enlace no tiene un significativo href, [se debe representarse mediante un `<button>` elemento](https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md).

{{"demo": "pages/components/links/ButtonLink.js"}}


text:
//
//  TPTripListViewDataSource.m
//  TP
//
//  Created by moxin on 2015-06-01 19:41:29 +0800.
//  Copyright (c) 2015年 VizLab. All rights reserved.
//

#import "TPTripListViewDataSource.h"
#import "TPTripListCell.h"
#import "TPTripListItem.h"

@interface TPTripListViewDataSource()

@end

@implementation TPTripListViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    //default:
    return 1;

}

- (Class)cellClassForItem:(id)item AtIndex:(NSIndexPath *)indexPath{

    //@REQUIRED:

    return [TPTripListCell class];

}

@end


text:
import {Bin} from 'd3-array/index';
import {ICounted} from './ICounted';

export interface IHistogram extends Bin<ICounted, number> {
  x: number;
  width: number;
  histMax: number;
  histPos: {[index: string]: number};
  histSum: {[index: string]: number};
  // [property: string]: number | any
}


text:
"use strict";
// Set properties of SVG like width, height.
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 2000  - margin.top - margin.bottom;
var padding = 50,
left_pad = 100;

var bisectDate = d3.bisector(function(d) { return d.startTijd; }).left;

window.onload = function(){
  loadData()
}

/*
 * load all data and store in queue.
 */
function loadData(){
  var q = queue(1)
  q.defer(d3.json, "westelijke2015.json")
  q.defer(d3.json, "JSON/westelijke2015_uurlijk.json")
  q.defer(d3.json, "damen2015.json")
  q.defer(d3.json, "JSON/damen2015_uurlijk.json")
  q.defer(d3.json, "damen2014.json")
  q.defer(d3.json, "JSON/damen2014_uurlijk.json")
  q.awaitAll(page)
}

/*
 * select different subselections of the data_array (from the queue) depending on which game is selected
 */
function page(error, data_array){
  var wes = document.getElementById("selectWes")
  wes.addEventListener("click", function(){
    clearSVG()
    // Hide the scatter plot SVG
    var graph = d3.select("#container_scatter")
      .style("opacity", "0")
    // Show the explanation of page.
    var info = d3.select(".infobox")
      .style("opacity", "1")
    // Show which competition is selected.
    var p = d3.select("#wedstrijd")
    p.html("Westelijke 2015")

    // Show that no subselection is made.
    var p = d3.select("#dag")
    p.html("gekozen dag")
    var p = d3.select("#soort_wedstrijd")
    p.html("soort wedstrijd gekozen")

    // Hide the wind information and wind arrow
    var wind = d3.select("#infoUpdate")
    wind.style("opacity", "0")
    var arrow = d3.select("#windArrow")
    arrow.style("opacity", "0")

    // Select the right data.
    var wesRes = data_array[0]
    var wesWea = data_array[1]
    selectDay(wesRes,wesWea)
  },true)
  var dam15 = document.getElementById("selecDam15")
  dam15.addEventListener("click", function(){
    clearSVG()
    // Hide the scatter plot SVG
    var graph = d3.select("#container_scatter")
      .style("opacity", "0")

    // Show the explanation of page.
    var info = d3.select(".infobox")
      .style("opacity", "1")

    // Show which competition is selected.
    var p = d3.select("#wedstrijd")
    p.html("Damen 2015")

    // Show that no subselection is made.
    var p = d3.select("#dag")
    p.html("gekozen dag")
    var p = d3.select("#soort_wedstrijd")
    p.html("soort wedstrijd gekozen")

    // Hide the wind information and wind arrow
    var wind = d3.select("#infoUpdate")
    wind.style("opacity", "0")
    var arrow = d3.select("#windArrow")
    arrow.style("opacity", "0")

    // Select the right data.
    var d15Res = data_array[2]
    var d15Wea = data_array[3]
    selectDay(d15Res,d15Wea)
  },false)
  var dam14 = document.getElementById("selecDam14")
  dam14.addEventListener("click", function(){
    clearSVG()
    // Hide the scatter plot SVG
    var graph = d3.select("#container_scatter")
      .style("opacity", "0")

    // Show the explanation of page.
    var info = d3.select(".infobox")
      .style("opacity", "1")

    // Show which competition is selected.
    var p = d3.select("#wedstrijd")
    p.html("Damen 2014")

    // Show that no subselection is made.
    var p = d3.select("#dag")
    p.html("gekozen dag")
    var p = d3.select("#soort_wedstrijd")
    p.html("soort wedstrijd gekozen")

    // Hide the wind information and wind arrow
    var wind = d3.select("#infoUpdate")
    wind.style("opacity", "0")
    var arrow = d3.select("#windArrow")
    arrow.style("opacity", "0")

    // Select the right data.
    var d14Res = data_array[4]
    var d14Wea = data_array[5]
    selectDay(d14Res,d14Wea)
  },false)
}

/*
 * Select subset of data depending on day clicked.
 */
function selectDay(results, weather){
  var sat = document.getElementById("zaterdag_select")
  sat.addEventListener("click", function(){
    var p = d3.select("#dag")
    p.html("Zaterdag")

    var p = d3.select("#soort_wedstrijd")
    p.html("soort wedstrijd gekozen")

    var weather_day = []
    saturday(results, weather, weather_day)
  },false)
  var sund = document.getElementById("zondag_select")
  sund.addEventListener("click", function(){
    var p = d3.select("#dag")
    p.html("Zondag")

    var p = d3.select("#soort_wedstrijd")
    p.html("soort wedstrijd gekozen")

    var weather_day = []
    sunday(results, weather, weather_day)
  },false)
}

/*
 * Only select those heats that where rowed on Saturday.
 */
function saturday (results, weather, weather_day){
  if (typeof(day_results) !== 'undefined') {
    clearArray(day_results)
  }
  weather_day = []
  for (var i = 0; i < (weather.length/2); i++){
    weather_day.push(weather[i])
  }
  var day_results = []
  results.forEach(function(d) {
    d.temp = d[0]
    if (d.temp == "za" || d.temp == "za "){
        day_results.push(d)
      }
    })

  // Clear the possibly existing graph and initialise a new SVG element
  clearSVG()
  initialise()

  // Draw the winddirection on Saturday.
  drawWindDirection(weather, weather_day)
  // Selection must be made for qualifiers, finals or both
  selectType(results, day_results, weather_day, weather)
}

/*
 * Only select those heats that where rowed on Sunday
 */
function sunday (results, weather, weather_day){
  if (typeof(day_results) !== 'undefined') {
    clearArray(day_results)
  }
  weather_day = []
  for (var i = 0; i < (weather.length/2); i++){
    weather_day.push(weather[13+i])
  }
  var day_results = []
  results.forEach(function(d) {
    d.temp = d[0]
    if (d.temp == "zo" || d.temp == "zo "){
      day_results.push(d)
    }
  })

  // Clear the possibly existing graph and initialise a new SVG element
  clearSVG()
  initialise()

  // Draw the winddirection on Sunday.
  drawWindDirection(weather, weather_day)
  // Selection must be made for qualifiers, finals or both
  selectType(results, day_results, weather_day, weather)
}

// Clear the SVG element and create a new svg element.
function initialise(){
  clearSVG()

  d3.select("#container_scatter").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("id", "scatter_results")
}

// clear the main SVG.
function clearSVG(){
  var rem = d3.select("#scatter_results")
  rem.remove()
  var rem = d3.select("#scatter_results").select("g")
  rem.remove()
}

// Clear the wind arrow SVG.
function clearWind(){
  var svg = d3.select("#wind")
  svg.remove()
}

/*
 * await selection of a time of competition (qualifiers, finals or both)
 */
function selectType(results, day_results, weather_day, weather){
  clearSVG()
  initialise()

  // Make sure an empty DataSelection is used
  var DataSelection = []
  clearArray(DataSelection)
  DataSelection = []

  // Qualifiers is selected, select right data.
  var vw = document.getElementById("select_voorwedstrijd")
  vw.addEventListener("click", function(){
    var p = d3.select("#soort_wedstrijd")
    p.html("Voorwedstrijden")

    // initialse svg for new graph
    initialise()

    // select the right data
    var DataSelection = []
    clearArray(DataSelection)
    day_results.forEach(function(d) {
      var temp = d[2].slice(-6)
      if (temp !== "finale"){
        DataSelection.push(d)
      }
      })

    // Draw graph using the selected data.
    drawScatter(DataSelection, results, day_results, weather_day, weather)
  },true)

  // Finals are selected, select right data.
  var finale = document.getElementById("select_finales")
  finale.addEventListener("click", function(){
    var p = d3.select("#soort_wedstrijd")
    p.html("Finales")

    // initialse svg for new graph
    initialise()

    // select the right data
    var DataSelection = []
    clearArray(DataSelection)
    day_results.forEach(function(d) {
      var temp = d[2].slice(-6)
      if (temp === "finale"){
        DataSelection.push(d)
      }
      })

    // Draw graph using the selected data.
    drawScatter(DataSelection, results, day_results, weather_day, weather)
  },true)

  // Both are selected, select right data.
  var both = document.getElementById("select-beide")
  both.addEventListener("click", function(){
    var p = d3.select("#soort_wedstrijd")
    p.html("Voorwedstrijden & Finales")

    // initialse svg for new graph
    initialise()

    // select the right data
    var DataSelection = []
    clearArray(DataSelection)
    day_results.forEach(function(d) {
      DataSelection.push(d)
    })

    // Draw graph using the selected data.
    drawScatter(DataSelection, results, day_results, weather_day, weather)
  },true)

}

/*
 * Draw the wind direction and update the wind div.
 */
function drawWindDirection(weather,weather_day){
  // Remove an old wind arrow.
  clearWind()
  var compass = d3.select("#compass")
    .style("opacity", "0")
  var svg = d3.select("#static_images").append("svg")
    .attr("id", "wind")
  // Get the width and height of the SVG to determine the middle.
  var width_wind = parseInt(svg.style("width"),10);
  var height_wind = parseInt(svg.style("height"),10);

  // Add an image of a compass to the svg
  svg.append("image")
    .attr("id", "comp")
    .attr("xlink:href", "images/compass2.png")
    .attr("width", width_wind)
    .attr("height", height_wind)

  // Determine average direction, strength and max strength for the selected day.
  var sum_direction = 0,
  sum_strength = 0,
  sum_maxStrength = 0,
  strengthMax = 0;
  for (var i = 0; i < weather_day.length; i++){
    var temp = weather_day[i]
    var direction = temp["Windrichting"].trim() % 360
    sum_direction += parseInt(direction,10)
    var strength = temp["Windsnelheid"].trim()
    sum_strength += parseInt(strength,10)
    var maxStrength = temp["Windstoot"].trim()
    if (maxStrength > strengthMax){
      strengthMax = maxStrength*0.1
    }
    sum_maxStrength += parseInt(maxStrength,10)
  }
  var avrDirection = (sum_direction/weather_day.length)
  var avrStrength = (sum_strength/weather_day.length)
  var avrMaxStrength = (sum_maxStrength/weather_day.length)
  var avrStrength = roundToTwo(avrStrength*0.1)

  // Define and rotate the main arrow depending on the average wind direction.
  var g = svg.append("g")
    .attr("id", "windArrow")
  g.attr("transform", "rotate(" + avrDirection + "," + width_wind/2 + "," + height_wind/2 + ")")
  // Define arrow
  g.append("line")
    .attr("x1", width_wind/2)
    .attr("y1", height_wind/2)
    .attr("x2", width_wind/2)
    .attr("y2", height_wind/5)
    .attr("stroke-width", 5)
    .attr("stroke", "blue");
  g.append("polygon")
    .attr("points", (width_wind/2 - 5) + "," + height_wind/5  + " " + (width_wind/2) + "," + (height_wind/5 - 10) + " " + (width_wind/2 + 5) + "," + height_wind/5)
    .attr("stroke-width", 4)
    .attr("fill", "blue")
    .attr("stroke", "blue")
    .style("opacity", "1")

  // Add information to the wind div.
  var div = d3.select("#infoUpdate")
  div.style("opacity", "1")
  div.html("Gemiddelde snelheid:
" + avrStrength + " m/s
 Hardste windstoot:
" + strengthMax + " m/s
")

  // A second arrow is used to show hourly wind directions and is defined here. Rotation is done in redirectArrow.
  var optionalArrow = svg.append("g")
    .attr("class", "optionalArrow")
    .style("opacity", "0")
  optionalArrow.append("line")
    .attr("x1", width_wind/2)
    .attr("y1", height_wind/2)
    .attr("x2", width_wind/2)
    .attr("y2", height_wind/5)
    .attr("stroke-width", 5)
    .attr("stroke", "green");
  optionalArrow.append("polygon")
    .attr("points", (width_wind/2 - 5) + "," + height_wind/5  + " " + (width_wind/2) + "," + (height_wind/5 - 10) + " " + (width_wind/2 + 5) + "," + height_wind/5)
    .attr("stroke-width", 4)
    .attr("fill", "green")
    .attr("stroke", "green")
  return weather_day;
}

// Draw the actual graph.
function drawScatter(DataSelection, results, day_results, weather_day, weather){
  var graph = d3.select("#container_scatter")
    .style("opacity", "1")
  var info = d3.select(".infobox")
    .style("opacity", "0")

  var svg = d3.select("#scatter_results").append("g")

  // reach the data with d3.
  var parseTime = d3.time.format("%H:%M").parse
  d3.json(DataSelection, function() {
    DataSelection.forEach(function(d) {
    d.baan =+ d[4]
    d.startTijd = parseTime(d[1])

    d.crew = d[5]
    d.finishtime = d.crew["results"]["finish"]["time"]
    d.finishPos =+ d.crew["results"]["finish"]["position"]
    d.radius = 20-3*d.finishPos
    })

  // Set the domain
  var xDomain = d3.extent(DataSelection, function(d) { return d.baan; })
  var yDomain = d3.extent(DataSelection, function(d) { return d.startTijd; })

  // Set the scale
  var xScale = d3.scale.linear().range([left_pad, width - padding*2]).domain(xDomain).nice()
  var yScale = d3.time.scale().range([padding, height - padding]).domain(yDomain).nice()

  // create the axis
  var yAxis = d3.svg.axis().scale(yScale).orient('left')
  var xAxis = d3.svg.axis().scale(xScale).orient('bottom')
    .ticks(6)
    .tickFormat(function (d, i) {
        return ['0', '1', '2', '3', '4', '5', '6', '7'][d];
    });

  // Create the Axis for the graph.
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0, 20)")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("y", "-7")
      .attr("x", "250")
      .style("text-anchor", "left")
      .text("Baan");

  svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate("+ (left_pad - padding/2) + ",0)")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", height)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Tijd")

  // Add the data to the graph as ellipses.
  svg.selectAll(".dot")
      .data(DataSelection)
  .enter().append("ellipse")
    .attr("class", "dot")
    .attr("ry", 5)
    .attr("rx", function (d) { return d.radius*1.5; })
    .attr("cx", function(d) { return xScale(d.baan); })
    .attr("cy", function(d) { return yScale(d.startTijd); })
    .attr('pointer-events', 'all')
    .style("fill", "red")
    .on("mouseover", function(d){
    showCrewTooltip()
    })
    .on("mouseout", function(d){
      hideCrewTooltip()
    })
  eventlistener(results, weather_day, DataSelection, yDomain, yScale)
})
}

// Listen for mouse events.
function eventlistener(results, weather_day, DataSelection,yDomain,yScale){
  var tooltip = d3.select("#tooltip")
    .style("opacity", "0")
  var point = d3.selectAll(".dot")
    .on("mouseover", function(){
      var crew = d3.select(this)
      showCrewTooltip()
      updateCrewTooltip(DataSelection, crew, event);
    })
    .on("mouseout", function(){
      hideCrewTooltip()
    })

  // Get the mouse coördinates if mouse is moved on scatter plot
  var svg = d3.select("#scatter_results")
  svg.on('mousemove', function() {
    var coordinates = d3.mouse(this)
    var xsvg = coordinates[0]
    var ysvg = coordinates[1] - 10;

    // transform the coordinates to a time
    var mouseTime = yScale.invert(ysvg)

    // Use only the hours value of time for redirection of arrow.
    var timeslot = mouseTime.getHours()
    redirectArrow(timeslot,weather_day)

    var i = bisectDate(DataSelection, mouseTime)
    var d = mouseTime

    updateHeatTooltip(i,d, DataSelection)
    mouseMoved()
  })
  svg.on("mouseleave", function(){
    mouseOut(event)
  })
  loadData();
}

/*
 * Rotates arrow in the compass to show hourly wind directions.
 */
function redirectArrow(timeslot,weather_day){
  for (var i = 0; i < weather_day.length; i++){
    var temp = weather_day[i]["Tijd"].trim()
    var svg = d3.select("#static_images").append("svg")
      .attr("id", "wind")
    // Get the width and height of the SVG to determine the middle.
    var width_wind = parseInt(svg.style("width"),10);
    var height_wind = parseInt(svg.style("height"),10);

    // Get the weather data from that hour.
    if (+temp === (+timeslot + 1)){
      var direction =+ weather_day[i]["Windrichting"].trim()
      var arrow = d3.select(".optionalArrow")
        .style("opacity", "1")
        .transition()
        .duration(500)
        .attr("transform", "rotate(" + direction + "," + width_wind/2 + "," + height_wind/2 + ")");

      // Get the strength and max strength for that hour of the day
      var strength = (+weather_day[i]["Windsnelheid"].trim())*0.1
      var maxStrength = (+weather_day[i]["Windstoot"].trim())*0.1

      var div = d3.select("#updateHour")
        .style("opacity", "1");
      div.html("Gemiddelde snelheid:
" + strength + " m/s
 Hardste windstoot:
" + maxStrength + " m/s
")

    }
  }
}

/*
 * Hide the tooltip and arrow showing hourly data when mouse is not on the scatterplot.
 */
function mouseOut(event){
  var div = d3.select("#tooltip")
    .style("opacity", "0")
  var arrow = d3.select(".optionalArrow")
    .style("opacity", "0")
  var div = d3.select("#updateHour")
    .style("opacity", "0");
}

// Make the tooltip for crew information visible
function showCrewTooltip(event){
  var div = d3.select("#crew_tooltip")
    .style("opacity", "1")
}
// Make the tooltip for crew information visible
function hideCrewTooltip(event){
  var div = d3.select("#crew_tooltip")
    .style("opacity", "0")
}

// Change content of Crew tooltip.
function updateCrewTooltip(day_results, crew, event){
  // Use the (in eventlistener) selected data point.
  var info = crew.node().__data__;
  var div = d3.select("#crew_tooltip")

  // Get all the variables for display in the tooltip.
  var tijd = info[1]
  var heat = info[2]
  var crewname = info[3]
  var lane = info[4]

  var pos500 = info[5]["results"]["500m"]["position"]
  var time500 = info[5]["results"]["500m"]["time"]

  var pos1000 = info[5]["results"]["1000m"]["position"]
  var time1000 = info[5]["results"]["1000m"]["time"]

  var pos1500 = info[5]["results"]["1500m"]["position"]
  var time1500 = info[5]["results"]["1500m"]["time"]

  var posFinish = info[5]["results"]["finish"]["position"]
  var timeFinish = info[5]["results"]["finish"]["time"]

  // Add the info to the tooltip
  var div = d3.select("#tooltipTitle")
  div.html(heat + "
")
  var div = d3.select("#tijd_crew")
  div.html("Starttijd: " + tijd)
  var div = d3.select("#ploeg_tooltip")
  div.html("Ploeg: " + crewname)
  var div = d3.select("#tussenstand_tooltip")
  div.html("

 500m:  " + pos500 + "
"
    + "1000m:  " + pos1000 + "
"
    + "1500m:  " + pos1500 + "
"
    + "finish:  " + posFinish + "
")
  var div = d3.select("#crewTooltipTijd")
  div.html("
" + time500 + "
" + time1000 + "
" + time1500 + "
" + timeFinish)
}

function mouseMoved(event){
  showTooltip(event)
  updateHeatTooltip(event)
}

// Set the opacity of the tooltip to 70%
function showTooltip(event){
  var div = d3.select("#tooltip")
    .style("opacity", "1")
}

// update the content of the tooltip for an entire heat.
function updateHeatTooltip(i,d,day_results){
    var heat = []
    var f = day_results[i]

    var starttijd = f.startTijd
    var field = f[2]

    // get all the data points in the same heat as f is.
    for (var x = 0; x < 6; x++) {
      if (i < 6){
        var temp = i + x;
        var ploeg_heat = day_results[temp]
        if (ploeg_heat[2] === field){
          addCrew(ploeg_heat, heat)
        }
      }
      else{
        var temp = i - x,
        temp2 = i + x;
        var ploeg_heat = day_results[temp]
        var ploeg2_heat = day_results[temp2]
        if (ploeg_heat[2] === field){
          addCrew(ploeg_heat, heat)
        }
        if (ploeg2_heat[2] === field){
          addCrew(ploeg2_heat, heat)
        }
      }
    }
    var baan = []
    for (var j = 0; j < heat.length; j++){
      var ploeg_overview = heat[j]

      // Get the time of the winning crew
      var position = ploeg_overview[5]["results"]["finish"]["position"]
      if (position == 1)
        var time = ploeg_overview[5]["results"]["finish"]["time"]

      //get the crewname for the appropriate lanes
      var lane = ploeg_overview[4]
      if (lane == 1)
        baan[0] = ploeg_overview[3]
      if (lane == 2)
        baan[1] = ploeg_overview[3]
      if (lane == 3)
        baan[2] = ploeg_overview[3]
      if (lane == 4)
        baan[3] = ploeg_overview[3]
      if (lane == 5)
        baan[4] = ploeg_overview[3]
      if (lane == 6)
        baan[5] = ploeg_overview[3]
      if (lane == 7)
        baan[6] = ploeg_overview[3]
      if (lane == 8)
        baan[7] = ploeg_overview[3]
    }

    // Set the crewname for a undefined crew in a lane to ----- for nicer display later on.
    for (var j = 0; j < 8; j++){
      var temp = baan[j]
      if (typeof temp == "undefined"){
        baan[j] = " ----- "
      }
    }

  // Add info the the actual tooltip
  var div = d3.select("#veld_tooltip")
  div.html(field)
  var div = d3.select("#tijd_tooltip")
  div.html("
" + "Winnende tijd: " + "" + time + "" + "
")

  // Show the lane positioning of the crews.
  var div = d3.select("#banen_tooltip")
  div.html("
" + "Baan 1: " + baan[0] + "
"
    + "Baan 2: " + baan[1] + "
"
    + "Baan 3: " + baan[2] + "
"
    + "Baan 4: " + baan[3] + "
"
    + "Baan 5: " + baan[4] + "
"
    + "Baan 6: " + baan[5] + "
"
    + "Baan 7: " + baan[6] + "
"
    + "Baan 8: " + baan[7] + "
")
}

/*
 *  Helper functions
 */
// Function to empty an array.
function clearArray(array){
  while(array.length > 0)
  array.pop()
  return array;
}

// Round to two decimals
function roundToTwo(num) {
    return +(Math.round(num + "e+2")  + "e-2");
}

// Functions to check wheater a crew belongs in a heat or not.
function crewExists(crewname, arr) {
  return arr.some(function(el) {
    return el.crewname === crewname;
  })
}
function addCrew(crewname, arr) {
  if (crewExists(crewname, arr)) {
    return false;
  }
  arr.push(crewname)
  return true;
}


text:
<?php

namespace Sylius\Component\User\Security\Generator;

/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
interface GeneratorInterface
{
    /**
     * Generates some random string
     *
     * @param  int    $length determines length of a generated string
     * @return string
     */
    public function generate($length);
}


text:
import { GameBusiness } from "../../data/business/GameBusiness";
import { IGame } from "shared/models";

export class GameManagementWorkflow {
    retrieveGameById(id: string, successCallback: (result: IGame) => void, errorCallback?: (error: any) => void) {
        var gameBusiness = new GameBusiness();
        gameBusiness.findById(id, (error, result) => {
            if (error) errorCallback({ "error": "error" });
            else successCallback(result);
        });
    }

    retrieveAllGames(successCallback: (result: IGame) => void, errorCallback?: (error: any) => void) {
        var gameBusiness = new GameBusiness();
        gameBusiness.retrieve((error, result) => {
            if (error) errorCallback({ "error": "error" });
            else successCallback(result);
        });
    }

    createGame(game: IGame, successCallback: (result: IGame) => void, errorCallback?: (error: any) => void) {
        var gameBusiness = new GameBusiness();

        gameBusiness.create(game, (error, result) => {
            if (error) errorCallback({ "error": "error" });
            else successCallback(result);
        });
    }
}


text:
package org.sakaiproject.tool.assessment.ui.bean.evaluation;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.jsf.model.PhaseAware;
import org.sakaiproject.tool.assessment.jsf.convert.AnswerSurveyConverter;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.ui.bean.util.Validator;
import org.sakaiproject.tool.assessment.ui.listener.evaluation.HistogramListener;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;

/**
 *
Description: class form for evaluating total scores

 *
 */
public class ExportResponsesBean implements Serializable, PhaseAware {

	/**
	 *
	 */
	private static final long serialVersionUID = 2854656853283125977L;
	/**
	 * Marks the beginning of each new sheet.
	 * If absent, treat as a single-sheet workbook.
	 */
	public static final String NEW_SHEET_MARKER = "<sheet/>";
	public static final String HEADER_MARKER = "";

	public static final String FORMAT = "<format ";
	public static final String FORMAT_BOLD = FORMAT + "bold/>";

	private String assessmentId;
	private String assessmentName;
	private boolean anonymous;

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

	/**
	 * Creates a new TotalScoresBean object.
	 */
	public ExportResponsesBean() {
		log.debug("Creating a new ExportResponsesBean");
	}

	/**
	 * get assessment id
	 *
	 * @return the assessment id
	 */
	public String getAssessmentId() {
		return Validator.check(assessmentId, "0");
	}

	/**
	 * set assessment id
	 *
	 * @param passessmentId the id
	 */
	public void setAssessmentId(String assessmentId) {
		this.assessmentId = assessmentId;
	}

	/**
	 * get assessment name
	 *
	 * @return the name
	 */
	public String getAssessmentName() {
		return Validator.check(assessmentName, "N/A");
	}

	/**
	 * set assessment name
	 *
	 * @param passessmentName the name
	 */
	public void setAssessmentName(String assessmentName) {
		this.assessmentName = assessmentName;
	}

	/**
	 * get anonymous
	 *
	 * @return anonymous
	 */
	public boolean getAnonymous() {
		return anonymous;
	}

	/**
	 * set anonymous
	 *
	 * @param anonymous
	 */
	public void setAnonymous(boolean anonymous) {
		this.anonymous = anonymous;
	}
	// Following three methods are for interface PhaseAware
	public void endProcessValidators() {
		log.debug("endProcessValidators");
	}

	public void endProcessUpdates() {
		log.debug("endProcessUpdates");
	}

	public void startRenderResponse() {
		log.debug("startRenderResponse");
	}

	public void exportExcel(ActionEvent event){
        log.debug("exporting as Excel: assessment id =  " + getAssessmentId());
        // allow local customization of spreadsheet output
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();
        response.reset();	// Eliminate the added-on stuff
        response.setHeader("Pragma", "public");	// Override old-style cache control
        response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");	// New-style
       	writeDataToResponse(getSpreadsheetData(), getDownloadFileName(), response);
       	faces.responseComplete();
    }

    private List<List<Object>> getSpreadsheetData() {
    	TotalScoresBean totalScores = (TotalScoresBean) ContextUtil.lookupBean("totalScores");
    	Map useridMap = totalScores.getUserIdMap(TotalScoresBean.CALLED_FROM_EXPORT_LISTENER);

        HistogramListener histogramListener = new HistogramListener();
  	  	Iterator detailedStats = histogramListener.getDetailedStatisticsSpreadsheetData(assessmentId).iterator();
  	  	detailedStats.next();
  	  	boolean showPartAndTotalScoreSpreadsheetColumns = true;
  		boolean showDetailedStatisticsSheet = (Boolean) detailedStats.next();

  	  	String audioMessage = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","audio_message");
    	String fileUploadMessage = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","file_upload_message");
    	String noSubmissionMessage = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","export_no_submission");
        GradingService gradingService = new GradingService();
        String poolString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","pool");
        String partString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","part");
        String questionString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","question");
        String responseString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","response");
        String rationaleString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","rationale");
        String itemGradingCommentsString = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","grader_comments");
        List exportResponsesDataList = gradingService.getExportResponsesData(assessmentId, anonymous, audioMessage, fileUploadMessage, noSubmissionMessage,
        		showPartAndTotalScoreSpreadsheetColumns, poolString, partString, questionString, responseString, rationaleString, itemGradingCommentsString, useridMap);
        //SAM-1693 the returned list could be null -DH
        List<List<Object>> list = new ArrayList<List<Object>>();
        if (exportResponsesDataList != null) {
        	list = (List<List<Object>>) exportResponsesDataList.get(0);
        }

        // Now insert the header line
        ArrayList<Object> headerList = new ArrayList<Object>();
        headerList.add(HEADER_MARKER);
        if (anonymous) {
  		  headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","sub_id"));
  	  	}
  	  	else {
  		  headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","last_name"));
  		  headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","first_name"));
  		  headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","user_name"));
  		  headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","num_submission"));
  	  	}

        PublishedAssessmentService pubService = new PublishedAssessmentService();
        if (showPartAndTotalScoreSpreadsheetColumns) {
	  	  	int numberOfSections = pubService.getPublishedSectionCount(Long.valueOf(assessmentId)).intValue();
	  	  	if (numberOfSections > 1) {
		  	  	for (int i = 1; i <= numberOfSections; i++) {
		  	  		headerList.add(partString + " " + i + " " + ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","score"));
		    	}
	  	  	}

	        headerList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","tot"));
	        headerList.add(itemGradingCommentsString);
        }
        //SAM-1693 the returned list could be null -DH
        if (exportResponsesDataList != null) {
        	headerList.addAll((ArrayList) exportResponsesDataList.get(1));
        }

  	    list.add(0,headerList);

  		ArrayList<Object> newSheetList;
  	  	newSheetList = new ArrayList<Object>();
  	  	newSheetList.add(NEW_SHEET_MARKER);
  	  	newSheetList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","responses"));
  	  	list.add(0, newSheetList);

  	  	if (showDetailedStatisticsSheet) {
  	  		newSheetList = new ArrayList<Object>();
  	  		newSheetList.add(NEW_SHEET_MARKER);
  	  		newSheetList.add(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","item_analysis"));
  	  		list.add(newSheetList);

        	while (detailedStats.hasNext()) {
        		list.add((List)detailedStats.next());
        	}
        }

        return list;
    }

    /**
     * Generates a default filename (minus the extension) for a download from this Gradebook.
     *
	 * @param   prefix for filename
	 * @return The appropriate filename for the export
	 */
    public String getDownloadFileName() {
		Date now = new Date();
		String dateFormat = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","export_filename_date_format");
		DateFormat df = new SimpleDateFormat(dateFormat, new ResourceLoader().getLocale());
		StringBuilder fileName = new StringBuilder(ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.EvaluationMessages","assessment"));
        if(StringUtils.trimToNull(assessmentName) != null) {
        	assessmentName = assessmentName.replaceAll("\\s", "_"); // replace whitespace with '_'
            fileName.append("-");
            fileName.append(assessmentName);
        }
		fileName.append("-");
		fileName.append(df.format(now));
		return fileName.toString();
	}

	public void writeDataToResponse(List<List<Object>> spreadsheetData, String fileName, HttpServletResponse response) {
		String mimetype = "application/vnd.ms-excel;charset=UTF-8";
		String extension = ".xls";
		int columns = findColumnSize(spreadsheetData);
		if (columns >= 255) {
			// allows for greater than 255 columns - SAK-16560
			mimetype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
			extension = ".xlsx";
			log.info("Samigo export ("+columns+" columns): Using xlsx mimetype: " + mimetype);
		}
		response.setContentType(mimetype);

		String escapedFilename = org.sakaiproject.util.Validator.escapeUrl(fileName);
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String userAgent = request.getHeader("User-Agent");
		response.setHeader("Content-disposition", "attachment; filename=" + escapedFilename + extension	+ "; filename*=UTF-8''" + escapedFilename + extension);

		OutputStream out = null;
		try {
			out = response.getOutputStream();
			getAsWorkbook(spreadsheetData).write(out);
			out.flush();
		} catch (IOException e) {
			if (log.isErrorEnabled()) log.error(e);
		} finally {
			try {
				if (out != null) out.close();
			} catch (IOException e) {
				if (log.isErrorEnabled()) log.error(e);
			}
		}
	}

	protected Workbook getAsWorkbookTest(List<List<Object>> spreadsheetData) {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet();
		Iterator<List<Object>> dataIter = spreadsheetData.iterator();

		// By convention, the first list in the list contains column headers.
		Row headerRow = sheet.createRow((short)0);
		List<Object> headerList = dataIter.next();
		for (short i = 0; i < headerList.size(); i++) {
			createCell(headerRow, i, null).setCellValue(headerList.get(i).toString());
		}
		short rowPos = 1;
		while (dataIter.hasNext()) {
			List<Object> rowData = dataIter.next();
			Row row = sheet.createRow(rowPos++);
			for (short i = 0; i < rowData.size(); i++) {
				Cell cell = createCell(row, i, null);
				Object data = rowData.get(i);
				if (data != null) {
					if (data instanceof Double) {
						cell.setCellValue(((Double)data).doubleValue());
					}
					else {
						cell.setCellValue(data.toString());
					}
				}
			}
		}
		return wb;
	}

	public Workbook getAsWorkbook(List<List<Object>> spreadsheetData) {
        // outer list is rows, inner list is columns (cells in the row)
	    int columns = findColumnSize(spreadsheetData);
		Workbook wb;
		if (columns < 255) {
            log.info("Samigo export ("+columns+" columns): Using xsl format");
		    wb = new HSSFWorkbook();
		} else {
		    // allows for greater than 255 columns - SAK-16560
		    log.info("Samigo export ("+columns+" columns): Using xslx format");
		    wb = new XSSFWorkbook();
		}

		CellStyle boldStyle = wb.createCellStyle();
		Font font = wb.createFont();
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		String fontName = ServerConfigurationService.getString("spreadsheet.font");
		if (fontName != null) {
			font.setFontName(fontName);
		}
		boldStyle.setFont(font);
		CellStyle headerStyle = boldStyle;

		CellStyle cellStyle = null;
		if (fontName != null) {
			font = wb.createFont();
			font.setFontName(fontName);
			cellStyle = wb.createCellStyle();
			cellStyle.setFont(font);
		}

		Sheet sheet = null;

		Iterator<List<Object>> dataIter = spreadsheetData.iterator();

		short rowPos = 0;
		while (dataIter.hasNext()) {
			List<Object> rowData = dataIter.next();

			if (rowData.get(0).toString().equals(NEW_SHEET_MARKER)) {
				 sheet = wb.createSheet(rowData.get(1).toString());
				 rowPos = 0;
			}
			// By convention, the first list in the list contains column headers.
			// This should only happen once and usually only in a single-sheet workbook
			else if (rowData.get(0).toString().equals(HEADER_MARKER)) {
			    if (sheet == null) {
		              sheet = wb.createSheet("responses"); // avoid NPE
			    }
				Row headerRow = sheet.createRow(rowPos++);
				for (short i = 0; i < rowData.size()-1; i++) {
					createCell(headerRow, i, headerStyle).setCellValue(rowData.get(i+1).toString());
				}
			}
			else {
			    if (sheet == null) {
			        sheet = wb.createSheet("responses"); // avoid NPE
			    }
				Row row = sheet.createRow(rowPos++);
				short colPos = 0;
				Iterator colIter = rowData.iterator();
				while (colIter.hasNext()) {
				//for (short i = 0; i < rowData.size(); i++) {
					Cell cell = null;

					//Object data = rowData.get(i);
					Object data = colIter.next();
					if (data != null) {
						if (data.toString().startsWith(FORMAT)) {
							if (data.equals(FORMAT_BOLD)) {
								cell = createCell(row, colPos++, boldStyle);
							}
							data = colIter.next();
						}
						else {
							cell = createCell(row, colPos++, cellStyle);
						}
						if (data != null) {
							if (data instanceof Double) {
								cell.setCellValue(((Double)data).doubleValue());
							} else {
								AnswerSurveyConverter converter = new AnswerSurveyConverter();
								String datac = converter.getAsString(null, null, data.toString());
								// stripping html for export, SAK-17021
								cell.setCellValue(FormattedText.convertFormattedTextToPlaintext(datac));
							}
						}
					}
				}
			}

		}

		return wb;
	}

	private int findColumnSize(List<List<Object>> spreadsheetData) {
        int columns = 0; // the largest number of columns required for a row
	    for (List<Object> list : spreadsheetData) {
            if (list != null && list.size() > columns) {
                columns = list.size();
            }
        }
        return columns;
    }

	private Cell createCell(Row row, short column, CellStyle cellStyle) {
		Cell cell = row.createCell(column);
		//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		if (cellStyle != null) {
			cell.setCellStyle(cellStyle);
		}

		return cell;
	}

}


text:
A small java library for storing data in a zip files under the following assumptions:
- you want to use a single archive to transfer data that would normally exist in multiple files
- the amount of data exceeds the amount of RAM available on your computer
- you may want to manually edit your data using only common software that is freely available for all desktop computers.


text:
(function() {
    'use strict';

    angular.module('seco.facetedSearch')
    .controller('CheckboxFacetController', CheckboxFacetController);

    /* ngInject */
    function CheckboxFacetController($scope, $controller, CheckboxFacet) {
        var args = { $scope: $scope, FacetImpl: CheckboxFacet };
        return $controller('AbstractFacetController', args);
    }
})();


text:
package de.uni.freiburg.iig.telematik.sepia.petrinet.transform;

import de.invation.code.toval.validate.Validate;
import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractFlowRelation;
import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractMarking;
import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractPetriNet;
import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractPlace;
import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractTransition;

public class AndToXorTransformer<P extends AbstractPlace<F,S>,
								 T extends AbstractTransition<F,S>,
								 F extends AbstractFlowRelation<P,T,S>,
								 M extends AbstractMarking<S>,
								 S extends Object>  extends PNTransformer<P,T,F,M,S>{

	protected T andSplit = null;
	protected T andJoin = null;

	public AndToXorTransformer(AbstractPetriNet<P, T, F, M, S> net, T andSplit, T andJoin) {
		super(net);
		Validate.notNull(andSplit);
		Validate.notNull(andJoin);
		this.andSplit = andSplit;
		this.andJoin = andJoin;
	}

	@Override
	public AbstractPetriNet<P, T, F, M, S> applyTransformation() {
		// TODO Auto-generated method stub
		AbstractPetriNet<P,T,F,M,S> result = net.clone();

		return result;
	}
}


text:
<?php
ini_set('include_path', '/var/www/includewww');

include_once 'db_connect.php';
include_once 'functions.php';

sec_session_start();
?>
<!DOCTYPE html>

        <meta name=viewport content="width=device-width, initial-scale=1">
        <meta charset="UTF-8">
        <?php if (login_check($mysqli) == true) : ?>
            <title>VoteCDJ : <?php echo htmlentities($_SESSION['username']); ?></title>
        <?php else : ?>
            <title>VoteCDJ : Erreur</title>
        <?php endif; ?>
        <link rel="stylesheet" href="styles/main.css" />

        <?php if (login_check($mysqli) == true) : ?>

                    Bienvenue <?php echo htmlentities($_SESSION['username']); ?>!

                    <?php
                        $post = $mysqli->query("SELECT * FROM post WHERE grade IN (SELECT grade FROM members WHERE username='{$_SESSION['username']}')");

                        echo "<form action='includewww/vote.php' method='post'>";
                        while($row = $post->fetch_assoc()) {
                            echo "
";
                            echo $row['name'];
                            echo "
";
                            $candidates = $mysqli->query("SELECT * FROM candidates WHERE postid={$row['id']}");
                            while($candidate = $candidates->fetch_assoc()) {
                                echo "<input type='radio' name='", str_replace(" ","", $row['name']), "' value='{$candidate['id']}'>";
                                echo $candidate['name'];
                                echo "
";
                            }
                            echo "
";
                        }
                        echo "<input type='submit' name='submit' value='Soumettre'/>";
                        echo "</form>";
                    ?>

                    Déconnexion

        <?php else : ?>

Vous n'êtes pas autorisé à accéder à cette page. Connectez-vous.

        <?php endif; ?>