text:
import { AbstractPlugin, IMetaData } from '../plugin/AbstractPlugin';
import PluginAPI from '../plugin/PluginAPI';
import Translation from '@util/Translation';
import showCommandHelp from '@ui/dialogs/commandHelp';
import JID from '@src/JID';
import { OnlyGroupChatError, ArgumentError } from '@src/CommandRepository';
import MultiUserContact from '@src/MultiUserContact';

const MIN_VERSION = '4.0.0';
const MAX_VERSION = '99.0.0';

export default class CommandPlugin extends AbstractPlugin {
   public static getId(): string {
      return 'command';
   }

   public static getName(): string {
      return 'Commands';
   }

   public static getMetaData(): IMetaData {
      return {
         description: Translation.t('setting-command-enable'),
         xeps: [],
      };
   }

   constructor(pluginAPI: PluginAPI) {
      super(MIN_VERSION, MAX_VERSION, pluginAPI);

      this.register();
   }

   private register() {
      this.pluginAPI.registerCommand(
         '/help',
         async () => {
            showCommandHelp(this.pluginAPI.getCommandRepository().getHelp());

            return true;
         },
         'cmd_help'
      );

      this.pluginAPI.registerCommand(
         '/clear',
         async (_args, contact) => {
            contact.getChatWindow().clear();

            return true;
         },
         'cmd_clear'
      );

      const subjectChangeAction = async (args: string[], contact: MultiUserContact) => {
         if (!contact.isGroupChat()) {
            return false;
         }

         let topic = args.slice(1).join(' ');

         contact.changeTopic(topic);

         return true;
      };

      this.pluginAPI.registerCommand('/subject', subjectChangeAction, '', 'multiuser');
      this.pluginAPI.registerCommand('/topic', subjectChangeAction, 'cmd_subject', 'multiuser');

      this.pluginAPI.registerCommand(
         '/invite',
         async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length < 2) {
               throw new ArgumentError();
            }

            let jid = new JID(args[1]);
            let reason = args.slice(2).join(' ');

            contact.invite(jid, reason);

            return true;
         },
         'cmd_invite',
         'multiuser'
      );

      this.pluginAPI.registerCommand(
         '/kick',
         async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length < 2) {
               throw new ArgumentError();
            }

            let nickname = args[1];
            let reason = args.slice(2).join(' ');

            contact.kick(nickname, reason);

            return true;
         },
         'cmd_kick',
         'multiuser'
      );

      this.pluginAPI.registerCommand(
         '/ban',
         async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length < 2) {
               throw new ArgumentError();
            }

            let jid = new JID(args[1]);
            let reason = args.slice(2).join(' ');

            contact.ban(jid, reason);

            return true;
         },
         'cmd_ban',
         'multiuser'
      );

      const affiliationChangeActionFactory =
         (affiliation: 'admin' | 'member' | 'owner' | 'none') => async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length !== 2) {
               throw new ArgumentError();
            }

            let jid = new JID(args[1]);

            contact.changeAffiliation(jid, affiliation);

            return true;
         };

      this.pluginAPI.registerCommand('/admin', affiliationChangeActionFactory('admin'), 'cmd_admin', 'multiuser');
      this.pluginAPI.registerCommand('/member', affiliationChangeActionFactory('member'), 'cmd_member', 'multiuser');
      this.pluginAPI.registerCommand('/owner', affiliationChangeActionFactory('owner'), 'cmd_owner', 'multiuser');
      this.pluginAPI.registerCommand('/revoke', affiliationChangeActionFactory('none'), 'cmd_revoke', 'multiuser');

      this.pluginAPI.registerCommand(
         '/nick',
         async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length !== 2) {
               throw new ArgumentError();
            }

            contact.changeNickname(args[1]);

            return true;
         },
         'cmd_nick',
         'multiuser'
      );

      this.pluginAPI.registerCommand(
         '/destroy',
         async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            contact.destroy();

            return true;
         },
         'cmd_destroy',
         'multiuser'
      );

      const roleChangeActionFactory =
         (role: 'moderator' | 'participant') => async (args: string[], contact: MultiUserContact) => {
            if (!contact.isGroupChat()) {
               throw new OnlyGroupChatError();
            }

            if (args.length !== 2) {
               throw new ArgumentError();
            }

            let nickname = args[1];

            contact.changeRole(nickname, role);

            return true;
         };

      this.pluginAPI.registerCommand('/moderator', roleChangeActionFactory('moderator'), 'cmd_moderator', 'multiuser');
      this.pluginAPI.registerCommand(
         '/participant',
         roleChangeActionFactory('participant'),
         'cmd_participant',
         'multiuser'
      );
   }
}


text:
import React from "react"
import { useHistory } from "react-router-dom"
import querystring from "querystring"
import { useLoginMutation, User } from "dicty-graphql-schema"
import { useAuthStore, ActionType } from "features/Authentication/AuthStore"
import oauthConfig from "common/utils/oauthConfig"

type LoginEventData = {
  /** Third-party provider (orcid, google, linkedin) */
  provider: string
  /** Query containing authorization code and possibly state */
  query: string
  /** Callback URL */
  url: string
}

const getLoginInputVariables = (data: LoginEventData) => {
  const provider = (oauthConfig as any)[data.provider]
  const parsed = querystring.parse(data.query.replace("?", ""))

  const variables = {
    input: {
      client_id: provider.clientId,
      redirect_url: data.url,
      state: parsed?.state?.toString() || "state",
      code: parsed.code as string,
      scopes: provider.scopes[0],
      provider: data.provider,
    },
  }

  return variables
}

/**
 * OauthSignHandler listens to an event message and attempts to login
 * with the event data.
 */

const OauthSignHandler = () => {
  const history = useHistory()
  const { dispatch } = useAuthStore()
  const [login, { data }] = useLoginMutation()

  React.useEffect(() => {
    const onMessage = async (event: MessageEvent) => {
      event.preventDefault()
      event.stopPropagation()
      if (!event.data.provider) {
        return
      }
      history.push("/load/auth")
      try {
        const { data } = await login({
          variables: getLoginInputVariables(event.data),
        })
        dispatch({
          type: ActionType.LOGIN,
          payload: {
            token: data?.login?.token as string,
            user: data?.login?.user as User,
            provider: data?.login?.identity.provider as string,
          },
        })
        history.push("/mydsc")
      } catch (error) {
        dispatch({
          type: ActionType.LOGIN_ERROR,
          payload: {
            error: error,
          },
        })
        history.push("/login")
      }
    }
    window.addEventListener("message", onMessage, false)
    return () => {
      window.removeEventListener("message", onMessage)
    }
  }, [data, dispatch, history, login])

  return null
}

export default OauthSignHandler

redpajama_set_name: RedPajamaGithub


text:
package net.minidev.ovh.api;

import com.fasterxml.jackson.core.type.TypeReference;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import net.minidev.ovh.api.license.OvhActionType;
import net.minidev.ovh.api.license.OvhChangeIpStatus;
import net.minidev.ovh.api.license.OvhOption;
import net.minidev.ovh.api.license.OvhOptionLabel;
import net.minidev.ovh.api.license.OvhPleskOrderConfiguration;
import net.minidev.ovh.api.license.OvhTask;
import net.minidev.ovh.api.license.OvhTaskStateEnum;
import net.minidev.ovh.api.license.plesk.OvhPlesk;
import net.minidev.ovh.api.service.OvhTerminationFutureUseEnum;
import net.minidev.ovh.api.service.OvhTerminationReasonEnum;
import net.minidev.ovh.api.services.OvhService;
import net.minidev.ovh.core.ApiOvhBase;
import net.minidev.ovh.core.ApiOvhCore;

/**
 * BasePath:https://eu.api.ovh.com/1.0
 * ResourcePath:/license/plesk
 * version:1.0
 */
public class ApiOvhLicenseplesk extends ApiOvhBase {
	public ApiOvhLicenseplesk(ApiOvhCore core) {
		super(core);
	}

	/**
	 * List available services
	 *
	 * REST: GET /license/plesk
	 */
	public ArrayList<String> GET() throws IOException {
		String qPath = "/license/plesk";
		StringBuilder sb = path(qPath);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t1);
	}
	private static TypeReference<ArrayList<String>> t1 = new TypeReference<ArrayList<String>>() {};

	/**
	 * Get the orderable Plesk versions and their associated compatibilities
	 *
	 * REST: GET /license/plesk/orderableVersions
	 * @param ip [required] Your license Ip
	 */
	public ArrayList<OvhPleskOrderConfiguration> orderableVersions_GET(String ip) throws IOException {
		String qPath = "/license/plesk/orderableVersions";
		StringBuilder sb = path(qPath);
		query(sb, "ip", ip);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t2);
	}
	private static TypeReference<ArrayList<OvhPleskOrderConfiguration>> t2 = new TypeReference<ArrayList<OvhPleskOrderConfiguration>>() {};

	/**
	 * Confirm termination of your service
	 *
	 * REST: POST /license/plesk/{serviceName}/confirmTermination
	 * @param futureUse [required] What next after your termination request
	 * @param reason [required] Reason of your termination request
	 * @param commentary [required] Commentary about your termination request
	 * @param token [required] The termination token sent by mail to the admin contact
	 * @param serviceName [required] The name of your Plesk license
	 */
	public String serviceName_confirmTermination_POST(String serviceName, String commentary, OvhTerminationFutureUseEnum futureUse, OvhTerminationReasonEnum reason, String token) throws IOException {
		String qPath = "/license/plesk/{serviceName}/confirmTermination";
		StringBuilder sb = path(qPath, serviceName);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "commentary", commentary);
		addBody(o, "futureUse", futureUse);
		addBody(o, "reason", reason);
		addBody(o, "token", token);
		String resp = exec(qPath, "POST", sb.toString(), o);
		return convertTo(resp, String.class);
	}

	/**
	 * Will tell if the ip can accept the license
	 *
	 * REST: GET /license/plesk/{serviceName}/canLicenseBeMovedTo
	 * @param destinationIp [required] The Ip on which you want to move this license
	 * @param serviceName [required] The name of your Plesk license
	 */
	public OvhChangeIpStatus serviceName_canLicenseBeMovedTo_GET(String serviceName, String destinationIp) throws IOException {
		String qPath = "/license/plesk/{serviceName}/canLicenseBeMovedTo";
		StringBuilder sb = path(qPath, serviceName);
		query(sb, "destinationIp", destinationIp);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhChangeIpStatus.class);
	}

	/**
	 * Move this license to another Ip
	 *
	 * REST: POST /license/plesk/{serviceName}/changeIp
	 * @param destinationIp [required] The Ip on which you want to move this license
	 * @param serviceName [required] The name of your Plesk license
	 */
	public OvhTask serviceName_changeIp_POST(String serviceName, String destinationIp) throws IOException {
		String qPath = "/license/plesk/{serviceName}/changeIp";
		StringBuilder sb = path(qPath, serviceName);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "destinationIp", destinationIp);
		String resp = exec(qPath, "POST", sb.toString(), o);
		return convertTo(resp, OvhTask.class);
	}

	/**
	 * Get this object properties
	 *
	 * REST: GET /license/plesk/{serviceName}
	 * @param serviceName [required] The name of your Plesk license
	 */
	public OvhPlesk serviceName_GET(String serviceName) throws IOException {
		String qPath = "/license/plesk/{serviceName}";
		StringBuilder sb = path(qPath, serviceName);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhPlesk.class);
	}

	/**
	 * Alter this object properties
	 *
	 * REST: PUT /license/plesk/{serviceName}
	 * @param body [required] New object properties
	 * @param serviceName [required] The name of your Plesk license
	 */
	public void serviceName_PUT(String serviceName, OvhPlesk body) throws IOException {
		String qPath = "/license/plesk/{serviceName}";
		StringBuilder sb = path(qPath, serviceName);
		exec(qPath, "PUT", sb.toString(), body);
	}

	/**
	 * options attached to this license
	 *
	 * REST: GET /license/plesk/{serviceName}/option
	 * @param serviceName [required] The name of your Plesk license
	 */
	public ArrayList<OvhOptionLabel> serviceName_option_GET(String serviceName) throws IOException {
		String qPath = "/license/plesk/{serviceName}/option";
		StringBuilder sb = path(qPath, serviceName);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t3);
	}
	private static TypeReference<ArrayList<OvhOptionLabel>> t3 = new TypeReference<ArrayList<OvhOptionLabel>>() {};

	/**
	 * Get this object properties
	 *
	 * REST: GET /license/plesk/{serviceName}/option/{label}
	 * @param serviceName [required] The name of your Plesk license
	 * @param label [required] This option designation
	 */
	public OvhOption serviceName_option_label_GET(String serviceName, net.minidev.ovh.api.license.OvhOptionLabel label) throws IOException {
		String qPath = "/license/plesk/{serviceName}/option/{label}";
		StringBuilder sb = path(qPath, serviceName, label);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhOption.class);
	}

	/**
	 * release this Option
	 *
	 * REST: DELETE /license/plesk/{serviceName}/option/{label}
	 * @param serviceName [required] The name of your Plesk license
	 * @param label [required] This option designation
	 */
	public OvhTask serviceName_option_label_DELETE(String serviceName, net.minidev.ovh.api.license.OvhOptionLabel label) throws IOException {
		String qPath = "/license/plesk/{serviceName}/option/{label}";
		StringBuilder sb = path(qPath, serviceName, label);
		String resp = exec(qPath, "DELETE", sb.toString(), null);
		return convertTo(resp, OvhTask.class);
	}

	/**
	 * Returns an array of ips where the license can be moved to
	 *
	 * REST: GET /license/plesk/{serviceName}/allowedDestinationIp
	 * @param serviceName [required] The name of your Plesk license
	 */
	public ArrayList<String> serviceName_allowedDestinationIp_GET(String serviceName) throws IOException {
		String qPath = "/license/plesk/{serviceName}/allowedDestinationIp";
		StringBuilder sb = path(qPath, serviceName);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t1);
	}

	/**
	 * tasks linked to this license
	 *
	 * REST: GET /license/plesk/{serviceName}/tasks
	 * @param status [required] Filter the value of status property (=)
	 * @param action [required] Filter the value of action property (=)
	 * @param serviceName [required] The name of your Plesk license
	 */
	public ArrayList<Long> serviceName_tasks_GET(String serviceName, OvhActionType action, OvhTaskStateEnum status) throws IOException {
		String qPath = "/license/plesk/{serviceName}/tasks";
		StringBuilder sb = path(qPath, serviceName);
		query(sb, "action", action);
		query(sb, "status", status);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t4);
	}
	private static TypeReference<ArrayList<Long>> t4 = new TypeReference<ArrayList<Long>>() {};

	/**
	 * Get this object properties
	 *
	 * REST: GET /license/plesk/{serviceName}/tasks/{taskId}
	 * @param serviceName [required] The name of your Plesk license
	 * @param taskId [required] This Task id
	 */
	public OvhTask serviceName_tasks_taskId_GET(String serviceName, Long taskId) throws IOException {
		String qPath = "/license/plesk/{serviceName}/tasks/{taskId}";
		StringBuilder sb = path(qPath, serviceName, taskId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhTask.class);
	}

	/**
	 * Terminate your service
	 *
	 * REST: POST /license/plesk/{serviceName}/terminate
	 * @param serviceName [required] The name of your Plesk license
	 */
	public String serviceName_terminate_POST(String serviceName) throws IOException {
		String qPath = "/license/plesk/{serviceName}/terminate";
		StringBuilder sb = path(qPath, serviceName);
		String resp = exec(qPath, "POST", sb.toString(), null);
		return convertTo(resp, String.class);
	}

	/**
	 * Get this object properties
	 *
	 * REST: GET /license/plesk/{serviceName}/serviceInfos
	 * @param serviceName [required] The name of your Plesk license
	 */
	public OvhService serviceName_serviceInfos_GET(String serviceName) throws IOException {
		String qPath = "/license/plesk/{serviceName}/serviceInfos";
		StringBuilder sb = path(qPath, serviceName);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhService.class);
	}

	/**
	 * Alter this object properties
	 *
	 * REST: PUT /license/plesk/{serviceName}/serviceInfos
	 * @param body [required] New object properties
	 * @param serviceName [required] The name of your Plesk license
	 */
	public void serviceName_serviceInfos_PUT(String serviceName, OvhService body) throws IOException {
		String qPath = "/license/plesk/{serviceName}/serviceInfos";
		StringBuilder sb = path(qPath, serviceName);
		exec(qPath, "PUT", sb.toString(), body);
	}
}


text:
var $ = require('./window').$;

var modal = $('#modal'),
    close = $('.md-close', modal),
    overlay = $('.md-overlay');

function removeModal() {
  modal.removeClass('md-show');
}

function handleCancel() {

}

function handleConfirm() {

}

$('.md-trigger').on('click', function (e) {
  modal.addClass('md-show');
});

overlay.on('click', function (e) {
  e.stopPropagation();
  removeModal();
});

close.on('click', function (e) {
  e.stopPropagation();
  removeModal();
});


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>UIScrollView(SSToolkitAdditions) Category Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<meta name="viewport" content="width=550" />
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.1 (build 840)" />

SSToolkit 1.0.2

				Sam Soffes

UIScrollView(SSToolkitAdditions) Category Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="instance_methods">Instance Methods</option>

	<option value="//api/name/scrollToTop">    - scrollToTop</option>

	<option value="//api/name/scrollToTopAnimated:">    - scrollToTopAnimated:</option>

</select>

Overview

Tasks

Scrolling

Instance Methods

scrollToTop

scrollToTopAnimated:

Index

Hierarchy

UIScrollView(SSToolkitAdditions) Category Reference

	Declared in
	UIScrollView+SSToolkitAdditions.h

Overview

Provides extensions to UIScrollView for various common tasks.

Tasks

Scrolling

		– scrollToTop

Scroll to the top of the receiver without animation.

		– scrollToTopAnimated:

Scroll to the top of the receiver.

Instance Methods

scrollToTop

Scroll to the top of the receiver without animation.

- (void)scrollToTop

Discussion

Scroll to the top of the receiver without animation.

Declared In

		UIScrollView+SSToolkitAdditions.h

scrollToTopAnimated:

Scroll to the top of the receiver.

- (void)scrollToTopAnimated:(BOOL)animated

Parameters

animated

YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate.

Discussion

Scroll to the top of the receiver.

Declared In

		UIScrollView+SSToolkitAdditions.h

Index

Hierarchy

© 2012 Sam Soffes. All rights reserved. (Last updated: 2012-11-21)

						Generated by appledoc 2.1 (build 840).


text:
package org.elasticsearch.index.query.functionscore;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RandomApproximationQuery;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.FilterScoreFunction;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.ScoreMode;
import org.elasticsearch.common.lucene.search.function.LeafScoreFunction;
import org.elasticsearch.common.lucene.search.function.RandomScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.lucene.search.function.WeightFactorFunction;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.fielddata.LeafFieldData;
import org.elasticsearch.index.fielddata.LeafNumericFieldData;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.MultiValueMode;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.sort.BucketedSort;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESTestCase;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ExecutionException;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;

public class FunctionScoreTests extends ESTestCase {

    private static final String UNSUPPORTED = "Method not implemented. This is just a stub for testing.";

    /**
     * Stub for IndexFieldData. Needed by some score functions. Returns 1 as count always.
     */
    private static class IndexFieldDataStub implements IndexFieldData<LeafFieldData> {
        @Override
        public String getFieldName() {
            return "test";
        }

        @Override
        public ValuesSourceType getValuesSourceType() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public LeafFieldData load(LeafReaderContext context) {
            return new LeafFieldData() {

                @Override
                public ScriptDocValues getScriptValues() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public SortedBinaryDocValues getBytesValues() {
                    return new SortedBinaryDocValues() {
                        @Override
                        public boolean advanceExact(int docId) {
                            return true;
                        }

                        @Override
                        public int docValueCount() {
                            return 1;
                        }

                        @Override
                        public BytesRef nextValue() {
                            return new BytesRef("0");
                        }
                    };
                }

                @Override
                public long ramBytesUsed() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public Collection<Accountable> getChildResources() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public void close() {
                }
            };
        }

        @Override
        public LeafFieldData loadDirect(LeafReaderContext context) throws Exception {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public SortField sortField(@Nullable Object missingValue, MultiValueMode sortMode,
                                        XFieldComparatorSource.Nested nested, boolean reverse) {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public BucketedSort newBucketedSort(BigArrays bigArrays, Object missingValue, MultiValueMode sortMode, Nested nested,
                SortOrder sortOrder, DocValueFormat format, int bucketSize, BucketedSort.ExtraData extra) {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public void clear() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public Index index() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }
    }

    /**
     * Stub for IndexNumericFieldData needed by some score functions. Returns 1 as value always.
     */
    private static class IndexNumericFieldDataStub extends IndexNumericFieldData {

        @Override
        public NumericType getNumericType() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public String getFieldName() {
            return "test";
        }

        @Override
        public ValuesSourceType getValuesSourceType() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public LeafNumericFieldData load(LeafReaderContext context) {
            return new LeafNumericFieldData() {
                @Override
                public SortedNumericDocValues getLongValues() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public SortedNumericDoubleValues getDoubleValues() {
                    return new SortedNumericDoubleValues() {
                        @Override
                        public boolean advanceExact(int docId) {
                            return true;
                        }

                        @Override
                        public int docValueCount() {
                            return 1;
                        }

                        @Override
                        public double nextValue() {
                            return 1d;
                        }
                    };
                }

                @Override
                public ScriptDocValues getScriptValues() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public SortedBinaryDocValues getBytesValues() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public long ramBytesUsed() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public Collection<Accountable> getChildResources() {
                    throw new UnsupportedOperationException(UNSUPPORTED);
                }

                @Override
                public void close() {
                }
            };
        }

        @Override
        public LeafNumericFieldData loadDirect(LeafReaderContext context) throws Exception {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        protected boolean sortRequiresCustomComparator() {
            return false;
        }

        @Override
        public void clear() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }

        @Override
        public Index index() {
            throw new UnsupportedOperationException(UNSUPPORTED);
        }
    }

    private static final ScoreFunction RANDOM_SCORE_FUNCTION = new RandomScoreFunction(0, 0, new IndexFieldDataStub());
    private static final ScoreFunction FIELD_VALUE_FACTOR_FUNCTION = new FieldValueFactorFunction("test", 1,
            FieldValueFactorFunction.Modifier.LN, 1.0, null);
    private static final ScoreFunction GAUSS_DECAY_FUNCTION =
        new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0,
            GaussDecayFunctionBuilder.GAUSS_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX);
    private static final ScoreFunction EXP_DECAY_FUNCTION =
        new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0,
            ExponentialDecayFunctionBuilder.EXP_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX);
    private static final ScoreFunction LIN_DECAY_FUNCTION =
        new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0,
            LinearDecayFunctionBuilder.LINEAR_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX);
    private static final ScoreFunction WEIGHT_FACTOR_FUNCTION = new WeightFactorFunction(4);
    private static final String TEXT = "The way out is through.";
    private static final String FIELD = "test";
    private static final Term TERM = new Term(FIELD, "through");
    private Directory dir;
    private IndexWriter w;
    private DirectoryReader reader;
    private IndexSearcher searcher;

    @Before
    public void initSearcher() throws IOException {
        dir = newDirectory();
        w = new IndexWriter(dir, newIndexWriterConfig(new StandardAnalyzer()));
        Document d = new Document();
        d.add(new TextField(FIELD, TEXT, Field.Store.YES));
        d.add(new TextField("_uid", "1", Field.Store.YES));
        w.addDocument(d);
        w.commit();
        reader = DirectoryReader.open(w);
        searcher = newSearcher(reader);
    }

    @After
    public void closeAllTheReaders() throws IOException {
        reader.close();
        w.close();
        dir.close();
    }

    public void testExplainFunctionScoreQuery() throws IOException {

        Explanation functionExplanation = getFunctionScoreExplanation(searcher, RANDOM_SCORE_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)");
        assertThat(functionExplanation.getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFunctionScoreExplanation(searcher, FIELD_VALUE_FACTOR_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "field value function: ln(doc['test'].value?:1.0 * factor=1.0)");
        assertThat(functionExplanation.getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFunctionScoreExplanation(searcher, GAUSS_DECAY_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "Function for field test:");
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("0.1 = exp(-0.5*pow(MAX[Math.max(Math.abs"
                + "(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFunctionScoreExplanation(searcher, EXP_DECAY_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "Function for field test:");
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(),
                equalTo("0.1 = exp(- MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFunctionScoreExplanation(searcher, LIN_DECAY_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "Function for field test:");
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("0.1 = max(0.0, ((1.1111111111111112"
                + " - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)])/1.1111111111111112)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFunctionScoreExplanation(searcher, WEIGHT_FACTOR_FUNCTION);
        checkFunctionScoreExplanation(functionExplanation, "product of:");
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(),
                equalTo("1.0 = constant score 1.0 - no function provided\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[1].toString(), equalTo("4.0 = weight\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0));
        assertThat(functionExplanation.getDetails()[0].getDetails()[1].getDetails().length, equalTo(0));
    }

    public Explanation getFunctionScoreExplanation(IndexSearcher searcher, ScoreFunction scoreFunction) throws IOException {
        FunctionScoreQuery functionScoreQuery =
            new FunctionScoreQuery(new TermQuery(TERM), scoreFunction, CombineFunction.AVG,0.0f, 100);
        Weight weight = searcher.createWeight(searcher.rewrite(functionScoreQuery), org.apache.lucene.search.ScoreMode.COMPLETE, 1f);
        Explanation explanation = weight.explain(searcher.getIndexReader().leaves().get(0), 0);
        return explanation.getDetails()[1];
    }

    public void checkFunctionScoreExplanation(Explanation randomExplanation, String functionExpl) {
        assertThat(randomExplanation.getDescription(), equalTo("min of:"));
        assertThat(randomExplanation.getDetails()[0].getDescription(), containsString(functionExpl));
    }

    public void testExplainFiltersFunctionScoreQuery() throws IOException {
        Explanation functionExplanation = getFiltersFunctionScoreExplanation(searcher, RANDOM_SCORE_FUNCTION);
        checkFiltersFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0));

        functionExplanation = getFiltersFunctionScoreExplanation(searcher, FIELD_VALUE_FACTOR_FUNCTION);
        checkFiltersFunctionScoreExplanation(functionExplanation, "field value function: ln(doc['test'].value?:1.0 * factor=1.0)", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0));

        functionExplanation = getFiltersFunctionScoreExplanation(searcher, GAUSS_DECAY_FUNCTION);
        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = "
                + "exp(-0.5*pow(MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFiltersFunctionScoreExplanation(searcher, EXP_DECAY_FUNCTION);
        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(),
                equalTo("0.1 = exp(- MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));

        functionExplanation = getFiltersFunctionScoreExplanation(searcher, LIN_DECAY_FUNCTION);
        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(),
                equalTo("0.1 = max(0.0, ((1.1111111111111112 - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin)))"
                        + " - 0.0(=offset), 0)])/1.1111111111111112)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));

        // now test all together
        functionExplanation = getFiltersFunctionScoreExplanation(searcher
            , RANDOM_SCORE_FUNCTION
            , FIELD_VALUE_FACTOR_FUNCTION
            , GAUSS_DECAY_FUNCTION
            , EXP_DECAY_FUNCTION
            , LIN_DECAY_FUNCTION
        );

        checkFiltersFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)", 0);
        assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0));

        checkFiltersFunctionScoreExplanation(functionExplanation,
            "field value function: ln(doc['test'].value?:1.0 * factor=1.0)", 1);
        assertThat(functionExplanation.getDetails()[0].getDetails()[1].getDetails()[1].getDetails().length, equalTo(0));

        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 2);
        assertThat(functionExplanation.getDetails()[0].getDetails()[2].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = "
                + "exp(-0.5*pow(MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[2].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));

        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 3);
        assertThat(functionExplanation.getDetails()[0].getDetails()[3].getDetails()[1].getDetails()[0].toString(), equalTo(
                "0.1 = exp(- " + "MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[3].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));

        checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 4);
        assertThat(functionExplanation.getDetails()[0].getDetails()[4].getDetails()[1].getDetails()[0].toString(),
                equalTo("0.1 = max(0.0, ((1.1111111111111112 - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin)))"
                        + " - 0.0(=offset), 0)])/1.1111111111111112)\n"));
        assertThat(functionExplanation.getDetails()[0].getDetails()[4].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0));
    }

    public Explanation getFiltersFunctionScoreExplanation(IndexSearcher searcher, ScoreFunction... scoreFunctions) throws IOException {
        FunctionScoreQuery functionScoreQuery = getFiltersFunctionScoreQuery(FunctionScoreQuery.ScoreMode.AVG,
                CombineFunction.AVG, scoreFunctions);
        return getExplanation(searcher, functionScoreQuery).getDetails()[1];
    }

    protected Explanation getExplanation(IndexSearcher searcher, FunctionScoreQuery functionScoreQuery) throws IOException {
        Weight weight = searcher.createWeight(searcher.rewrite(functionScoreQuery), org.apache.lucene.search.ScoreMode.COMPLETE, 1f);
        return weight.explain(searcher.getIndexReader().leaves().get(0), 0);
    }

    public FunctionScoreQuery getFiltersFunctionScoreQuery(FunctionScoreQuery.ScoreMode scoreMode,
                                                           CombineFunction combineFunction, ScoreFunction... scoreFunctions) {
        ScoreFunction[] filterFunctions = new ScoreFunction[scoreFunctions.length];
        for (int i = 0; i < scoreFunctions.length; i++) {
            filterFunctions[i] = new FunctionScoreQuery.FilterScoreFunction(
                new TermQuery(TERM), scoreFunctions[i]);
        }
        return new FunctionScoreQuery(new TermQuery(TERM),
            scoreMode, filterFunctions, combineFunction,Float.MAX_VALUE * -1, Float.MAX_VALUE);
    }

    public void checkFiltersFunctionScoreExplanation(Explanation randomExplanation, String functionExpl, int whichFunction) {
        assertThat(randomExplanation.getDescription(), equalTo("min of:"));
        Explanation explanation = randomExplanation.getDetails()[0];
        assertThat(explanation.getDescription(), equalTo("function score, score mode [avg]"));
        Explanation functionExplanation = randomExplanation.getDetails()[0].getDetails()[whichFunction];
        assertThat(functionExplanation.getDescription(), equalTo("function score, product of:"));
        assertThat(functionExplanation.getDetails()[0].getDescription(), equalTo("match filter: " + FIELD + ":" + TERM.text()));
        assertThat(functionExplanation.getDetails()[1].getDescription(), equalTo(functionExpl));
    }

    private static float[] randomPositiveFloats(int size) {
        float[] values = new float[size];
        for (int i = 0; i < values.length; i++) {
            values[i] = randomFloat() * randomInt(100) + 1.e-5f;
        }
        return values;
    }

    private static double[] randomPositiveDoubles(int size) {
        double[] values = new double[size];
        for (int i = 0; i < values.length; i++) {
            double rand = randomValueOtherThanMany((d) -> Double.compare(d, 0) < 0, ESTestCase::randomDouble);
            values[i] = rand * randomInt(100) + 1.e-5d;
        }
        return values;
    }

    private static class ScoreFunctionStub extends ScoreFunction {
        private double score;

        ScoreFunctionStub(double score) {
            super(CombineFunction.REPLACE);
            this.score = score;
        }

        @Override
        public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException {
            return new LeafScoreFunction() {
                @Override
                public double score(int docId, float subQueryScore) {
                    return score;
                }

                @Override
                public Explanation explainScore(int docId, Explanation subQueryScore) throws IOException {
                    return Explanation.match((float) score, "a random score for testing");
                }
            };
        }

        @Override
        public boolean needsScores() {
            return false;
        }

        @Override
        protected boolean doEquals(ScoreFunction other) {
            return false;
        }

        @Override
        protected int doHashCode() {
            return 0;
        }
    }

    public void testSimpleWeightedFunction() throws IOException, ExecutionException, InterruptedException {
        int numFunctions = randomIntBetween(1, 3);
        float[] weights = randomPositiveFloats(numFunctions);
        double[] scores = randomPositiveDoubles(numFunctions);
        ScoreFunctionStub[] scoreFunctionStubs = new ScoreFunctionStub[numFunctions];
        for (int i = 0; i < numFunctions; i++) {
            scoreFunctionStubs[i] = new ScoreFunctionStub(scores[i]);
        }
        WeightFactorFunction[] weightFunctionStubs = new WeightFactorFunction[numFunctions];
        for (int i = 0; i < numFunctions; i++) {
            weightFunctionStubs[i] = new WeightFactorFunction(weights[i], scoreFunctionStubs[i]);
        }

        FunctionScoreQuery functionScoreQueryWithWeights = getFiltersFunctionScoreQuery(
                FunctionScoreQuery.ScoreMode.MULTIPLY
                , CombineFunction.REPLACE
                , weightFunctionStubs
        );

        TopDocs topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1);
        float scoreWithWeight = topDocsWithWeights.scoreDocs[0].score;
        double score = 1;
        for (int i = 0; i < weights.length; i++) {
            score *= weights[i] * scores[i];
        }
        assertThat(scoreWithWeight / (float) score, is(1f));
        float explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue().floatValue();
        assertThat(explainedScore / scoreWithWeight, is(1f));

        functionScoreQueryWithWeights = getFiltersFunctionScoreQuery(
                FunctionScoreQuery.ScoreMode.SUM
                , CombineFunction.REPLACE
                , weightFunctionStubs
        );

        topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1);
        scoreWithWeight = topDocsWithWeights.scoreDocs[0].score;
        double sum = 0;
        for (int i = 0; i < weights.length; i++) {
            sum += weights[i] * scores[i];
        }
        assertThat(scoreWithWeight / (float) sum, is(1f));
        explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue().floatValue();
        assertThat(explainedScore / scoreWithWeight, is(1f));

        functionScoreQueryWithWeights = getFiltersFunctionScoreQuery(
                FunctionScoreQuery.ScoreMode.AVG
                , CombineFunction.REPLACE
                , weightFunctionStubs
        );

        topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1);
        scoreWithWeight = topDocsWithWeights.scoreDocs[0].score;
        double norm = 0;
        sum = 0;
        for (int i = 0; i < weights.length; i++) {
            norm += weights[i];
            sum += weights[i] * scores[i];
        }
        assertThat(scoreWithWeight / (float) (sum / norm), is(1f));
        explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue().floatValue();
        assertThat(explainedScore / scoreWithWeight, is(1f));

        functionScoreQueryWithWeights = getFiltersFunctionScoreQuery(
                FunctionScoreQuery.ScoreMode.MIN
                , CombineFunction.REPLACE
                , weightFunctionStubs
        );

        topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1);
        scoreWithWeight = topDocsWithWeights.scoreDocs[0].score;
        double min = Double.POSITIVE_INFINITY;
        for (int i = 0; i < weights.length; i++) {
            min = Math.min(min, weights[i] * scores[i]);
        }
        assertThat(scoreWithWeight / (float) min, is(1f));
        explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue().floatValue();
        assertThat(explainedScore / scoreWithWeight, is(1f));

        functionScoreQueryWithWeights = getFiltersFunctionScoreQuery(
                FunctionScoreQuery.ScoreMode.MAX
                , CombineFunction.REPLACE
                , weightFunctionStubs
        );

        topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1);
        scoreWithWeight = topDocsWithWeights.scoreDocs[0].score;
        double max = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < weights.length; i++) {
            max = Math.max(max, weights[i] * scores[i]);
        }
        assertThat(scoreWithWeight / (float) max, is(1f));
        explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue().floatValue();
        assertThat(explainedScore / scoreWithWeight, is(1f));
    }

    public void testWeightOnlyCreatesBoostFunction() throws IOException {
        FunctionScoreQuery filtersFunctionScoreQueryWithWeights = new FunctionScoreQuery(new MatchAllDocsQuery(),
            new WeightFactorFunction(2), CombineFunction.MULTIPLY,0.0f, 100);
        TopDocs topDocsWithWeights = searcher.search(filtersFunctionScoreQueryWithWeights, 1);
        float score = topDocsWithWeights.scoreDocs[0].score;
        assertThat(score, equalTo(2.0f));
    }

    public void testMinScoreExplain() throws IOException {
        Query query = new MatchAllDocsQuery();
        Explanation queryExpl = searcher.explain(query, 0);

        FunctionScoreQuery fsq = new FunctionScoreQuery(query,0f, Float.POSITIVE_INFINITY);
        Explanation fsqExpl = searcher.explain(fsq, 0);
        assertTrue(fsqExpl.isMatch());
        assertEquals(queryExpl.getValue(), fsqExpl.getValue());
        assertEquals(queryExpl.getDescription(), fsqExpl.getDescription());

        fsq = new FunctionScoreQuery(query, 10f, Float.POSITIVE_INFINITY);
        fsqExpl = searcher.explain(fsq, 0);
        assertFalse(fsqExpl.isMatch());
        assertEquals("Score value is too low, expected at least 10.0 but got 1.0", fsqExpl.getDescription());

        FunctionScoreQuery ffsq = new FunctionScoreQuery(query, 0f, Float.POSITIVE_INFINITY);
        Explanation ffsqExpl = searcher.explain(ffsq, 0);
        assertTrue(ffsqExpl.isMatch());
        assertEquals(queryExpl.getValue(), ffsqExpl.getValue());
        assertEquals(queryExpl.getDescription(), ffsqExpl.getDescription());

        ffsq = new FunctionScoreQuery(query, 10f, Float.POSITIVE_INFINITY);
        ffsqExpl = searcher.explain(ffsq, 0);
        assertFalse(ffsqExpl.isMatch());
        assertEquals("Score value is too low, expected at least 10.0 but got 1.0", ffsqExpl.getDescription());
    }

    public void testPropagatesApproximations() throws IOException {
        Query query = new RandomApproximationQuery(new MatchAllDocsQuery(), random());
        IndexSearcher searcher = newSearcher(reader);
        searcher.setQueryCache(null); // otherwise we could get a cached entry that does not have approximations

        FunctionScoreQuery fsq = new FunctionScoreQuery(query, null, Float.POSITIVE_INFINITY);
        for (org.apache.lucene.search.ScoreMode scoreMode : org.apache.lucene.search.ScoreMode.values()) {
            Weight weight = searcher.createWeight(fsq, scoreMode, 1f);
            Scorer scorer = weight.scorer(reader.leaves().get(0));
            assertNotNull(scorer.twoPhaseIterator());
        }
    }

    public void testFunctionScoreHashCodeAndEquals() {
        Float minScore = randomBoolean() ? null : 1.0f;
        CombineFunction combineFunction = randomFrom(CombineFunction.values());
        float maxBoost = randomBoolean() ? Float.POSITIVE_INFINITY : randomFloat();
        ScoreFunction function = new DummyScoreFunction(combineFunction);

        FunctionScoreQuery q =
            new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost);
        FunctionScoreQuery q1 =
            new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost);
        assertEquals(q, q);
        assertEquals(q.hashCode(), q.hashCode());
        assertEquals(q, q1);
        assertEquals(q.hashCode(), q1.hashCode());

        FunctionScoreQuery diffQuery =
            new FunctionScoreQuery(new TermQuery(new Term("foo", "baz")), function, combineFunction, minScore, maxBoost);
        FunctionScoreQuery diffMinScore =
            new FunctionScoreQuery(q.getSubQuery(), function, combineFunction, minScore == null ? 1.0f : null, maxBoost);
        ScoreFunction otherFunction = new DummyScoreFunction(combineFunction);
        FunctionScoreQuery diffFunction = new FunctionScoreQuery(q.getSubQuery(), otherFunction, combineFunction, minScore, maxBoost);
        FunctionScoreQuery diffMaxBoost = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")),
            function, combineFunction, minScore, maxBoost == 1.0f ? 0.9f : 1.0f);
        FunctionScoreQuery[] queries = new FunctionScoreQuery[] { diffFunction,
            diffMinScore,
            diffQuery,
            q,
            diffMaxBoost
        };
        final int numIters = randomIntBetween(20, 100);
        for (int i = 0; i < numIters; i++) {
            FunctionScoreQuery left = randomFrom(queries);
            FunctionScoreQuery right = randomFrom(queries);
            if (left == right) {
                assertEquals(left, right);
                assertEquals(left.hashCode(), right.hashCode());
            } else {
                assertNotEquals(left + " == " + right, left, right);
            }
        }

    }

    public void testFilterFunctionScoreHashCodeAndEquals() {
        CombineFunction combineFunction = randomFrom(CombineFunction.values());
        ScoreFunction scoreFunction = new DummyScoreFunction(combineFunction);
        Float minScore = randomBoolean() ? null : 1.0f;
        Float maxBoost = randomBoolean() ? Float.POSITIVE_INFINITY : randomFloat();

        FilterScoreFunction function =
            new FilterScoreFunction(new TermQuery(new Term("filter", "query")), scoreFunction);
        FunctionScoreQuery q = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")),
                function, combineFunction, minScore, maxBoost);
        FunctionScoreQuery q1 =
            new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost);
        assertEquals(q, q);
        assertEquals(q.hashCode(), q.hashCode());
        assertEquals(q, q1);
        assertEquals(q.hashCode(), q1.hashCode());
        FunctionScoreQuery diffCombineFunc = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function,
                combineFunction == CombineFunction.AVG ? CombineFunction.MAX : CombineFunction.AVG, minScore, maxBoost);
        FunctionScoreQuery diffQuery = new FunctionScoreQuery(new TermQuery(new Term("foo", "baz")),
                function, combineFunction, minScore, maxBoost);
        FunctionScoreQuery diffMaxBoost = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")),
                function, combineFunction, minScore, maxBoost == 1.0f ? 0.9f : 1.0f);
        FunctionScoreQuery diffMinScore = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")),
            function, combineFunction, minScore == null ? 0.9f : null, maxBoost);
        FilterScoreFunction otherFunc = new FilterScoreFunction(new TermQuery(new Term("filter", "other_query")), scoreFunction);
        FunctionScoreQuery diffFunc = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), randomFrom(ScoreMode.values()),
            randomBoolean() ? new ScoreFunction[] { function, otherFunc } :
                new ScoreFunction[] { otherFunc }, combineFunction, minScore, maxBoost);

        FunctionScoreQuery[] queries = new FunctionScoreQuery[] {
            diffQuery,
            diffMaxBoost,
            diffMinScore,
            diffFunc,
            q,
            diffCombineFunc
        };
        final int numIters = randomIntBetween(20, 100);
        for (int i = 0; i < numIters; i++) {
            FunctionScoreQuery left = randomFrom(queries);
            FunctionScoreQuery right = randomFrom(queries);
            if (left == right) {
                assertEquals(left, right);
                assertEquals(left.hashCode(), right.hashCode());
            } else {
                assertNotEquals(left + " == " + right, left, right);
            }
        }
    }

    public void testExplanationAndScoreEqualsEvenIfNoFunctionMatches() throws IOException {
        IndexSearcher localSearcher = newSearcher(reader);
        CombineFunction combineFunction = randomFrom(new
            CombineFunction[]{CombineFunction.SUM, CombineFunction.AVG, CombineFunction.MIN, CombineFunction.MAX,
            CombineFunction.MULTIPLY, CombineFunction.REPLACE});

        // check for document that has no matching function
        FunctionScoreQuery query = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")),
            new FilterScoreFunction(new TermQuery(new Term("_uid", "2")), new WeightFactorFunction(10)),
            combineFunction, Float.NEGATIVE_INFINITY, Float.MAX_VALUE);
        TopDocs searchResult = localSearcher.search(query, 1);
        Explanation explanation = localSearcher.explain(query, searchResult.scoreDocs[0].doc);
        assertThat(searchResult.scoreDocs[0].score, equalTo(explanation.getValue()));

        // check for document that has a matching function
        query = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")),
            new FilterScoreFunction(new TermQuery(new Term("_uid", "1")), new WeightFactorFunction(10)),
                combineFunction, Float.NEGATIVE_INFINITY, Float.MAX_VALUE);
        searchResult = localSearcher.search(query, 1);
        explanation = localSearcher.explain(query, searchResult.scoreDocs[0].doc);
        assertThat(searchResult.scoreDocs[0].score, equalTo(explanation.getValue()));
    }

    public void testWeightFactorNeedsScore() {
        for (boolean needsScore : new boolean[] {true, false}) {
            WeightFactorFunction function = new WeightFactorFunction(10.0f, new ScoreFunction(CombineFunction.REPLACE) {
                @Override
                public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException {
                    return null;
                }

                @Override
                public boolean needsScores() {
                    return needsScore;
                }

                @Override
                protected boolean doEquals(ScoreFunction other) {
                    return false;
                }

                @Override
                protected int doHashCode() {
                    return 0;
                }
            });
            assertEquals(needsScore, function.needsScores());
        }
    }

    private static class ConstantScoreFunction extends ScoreFunction {
        final double value;

        protected ConstantScoreFunction(double value) {
            super(CombineFunction.REPLACE);
            this.value = value;
        }

        @Override
        public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException {
            return new LeafScoreFunction() {
                @Override
                public double score(int docId, float subQueryScore) throws IOException {
                    return value;
                }

                @Override
                public Explanation explainScore(int docId, Explanation subQueryScore) throws IOException {
                    return null;
                }
            };
        }

        @Override
        public boolean needsScores() {
            return false;
        }

        @Override
        protected boolean doEquals(ScoreFunction other) {
            return false;
        }

        @Override
        protected int doHashCode() {
            return 0;
        }
    }

    public void testWithInvalidScores() {
        IndexSearcher localSearcher = new IndexSearcher(reader);
        FunctionScoreQuery query1 = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")),
            new ConstantScoreFunction(Float.NaN), CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY);
        ElasticsearchException exc = expectThrows(ElasticsearchException.class, () -> localSearcher.search(query1, 1));
        assertThat(exc.getMessage(), containsString("function score query returned an invalid score: " + Float.NaN));
        FunctionScoreQuery query2 = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")),
            new ConstantScoreFunction(Float.NEGATIVE_INFINITY), CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY);
        exc = expectThrows(ElasticsearchException.class, () -> localSearcher.search(query2, 1));
        assertThat(exc.getMessage(), containsString("function score query returned an invalid score: " + Float.NEGATIVE_INFINITY));
    }

    public void testExceptionOnNegativeScores() {
        IndexSearcher localSearcher = new IndexSearcher(reader);
        TermQuery termQuery = new TermQuery(new Term(FIELD, "out"));

        // test that field_value_factor function throws an exception on negative scores
        FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.NONE;
        final ScoreFunction fvfFunction = new FieldValueFactorFunction(FIELD, -10,  modifier, 1.0, new IndexNumericFieldDataStub());
        FunctionScoreQuery fsQuery1 =
            new FunctionScoreQuery(termQuery, fvfFunction, CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY);
        IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> localSearcher.search(fsQuery1, 1));
        assertThat(exc.getMessage(), containsString("field value function must not produce negative scores"));
        assertThat(exc.getMessage(), not(containsString("consider using ln1p or ln2p instead of ln to avoid negative scores")));
        assertThat(exc.getMessage(), not(containsString("consider using log1p or log2p instead of log to avoid negative scores")));
    }

    public void testExceptionOnLnNegativeScores() {
        IndexSearcher localSearcher = new IndexSearcher(reader);
        TermQuery termQuery = new TermQuery(new Term(FIELD, "out"));

        // test that field_value_factor function using modifier ln throws an exception on negative scores
        FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.LN;
        final ScoreFunction fvfFunction = new FieldValueFactorFunction(FIELD, 0.5f, modifier, 1.0, new IndexNumericFieldDataStub());
        FunctionScoreQuery fsQuery1 =
                new FunctionScoreQuery(termQuery, fvfFunction, CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY);
        IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> localSearcher.search(fsQuery1, 1));
        assertThat(exc.getMessage(), containsString("consider using ln1p or ln2p instead of ln to avoid negative scores"));
    }

    public void testExceptionOnLogNegativeScores() {
        IndexSearcher localSearcher = new IndexSearcher(reader);
        TermQuery termQuery = new TermQuery(new Term(FIELD, "out"));

        // test that field_value_factor function using modifier log throws an exception on negative scores
        FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.LOG;
        final ScoreFunction fvfFunction = new FieldValueFactorFunction(FIELD, 0.5f, modifier, 1.0, new IndexNumericFieldDataStub());
        FunctionScoreQuery fsQuery1 =
                new FunctionScoreQuery(termQuery, fvfFunction, CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY);
        IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> localSearcher.search(fsQuery1, 1));
        assertThat(exc.getMessage(), containsString("consider using log1p or log2p instead of log to avoid negative scores"));
    }

    private static class DummyScoreFunction extends ScoreFunction {
        protected DummyScoreFunction(CombineFunction scoreCombiner) {
            super(scoreCombiner);
        }

        @Override
        public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException {
            return null;
        }

        @Override
        public boolean needsScores() {
            return false;
        }

        @Override
        protected boolean doEquals(ScoreFunction other) {
            return other == this;
        }

        @Override
        protected int doHashCode() {
            return 0;
        }
    }
}


text:
"""
Copyright (c) 2020 The Orbit Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
"""

import logging
import time

from pywinauto.base_wrapper import BaseWrapper

from core.orbit_e2e import E2ETestCase, wait_for_condition

class MoveTab(E2ETestCase):
    """
    Move a tab from the right widget to the left, and back again. Verify the position after each move.
    """

    def right_click_move_context(self, item):
        item.click_input(button='right')
        context_menu = self.suite.application.window(best_match="TabBarContextMenu")
        self.find_control("MenuItem", name_contains="Move",
                          parent=context_menu).click_input(button='left')

    @staticmethod
    def _count_tabs(tab_control: BaseWrapper) -> int:
        return len(tab_control.children(control_type='TabItem'))

    def _execute(self, tab_title, tab_name):
        # Find tab and left and right tab bar
        tab_item = self.find_control("TabItem", tab_title)
        right_tab_bar = self.find_control("Tab",
                                          parent=self.find_control("Group", "RightTabWidget"),
                                          recurse=False)
        left_tab_bar = self.find_control("Tab",
                                         parent=self.find_control("Group", "MainTabWidget"),
                                         recurse=False)

        # Init tests
        left_tab_count = self._count_tabs(left_tab_bar)
        right_tab_count = self._count_tabs(right_tab_bar)

        tab_parent = tab_item.parent()
        self.expect_eq(tab_parent, right_tab_bar,
                       "%s tab is initialized in the right pane" % tab_title)

        # Move "Functions" tab to the left pane, check no. of tabs and if the tab is enabled
        logging.info('Moving tab to the left pane (current tab count: %d)', right_tab_count)
        self.right_click_move_context(tab_item)
        self.expect_eq(self._count_tabs(right_tab_bar), right_tab_count - 1,
                       "1 tab removed from right pane")
        self.expect_eq(self._count_tabs(left_tab_bar), left_tab_count + 1,
                       "1 tab added to the left pane")

        tab_item = self.find_control("TabItem", name=tab_title)
        self.expect_eq(tab_item.parent(), left_tab_bar, "Tab is parented under the left pane")
        self.expect_true(self.find_control("Group", name=tab_name).is_visible(), "Tab is visible")

        # Move back, check no. of tabs
        logging.info('Moving "%s" tab back to the right pane', tab_title)
        self.right_click_move_context(tab_item)
        self.expect_eq(self._count_tabs(right_tab_bar), right_tab_count,
                       "1 tab removed from left pane")
        self.expect_eq(self._count_tabs(left_tab_bar), left_tab_count,
                       "1 tab added to the right pane")

        tab_item = self.find_control("TabItem", name=tab_title)
        self.expect_eq(tab_item.parent(), right_tab_bar, "Tab is parented under the right pane")
        self.expect_true(
            self.find_control("Group", name=tab_name).is_visible(), "Functions tab is visible")

class EndSession(E2ETestCase):
    """
    Click menu entry to end session.
    """

    def _execute(self):
        time.sleep(1)
        app_menu = self.suite.top_window().descendants(control_type="MenuBar")[1]
        app_menu.item_by_path("File->End Session").click_input()
        wait_for_condition(
            lambda: self.suite.application.top_window().class_name() ==
            "orbit_session_setup::SessionSetupDialog", 30)
        self.suite.top_window(force_update=True)

class DismissDialog(E2ETestCase):
    """
    Find a dialog, compare the title and dismiss it by clicking 'OK'.
    """

    def _execute(self, title_contains: str):
        searchRegex = ".*" + title_contains + ".*"
        dialog_box = self.suite.top_window().child_window(title_re=searchRegex,
                                                          control_type="Window")
        self.expect_true(dialog_box is not None, 'Dialog found.')
        ok_button = dialog_box.descendants(control_type='Button', title='OK')[0]
        self.expect_true(ok_button is not None, 'OK Button found.')
        ok_button.click_input()

class RenameMoveCaptureFile(E2ETestCase):
    """
    Click menu entry "Rename/Move Capture File", enter new_capture_path and confirm it.
    """

    def _execute(self, new_capture_path):
        app_menu = self.suite.top_window().descendants(control_type="MenuBar")[1]
        app_menu.item_by_path("File->Rename/Move Capture File").click_input()

        wait_for_condition(lambda: self.find_control('Edit', 'File name:') is not None,
                           max_seconds=120)
        file_name_edit = self.find_control('Edit', 'File name:')

        file_name_edit.set_edit_text(new_capture_path)

        save_button = self.find_control('Button', 'Save')
        save_button.click_input()

        # This waits until no more "Window"s can be found. That means only the OrbitMainWindow is
        # visible, no warnings, errors or progression dialogs
        wait_for_condition(
            lambda: self.find_control(control_type="Window", raise_on_failure=False) is None,
            max_seconds=30)


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"encoding/json"
	"strconv"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// ClusterSpace cluster space
//
// swagger:model cluster_space
type ClusterSpace struct {

	// block storage
	BlockStorage *ClusterSpaceBlockStorage `json:"block_storage,omitempty"`

	// cloud storage
	CloudStorage *ClusterSpaceCloudStorage `json:"cloud_storage,omitempty"`

	// Storage efficiency
	Efficiency *SpaceEfficiency `json:"efficiency,omitempty"`

	// Storage efficiency that does not include the savings provided by Snapshot copies.
	EfficiencyWithoutSnapshots *SpaceEfficiency `json:"efficiency_without_snapshots,omitempty"`

	// Storage efficiency that does not include the savings provided by Snapshot copies and FlexClones.
	EfficiencyWithoutSnapshotsFlexclones *SpaceEfficiency `json:"efficiency_without_snapshots_flexclones,omitempty"`
}

// Validate validates this cluster space
func (m *ClusterSpace) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateBlockStorage(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateCloudStorage(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateEfficiency(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateEfficiencyWithoutSnapshots(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateEfficiencyWithoutSnapshotsFlexclones(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpace) validateBlockStorage(formats strfmt.Registry) error {
	if swag.IsZero(m.BlockStorage) { // not required
		return nil
	}

	if m.BlockStorage != nil {
		if err := m.BlockStorage.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("block_storage")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) validateCloudStorage(formats strfmt.Registry) error {
	if swag.IsZero(m.CloudStorage) { // not required
		return nil
	}

	if m.CloudStorage != nil {
		if err := m.CloudStorage.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("cloud_storage")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) validateEfficiency(formats strfmt.Registry) error {
	if swag.IsZero(m.Efficiency) { // not required
		return nil
	}

	if m.Efficiency != nil {
		if err := m.Efficiency.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) validateEfficiencyWithoutSnapshots(formats strfmt.Registry) error {
	if swag.IsZero(m.EfficiencyWithoutSnapshots) { // not required
		return nil
	}

	if m.EfficiencyWithoutSnapshots != nil {
		if err := m.EfficiencyWithoutSnapshots.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) validateEfficiencyWithoutSnapshotsFlexclones(formats strfmt.Registry) error {
	if swag.IsZero(m.EfficiencyWithoutSnapshotsFlexclones) { // not required
		return nil
	}

	if m.EfficiencyWithoutSnapshotsFlexclones != nil {
		if err := m.EfficiencyWithoutSnapshotsFlexclones.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots_flexclones")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this cluster space based on the context it is used
func (m *ClusterSpace) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateBlockStorage(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateCloudStorage(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateEfficiency(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateEfficiencyWithoutSnapshots(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateEfficiencyWithoutSnapshotsFlexclones(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpace) contextValidateBlockStorage(ctx context.Context, formats strfmt.Registry) error {

	if m.BlockStorage != nil {
		if err := m.BlockStorage.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("block_storage")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) contextValidateCloudStorage(ctx context.Context, formats strfmt.Registry) error {

	if m.CloudStorage != nil {
		if err := m.CloudStorage.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("cloud_storage")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) contextValidateEfficiency(ctx context.Context, formats strfmt.Registry) error {

	if m.Efficiency != nil {
		if err := m.Efficiency.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) contextValidateEfficiencyWithoutSnapshots(ctx context.Context, formats strfmt.Registry) error {

	if m.EfficiencyWithoutSnapshots != nil {
		if err := m.EfficiencyWithoutSnapshots.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpace) contextValidateEfficiencyWithoutSnapshotsFlexclones(ctx context.Context, formats strfmt.Registry) error {

	if m.EfficiencyWithoutSnapshotsFlexclones != nil {
		if err := m.EfficiencyWithoutSnapshotsFlexclones.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots_flexclones")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *ClusterSpace) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ClusterSpace) UnmarshalBinary(b []byte) error {
	var res ClusterSpace
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// ClusterSpaceBlockStorage cluster space block storage
//
// swagger:model ClusterSpaceBlockStorage
type ClusterSpaceBlockStorage struct {

	// Available space across the cluster
	Available int64 `json:"available,omitempty"`

	// Inactive data across all aggregates
	InactiveData int64 `json:"inactive_data,omitempty"`

	// medias
	Medias []*ClusterSpaceBlockStorageMediasItems0 `json:"medias,omitempty"`

	// Total physical used space across the cluster
	PhysicalUsed int64 `json:"physical_used,omitempty"`

	// Total space across the cluster
	Size int64 `json:"size,omitempty"`

	// Space used (includes volume reserves)
	Used int64 `json:"used,omitempty"`
}

// Validate validates this cluster space block storage
func (m *ClusterSpaceBlockStorage) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateMedias(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpaceBlockStorage) validateMedias(formats strfmt.Registry) error {
	if swag.IsZero(m.Medias) { // not required
		return nil
	}

	for i := 0; i < len(m.Medias); i++ {
		if swag.IsZero(m.Medias[i]) { // not required
			continue
		}

		if m.Medias[i] != nil {
			if err := m.Medias[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("block_storage" + "." + "medias" + "." + strconv.Itoa(i))
				}
				return err
			}
		}

	}

	return nil
}

// ContextValidate validate this cluster space block storage based on the context it is used
func (m *ClusterSpaceBlockStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateMedias(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpaceBlockStorage) contextValidateMedias(ctx context.Context, formats strfmt.Registry) error {

	for i := 0; i < len(m.Medias); i++ {

		if m.Medias[i] != nil {
			if err := m.Medias[i].ContextValidate(ctx, formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("block_storage" + "." + "medias" + "." + strconv.Itoa(i))
				}
				return err
			}
		}

	}

	return nil
}

// MarshalBinary interface implementation
func (m *ClusterSpaceBlockStorage) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ClusterSpaceBlockStorage) UnmarshalBinary(b []byte) error {
	var res ClusterSpaceBlockStorage
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// ClusterSpaceBlockStorageMediasItems0 cluster space block storage medias items0
//
// swagger:model ClusterSpaceBlockStorageMediasItems0
type ClusterSpaceBlockStorageMediasItems0 struct {

	// Available space
	Available int64 `json:"available,omitempty"`

	// Storage Efficiency
	Efficiency *SpaceEfficiency `json:"efficiency,omitempty"`

	// Storage efficiency that does not include the savings provided by Snapshot copies.
	EfficiencyWithoutSnapshots *SpaceEfficiency `json:"efficiency_without_snapshots,omitempty"`

	// Storage efficiency that does not include the savings provided by Snapshot copies and FlexClones.
	EfficiencyWithoutSnapshotsFlexclones *SpaceEfficiency `json:"efficiency_without_snapshots_flexclones,omitempty"`

	// Total physical used space
	PhysicalUsed int64 `json:"physical_used,omitempty"`

	// Total space
	Size int64 `json:"size,omitempty"`

	// The type of media being used
	// Enum: [hdd hybrid lun ssd vmdisk]
	Type string `json:"type,omitempty"`

	// Used space
	Used int64 `json:"used,omitempty"`
}

// Validate validates this cluster space block storage medias items0
func (m *ClusterSpaceBlockStorageMediasItems0) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateEfficiency(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateEfficiencyWithoutSnapshots(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateEfficiencyWithoutSnapshotsFlexclones(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateType(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) validateEfficiency(formats strfmt.Registry) error {
	if swag.IsZero(m.Efficiency) { // not required
		return nil
	}

	if m.Efficiency != nil {
		if err := m.Efficiency.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) validateEfficiencyWithoutSnapshots(formats strfmt.Registry) error {
	if swag.IsZero(m.EfficiencyWithoutSnapshots) { // not required
		return nil
	}

	if m.EfficiencyWithoutSnapshots != nil {
		if err := m.EfficiencyWithoutSnapshots.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) validateEfficiencyWithoutSnapshotsFlexclones(formats strfmt.Registry) error {
	if swag.IsZero(m.EfficiencyWithoutSnapshotsFlexclones) { // not required
		return nil
	}

	if m.EfficiencyWithoutSnapshotsFlexclones != nil {
		if err := m.EfficiencyWithoutSnapshotsFlexclones.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots_flexclones")
			}
			return err
		}
	}

	return nil
}

var clusterSpaceBlockStorageMediasItems0TypeTypePropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["hdd","hybrid","lun","ssd","vmdisk"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		clusterSpaceBlockStorageMediasItems0TypeTypePropEnum = append(clusterSpaceBlockStorageMediasItems0TypeTypePropEnum, v)
	}
}

const (

	// BEGIN DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0
	// ClusterSpaceBlockStorageMediasItems0
	// type
	// Type
	// hdd
	// END DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0TypeHdd captures enum value "hdd"
	ClusterSpaceBlockStorageMediasItems0TypeHdd string = "hdd"

	// BEGIN DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0
	// ClusterSpaceBlockStorageMediasItems0
	// type
	// Type
	// hybrid
	// END DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0TypeHybrid captures enum value "hybrid"
	ClusterSpaceBlockStorageMediasItems0TypeHybrid string = "hybrid"

	// BEGIN DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0
	// ClusterSpaceBlockStorageMediasItems0
	// type
	// Type
	// lun
	// END DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0TypeLun captures enum value "lun"
	ClusterSpaceBlockStorageMediasItems0TypeLun string = "lun"

	// BEGIN DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0
	// ClusterSpaceBlockStorageMediasItems0
	// type
	// Type
	// ssd
	// END DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0TypeSsd captures enum value "ssd"
	ClusterSpaceBlockStorageMediasItems0TypeSsd string = "ssd"

	// BEGIN DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0
	// ClusterSpaceBlockStorageMediasItems0
	// type
	// Type
	// vmdisk
	// END DEBUGGING
	// ClusterSpaceBlockStorageMediasItems0TypeVmdisk captures enum value "vmdisk"
	ClusterSpaceBlockStorageMediasItems0TypeVmdisk string = "vmdisk"
)

// prop value enum
func (m *ClusterSpaceBlockStorageMediasItems0) validateTypeEnum(path, location string, value string) error {
	if err := validate.EnumCase(path, location, value, clusterSpaceBlockStorageMediasItems0TypeTypePropEnum, true); err != nil {
		return err
	}
	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) validateType(formats strfmt.Registry) error {
	if swag.IsZero(m.Type) { // not required
		return nil
	}

	// value enum
	if err := m.validateTypeEnum("type", "body", m.Type); err != nil {
		return err
	}

	return nil
}

// ContextValidate validate this cluster space block storage medias items0 based on the context it is used
func (m *ClusterSpaceBlockStorageMediasItems0) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateEfficiency(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateEfficiencyWithoutSnapshots(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateEfficiencyWithoutSnapshotsFlexclones(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) contextValidateEfficiency(ctx context.Context, formats strfmt.Registry) error {

	if m.Efficiency != nil {
		if err := m.Efficiency.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) contextValidateEfficiencyWithoutSnapshots(ctx context.Context, formats strfmt.Registry) error {

	if m.EfficiencyWithoutSnapshots != nil {
		if err := m.EfficiencyWithoutSnapshots.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots")
			}
			return err
		}
	}

	return nil
}

func (m *ClusterSpaceBlockStorageMediasItems0) contextValidateEfficiencyWithoutSnapshotsFlexclones(ctx context.Context, formats strfmt.Registry) error {

	if m.EfficiencyWithoutSnapshotsFlexclones != nil {
		if err := m.EfficiencyWithoutSnapshotsFlexclones.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("efficiency_without_snapshots_flexclones")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *ClusterSpaceBlockStorageMediasItems0) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ClusterSpaceBlockStorageMediasItems0) UnmarshalBinary(b []byte) error {
	var res ClusterSpaceBlockStorageMediasItems0
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// ClusterSpaceCloudStorage cluster space cloud storage
//
// swagger:model ClusterSpaceCloudStorage
type ClusterSpaceCloudStorage struct {

	// Total space used in cloud.
	// Read Only: true
	Used int64 `json:"used,omitempty"`
}

// Validate validates this cluster space cloud storage
func (m *ClusterSpaceCloudStorage) Validate(formats strfmt.Registry) error {
	return nil
}

// ContextValidate validate this cluster space cloud storage based on the context it is used
func (m *ClusterSpaceCloudStorage) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateUsed(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ClusterSpaceCloudStorage) contextValidateUsed(ctx context.Context, formats strfmt.Registry) error {

	if err := validate.ReadOnly(ctx, "cloud_storage"+"."+"used", "body", int64(m.Used)); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *ClusterSpaceCloudStorage) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ClusterSpaceCloudStorage) UnmarshalBinary(b []byte) error {
	var res ClusterSpaceCloudStorage
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Yasb.Common.Tests.Messages;

namespace Yasb.Common.Messaging
{
    public class MessageEnvelope
    {
        private Dictionary<string, object> _headers = new Dictionary<string, object>();
        public MessageEnvelope()
        {

        }
        public MessageEnvelope(IMessage message)
        {
            Message = message;
        }

        public IMessage Message { get; set; }

        public string Id { get; set; }

        public int RetriesNumber { get; set; }

        public string LastErrorMessage { get; set; }

        public long? StartTimestamp { get; set; }

        public DateTime? StartTime
        {
            get
            {
                if (!StartTimestamp.HasValue)
                    return null;
                return DateTime.MinValue.Add(new TimeSpan(StartTimestamp.Value));
            }
        }
        public void SetHeader<TValue>(string name, TValue value)
        {
            _headers[name] = value;
        }

        public TValue GetHeader<TValue>(string name)
        {
            object value = default(TValue);
            return _headers.TryGetValue(name, out value) ? (TValue)value : default(TValue);
        }

    }

}


text:
void ReadPngData(png_structp png_ptr, png_bytep data, png_size_t length)
{
	if (png_ptr == nullptr)
		return;

	ChilliSource::IBinaryInputStream* pStream = (ChilliSource::IBinaryInputStream*)png_get_io_ptr(png_ptr);
	pStream->Read(reinterpret_cast<u8*>(data), s32(length));
}

namespace CSBackend
{
	namespace Windows
	{
		//----------------------------------------------------------------------------------
		/// Constructor
		//----------------------------------------------------------------------------------
		PngImage::PngImage()
		{
			mbIsLoaded = false;
			mdwHeight = -1;
			mdwWidth = -1;
			mpData = nullptr;
		}
		//----------------------------------------------------------------------------------
		/// Constructor
		//----------------------------------------------------------------------------------
		PngImage::PngImage(ChilliSource::StorageLocation ineLocation, const std::string& instrFilename)
		{
			mbIsLoaded = false;
			mdwHeight = -1;
			mdwWidth = -1;
			mpData = nullptr;

			Load(ineLocation, instrFilename);
		}
		//----------------------------------------------------------------------------------
		/// Destructor
		//----------------------------------------------------------------------------------
		PngImage::~PngImage()
		{
			if (mbIsLoaded == true)
			{
				Release();
			}
		}
		//----------------------------------------------------------------------------------
		/// Load PNG
		///
		/// Loads a png from a file within documents or the package.
		/// @param Storgae location of the file
		/// @param std::string instrFilename - the path to the file relative to either
		///									   documents or the package.
		//----------------------------------------------------------------------------------
		void PngImage::Load(ChilliSource::StorageLocation ineLocation, const std::string& instrFilename)
		{
			//create the file stream
			auto stream = ChilliSource::Application::Get()->GetFileSystem()->CreateBinaryInputStream(ineLocation, instrFilename);

			//insure the stream is not broken
			if (stream == nullptr)
			{
				return;
			}

			//load from lib png
			if (LoadWithLibPng(stream) == true)
			{
				mbIsLoaded = true;
			}
		}
		//----------------------------------------------------------------------------------
		/// Release
		///
		/// Releases the image data
		/// @param bool inReleaseImageData - Whether or not to release the image data
		//----------------------------------------------------------------------------------
		void PngImage::Release(bool inReleaseImageData)
		{
			if (mbIsLoaded != false)
			{
				mbIsLoaded = false;
				mdwHeight = -1;
				mdwWidth = -1;
				if (inReleaseImageData)
					delete[] mpData;
				mpData = (u8*)nullptr;
			}
		}
		//----------------------------------------------------------------------------------
		/// Is Loaded
		///
		/// returns whether or not the image is loaded
		//----------------------------------------------------------------------------------
		bool PngImage::IsLoaded()
		{
			return mbIsLoaded;
		}
		//----------------------------------------------------------------------------------
		/// Get Height
		///
		/// returns the height of the image
		//----------------------------------------------------------------------------------
		s32 PngImage::GetHeight()
		{
			return mdwHeight;
		}
		//----------------------------------------------------------------------------------
		/// Get Width
		///
		/// returns the width of the image
		//----------------------------------------------------------------------------------
		s32 PngImage::GetWidth()
		{
			return mdwWidth;
		}
		//----------------------------------------------------------------------------------
		/// Get Image Data
		///
		/// returns the image data.
		//----------------------------------------------------------------------------------
		u8 * PngImage::GetImageData()
		{
			return mpData;
		}
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
		u32 PngImage::GetDataSize() const
		{
			return m_dataSize;
		}
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
		ChilliSource::ImageFormat PngImage::GetImageFormat() const
		{
			return m_format;
		}
		//----------------------------------------------------------------------------------
		/// Load with lib png
		///
		/// Loads the png data using lib png
		/// @param FileStreamSPtr inStream - the steam lib png should use to read the data.
		//----------------------------------------------------------------------------------
		bool PngImage::LoadWithLibPng(const ChilliSource::IBinaryInputStreamUPtr& inStream)
		{
			//insure that it is indeed a png
			const s32 dwHeaderSize = 8;
			u8 ubyHeader[dwHeaderSize];
			inStream->Read(ubyHeader, dwHeaderSize);

			if (png_sig_cmp(ubyHeader, 0, dwHeaderSize) > 0)
			{
				CS_LOG_ERROR("PNG header invalid.");
				return false;
			}

			//create the png structure
			png_structp pPng = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
			if (!pPng)
			{
				CS_LOG_ERROR("Could not create pPng");
				return false;
			}

			//create the png info
			png_infop pInfo = png_create_info_struct(pPng);
			if (!pInfo)
			{
				CS_LOG_ERROR("Could not create pInfo");
				png_destroy_read_struct(&pPng, (png_infopp)nullptr, (png_infopp)nullptr);
				return false;
			}

			//setup jump
			if (setjmp(png_jmpbuf(pPng)))
			{
				CS_LOG_ERROR("Error while loading PNG.");
				png_destroy_read_struct(&pPng, &pInfo, (png_infopp)nullptr);
				return false;
			}

			//Setup the ReadPngData function for use within libPng
			png_set_read_fn(pPng,(void*)inStream.get(), ReadPngData);

			//tell it that we've ready read 8 bytes of data
			png_set_sig_bytes(pPng, dwHeaderSize);

			//read the chunks of data upto the actual image data
			png_read_info(pPng, pInfo);

			//get the info thats just been read
			png_uint_32 udwWidth = 0;
			png_uint_32 udwHeight = 0;
			s32 dwBitDepth = -1;
			s32 dwColorType = -1;
			s32 dwInterlaceType = -1;
			s32 dwCompressionMethod = -1;
			s32 dwFilterMethod = -1;
			png_get_IHDR(pPng, pInfo, &udwWidth, &udwHeight, &dwBitDepth, &dwColorType, &dwInterlaceType, &dwCompressionMethod, &dwFilterMethod);

			//--transformations
			//sorts out grey scale images, probably not needed, but put in anyway
			if (dwColorType == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(pPng);
			if (dwColorType == PNG_COLOR_TYPE_GRAY && dwBitDepth < 8) png_set_expand_gray_1_2_4_to_8(pPng);
			if (png_get_valid(pPng, pInfo, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pPng);

			//insure all files use 1 bit each for R,G,B and A
			if (dwBitDepth == 16) png_set_strip_16(pPng);

			//unpack compressed pixels
			if (dwBitDepth < 8) png_set_packing(pPng);

			//pack in an alpha value if there isn't one.
			if (dwColorType == PNG_COLOR_TYPE_RGB || dwColorType == PNG_COLOR_TYPE_GRAY)
				png_set_add_alpha(pPng, (u8)255, PNG_FILLER_AFTER);

			//for the sake of simplicity, turn grey scale images into RGB
			if (dwColorType == PNG_COLOR_TYPE_GRAY || dwColorType == PNG_COLOR_TYPE_GRAY_ALPHA)
				png_set_gray_to_rgb(pPng);

			//set to little endianness
			if (dwBitDepth == 16)
				png_set_swap(pPng);

			//tell libpng to handling interlacing
			s32 number_of_passes = png_set_interlace_handling(pPng);

			//after all these transformations, update the png info
			png_read_update_info(pPng, pInfo);

			//read the image into the data buffer
			s32 dwRowBytes = s32(png_get_rowbytes(pPng, pInfo));
			m_dataSize = dwRowBytes * udwHeight;
			mpData = new u8[m_dataSize];

			for (s32 pass = 0; pass < number_of_passes; pass++)
			{
				for (u32 y = 0; y < udwHeight; y += 1)
				{
					png_bytep row = (mpData + y * dwRowBytes);
					png_read_rows(pPng, &row, nullptr, 1);
				}
			}

			//store the width and height
			mdwWidth = (s32)udwWidth;
			mdwHeight = (s32)udwHeight;

			//-------- Get the image format
			png_get_IHDR(pPng, pInfo, &udwWidth, &udwHeight, &dwBitDepth, &dwColorType, &dwInterlaceType, &dwCompressionMethod, &dwFilterMethod);
			switch (dwColorType)
			{
			case PNG_COLOR_TYPE_GRAY:
				m_format = ChilliSource::ImageFormat::k_Lum8;
				break;
			case PNG_COLOR_TYPE_GRAY_ALPHA:
				m_format = ChilliSource::ImageFormat::k_LumA88;
				break;
			case PNG_COLOR_TYPE_RGB:
				m_format = ChilliSource::ImageFormat::k_RGB888;
				break;
			case PNG_COLOR_TYPE_RGB_ALPHA:
				m_format = ChilliSource::ImageFormat::k_RGBA8888;
				break;
			default:
				CS_LOG_ERROR("Trying to load a PNG with an unknown colour format!");
				png_read_end(pPng, nullptr);
				png_destroy_read_struct(&pPng, &pInfo, (png_infopp)nullptr);
				return false;
				break;
			}

			//end the read
			png_read_end(pPng, nullptr);

			//deallocate everything
			png_destroy_read_struct(&pPng, &pInfo, (png_infopp)nullptr);
			return true;
		}
	}
}

#endif