text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>IDL Definitions</title>
<link rel='stylesheet' type='text/css' href='./spec.css' />
<link rel='stylesheet' type='text/css' href='W3C-REC.css' />
<link rel='next' href='java-binding.html' />
<link rel='contents' href='Overview.html#contents' />
<link rel='index' href='def-index.html' />
<link rel='previous' href='ranges.html' />

previous   next   contents   index

13 November,
2000

Appendix A: IDL Definitions

This appendix contains the complete OMG IDL [OMGIDL] for the Level 2 Document
Object Model Traversal and Range definitions. The definitions are
divided into Traversal, and Range.

The IDL files are also available as: http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/idl.zip

A.1: Document Object Model
Traversal

traversal.idl:

// File: traversal.idl

#ifndef _TRAVERSAL_IDL_
#define _TRAVERSAL_IDL_

#include "dom.idl"

#pragma prefix "dom.w3c.org"
module traversal
{

  typedef dom::Node Node;

  interface NodeFilter;

  // Introduced in DOM Level 2:
  interface NodeIterator {
    readonly attribute Node             root;
    readonly attribute unsigned long    whatToShow;
    readonly attribute NodeFilter       filter;
    readonly attribute boolean          expandEntityReferences;
    Node               nextNode()
                                        raises(dom::DOMException);
    Node               previousNode()
                                        raises(dom::DOMException);
    void               detach();
  };

  // Introduced in DOM Level 2:
  interface NodeFilter {

    // Constants returned by acceptNode
    const short               FILTER_ACCEPT                  = 1;
    const short               FILTER_REJECT                  = 2;
    const short               FILTER_SKIP                    = 3;

    // Constants for whatToShow
    const unsigned long       SHOW_ALL                       = 0xFFFFFFFF;
    const unsigned long       SHOW_ELEMENT                   = 0x00000001;
    const unsigned long       SHOW_ATTRIBUTE                 = 0x00000002;
    const unsigned long       SHOW_TEXT                      = 0x00000004;
    const unsigned long       SHOW_CDATA_SECTION             = 0x00000008;
    const unsigned long       SHOW_ENTITY_REFERENCE          = 0x00000010;
    const unsigned long       SHOW_ENTITY                    = 0x00000020;
    const unsigned long       SHOW_PROCESSING_INSTRUCTION    = 0x00000040;
    const unsigned long       SHOW_COMMENT                   = 0x00000080;
    const unsigned long       SHOW_DOCUMENT                  = 0x00000100;
    const unsigned long       SHOW_DOCUMENT_TYPE             = 0x00000200;
    const unsigned long       SHOW_DOCUMENT_FRAGMENT         = 0x00000400;
    const unsigned long       SHOW_NOTATION                  = 0x00000800;

    short              acceptNode(in Node n);
  };

  // Introduced in DOM Level 2:
  interface TreeWalker {
    readonly attribute Node             root;
    readonly attribute unsigned long    whatToShow;
    readonly attribute NodeFilter       filter;
    readonly attribute boolean          expandEntityReferences;
             attribute Node             currentNode;
                                        // raises(dom::DOMException) on setting

    Node               parentNode();
    Node               firstChild();
    Node               lastChild();
    Node               previousSibling();
    Node               nextSibling();
    Node               previousNode();
    Node               nextNode();
  };

  // Introduced in DOM Level 2:
  interface DocumentTraversal {
    NodeIterator       createNodeIterator(in Node root,
                                          in unsigned long whatToShow,
                                          in NodeFilter filter,
                                          in boolean entityReferenceExpansion)
                                        raises(dom::DOMException);
    TreeWalker         createTreeWalker(in Node root,
                                        in unsigned long whatToShow,
                                        in NodeFilter filter,
                                        in boolean entityReferenceExpansion)
                                        raises(dom::DOMException);
  };
};

#endif // _TRAVERSAL_IDL_

A.2: Document Object Model
Range

ranges.idl:

// File: ranges.idl

#ifndef _RANGES_IDL_
#define _RANGES_IDL_

#include "dom.idl"

#pragma prefix "dom.w3c.org"
module ranges
{

  typedef dom::Node Node;
  typedef dom::DocumentFragment DocumentFragment;
  typedef dom::DOMString DOMString;

  // Introduced in DOM Level 2:
  exception RangeException {
    unsigned short   code;
  };
  // RangeExceptionCode
  const unsigned short      BAD_BOUNDARYPOINTS_ERR         = 1;
  const unsigned short      INVALID_NODE_TYPE_ERR          = 2;

  // Introduced in DOM Level 2:
  interface Range {
    readonly attribute Node             startContainer;
                                        // raises(dom::DOMException) on retrieval

    readonly attribute long             startOffset;
                                        // raises(dom::DOMException) on retrieval

    readonly attribute Node             endContainer;
                                        // raises(dom::DOMException) on retrieval

    readonly attribute long             endOffset;
                                        // raises(dom::DOMException) on retrieval

    readonly attribute boolean          collapsed;
                                        // raises(dom::DOMException) on retrieval

    readonly attribute Node             commonAncestorContainer;
                                        // raises(dom::DOMException) on retrieval

    void               setStart(in Node refNode,
                                in long offset)
                                        raises(RangeException,
                                               dom::DOMException);
    void               setEnd(in Node refNode,
                              in long offset)
                                        raises(RangeException,
                                               dom::DOMException);
    void               setStartBefore(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);
    void               setStartAfter(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);
    void               setEndBefore(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);
    void               setEndAfter(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);
    void               collapse(in boolean toStart)
                                        raises(dom::DOMException);
    void               selectNode(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);
    void               selectNodeContents(in Node refNode)
                                        raises(RangeException,
                                               dom::DOMException);

    // CompareHow
    const unsigned short      START_TO_START                 = 0;
    const unsigned short      START_TO_END                   = 1;
    const unsigned short      END_TO_END                     = 2;
    const unsigned short      END_TO_START                   = 3;

    short              compareBoundaryPoints(in unsigned short how,
                                             in Range sourceRange)
                                        raises(dom::DOMException);
    void               deleteContents()
                                        raises(dom::DOMException);
    DocumentFragment   extractContents()
                                        raises(dom::DOMException);
    DocumentFragment   cloneContents()
                                        raises(dom::DOMException);
    void               insertNode(in Node newNode)
                                        raises(dom::DOMException,
                                               RangeException);
    void               surroundContents(in Node newParent)
                                        raises(dom::DOMException,
                                               RangeException);
    Range              cloneRange()
                                        raises(dom::DOMException);
    DOMString          toString()
                                        raises(dom::DOMException);
    void               detach()
                                        raises(dom::DOMException);
  };

  // Introduced in DOM Level 2:
  interface DocumentRange {
    Range              createRange();
  };
};

#endif // _RANGES_IDL_

previous   next   contents   index


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Svetsoft.Nmea.Tests
{
    [TestClass]
    public class RmcSentenceTests
    {
        /// <summary>
        ///     Checks whether a parsed RMC sentence from the NMEA specification equals the string it was built from.
        /// </summary>
        [TestMethod]
        public void ParseGprmcSentence()
        {
            var sentence = new RmcSentence("$GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62");

            // NmeaSentence (Inherited)
            Assert.AreEqual("$GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62", sentence.Sentence);
            Assert.AreEqual("GPRMC", sentence.MessageType);
            Assert.AreEqual("62", sentence.Checksum);
            CollectionAssert.AreEqual(new[]
            {
                "081836",
                "A",
                "3751.65",
                "S",
                "14507.36",
                "E",
                "000.0",
                "360.0",
                "130998",
                "011.3",
                "E"
            }, sentence.Fields);

            // RMC-specific
            Assert.AreEqual(Status.ActiveValue, sentence.NavigationState);
            Assert.AreEqual(3751.65, sentence.Position.Latitude.Sexagesimal.Degrees);
            Assert.AreEqual(LatitudeHemisphere.South, sentence.Position.Latitude.Hemisphere);
            Assert.AreEqual(14507.36, sentence.Position.Longitude.Sexagesimal.Degrees);
            Assert.AreEqual(LongitudeHemisphere.East, sentence.Position.Longitude.Hemisphere);
            Assert.AreEqual(0.0, sentence.Speed.Value);
            Assert.AreEqual(SpeedUnit.Knots, sentence.Speed.Unit);
            Assert.AreEqual(360.0, sentence.Bearing.Value.Sexagesimal.Degrees);
            Assert.AreEqual(new DateTime(2098, 09, 13, 08, 18, 36), sentence.FixUtcDateTime);
            Assert.AreEqual(011.3, sentence.MagneticVariation.Sexagesimal.Degrees);
            Assert.AreEqual(LongitudeHemisphere.East, sentence.MagneticVariation.Hemisphere);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.checkpoint.channel;

import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter.ChannelStateWriteResult;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.state.AbstractChannelStateHandle;
import org.apache.flink.runtime.state.CheckpointStreamFactory;
import org.apache.flink.runtime.state.CheckpointStreamFactory.CheckpointStateOutputStream;
import org.apache.flink.runtime.state.InputChannelStateHandle;
import org.apache.flink.runtime.state.ResultSubpartitionStateHandle;
import org.apache.flink.runtime.state.StreamStateHandle;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.function.RunnableWithException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.concurrent.NotThreadSafe;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;

import static java.util.Collections.emptyList;
import static org.apache.flink.runtime.state.CheckpointedStateScope.EXCLUSIVE;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;

/**
 * Writes channel state for a specific checkpoint-subtask-attempt triple.
 */
@NotThreadSafe
class ChannelStateCheckpointWriter {
	private static final Logger LOG = LoggerFactory.getLogger(ChannelStateCheckpointWriter.class);

	private final DataOutputStream dataStream;
	private final CheckpointStateOutputStream checkpointStream;
	private final ChannelStateWriteResult result;
	private final Map<InputChannelInfo, List<Long>> inputChannelOffsets = new HashMap<>();
	private final Map<ResultSubpartitionInfo, List<Long>> resultSubpartitionOffsets = new HashMap<>();
	private final ChannelStateSerializer serializer;
	private final long checkpointId;
	private boolean allInputsReceived = false;
	private boolean allOutputsReceived = false;
	private final RunnableWithException onComplete;

	ChannelStateCheckpointWriter(
			CheckpointStartRequest startCheckpointItem,
			CheckpointStreamFactory streamFactory,
			ChannelStateSerializer serializer,
			RunnableWithException onComplete) throws Exception {
		this(
			startCheckpointItem.getCheckpointId(),
			startCheckpointItem.getTargetResult(),
			streamFactory.createCheckpointStateOutputStream(EXCLUSIVE),
			serializer,
			onComplete);
	}

	ChannelStateCheckpointWriter(
			long checkpointId,
			ChannelStateWriteResult result,
			CheckpointStateOutputStream stream,
			ChannelStateSerializer serializer,
			RunnableWithException onComplete) throws Exception {
		this(checkpointId, result, serializer, onComplete, stream, new DataOutputStream(stream));
	}

	ChannelStateCheckpointWriter(
			long checkpointId,
			ChannelStateWriteResult result,
			ChannelStateSerializer serializer,
			RunnableWithException onComplete,
			CheckpointStateOutputStream checkpointStateOutputStream,
			DataOutputStream dataStream) throws Exception {
		this.checkpointId = checkpointId;
		this.result = checkNotNull(result);
		this.checkpointStream = checkNotNull(checkpointStateOutputStream);
		this.serializer = checkNotNull(serializer);
		this.dataStream = checkNotNull(dataStream);
		this.onComplete = checkNotNull(onComplete);
		runWithChecks(() -> serializer.writeHeader(dataStream));
	}

	void writeInput(InputChannelInfo info, Buffer... flinkBuffers) throws Exception {
		write(inputChannelOffsets, info, flinkBuffers, !allInputsReceived);
	}

	void writeOutput(ResultSubpartitionInfo info, Buffer... flinkBuffers) throws Exception {
		write(resultSubpartitionOffsets, info, flinkBuffers, !allOutputsReceived);
	}

	private <K> void write(Map<K, List<Long>> offsets, K key, Buffer[] flinkBuffers, boolean precondition) throws Exception {
		try {
			if (result.isDone()) {
				return;
			}
			runWithChecks(() -> {
				checkState(precondition);
				offsets
					.computeIfAbsent(key, unused -> new ArrayList<>())
					.add(checkpointStream.getPos());
				serializer.writeData(dataStream, flinkBuffers);
			});
		} finally {
			for (Buffer flinkBuffer : flinkBuffers) {
				flinkBuffer.recycleBuffer();
			}
		}
	}

	void completeInput() throws Exception {
		LOG.debug("complete input, output completed: {}", allOutputsReceived);
		complete(!allInputsReceived, () -> allInputsReceived = true);
	}

	void completeOutput() throws Exception {
		LOG.debug("complete output, input completed: {}", allInputsReceived);
		complete(!allOutputsReceived, () -> allOutputsReceived = true);
	}

	private void complete(boolean precondition, RunnableWithException complete) throws Exception {
		if (result.isDone()) {
			// likely after abort - only need to set the flag run onComplete callback
			doComplete(precondition, complete, onComplete);
		} else {
			runWithChecks(() -> doComplete(precondition, complete, onComplete, this::finishWriteAndResult));
		}
	}

	private void finishWriteAndResult() throws IOException {
		if (inputChannelOffsets.isEmpty() && resultSubpartitionOffsets.isEmpty()) {
			dataStream.close();
			result.inputChannelStateHandles.complete(emptyList());
			result.resultSubpartitionStateHandles.complete(emptyList());
			return;
		}
		dataStream.flush();
		StreamStateHandle underlying = checkpointStream.closeAndGetHandle();
		complete(
				result.inputChannelStateHandles,
				inputChannelOffsets,
				(chan, offsets) -> new InputChannelStateHandle(chan, underlying, offsets));
		complete(
				result.resultSubpartitionStateHandles,
				resultSubpartitionOffsets,
				(chan, offsets) -> new ResultSubpartitionStateHandle(chan, underlying, offsets));
	}

	private void doComplete(boolean precondition, RunnableWithException complete, RunnableWithException... callbacks) throws Exception {
		Preconditions.checkArgument(precondition);
		complete.run();
		if (allInputsReceived && allOutputsReceived) {
			for (RunnableWithException callback : callbacks) {
				callback.run();
			}
		}
	}

	private <I, H extends AbstractChannelStateHandle<I>> void complete(
			CompletableFuture<Collection<H>> future,
			Map<I, List<Long>> offsets,
			BiFunction<I, List<Long>, H> buildHandle) {
		final Collection<H> handles = new ArrayList<>();
		for (Map.Entry<I, List<Long>> e : offsets.entrySet()) {
			handles.add(buildHandle.apply(e.getKey(), e.getValue()));
		}
		future.complete(handles);
		LOG.debug("channel state write completed, checkpointId: {}, handles: {}", checkpointId, handles);
	}

	private void runWithChecks(RunnableWithException r) throws Exception {
		try {
			checkState(!result.isDone(), "result is already completed", result);
			r.run();
		} catch (Exception e) {
			fail(e);
			throw e;
		}
	}

	public void fail(Throwable e) throws Exception {
		result.fail(e);
		checkpointStream.close();
	}

}


text:
namespace chromeos {
namespace app_time {

// Type of usage restriction that can be applied to the installed app.
enum class AppRestriction {
  kUnknown,
  // Installed app is not available for the user.
  kBlocked,
  // Daily time limit is enforced. Installed app will become unavailable for
  // the user after time limit is reached on a given day.
  kTimeLimit,
};

// State of the app. Used for activity recording and status reporting. The enum
// values are persisted in user pref service. Existing values should never be
// deleted or reordered. New states should be appended at the end.
enum class AppState {
  // App is available for the user.
  kAvailable = 0,
  // App cannot be restricted. Used for important system apps.
  kAlwaysAvailable = 1,
  // App is not available for the user because of being blocked.
  kBlocked = 2,
  // App is not available for the user because daily time limit was reached.
  kLimitReached = 3,
  // App is uninstalled. Activity might still be preserved and reported for
  // recently uninstalled apps.
  kUninstalled = 4,
};

// Type of notification to show the child user.
enum class AppNotification {
  kUnknown,

  // Five minutes left before the application's time limit is reached.
  kFiveMinutes,

  // One minjute left before the application's time limit is reached.
  kOneMinute,

  // Application's time limit reached.
  kTimeLimitReached,

  // Application's time limit has been updated by parents.
  kTimeLimitChanged,

  // Application is blocked.
  kBlocked,

  // Application is unblocked.
  kAvailable
};

enum class ChromeAppActivityState {
  // The browser is active and hosts urls in its active tab which are not
  // whitelisted.
  kActive,

  // Same as |kActive| except the urls the browser hosts are whitelisted.
  kActiveWhitelisted,

  // The browser window is not active.
  kInactive,
};

// Identifies an app for app time limits.
// Different types of use different identifier format. ARC++ apps are identified
// by Android package name. Other types of apps use 32 character long Chrome
// specific app id.
class AppId {
 public:
  AppId(apps::mojom::AppType app_type, const std::string& app_id);
  AppId(const AppId&);
  AppId& operator=(const AppId&);
  AppId(AppId&&);
  AppId& operator=(AppId&&);
  ~AppId();

  apps::mojom::AppType app_type() const { return app_type_; }
  const std::string& app_id() const { return app_id_; }

  bool operator==(const AppId&) const;
  bool operator!=(const AppId&) const;
  bool operator<(const AppId&) const;
  friend std::ostream& operator<<(std::ostream&, const AppId&);

 private:
  apps::mojom::AppType app_type_ = apps::mojom::AppType::kUnknown;

  // Package name for |ARC| apps, 32 character long Chrome specific app id
  // otherwise.
  std::string app_id_;
};

struct PauseAppInfo {
  PauseAppInfo(const AppId& app, base::TimeDelta limit, bool show_dialog);

  AppId app_id;
  base::TimeDelta daily_limit;
  bool show_pause_dialog = true;
};

// Represents restriction that can be applied to an installed app.
class AppLimit {
 public:
  // Creates AppLimit.
  // |daily_limit| can only be set when |restriction| is kTimeLimit.
  // |daily_limit| needs to be in range of [0, 24] hours.
  AppLimit(AppRestriction restriction,
           base::Optional<base::TimeDelta> daily_limit,
           base::Time last_updated);
  AppLimit(const AppLimit&);
  AppLimit& operator=(const AppLimit&);
  AppLimit(AppLimit&&);
  AppLimit& operator=(AppLimit&&);
  ~AppLimit();

  AppRestriction restriction() const { return restriction_; }
  base::Time last_updated() const { return last_updated_; }
  const base::Optional<base::TimeDelta>& daily_limit() const {
    return daily_limit_;
  }

 private:
  // Usage restriction applied to the app.
  AppRestriction restriction_ = AppRestriction::kUnknown;

  // Daily usage limit. Only set |restriction| is kTimeLimit.
  // Has to be between 0 and 24 hours.
  base::Optional<base::TimeDelta> daily_limit_;

  // UTC timestamp for the last time the limit was updated.
  base::Time last_updated_;
};

// Contains information about app usage.
class AppActivity {
 public:
  class ActiveTime {
   public:
    static const base::TimeDelta kActiveTimeMergePrecision;

    // If |t1| and |t2| overlap or are within |kActiveTimeMergePrecision| of
    // each other, this static method creates a new ActiveTime with the earlier
    // of |t1|'s or |t2|'s |active_from| and the later of |t1|'s or |t2|'s
    // |active_to_|.
    static base::Optional<ActiveTime> Merge(const ActiveTime& t1,
                                            const ActiveTime& t2);

    ActiveTime(base::Time start, base::Time end);
    ActiveTime(const ActiveTime& rhs);
    ActiveTime& operator=(const ActiveTime& rhs);

    bool operator==(const ActiveTime&) const;
    bool operator!=(const ActiveTime&) const;

    // Returns whether |timestamp| is included in this time period.
    bool Contains(base::Time timestamp) const;

    // Returns whether |timestamp| is earlier than this time period's start.
    bool IsEarlierThan(base::Time timestamp) const;

    // Returns whether |timestamp| is later than this time period's end.
    bool IsLaterThan(base::Time timestamp) const;

    base::Time active_from() const { return active_from_; }
    void set_active_from(base::Time active_from);
    base::Time active_to() const { return active_to_; }
    void set_active_to(base::Time active_to);

   private:
    base::Time active_from_;
    base::Time active_to_;
  };

  // Creates AppActivity and sets current |app_state_|.
  explicit AppActivity(AppState app_state);
  AppActivity(AppState app_state, base::TimeDelta running_active_time);
  AppActivity(const AppActivity&);
  AppActivity& operator=(const AppActivity&);
  AppActivity(AppActivity&&);
  AppActivity& operator=(AppActivity&&);
  ~AppActivity();

  void SetAppState(AppState app_state);
  void SetAppActive(base::Time timestamp);
  void SetAppInactive(base::Time timestamp);

  // Called when reset time has been reached.
  // Resets |running_active_time_|.
  // If the application is currently running, uses |timestamp| as current time
  // to log activity.
  void ResetRunningActiveTime(base::Time timestamp);

  base::TimeDelta RunningActiveTime() const;

  // Updates |active_times_| to include the current activity. If the app is
  // active, it saves the activitity until |timestamp|.
  void CaptureOngoingActivity(base::Time timestamp);

  // Caller takes ownership of |active_times_| i.e. |active_times_| is moved and
  // thus becomes empty after this method is called. Called from
  // AppActivityRegistry::SaveAppActivity when the app activity is going to be
  // saved in user preference.
  std::vector<ActiveTime> TakeActiveTimes();

  bool is_active() const { return is_active_; }
  AppState app_state() const { return app_state_; }
  const std::vector<ActiveTime>& active_times() const { return active_times_; }
  AppNotification last_notification() const { return last_notification_; }

  void set_last_notification(AppNotification notification) {
    last_notification_ = notification;
  }

  // Chrome and web apps share the same time limit. Therefore, we need to have a
  // consistent |running_active_time_| across all web apps and chrome.
  void set_running_active_time(base::TimeDelta time) {
    DCHECK(!is_active_);
    running_active_time_ = time;
  }

 private:
  // boolean to specify if the application is active.
  bool is_active_ = false;

  AppNotification last_notification_ = AppNotification::kUnknown;

  // Current state of the app.
  // There might be relevant activity recoded for app that was uninstalled
  // recently.
  AppState app_state_ = AppState::kAvailable;

  // Keeps the sum of the active times since the last reset.
  base::TimeDelta running_active_time_;

  // The time app was active.
  std::vector<ActiveTime> active_times_;

  // Time tick for the last time the activity was updated.
  base::TimeTicks last_updated_time_ticks_;
};

}  // namespace app_time
}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_CHILD_ACCOUNTS_TIME_LIMITS_APP_TYPES_H_


text:
<?php
	function getSteemitUsername() {
		if (isset($_ENV['steemit_username'])) return $_ENV['steemit_username'];
		return null;
	}
?>
<!DOCTYPE html>

	<title>
		SportsPodium Pre-ICO
	</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

	<link rel="stylesheet" href="./bootstrap-3.3.7-dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="./bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">

The Pre-ICO for SportsPodium is finished.

		<?php include 'form-finished.php'; ?>


text:
This test project is built from a blank ionic app and allows to visually test the ionic date picker from original project,
to compare with current project that forks it.


text:
Listed in order or priority:

- ~~Add formatting to excerpt on posts page.~~ Done, 9.14.16
- ~~Add single.php and content-single.php.~~ Done, 9.14.16
- ~~Add comments to single blog posts.~~ Done, 9.14.16
- ~~Add page.php and content-page.php.~~ Done, 9.17.16
- ~~Add archive.php.~~ Done, 9.17.16
- ~~Add search.php and content-search.php.~~ Done, 9.17.16
- Add 404.php.
- Clean up index.php (remove unused content)
- Display categories and tags on posts


text:
package com.transitionseverywhere.utils;

import android.annotation.TargetApi;
import android.graphics.PointF;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Property;

/**
 * Created by Andrey Kulikov on 15.08.15.
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public abstract class PointFProperty<T> extends Property<T, PointF> {

    public PointFProperty() {
        super(PointF.class, null);
        // null instead of name here because it's used only for calling setter
        // and getter via reflection. but we have our own overridden set and get.
    }

    /**
     * Just default realisation. Some of properties can have no getter. Override for real getter
     */
    @Override
    @Nullable
    public PointF get(@NonNull T object) {
        return null;
    }

}


text:
require 'rubygems'
require 'bundler/setup'
require 'trakt_api'
# require 'vcr'
# require 'webmock'

# VCR.configure do |c|
#   c.cassette_library_dir     = 'spec/cassettes'
#   c.hook_into                :webmock
#   c.default_cassette_options = { :record => :new_episodes }
#   c.configure_rspec_metadata!
#   #c.debug_logger = $stdout
# end

RSpec.configure do |c|
  #c.extend VCR::RSpec::Macros
  c.treat_symbols_as_metadata_keys_with_true_values = true
end


text:
package com.cloud.network.topology;

import com.cloud.agent.api.Command;
import com.cloud.agent.api.PvlanSetupCommand;
import com.cloud.agent.manager.Commands;
import com.cloud.dc.DataCenter;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.PublicIpAddress;
import com.cloud.network.VpnUser;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.rules.AdvancedVpnRules;
import com.cloud.network.rules.DhcpEntryRules;
import com.cloud.network.rules.DhcpPvlanRules;
import com.cloud.network.rules.NetworkAclsRules;
import com.cloud.network.rules.NicPlugInOutRules;
import com.cloud.network.rules.PrivateGatewayRules;
import com.cloud.network.rules.PublicIpAclsRules;
import com.cloud.network.rules.StaticRoutesRules;
import com.cloud.network.rules.UserdataPwdRules;
import com.cloud.network.rules.VpcIpAssociationRules;
import com.cloud.network.vpc.NetworkACLItem;
import com.cloud.network.vpc.PrivateIpAddress;
import com.cloud.network.vpc.PrivateIpVO;
import com.cloud.network.vpc.StaticRouteProfile;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineProfile;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class AdvancedNetworkVisitor extends BasicNetworkVisitor {

    private static final Logger s_logger = LoggerFactory.getLogger(AdvancedNetworkVisitor.class);

    @Override
    public boolean visit(final UserdataPwdRules userdata) throws ResourceUnavailableException {
        final VirtualRouter router = userdata.getRouter();

        final Commands commands = new Commands(Command.OnError.Stop);
        final VirtualMachineProfile profile = userdata.getProfile();
        final NicVO nicVo = userdata.getNicVo();
        final UserVmVO userVM = userdata.getUserVM();

        _commandSetupHelper.createPasswordCommand(router, profile, nicVo, commands);
        _commandSetupHelper.createVmDataCommand(router, userVM, nicVo, userVM.getDetail("SSH.PublicKey"), commands);

        return _networkGeneralHelper.sendCommandsToRouter(router, commands);
    }

    @Override
    public boolean visit(final DhcpEntryRules dhcp) throws ResourceUnavailableException {
        final VirtualRouter router = dhcp.getRouter();

        final Commands commands = new Commands(Command.OnError.Stop);
        final NicVO nicVo = dhcp.getNicVo();
        final UserVmVO userVM = dhcp.getUserVM();

        _commandSetupHelper.createDhcpEntryCommand(router, userVM, nicVo, commands);

        return _networkGeneralHelper.sendCommandsToRouter(router, commands);
    }

    @Override
    public boolean visit(final NetworkAclsRules acls) throws ResourceUnavailableException {
        final VirtualRouter router = acls.getRouter();
        final Network network = acls.getNetwork();

        final Commands commands = new Commands(Command.OnError.Continue);
        final List<? extends NetworkACLItem> rules = acls.getRules();
        _commandSetupHelper.createNetworkACLsCommands(rules, router, commands, network.getId(), acls.isPrivateGateway());

        return _networkGeneralHelper.sendCommandsToRouter(router, commands);
    }

    @Override
    public boolean visit(final PublicIpAclsRules acls) throws ResourceUnavailableException {
        final VirtualRouter router = acls.getRouter();

        final Commands commands = new Commands(Command.OnError.Continue);
        final List<? extends NetworkACLItem> rules = acls.getRules();
        _commandSetupHelper.createPublicIpACLsCommands(rules, router, commands, acls.getPublicIp());

        return _networkGeneralHelper.sendCommandsToRouter(router, commands);
    }

    @Override
    public boolean visit(final VpcIpAssociationRules vpcip) throws ResourceUnavailableException {
        final VirtualRouter router = vpcip.getRouter();

        final Commands cmds = new Commands(Command.OnError.Continue);
        final Map<String, String> vlanMacAddress = vpcip.getVlanMacAddress();
        final List<PublicIpAddress> ipsToSend = vpcip.getIpsToSend();

        if (!ipsToSend.isEmpty()) {
            s_logger.debug("DEBUG::in AdvancedNetworkTopology --> will createVpcAssociatePublicIPCommands and send to router --> " + router.getId());
            _commandSetupHelper.createVpcAssociatePublicIPCommands(router, ipsToSend, cmds, vlanMacAddress);
            return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
        } else {
            return true;
        }
    }

    @Override
    public boolean visit(final AdvancedVpnRules vpnRules) throws ResourceUnavailableException {
        final VirtualRouter router = vpnRules.getRouter();
        final List<? extends VpnUser> users = vpnRules.getUsers();

        final Commands cmds = new Commands(Command.OnError.Continue);
        _commandSetupHelper.createApplyVpnUsersCommand(users, router, cmds);

        // Currently we receive just one answer from the agent. In the future we
        // have to parse individual answers and set
        // results accordingly
        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    }

    @Override
    public boolean visit(final PrivateGatewayRules privateGW) throws ResourceUnavailableException {
        final VirtualRouter router = privateGW.getRouter();
        final NicProfile nicProfile = privateGW.getNicProfile();

        final boolean isAddOperation = privateGW.isAddOperation();

        if (router.getState() == State.Running) {

            final PrivateIpVO ipVO = privateGW.retrivePrivateIP(this);
            final Network network = privateGW.retrievePrivateNetwork(this);

            final String netmask = NetUtils.getCidrNetmask(network.getCidr());
            final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, nicProfile.getMacAddress());

            final Commands cmds = new Commands(Command.OnError.Stop);
            _commandSetupHelper.createSetupPrivateGatewayCommand(router, ip, cmds, nicProfile, isAddOperation);

            try {
                if (_networkGeneralHelper.sendCommandsToRouter(router, cmds)) {
                    s_logger.debug("Successfully applied ip association for ip " + ip + " in vpc network " + network);
                    return true;
                } else {
                    s_logger.warn("Failed to associate ip address " + ip + " in vpc network " + network);
                    return false;
                }
            } catch (final Exception ex) {
                s_logger.warn("Failed to send  " + (isAddOperation ? "add " : "delete ") + " private network " + network + " commands to rotuer ");
                return false;
            }
        } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
            s_logger.debug("Router " + router.getInstanceName() + " is in " + router.getState() + ", so not sending setup private network command to the backend");
        } else {
            s_logger.warn("Unable to setup private gateway, virtual router " + router + " is not in the right state " + router.getState());

            throw new ResourceUnavailableException("Unable to setup Private gateway on the backend," + " virtual router " + router + " is not in the right state",
                    DataCenter.class, router.getDataCenterId());
        }
        return true;
    }

    @Override
    public boolean visit(final DhcpPvlanRules dhcp) throws ResourceUnavailableException {
        final VirtualRouter router = dhcp.getRouter();
        final PvlanSetupCommand setupCommand = dhcp.getSetupCommand();

        // In fact we send command to the host of router, we're not programming
        // router but the host
        final Commands cmds = new Commands(Command.OnError.Stop);
        cmds.addCommand(setupCommand);

        try {
            return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
        } catch (final ResourceUnavailableException e) {
            s_logger.warn("Timed Out", e);
            return false;
        }
    }

    @Override
    public boolean visit(final NicPlugInOutRules nicPlugInOutRules) throws ResourceUnavailableException {
        final VirtualRouter router = nicPlugInOutRules.getRouter();

        final Commands commands = nicPlugInOutRules.getNetUsageCommands();

        if (commands.size() > 0) {
            return _networkGeneralHelper.sendCommandsToRouter(router, commands);
        }
        return true;
    }

    @Override
    public boolean visit(final StaticRoutesRules staticRoutesRules) throws ResourceUnavailableException {
        final VirtualRouter router = staticRoutesRules.getRouter();
        final List<StaticRouteProfile> staticRoutes = staticRoutesRules.getStaticRoutes();

        final Commands cmds = new Commands(Command.OnError.Continue);
        _commandSetupHelper.createStaticRouteCommands(staticRoutes, router, cmds);

        return _networkGeneralHelper.sendCommandsToRouter(router, cmds);
    }
}


text:
function [areaList, smoothedAreaList] = mrmComputeMeshArea(msh, vertInds);
% Compute area for all or some triangles in a mesh.
%    [areaList, smoothedAreaList] = mrmComputeMeshArea(msh, [vertInds=[]]);
%
% Computes the area of all triangles in a mesh (vertInds=[]) or the area of
% the subset of triangles whose vertices are in the list of vertInds.
% (NOTE: all 3 of a triangle's vertices must be in the list for it to be
% counted.)
%
% The algorithm uses the initVertices (the vertices from the unsmoothed
% mesh). But, if you catch a second return arg, you can get the areas for
% the smoothed mesh verices too.
%
% HISTORY:
%  2005.08.03 RFD: wrote it.

if(~exist('vertInds','var')), vertInds = []; end

verts(1,:) = msh.initVertices(1,:)*msh.mmPerVox(1);
verts(2,:) = msh.initVertices(2,:)*msh.mmPerVox(2);
verts(3,:) = msh.initVertices(3,:)*msh.mmPerVox(3);

if(~isempty(vertInds))
    currentT = meshGet(msh,'triangles')+1;
    triInds = ismember(currentT(1,:), vertInds) ...
            & ismember(currentT(2,:), vertInds) ...
            & ismember(currentT(3,:), vertInds);
    triangles = currentT(:,triInds);
    clear triInds;
else
    triangles = meshGet(msh,'triangles')+1;
end

% compute all edge lengths
a = sqrt(sum((verts(:,triangles(1,:))-verts(:,triangles(2,:))).^2));
b = sqrt(sum((verts(:,triangles(2,:))-verts(:,triangles(3,:))).^2));
c = sqrt(sum((verts(:,triangles(3,:))-verts(:,triangles(1,:))).^2));

% find half the perimeter
s = (a+b+c)/2;

% Heron's formula:
areaList = sqrt(s.*(s-a).*(s-b).*(s-c));

% We occasionally get non-real vals for degenerate triangles.
areaList(~isreal(areaList)) = 0;

if(nargout>1)
    % do it again, this time with the smoothed vertices
    currentV = meshGet(msh,'vertices');
    verts(1,:) = currentV(1,:)*msh.mmPerVox(1);
    verts(2,:) = currentV(2,:)*msh.mmPerVox(2);
    verts(3,:) = currentV(3,:)*msh.mmPerVox(3);
    a = sqrt(sum((verts(:,triangles(1,:))-verts(:,triangles(2,:))).^2));
    b = sqrt(sum((verts(:,triangles(2,:))-verts(:,triangles(3,:))).^2));
    c = sqrt(sum((verts(:,triangles(3,:))-verts(:,triangles(1,:))).^2));
    s = (a+b+c)/2;
    smoothedAreaList = sqrt(s.*(s-a).*(s-b).*(s-c));
    smoothedAreaList(~isreal(smoothedAreaList)) = 0;
end

return;


text:
import PropTypes from 'prop-types';
import React from 'react';

import ThumbnailCardContent from './ThumbnailCardContent';

const ThumbnailCardAttachment = ({ attachment: { content }, disabled }) => (
  <ThumbnailCardContent content={content} disabled={disabled} />
);

ThumbnailCardAttachment.defaultProps = {
  disabled: undefined
};

ThumbnailCardAttachment.propTypes = {
  attachment: PropTypes.shape({
    content: PropTypes.shape({
      buttons: PropTypes.array,
      images: PropTypes.arrayOf(
        PropTypes.shape({
          alt: PropTypes.string.isRequired,
          tap: PropTypes.any,
          url: PropTypes.string.isRequired
        })
      ),
      subtitle: PropTypes.string,
      tap: PropTypes.any,
      text: PropTypes.string,
      title: PropTypes.string
    }).isRequired
  }).isRequired,
  disabled: PropTypes.bool
};

export default ThumbnailCardAttachment;


text:
require 'rack'
require 'peekarails/metrics'

module Peekarails
  class Rack

    attr_reader :app, :options

    def initialize app, options = {}
      @app = app
      @options = options
    end

    def call env
      request = ActionDispatch::Request.new(env)

      if request.filtered_path =~ /^\/assets\/*./
        return app.call(env)
      end

      context = {}
      context[:method] = request.request_method
      context[:path] = request.filtered_path
      context[:timestamp] = Time.now.to_i

      Thread.current[:peekarails_context] = context

      gc_before = GC.stat

      status, headers, body = nil

      begin
        status, headers, body = app.call(env)
      rescue Exception => exception
        context = Thread.current[:peekarails_context]
        context[:error] = true

        Peekarails::Metrics.record_request! context

        raise exception
      end

      gc_after = GC.stat

      context = Thread.current[:peekarails_context]

      context[:status] = status

      context[:gc_count] = (gc_after[:count] || 0) - (gc_before[:count] || 0)
      context[:gc_minor_count] = (gc_after[:minor_gc_count] || 0) - (gc_before[:minor_gc_count] || 0)
      context[:gc_major_count] = (gc_after[:major_gc_count] || 0) - (gc_before[:major_gc_count] || 0)
      context[:gc_heap_used] = gc_after[:heap_used]
      context[:gc_heap_free] = gc_after[:heap_length] - gc_after[:heap_used]

      begin
        Peekarails::Metrics.record_request! context
      rescue Exception => exception
        Rails.logger.error "Recording error in peek-a-rails:\n#{exception}\n#{context.inspect}"
      end

      [status, headers, body]
    end
  end
end


text:
ActionController::Routing::Routes.draw do |map|
  map.namespace :admin do |admin|
    admin.resources :extracts do |page|
      page.resources :children, :controller => "pages",    :path_prefix => "/admin/extracts/:page_id", :except => [:index]
      page.resources :children, :controller => "extracts", :path_prefix => "/admin/extracts/:page_id", :only => [:index]
    end
  end
end


text:
int screenId = 0;

extern json_spirit::Value GetNetworkHashPS(int lookup, int height);
extern json_spirit::Value ValueFromAmount(int64 amount);
//extern int64 GetTotalSupply();

ClickableLabel::ClickableLabel(QWidget * parent ) :
    QLabel(parent)
{
}

ClickableLabel::~ClickableLabel()
{
}

void ClickableLabel::mousePressEvent ( QMouseEvent * event )
{
    emit clicked();
}

GuiHeader::~GuiHeader(){
}

GuiHeader::GuiHeader(QWidget *parent) :
    QWidget(parent),
    clientModel(0),
    walletModel(0),
    currentBalance(-1),
    currentUnconfirmedBalance(-1),
    currentImmatureBalance(-1)
{

    QFont largeFont; largeFont.setPixelSize(20);
    QFont boldFont; boldFont.setBold(true);
    QFont font;   font.setFamily(":/font/montserrat-bold");       font.setPixelSize(16);       font.setStyleStrategy(QFont::PreferAntialias);       font.setBold(true);
    QFont fontV;   fontV.setFamily(":/font/montserrat-bold");       fontV.setPixelSize(9);       fontV.setStyleStrategy(QFont::PreferAntialias);       fontV.setBold(false);

    this->setFixedSize(1000,120);

    backGround = new QWidget(this);
    backGround->setFixedSize(1000,120);
    backGround->setStyleSheet("background: #191923"); //background-color: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #191923, stop: 1 #87878D)

    bottomLine = new QWidget(this);
    bottomLine->setFixedSize(1000,5);
    bottomLine->move(0,115);
    bottomLine->setStyleSheet("background-color: #3c3c3b");

    chipCoinLogo = new ClickableLabel(this);
    chipCoinLogo->setPixmap( QPixmap(":/icons/gui_header_logo"));
    chipCoinLogo->setContentsMargins(0,0,0,0);
    chipCoinLogo->move(15,35-10);
    chipCoinLogo->adjustSize();

    versionLabel = new QLabel(this);
    versionLabel->setFont(fontV);
    versionLabel->move(0,90);
    versionLabel->setFixedWidth(95);
    versionLabel->setAlignment(Qt::AlignCenter);
    versionLabel->setStyleSheet("color: #FFFFFF");
    //versionLabel->setText("v 0.9.15.5");

    QWidget *separatorLine = new QWidget(this);
    separatorLine->setFixedSize(2,115);
    separatorLine->move(93,0);
    separatorLine->setStyleSheet("background-color: #3c3c3b");

    walletOverview = new QFrame(this);
    walletOverview->setStyleSheet("QFrame {color: #FFFFFF;} .QLabel { border: none; background: none; }");

    QWidget *walletOverviewBox = new QWidget(walletOverview);
    walletOverviewBox->setStyleSheet(".QWidget {background-color: rgba(0,0,0, 0);}");

    QLabel *balanceTitle = new QLabel("Balance:");

    QLabel *unconfirmedTitle = new QLabel("Unconfirmed:");

    QLabel *immatureTitle = new QLabel("Immature:");

    labelBalance = new QLabel();
    labelBalance->setFont(boldFont);
    labelBalance->setText("---");
    labelBalance->setCursor(Qt::IBeamCursor);
    labelBalance->setTextInteractionFlags(Qt::TextSelectableByMouse);

    labelUnconfirmedBalance = new QLabel();
    labelUnconfirmedBalance->setFont(boldFont);
    labelUnconfirmedBalance->setText("---");
    labelUnconfirmedBalance->setCursor(Qt::IBeamCursor);
    labelUnconfirmedBalance->setTextInteractionFlags(Qt::TextSelectableByMouse);

    labelImmatureBalance = new QLabel();
    labelImmatureBalance->setFont(boldFont);
    labelImmatureBalance->setText("---");
    labelImmatureBalance->setCursor(Qt::IBeamCursor);
    labelImmatureBalance->setTextInteractionFlags(Qt::TextSelectableByMouse);

    walletTitle = new QLabel(walletOverview);
    walletTitle->setStyleSheet("QLabel { color: #FFFFFF; }");
    walletTitle->setFont(font);
    walletTitle->setText("Bank (out of sync)");
    walletTitle->setFixedWidth(200);
    walletTitle->move(3,3);

    QFormLayout *formLayout = new QFormLayout();

    formLayout->addRow(balanceTitle, labelBalance);
    formLayout->addRow(unconfirmedTitle, labelUnconfirmedBalance);
    formLayout->addRow(immatureTitle, labelImmatureBalance);

    formLayout->setContentsMargins(10,10,10,10);
    formLayout->setVerticalSpacing(8);
    formLayout->setHorizontalSpacing(10);
    walletOverviewBox->setLayout(formLayout);

    QHBoxLayout  *boxLayout = new QHBoxLayout();
    boxLayout->addWidget(walletOverviewBox);
    boxLayout->setContentsMargins(0,30,0,0);
    walletOverview->setLayout(boxLayout);

    walletOverview->setMinimumWidth(250);
    walletOverview->setMaximumWidth(250);

    recentOverview = new QFrame(this);
    recentOverview->setStyleSheet("QFrame {color: #FFFFFF;} .QLabel { border: none; background: none; }");

    QWidget *recentOverviewBox = new QWidget(recentOverview);
    recentOverviewBox->setStyleSheet(".QWidget {background-color: rgba(0,0,0, 0);}");

    QLabel *recentTitle = new QLabel(recentOverview);
    recentTitle->setStyleSheet("QLabel { color: #FFFFFF; }");
    recentTitle->setFont(font);
    recentTitle->setText("Recent Transactions");
    recentTitle->setFixedWidth(160);
    recentTitle->move(3,3);

    for(int a=0;a<3;a++){
        recentLabel[a][0] = new ClickableLabel(recentOverview);
        recentLabel[a][0]->setFont(boldFont);
        recentLabel[a][1] = new ClickableLabel(recentOverview);
        recentLabel[a][2] = new ClickableLabel(recentOverview);
    }

    for(int b=0;b<3;b++){
        recentOverviewCol[b] = new QWidget(recentOverview);
        recentOverviewCol[b]->setStyleSheet("border: none; background: none;");
        recentColLayout[b] = new QVBoxLayout();

        recentColLayout[b]->addWidget(recentLabel[0][b]);
        recentColLayout[b]->addWidget(recentLabel[1][b]);
        recentColLayout[b]->addWidget(recentLabel[2][b]);

        recentColLayout[b]->setContentsMargins(0,0,0,0);
        recentColLayout[b]->setSpacing(0);
        recentOverviewCol[b]->setLayout(recentColLayout[b]);
    }

    QHBoxLayout  *allRows = new QHBoxLayout();
    allRows->addWidget(recentOverviewCol[0]);
    allRows->addWidget(recentOverviewCol[1]);
    allRows->addWidget(recentOverviewCol[2]);
    allRows->setContentsMargins(10,10-3,10,10);
    allRows->setSpacing(10);
    recentOverviewBox->setLayout(allRows);

    QHBoxLayout  *boxLayout2 = new QHBoxLayout();
    boxLayout2->addWidget(recentOverviewBox);
    boxLayout2->setContentsMargins(0,30,0,0);
    recentOverview->setLayout(boxLayout2);

    recentOverview->setMinimumWidth(250);
    recentOverview->setMaximumWidth(800);

    networkOverview = new QFrame(this);
    networkOverview->setStyleSheet("QFrame {color: #FFFFFF;} .QLabel { border: none; background: none; }");

    QWidget *networkOverviewBox = new QWidget(networkOverview);
    networkOverviewBox->setStyleSheet(".QWidget {background-color: rgba(0,0,0, 0);}");

    QLabel *blockCountTitle = new QLabel("Blockcount:");

    //QLabel *moneySupplyTitle = new QLabel("Moneysupply:");

    QLabel *hashRateTitle = new QLabel("Hashrate:");

    blockCount = new QLabel();
    blockCount->setFont(boldFont);
    blockCount->setText("---");
    blockCount->setCursor(Qt::IBeamCursor);
    blockCount->setTextInteractionFlags(Qt::TextSelectableByMouse);

    moneySupply = new QLabel();
    moneySupply->setFont(boldFont);
    moneySupply->setText("---");
    moneySupply->setCursor(Qt::IBeamCursor);
    moneySupply->setTextInteractionFlags(Qt::TextSelectableByMouse);

    hashRate = new QLabel();
    hashRate->setFont(boldFont);
    hashRate->setText("---");
    hashRate->setCursor(Qt::IBeamCursor);
    hashRate->setTextInteractionFlags(Qt::TextSelectableByMouse);

    networkTitle = new QLabel(networkOverview);
    networkTitle->setStyleSheet("QLabel { color: #FFFFFF; }");
    networkTitle->setFont(font);
    networkTitle->setText("Network Statistics (out of sync)");
    networkTitle->setFixedWidth(190);
    networkTitle->move(3,3);

    QFormLayout *formLayout3 = new QFormLayout();

    formLayout3->addRow(blockCountTitle, blockCount);
    //formLayout3->addRow(moneySupplyTitle, moneySupply);
    formLayout3->addRow(hashRateTitle, hashRate);

    formLayout3->setContentsMargins(10,10,10,10);
    formLayout3->setVerticalSpacing(8);
    formLayout3->setHorizontalSpacing(10);
    networkOverviewBox->setLayout(formLayout3);

    QHBoxLayout  *boxLayout3 = new QHBoxLayout();
    boxLayout3->addWidget(networkOverviewBox);
    boxLayout3->setContentsMargins(0,30,0,0);
    networkOverview->setLayout(boxLayout3);

    networkOverview->setMinimumWidth(200);
    networkOverview->setMaximumWidth(250);

    QHBoxLayout  *mainLayout = new QHBoxLayout();
    mainLayout->addWidget(walletOverview);
    mainLayout->addWidget(recentOverview);
    mainLayout->addWidget(networkOverview);//,0,Qt::AlignRight);
    mainLayout->setContentsMargins(101,0,5,10);
    mainLayout->setAlignment(Qt::AlignLeft);
    setLayout(mainLayout);

    for(int a=0;a<3;a++){
        for(int b=0;b<3;b++){
            mapper[a][b] = new QSignalMapper( this );
            mapper[a][b]->setMapping(recentLabel[a][b],a);
            connect( recentLabel[a][b], SIGNAL(clicked()), mapper[a][b], SLOT(map()) );
            connect(mapper[a][b], SIGNAL(mapped(int)), SLOT(handleTransactionClicked(int)));
        }
    }

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateDisplayUnit()));
    timer->start(500);
}

void GuiHeader::resize(int width)
{
    this->setFixedWidth(width);
    backGround->setFixedWidth(width);
    bottomLine->setFixedWidth(width);
}

void GuiHeader::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
    currentBalance = balance;
    currentUnconfirmedBalance = unconfirmedBalance;
    currentImmatureBalance = immatureBalance;

    labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
    labelUnconfirmedBalance->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
    labelImmatureBalance->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
}

void GuiHeader::setClientModel(ClientModel *model)
{
    this->clientModel = model;

    if(model)
    {
        versionLabel->setText(model->formatFullVersion().split("-")[0]);
    }
}

void GuiHeader::setWalletModel(WalletModel *model)
{
    this->walletModel = model;

    if(model && model->getOptionsModel())
    {
        filter = new TransactionFilterProxy();
        filter->setSourceModel(model->getTransactionTableModel());
        filter->setLimit(3);//NUM_ITEMS);
        filter->setDynamicSortFilter(true);
        filter->setSortRole(Qt::EditRole);
        filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);

        // Keep up to date with wallets
        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
        connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));

    }

    // update the display unit, to not use the default ("BTC")
    updateDisplayUnit();
}

void GuiHeader::updateDisplayUnit()
{
    if(walletModel && walletModel->getOptionsModel())
    {
        unit = walletModel->getOptionsModel()->getDisplayUnit();
        if(currentBalance != -1)
            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance);

        QDateTime now = QDateTime::currentDateTime();

        for(int i=0; i<filter->rowCount();i++){

            QString amountText = BitcoinUnits::formatWithUnit(unit, filter->data(filter->index(i, 0), TransactionTableModel::AmountRole).toLongLong());
            bool confirmed = filter->data(filter->index(i, 0), TransactionTableModel::ConfirmedRole).toBool();
            if(!confirmed)
            {
                amountText = QString("[") + amountText + QString("]");
            }

            recentLabel[i][0]->setText(amountText);
            if(filter->data(filter->index(i, 0), TransactionTableModel::AmountRole).toLongLong() < 0){
                recentLabel[i][1]->setText("Sent");
            } else{
               recentLabel[i][1]->setText("Received");
            }

            QString agoString = "";
            qint64 ago = filter->data(filter->index(i, 0), TransactionTableModel::DateRole).toDateTime().secsTo(now);
            if(ago <60){
                agoString = QString::number(ago)+" sec ago";
            }
            if(ago >=60 && ago <3600){
                agoString = QString::number(ago/60)+" min ago";
            }
            if(ago >=3600 && ago <86400){
                agoString = QString::number(ago/3600)+" h ago";
            }
            if(ago >=86400 && ago <31536000){
                agoString = QString::number(ago/86400)+" d ago";
            }
            if(ago >=31536000){
                agoString = QString::number(ago/86400)+" y ago";
            }

            recentLabel[i][2]->setText(agoString);

            recentLabel[i][0]->setToolTip(filter->data(filter->index(i, 0), TransactionTableModel::ToAddress).toString());
            recentLabel[i][1]->setToolTip(filter->data(filter->index(i, 0), TransactionTableModel::ToAddress).toString());
            recentLabel[i][2]->setToolTip(filter->data(filter->index(i, 0), TransactionTableModel::ToAddress).toString());
        }
    }
}

void GuiHeader::showOutOfSyncWarning(bool fShow)
{
    if(fShow){
        walletTitle->setText("Bank (out of sync)");
        networkTitle->setText("Network Statistics (out of sync)");
    } else{
        walletTitle->setText("Bank");
        networkTitle->setText("Network Statistics");
    }
}

static QString formatHashrate(int64 n)
{
    if (n == 0)
        return "0 H/s";

    int i = (int)floor(log(n)/log(1000));
    float v = n*pow(1000.0f, -i);

    QString prefix = "";
    if (i >= 1 && i < 9)
        prefix = " kMGTPEZY"[i];

    return QString("%1 %2H/s").arg(v, 0, 'f', 2).arg(prefix);
}

void GuiHeader::updateNetworkOverview()
{
    blockCount->setText(QString::number(nBestHeight));

   // int totalMoney = (double)GetTotalSupply()/(double)COIN;
    //moneySupply->setText(QString::number( totalMoney)+" CHIP");

    int64 NetworkHashrate = GetNetworkHashPS(120, -1).get_int64();
    hashRate->setText(formatHashrate(NetworkHashrate));

}

void GuiHeader::handleTransactionClicked(int indexa)
{
    if(filter->rowCount() > indexa){
        QModelIndex id = filter->index(indexa,3, QModelIndex());
        emit transactionClicked2(filter->mapToSource(id));
    }
}