text:
<?php

namespace Albatross\AceBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ForecastScopeRepository extends EntityRepository {

    public function findOneByMonthAndBu($date, $bu) {
        $qb = $this->_em->createQueryBuilder();

        if ($bu == null) {
            $qb->select('f')
                    ->from('AlbatrossAceBundle:ForecastScope', 'f')
                    ->leftJoin('f.bu', 'b')
                    ->where('f.month = :date')
                    ->andWhere('b.id is null')
                    ->setMaxResults(1);
            $qb->setParameters(array(
                'date' => $date
            ));
        } else {
            $qb->select('f')
                    ->from('AlbatrossAceBundle:ForecastScope', 'f')
                    ->leftJoin('f.bu', 'b')
                    ->where('f.month = :date')
                    ->andWhere('b.id = :bu')
                    ->setMaxResults(1);
            $qb->setParameters(array(
                'date' => $date,
                'bu' => $bu
            ));
        }

        $query = $qb->getQuery();
        $result = $query->getResult();
        foreach ($result as $re) {
            $result = $re;
        }

        return $result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PHPKitchen\Domain\Specs\Unit\Stubs\Models\Tmux;

use PHPKitchen\Domain\Base\Entity;
use PHPKitchen\Domain\Specs\Unit\Stubs\Models\Dummy\DummyEntity;

/**
 * Represents
 *
 * @property DummyEntity $dummy
 * @property DummyEntity $dummyRecord
 *
 * @package tests\stubs\models\tmux
 * @author Dmitry Kolodko <prowwid@gmail.com>
 */
class TmuxEntity extends Entity {
}


text:
package im.vector.preference;

import android.annotation.SuppressLint;
import android.content.Context;
import android.preference.ListPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import im.vector.R;

/**
 * Customize ListPreference class to add a warning icon to the right side of the list.
 */
public class VectorListPreference extends ListPreference {

    /**
     * Interface definition for a callback to be invoked when the warning icon is clicked.
     */
    public interface OnPreferenceWarningIconClickListener {
        /**
         * Called when a warning icon has been clicked.
         *
         * @param preference The Preference that was clicked.
         */
        void onWarningIconClick(Preference preference);
    }

    //
    private View mWarningIconView;
    private boolean mIsWarningIconVisible = false;
    private OnPreferenceWarningIconClickListener mWarningIconClickListener;

    public VectorListPreference(Context context) {
        super(context);
    }

    public VectorListPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("NewApi")
    public VectorListPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        setWidgetLayoutResource(R.layout.vector_settings_list_preference_with_warning);
        View view = super.onCreateView(parent);

        mWarningIconView = view.findViewById(R.id.list_preference_warning_icon);
        mWarningIconView.setVisibility(mIsWarningIconVisible ? View.VISIBLE : View.GONE);

        mWarningIconView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mWarningIconClickListener) {
                    mWarningIconClickListener.onWarningIconClick(VectorListPreference.this);
                }
            }
        });

        return view;
    }

    /**
     * Sets the callback to be invoked when this warning icon is clicked.
     *
     * @param onPreferenceWarningIconClickListener The callback to be invoked.
     */
    public void setOnPreferenceWarningIconClickListener(OnPreferenceWarningIconClickListener onPreferenceWarningIconClickListener) {
        mWarningIconClickListener = onPreferenceWarningIconClickListener;
    }

    /**
     * Set the warning icon visibility.
     * @param isVisible to display the icon
     */
    public void setWarningIconVisible(boolean isVisible) {
        mIsWarningIconVisible = isVisible;

        if (null != mWarningIconView) {
            mWarningIconView.setVisibility(mIsWarningIconVisible ? View.VISIBLE : View.GONE);
        }
    }
}


text:
package cgeo.geocaching.enumerations;

import cgeo.geocaching.loaders.AbstractSearchLoader.CacheListLoaderType;

import androidx.annotation.NonNull;

public enum CacheListType {
    OFFLINE(true, CacheListLoaderType.OFFLINE, true),
    POCKET(false, CacheListLoaderType.POCKET),
    HISTORY(true, CacheListLoaderType.HISTORY, true),
    NEAREST(false, CacheListLoaderType.NEAREST),
    COORDINATE(false, CacheListLoaderType.COORDINATE),
    KEYWORD(false, CacheListLoaderType.KEYWORD),
    ADDRESS(false, CacheListLoaderType.ADDRESS),
    FINDER(false, CacheListLoaderType.FINDER),
    OWNER(false, CacheListLoaderType.OWNER),
    MAP(false, CacheListLoaderType.MAP);

    /**
     * whether or not this list allows switching to another list
     */
    public final boolean canSwitch;
    public final boolean isStoredInDatabase;

    @NonNull public final CacheListLoaderType loaderType;

    CacheListType(final boolean canSwitch, @NonNull final CacheListLoaderType loaderType) {
        this(canSwitch, loaderType, false);
    }

    CacheListType(final boolean canSwitch, @NonNull final CacheListLoaderType loaderType, final boolean isStoredInDatabase) {
        this.canSwitch = canSwitch;
        this.loaderType = loaderType;
        this.isStoredInDatabase = isStoredInDatabase;
    }

    public int getLoaderId() {
        return loaderType.getLoaderId();
    }

}


text:
package com.cloud.legacymodel.exceptions;

public class ResourceUnavailableException extends CloudException {
    Class<?> _scope;
    long _id;

    public ResourceUnavailableException(final String msg, final Class<?> scope, final long resourceId) {
        this(msg, scope, resourceId, null);
    }

    public ResourceUnavailableException(final String msg, final Class<?> scope, final long resourceId, final Throwable cause) {
        super(new StringBuilder("Resource [").append(scope.getSimpleName()).append(":").append(resourceId).append("] is unreachable: ").append(msg).toString(), cause);
        _scope = scope;
        _id = resourceId;
    }

    public Class<?> getScope() {
        return _scope;
    }

    public long getResourceId() {
        return _id;
    }
}


text:
package org.workcraft.serialisation.xml;

public interface XMLDeserialiser {
    String getClassName();
}


text:
package hipchat

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	"net/url"
	"os"
	"os/user"
	"path/filepath"
	"strconv"
	"strings"
)

const (
	defaultBaseURL = "https://api.hipchat.com/v2/"
)

// Client manages the communication with the HipChat API.
type Client struct {
	authToken string
	BaseURL   *url.URL
	client    *http.Client
	// Room gives access to the /room part of the API.
	Room *RoomService
	// User gives access to the /user part of the API.
	User *UserService
	// Emoticon gives access to the /emoticon part of the API.
	Emoticon *EmoticonService
}

// Links represents the HipChat default links.
type Links struct {
	Self string `json:"self"`
}

// PageLinks represents the HipChat page links.
type PageLinks struct {
	Links
	Prev string `json:"prev"`
	Next string `json:"next"`
}

// ID represents a HipChat id.
// Use a separate struct because it can be a string or a int.
type ID struct {
	ID string `json:"id"`
}

// AuthTest can be set to true to test an auth token.
//
// HipChat API docs: https://www.hipchat.com/docs/apiv2/auth#auth_test
var AuthTest = false

// AuthTestResponse will contain the server response of any
// API calls if AuthTest=true.
var AuthTestResponse = map[string]interface{}{}

// NewClient returns a new HipChat API client. You must provide a valid
// AuthToken retrieved from your HipChat account.
func NewClient(authToken string) *Client {
	baseURL, err := url.Parse(defaultBaseURL)
	if err != nil {
		panic(err)
	}

	c := &Client{
		authToken: authToken,
		BaseURL:   baseURL,
		client:    http.DefaultClient,
	}
	c.Room = &RoomService{client: c}
	c.User = &UserService{client: c}
	c.Emoticon = &EmoticonService{client: c}
	return c
}

// NewRequest creates an API request. This method can be used to performs
// API request not implemented in this library. Otherwise it should not be
// be used directly.
// Relative URLs should always be specified without a preceding slash.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
	rel, err := url.Parse(urlStr)
	if err != nil {
		return nil, err
	}

	if AuthTest {
		// Add the auth_test param
		values := rel.Query()
		values.Add("auth_test", strconv.FormatBool(AuthTest))
		rel.RawQuery = values.Encode()
	}

	u := c.BaseURL.ResolveReference(rel)

	buf := new(bytes.Buffer)
	if body != nil {
		err := json.NewEncoder(buf).Encode(body)
		if err != nil {
			return nil, err
		}
	}

	req, err := http.NewRequest(method, u.String(), buf)
	if err != nil {
		return nil, err
	}

	req.Header.Add("Authorization", "Bearer "+c.authToken)
	req.Header.Add("Content-Type", "application/json")
	return req, nil
}

// NewFileUploadRequest creates an API request to upload a file.
// This method manually formats the request as multipart/related with a single part
// of content-type application/json and a second part containing the file to be sent.
// Relative URLs should always be specified without a preceding slash.
func (c *Client) NewFileUploadRequest(method, urlStr string, v interface{}) (*http.Request, error) {
	rel, err := url.Parse(urlStr)
	if err != nil {
		return nil, err
	}

	u := c.BaseURL.ResolveReference(rel)

	shareFileReq, ok := v.(*ShareFileRequest)
	if !ok {
		return nil, errors.New("ShareFileRequest corrupted")
	}
	path := shareFileReq.Path
	message := shareFileReq.Message

	// Resolve home path
	if strings.HasPrefix(path, "~") {
		usr, _ := user.Current()
		path = strings.Replace(path, "~", usr.HomeDir, 1)
	}

	// Check if file exists
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return nil, err
	}

	// Read file and encode to base 64
	file, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	b64 := base64.StdEncoding.EncodeToString(file)
	contentType := mime.TypeByExtension(filepath.Ext(path))

	// Set proper filename
	filename := shareFileReq.Filename
	if filename == "" {
		filename = filepath.Base(path)
	} else if filepath.Ext(filename) != filepath.Ext(path) {
		filename = filepath.Base(filename) + filepath.Ext(path)
	}

	// Build request body
	body := "--hipfileboundary\n" +
		"Content-Type: application/json; charset=UTF-8\n" +
		"Content-Disposition: attachment; name=\"metadata\"\n\n" +
		"{\"message\": \"" + message + "\"}\n" +
		"--hipfileboundary\n" +
		"Content-Type: " + contentType + " charset=UTF-8\n" +
		"Content-Transfer-Encoding: base64\n" +
		"Content-Disposition: attachment; name=file; filename=" + filename + "\n\n" +
		b64 + "\n" +
		"--hipfileboundary\n"

	b := &bytes.Buffer{}
	b.Write([]byte(body))

	req, err := http.NewRequest(method, u.String(), b)
	if err != nil {
		return nil, err
	}

	req.Header.Add("Authorization", "Bearer "+c.authToken)
	req.Header.Add("Content-Type", "multipart/related; boundary=hipfileboundary")

	return req, err
}

// Do performs the request, the json received in the response is decoded
// and stored in the value pointed by v.
// Do can be used to perform the request created with NewRequest, as the latter
// it should be used only for API requests not implemented in this library.
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if AuthTest {
		// If AuthTest is enabled, the reponse won't be the
		// one defined in the API endpoint.
		err = json.NewDecoder(resp.Body).Decode(&AuthTestResponse)
	} else {
		if c := resp.StatusCode; c < 200 || c > 299 {
			return resp, fmt.Errorf("Server returns status %d", c)
		}

		if v != nil {
			if w, ok := v.(io.Writer); ok {
				io.Copy(w, resp.Body)
			} else {
				err = json.NewDecoder(resp.Body).Decode(v)
			}
		}
	}
	return resp, err
}


text:
adaline
=======

Calculating the weights for an ADALINE using the Delta Rule

This is very simple application for those who learning 'Neural Networks' especially with Phil Picton's book, There really isn't much to it. However I hope, it may be of some interest to people who are learning Neural Networks.


text:
package swingFirst;

import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JTextField;

import javax.swing.JOptionPane;

class MyActionListener implements ActionListener  {
	public void actionPerformed( ActionEvent e) {
		JButton source = ( JButton ) e.getSource();
		String buttonText = source.getText();
		JOptionPane.showMessageDialog(null, "You clicked " + buttonText);
	}
}

public class winUser {

	public static void getWindow()
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JFrame jFrame = new JFrame(" Register User ");

		jFrame.setLayout( new FlowLayout() );
		jFrame.setSize(250, 120);
		jFrame.setLayout( new GridLayout(3,2) );

		jFrame.add( new JLabel("Name: ") );
		jFrame.add( new JTextField() );

		jFrame.add( new JLabel("E-mail: ") );

		jFrame.add( new JTextField() );

		jFrame.add( new JCheckBox("newsletter") );

		JButton button = new JButton("Register");
		button.addActionListener( new MyActionListener() );
		jFrame.getContentPane().add( button );

		jFrame.pack();
		jFrame.setVisible(true);
//		return JFrame;
	}
}


text:
module ApplicationHelper

	NUM_WEEK_DAYS = 7
	MESSAGE_CHECK_USAGE_COMMAND = I18n.t(:check_usage_command)
	NUMBER_REGULAR_EXPRESSION = /^-?[0-9]+$/
	DATE_REGULAR_EXPRESSION   = /^[0-3]?[0-9]\/[0-3]?[0-9]$/
	END_DATE_STRING = "02/07/2017"
	END_STREAM_STRING = "\n-----------------------------------------------\n"
	STRING_TOMORROW_PT_BR = "amanhã"

	def getDayFromString (day)
		currentWeekDay = Time.zone.now.wday

		weekDayRequested = 1

		case day
		when t(:week_day_monday)
			weekDayRequested = daysBefore(currentWeekDay, 1)
		when t(:week_day_tuesday)
			weekDayRequested = daysBefore(currentWeekDay, 2)
		when t(:week_day_wednesday)
			weekDayRequested = daysBefore(currentWeekDay, 3)
		when t(:week_day_thursday)
			weekDayRequested = daysBefore(currentWeekDay, 4)
		when t(:week_day_friday)
			weekDayRequested = daysBefore(currentWeekDay, 5)
		when t(:week_day_saturday)
			weekDayRequested = daysBefore(currentWeekDay, 6)
		when t(:week_day_sunday)
			weekDayRequested = daysBefore(currentWeekDay, 0)
		when t(:week_tomorrow), STRING_TOMORROW_PT_BR
			weekDayRequested = 1
		else
			return nil
		end

		dateRequested = Time.zone.now.day.to_i + weekDayRequested.to_i

		return dateRequested.to_s
	end

	def daysBefore(currentWeekDay, requestedWeekDay)
		difference = requestedWeekDay - currentWeekDay
		if difference < 0
			difference += NUM_WEEK_DAYS
		end
		return difference
	end

	def validateDayFromMonth(day)
		if day > 30 || day < 1
			return I18n.t(:error_invalid_days)
		end
	end

	def validateMonth(month)
		if month < 6 || month > 7
			return I18n.t(:error_invalid_days)
		end
	end

	def validateDateFromInput(day, month)
		return validateDayFromMonth(day) || validateMonth(month)
	end

	def weekDayName(dayNumber)
  		return I18n.t(:day_names)[dayNumber]
	end

end


text:
package integration

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/Jeffail/benthos/v3/internal/integration"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/gofrs/uuid"
	"github.com/ory/dockertest/v3"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func createBucketQueue(s3Port, sqsPort, id string) error {
	endpoint := fmt.Sprintf("http://localhost:%v", s3Port)
	bucket := "bucket-" + id
	sqsQueue := "queue-" + id
	sqsEndpoint := fmt.Sprintf("http://localhost:%v", sqsPort)
	sqsQueueURL := fmt.Sprintf("%v/queue/%v", sqsEndpoint, sqsQueue)

	var s3Client *s3.S3
	if s3Port != "" {
		s3Client = s3.New(session.Must(session.NewSession(&aws.Config{
			S3ForcePathStyle: aws.Bool(true),
			Credentials:      credentials.NewStaticCredentials("xxxxx", "xxxxx", "xxxxx"),
			Endpoint:         aws.String(endpoint),
			Region:           aws.String("eu-west-1"),
		})))
	}

	var sqsClient *sqs.SQS
	if sqsPort != "" {
		sqsClient = sqs.New(session.Must(session.NewSession(&aws.Config{
			Credentials: credentials.NewStaticCredentials("xxxxx", "xxxxx", "xxxxx"),
			Endpoint:    aws.String(sqsEndpoint),
			Region:      aws.String("eu-west-1"),
		})))
	}

	if s3Client != nil {
		if _, err := s3Client.CreateBucket(&s3.CreateBucketInput{
			Bucket: &bucket,
		}); err != nil {
			return err
		}
	}

	if sqsClient != nil {
		if _, err := sqsClient.CreateQueue(&sqs.CreateQueueInput{
			QueueName: aws.String(sqsQueue),
		}); err != nil {
			return err
		}
	}

	if s3Client != nil {
		if err := s3Client.WaitUntilBucketExists(&s3.HeadBucketInput{
			Bucket: &bucket,
		}); err != nil {
			return err
		}
	}

	var sqsQueueArn *string
	if sqsPort != "" {
		res, err := sqsClient.GetQueueAttributes(&sqs.GetQueueAttributesInput{
			QueueUrl:       &sqsQueueURL,
			AttributeNames: []*string{aws.String("All")},
		})
		if err != nil {
			return err
		}
		sqsQueueArn = res.Attributes["QueueArn"]
	}

	if s3Port != "" && sqsPort != "" {
		if _, err := s3Client.PutBucketNotificationConfiguration(&s3.PutBucketNotificationConfigurationInput{
			Bucket: &bucket,
			NotificationConfiguration: &s3.NotificationConfiguration{
				QueueConfigurations: []*s3.QueueConfiguration{
					{
						Events: []*string{
							aws.String("s3:ObjectCreated:*"),
						},
						QueueArn: sqsQueueArn,
					},
				},
			},
		}); err != nil {
			return err
		}
	}
	return nil
}

var _ = registerIntegrationTest("aws", func(t *testing.T) {
	t.Parallel()

	pool, err := dockertest.NewPool("")
	require.NoError(t, err)

	pool.MaxWait = time.Second * 30

	resource, err := pool.RunWithOptions(&dockertest.RunOptions{
		Repository:   "localstack/localstack",
		ExposedPorts: []string{"4566/tcp"},
		Env:          []string{"SERVICES=s3,sqs"},
	})
	require.NoError(t, err)
	t.Cleanup(func() {
		assert.NoError(t, pool.Purge(resource))
	})

	resource.Expire(900)

	servicePort := resource.GetPort("4566/tcp")

	require.NoError(t, pool.Retry(func() error {
		u4, err := uuid.NewV4()
		require.NoError(t, err)

		return createBucketQueue(servicePort, servicePort, u4.String())
	}))

	t.Run("s3_to_sqs", func(t *testing.T) {
		template := `
output:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    path: ${!count("$ID")}.txt
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
    batching:
      count: $OUTPUT_BATCH_COUNT

input:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    delete_objects: true
    sqs:
      url: http://localhost:$PORT/queue/queue-$ID
      key_path: Records.*.s3.object.key
      endpoint: http://localhost:$PORT
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
`
		integration.StreamTests(
			integration.StreamTestOpenClose(),
			// integration.StreamTestMetadata(), Does dumb stuff with rewriting keys.
			// integration.StreamTestSendBatch(10),
			integration.StreamTestSendBatchCount(10),
			integration.StreamTestStreamSequential(10),
			// integration.StreamTestStreamParallel(10),
			// integration.StreamTestStreamParallelLossy(10),
			integration.StreamTestStreamParallelLossyThroughReconnect(10),
		).Run(
			t, template,
			integration.StreamTestOptPreTest(func(t testing.TB, ctx context.Context, testID string, vars *integration.StreamTestConfigVars) {
				require.NoError(t, createBucketQueue(servicePort, servicePort, testID))
			}),
			integration.StreamTestOptPort(servicePort),
			integration.StreamTestOptAllowDupes(),
		)
	})

	t.Run("s3_to_sqs_lines", func(t *testing.T) {
		template := `
output:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    path: ${!count("$ID")}.txt
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
    batching:
      count: $OUTPUT_BATCH_COUNT
      processors:
        - archive:
            format: lines

input:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    delete_objects: true
    codec: lines
    sqs:
      url: http://localhost:$PORT/queue/queue-$ID
      key_path: Records.*.s3.object.key
      endpoint: http://localhost:$PORT
      delay_period: 1s
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
`
		integration.StreamTests(
			integration.StreamTestOpenClose(),
			integration.StreamTestStreamSequential(20),
			integration.StreamTestSendBatchCount(10),
			integration.StreamTestStreamParallelLossyThroughReconnect(20),
		).Run(
			t, template,
			integration.StreamTestOptPreTest(func(t testing.TB, ctx context.Context, testID string, vars *integration.StreamTestConfigVars) {
				if vars.OutputBatchCount == 0 {
					vars.OutputBatchCount = 1
				}
				require.NoError(t, createBucketQueue(servicePort, servicePort, testID))
			}),
			integration.StreamTestOptPort(servicePort),
			integration.StreamTestOptAllowDupes(),
		)
	})

	t.Run("s3", func(t *testing.T) {
		template := `
output:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    path: ${!count("$ID")}.txt
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
    batching:
      count: $OUTPUT_BATCH_COUNT

input:
  aws_s3:
    bucket: bucket-$ID
    endpoint: http://localhost:$PORT
    force_path_style_urls: true
    region: eu-west-1
    delete_objects: true
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
`
		integration.StreamTests(
			integration.StreamTestOpenCloseIsolated(),
			integration.StreamTestStreamIsolated(10),
		).Run(
			t, template,
			integration.StreamTestOptPreTest(func(t testing.TB, ctx context.Context, testID string, vars *integration.StreamTestConfigVars) {
				require.NoError(t, createBucketQueue(servicePort, "", testID))
			}),
			integration.StreamTestOptPort(servicePort),
			integration.StreamTestOptVarOne("false"),
		)
	})

	t.Run("sqs", func(t *testing.T) {
		template := `
output:
  aws_sqs:
    url: http://localhost:$PORT/queue/queue-$ID
    endpoint: http://localhost:$PORT
    region: eu-west-1
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
    max_in_flight: $MAX_IN_FLIGHT
    batching:
      count: $OUTPUT_BATCH_COUNT

input:
  aws_sqs:
    url: http://localhost:$PORT/queue/queue-$ID
    endpoint: http://localhost:$PORT
    region: eu-west-1
    credentials:
      id: xxxxx
      secret: xxxxx
      token: xxxxx
`
		integration.StreamTests(
			integration.StreamTestOpenClose(),
			integration.StreamTestSendBatch(10),
			integration.StreamTestStreamSequential(50),
			integration.StreamTestStreamParallel(50),
			integration.StreamTestStreamParallelLossy(50),
			integration.StreamTestStreamParallelLossyThroughReconnect(50),
		).Run(
			t, template,
			integration.StreamTestOptPreTest(func(t testing.TB, ctx context.Context, testID string, vars *integration.StreamTestConfigVars) {
				require.NoError(t, createBucketQueue("", servicePort, testID))
			}),
			integration.StreamTestOptPort(servicePort),
		)
	})
})


text:
var isGithubDemo = isGithubDemo || false;  // This is for GitHub demo only. Remove it in your project

void function(window, document, undefined) {

  // ES5 strict mode
  "user strict";

  var MIN_COLUMN_COUNT = 3; // minimal column count
  var COLUMN_WIDTH = 220;   // cell width: 190, padding: 14 * 2, border: 1 * 2
  var CELL_PADDING = 26;    // cell padding: 14 + 10, border: 1 * 2
  var GAP_HEIGHT = 15;      // vertical gap between cells
  var GAP_WIDTH = 15;       // horizontal gap between cells
  var THRESHOLD = 2000;     // determines whether a cell is too far away from viewport (px)

  var columnHeights;        // array of every column's height
  var columnCount;          // number of columns
  var noticeDelay;          // popup notice timer
  var resizeDelay;          // resize throttle timer
  var scrollDelay;          // scroll throttle timer
  var managing = false;     // flag for managing cells state
  var loading = false;      // flag for loading cells state

  var noticeContainer = document.getElementById('notice');
  var cellsContainer = document.getElementById('cells');
  var cellTemplate = document.getElementById('template').innerHTML;

  // Cross-browser compatible event handler.
  var addEvent = function(element, type, handler) {
    if(element.addEventListener) {
      addEvent = function(element, type, handler) {
        element.addEventListener(type, handler, false);
      };
    } else if(element.attachEvent) {
      addEvent = function(element, type, handler) {
        element.attachEvent('on' + type, handler);
      };
    } else {
      addEvent = function(element, type, handler) {
        element['on' + type] = handler;
      };
    }
    addEvent(element, type, handler);
  };

  // Get the minimal value within an array of numbers.
  var getMinVal = function(arr) {
    return Math.min.apply(Math, arr);
  };

  // Get the maximal value within an array of numbers.
  var getMaxVal = function(arr) {
    return Math.max.apply(Math, arr);
  };

  // Get index of the minimal value within an array of numbers.
  var getMinKey = function(arr) {
    var key = 0;
    var min = arr[0];
    for(var i = 1, len = arr.length; i < len; i++) {
      if(arr[i] < min) {
        key = i;
        min = arr[i];
      }
    }
    return key;
  };

  // Get index of the maximal value within an array of numbers.
  var getMaxKey = function(arr) {
    var key = 0;
    var max = arr[0];
    for(var i = 1, len = arr.length; i < len; i++) {
      if(arr[i] > max) {
        key = i;
        max = arr[i];
      }
    }
    return key;
  };

  // Pop notice tag after user liked or marked an item.
  var updateNotice = function(event) {
    clearTimeout(noticeDelay);
    var e = event || window.event;
    var target = e.target || e.srcElement;
    if(target.tagName == 'SPAN') {
      var targetTitle = target.parentNode.tagLine;
      noticeContainer.innerHTML = (target.className == 'like' ? 'Liked ' : 'Marked ') + '<strong>' + targetTitle + '</strong>';
      noticeContainer.className = 'on';
      noticeDelay = setTimeout(function() {
        noticeContainer.className = 'off';
      }, 2000);
    }
  };

  // Calculate column count from current page width.
  var getColumnCount = function() {
    return Math.max(MIN_COLUMN_COUNT, Math.floor((document.body.offsetWidth + GAP_WIDTH) / (COLUMN_WIDTH + GAP_WIDTH)));
  };

  // Reset array of column heights and container width.
  var resetHeights = function(count) {
    columnHeights = [];
    for(var i = 0; i < count; i++) {
      columnHeights.push(0);
    }
    cellsContainer.style.width = (count * (COLUMN_WIDTH + GAP_WIDTH) - GAP_WIDTH) + 'px';
  };

  // Fetch JSON string via Ajax, parse to HTML and append to the container.
  var appendCells = function(num) {
    if(loading) {
      // Avoid sending too many requests to get new cells.
      return;
    }
    var xhrRequest = new XMLHttpRequest();
    var fragment = document.createDocumentFragment();
    var cells = [];
    var images;
    xhrRequest.open('GET', 'json.php?n=' + num, true);
    xhrRequest.onreadystatechange = function() {
      if(xhrRequest.readyState == 4 && xhrRequest.status == 200) {
        images = JSON.parse(xhrRequest.responseText);
        for(var j = 0, k = images.length; j < k; j++) {
          var cell = document.createElement('div');
          cell.className = 'cell pending';
          cell.tagLine = images[j].title;
          cells.push(cell);
          front(cellTemplate, images[j], cell);
          fragment.appendChild(cell);
        }
        cellsContainer.appendChild(fragment);
        loading = false;
        adjustCells(cells);
      }
    };
    loading = true;
    xhrRequest.send(null);
  };

  // Fake mode, only for GitHub demo. Delete this function in your project.
  var appendCellsDemo = function(num) {
    if(loading) {
      // Avoid sending too many requests to get new cells.
      return;
    }
    var fragment = document.createDocumentFragment();
    var cells = [];
    var images = [0, 286, 143, 270, 143, 190, 285, 152, 275, 285, 285, 128, 281, 242, 339, 236, 157, 286, 259, 267, 137, 253, 127, 190, 190, 225, 269, 264, 272, 126, 265, 287, 269, 125, 285, 190, 314, 141, 119, 274, 274, 285, 126, 279, 143, 266, 279, 600, 276, 285, 182, 143, 287, 126, 190, 285, 143, 241, 166, 240, 190];
    for(var j = 0; j < num; j++) {
      var key = Math.floor(Math.random() * 60) + 1;
      var cell = document.createElement('div');
      cell.className = 'cell pending';
      cell.tagLine = 'demo picture ' + key;
      cells.push(cell);
      front(cellTemplate, { 'title': 'demo picture ' + key, 'src': key, 'height': images[key], 'width': 190 }, cell);
      fragment.appendChild(cell);
    }
    // Faking network latency.
    setTimeout(function() {
      loading = false;
      cellsContainer.appendChild(fragment);
      adjustCells(cells);
    }, 2000);
  };

  // Position the newly appended cells and update array of column heights.
  var adjustCells = function(cells, reflow) {
    var columnIndex;
    var columnHeight;
    for(var j = 0, k = cells.length; j < k; j++) {
      // Place the cell to column with the minimal height.
      columnIndex = getMinKey(columnHeights);
      columnHeight = columnHeights[columnIndex];
      cells[j].style.height = (cells[j].offsetHeight - CELL_PADDING) + 'px';
      cells[j].style.left = columnIndex * (COLUMN_WIDTH + GAP_WIDTH) + 'px';
      cells[j].style.top = columnHeight + 'px';
      columnHeights[columnIndex] = columnHeight + GAP_HEIGHT + cells[j].offsetHeight;
      if(!reflow) {
        cells[j].className = 'cell ready';
      }
    }
    cellsContainer.style.height = getMaxVal(columnHeights) + 'px';
    manageCells();
  };

  // Calculate new column data if it's necessary after resize.
  var reflowCells = function() {
    // Calculate new column count after resize.
    columnCount = getColumnCount();
    if(columnHeights.length != columnCount) {
      // Reset array of column heights and container width.
      resetHeights(columnCount);
      adjustCells(cellsContainer.children, true);
    } else {
      manageCells();
    }
  };

  // Toggle old cells' contents from the DOM depending on their offset from the viewport, save memory.
  // Load and append new cells if there's space in viewport for a cell.
  var manageCells = function() {
    // Lock managing state to avoid another async call. See {Function} delayedScroll.
    managing = true;

    var cells = cellsContainer.children;
    var viewportTop = (document.body.scrollTop || document.documentElement.scrollTop) - cellsContainer.offsetTop;
    var viewportBottom = (window.innerHeight || document.documentElement.clientHeight) + viewportTop;

    // Remove cells' contents if they are too far away from the viewport. Get them back if they are near.
    // TODO: remove the cells from DOM should be better :<
    for(var i = 0, l = cells.length; i < l; i++) {
      if((cells[i].offsetTop - viewportBottom > THRESHOLD) || (viewportTop - cells[i].offsetTop - cells[i].offsetHeight > THRESHOLD)) {
        if(cells[i].className === 'cell ready') {
          cells[i].fragment = cells[i].innerHTML;
          cells[i].innerHTML = '';
          cells[i].className = 'cell shadow';
        }
      } else {
        if(cells[i].className === 'cell shadow') {
          cells[i].innerHTML = cells[i].fragment;
          cells[i].className = 'cell ready';
        }
      }
    }

    // If there's space in viewport for a cell, request new cells.
    if(viewportBottom > getMinVal(columnHeights)) {
      // Remove the if/else statement in your project, just call the appendCells function.
      if(isGithubDemo) {
        appendCellsDemo(columnCount);
      } else {
        appendCells(columnCount);
      }
    }

    // Unlock managing state.
    managing = false;
  };

  // Add 500ms throttle to window scroll.
  var delayedScroll = function() {
    clearTimeout(scrollDelay);
    if(!managing) {
      // Avoid managing cells for unnecessity.
      scrollDelay = setTimeout(manageCells, 500);
    }
  };

  // Add 500ms throttle to window resize.
  var delayedResize = function() {
    clearTimeout(resizeDelay);
    resizeDelay = setTimeout(reflowCells, 500);
  };

  // Initialize the layout.
  var init = function() {
    // Add other event listeners.
    addEvent(cellsContainer, 'click', updateNotice);
    addEvent(window, 'resize', delayedResize);
    addEvent(window, 'scroll', delayedScroll);

    // Initialize array of column heights and container width.
    columnCount = getColumnCount();
    resetHeights(columnCount);

    // Load cells for the first time.
    manageCells();
  };

  // Ready to go!
  addEvent(window, 'load', init);

}(window, document);


text:
namespace SimpleInjector.CodeSamples.Tests.Unit
{
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class ParameterConventionTests
    {
        public interface IService
        {
        }

        public interface IDependency
        {
        }

        [TestMethod]
        public void RegisterConcrete_WithAllValidParameters_Succeeds()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            // Act
            // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
            container.Register<ClassWithOnlyPrimitiveConstructorParams>(
                convention.WithParameter("someValue", "foo"),
                convention.WithParameter(() => DateTime.MinValue),
                convention.WithParameter("name", () => "bar"));

            container.GetInstance<ClassWithOnlyPrimitiveConstructorParams>();
        }

        [TestMethod]
        public void Register_WithAllValidParameters_Succeeds()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            // Act
            // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
            container.Register<IService, ClassWithOnlyPrimitiveConstructorParams>(
                convention.WithParameter("someValue", "foo"),
                convention.WithParameter(() => DateTime.MinValue),
                convention.WithParameter("name", () => "bar"));

            container.GetInstance<ClassWithOnlyPrimitiveConstructorParams>();
        }

        [TestMethod]
        public void RegisterSingleConcrete_WithAllValidParameters_Succeeds()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            // Act
            // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
            container.RegisterSingle<ClassWithOnlyPrimitiveConstructorParams>(
                convention.WithParameter("someValue", "foo"),
                convention.WithParameter(() => DateTime.MinValue),
                convention.WithParameter("name", () => "bar"));

            container.GetInstance<ClassWithOnlyPrimitiveConstructorParams>();
        }

        [TestMethod]
        public void RegisterSingle_WithAllValidParameters_Succeeds()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            // Act
            // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
            container.RegisterSingle<IService, ClassWithOnlyPrimitiveConstructorParams>(
                convention.WithParameter("someValue", "foo"),
                convention.WithParameter(() => DateTime.MinValue),
                convention.WithParameter("name", () => "bar"));

            container.GetInstance<ClassWithOnlyPrimitiveConstructorParams>();
        }

        [TestMethod]
        public void GetInstance_TypeWithAllValidParametersRegistered_InjectsExpectedValues()
        {
            // Arrange
            string someValue = "foo";
            DateTime now = new DateTime(2012, 03, 4);
            string name = "bar";

            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
            container.Register<ClassWithOnlyPrimitiveConstructorParams>(
                convention.WithParameter("someValue", someValue),
                convention.WithParameter(() => now),
                convention.WithParameter("name", () => name));

            // Act
            var instance = container.GetInstance<ClassWithOnlyPrimitiveConstructorParams>();

            // Assert
            Assert.AreEqual(now, instance.Now);
            Assert.AreEqual(someValue, instance.SomeValue);
            Assert.AreEqual(name, instance.Name);
        }

        [TestMethod]
        public void Register_TypeWithMixedParameters_Succeeds()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            container.RegisterSingle<IDependency>(new Dependency());

            // Act
            // ctor: ClassWithAPrimitiveConstructorParam(IDependency dependency, Decimal someDecimal)
            container.RegisterSingle<ClassWithAPrimitiveConstructorParam>(
                convention.WithParameter("someDecimal", decimal.MinValue));
        }

        [TestMethod]
        public void GetInstance_Type_TypeWithMixedParameters_InjectsExpectedValues()
        {
            // Arrange
            var expectedDependency = new Dependency();
            decimal expectedDecimal = decimal.MaxValue;

            var container = new Container();
            var convention = new ParameterConvention(container);
            container.Options.RegisterParameterConvention(convention);
            container.RegisterSingle<IDependency>(expectedDependency);

            // ctor: ClassWithAPrimitiveConstructorParam(IDependency dependency, Decimal someDecimal)
            container.RegisterSingle<ClassWithAPrimitiveConstructorParam>(
                convention.WithParameter("someDecimal", expectedDecimal));

            // Act
            var instance = container.GetInstance<ClassWithAPrimitiveConstructorParam>();

            // Assert
            Assert.IsTrue(object.ReferenceEquals(expectedDependency, instance.Dependency));
            Assert.AreEqual(expectedDecimal, instance.SomeDecimal);
        }

        [TestMethod]
        public void Register_WithParameterWithNonExistingParamName_FailsWithExpectedException()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            try
            {
                // Act
                // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
                container.Register<ClassWithOnlyPrimitiveConstructorParams>(
                    convention.WithParameter("notExistingParamName", "foo"),
                    convention.WithParameter(() => DateTime.MinValue),
                    convention.WithParameter("name", () => "bar"));

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ArgumentException ex)
            {
                AssertThat.StringContains(
                    "Parameter with name 'notExistingParamName' of type String is not a parameter of " +
                    "the constructor of type ClassWithOnlyPrimitiveConstructorParams",
                    ex.Message);
            }
        }

        [TestMethod]
        public void Register_AmbiguousWithParameterRegistrations_FailsWithExpectedException()
        {
            // Arrange
            var container = new Container();

            var convention = new ParameterConvention(container);

            container.Options.RegisterParameterConvention(convention);

            try
            {
                // Act
                // ctor: ClassWithPrimiveConstructorParams(string someValue, DateTime now, string name)
                container.Register<ClassWithOnlyPrimitiveConstructorParams>(
                    convention.WithParameter<string>("foo"),
                    convention.WithParameter(() => DateTime.MinValue),
                    convention.WithParameter("name", () => "bar"));

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ArgumentException ex)
            {
                AssertThat.StringContains(
                    "Multiple parameter registrations found for type ClassWithOnlyPrimitiveConstructorParams " +
                    "that match to parameter with name 'name' of type String.",
                    ex.Message);
            }
        }

        public class ClassWithOnlyPrimitiveConstructorParams : IService
        {
            public ClassWithOnlyPrimitiveConstructorParams(string someValue, DateTime now, string name)
            {
                this.SomeValue = someValue;
                this.Now = now;
                this.Name = name;
            }

            public string SomeValue { get; private set; }

            public DateTime Now { get; private set; }

            public string Name { get; private set; }
        }

        public class ClassWithAPrimitiveConstructorParam
        {
            public ClassWithAPrimitiveConstructorParam(IDependency dependency, decimal someDecimal)
            {
                this.Dependency = dependency;
                this.SomeDecimal = someDecimal;
            }

            public IDependency Dependency { get; private set; }

            public decimal SomeDecimal { get; private set; }
        }

        public class Dependency : IDependency
        {
        }
    }
}


text:
\hypertarget{resources_8cpp}{\section{C\-:/\-Users/\-Clarke/\-Documents/\-Codeblocks/\-O\-Omap\-Game/resources.cpp File Reference}
\label{resources_8cpp}\index{C\-:/\-Users/\-Clarke/\-Documents/\-Codeblocks/\-O\-Omap\-Game/resources.\-cpp@{C\-:/\-Users/\-Clarke/\-Documents/\-Codeblocks/\-O\-Omap\-Game/resources.\-cpp}}
}
{\ttfamily \#include \char`\"{}resources.\-h\char`\"{}}\\*
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
void \hyperlink{resources_8cpp_a6a3ca153f0817e8ba91a023b886bb662}{Clear\-Screen} ()
\item
int \hyperlink{resources_8cpp_aa6006a265ed886e0b70e3324ca908ad4}{Random\-Number} (int minimum, int maximum)
\end{DoxyCompactItemize}

\subsection{Function Documentation}
\hypertarget{resources_8cpp_a6a3ca153f0817e8ba91a023b886bb662}{\index{resources.\-cpp@{resources.\-cpp}!Clear\-Screen@{Clear\-Screen}}
\index{Clear\-Screen@{Clear\-Screen}!resources.cpp@{resources.\-cpp}}
\subsubsection[{Clear\-Screen}]{\setlength{\rightskip}{0pt plus 5cm}void Clear\-Screen (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{resources_8cpp_a6a3ca153f0817e8ba91a023b886bb662}

Definition at line 3 of file resources.\-cpp.

\hypertarget{resources_8cpp_aa6006a265ed886e0b70e3324ca908ad4}{\index{resources.\-cpp@{resources.\-cpp}!Random\-Number@{Random\-Number}}
\index{Random\-Number@{Random\-Number}!resources.cpp@{resources.\-cpp}}
\subsubsection[{Random\-Number}]{\setlength{\rightskip}{0pt plus 5cm}int Random\-Number (
\begin{DoxyParamCaption}
\item[{int}]{minimum, }
\item[{int}]{maximum}
\end{DoxyParamCaption}
)}}\label{resources_8cpp_aa6006a265ed886e0b70e3324ca908ad4}
Create a random seed

Generate random number between min and max

Definition at line 40 of file resources.\-cpp.


text:
Aldous
======

Static site generator.

Overview
--------

Aldous is a _backend_ for static site generators that doesn't rely on any file I/O. Its architecture is highly inspired by [Metalsmith](http://www.metalsmith.io/).

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

`$ npm install aldous --save`

Usage
-----

See [examples/](examples/).

**Note**: You can run the test suite by executing `npm test` in the root directory of this module.

License
-------

Aldous is freely distributed under the [MIT license](LICENSE).


text:
#pragma once

#include <string>

namespace indexer {

    enum class SortingProperty {

        SORT_NOTSUPPORTED_COLUMNS,
        SORT_NAME,
        SORT_SIZE,
        SORT_CREATION_TIME,
        SORT_LASTACCESS_TIME,
        SORT_LASTWRITE_TIME,
        SORT_PATH,
        SORT_EXTENSION,
        SORT_TYPE
    };

    SortingProperty PropertyNameToSortingPropertyEnum(std::string prop_name);

    std::wstring SortingPropertyEnumToPropertyName(SortingProperty prop);

} // namespace indexer


text:
package assignment3;

import static org.junit.Assert.*;

import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class VertexTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGetVertex() {
		int id = 10;
		Vertex vertex = Vertex.getVertex(id);
		assertTrue(vertex.id == 10);
	}

	@Test
	public void testGetCostFromStart() {
		int id = 11;
		Vertex vertex = Vertex.getVertex(id);
		assertTrue(vertex.getCostFromStart() > Double.MAX_VALUE);
	}

	@Test
	public void testSetCostFromStartIfSmaller() {
		int id = 12;
		Vertex vertex = Vertex.getVertex(id);
		double newCost = 5;
		vertex.setCostFromStartIfSmaller(newCost);
		assertEquals(newCost, vertex.getCostFromStart(), 0.001);
		;
	}

	@Test
	public void testIsVisited() {
		int id = 13;
		Vertex vertex = Vertex.getVertex(id);
		assertFalse(vertex.isVisited());
	}

	@Test
	public void testSetVisited() {
		int id = 14;
		Vertex vertex = Vertex.getVertex(id);
		vertex.setVisited(true);
		assertTrue(vertex.isVisited());
	}

	@Test
	public void testGetNeighbors() {
		int id = 16;
		Vertex vertex = Vertex.getVertex(id);
		List<Vertex> list = vertex.getNeighbors();
		int[] neighbors = new int[] {0, 29, 82, 118, 172, 261, 329, 331, 332};
		assertTrue(list.size() == neighbors.length);
		for(int i = 0; i < list.size(); i++) {
			assertTrue(list.get(i).id == neighbors[i]);
		}
	}
	/*
	@Test
	public void testPopulateNeighbors() {
		int id = 17;
		Vertex vertex = Vertex.getVertex(id);
		vertex.populateNeighbors();
		assertTrue(vertex.neighbors != null);
	}

	@Test
	public void testGetNeighborIDFromFile() {
		int id = 2;
		Vertex vertex = Vertex.getVertex(id);
		Integer[] neighborsArray = new Integer[] {0, 20, 115, 116, 149, 226, 312, 326, 333, 343};
		List<Integer> actualList = vertex.getNeighborIDFromFile();
		assertArrayEquals(neighborsArray, actualList.toArray(new Integer[actualList.size()]));
	}

	@Test
	public void testReadInputFile() {
		assertTrue(Vertex.readInputFile().length() == 854361);
	}

	@Test
	public void testSameVertex() {
		Vertex vertex0 = Vertex.getVertex(0);
		Vertex vertex1 = Vertex.getVertex(1);
		Vertex vertex0From1 = vertex1.getNeighbors().get(0).getKey();
		assertEquals(vertex0.getCostFromStart(), vertex0From1.getCostFromStart(), 0.001);
		vertex0From1.setCostFromStartIfSmaller(0);
		assertEquals(vertex0.getCostFromStart(), vertex0From1.getCostFromStart(), 0.001);
	}

	@Test
	public void testFindIDAtEnd() {
		int id = 321;
		Vertex vertex = Vertex.getVertex(id);
		int[] neighborsAsSource = new int[] {0, 143, 175};
		Matcher m = vertex.findIDAtEnd();
		for(int i = 0; i < neighborsAsSource.length; i++) {
			m.find();
			assertEquals(String.valueOf(neighborsAsSource[i]), m.group(1));
		}
	}

	@Test
	public void testFindIDAtStart() {
		int id = 84;
		Vertex vertex = Vertex.getVertex(id);
		int[] neighborsAsTarget = new int[] {224, 236, 237, 265, 276, 304, 313};
		Matcher m = vertex.findIDAtStart();
		for(int i = 0; i < neighborsAsTarget.length; i++) {
			m.find();
			assertEquals(String.valueOf(neighborsAsTarget[i]), m.group(1));
		}
	}*/
}


text:
// external
import {
  ComponentFactoryResolver,
  EventEmitter,
  forwardRef,
  Inject,
  Injectable,
  Input,
  Output
} from '@angular/core';
import { component, DynamicComponentClass } from '@ngx-core/common';
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { element } from '@ngx-form/type';
import { FormElementInterface } from '@ngx-form/interface';

// internal
import { ErrorService } from './error.service';
import { FormElementService } from './ngx-form-element.service';
import { ValidatorService } from './validator.service';

/**
 * @export
 * @abstract
 * @class FormElementClass
 * @extends {DynamicComponentClass}
 */
export abstract class FormElementClass extends DynamicComponentClass {
  /**
   * Main @Input('config') that is used to assign all possible `properties` specified in its interface.
   * @type {FormElementInterface}
   * @memberof FormElementClass
   */
  @Input('config') config: FormElementInterface | undefined;

    /**
   * @type {FormGroup}
   * @memberof FormElementClass
   */
  _formGroup: FormGroup;
  @Input('form') set formGroup(formGroup: FormGroup) {
    this._formGroup = formGroup;
  }
  get formGroup(): FormGroup {
    return this._formGroup;
  }

  /**
   * Property of `any` type for html angular attribute `[(NgModel)]` or for formGroup.
   */
  @Input('model') model: Object;

  /**
   * @type {formGroupName}
   * @memberof FormElementClass
  _formGroupName: string;
  @Input() set formGroupName(formGroupName: string) {
    this._formGroupName = formGroupName;
    this.__set('formGroupName');
  }
  get formGroupName(): string {
    return this._formGroupName;
  }
  */

  removed = false;

  // Events
  @Output() cancelled: EventEmitter<any> = new EventEmitter();
  @Output() changed: EventEmitter<any> = new EventEmitter();
  @Output() created: EventEmitter<any> = new EventEmitter();
  @Output() destroyed: EventEmitter<any> = new EventEmitter();
  @Output() submitted: EventEmitter<any> = new EventEmitter();

  /**
   * Creates an instance of FormElementClass.
   * @param {ComponentFactoryResolver} componentFactoryResolver
   * @param {FormBuilder} formBuilder
   * @param {FormElementService} formElementService
   * @param {ValidatorService} validatorService
   * @memberof FormElementClass
   */
  constructor(
    componentFactoryResolver: ComponentFactoryResolver,
    protected formBuilder: FormBuilder,
    protected formElementService: FormElementService, // @Inject(forwardRef(() => FormElementService))
    protected validatorService: ValidatorService, // @Inject(forwardRef(() => ValidatorService))
    protected errorService: ErrorService
  ) {
    super(componentFactoryResolver);
  }

  /**
   * Dynamically create new component from property `elementComponent`
   * @memberof FormElementClass
   */
  public create(): void {
    if (this.config) {
      const createElement = this.formElementService.find(this.config.element);

      if (createElement) {
        this.__create(createElement);
        this.removed = false;
        // add formGroup if not exists
        if (!this.formGroup) {
          this.formGroup = this.formBuilder.group({});
        }
        this.__assign<Object>('model', this.model);
        this.__assign<FormGroup>('formGroup', this.formGroup);
        this.formGroup.controls[this.config.key] = new FormControl();
        this.formControl().markAsTouched();
        this.validatorService.setFormControl(this.formControl());
        this.errorService.setFormControl(this.formControl());

        // assign config to __component instance
        if (this.config) {
          Object.keys(this.config).forEach((prop, index) => {
            if (this.config) {
              this.validatorService.patchValidators(prop, this.config[prop]);

              if (this.config[prop] instanceof Object) {
                Object.keys(this.config[prop]).forEach(subprop => {
                  if (this.config) {
                    this.validatorService.patchValidators(subprop, this.config[prop][subprop]);
                  }
                });
              }
              // assign to created __component instance
              this.__assign(prop, this.config[prop]);
            }
          })

          this.__subscribe('cancelled', this.onCancelled);
          this.__subscribe('changed', this.onChanged);
          this.__subscribe('submitted', this.onSubmitted);

          // subscribe to valueChanges in formGroup
          this.formControl().valueChanges.subscribe(model => this.updateValueAndValidity());
          // this.formControl().statusChanges.subscribe(() => { });

          this.created.emit(true);
          this.destroyed.emit(false);
        }
      } else {
        throw new Error(`
          You need to define FormElementConfig for example as below:
          FormElementModule.forRoot({
              elements: [
                { name: 'input', component: YourInputComponent },
                { name: 'select', component: YourSelectComponent }
              ]
            }),
        `);
      }
    }
  }

  /**
   * returns form control of specified key
   * @param {string} [key]
   * @returns {AbstractControl}
   * @memberof FormElementClass
   */
  public formControl(key?: string): AbstractControl  {
    return this.formGroup.controls[key ? key : ((this.config) ? this.config.key : '')];
  }

  public get(property: string): any {
    return this.__get(property);
  }

  /**
   * On submit emit event `cancelled` and if property `destroy.onCancelled` is true remove `__component` instance
   * @private
   * @memberof FormElementClass
   */
  private onCancelled = (result: any) => {
    this.cancelled.emit(result);
    if (this.config) {
      if (this.config.destroy && this.config.destroy.onCancelled === true) {
        this.remove(this.config.destroy.onCancelled);
      }
    }
  }

  /**
   * On submit emit event `changed` and if property `destroy.onChanged` is true remove `__component` instance
   * @private
   * @memberof FormElementClass
   */
  private onChanged = (result: any) => {
    if (result) {
      this.changed.emit(result);
    }
    if (this.config) {
      if (this.config.destroy && this.config.destroy.onChanged === true) {
        this.remove(true);
      }
    }
  }

  /**
   * On submit emit event `submitted` and if property `destroy.onSubmitted` is true remove `__component` instance
   * @private
   * @memberof FormElementClass
   */
  private onSubmitted = (result: any) => {
    if (result) {
      this.submitted.emit(result);
    }
    if (this.config) {
      if (this.config.destroy && this.config.destroy.onSubmitted === true) {
        this.remove(true);
      }
    }
  }

  /**
   * If true destroy created component in property `__component` and set to null
   * @public
   * @param {boolean} [destroy]
   * @memberof FormElementClass
   */
  public remove(destroy?: boolean): void {
    if (destroy === true) {
      this.__destroy();
      this.removed = true;

      // remove form control
      this.removeFormControl();

      // emit created and destroyed
      this.created.emit(false);
      this.destroyed.emit(true);
    }
  }

  /**
   * Remove formGroup control using formGroup.removeControl with setTimeout
   * @memberof FormElementClass
   */
  removeFormControl() {
    setTimeout(() => {
      if (this.config) {
        this.formGroup.removeControl(this.config.key);
      }
    });
  }

  /**
   * Subscribe to `__component` instance specific `property` name.
   * @param {string} property
   * @param {*} [callback]
   * @param {*} [error]
   * @param {*} [complete]
   * @memberof FormElementClass
   */
  subscribe(property: string, callback?: any, error?: any, complete?: any): void {
    this.__subscribe(property, callback, error, complete);
  }

  /**
   * formGroup updateValueAndValidity with setTimeout
   * @memberof FormElementClass
   */
  updateValueAndValidity() {
    setTimeout(() => {
      this.formGroup.updateValueAndValidity();
    });
  }
}


text:
package ca.uwaterloo.joos.test;

import static org.junit.Assert.fail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import ca.uwaterloo.joos.Main;
import ca.uwaterloo.joos.parser.LR1Parser;
import ca.uwaterloo.joos.scanner.Scanner;
import ca.uwaterloo.joos.weeder.Weeder;

@SuppressWarnings("serial")
@RunWith(value = Parameterized.class)
public class A1Test {

	private static Main instance;
	private static class A1Exception extends Exception {}

	@BeforeClass
	public static void setUp() {
		instance = new Main();

		try {
			File outFile = new File("tmp/a1test.out");
			if (outFile.exists()) {
				outFile.delete();
			}
			System.setOut(new PrintStream(outFile));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}

	@Parameters(name = "{0}")
	public static Collection<Object[]> data() {
		List<Object[]> data = new ArrayList<Object[]>();

		try {
			File directory = new File("testcases/a1");
			File[] testFileList = directory.listFiles();
			for (File testFile: testFileList) {
				data.add( new Object[] { testFile });
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return data;
	}

	private File testFile;

	public A1Test(File testFile) {
		this.testFile = testFile;
	}

	@Test
	public void Test() {
		Exception fileException = extractFileError(testFile);
		Exception realException = null;

		try {
			instance.constructAst(testFile);
			if (fileException != null) {
				System.out.println("Expecting: " + fileException.getClass().getSimpleName() + "\t"
						+ "but got: NoException" + "\t\t"
						+ "[" + testFile.getName() + "]");
				fail("Fail to reject");
			}
		} catch (Exception e) {
			realException = e;
			if (fileException == null) {
				System.out.println("Expecting: NoException" + "\t"
						+ "but got: " + realException.getClass().getSimpleName() + "\t\t"
						+ "[" + testFile.getName() + "]");
				fail("Fail to let it through");
			}
			else if (!realException.getClass().getSimpleName().equals(fileException.getClass().getSimpleName())) {
//				System.out.println("Expecting: " + fileException.getClass().getSimpleName() + "\t"
//						+ "but got: " + realException.getClass().getSimpleName() + "\t\t"
//						+ "[" + testFile.getName() + "]");
			}
		}

//		if(fileException != null && realException != null) {
//			assertEquals(fileException.getClass().getSimpleName(), realException.getClass().getSimpleName());
//		}
//		else {
//			assertSame(fileException, realException);
//		}
	}

	private Exception extractFileError(File testFile) {
		Exception fileExcpetion = null;
		if(testFile.getName().contains("Je"))
		try {
			BufferedReader br = new BufferedReader(new FileReader(testFile));
			String errorMessage = new String();

			while (errorMessage != null && !errorMessage.contains("JOOS1:")) {
				errorMessage = br.readLine();
			}

			if(errorMessage != null) fileExcpetion = extractError(errorMessage);
			if (fileExcpetion == null) {
				fileExcpetion = new A1Exception();
			}
			br.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileExcpetion;
	}

	public Exception extractError(String errorMessage) {
		if (errorMessage.contains("LEXER_EXCEPTION")) {
			return new Scanner.ScanException("");
		} else if (errorMessage.contains("PARSER_EXCEPTION") || errorMessage.contains("SYNTAX_ERROR")) {
			return new LR1Parser.ParseException("");
		} else if (errorMessage.contains("INVALID_INTEGER")) {
			return new Weeder.WeedException("");
		}

		return null;
	}
}


text:
module.exports = function(app, db, apiRouter) {

	var BookingResource = require('express').Router({ mergeParams: true });

    /**
     * Block comment for route
     * @return res
     */
	BookingResource.get('/', function(req, res, next) {
        db.Booking.findAll({ include: [{ all: true, nested: true }]})
        .then(function(booking) {
            res.status(200).json(booking);
        })
        .on('error', function(err) {
            res.status(500).json({ error: err });
        });
	});

    BookingResource.get('/:id', function(req, res, next) {
        db.Booking.find(req.params.id)
            .then(function(booking) {
                if (booking !== null) {
                    res.status(200).json( booking );
                } else {
                    res.status(404).json({ error: 'Booking not Found'});
                }
            })
            .on('error', function(err) {
                res.status(500).json({ error: err });
            });
    });

    BookingResource.post('/', function (req, res) {
        db.Booking.create({
            license_plate: req.body.license_plate,
            booking_date: req.body.booking_date,
            user_id: req.body.user_id,
            car_owner: req.body.car_owner,
            days_of_booking: req.body.days_of_booking

        }).then(function(booking) {
            res.status(201).json( booking );
        }).on('error', function (err) {
            if (err.name === "SequelizeUniqueConstraintError") {
                res.status(409).json({ error: 'Resource Already Exists' });
            } else {
                res.status(500).json({ error: err });
            }
        })
    });

    BookingResource.put('/:id', function (req, res) {
         db.Booking.find(req.params.id)
            .then(function(booking) {
                if (booking !== null) {
                    booking.license_plate = req.body.license_plate;
                    booking.booking_date = req.body.booking_date;
                    booking.user_id = req.body.user_id;
                    booking.car_owner = req.body.car_owner;
                    booking.days_of_booking = req.body.days_of_booking;

                    booking.save()
                        .then(function(booking) {
                            res.status(200).json(booking);
                        })
                        .on('error', function(err) {
                            res.status(500).json({ error: err });
                        })
                } else {
                    res.status(404).json({ error: 'Booking not Found' });
                }
            })
            .on('error', function(err) {
                res.status(500).json({ error: err });
            });
    });

    /**
     * Delete the booking specified and returns 204 No Content if that was successful.
     * If the user does not have access to delete the vehicle, you'll see 403 Forbidden.
     *
     * @param req.param.id
     * @return res
     */
    BookingResource.delete('/:id', function (req, res) {
        db.Booking.find(req.params.id)
            .then(function(booking) {
                if (booking !== null) {
                    booking.destroy()
                        .then(function() {
                            res.status(204).send('');
                        })
                } else {
                    res.status(404).json({ error: 'Booking Not Found'});
                }
            })
            .on('error', function(err) {
                res.status(500).json({ error: err });
            });
    });

    apiRouter.use('/bookings', BookingResource);
}


text:
package com.orhanobut.logger;

import android.util.Log;

class AndroidLogAdapter implements LogAdapter {
  @Override public void d(String tag, String message) {
    Log.d(tag, message);
  }

  @Override public void e(String tag, String message) {
    Log.e(tag, message);
  }

  @Override public void w(String tag, String message) {
    Log.w(tag, message);
  }

  @Override public void i(String tag, String message) {
    Log.i(tag, message);
  }

  @Override public void v(String tag, String message) {
    Log.v(tag, message);
  }

  @Override public void wtf(String tag, String message) {
    Log.wtf(tag, message);
  }
}


text:
#ifndef EL_TRR2K_TNNT_HPP
#define EL_TRR2K_TNNT_HPP

#include "./NTTN.hpp"

namespace El {
namespace trr2k {

// E := alpha A' B + beta C D' + gamma E
template<typename T>
void Trr2kTNNT
( UpperOrLower uplo, Orientation orientA, Orientation orientD,
  T alpha, const AbstractDistMatrix<T>& A, const AbstractDistMatrix<T>& B,
  T beta,  const AbstractDistMatrix<T>& C, const AbstractDistMatrix<T>& D,
  T gamma,       AbstractDistMatrix<T>& E )
{
    DEBUG_ONLY(CSE cse("trr2k::Trr2kTNNT"))
    Trr2kNTTN
    ( uplo, orientD, orientA, beta, C, D, alpha, A, B, gamma, E );
}

} // namespace trr2k
} // namespace El

#endif // ifndef EL_TRR2K_TNNT_HPP


text:
from PreprocessedData import *
from config import get_configs
from load_songs_tools import get_raw_data

def test_PreprocessedSeq():
    configs = get_configs()
    seqs, syms = get_raw_data(configs)
    window = configs["window"]
    seq = seqs[0]
    seq[1] = 'a'
    seq_p = PreprocessedSeq(seq, syms, configs["window"])
    data = PreprocessedData(seqs[:2], syms, window)


text:
    #pragma interface "directory.h"
#endif

//----------------------------------------------------------------------------------------
// Headers
//----------------------------------------------------------------------------------------

#include "app.h"

class DirectoryDialog : public wxDialog
{
public:
    DirectoryDialog( wxWindow* parent );

    wxListCtrl  *OTList;
    wxListCtrl  *PhoneList;
    wxListCtrl  *AccountList;

private:

    void         Show(void);

    wxNotebook  *DirectoryNotebook;
    void         OnAddOTList(wxCommandEvent &event);
    void         OnRemoveOTList(wxCommandEvent &event);
    void         OnDialOTList(wxCommandEvent &event);
    void         OnDialOTListActivatedEvent(wxListEvent &event);
    void         OnAddPhoneList(wxCommandEvent &event);
    void         OnRemovePhoneList(wxCommandEvent &event);
    void         OnDialPhoneList(wxCommandEvent &event);
    void         OnDialPhoneListActivatedEvent(wxListEvent &event);

    DECLARE_EVENT_TABLE()

};

class AddOTListDialog : public wxDialog
{
public:
    AddOTListDialog( wxWindow* parent, wxString selection );

    wxSpinCtrl  *OTNo;
    wxTextCtrl  *Name;
    wxTextCtrl  *Extension;

private:

    void         OnAdd(wxCommandEvent &event);

    DECLARE_EVENT_TABLE()

};

class AddPhoneListDialog : public wxDialog
{
public:
    AddPhoneListDialog( wxWindow* parent, wxString selection );

    wxTextCtrl  *Name;
    wxTextCtrl  *Extension;
    wxTextCtrl  *RingTone;

private:

    void         OnAdd(wxCommandEvent &event);
    void         OnBrowse(wxCommandEvent &event);
    void         OnPreviewRingTone(wxCommandEvent &event);

    DECLARE_EVENT_TABLE()

};

#endif  //_DIRECTORY_H_


text:
title: Structure
page_title: Structure - UI for WinForms Documentation
description: RadRepeatButton provides press-and-hold functionality and it is an ideal UI element for allowing users to control an increasing or decreasing value, such as volume or brightness.
slug: winforms/buttons/repeatbutton/structure
tags: repeatbutton
published: True
position: 1
---

# Structure

This article will show the internal elements structure of __RadRepeatButton__:

>caption Figure 1: RadRepeatButton's elements hierarchy

![buttons-repeatbutton-structure 001](images/buttons-repeatbutton-structure001.png)

1. __FillPrimitive__: represents the repeat button's filling
1. __ImageAndTextLayoutPanel__

	2\.1\. __ImagePrimitive__: represents the repeat button's image

	2\.2\. __TextPrimitive__: represents the repeat button's text
3. __BorderPrimitive__: represents's the repeat button's border

>caption Figure 2: RadRepeatButton's structure

![buttons-repeatbutton-structure 002](images/buttons-repeatbutton-structure002.png)


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->longText('content');
            $table->integer('user_id')->unsigned();
            $table->string('username');
            $table->integer('recommend_count')->default(0);
            $table->integer('read_count')->unsigned()->default(0);
            $table->integer('comments_count')->default(0);
            $table->integer('followers_count')->default(1);
            $table->timestamps();

            $table->foreign('username')
                ->references('name')
                ->on('users')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}


text:
using System;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace DeRange.Config
{
    [Serializable]
    [XmlRoot(ElementName = "KeyboardShortcut")]
    public class KeyboardShortcut
    {
        public bool ShiftModifier { get; set; }
        public bool CtrlModifier { get; set; }
        public bool AltModifier { get; set; }
        public bool WinModifier { get; set; }
        public Keys Key { get; set; }
        public KeyModifier KeyModifier
        {
            get
            {
                KeyModifier mod = KeyModifier.None;

                if (AltModifier)
                {
                    mod |= KeyModifier.Alt;
                }
                if (WinModifier)
                {
                    mod |= KeyModifier.Win;
                }
                if (ShiftModifier)
                {
                    mod |= KeyModifier.Shift;
                }
                if (CtrlModifier)
                {
                    mod |= KeyModifier.Ctrl;
                }

                return mod;
            }
        }
    }
}