text:
'use strict';

var OAuth2 = require('oauth').OAuth2,
    http = require('http'),
    oauthConfig = require('../config/oauth');

var db = require('../models'),
    User = db.User;

var errors = {
  incorrectApiKey: {
    ok: false,
    error: {
      type: "invalid_request",
      message: "The API key provided is not valid"
    }
  },
  keyNotFound: {
    ok: false,
    error: {
      type: "Not Found",
      message: "No API key was found in this request"
    }
  }
};

var getApiKey = function(req) {
  var headerRegex = /^Bearer (\w+)/;

  if (headerRegex.test(req.headers.authorization)) {
    return req.headers.authorization.match(headerRegex)[1];
  }

  if (req.method === "GET") {
    if (req.query.api_key !== undefined && /\w+/.test(req.query.api_key)) {
      return req.query.api_key;
    }
  }

  if (['POST', 'DELETE', 'PUT'].indexOf(req.method) > -1) {
    if (req.body.api_key !== undefined && /\w+/.test(req.body.api_key)) {
      return req.body.api_key;
    }
  }

  return false;
};

var ApplicationController = {};

// TODO - put authenticated user in req
ApplicationController.authenticate = function(req, res, next) {
  var clientId = process.env.CLIENT_ID,
      clientSecret = process.env.CLIENT_SECRET,
      grantType = process.env.GRANT_TYPE,
      clientBasicAuth = new Buffer(clientId + ':' + clientSecret).toString('base64');

  var oauth2 = new OAuth2(
    clientId,
    clientSecret,
    oauthConfig.server,
    oauthConfig.authorisePath,
    oauthConfig.tokenPath,
    { 'Authorization': 'Basic ' + clientBasicAuth }
  );

  var profilePath = oauthConfig.server + oauthConfig.profilePath;

  req.apiKey = getApiKey(req);

  if (!req.apiKey) {
    return res.json(400, errors.keyNotFound);
  }

  User
    .find({ where: { apiKey: req.apiKey } })

    .error(function(err) {
      next(error);
    })

    .success(function(user) {
      if (user) {
        req.user = user;
        var reqPath = '/' + oauthConfig.profilePath +
          '?access_token=' + user.accessToken;
        var authGet = http.get(oauthConfig.server + reqPath, function (authRes) {
            authRes.setEncoding('utf8');
            authRes.on('data', function(data){
              if (JSON.parse(data).username === user.username) {
                next();
              } else {
                return res.json(400, errors.incorrectApiKey);
              }
            });
          }
        );
        authGet.on('error', function(e){
          return res.json(400, e);
        });
        authGet.end();
      } else {
        return res.json(400, errors.incorrectApiKey);
      }
    });
};

module.exports = ApplicationController;


text:
"""."""

class Node(object):
    """Node class."""

    def __init__(self, data=None, next_data=None, previous_data=None):
        """Initialize the node structure."""
        self.data = data
        self.next_node = next_data
        self.previous = previous_data

    def get_data(self):
        """Return current data."""
        return self.data

    def get_next(self):
        """Return next data."""
        return self.next_node

    def set_data(self, newdata):
        """Set next data."""
        self.data = newdata

    def set_next(self, new_next):
        """."""
        self.next_node = new_next

class LinkedList(object):
    """Linked-List class."""

    def __init__(self, iterable=None):
        """Initialize the LinkedList as an instance."""
        self.head = None
        if isinstance(iterable, (str, tuple, list)):
            for item in iterable:
                self.insert(item)

    def insert(self, data):
        """Insert or push a value into the linked-list."""
        new_node = Node(data, self.head)
        new_node.set_next(self.head)
        self.head = new_node

    def display(self):
        """Display the current lnked-list."""
        current = self.head
        final_str = '('
        while current:
            current_data = current.get_data()
            final_str += '{}, '.format(current_data)
            current = current.get_next()
        final_str += ')'
        return final_str

    def size(self):
        """Return the size of the current linked-list."""
        current = self.head
        count = 0
        while current:
            count += 1
            current = current.get_next()
        return count

    def search(self, data):
        """Search for an value in the linked-list."""
        current = self.head
        match = False
        while current and not match:
            if current.get_data() == data:
                match = True
            else:
                current = current.get_next()
        if current is None:
            raise ValueError('Value not in the linked-list')
        return current.data

    def delete(self, data):
        """Delete an value from the linked-list."""
        current = self.head
        previous = None
        while current:
            if current.get_data() == data:
                    break
            else:
                previous = current
                current = current.get_next()
        if current is None:
            raise ValueError("Value not in the linked-list")
        elif previous is None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

    def pop(self):
        """Pop the head of the linked-list."""
        output = self.head
        if not self.head:
            raise IndexError("Nothing left to pop")
        self.head = self.head.get_next()
        return output.data

    def __len__(self):
        """Return the length of linked-list."""
        return self.size()

    def __print__(self):
        """Print out the current linked-list."""
        return self.display()

redpajama_set_name: RedPajamaGithub


text:
/* global TrelloPowerUp */

var t = TrelloPowerUp.iframe();
var board = {};
var cards = {};
var jsonData = {};

t.render(function(){
  // this function we be called once on initial load
  // and then called each time something changes that
  // you might want to react to, such as new data being
  // stored with t.set()
});

function authorizeUser() {
  $.ajax({
    url: 'https://trello.com/b/sPYLhDVX/test-board-4.json',
    dataType: 'JSONP',
    xhrFields: {
      withCredentials: true
    },
    success: function(data){
      console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
    }
  });
  debugger;
//   Trello.authorize({
//     type: 'popup',
//     name: 'Powerup Authorization',
//     scope: {
//       read: 'true',
//       write: 'true' },
//     expiration: 'never',
//     success: authenticationSuccess,
//     error: authenticationFailure
//   });
}

// var authenticationSuccess = function() { console.log('Successful authentication'); };

// var authenticationFailure = function() { console.log('Failed authentication'); };

function getBoard() {
  t.board('id', 'name', 'url', 'shortLink', 'members')
    .then(function(promiseResult) {
      board = promiseResult;
      console.log(board);
    var jsonURL = board.url + ".json";
    $.getJSON(jsonURL, function(data) {
      console.log("hey");
      console.log(data);
      jsonData = data;
    });
  });
}

function getCards() {
  t.cards('id', 'name', 'desc', 'due', 'closed', 'cover', 'attachments', 'members', 'labels', 'url', 'shortLink', 'idList', 'idShort')
    .then(function(promiseResult) {
    cards = promiseResult
      console.log(cards);
  });
}


text:
import os

from envisage.ui.tasks.preferences_pane import PreferencesPane
from pyface.constant import OK
from pyface.file_dialog import FileDialog
from pyface.message_dialog import warning
from pyface.timer.do_later import do_later
from traits.api import Str, Password, Enum, Button, on_trait_change, Color, String, List, File, HasTraits, Bool, Int
from traitsui.api import View, VGroup, HGroup, spring, Label, Spring, \
    EnumEditor, ObjectColumn, TableEditor, UItem
from traitsui.editors import TextEditor
# ============= standard library imports ========================
# ============= local library imports  ==========================
from traitsui.extras.checkbox_column import CheckboxColumn

from pychron.core.helpers.strtools import to_bool, to_csv_str
from pychron.core.pychron_traits import HostStr
from pychron.core.ui.custom_label_editor import CustomLabel
from pychron.core.yaml import yload
from pychron.envisage.icon_button_editor import icon_button_editor
from pychron.envisage.tasks.base_preferences_helper import FavoritesPreferencesHelper
from pychron.paths import paths
from pychron.pychron_constants import NULL_STR

# IPREGEX = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')

def show_databases(kind, host, user, password, schema_identifier='AnalysisTbl', exclude=None):
    records = []
    if kind == 'mysql':
        import pymysql
        if exclude is None:
            exclude = ('information_schema', 'performance_schema', 'mysql')
        try:
            conn = pymysql.connect(host=host, port=3306, user=user,
                                   connect_timeout=0.25,
                                   passwd=password, db='information_schema')
            cur = conn.cursor()
            if schema_identifier:
                sql = '''select TABLE_SCHEMA from TABLES where TABLE_NAME="{}"'''.format(schema_identifier)
            else:
                sql = 'SHOW TABLES'

            cur.execute(sql)
            records = cur.fetchall()

        except BaseException:
            pass
    elif kind == 'mssql':
        import pymssql
        if exclude is None:
            exclude = ('master', 'tempdb', 'model', 'msdb')
        try:
            conn = pymssql.connect(host, user, password, timeout=1)
            cur = conn.cursor()
            sql = 'SELECT * FROM sys.databases'
            cur.execute(sql)
            records = cur.fetchall()
        except pymssql.OperationalError:
            pass

    names = [di[0] for di in records if di[0] not in exclude]
    return names

class ConnectionMixin(HasTraits):
    test_connection_button = Button
    # _test_connection_button = Button

    _connected_label = String('Not Tested')
    _connected_color = Color('orange')
    _adapter_klass = 'pychron.database.core.database_adapter.DatabaseAdapter'
    _names = List
    _test_func = None

    def _reset_connection_label(self, d):
        def func():
            self._connected_label = 'Not Tested'
            self._connected_color = 'orange'

        if d:
            do_later(func)
        else:
            func()

    def _get_connection_dict(self):
        raise NotImplementedError

    def _get_adapter(self):
        args = self._adapter_klass.split('.')
        mod, klass = '.'.join(args[:-1]), args[-1]
        mod = __import__(mod, fromlist=[klass])
        return getattr(mod, klass)

    def _test_connection(self, kw):
        klass = self._get_adapter()
        db = klass(**kw)
        self._connected_label = ''
        if self._test_func:
            db.test_func = self._test_func

        return db.connect(warn=False)

    def _test_connection_button_fired(self):
        kw = self._get_connection_dict()
        self._connected_label = 'Not Connected'
        self._connected_color = 'red'

        if kw is not None:
            c = self._test_connection(kw)

            if c:
                self._connected_color = 'green'
                self._connected_label = 'Connected'
        else:
            warning(None, 'Please select a connection to test')

class ConnectionFavoriteItem(HasTraits):
    enabled = Bool
    name = Str
    dbname = Str
    host = HostStr
    kind = Enum('mysql', 'sqlite', 'mssql', 'postgres', NULL_STR)
    username = Str
    names = List
    password = Password
    schema_identifier = Str
    path = File
    default = Bool
    timeout = Int(5)

    attributes = ('name', 'kind', 'username', 'host', 'dbname', 'password', 'enabled', 'default', 'path', 'timeout')

    def __init__(self, schema_identifier='', attrs=None, kind=None):
        super(ConnectionFavoriteItem, self).__init__()
        self.schema_identifier = schema_identifier
        if kind is not None:
            self.kind = kind

        if attrs:
            attrs = attrs.split(',')

            try:
                self.name, self.kind, self.username, self.host, self.dbname, self.password = attrs
            except ValueError:
                try:
                    self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled = attrs
                    self.enabled = to_bool(enabled)
                except ValueError:
                    try:
                        (self.name, self.kind, self.username, self.host, self.dbname,
                         self.password, enabled, default) = attrs

                        self.enabled = to_bool(enabled)
                        self.default = to_bool(default)
                    except ValueError:
                        try:
                            (self.name, self.kind, self.username, self.host, self.dbname,
                             self.password, enabled, default, path) = attrs
                            self.enabled = to_bool(enabled)
                            self.default = to_bool(default)
                            self.path = path
                        except ValueError:
                            (self.name, self.kind, self.username, self.host, self.dbname,
                             self.password, enabled, default, path, timeout) = attrs
                            self.enabled = to_bool(enabled)
                            self.default = to_bool(default)
                            self.path = path
                            self.timeout = int(timeout)

            self.load_names()

    def load_names(self):
        if self.username and self.host and self.password:
            if self.schema_identifier:
                names = show_databases(self.kind, self.host, self.username, self.password, self.schema_identifier)
                self.names = names

    def to_string(self):
        attrs = [getattr(self, attr) for attr in self.attributes]
        return to_csv_str(attrs)

    # def to_string(self):
    #     attrs = [getattr(self, attr) for attr in ('name', 'kind', 'username', 'host',
    #                                               'dbname', 'password', 'enabled', 'default', 'path')]
    #     return to_csv_str(attrs)

    # return ','.join([str(getattr(self, attr)) for attr in ('name', 'kind', 'username', 'host',
    #                                                        'dbname', 'password', 'enabled', 'default', 'path')])

    def __repr__(self):
        return self.name

class ConnectionPreferences(FavoritesPreferencesHelper, ConnectionMixin):
    preferences_path = 'pychron.database'
    add_favorite_path = Button
    add_favorite_shareable_archive = Button

    _fav_klass = ConnectionFavoriteItem
    _schema_identifier = None
    load_names_button = Button

    def __init__(self, *args, **kw):
        super(ConnectionPreferences, self).__init__(*args, **kw)

    def _add_favorite_shareable_archive_fired(self):
        dlg = FileDialog(action='open', wildcard='*.pz', default_directory=paths.data_dir)
        if dlg.open() == OK:
            if dlg.path:
                yd = yload(dlg.path)
                name = os.path.splitext(os.path.basename(dlg.path))[0]
                path = os.path.join(paths.offline_db_dir, '{}.sqlite'.format(name))
                with open(path, 'wb') as wfile:
                    wfile.write(yd['database'])

                item = self._fav_factory(kind='sqlite', path=path, enabled=True)
                item.trait_set(**{k: yd[k] for k in ['organization',
                                                     'meta_repo_name']})
                item.meta_repo_dir = '{}MetaData'.format(item.organization)

                self._fav_items.append(item)
                self._set_favorites()

    def _add_favorite_path_fired(self):
        dlg = FileDialog(action='open')
        if dlg.open() == OK:
            if dlg.path:
                self._fav_items.append(self._fav_factory(kind='sqlite', path=dlg.path, enabled=True))
                self._set_favorites()

    def _fav_factory(self, fav=None, **kw):
        f = self._fav_klass(self._schema_identifier, fav)
        f.trait_set(**kw)

        return f

    def _get_connection_dict(self):
        obj = self._selected
        if obj is not None:
            return dict(username=obj.username,
                        host=obj.host,
                        password=obj.password,
                        name=obj.dbname,
                        kind=obj.kind, timeout=obj.timeout)

    def __selected_changed(self):
        self._reset_connection_label(True)

    def _load_names_button_fired(self):
        obj = self._selected
        if obj:
            obj.load_names()

    @on_trait_change('_fav_items:+')
    def fav_item_changed(self, obj, name, old, new):
        if name in ('username', 'host', 'password'):
            obj.load_names()
        elif name == 'default':
            if not old:
                if obj.enabled:
                    for fav in self._fav_items:
                        if fav != obj:
                            fav.trait_setq(default=False)
                else:
                    obj.trait_setq(default=False)
            else:
                obj.trait_setq(default=True)

        self._set_favorites()

class ConnectionPreferencesPane(PreferencesPane):
    model_factory = ConnectionPreferences
    category = 'Database'

    def get_columns(self):
        cols = [CheckboxColumn(name='enabled'),
                CheckboxColumn(name='default'),
                ObjectColumn(name='kind'),
                ObjectColumn(name='name'),
                ObjectColumn(name='username'),
                ObjectColumn(name='password',
                             format_func=lambda x: '*' * len(x),
                             editor=TextEditor(password=True)),
                ObjectColumn(name='host'),
                ObjectColumn(name='timeout'),
                ObjectColumn(name='dbname',
                             label='Database',
                             editor=EnumEditor(name='names')),
                ObjectColumn(name='path', style='readonly')]
        return cols

    def get_buttons(self):
        return HGroup(icon_button_editor('add_favorite', 'database_add',
                                         tooltip='Add saved connection'),
                      icon_button_editor('add_favorite_path', 'dbs_sqlite',
                                         tooltip='Add sqlite database'),
                      icon_button_editor('add_favorite_shareable_archive',
                                         'add_archive',
                                         tooltip='Add a shareable archive'),
                      icon_button_editor('delete_favorite', 'delete',
                                         tooltip='Delete saved connection'),
                      icon_button_editor('test_connection_button', 'database_connect',
                                         tooltip='Test connection'),
                      icon_button_editor('load_names_button', 'arrow_refresh',
                                         enabled_when='load_names_enabled',
                                         tooltip='Load available database schemas on the selected server'))

    def get_fav_group(self, edit_view=None):
        cols = self.get_columns()
        editor = TableEditor(columns=cols,
                             selected='_selected',
                             sortable=False)
        if edit_view:
            editor.edit_view = edit_view

        fav_grp = VGroup(UItem('_fav_items',
                               width=100,
                               editor=editor),
                         HGroup(self.get_buttons(),
                                Spring(width=10, springy=False),
                                Label('Status:'),
                                CustomLabel('_connected_label',
                                            label='Status',
                                            weight='bold',
                                            color_name='_connected_color'),
                                spring,
                                show_labels=False))
        return fav_grp

    def traits_view(self):
        fav_grp = self.get_fav_group()
        return View(fav_grp)

# ============= EOF =============================================


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
INA (Int Nannoplankton Assoc) Newsl 10 (1): 31.

#### Original name
null

### Remarks
null


text:
#ifndef CBHELPERATTACHMENT_H_
#define CBHELPERATTACHMENT_H_

namespace Cloudbase {

/**
 * This defines a file attachment for an insert/update request in the helper class.
 */
class CBHelperAttachment {
public:
	std::string fileName; /// The name of the file attached "example.jpg"
	std::string filePath; /// The full path of the file attached
	int fileSize; /// The size of the file attached
};

}

#endif /* CBHELPERATTACHMENT_H_ */


text:
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"testing"
	"time"
)

// Should serve stale object and not hit any other backends, if origin
// is down and object is beyond TTL but still in cache.
func TestServeStaleOriginDown(t *testing.T) {
	ResetBackends(backendsByPriority)

	const expectedBody = "going off like stilton"
	const respTTL = time.Duration(2 * time.Second)
	const respTTLWithBuffer = 5 * respTTL
	headerValue := fmt.Sprintf("max-age=%.0f", respTTL.Seconds())

	// All backends except origin.
	for _, backend := range backendsByPriority[1:] {
		backend.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
			t.Errorf("Server %s received request and it shouldn't have", backend.Name)
			w.Write([]byte(backend.Name))
		})
	}

	req := NewUniqueEdgeGET(t)

	for requestCount := 1; requestCount < 6; requestCount++ {
		switch requestCount {
		case 1: // Request 1 populates cache.
			originServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Cache-Control", headerValue)
				w.Write([]byte(expectedBody))
			})
		case 2: // Request 2+ from stale.
			time.Sleep(respTTLWithBuffer)
			originServer.Stop()
		}

		resp := RoundTripCheckError(t, req)
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Fatal(err)
		}
		if bodyStr := string(body); bodyStr != expectedBody {
			t.Errorf(
				"Request %d received incorrect response body. Expected %q, got %q",
				requestCount,
				expectedBody,
				bodyStr,
			)
		}
	}
}

// Should serve stale object and not hit any other backends, if origin
// returns a 5xx response and object is beyond TTL but still in cache.
func TestServeStaleOrigin5xx(t *testing.T) {
	ResetBackends(backendsByPriority)

	const expectedResponseStale = "going off like stilton"
	const expectedResponseFresh = "as fresh as daisies"

	const respTTL = time.Duration(2 * time.Second)
	const respTTLWithBuffer = 5 * respTTL
	// Allow varnish's beresp.saintmode to expire.
	const waitSaintMode = time.Duration(5 * time.Second)
	headerValue := fmt.Sprintf("max-age=%.0f", respTTL.Seconds())

	// All backends except origin.
	for _, backend := range backendsByPriority[1:] {
		backend.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
			t.Errorf("Server %s received request and it shouldn't have", backend.Name)
			w.Write([]byte(backend.Name))
		})
	}

	req := NewUniqueEdgeGET(t)

	var expectedBody string
	for requestCount := 1; requestCount < 6; requestCount++ {
		switch requestCount {
		case 1: // Request 1 populates cache.
			expectedBody = expectedResponseStale

			originServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Cache-Control", headerValue)
				w.Write([]byte(expectedBody))
			})
		case 2: // Requests 2,3,4 come from stale.
			time.Sleep(respTTLWithBuffer)
			expectedBody = expectedResponseStale

			originServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusServiceUnavailable)
				w.Write([]byte(originServer.Name))
			})
		case 5: // Last request comes directly from origin again.
			time.Sleep(waitSaintMode)
			expectedBody = expectedResponseFresh

			originServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {
				w.Write([]byte(expectedBody))
			})
		}

		resp := RoundTripCheckError(t, req)
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Fatal(err)
		}
		if bodyStr := string(body); bodyStr != expectedBody {
			t.Errorf(
				"Request %d received incorrect response body. Expected %q, got %q",
				requestCount,
				expectedBody,
				bodyStr,
			)
		}
	}
}


text:
<?php require_once('_header.php'); ?>

Orders :: View

There was a problem updating this record.

Please contact administrator.

<?php require_once('_footer.php'); ?>


text:
package com.thoughtworks.go.domain;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ChecksumFileHandlerTest {

    private File file;
    private ChecksumFileHandler checksumFileHandler;

    @Rule
    public final TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Before public void setUp() throws Exception {
        file = temporaryFolder.newFile();
        checksumFileHandler = new ChecksumFileHandler(file);
    }

    @Test
    public void shouldGenerateChecksumFileUrl() throws IOException {
        String url = checksumFileHandler.url("http://foo/go", "cruise/1/stage/1/job");
        assertThat(url, is("http://foo/go/remoting/files/cruise/1/stage/1/job/cruise-output/md5.checksum"));
    }

    @Test
    public void shouldStoreTheMd5ChecksumOnTheAgent() throws IOException {
        checksumFileHandler.handle(new ByteArrayInputStream("Hello World".getBytes()));
        assertThat(FileUtils.readFileToString(file, UTF_8), is("Hello World"));
    }

    @Test
    public void shouldDeleteOldMd5ChecksumFileIfItWasNotFoundOnTheServer() throws IOException {
        StubGoPublisher goPublisher = new StubGoPublisher();
        file.createNewFile();

        boolean isSuccessful = checksumFileHandler.handleResult(HttpServletResponse.SC_NOT_FOUND, goPublisher);
        assertThat(isSuccessful, is(true));
        assertThat(file.exists(), is(false));
    }

    @Test
    public void shouldRetainMd5ChecksumFileIfItIsDownloadedSuccessfully() throws IOException {
        StubGoPublisher goPublisher = new StubGoPublisher();
        file.createNewFile();

        boolean isSuccessful = checksumFileHandler.handleResult(HttpServletResponse.SC_OK, goPublisher);
        assertThat(isSuccessful, is(true));
        assertThat(file.exists(), is(true));

    }

    @Test
    public void shouldHandleResultIfHttpCodeSaysFileNotFound() {
        StubGoPublisher goPublisher = new StubGoPublisher();
        assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_NOT_FOUND, goPublisher), is(true));
        assertThat(goPublisher.getMessage(), containsString(String.format("[WARN] The md5checksum property file was not found on the server. Hence, Go can not verify the integrity of the artifacts.", file)));
    }

    @Test
    public void shouldHandleResultIfHttpCodeIsSuccessful() {
        StubGoPublisher goPublisher = new StubGoPublisher();
        assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_OK, goPublisher), is(true));
    }

    @Test
    public void shouldHandleResultIfHttpCodeSaysFileNotModified() {
        StubGoPublisher goPublisher = new StubGoPublisher();
        assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_NOT_MODIFIED, goPublisher), is(true));
    }

    @Test
    public void shouldHandleResultIfHttpCodeSaysFilePermissionDenied() {
        StubGoPublisher goPublisher = new StubGoPublisher();
        assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_FORBIDDEN, goPublisher), is(false));
    }

    @Test
    public void shouldGetArtifactMd5Checksum() throws IOException {
        checksumFileHandler.handle(new ByteArrayInputStream("Hello!!!1".getBytes()));
        ArtifactMd5Checksums artifactMd5Checksums = checksumFileHandler.getArtifactMd5Checksums();
        assertThat(artifactMd5Checksums, is(new ArtifactMd5Checksums(file)));
    }

    @Test
    public void shouldReturnNullArtifactMd5ChecksumIfFileDoesNotExist() {
        file.delete();
        assertThat(checksumFileHandler.getArtifactMd5Checksums(), is(nullValue()));
    }

}


text:
export const test = "test";

export function foo () {
  const x = { test };
}

//// [shorthandOfExportedEntity01_targetES2015_CommonJS.js]
"use strict";
exports.test = "test";
function foo() {
    const x = { test: exports.test };
}
exports.foo = foo;

//// [shorthandOfExportedEntity01_targetES2015_CommonJS.d.ts]
export declare const test = "test";
export declare function foo(): void;


text:
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.lang.Integer;

/*************************************************************************
* Provide a file history mechanism for the File menu of a parent frame). *
*                                                                        *
* @since JDK 1.2                                                         *
* @Edited by Adam Lara for JDK 6 support and additional features         *
* @original author Klaus Berg                                                     *
*************************************************************************/
public class FileHistory {

   private static final int MAX_ITEM_LEN = 50;
   private static final String FILE_SEPARATOR_STR = System.getProperty("file.separator");
   private static String historySerFile;
   private static int max_itemnames;
   static ArrayList itemnameHistory = new ArrayList(max_itemnames);
   static ArrayList pathnameHistory = new ArrayList(max_itemnames);

   private IFileHistory caller;
   private JComboBox fileMenu;

   // --- IFileHistory interface ----------------------------------------------

   /**
    * Interface that must be implemented by a GUI applcation frame
    * that wants to use the FileHistory class.
    *
    * @author Klaus Berg
    * @since JDK 1.2
    */
   public static interface IFileHistory {

      /**
       * Get the application name to identify the configuration file in the
       * the USER_HOME directory. This name should be unique in this directory.
       *
       * @return the application name
       */
      public String getApplicationName();

      /**
       * Get a handle to the frame's file menu.
       *
       * @return the frame's file menu
       */
      public JComboBox getFileMenu();

      /**
       * Return the size of the main application frame.
       * It is used to center the file history maintenance window.
       *
       * @return the main GUI frame's size
       */
      public Dimension getSize();

      /**
       * Return the main application frame.
       * It is used to center the file history maintenance window.
       *
       * @return the main GUI frame
       */
      public JFrame getFrame();

      /**
        * Perform the load file activity.
        *
        * @param path   the pathname of the loaded file
        */
      public void loadFile(String pathname, String filename);

   }

   // -------------------------------------------------------------------------

   // CONSTRUCTOR: caller is the parent frame that hosts the file menu
   public FileHistory(IFileHistory caller) {
      this.caller = caller;
      historySerFile = "FileHistory.xml";
      String max_itemnames_str = System.getProperty("itemnames.max", "9");
      try {
         max_itemnames = Integer.parseInt(max_itemnames_str);
      }
      catch (NumberFormatException e) {
         System.err.println(e);
         e.printStackTrace();
         System.exit(1);
      }
      if (max_itemnames < 1) {
         max_itemnames = 9;
      }
      fileMenu = caller.getFileMenu();
   }

   /*******************************************************************
   * Initialize itemname and pathname arraylists from historySerFile. *
   * build up the additional entries in the File menu.                *
   *******************************************************************/
   public final void initFileMenuHistory() {
      if (new File(historySerFile).exists()) {
         try {
             FileInputStream fis = new FileInputStream(historySerFile);
             XMLDecoder decoder =
              new XMLDecoder(new BufferedInputStream(fis));
             Integer itemnameCount = (Integer)decoder.readObject();
             decoder.close();
              if (itemnameCount > max_itemnames) {
              itemnameCount = max_itemnames;
            }
            for (int i=0; i<itemnameCount; i++) {
               itemnameHistory.add((String)decoder.readObject());
               pathnameHistory.add((String)decoder.readObject());
               fileMenu.addItem(itemnameHistory.get(i));
            }
            for (int x=0; x<itemnameCount; x++) {
                fileMenu.addActionListener(new ItemListener(x));
            }

            fis.close();

         }
         catch (Exception e) {
            System.err.println("Trouble reading file history entries: " + e);
            e.printStackTrace();
         }
      }
   }

   /***********************************************************
   * Save itemname and pathname arraylists to historySerFile. *
   ***********************************************************/
   public void saveHistoryEntries() {
      try {
       XMLEncoder e = new java.beans.XMLEncoder(
                          new BufferedOutputStream(
                              new FileOutputStream("FileHistory.xml")));
            Integer itemnameCount = new Integer(itemnameHistory.size());
            e.writeObject(itemnameCount);
            for (int i=0; i<itemnameCount; i++) {
            e.writeObject((String)itemnameHistory.get(i));
            e.writeObject((String)pathnameHistory.get(i));
            }

       e.close();

      }
      catch (Exception e) {
         System.err.println("Trouble saving file history entries: " + e);
         e.printStackTrace();
      }
   }

   /*******************************************************************
   * Insert the last loaded pathname into the File menu if it is not  *
   * present yet. Only max pathnames are shown (the max number can be *
   * set in Jmon.ini, default is 9). Every item starts with 	      *
   * "<i>: ", where <i> is in the range [1..max].	              *
   * The loaded itemname will become item number 1 in the list.       *
   *******************************************************************/
   public final void insertPathname(String pathname, String filename) {
         // remove all itemname entries to prepare for re-arrangement
        ActionListener[] menuListeners = fileMenu.getActionListeners();
        for (int x=0; x<menuListeners.length; x++) {
            fileMenu.removeActionListener(menuListeners[x]);
        }
        for (int i=fileMenu.getItemCount()-1, j=0; j < itemnameHistory.size(); i--, j++) {
            fileMenu.removeItemAt(i);//.remove(i);
        }
        if (itemnameHistory.size() == max_itemnames) {  // fileList is full: remove last entry to get space for the first item
            itemnameHistory.remove(max_itemnames-1);
            pathnameHistory.remove(max_itemnames-1);
        }
        itemnameHistory.add(0, filename);
        pathnameHistory.add(0, pathname);
        for (int i=0; i<itemnameHistory.size(); i++) {
            fileMenu.addItem(itemnameHistory.get(i));
        }
        for (int i=0; i<itemnameHistory.size(); i++) {
            fileMenu.addActionListener(new ItemListener(i));
        }

   }

   /**************************************************************
   * Create a JList instance with itemnameHistory as its model.  *
   **************************************************************/
   private final JList createItemList() {
      ListModel model = new ListModel();
      JList list = new JList(model);
      list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      return list;
   }

   // --- Helper classes ------------------------------------------------------

   /***********************************************************
   * Create a tooltip location directly over the menu item,   *
   * ie, left allign the tooltip text in "overlay" technique. *
   ***********************************************************/
   private final class MenuItemWithFixedTooltip extends JButton {

      public MenuItemWithFixedTooltip(String text) {
         super(text);
      }

      public Point getToolTipLocation(MouseEvent e) {
         Graphics g = getGraphics();
         FontMetrics metrics = g.getFontMetrics(g.getFont());
         String prefix = itemnameHistory.size() <= 9 ? "8: " : "88: ";
         int prefixWidth = metrics.stringWidth(prefix);
         int x = JButton.TRAILING + JButton.LEADING -1 + prefixWidth;
         return new Point(x, 0);
      }
   }

   /***********************************
   * Listen to menu item selections.  *
   ***********************************/
   private final class ItemListener implements ActionListener {
      int itemNbr;

      ItemListener(int itemNbr) {
         this.itemNbr = itemNbr;
      }

      public void actionPerformed(ActionEvent e) {
         /*int key=fileMenu.getSelectedIndex();
         if(key==0){
            caller.loadFile((String)pathnameHistory.get(itemNbr), "menu action performed key=0");
         }
         else if(key>=0){
            caller.loadFile((String)pathnameHistory.get(key), "menu action performed key>0");
         }
         else if(key<0){
             return;
         }*/
         //JMenuItem item = (JMenuItem)e.getSource();

         //FileHistory.this.insertPathname(item.getToolTipText());
      }
   }

   /********************************************************
   * The list model for our File History dialog itemList.  *
   ********************************************************/
   private final class ListModel extends AbstractListModel {

      public Object getElementAt(int i) {
         return itemnameHistory.get(i);
      }

      public int getSize() {
         return itemnameHistory.size();
      }

   }

} // end class FileHistory


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<bean parent="dorado.expressionVarsInitializerRegister">
		<property name="contextInitializer">
			<bean
				class="com.bstek.bdf3.security.ui.context.SecurityContextVarsInitializer" />
		</property>
	</bean>

	<bean parent="dorado.packagesConfigLoader">
		<property name="configLocation"
			value="com/bstek/bdf3/security/ui/packages-config.xml">
		</property>
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename"
			value="classpath:org/springframework/security/messages" />
	</bean>
</beans>


text:
@extends('layouts.master')

@section('content-header')

        {{ trans('dynamicfield::dynamicfield.title.optionvalues') }}

 {{ trans('core::core.breadcrumb.home') }}

{{ trans('dynamicfield::dynamicfield.title.optionvalues') }}

@stop

@section('styles')
    {!! Theme::script('js/vendor/ckeditor/ckeditor.js') !!}

    <link href="{{{ Module::asset('dynamicfield:css/jquery-ui.min.css') }}}" rel="stylesheet" type="text/css" />
    <link href="{{{ Module::asset('dynamicfield:css/styles.css') }}}" rel="stylesheet" type="text/css" />
@stop

@section('content')

        {!! Form::open([ 'route' => ['admin.dynamicfield.optionvalues.store']]) !!}

                                        <entities :entities="{{ json_encode($entities) }}"></entities>

                                <button type="submit" class="btn btn-primary btn-flat" name="button" value="index" >

                                    {{ trans('core::core.button.update and back') }}
                                </button>
                                <button type="submit" class="btn btn-primary btn-flat">
                                    {{ trans('core::core.button.update') }}
                                </button>
                                <button class="btn btn-default btn-flat" name="button" type="reset">{{ trans('core::core.button.reset') }}</button>
                                 {{ trans('core::core.button.cancel') }}

        {!! Form::close() !!}

@stop

@section('footer')

@stop
@section('shortcuts')

b

{{ trans('core::core.back to index') }}

@stop

@section('scripts')

@stop


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

namespace S22.Xmpp.Extensions.Socks5 {
	/// <summary>
	/// Represents a SOCKS5 client-greeting message.
	/// </summary>
	[Serializable]
	internal class ClientGreeting {
		/// <summary>
		/// The version of the protocol.
		/// </summary>
		const byte version = 5;
		/// <summary>
		/// A set of authentication methods advertised to the server.
		/// </summary>
		HashSet<AuthMethod> methods = new HashSet<AuthMethod>();

		/// <summary>
		/// An enumerable collection of authentication methods.
		/// </summary>
		public IEnumerable<AuthMethod> Methods {
			get {
				return methods;
			}
		}

		/// <summary>
		/// Serializes the instance into an array of bytes.
		/// </summary>
		/// <returns>An array of bytes representing the instance of the
		/// ClientGreeting class.</returns>
		public byte[] Serialize() {
			ByteBuilder b = new ByteBuilder()
				.Append(version)
				.Append((byte) methods.Count);
			foreach (AuthMethod m in Methods)
				b.Append((byte) m);
			return b.ToArray();
		}

		/// <summary>
		/// Deserializes a new instance of the ClientGreeting class from the
		/// specified byte array.
		/// </summary>
		/// <param name="buffer">An array of bytes to deserialize a new instance
		/// of the ClientGreeting class from.</param>
		/// <returns>An initialized instance of the ClientGreeting class.</returns>
		/// <exception cref="ArgumentNullException">The buffer parameter is
		/// null.</exception>
		/// <exception cref="SerializationException">The specified buffer does
		/// not contain a valid SOCKS5 client-greeting message.</exception>
		public static ClientGreeting Deserialize(byte[] buffer) {
			buffer.ThrowIfNull("buffer");
			using (var ms = new MemoryStream(buffer)) {
				using (BinaryReader r = new BinaryReader(ms)) {
					if (r.ReadByte() != version)
						throw new SerializationException("Invalid SOCKS5 greeting.");
					byte count = r.ReadByte();
					AuthMethod[] methods = new AuthMethod[count];
					for (int i = 0; i < count; i++)
						methods[i] = (AuthMethod) r.ReadByte();
					return new ClientGreeting(methods);
				}
			}
		}

		/// <summary>
		/// Initializes a new instance of the ClientGreeting class.
		/// </summary>
		/// <param name="methods">The authentication methods the client wishes
		/// to advertise.</param>
		public ClientGreeting(params AuthMethod[] methods) {
			if (methods != null) {
				foreach (var m in methods)
						this.methods.Add(m);
			}
		}

		/// <summary>
		/// Initializes a new instance of the ClientGreeting class.
		/// </summary>
		/// <param name="methods">An enumerable collection of authentication
		/// methods the client wishes to advertise.</param>
		/// <exception cref="ArgumentNullException">The methods parameter is
		/// null.</exception>
		public ClientGreeting(IEnumerable<AuthMethod> methods) {
			methods.ThrowIfNull("methods");
			foreach (var m in methods)
				this.methods.Add(m);
		}
	}
}


text:
import models from '../models';
import { verifyDocumentParams, verifyDocUpdateParams,
  verifyIsInt } from '../helpers/validation';
import { getAllDocuments, updateDeleteDoc, getDocById, getDocByUserId,
  getDocumentsByRole } from '../helpers/query';
import { paginateResult } from '../helpers/pagination';

const Document = models.Document;
/**
   * Creates a new instance of document in the database
   * @function createDocument
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - contains the response gotten from the request
   */
const createDocument = (request, response) => {
  verifyDocumentParams(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();
    if (!noErrors) {
      return response.status(412).json({
        detailed_error: validationErrors,
        more_info: 'https://dmsys.herokuapp.com/#creates-new-documents'
      });
    }
    Document.create({
      title: request.body.title,
      content: request.body.content,
      access: request.body.access,
      userId: request.decoded.data.id,
      roleId: request.decoded.data.roleId,
    })
    .then(document => response.status(201).json({
      message: 'Document created',
      document: {
        title: document.title,
        access: document.access,
        ownerId: request.decoded.data.id,
        create_date: document.createdAt,
      }
    })
    )
    .catch(error => response.status(409).json({
      error: 'An unexpected error occurred',
      detailed_error: error,
      more_info: 'https://dmsys.herokuapp.com/#creates-new-documents'
    })
    );
  });
};

/**
   * fetches all documents in the database according to the users' access right
   * @function getAllDocument
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - nformation about the documents
   * in the database
   */
const getAllDocument = (request, response) => {
  const query = getAllDocuments(request);
  Document.findAndCountAll(query)
  .then((documents) => {
    if (documents.count < 1) {
      return response.status(401).json({
        error: 'You dont have access to view available document(s)',
        documents,
        more_info:
          'https://dmsys.herokuapp.com/#find-matching-instances-of-document',
      });
    }
    response.status(200).json(
      paginateResult(documents, query, 'documents')
    );
  })
  .catch(error => response.status(500).json({
    error: 'An unexpected error occurred',
    detailed_error: error,
  }));
};

/**
   * updates document in the database that matches the document ID supplied
   * @function updateDocument
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - information about the document updated
   */
const updateDocument = (request, response) => {
  verifyDocUpdateParams(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();

    if (!noErrors) {
      return response.status(412).json({
        detailed_error: validationErrors,
        more_info: 'https://dmsys.herokuapp.com/#update-document'
      });
    }
    delete request.body.roleId;
    const query = updateDeleteDoc(request);
    Document.update(request.body, query)
    .then((document) => {
      if (document[0] !== 0) {
        return response.status(200).json({
          message: 'Documents updated successfully',
        });
      }
      Document.findAll({ where: { id: request.query.id } })
      .then((notfound) => {
        if (notfound.length < 1) {
          return response.status(404).json({
            error: 'the Document ID does not exist',
            more_info: 'https://dmsys.herokuapp.com/#update-document',
          });
        }
        response.status(401).json({
          error: 'You require access to update this Document',
          more_info: 'https://dmsys.herokuapp.com/#update-document',
        });
      });
    })
    .catch((error) => {
      response.status(400).json({
        error: 'An unexpected error occured',
        detailed_error: error.errors,
        more_info: 'https://dmsys.herokuapp.com/#update-document',
      });
    });
  });
};

/**
   * deletes the document located at the specified ID
   * @function documentById
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - information about the deleted document
   */
const documentById = (request, response) => {
  verifyIsInt(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();
    if (!noErrors) {
      return response.status(412).json({ detailed_error: validationErrors });
    }
    const query = getDocById(request);
    Document.findAll(query)
    .then((document) => {
      if (document.length !== 0) {
        return response.status(200).json({
          message: 'retrieved successfully',
          document
        });
      }
      Document.findAll({ where: { id: request.query.id } })
      .then((notfound) => {
        if (notfound.length < 1) {
          return response.status(404).json({
            error: 'the Document ID does not exist',
            more_info: 'https://dmsys.herokuapp.com/#get-documents-by-id',
          });
        }
        response.status(401).json({
          error: 'You require access to update this Document',
          more_info: 'https://dmsys.herokuapp.com/#get-documents-by-id',
        });
      });
    })
    .catch(error => response.status(500).json({
      error: 'An unexpected error occurred',
      detailed_error: error,
    }));
  });
};

/**
   * deletes the document located at the specified ID
   * @function deleteDocument
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - information about the deleted document
   */
const deleteDocument = (request, response) => {
  verifyIsInt(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();
    if (!noErrors) {
      return response.status(412).json({ detailed_error: validationErrors });
    }
    const query = updateDeleteDoc(request);
    Document.destroy(query)
    .then((document) => {
      if (document !== 0) {
        return response.status(200).json({
          message: 'deleted successfully',
        });
      }
      Document.findAll({ where: { id: request.query.id } })
      .then((notfound) => {
        if (notfound.length < 1) {
          return response.status(404).json({
            error: 'the Document ID does not exist',
            more_info: 'https://dmsys.herokuapp.com/#delete-documents',
          });
        }
        response.status(401).json({
          error: 'You require access to update this Document',
          more_info: 'https://dmsys.herokuapp.com/#delete-documents',
        });
      });
    })
    .catch(error => response.status(500).json({
      error: 'An unexpected error occurred',
      detailed_error: error,
    }));
  });
};

/**
   * gets all documents that matches the userID
   * @function getDocumentByUserId
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - information about the status of the request
   */
const getDocumentByUserId = (request, response) => {
  verifyIsInt(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();
    if (!noErrors) {
      return response.status(412).json({
        error: validationErrors,
        more_info: 'https://dmsys.herokuapp.com/#get-documents-by-userid',
      });
    }
    const query = getDocByUserId(request);
    Document.findAll(query)
    .then((documents) => {
      if (documents.length > 0) {
        return response.status(200).json({
          message: 'retrieved successfully',
          documents
        });
      }
      Document.findAll({ where: { id: request.query.id } })
      .then((notfound) => {
        if (notfound.length < 1) {
          return response.status(404).json({
            error: 'UserId does not exist',
            more_info: 'https://dmsys.herokuapp.com/#get-documents-by-userid',
          });
        }
        response.status(401).json({
          error: 'you do not have access to view available document(s)',
          more_info: 'https://dmsys.herokuapp.com/#get-documents-by-userid',
        });
      });
    })
    .catch(error => response.status(500).json({
      error: 'An unexpected error occurred',
      detailed_error: error,
    }));
  });
};

/**
   * gets all documents that matches the roleId
   * @function getDocumentByRole
   * @param {object} request request
   * @param {object} response response
   * @return {object} object - information about the status of the request
   */
const getDocumentByRole = (request, response) => {
  verifyIsInt(request)
  .then((result) => {
    const validationErrors = result.mapped();
    const noErrors = result.isEmpty();
    if (!noErrors) {
      return response.status(412).json({
        error: validationErrors,
        more_info: 'https://dmsys.herokuapp.com/#get-documents-by-roleid',
      });
    }
    const query = getDocumentsByRole(request);
    Document.findAndCountAll(query)
    .then((documents) => {
      if (documents.count < 1) {
        return response.status(404).json({
          error: 'No document exists with the specified role Id',
          more_info: 'https://dmsys.herokuapp.com/#get-documents-by-roleid',
        });
      }
      response.status(200).json(paginateResult(documents, query, 'documents'));
    })
    .catch(error => response.status(500).json({
      error: 'An unexpected error occurred',
      detailed_error: error,
    }));
  });
};

module.exports = {
  createDocument,
  getAllDocument,
  updateDocument,
  documentById,
  deleteDocument,
  getDocumentByUserId,
  getDocumentByRole,
};


text:
package config

import (
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func Test_LoadEnv(t *testing.T) {
	os.Setenv("PORT", "8001")
	os.Setenv("STATS_AUTO_DISCOVER_WHITE_LIST", "api,foo,bar")
	os.Setenv("BASIC_USERS", "admin:admin,test:test")
	os.Setenv("GITHUB_ORGANIZATIONS", "hellofresh,tests")
	os.Setenv("GITHUB_TEAMS", "hellofresh:tests,tests:devs")
	os.Setenv("JANUS_ADMIN_TEAM", "janus-owners")

	globalConfig, err := LoadEnv()
	require.NoError(t, err)

	assert.Equal(t, 8001, globalConfig.Port)
	assert.Equal(t, 8081, globalConfig.Web.Port)
	assert.Equal(t, "HS256", globalConfig.Web.Credentials.Algorithm)
	assert.Equal(t, uint(0), globalConfig.Stats.AutoDiscoverThreshold)
	assert.Equal(t, []string{"api", "foo", "bar"}, globalConfig.Stats.AutoDiscoverWhiteList)
	assert.Equal(t, "error-log", globalConfig.Stats.ErrorsSection)
	assert.False(t, globalConfig.TLS.IsHTTPS())
	assert.False(t, globalConfig.Tracing.IsGoogleCloudEnabled())
	assert.False(t, globalConfig.Tracing.IsAppdashEnabled())
	assert.Equal(t, map[string]string{"admin": "admin", "test": "test"}, globalConfig.Web.Credentials.Basic.Users)
	assert.Equal(t, map[string]string{"hellofresh": "tests", "tests": "devs"}, globalConfig.Web.Credentials.Github.Teams)
	assert.Equal(t, []string{"hellofresh", "tests"}, globalConfig.Web.Credentials.Github.Organizations)
	assert.Equal(t, "janus-owners", globalConfig.Web.Credentials.JanusAdminTeam)
	assert.True(t, globalConfig.Web.Credentials.Github.IsConfigured())
}


text:
SPEC_BEGIN(InitialTests)

describe(@"RACSerialCommand", ^{

  context(@"will pass", ^{

      it(@"should output 1 2 3", ^{
          __block NSNumber* number = nil;
          RACSerialCommand* command = [[RACSerialCommand alloc] initWithSignalBlock:^RACSignal*(id input){
            NSLog(@"init %@", input);
            number = input;
            RACSignal* signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                [subscriber sendNext:input];
                NSLog(@"sent %@", input);

                [[[RACSignal empty] delay:2.0] subscribeCompleted:^() {
                    [subscriber sendCompleted];
                }];
                 return nil;
            }];

            return signal;
          }];
          RACScheduler* scheduler = [RACScheduler mainThreadScheduler];
          [RACSignal startEagerlyWithScheduler:scheduler block:^(id<RACSubscriber> subscriber){
              [command execute:@(1)];
              [command execute:@(2)];
              [command execute:@(3)];
          }];
        [[expectFutureValue(number) shouldEventuallyBeforeTimingOutAfter(10000.0)] equal:@(3)];
      });
  });
});

SPEC_END


text:
#region License

#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
using Common.Logging.Configuration;

namespace Common.Logging.MultipleLogger
{
    public class ConfigurationSectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            var mainConfigSectionHandler = new Common.Logging.ConfigurationSectionHandler();
            var logSettings = new List<LogSetting>();
            var adapterRegistrations = section.SelectNodes("factoryAdapter");

            //leverage the 'base' config section handler to process ea. individual factoryAdapter listing for us
            foreach (var adapterRegistration in adapterRegistrations)
            {
                var adapterRegistrationNode = adapterRegistration as XmlNode;

                if (null != adapterRegistrationNode)
                {
                    var nodeToParse = WrapAdapterRegistrationNodeInParentNode(adapterRegistrationNode);
                    logSettings.Add(mainConfigSectionHandler.Create(parent as LogSetting, configContext, nodeToParse));
                }
            }

            return logSettings;
        }

        /// <summary>
        /// Wraps the adapter node in parent node.
        /// </summary>
        /// <param name="adapterRegistrationNode">The adapter registration node.</param>
        /// <returns>XmlNode.</returns>
        /// <remarks>the 'base' config section handler expects the factoryAdapter node to *not* be the outer-most Xml parent node
        /// so in order to properly leverage the main config handler for this task we first have to 'wrap' each factoryAdapter entry
        /// in an outer XmlNode before it can be used as input to the main handler to produce an adapter.</remarks>
        private XmlNode WrapAdapterRegistrationNodeInParentNode(XmlNode adapterRegistrationNode)
        {
            var xmlDoc = new XmlDocument();
            var parentNode = xmlDoc.CreateNode(XmlNodeType.Element, "placeholderParent", string.Empty);
            parentNode.AppendChild(xmlDoc.ImportNode(adapterRegistrationNode, true));
            return parentNode;
        }
    }
}