text:
require "test_helper"
require "./test/support/sequel"
require "shrine/plugins/sequel"

describe Shrine::Plugins::Sequel do
  before do
    @shrine = shrine { plugin :sequel }

    user_class = Class.new(Sequel::Model)
    user_class.set_dataset(:users)

    @user     = user_class.new
    @attacher = @shrine::Attacher.from_model(@user, :avatar)
  end

  describe "Attachment" do
    describe "validate" do
      before do
        @shrine.plugin :validation
      end

      it "adds attacher errors to the record" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @attacher.class.validate { errors << "error" }
        @user.avatar = fakeio
        refute @user.valid?
        assert_equal Hash[avatar: ["error"]], @user.errors.to_hash
      end

      it "is skipped if validations are disabled" do
        @shrine.plugin :sequel, validations: false
        @user.class.include @shrine::Attachment.new(:avatar)

        @attacher.class.validate { errors << "error" }
        @user.avatar = fakeio
        assert @user.valid?
      end
    end

    describe "before_save" do
      it "calls Attacher#save if attachment has changed" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.avatar = fakeio
        @user.avatar_attacher.expects(:save).once
        @user.save
      end

      it "doesn't call Attacher#save if attachment has not changed" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.name = "Janko"
        @user.avatar_attacher.expects(:save).never
        @user.save
      end

      it "is skipped when hooks are disabled" do
        @shrine.plugin :sequel, hooks: false
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.avatar = fakeio
        @user.avatar_attacher.expects(:save).never
        @user.save
      end
    end

    describe "after_save" do
      it "finalizes attacher when attachment changes" do
        @user.class.include @shrine::Attachment.new(:avatar)

        previous_file = @attacher.upload(fakeio)
        @user.avatar_data = previous_file.to_json

        @user.avatar = fakeio
        @user.save

        assert_equal :store, @user.avatar.storage_key
        refute previous_file.exists?
      end

      it "persists changes after finalization" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.avatar = fakeio
        @user.save
        @user.reload

        assert_equal :store, @user.avatar.storage_key
      end

      it "performs finalization after the transaction commits" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.avatar = fakeio

        @user.db.transaction do
          @user.save
          assert_equal :cache, @user.avatar.storage_key
        end
        assert_equal :store, @user.avatar.storage_key
      end

      it "ignores validation errors" do
        @user.class.include @shrine::Attachment.new(:avatar)
        @user.instance_eval do
          def validate
            errors.add(:name, "must be present")
          end
        end

        @user.avatar = fakeio
        @user.save(validate: false)
        @user.reload

        assert_equal :store, @user.avatar.storage_key
      end

      it "is skipped when hooks are disabled" do
        @shrine.plugin :sequel, hooks: false
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.avatar = fakeio
        @user.save

        assert_equal :cache, @user.avatar.storage_key
      end
    end

    describe "after_destroy" do
      it "deletes attached files" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @attacher.set @attacher.upload(fakeio)
        @user.save

        @user.destroy

        refute @user.avatar.exists?
      end

      it "is skipped when hooks are disabled" do
        @shrine.plugin :sequel, hooks: false
        @user.class.include @shrine::Attachment.new(:avatar)

        @attacher.set @attacher.upload(fakeio)
        @user.save

        @user.destroy

        assert @user.avatar.exists?
      end
    end

    describe "#_refresh" do
      it "reloads the attacher on Sequel::Model#reload" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save
        @user.avatar_attacher # ensure attacher is memoized

        file = @attacher.upload(fakeio)
        @user.this.update(avatar_data: file.to_json)

        @user.reload

        assert_equal file, @user.avatar
      end

      it "reloads the attacher on Sequel::Model#refresh" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save
        @user.avatar_attacher # ensure attacher is memoized

        file = @attacher.upload(fakeio)
        @user.this.update(avatar_data: file.to_json)

        @user.refresh

        assert_equal file, @user.avatar
      end

      it "reloads the attacher on Sequel::Model#lock!" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save
        @user.avatar_attacher # ensure attacher is memoized

        file = @attacher.upload(fakeio)
        @user.this.update(avatar_data: file.to_json)

        @user.db.transaction { @user.lock! }

        assert_equal file, @user.avatar
      end

      it "preserves state other than the file" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save
        @user.avatar_attacher(cache: :other_cache)
        @user.avatar_attacher.context[:foo] = "bar"
        @user.reload

        assert_equal :other_cache, @user.avatar_attacher.cache_key
        assert_equal "bar",        @user.avatar_attacher.context[:foo]
      end

      it "doesn't initialize the attacher if it hasn't been initialized" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save
        @user = @user.class.with_pk!(@user.id)
        @user.reload

        refute @user.instance_variable_defined?(:@avatar_attacher)
      end

      it "returns self" do
        @user.class.include @shrine::Attachment.new(:avatar)

        @user.save

        assert_equal @user, @user.reload
      end

      it "keeps private visibility" do
        @user.class.include @shrine::Attachment.new(:avatar)

        assert_includes @user.class.private_instance_methods, :_refresh
      end
    end

    it "can still be included into non-Sequel classes" do
      model_class = model_class(:avatar_data)
      model_class.include @shrine::Attachment.new(:avatar)

      %i[validate after_save after_destroy _refresh].each do |method_name|
        refute_includes model_class.instance_methods, method_name
      end
    end
  end

  describe "Attacher" do
    describe "JSON columns" do
      after do
        @user.class.db_schema[:avatar_data][:type] = :string # revert schema change
      end

      [:json, :jsonb].each do |type|
        it "handles #{type} type" do
          @user.class.db_schema[:avatar_data][:type] = type

          @attacher.load_model(@user, :avatar)
          @attacher.attach(fakeio)

          assert_equal @attacher.file.data, @user.avatar_data

          @attacher.reload

          assert_equal @attacher.file.data, @user.avatar_data
        end
      end
    end

    describe "#atomic_promote" do
      it "promotes cached file to permanent storage" do
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote

        assert @attacher.stored?
        @attacher.reload
        assert @attacher.stored?
      end

      it "updates the record with promoted file" do
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote

        @user.reload
        @attacher.reload
        assert @attacher.stored?
      end

      it "returns the promoted file" do
        @attacher.attach_cached(fakeio)
        @user.save

        file = @attacher.atomic_promote

        assert_equal @attacher.file, file
      end

      it "accepts promote options" do
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote(location: "foo")

        assert_equal "foo", @attacher.file.id
      end

      it "persists any other attribute changes" do
        @attacher.attach_cached(fakeio)
        @user.save

        @user.name = "Janko"
        @attacher.atomic_promote

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
      end

      it "executes the given block before persisting" do
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote { @user.name = "Janko" }

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
      end

      it "fails on attachment change" do
        @attacher.attach_cached(fakeio)
        @user.save

        @user.this.update(avatar_data: nil)

        @user.name = "Janko"
        assert_raises(Shrine::AttachmentChanged) do
          @attacher.atomic_promote { @block_called = true }
        end

        @user.reload
        @attacher.reload

        assert_nil @attacher.file
        assert_nil @user.name
        refute @block_called
      end

      it "respects column serializer" do
        @attacher = @shrine::Attacher.from_model(@user, :avatar, column_serializer: RubySerializer)
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote

        @user.reload
        @attacher.reload
        assert @attacher.stored?
      end

      it "accepts custom reload strategy" do
        cached_file = @attacher.attach_cached(fakeio)
        @user.save

        @user.this.update(avatar_data: nil) # this change will not be detected

        @user.name = "Janko"
        @attacher.atomic_promote(reload: -> (&block) {
          block.call @user.class.new(avatar_data: cached_file.to_json)
        })

        @user.reload
        @attacher.reload
        assert @attacher.stored?
        assert_equal "Janko", @user.name
      end

      it "allows disabling reloading" do
        cached_file = @attacher.attach_cached(fakeio)
        @user.save

        @user.this.update(avatar_data: nil) # this change will not be detected

        @user.name = "Janko"
        @attacher.atomic_promote(reload: false)

        @user.reload
        @attacher.reload
        assert @attacher.stored?
        assert_equal "Janko", @user.name
      end

      it "accepts custom persist strategy" do
        @attacher.attach_cached(fakeio)
        @user.save

        @attacher.atomic_promote(persist: -> {
          @user.name = "Janko"
          @user.save
        })

        @user.reload
        @attacher.reload
        assert @attacher.stored?
        assert_equal "Janko", @user.name
      end

      it "allows disabling persistence" do
        @attacher.attach_cached(fakeio)
        @user.save

        @user.name = "Janko"
        @attacher.atomic_promote(persist: false)

        assert @attacher.stored?
        assert_equal "Janko", @user.name

        @user.reload
        @attacher.reload
        assert @attacher.cached?
        assert_nil @user.name
      end

      it "raises NotImplementedError for non-Sequel attacher" do
        @attacher = @shrine::Attacher.new

        assert_raises NotImplementedError do
          @attacher.atomic_promote
        end
      end
    end

    describe "#atomic_persist" do
      it "persists the record" do
        file = @attacher.attach(fakeio)
        @user.save

        @user.name = "Janko"
        @attacher.atomic_persist

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
        assert_equal file,    @attacher.file
      end

      it "executes the given block before persisting" do
        @attacher.attach(fakeio)
        @user.save

        @attacher.atomic_persist { @user.name = "Janko" }

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
      end

      it "fails on attachment change" do
        @attacher.attach(fakeio)
        @user.save

        @user.this.update(avatar_data: nil)

        @user.name = "Janko"
        assert_raises(Shrine::AttachmentChanged) do
          @attacher.atomic_persist { @block_called = true }
        end

        @user.reload
        @attacher.reload

        assert_nil @attacher.file
        assert_nil @user.name
        refute @block_called
      end

      it "respects column serializer" do
        @attacher = @shrine::Attacher.from_model(@user, :avatar, column_serializer: RubySerializer)
        @attacher.attach(fakeio)
        @user.save

        @user.name = "Janko"
        @attacher.atomic_persist

        @user.reload
        @attacher.reload
        assert_equal "Janko", @user.name
      end

      it "accepts custom reload strategy" do
        @attacher.attach(fakeio)
        @user.save

        @user.this.update(avatar_data: nil) # this change will not be detected

        @user.name = "Name"
        @attacher.atomic_persist(reload: -> (&block) { block.call(@user) })

        assert_equal "Name", @user.reload.name
      end

      it "allows disabling reloading" do
        @attacher.attach(fakeio)
        @user.save

        @user.this.update(avatar_data: nil) # this change will not be detected

        @user.name = "Name"
        @attacher.atomic_persist(reload: false)

        assert_equal "Name", @user.reload.name
      end

      it "accepts custom persist strategy" do
        @attacher.attach(fakeio)
        @user.save

        @attacher.atomic_persist(persist: -> {
          @user.name = "Janko"
          @user.save
        })

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
      end

      it "allows disabling persistence" do
        @attacher.attach(fakeio)
        @user.save

        @user.name = "Janko"
        @attacher.atomic_persist(persist: false)

        assert_equal "Janko", @user.name
        assert_nil @user.reload.name
      end

      it "accepts current file" do
        @user.save

        file = @attacher.upload(fakeio)
        @user.this.update(avatar_data: file.to_json)

        assert_raises(Shrine::AttachmentChanged) do
          @attacher.atomic_persist
        end

        @user.name = "Janko"
        @attacher.atomic_persist(file)

        assert_equal "Janko", @user.name
        assert_equal "Janko", @user.reload.name
      end

      it "raises NotImplementedError for non-Sequel attacher" do
        @attacher = @shrine::Attacher.new

        assert_raises NotImplementedError do
          @attacher.atomic_persist
        end
      end
    end

    describe "#persist" do
      it "persists the record" do
        file = @attacher.upload(fakeio)
        @user.avatar_data = file.to_json

        @attacher.persist

        assert_equal file.to_json, @user.reload.avatar_data
      end

      it "persists only changes" do
        @user.save
        @user.this.update(name: "Janko")

        file = @attacher.upload(fakeio)
        @user.avatar_data = file.to_json

        @attacher.persist

        assert_equal "Janko", @user.reload.name
      end

      it "skips validations" do
        @user.instance_eval do
          def validate
            errors.add(:name, "must be present")
          end
        end

        @user.name = "Janko"
        @user.save(validate: false)

        @user.name = nil
        @attacher.persist

        assert_nil @user.reload.name
      end

      it "triggers hooks when persisting" do
        @user.save

        after_save_called = false
        @user.class.send(:define_method, :after_save) { after_save_called = true }

        @user.name = "Janko"
        @attacher.persist

        assert after_save_called
      end

      it "raises NotImplementedError for non-Sequel attacher" do
        @attacher = @shrine::Attacher.new

        assert_raises NotImplementedError do
          @attacher.persist
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>http::response</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../ref.html" title="This Page Intentionally Left Blank 2/2">
<link rel="prev" href="boost__beast__http__request.html" title="http::request">
<link rel="next" href="boost__beast__http__file_body.html" title="http::file_body">

Home
Libraries
People
FAQ
More

http::response

        A typical HTTP response.

        Synopsis

        Defined in header <boost/beast/http/message.hpp>

template<
    class Body,
    class Fields = fields>
using response = message< false, Body, Fields >;

        Types

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  body_type

                  The type providing the body traits.

                  fields_type

                  The type representing the fields.

                  header_type

                  The base class used to hold the header portion of the message.

                  is_request

                  Indicates if the header is a request or response.

        Member
        Functions

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  base

                  Returns the header portion of the message.

                  body

                  Returns the body.

                  chunked

                  Returns true if the
                  chunked Transfer-Encoding is specified.
 —

                  Set or clear the chunked Transfer-Encoding.

                  content_length

                  Set or clear the Content-Length field.

                  has_content_length

                  Returns true if the
                  Content-Length field is present.

                  keep_alive

                  Returns true if the
                  message semantics indicate keep-alive.
 —

                  Set the keep-alive message semantic option.

                  message

                  Constructor.
 —
 Construct
                  a message.

                  method

                  Return the request-method verb.
 —

                  Set the request-method.

                  method_string

                  Return the request-method as a string.
 —

                  Set the request-method.

                  need_eof

                  Returns true if the
                  message semantics require an end of file.

                  operator=

                  Assignment.

                  payload_size

                  Returns the payload size of the body in octets if possible.

                  prepare_payload

                  Prepare the message payload fields for the body.

                  reason

                  Return the response reason-phrase.
 —

                  Set the response reason-phrase (deprecated)

                  result

                  The response status-code result.
 —

                  Set the response status-code.
 —

                  Set the response status-code as an integer.

                  result_int

                  The response status-code expressed as an integer.

                  target

                  Returns the request-target string.
 —

                  Set the request-target string.

                  version

                  Return the HTTP-version.
 —

                  Set the HTTP-version.

        This container is derived from the Fields
        template type. To understand all of the members of this class it is necessary
        to view the declaration for the Fields
        type. When using the default fields container, those declarations are in
        fields.
        A message can be a request or response, depending on the isRequest
        template argument value. Requests and responses have different types; functions
        may be overloaded based on the type if desired. The Body
        template argument type determines the model used to read or write the content
        body of the message. Newly constructed messages objects have version set
        to HTTP/1.1. Newly constructed response objects also have result code set
        to status::ok.

        Template
        Parameters

<colgroup>
<col>
<col>
</colgroup>

                  Type

                  Description

                  isRequest

                  true if this represents
                  a request, or false
                  if this represents a response. Some class data members are conditionally
                  present depending on this value.

                  Body

                  A type meeting the requirements of Body.

                  Fields

                  The type of container used to hold the field value pairs.

Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
import d3 from 'd3';
import * as graphConstants from './graphConstants';

export default function (svg, nodes) {

  const { WIDTH, OUTPUT_LAYER_LABEL, INPUT_LAYER_NODE_WIDTH } = graphConstants;

  const edgeMessages = [];
  for (let i = 1; i < nodes.length; i++) {
    const a = nodes[i - 1].length;
    const b = nodes[i].length;
    edgeMessages.push(
      `${a*b} edges`
    );
  }

  const isLast = index => index === nodes.length - 1;

  const xScaleNodeLabel = d3.scale.linear()
    .domain([0, nodes.length - 1])
    .range([0, WIDTH - OUTPUT_LAYER_LABEL - INPUT_LAYER_NODE_WIDTH]);

  const xScaleEdgeLabel = d3.scale.linear()
    .domain([0, nodes.length - 1])
    .range([0, WIDTH - OUTPUT_LAYER_LABEL - INPUT_LAYER_NODE_WIDTH]);

  const nodeLabels = svg
    .selectAll('.header-node-labels')
    .data(nodes);

  nodeLabels
    .enter()
    .append('text')
    .attr('class', 'header-node-labels');

  nodeLabels
    .attr('dx', (d, i) => {
      if (i === 0) return xScaleNodeLabel(i);
      if (isLast(i)) return xScaleNodeLabel(i) - 75;
      return xScaleNodeLabel(i) - 25;
    })
    .attr('dy', 9)
    .attr('font-size', 12)
    .attr('text-anchor', 'left')
    .attr('stroke-width', '1')
    .attr('stroke', 'rgb(60,60,60)')
    .text((d, i) => {
      if (i === 0) return '784 Input Nodes';
      if (isLast(i)) return `${nodes[i].length} Output Nodes`;
      return `${nodes[i].length} Hidden Nodes`;
    });

  const edgeLabels = svg
      .selectAll('.header-edge-labels')
      .data(edgeMessages);

  edgeLabels
      .enter()
      .append('text')
      .attr('class', 'header-edge-labels');

  edgeLabels
      .attr('dx', (d, i) => xScaleEdgeLabel(i) + xScaleEdgeLabel(1) / 2 - 30)
      .attr('dy', 9)
      .attr('font-size', 12)
      .attr('text-anchor', 'left')
      .attr('stroke-width', '.5')
      .attr('stroke', 'rgb(110,110,110)')
      .text(d => d);

}


text:
package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;

import core.Action;
import core.Config;
import core.Joueur;

public class Client extends Thread {
	private Socket client;
	private DispatcherServeur serveur;
	private boolean attendTop;

	private static final String TOP = "1";
	private static final String SOLDE = "2";
	private static final String OPERATIONS = "3";
	private static final String ACHATS = "4 ";
	private static final String VENTES = "5 ";
	private static final String HISTO = "6 "; // on définit un dictionnaire qui permettra une communication
	private static final String ASK = "7 "; // client/serveur avec des messages très courts
	private static final String BID = "8 "; // sans perdre de lisibilité du code
	private static final String SUIVRE = "9 ";
	private static final String ANNULER = "A ";
	private static final String FIN = "B";
	private static final String CREATE = "C ";
	private static final String JOIN = "D ";
	private static final String LISTECOUPS = "E";
	private static final String AVANTTOP = "F";

	public Client(Socket client, DispatcherServeur serveur) {
		super();
		this.client = client;
		this.serveur = serveur;
		this.attendTop=false;
		start();
	}

	public void run() {
		System.out.println("Client connecté");
		int nombreActions = Action.values().length;
		Partie current = null;
		Joueur joueur = null;
		int numero_partie = -1;
		boolean create = false;
		String identifier = "";
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()),
					Config.getInstance().MAX_PACKET_SIZE_INPUT);
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

			envoyer(out, Config.getInstance().VERSION);
			identifier = childishness(out, in);

			String userInput;
			boolean join = false;

			while ((userInput = in.readLine()) != null) {
				// System.out.println(userInput + "\n");

				String[] arguments = userInput.split(" ");
				boolean peut_jouer = (create || join) && current.getMarche().est_ouvert()
						&& !current.getMarche().est_fini();

				// Utilisateur n'ayant ni créé ni rejoint peut créer

				if (userInput.startsWith(SOLDE) && (create || join) && current.getMarche().est_ouvert()) {
					String begin = "{'euros':" + String.valueOf(joueur.getSolde_euros()) + ", ";
					envoyer(out, begin + MapToStringPython(joueur.getSolde_actions()) + "}");
				} else if (userInput.startsWith(OPERATIONS) && peut_jouer) {
					envoyer(out, String.valueOf(ListPairToStringPythonKeyOnly(joueur.getOperationsOuvertes())));
				} else if (userInput.startsWith(ACHATS)) {
					if (arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) {
						int arg = Integer.parseInt(arguments[1]);
						if (arg < nombreActions && arg >= 0) {
							Action a = Action.values()[arg];
							envoyer(out, current.getMarche().getListeAchatsString(a, 0));
						} else
							envoyer(out, "-4");
					} else if (arguments.length == 3 && StringUtils.isNumeric(arguments[1])
							&& StringUtils.isNumeric(arguments[2]) && peut_jouer) {
						int arg1 = Integer.parseInt(arguments[1]);
						if (arg1 < nombreActions && arg1 >= 0) {
							int arg2 = Integer.parseInt(arguments[2]);
							Action a = Action.values()[arg1];
							envoyer(out, current.getMarche().getListeAchatsString(a, arg2));
						} else
							envoyer(out, "-4");
					} else
						envoyer(out, "-4");
				} else if (userInput.startsWith(VENTES)) {
					if (arguments.length == 2 && StringUtils.isNumeric(arguments[1]) && peut_jouer) {
						int arg = Integer.parseInt(arguments[1]);
						if (arg < nombreActions && arg >= 0) {
							Action a = Action.values()[arg];
							envoyer(out, current.getMarche().getListeVentesString(a, 0));
						} else
							envoyer(out, "-4");
					} else if (arguments.length == 3 && StringUtils.isNumeric(arguments[1])
							&& StringUtils.isNumeric(arguments[2]) && peut_jouer) {
						int arg1 = Integer.parseInt(arguments[1]);
						if (arg1 < nombreActions && arg1 >= 0) {
							int arg2 = Integer.parseInt(arguments[2]);
							Action a = Action.values()[arg1];
							envoyer(out, current.getMarche().getListeVentesString(a, arg2));
						} else
							envoyer(out, "-4");
					} else
						envoyer(out, "-4");
				} else if (userInput.startsWith(HISTO) && arguments.length == 3 && StringUtils.isNumeric(arguments[1])
						&& StringUtils.isNumeric(arguments[2]) && (create || join)
						&& current.getMarche().est_ouvert()) {
					int arg = Integer.parseInt(arguments[1]);
					if (arg < nombreActions && arg >= 0) {
						Action a = Action.values()[arg];
						envoyer(out, String
								.valueOf(current.getMarche().getHistoriqueEchanges(a, Integer.parseInt(arguments[2]))));
					} else
						envoyer(out, "-4");
				} else if (userInput.startsWith(ASK) && arguments.length == 4 && StringUtils.isNumeric(arguments[1])
						&& NumberUtils.isCreatable(arguments[2]) && StringUtils.isNumeric(arguments[3]) && peut_jouer) {
					int arg = Integer.parseInt(arguments[1]);
					if (arg < nombreActions && arg >= 0) {
						Action a = Action.values()[arg];
						float prix = Float.parseFloat(arguments[2]);
						int volume = Integer.parseInt(arguments[3]);
						envoyer(out, String.valueOf(current.getMarche().achat(joueur, a, prix, volume)));
					} else
						envoyer(out, "-12");
				} else if (userInput.startsWith(BID) && arguments.length == 4 && StringUtils.isNumeric(arguments[1])
						&& NumberUtils.isCreatable(arguments[2]) && StringUtils.isNumeric(arguments[3]) && peut_jouer) {
					int arg = Integer.parseInt(arguments[1]);
					if (arg < nombreActions && arg >= 0) {
						Action a = Action.values()[arg];
						float prix = Float.parseFloat(arguments[2]);
						int volume = Integer.parseInt(arguments[3]);
						envoyer(out, String.valueOf(current.getMarche().vend(joueur, a, prix, volume)));
					} else
						envoyer(out, "-12");
				} else if (userInput.startsWith(SUIVRE) && arguments.length == 2 && StringUtils.isNumeric(arguments[1])
						&& peut_jouer) {
					int ordre = Integer.parseInt(arguments[1]);
					envoyer(out, String.valueOf(current.getMarche().suivre(joueur, ordre)));
				} else if (userInput.startsWith(ANNULER) && arguments.length == 2 && StringUtils.isNumeric(arguments[1])
						&& peut_jouer) {
					int ordre = Integer.parseInt(arguments[1]);
					envoyer(out, String.valueOf(current.getMarche().annuler(joueur, ordre)));
				} else if (userInput.startsWith(FIN) && arguments.length == 1 && (create || join)
						&& current.getMarche().est_ouvert()) {
					envoyer(out, String.valueOf(current.getMarche().fin()));
				} else if (userInput.startsWith(LISTECOUPS) && (create || join) && current.getMarche().est_fini()) {
					envoyer(out, current.getMarche().getListeOperationsString());
				} else if (userInput.startsWith(AVANTTOP) && create && !current.getMarche().est_ouvert()) {
					envoyer(out, current.getMarche().getListeJoueursStringDico());
				} else if (userInput.startsWith(CREATE) && arguments.length == 4 && !create && !join) {
					String nom = arguments[1];
					String modeBanque= arguments[2];
					String modeExam= arguments[3];

					numero_partie = (int) (Math.random() * 100000);
					if ((modeBanque.equals("1")||modeBanque.equals("2")||modeBanque.equals("3")) && (modeExam.equals("0")||modeExam.equals("1"))){
						if(modeExam.equals("1") && !Config.getInstance().cles.containsKey(nom)) {
							envoyer(out,"-5");
						}
						else{
							envoyer(out, String.valueOf(numero_partie));
							current = new Partie(Integer.parseInt(modeBanque),Integer.parseInt(modeExam));
							joueur = current.ajouter_client(this, nom, identifier);
							serveur.ajouterPartie(numero_partie, current);
							create = true;
						}
					}
					else
						envoyer(out,"-4");

				} else if (userInput.startsWith(JOIN) && arguments.length == 3 && StringUtils.isNumeric(arguments[1])
						&& !create && !join) {
					numero_partie = Integer.parseInt(arguments[1]);
					String nom = arguments[2];

					if (!serveur.partieExiste(numero_partie)) {
						envoyer(out, "-1");
						continue;
					}

					if (!serveur.getListepartie(numero_partie).getMarche().nom_possible(nom)) {
						envoyer(out, "-2");
						continue;
					}

					if (serveur.getListepartie(numero_partie).getMarche().est_ouvert()) {
						envoyer(out, "-3");
						continue;
					}

					current = serveur.getListepartie(numero_partie);

					if (current.isModeExamen()&&( !Config.getInstance().cles.containsKey(nom) || !current.testUniciteDeLaConnexion(client,nom)))
					{
						envoyer(out, "-5");
						continue;
					}

					envoyer(out, "0");
					join=true;
					joueur = current.ajouter_client(this, nom, identifier);
				} else if (userInput.startsWith(TOP) && create && !current.getMarche().est_ouvert()) {
					String retour = current.getMarche().getListeJoueursStringDico();
					long futureTop = System.currentTimeMillis() + 3500;//in 3.5 seconds
					for (Client c : current.getListe_client()){
						Socket s = c.getSock();
						try {
							if (!s.equals(client) && c.isAttendTop()) {
								BufferedWriter outAdvers = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
								envoyer(outAdvers, "("+String.valueOf((int)(futureTop - System.currentTimeMillis()))+",)");
							}
						} catch(Exception e) {
							//peu importe client perdu
						}
					}
					envoyer(out, "("+String.valueOf((int)(futureTop - System.currentTimeMillis())+","+retour+")"));
					long reste = futureTop - System.currentTimeMillis() - 50;
					if(reste > 0)
						Thread.sleep(reste);
					current.getMarche().commence();
				} else if (userInput.startsWith(TOP) && !current.getMarche().est_ouvert()) {
				  // attend le top
					attendTop = true;
				} else if (userInput.startsWith(TOP) && current.getMarche().est_ouvert() && join && !attendTop && !create) {
				  // retardataires qui ont oublie d'appeller top
					envoyer(out, "0");
					attendTop = true;
				} else {
					System.out.println("FAIL |" + userInput + "|");
					envoyer(out, "-4");
				}
			}

			libererPartie(current, numero_partie, create, joueur,identifier);
		} catch (Exception e) {
			if (!(e instanceof SocketException))
				e.printStackTrace();
			try {
				libererPartie(current, numero_partie, create, joueur,identifier);
			} catch (Exception e1) {
				e1.printStackTrace();
				if (!(e1 instanceof SocketException))
					e.printStackTrace();
			}
		}

	}

	public Socket getSock() {
		return client;
	}

	public boolean isAttendTop() {
		return attendTop;
	}

	private String childishness(BufferedWriter out, BufferedReader in) throws IOException, NoSuchAlgorithmException {
		int ids = (int) (Math.random() * 100000);
		envoyer(out, String.valueOf(ids));
		envoyer(out, Config.getInstance().CHILDISHNESS);
		String identifier = in.readLine();
		MessageDigest mdj = MessageDigest.getInstance("MD5");
		mdj.update(identifier.getBytes());
		byte[] digest = mdj.digest();
		StringBuffer sb = new StringBuffer();
		for (byte b : digest) {
			sb.append(String.format("%02x", b & 0xff));
		}
		String md = in.readLine();
		if(!md.equals(new String(sb)))
			throw new IOException("child");

		return identifier.substring(identifier.indexOf(":")+1, identifier.length());
	}

	private void envoyer(BufferedWriter out, String packet) throws IOException {
		StringBuilder length = new StringBuilder(Config.getInstance().PACKET_SIZE);
		String llength = String.valueOf(packet.length());
		if (packet.length() > Config.getInstance().RESERVED_SIZE_SEND_PACKET) {
			System.out.println("ERROR : packet too small");
			System.err.println("ERROR : packet too small");
		}
		for (int i = llength.length(); i < Config.getInstance().PACKET_SIZE; i++)
			length.insert(0, "0");
		length.append(llength);

		out.write(new String(length));
		out.write(packet);
		out.flush();
	}

	private void libererPartie(Partie current, int numero_partie, boolean create, Joueur joueur, String identifier) throws IOException {
		if (joueur != null && current != null) {
			current.getMarche().retirer_joueur(joueur);
		}

		if (current != null && create) {
			for (Client c : current.getListe_client()){
				Socket s = c.getSock();
				s.close();
			}

			current.getMarche().destroy();
			serveur.retirerPartie(numero_partie);
		} else if (!create) {
			if(current != null)
				current.retirerJoueur(client,identifier);
			client.close();
		}
		System.out.println("Client déconnecté");
	}

	private <E, V> String MapToStringPython(Map<E, V> map) {
		StringBuffer sb = new StringBuffer(12 * map.size());
		for (Map.Entry<E, V> v : map.entrySet()) {
			sb.append('\'');
			sb.append(String.valueOf(v.getKey()));
			sb.append("':");
			sb.append(String.valueOf(v.getValue()));
			sb.append(',');
		}

		if (map.size() != 0)
			sb.deleteCharAt(sb.length() - 1);
		return new String(sb);
	}

	private <E, V> String ListPairToStringPythonKeyOnly(List<Pair<E, V>> list) {
		StringBuffer sb = new StringBuffer(12 * list.size());
		sb.append('[');
		for (Pair<E, V> v : list) {
			sb.append(String.valueOf(v.getKey()));
			sb.append(',');
		}

		if (list.size() != 0)
			sb.deleteCharAt(sb.length() - 1);
		sb.append(']');
		return new String(sb);
	}
}


text:
package org.kohsuke.github;

import org.apache.commons.lang3.SystemUtils;
import org.junit.Assume;
import org.junit.Test;
import org.kohsuke.github.authorization.AuthorizationProvider;
import org.kohsuke.github.authorization.ImmutableAuthorizationProvider;
import org.kohsuke.github.authorization.UserAuthorizationProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static org.hamcrest.Matchers.*;

/**
 * Unit test for {@link GitHub}.
 */
public class GitHubConnectionTest extends AbstractGitHubWireMockTest {

    public GitHubConnectionTest() {
        useDefaultGitHub = false;
    }

    @Test
    public void testOffline() throws Exception {
        GitHub hub = GitHub.offline();
        assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
                equalTo("https://api.github.invalid/test"));
        assertThat(hub.isAnonymous(), is(true));
        try {
            hub.getRateLimit();
            fail("Offline instance should always fail");
        } catch (IOException e) {
            assertThat(e.getMessage(), equalTo("Offline"));
        }
    }

    @Test
    public void testGitHubServerWithHttp() throws Exception {
        GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
        assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
                equalTo("http://enterprise.kohsuke.org/api/v3/test"));
    }

    @Test
    public void testGitHubServerWithHttps() throws Exception {
        GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
        assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
                equalTo("https://enterprise.kohsuke.org/api/v3/test"));
    }

    @Test
    public void testGitHubServerWithoutServer() throws Exception {
        GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus");
        assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
                equalTo("https://api.github.com/test"));
    }

    @Test
    public void testGitHubBuilderFromEnvironment() throws IOException {
        // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+
        Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0));

        Map<String, String> props = new HashMap<String, String>();

        props.put("endpoint", "bogus endpoint url");
        props.put("oauth", "bogus oauth token string");
        setupEnvironment(props);
        GitHubBuilder builder = GitHubBuilder.fromEnvironment();

        assertThat(builder.endpoint, equalTo("bogus endpoint url"));

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue());

        props.put("login", "bogus login");
        setupEnvironment(props);
        builder = GitHubBuilder.fromEnvironment();

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));

        props.put("jwt", "bogus jwt token string");
        setupEnvironment(props);
        builder = GitHubBuilder.fromEnvironment();

        assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class)));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("Bearer bogus jwt token string"));

        props.put("password", "bogus weak password");
        setupEnvironment(props);
        builder = GitHubBuilder.fromEnvironment();

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA=="));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));

    }

    @Test
    public void testGitHubBuilderFromCustomEnvironment() throws IOException {
        // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+
        Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0));

        Map<String, String> props = new HashMap<String, String>();

        props.put("customEndpoint", "bogus endpoint url");
        props.put("customOauth", "bogus oauth token string");
        setupEnvironment(props);
        GitHubBuilder builder = GitHubBuilder
                .fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint");

        assertThat(builder.endpoint, equalTo("bogus endpoint url"));

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue());

        props.put("customLogin", "bogus login");
        setupEnvironment(props);
        builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint");

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));

        props.put("customPassword", "bogus weak password");
        setupEnvironment(props);
        builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth", "customEndpoint");

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA=="));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));
    }

    @Test
    public void testGitHubBuilderFromCredentialsWithEnvironment() throws IOException {
        // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+
        Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0));
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        Map<String, String> props = new HashMap<String, String>();

        props.put("endpoint", "bogus endpoint url");
        props.put("oauth", "bogus oauth token string");
        setupEnvironment(props);
        GitHubBuilder builder = GitHubBuilder.fromCredentials();

        assertThat(builder.endpoint, equalTo("bogus endpoint url"));

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue());

        props.put("login", "bogus login");
        setupEnvironment(props);
        builder = GitHubBuilder.fromCredentials();

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus oauth token string"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));

        props.put("jwt", "bogus jwt token string");
        setupEnvironment(props);
        builder = GitHubBuilder.fromCredentials();

        assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class)));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("Bearer bogus jwt token string"));

        props.put("password", "bogus weak password");
        setupEnvironment(props);
        builder = GitHubBuilder.fromCredentials();

        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA=="));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));
    }

    @Test
    public void testGitHubBuilderFromCredentialsWithPropertyFile() throws IOException {
        // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+
        Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0));
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        Map<String, String> props = new HashMap<String, String>();

        // Clear the environment
        setupEnvironment(props);
        try {
            GitHubBuilder.HOME_DIRECTORY = new File(getTestDirectory());
            try {
                GitHubBuilder builder = GitHubBuilder.fromCredentials();
                fail();
            } catch (Exception e) {
                assertThat(e, instanceOf(IOException.class));
                assertThat(e.getMessage(), equalTo("Failed to resolve credentials from ~/.github or the environment."));
            }

            props = new HashMap<String, String>();

            props.put("endpoint", "bogus endpoint url");
            props.put("oauth", "bogus oauth token string");

            setupPropertyFile(props);

            GitHubBuilder builder = GitHubBuilder.fromCredentials();

            assertThat(builder.endpoint, equalTo("bogus endpoint url"));

            assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
            assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                    equalTo("token bogus oauth token string"));
            assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), nullValue());

            props.put("login", "bogus login");
            setupPropertyFile(props);
            builder = GitHubBuilder.fromCredentials();

            assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
            assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                    equalTo("token bogus oauth token string"));
            assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));

            props.put("jwt", "bogus jwt token string");
            setupPropertyFile(props);
            builder = GitHubBuilder.fromCredentials();

            assertThat(builder.authorizationProvider, not(instanceOf(UserAuthorizationProvider.class)));
            assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                    equalTo("Bearer bogus jwt token string"));

            props.put("password", "bogus weak password");
            setupPropertyFile(props);
            builder = GitHubBuilder.fromCredentials();

            assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
            assertThat(builder.authorizationProvider.getEncodedAuthorization(),
                    equalTo("Basic Ym9ndXMgbG9naW46Ym9ndXMgd2VhayBwYXNzd29yZA=="));
            assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("bogus login"));
        } finally {
            GitHubBuilder.HOME_DIRECTORY = null;
            File propertyFile = new File(getTestDirectory(), ".github");
            propertyFile.delete();
        }
    }

    private void setupPropertyFile(Map<String, String> props) throws IOException {
        File propertyFile = new File(getTestDirectory(), ".github");
        Properties properties = new Properties();
        properties.putAll(props);
        properties.store(new FileOutputStream(propertyFile), "");
    }

    private String getTestDirectory() {
        return new File("target").getAbsolutePath();
    }

    @Test
    public void testAnonymous() throws IOException {
        // we disable this test for JDK 16+ as the current hacks in setupEnvironment() don't work with JDK 16+
        Assume.assumeThat(Double.valueOf(System.getProperty("java.specification.version")), lessThan(16.0));

        Map<String, String> props = new HashMap<String, String>();

        props.put("endpoint", mockGitHub.apiServer().baseUrl());
        setupEnvironment(props);

        // No values present except endpoint
        GitHubBuilder builder = GitHubBuilder
                .fromEnvironment("customLogin", "customPassword", "customOauth", "endpoint");

        assertThat(builder.endpoint, equalTo(mockGitHub.apiServer().baseUrl()));
        assertThat(builder.authorizationProvider, sameInstance(AuthorizationProvider.ANONYMOUS));
    }

    @Test
    public void testGithubBuilderWithAppInstallationToken() throws Exception {

        GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus app token");
        assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
        assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus app token"));
        assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), is(emptyString()));

        // test authorization header is set as in the RFC6749
        GitHub github = builder.build();
        // change this to get a request
        assertThat(github.getClient().getEncodedAuthorization(), equalTo("token bogus app token"));
        assertThat(github.getClient().getLogin(), is(emptyString()));
    }

    @Test
    public void testGitHubIsApiUrlValid() throws IOException {
        // NOTE: We cannot test connectAnonymously on a general basis because it can hang if
        // rate limit is reached. We connectToEnterpriseAnonymously as the nearest equivalent.
        // GitHub hub = GitHub.connectAnonymously();

        GitHub hub = GitHub.connectToEnterpriseAnonymously(mockGitHub.apiServer().baseUrl());
        hub.checkApiUrlValidity();
        try {
            hub.checkApiUrlValidity();
            fail();
        } catch (IOException ioe) {
            assertThat(ioe.getMessage(), containsString("doesn't look like GitHub API URL"));
        }
        try {
            hub.checkApiUrlValidity();
            fail();
        } catch (IOException ioe) {
            assertThat(ioe.getMessage(), containsString("private mode enabled"));
        }
        try {
            hub.getClient().requireCredential();
            fail();
        } catch (Exception e) {
            assertThat(e.getMessage(), containsString("This operation requires a credential"));
        }
    }

    @Test
    public void testGitHubOAuthUserQuery() throws IOException {
        snapshotNotAllowed();
        mockGitHub.customizeRecordSpec(recordSpecBuilder -> recordSpecBuilder.captureHeader("Authorization"));
        gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl())
                .withAuthorizationProvider(ImmutableAuthorizationProvider.fromOauthToken("super_secret_token"))
                .build();
        assertThat(mockGitHub.getRequestCount(), equalTo(1));
        assertThat(gitHub.getMyself(), notNullValue());
        assertThat(gitHub.getMyself().root(), notNullValue());
        assertThat(gitHub.getMyself().getLogin(), equalTo("bitwiseman"));
        assertThat(mockGitHub.getRequestCount(), equalTo(1));
    }

    /*
     * Copied from StackOverflow: http://stackoverflow.com/a/7201825/2336755
     *
     * This allows changing the in memory process environment.
     *
     * Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve
     * them.
     */
    private void setupEnvironment(Map<String, String> newenv) {
        try {
            Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
            Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
            theEnvironmentField.setAccessible(true);
            Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
            env.putAll(newenv);
            Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                    .getDeclaredField("theCaseInsensitiveEnvironment");
            theCaseInsensitiveEnvironmentField.setAccessible(true);
            Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
            cienv.putAll(newenv);
        } catch (NoSuchFieldException e) {
            try {
                Class[] classes = Collections.class.getDeclaredClasses();
                Map<String, String> env = System.getenv();
                for (Class cl : classes) {
                    if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                        Field field = cl.getDeclaredField("m");
                        field.setAccessible(true);
                        Object obj = field.get(env);
                        Map<String, String> map = (Map<String, String>) obj;
                        map.clear();
                        map.putAll(newenv);
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}


text:
/**
 * Fake page processor
 */
Aria.classDefinition({
    $classpath : "test.aria.pageEngine.pageEngine.pageEngineDisposal.PageProvider",
    $implements : ["aria.pageEngine.pageProviders.PageProviderInterface"],
    $prototype : {

        /**
         * @param {aria.pageEngine.CfgBeans.ExtendedCallback} callback
         */
        loadSiteConfig : function (callback) {
            this.$callback(callback.onsuccess, {
                containerId : "testId"
            });
        },

        /**
         * @param {String} pageId Id of the page
         * @param {aria.pageEngine.CfgBeans.ExtendedCallback} callback
         */
        loadPageDefinition : function (pageId, callback) {
            this.$callback(callback.onsuccess, {
                pageId : "aaa",
                pageComposition : {
                    template : "test.aria.pageEngine.pageEngine.pageEngineDisposal.MainLayout",
                    placeholders : {
                        "newsInfo" : {
                            "contentId" : "pgen_news_and_info"
                        }
                    }
                }
            });
        }
    }
});


text:
const passport = require('passport');
const messageRouter = require('express').Router();
const Message = require('../models/message');

messageRouter.get('/chatlog/:roomId', passport.authenticate('jwt', { session: false }),
  (req, res) => {
    if (!req.params.roomId) {
      res.sendStatus(400);
    }

    Message.find({ room: req.params.roomId }).populate('author').exec().then(messages => {
      res.json(messages);
    }).catch(err => {
      res.status(500).json(err);
    });
  });

module.exports = messageRouter;


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Daniel McGrath</title>

    <meta name="description" content="Creative Resume Template">
    <meta name="keywords" content="berg, creative, resume, template">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

    <link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Raleway:400,700' rel='stylesheet' type='text/css'>

    <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">

    <link href="assets/plugins/icons-mind/style.css" rel="stylesheet" type="text/css">
    <link href="assets/plugins/fontawesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="assets/plugins/jpreloader/css/jpreloader.css" rel="stylesheet" type="text/css">
    <link href="assets/plugins/animate-css/animate.min.css" rel="stylesheet" type="text/css">
    <link href="assets/plugins/magnificPopup/magnific-popup.css" rel="stylesheet" type="text/css">
    <link href="assets/plugins/flexSlider/flexslider.css" rel="stylesheet" type="text/css">

    <link href="assets/css/berg.css" rel="stylesheet" type="text/css">

    <link href="assets/css/colors/red.css" rel="stylesheet" type="text/css">

                    I'm Daniel McGrath

IT Support Specialist at Louis T. Roth

22 years young, college graduate, hard worker.

                        Know Me Better

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".berg-collapse">
                    Toggle navigation

                </button>

                Daniel McGrath

                        Home

                        Profile

                        Portfolio

                        Services

                        Resume

                        References

                        Skills

                        Contact

Hello, My Name is Daniel.

                                        Daniel McGrath, 22 years young, born and grew up in Louisville, Kentucky. Highly motivated graduate with a specialty in information security.

                                        I currently work at Louis T. Roth & Company, where I spend my time doing IT support.

                                        Having graduated in the Spring of 2016 from the University of Louisville, I received a BSBA in Computer Information Systems with a specialty in Information Security.

Contact Details

Daniel McGrath

Louisville, Kentucky

502.548.1934

Daniel.Parker.McGrath@gmail.com

www.DanielPMcGrath.com

                                         Download Resume

My Latest Work

I'm looking to expand my skillset in the IT world.

Blank

Blank

Blank

Blank

Blank

Blank

Blank

Blank

What I'm Doing

                            I love what I do. I take great pride in what I do. And I can't do something halfway, three-quarters, nine-tenths. If I'm going to do something, I go all the way.

1.Information Security

                                    I specialize in Information Security at the University of Louisville. I have used many tools that relate to information security such as Nmap, Zenmap, Wireshark, etc. With these tools, I have gained experience by doing 'simulations' and 'labs' in class.

2.Database Administration

                                    I have designed several databases while at UofL for practice and for clients. I have mostly used SQL Server and MySQL. Once developed, I maintain the database and make changes when needed or requested.

3.Web Development

                                    I can develop and create basic websites using HTML/CSS and JavaScript.

4.Technical Writing

                                    While at UofL, I designed and created a system with several other individuals that required a lot of technical writing. We created use cases & use case diagrams. ERD's, class diagrams, Gantt charts, sequence/navigation diagrams, etc.

5.Computer Forensics

                                    I am currently enrolled in a class where I am learning to image hard drives, find deleted files, work with the file system and more. This class has been very interesting for me due to my speciality in IT security.

6.Virtualization

                                    I have had a lot of experience with virtualization at the University of Louisville. For a lot of the testing in my IT security classes, we had to run virtual machines ranging from Deft to Kali Linux and Metasploitable. Inside these environments we often did simulations and tests to see how different networks and systems interact with each other.

My Strengths

"Success is not final, failure is not fatal: it is the courage to continue that counts."

                        -Winston Churchill

ME

Excellent

Very Good

Good

Inexperienced

                                        84%

                                            Management

                                        75%

                                            Reliable

                                        70%

                                            Communication

                                        65%

                                            Leadership

                                        90%

                                            Work Ethic

My Resume

                            "If opportunity doesn't knock, build a door."

                        -Milton Berle

                            My Education

                            2008 - 2016

                                    2012 - 2016

Bachelors Degree - University of Louisville

                                                I received a BSBA at the University of Louisville College of Business. I am a Computer Information Systems major with a concentration in Information Security. I graduated in the Spring of 2016.

                                    2008 - 2012

Ballard High School, Louisville, KY

                            Work Experience

                            2010 - Now

                                    2016 - Now

IT Support - Louis T. Roth & Company, Louisville, KY

                                                Responsibilities:

                                                Responsible for providing technical assistance and support related to computer systems, hardware, or software. Provide assistance to the IT manager whenever needed.

                                    2016

Help Desk Intern - M & P Collections/Fenton & McGarvey P.S.C., Louisville, KY

                                                Responsibilities:

                                                Responsible for answering calls and taking tickets and providing technical assistance and support related to computer systems, hardware, or software when needed.

                                    2015 - 2016

Server - Artesano Vino Tapas Y Mas, Louisville, KY

                                                Responsibilities:

                                                -Generate approx. $3000 worth of sales for company each week.

                                    2012 - 2015

Bar back - Captain's Quarters Riverside Grille, Louisville, KY

                                                Responsibilities:

                                                -Entrusted with inventory of $40,000 worth of product.

                                                -Gained insight on operations within a multi-million-dollar business.

                                    2010 - 2012

Manager/Lifeguard - Kentuckiana Pool Management, Louisville, KY

                                                Responsibilities:

                                                -Managed/scheduled 3 other lifeguards & ordered different pool products as needed (approx. $150/week).

References

"The price of success is hard work, dedication to the job at hand, and the determination that whether we win or lose, we have applied the best of ourselves to the task at hand."

                        -Vince Lombardi

Lorena Group

                                                "Daniel is officially the man! His level of professionalism and the understanding of the subject matter is the reason i will be looking forward to working with him in the future."

                                                Eka Smith

                                                President Director

NET TV

                                                "As always Daniel did an excellent job in just few hours. Great communication and fast excecution. Thanks for great work :)"

                                                Will Rout

                                                CO-FOUNDER / CEO

MNC Group

                                                "As always, great creative thinking for the best solution. Daniel is by far the most professional and knowledgeable provider I worked with. I will hire him again :)"

                                                Harry Huber

                                                President Director

CT Corp

                                                "We called on Daniel to help us deliver on few projects with tight deadlines. He seamlessly integrated into our workflow and quickly became a key part of our team. Great job!"

                                                Claire Hundley

                                                Founder and Chairman

Mustika Ratu

                                                "Daniel's technical knowledge and branding experience came together and resulted in a site that is not only catching and interesting, but also one that is user-friendly. Thanks again."

                                                Mollie Joe

                                                President Director

Skills & Expertise

A winner is someone who recognizes his God-given talents, works his tail off to develop them into skills, and uses these skills to accomplish his goals.

                                45%

HTML5 + CSS3

                                65%

SQL

                                68%

VMware

                                80%

Technical Writing

                                45%

C#

                                65%

Unix/Linux

Knowledge

Human behavior flows from three main sources: desire, emotion, and knowledge.

Information Security

                                    70%

Web Development

                                    50%

Database Administration

                                    62%

Virtualization

                                    68%

Operating Systems

                                    80%

Microsoft Office

                                    90%

Accolades

"To accomplish great things, we must dream as well as act."

                        -Anatole France

Eagle Scout, Boyscouts of America

Received the highest ranking in Scouting - Eagle.

Performed in Carnegie Hall with the Ballard Choir in 2011.

Contact Me

                            Would you like to get in touch with me? Send me a message down below and I will get back to you ASAP. Thanks!

                        <form action="contact/send_mail.php" method="post" name="contact-form" id="contact-form" class="contact-form validate element-line" role="form">

                                            <input type="text" name="name" id="name" class="form-control required" placeholder="Name" autocomplete="off">

                                            <input type="email" name="email" id="email" class="form-control required email" placeholder="Email" autocomplete="off">

                                            <input type="text" name="subject" id="subject" class="form-control required" placeholder="Subject" autocomplete="off">

                                            <textarea name="message" id="message" class="form-control required" placeholder="Message"></textarea>

                                        <button id="submit" type="submit">Send Message</button>

                        </form>

Louisville, Kentucky

© 2016 Daniel McGrath. All rights reserved.


text:
title: "Research Projects"
layout: archive
excerpt: "Introduction to Karthik's research projects"
sitemap: false
permalink: /projects/
author_profile: true
---

{% include base_path %}

{% include paginator.html %}


text:
package org.kie.workbench.common.stunner.cm.client.command;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.cm.client.command.canvas.CaseManagementDeleteCanvasNodeCommand;
import org.kie.workbench.common.stunner.cm.client.command.graph.CaseManagementSafeDeleteNodeCommand;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.command.impl.SafeDeleteNodeCommand;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

@RunWith(MockitoJUnitRunner.class)
public class CaseManagementDeleteNodeCommandTest extends CaseManagementAbstractCommandTest {

    private CaseManagementDeleteNodeCommand tested;

    @Before
    public void setUp() {
        super.setup();

        tested = new CaseManagementDeleteNodeCommand(candidate);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testCaseManagementCanvasDeleteProcessor() {
        final CaseManagementDeleteNodeCommand.CaseManagementCanvasDeleteProcessor processor =
                new CaseManagementDeleteNodeCommand.CaseManagementCanvasDeleteProcessor(
                        SafeDeleteNodeCommand.Options.defaults());

        final CaseManagementDeleteCanvasNodeCommand command = processor.createDeleteCanvasNodeCommand(candidate);

        assertNotNull(command);
        assertEquals(candidate,
                     command.getCandidate());
    }

    @Test
    public void testNewGraphCommand() {
        final Command<GraphCommandExecutionContext, RuleViolation> graphCommand = tested.newGraphCommand(canvasHandler);

        assertNotNull(graphCommand);
        assertTrue(graphCommand instanceof CaseManagementSafeDeleteNodeCommand);
        assertEquals(candidate,
                     ((CaseManagementSafeDeleteNodeCommand) graphCommand).getNode());
    }
}


text:
/*eslint no-console: 0 */
import Updater from '../Updater';
import request from 'request';

const url = 'http://audiocrawl.co/api/demos?page=';

export default class AwesomeWebaudio extends Updater {
  run(cb) {
    const self = this;
    let page = 1;
    const getUrl = function () {
      request(`${url}${page}`, function (error, response, body) {
        console.log(`Crawling ${url}${page}.`);
        if (!error && response.statusCode == 200) {
          const info = JSON.parse(body);
          if (Array.isArray(info.demos)) {
            for (let i = 0; i < info.demos.length; i++) {
              const data = info.demos[i];
              self.addUrl(data.url);
              self.addTag(data.url, 'audiocrawl.co');
              if (Array.isArray(data.tags)) {
                for (let j = 0; j < data.tags.length; j++) {
                  self.addTag(data.url, data.tags[j].title);
                }
              }
              self.addSource(data.url, 'http://audiocrawl.co/');
              self.addProperty(data.url, 'title', data.title);
              self.addProperty(data.url, 'image', data.image);
            }
            // move on to next page
            page++;
            getUrl();
          } else {
            cb();
          }
        } else {
          cb();
        }
      });
    };
    getUrl();
  }
}


text:
'use strict';

var helpers = require('./helpers');
var stormpath = require('./stormpath');

/**
 * This callback, when called, will simply continue processing the HTTP
 * request.
 *
 * @callback nextCallback
 */

/**
 * Assert that a user is logged into an account before allowing the user to
 * continue.  If the user is not logged in, they will be redirected to the login
 * page.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request if the user is authenticated.
 */
module.exports.loginRequired = function(req, res, next) {
  if (!req.user || !req.stormpathSession || !req.stormpathSession.user) {
    // Wipe req.user, just in case.
    req.user = undefined;

    var url = req.app.get('stormpathLoginUrl') + '?next=' + encodeURIComponent(req.originalUrl);
    res.redirect(302, url);
  } else {
    next();
  }
};

/**
 * Assert that a user is a member of one or more groups before allowing the user
 * to continue.  If the user is not logged in, or does not meet the group
 * requirements, they will be redirected to the login page.
 *
 * @method
 *
 * @param {String[]} groups - A list of groups to assert membership in.  Groups
 *   must be specified by group name.
 * @param {Boolean} [all=true] - Should we assert the user is a member of all groups,
 *   or just one?
 *
 * @returns {Function} Returns an express middleware which asserts a user's
 *   group membership, and only allows the user to continue if the assertions
 *   are true.
 */
module.exports.groupsRequired = function(groups, all) {
  all = all === false ? false : true;

  return function(req, res, next) {
    // Ensure the user is logged in.
    if (!req.user || !req.stormpathSession || !req.stormpathSession.user) {
      // Wipe req.user, just in case.
      req.user = undefined;

      var url = req.app.get('stormpathLoginUrl') + '?next=' + encodeURIComponent(req.originalUrl);
      res.redirect(302, url);

    // If this user must be a member of all groups, we'll ensure that is the
    // case.
    } else {
      var done = groups.length;
      var safe = false;

      req.user.getGroups(function(err, grps) {
        if (err) {
          helpers.render(req.app.get('stormpathUnauthorizedView'), res);
          req.app.get('stormpathLogger').info('Could not fetch user ' + req.user.email + '\'s groups.');
        } else {
          // Iterate through each group on the user's account, checking to see
          // whether or not it's one of the required groups.
          grps.each(function(group, c) {
            if (groups.indexOf(group.name) > -1) {
              if (!all || --done === 0) {
                safe = true;
                next();
              }
            }
            c();
          },
          // If we get here, it means the user didn't meet the requirements,
          // so we'll send them to the login page with the ?next querystring set.
          function() {
            if (!safe) {
              helpers.render(req.app.get('stormpathUnauthorizedView'), res);
              req.app.get('stormpathLogger').info('User ' + req.user.email + ' attempted to access a protected endpoint but did not meet the group check requirements.');
            }
          });
        }
      });
    }
  };
};

/**
 * Assert that a user has specified valid API credentials before allowing them
 * to continue.  If the user's credentials are invalid, a 401 will be returned
 * along with an appropriate error message.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request if the user is authenticated.
 */
module.exports.apiAuthenticationRequired = function(req, res, next) {
  // Wipe user data in case it was previously set by helpers.getUser().
  req.user = undefined;
  req.permissions = undefined;
  res.locals.user = undefined;
  res.locals.permissions = undefined;

  if (!req.headers.authorization) {
    req.app.get('stormpathLogger').info('User attempted to access a protected API endpoint with invalid credentials.');
    res.status(401).json({ error: 'Invalid API credentials.' });
  } else {
    req.app.get('stormpathApplication').authenticateApiRequest({ request: req }, function(err, authResult) {
      if (err) {
        req.app.get('stormpathLogger').info('Attempted to authenticate a user via the HTTP authorization header, but invalid credentials were supplied.');
        res.status(401).json({ error: 'Invalid API credentials.' });
      } else {
        authResult.getAccount(function(err, account) {
          if (err) {
            req.app.get('stormpathLogger').info('Attempted to retrieve a user\'s account, but this operation failed.');
            res.status(401).json({ error: 'Invalid API credentials.' });
            return;
          }

          helpers.expandAccount(req.app, account, function(err, expandedAccount) {
            if (err) {
              req.app.get('stormpathLogger').info('Attempted to expand a user\'s account, but this operation failed.');
              res.status(401).json({ error: 'Invalid API credentials.' });
              return;
            }

            res.locals.user = expandedAccount;
            res.locals.permissions = authResult.grantedScopes;
            req.user = expandedAccount;
            req.permissions = authResult.grantedScopes;

            return next();
          });
        });
      }
    });
  }
};

/**
 * Assert that a user is logged into an account before allowing the user to
 * continue.  If the user is not logged in, they will be redirected to the login
 * page.  This method allows the user to authenticate ANY WAY THEY WISH, and
 * responds appropriately given the Accept type of the client.  This is useful
 * for SPA type applications.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request if the user is authenticated.
 */
module.exports.authenticationRequired = function(req, res, next) {
  if (!req.user) {
    req.app.get('stormpathLogger').info('User attempted to access a protected endpoint with invalid credentials.');
    if (req.accepts(['html', 'json']) === 'html') {
      var url = req.app.get('stormpathLoginUrl') + '?next=' + encodeURIComponent(req.originalUrl);
      res.redirect(302, url);
    } else {
      res.status(401).json({ error: 'Invalid API credentials.' });
    }
  } else {
    next();
  }
};


text:
namespace TasteIt.Web.Infrastructure.Mapping
{
    public interface IMapTo<T>
        where T : class
    {
    }
}


text:
namespace {

class StatementErrorHandler : public sql::ErrorDelegate {
 public:
  StatementErrorHandler() : error_(SQLITE_OK) {}

  virtual int OnError(int error, sql::Connection* connection,
                      sql::Statement* stmt) OVERRIDE {
    error_ = error;
    const char* sql_txt = stmt ? stmt->GetSQLStatement() : NULL;
    sql_text_ = sql_txt ? sql_txt : "no statement available";
    return error;
  }

  int error() const { return error_; }

  void reset_error() {
    sql_text_.clear();
    error_ = SQLITE_OK;
  }

  const char* sql_statement() const { return sql_text_.c_str(); }

 protected:
  virtual ~StatementErrorHandler() {}

 private:
  int error_;
  std::string sql_text_;
};

class SQLiteFeaturesTest : public testing::Test {
 public:
  SQLiteFeaturesTest() : error_handler_(new StatementErrorHandler) {}

  void SetUp() {
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_));
    path_ = path_.AppendASCII("SQLStatementTest.db");
    file_util::Delete(path_, false);
    ASSERT_TRUE(db_.Open(path_));
    // The |error_handler_| will be called if any sqlite statement operation
    // returns an error code.
    db_.set_error_delegate(error_handler_);
  }

  void TearDown() {
    // If any error happened the original sql statement can be found in
    // error_handler_->sql_statement().
    EXPECT_EQ(SQLITE_OK, error_handler_->error());
    db_.Close();
    // If this fails something is going on with cleanup and later tests may
    // fail, so we want to identify problems right away.
    ASSERT_TRUE(file_util::Delete(path_, false));
  }

  sql::Connection& db() { return db_; }

  int sqlite_error() const { return error_handler_->error(); }
  void reset_error() const { error_handler_->reset_error(); }

 private:
  FilePath path_;
  sql::Connection db_;
  scoped_refptr<StatementErrorHandler> error_handler_;
};

// Do not include fts1 support, it is not useful, and nobody is
// looking at it.
TEST_F(SQLiteFeaturesTest, NoFTS1) {
  ASSERT_EQ(SQLITE_ERROR, db().ExecuteAndReturnErrorCode(
      "CREATE VIRTUAL TABLE foo USING fts1(x)"));
}

// fts2 is used for older history files, so we're signed on for
// keeping our version up-to-date.
// TODO(shess): Think up a crazy way to get out from having to support
// this forever.
TEST_F(SQLiteFeaturesTest, FTS2) {
  ASSERT_TRUE(db().Execute("CREATE VIRTUAL TABLE foo USING fts2(x)"));
}

// fts3 is used for current history files, and also for WebDatabase.
TEST_F(SQLiteFeaturesTest, FTS3) {
  ASSERT_TRUE(db().Execute("CREATE VIRTUAL TABLE foo USING fts3(x)"));
}

}  // namespace


text:
package edu.cmu.sphinx.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * A program that takes in a reference transcript and a hypothesis transcript and figures out how many gap insertion
 * errors are there. The hypothesis transcript file should contain timestamps for when each word was entered and exited.
 * <p>The gap insertion detection algorithm works as follows. It takes each hypothesized word individually and see
 * whether it falls into a non-speech region in the reference transcript. If it does, that hypothesized word is counted
 * as a gap insertion.
 */
public class GapInsertionDetector {

    private ReferenceFile referenceFile;
    private HypothesisFile hypothesisFile;
    private int totalGapInsertions;
    private boolean showGapInsertions;

    /**
     * Create a gap insertion detector to detect gap insertions using the given reference file and hypothesis file.
     *
     * @param referenceFile     the file of references
     * @param hypothesisFile    the file of hypotheses
     * @param showGapInsertions if true show gap insertions.
     */
    public GapInsertionDetector(String referenceFile, String hypothesisFile,
                                boolean showGapInsertions)
            throws IOException {
        this.referenceFile = new ReferenceFile(referenceFile);
        this.hypothesisFile = new HypothesisFile(hypothesisFile);
    }

    /**
     * Detect the gap insertion errors.
     *
     * @return the total number of gap insertion errors
     */
    public int detect() throws IOException {
        int gaps = 0;
        boolean done = false;
        ReferenceUtterance reference = referenceFile.nextUtterance();
        StringBuilder log = new StringBuilder();
        while (!done) {
            HypothesisWord word = hypothesisFile.nextWord();
            if (word != null) {
                boolean hasGapError = false;

                // go to the relevant reference utterance
                while (reference != null &&
                        reference.getEndTime() < word.getStartTime()) {
                    reference = referenceFile.nextUtterance();
                }

                // 'reference' should be the relevant one now
                if (reference != null) {
                    if (reference.isSilenceGap()) {
                        hasGapError = true;
                    } else {
                        while (reference.getEndTime() < word.getEndTime()) {
                            reference = referenceFile.nextUtterance();
                            if (reference == null ||
                                    reference.isSilenceGap()) {
                                hasGapError = true;
                                break;
                            }
                        }
                    }
                } else {
                    // if no more reference words, this is a gap insertion
                    hasGapError = true;
                }

                if (hasGapError) {
                    gaps++;
                    if (showGapInsertions) {
                        log.append("GapInsError: Utterance: ").append(hypothesisFile.getUtteranceCount())
                                .append(" Word: ").append(word.getText()).append(" (")
                                .append(word.getStartTime()).append(',').append(word.getEndTime()).append("). ");
                        if (reference != null) {
                            assert reference.isSilenceGap();
                            log.append("Reference: <sil> (").append(reference.getStartTime())
                                    .append(',').append(reference.getEndTime()).append(')');
                        }
                        log.append('\n');
                    }
                }
            } else {
                done = true;
            }
        }
        totalGapInsertions += gaps;
        if (showGapInsertions) {
            System.out.println(log);
        }
        return gaps;
    }

    /**
     * A command line program for detecting gap insertion errors. To run this program, type: <code> java
     * GapInsertionDetector {propsFile} {referenceFile} {hypothesisFile} </code> The propsFile need to have only one
     * property: <code> edu.cmu.sphinx.util.GapInsertionDetector.showGapInsertions=true/false </code>
     */
    public static void main(String[] argv) {

        if (argv.length < 2) {
            System.out.println("Usage: java GapInsertionDetector " +
                    "<referenceFile> <hypothesisFile>");
        }
        try {
            String referenceFile = argv[0];
            String hypothesisFile = argv[1];

            GapInsertionDetector gid = new GapInsertionDetector
                    (referenceFile, hypothesisFile, true);
            System.out.println("# of gap insertions: " + gid.detect());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * Creates a ReferenceFile.
 */
class ReferenceFile {

    private BufferedReader reader;

    /**
     * Creates a ReferenceFile, given the name of the reference file.
     *
     * @param fileName the name of the reference file
     */
    ReferenceFile(String fileName) throws IOException {
        reader = new BufferedReader(new FileReader(fileName));
    }

    /**
     * Returns the next available ReferenceUtterance. This method skips all the silence gaps.
     *
     * @return the next available ReferenceUtterance, or null if the end of file has been reached.
     */
    ReferenceUtterance nextUtterance() throws IOException {
        String line = reader.readLine();
        if (line != null) {
            return new ReferenceUtterance(line);
        } else {
            return null;
        }
    }
}

/**
 * Converts a line in the HUB-4 .stm reference file into an object.
 */
class ReferenceUtterance {

    private boolean isSilenceGap;
    private final float startTime;
    private final float endTime;
    private final String[] words;

    /**
     * Creates a ReferenceUtterance from the given line of reference.
     *
     * @param line the line of reference, in the format: [test_name] [category] [speaker_name|"inter_segment_gap"]
     *             [start_time] [end_time] [<params>] [reference_text]
     */
    ReferenceUtterance(String line) {
        StringTokenizer st = new StringTokenizer(line);
        st.nextToken();                 // parse the test set name
        st.nextToken();                 // parse category
        String type = st.nextToken();   // parse speaker
        if (type.equals("inter_segment_gap")) {
            isSilenceGap = true;
        }
        startTime = Float.parseFloat(st.nextToken()); // parse start time
        endTime = Float.parseFloat(st.nextToken());   // parse end time

        if (st.hasMoreTokens()) {
            st.nextToken();                               // parse <...>
            words = new String[st.countTokens()];
            for (int i = 0; i < words.length; i++) {
                words[i] = st.nextToken();
            }
        } else {
            words = new String[0];
        }
    }

    /**
     * Returns true if this is a silence gap.
     *
     * @return true if this is a silence gap, false otherwise.
     */
    boolean isSilenceGap() {
        return isSilenceGap;
    }

    /**
     * Returns the starting time (in seconds) of this utterance.
     *
     * @return the starting time of this utterance
     */
    float getStartTime() {
        return startTime;
    }

    /**
     * Returns the ending time (in seconds) of this utterance.
     *
     * @return the ending time of this utterance
     */
    float getEndTime() {
        return endTime;
    }

    /**
     * Returns the text of this utterance.
     *
     * @return the text of this utterance
     */
    String[] getWords() {
        return words;
    }
}

class HypothesisFile {

    private BufferedReader reader;
    private Iterator<HypothesisWord> iterator;
    private int utteranceCount;

    /**
     * Creates a HypothesisFile from the given file.
     *
     * @param fileName the name of the hypothesis file
     */
    HypothesisFile(String fileName) throws IOException {
        reader = new BufferedReader(new FileReader(fileName));
    }

    /**
     * Returns the next hypothesized word in the hypothesis file.
     *
     * @return the next hypothesized word
     */
    HypothesisWord nextWord() throws IOException {
        if (iterator == null || !iterator.hasNext()) {
            HypothesisUtterance utterance = nextUtterance();
            if (utterance != null) {
                iterator = utterance.getWords().iterator();
            } else {
                iterator = null;
            }
        }
        if (iterator == null) {
            return null;
        } else {
            return iterator.next();
        }
    }

    /**
     * Returns the next available hypothesis utterance.
     *
     * @return the next available hypothesis utterance, or null if the end of file has been reached
     */
    private HypothesisUtterance nextUtterance() throws IOException {
        String line = reader.readLine();
        if (line != null) {
            utteranceCount++;
            HypothesisUtterance utterance = new HypothesisUtterance(line);
            if (utterance.getWordCount() <= 0) {
                return nextUtterance();
            } else {
                return utterance;
            }
        } else {
            return null;
        }
    }

    /**
     * Returns the utterance count.
     *
     * @return the utterance count
     */
    public int getUtteranceCount() {
        return utteranceCount;
    }
}

/**
 * A hypothesis utterance, which will give you a list of hypothesis words.
 */
class HypothesisUtterance {

    private final List<HypothesisWord> words;
    private float startTime;
    private float endTime;

    /**
     * Creates a hypothesis utterance from a line of input describing the hypothesis.
     */
    HypothesisUtterance(String line) {
        words = new LinkedList<HypothesisWord>();
        StringTokenizer st = new StringTokenizer(line, " \t\n\r\f(),");
        while (st.hasMoreTokens()) {
            String text = st.nextToken();
            try {
                float myStartTime = Float.parseFloat(st.nextToken());
                float myEndTime = Float.parseFloat(st.nextToken());
                HypothesisWord word = new HypothesisWord
                        (text, myStartTime, myEndTime);
                words.add(word);
            } catch (NumberFormatException nfe) {
                System.out.println("NumberFormatException at line: " + line);
                nfe.printStackTrace();
            }
        }
        if (!words.isEmpty()) {
            HypothesisWord firstWord = words.get(0);
            startTime = firstWord.getStartTime();
            HypothesisWord lastWord =
                    words.get(words.size() - 1);
            endTime = lastWord.getEndTime();
        }
    }

    /**
     * Returns the number of words in this hypothesis.
     *
     * @return the number of words in this hypothesis
     */
    int getWordCount() {
        return words.size();
    }

    /**
     * Returns a list of the words in this hypothesis.
     *
     * @return a list of the words in this hypothesis
     */
    List<HypothesisWord> getWords() {
        List<HypothesisWord> newList = new LinkedList<HypothesisWord>();
        newList.addAll(words);
        return newList;
    }

    /**
     * Returns the start time of this hypothesis.
     *
     * @return the start time of this hypothesis
     */
    float getStartTime() {
        return startTime;
    }

    /**
     * Returns the end time of this hypothesis.
     *
     * @return the end time of this hypothesis
     */
    float getEndTime() {
        return endTime;
    }
}

/**
 * A word in the hypothesis, containing information about when the word started and ended.
 */
class HypothesisWord {

    private final String text;
    private final float startTime;
    private final float endTime;

    /**
     * Constructs a hypothesis word with the given start and end times.
     *
     * @param text      the text of the hypothesized word
     * @param startTime the starting time of the word
     * @param endTime   the ending time of the word
     */
    HypothesisWord(String text, float startTime, float endTime) {
        this.text = text;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    /**
     * Returns the text of the word.
     *
     * @return the text of the word
     */
    String getText() {
        return text;
    }

    /**
     * Returns the starting time of the word.
     *
     * @return the starting time of the word
     */
    float getStartTime() {
        return startTime;
    }

    /**
     * Returns the ending time of the word.
     *
     * @return the ending time of the word
     */
    float getEndTime() {
        return endTime;
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Relationships in ArchiMate</title>
<link href="../Styles/style.css" rel="stylesheet" type="text/css" />

Relationships in ArchiMate

You can view all of the legal ArchiMate relationships between entities. You can access this window from the Help | ArchiMate Relationships menu item. These are read-only and for informational purposes only.

Relationships matrix


text: Scripts to use with Docker, along with example Dockerfile's


text:
<?php

namespace Ds\Bundle\CommunicationBundle\Controller\Api\Rest;

use Ds\Bundle\ApiBundle\Controller\Api\Rest\AbstractController;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use FOS\RestBundle\Controller\Annotations\NamePrefix;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;

/**
 * Class TemplateController
 *
 * @RouteResource("template")
 * @Route("/communication")
 * @NamePrefix("ds_communication_api_rest_")
 */
class TemplateController extends AbstractController
{
    /**
     * Get collection action
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @AclAncestor("ds.communication.template.view")
     * @QueryParam(name="page", requirements="\d+", nullable=true)
     * @QueryParam(name="limit", requirements="\d+", nullable=true)
     */
    public function cgetAction()
    {
        $request = $this->get('request');
        $page = (integer) $request->get('page', 1);
        $limit = (integer) $request->get('limit', self::ITEMS_PER_PAGE);
        $criteria = $this->getFilterCriteria($this->getSupportedQueryParameters(__FUNCTION__));

        return $this->handleGetListRequest($page, $limit, $criteria);
    }

    /**
     * Get action
     *
     * @param integer $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @AclAncestor("ds.communication.template.view")
     */
    public function getAction($id)
    {
        return $this->handleGetRequest($id);
    }

    /**
     * Put action
     *
     * @param integer $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @AclAncestor("ds.communication.template.edit")
     */
    public function putAction($id)
    {
        return $this->handleUpdateRequest($id);
    }

    /**
     * Post action
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @AclAncestor("ds.communication.template.create")
     */
    public function postAction()
    {
        return $this->handleCreateRequest();
    }

    /**
     * Delete action
     *
     * @param integer $id
     * @return \Symfony\Component\HttpFoundation\Response
     * @AclAncestor("ds.communication.template.delete")
     */
    public function deleteAction($id)
    {
        return $this->handleDeleteRequest($id);
    }

    /**
     * {@inheritdoc}
     */
    public function getForm()
    {
        return $this->get('ds.communication.form.api.template');
    }

    /**
     * {@inheritdoc}
     */
    public function getFormHandler()
    {
        return $this->get('ds.communication.form.handler.template');
    }

    /**
     * {@inheritdoc}
     */
    public function getManager()
    {
        return $this->get('ds.communication.manager.template');
    }

    /**
     * {@inheritdoc}
     */
    protected function transformEntityField($field, &$value)
    {
        switch ($field) {
            default:
                parent::transformEntityField($field, $value);
        }
    }
}


text:
from flask_babel import gettext

from . import api

@api.route ('/fake')
def index():
    return gettext(u'Hello API!')