repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
joshng/papaya
papaya/src/main/java/com/joshng/util/collect/FunctionalList.java
6387
package com.joshng.util.collect; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import javax.annotation.Nullable; import java.util.*; import java.util.function.Consumer; import static com.google.common.base.Preconditions.checkNotNull; import static com.joshng.util.reflect.Reflect.blindCast; /** * User: josh * Date: Aug 27, 2011 * Time: 4:26:26 PM */ public class FunctionalList<E> extends FunctionalIterable<E> implements FunList<E> { FunctionalList(ImmutableList<E> delegate) { super(delegate); } @Override public ImmutableList<E> delegate() { return (ImmutableList<E>) super.delegate(); } public static <T> FunList<T> extendList(ImmutableList<T> list) { if (list.isEmpty()) return Functional.emptyList(); return new FunctionalList<>(list); } public static <T> FunList<T> copyOf(T[] items) { if (items.length == 0) return Functional.emptyList(); return new FunctionalList<>(ImmutableList.copyOf(items)); } public static <T> FunList<T> copyOf(Iterator<? extends T> items) { checkNotNull(items); if (!items.hasNext()) return Functional.emptyList(); return new FunctionalList<>(ImmutableList.copyOf(items)); } public static <T> Builder<T> builder() { return new Builder<>(); } @SuppressWarnings("Convert2Lambda") @Override public FunIterable<FunList<E>> partition(final int size) { return new FunctionalIterable<>(new Iterable<FunList<E>>() { public Iterator<FunList<E>> iterator() { return new AbstractIterator<FunList<E>>() { private final int end = size(); private int idx = 0; @Override protected FunList<E> computeNext() { if (idx == end) return endOfData(); int start = idx; idx = Math.min(idx + size, end); return FunctionalList.extendList(delegate().subList(start, idx)); } }; } }); } public FunList<E> subList(int fromIndex, int toIndex) { return extendList(delegate().subList(fromIndex, toIndex)); } public Maybe<E> head() { return isEmpty() ? Maybe.<E>not() : Maybe.definitely(get(0)); } public FunList<E> tail() { if (isEmpty()) return this; ImmutableList<E> delegate = delegate(); return extendList(delegate.subList(1, delegate.size())); } @Override public Maybe<E> foot() { return isEmpty() ? Maybe.<E>not() : Maybe.definitely(delegate().get(size() - 1)); } public FunList<E> limit(int maxElements) { return subList(0, Math.min(maxElements, size())); } public FunList<E> skip(int skippedElements) { int size = size(); return subList(Math.min(skippedElements, size), size); } public FunList<E> foreach(Consumer<? super E> visitor) { super.foreach(visitor); return this; } public FunList<E> toList() { return this; } public FunList<E> reverse() { return new FunctionalList<>(delegate().reverse()); } public void add(int index, E element) { throw FunCollection.rejectMutation(); } public boolean addAll(int index, Collection<? extends E> elements) { throw FunCollection.rejectMutation(); } public E get(int index) { return delegate().get(index); } public int indexOf(Object element) { return delegate().indexOf(element); } public int lastIndexOf(Object element) { return delegate().lastIndexOf(element); } public ListIterator<E> listIterator() { return delegate().listIterator(); } public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); } public E remove(int index) { throw FunCollection.rejectMutation(); } public E set(int index, E element) { throw FunCollection.rejectMutation(); } @SuppressWarnings({"unchecked"}) @Override public <U> FunList<U> cast() { return blindCast(this); } public static class Builder<T> { private final ImmutableList.Builder<T> listBuilder = ImmutableList.builder(); public Builder<T> add(T element) { listBuilder.add(element); return this; } public Builder<T> addAll(Iterable<? extends T> elements) { listBuilder.addAll(elements); return this; } @SafeVarargs public final Builder<T> add(T... elements) { listBuilder.add(elements); return this; } public Builder<T> addAll(Iterator<? extends T> elements) { listBuilder.addAll(elements); return this; } public FunList<T> build() { return extendList(listBuilder.build()); } } static final EmptyList EMPTY = new EmptyList(); @SuppressWarnings({"unchecked"}) private static class EmptyList extends EmptyCollection implements FunList { public ImmutableList delegate() { return ImmutableList.of(); } public FunList reverse() { return this; } public EmptyList tail() { return this; } @Override public EmptyList foreach(Consumer visitor) { return this; } @Override public FunList cast() { return this; } public boolean addAll(int index, Collection c) { throw FunCollection.rejectMutation(); } public Object get(int index) { throw indexOutOfBounds(index); } public Object set(int index, Object element) { throw FunCollection.rejectMutation(); } public void add(int index, Object element) { throw FunCollection.rejectMutation(); } public int indexOf(java.lang.Object o) { return -1; } public int lastIndexOf(java.lang.Object o) { return -1; } public ListIterator listIterator() { return Collections.emptyListIterator(); } public ListIterator listIterator(int index) { return listIterator(); } public List subList(int fromIndex, int toIndex) { if (fromIndex != 0) throw indexOutOfBounds(fromIndex); if (toIndex != 0) throw indexOutOfBounds(toIndex); return this; } private IndexOutOfBoundsException indexOutOfBounds(int index) { return new IndexOutOfBoundsException(String.valueOf(index)); } @Override public boolean equals(@Nullable Object object) { return object == this || (object instanceof List && ((List) object).isEmpty()); } @Override public int hashCode() { return delegate().hashCode(); } } }
bsd-2-clause
seraphy/EmbeddedTomcatLauncher
src/jp/seraphyware/embeddedtomcat/SimpleServerConfigurator1.java
3551
package jp.seraphyware.embeddedtomcat; import java.io.File; import java.io.IOException; import javax.servlet.ServletException; import org.apache.catalina.Host; import org.apache.catalina.core.StandardContext; import org.apache.catalina.session.StandardManager; import org.apache.catalina.startup.Tomcat; /** * 1つのポートと、1つのウェブアプリを起動する最小構成例.<br> */ public final class SimpleServerConfigurator1 extends AbstractServerConfigurator { /** * デフォルトのポート */ private int port = 8081; /** * コンストラクタ */ public SimpleServerConfigurator1() { // リスンするポートをシステムプロパティより取得する. String strPort = System.getProperty("port"); if (strPort != null && strPort.trim().length() > 0) { port = Integer.parseInt(strPort); } } /** * リスンポートを返す. */ @Override public int getPort() { return port; } /** * もっとも単純なTomcatの独自のスタートアップ方法による初期化.<br> */ @Override public void init() throws IOException, ServletException { if (tomcat != null) { throw new IllegalStateException("already initialized"); } // Tomcatの組み込み or テストの構成用のヘルパクラスを構築. tomcat = new Tomcat(); // リスンするポートの指定 tomcat.setPort(port); // -------------------------------- // ベースディレクトリの指定. // -------------------------------- // CATALINA_HOME, CATALINA_BASEシステムプロパティの設定. // このディレクトリ下でJSPのコンパイルやセッションの永続化など // さまざまなデータの保存が行われる. String baseDir = new File(getAppRootDir(), "work").getCanonicalPath(); tomcat.setBaseDir(baseDir); // -------------------------------- // 自動的に構成された標準構成のHostインスタンスを取得する // -------------------------------- Host host = tomcat.getHost(); // 仮想ホストのアプリケーションディレクトリを指定する. // baseDirからの相対で指定するか、もしくは絶対パスを指定する. String appbase = new File(getAppRootDir(), "webapp1").getCanonicalPath(); host.setAppBase(appbase); // -------------------------------- // アプリケーションを1つ構成する. // -------------------------------- // 1つのアプリだけで良いのでアプリケーションフォルダ自身とする. ctx = (StandardContext) tomcat.addWebapp("/", appbase); // -------------------------------- // コンテキストマネージャを設定する // -------------------------------- StandardManager manager = new StandardManager(); // セッションをファイルにシリアライズさせないためファイル名をnullにする. // (デフォルトではワークディレクトリ上にSESSIONS.SERファイルが生成される) manager.setPathname(null); ctx.setManager(manager); } /** * エントリポイント * * @param args */ public static void main(String[] args) { EmbeddedServerFrame.launch(new SimpleServerConfigurator1()); } }
bsd-2-clause
klrkdekira/golang-talks
2014/golang-101/snippets/import.go
84
import ( "tutorial" "tutorial/lib" ) $ go get tutorial/cmd/tutoriald $ tutoriald
bsd-2-clause
aftabahmedsajid/XenCenter-Complete-dependencies-
XenModel/Actions/Host/ApplyLicenseEditionAction.cs
11860
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Linq; using System.Collections.Generic; using XenAPI; using XenAdmin.Alerts; using System.ComponentModel; using System.Threading; using XenAdmin.Core; using XenAdmin.Actions.HostActions; namespace XenAdmin.Actions { /// <summary> /// This Action is for v6 (Midnight Ride) licensing. It sets the license server details and sets the edition to advanced, enterprise, enterprise-xd, platinum or free. /// </summary> public class ApplyLicenseEditionAction : AsyncAction { private readonly IEnumerable<IXenObject> xos; private readonly Host.Edition _edition; private readonly string _licenseServerAddress; private readonly string _licenseServerPort; public List<LicenseFailure> LicenseFailures { get; private set; } protected readonly Action<List<LicenseFailure>, string> DoOnLicensingFailure; /// <summary> /// Initializes a new instance of the <see cref="ApplyLicenseEditionAction"/> class. /// </summary> /// <param name="xos">The hosts for which the license should be set.</param> /// <param name="edition">The edition the hosts should be set to.</param> /// <param name="licenseServerAddress">The license server address.</param> /// <param name="licenseServerPort">The license server port.</param> /// <param name="DoOnLicensingFailure">The method to call when the licensing fails. This method will show failure details in a dialog</param> public ApplyLicenseEditionAction(IEnumerable<IXenObject> xos, Host.Edition edition, string licenseServerAddress, string licenseServerPort, Action<List<LicenseFailure>, string> DoOnLicensingFailure) : base(null, Messages.LICENSE_UPDATING_LICENSES) { LicenseFailures = new List<LicenseFailure>(); Util.ThrowIfEnumerableParameterNullOrEmpty(xos, "xenobjects"); _edition = edition; this.xos = xos; _licenseServerAddress = licenseServerAddress; _licenseServerPort = licenseServerPort; this.DoOnLicensingFailure = DoOnLicensingFailure; } private static void SetLicenseServer(Host host, string licenseServerAddress, string licenseServerPort) { Dictionary<string, string> d = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(licenseServerAddress) && !string.IsNullOrEmpty(licenseServerPort)) { d.Add("address", licenseServerAddress); d.Add("port", licenseServerPort); } XenAPI.Host.set_license_server(host.Connection.Session, host.opaque_ref, d); } protected override void Run() { // PR-1102: hosts that have been updated, plus the previous edition information - this data will be sent to the licensing server Dictionary<Host, LicensingHelper.LicenseDataStruct> updatedHosts = new Dictionary<Host, LicensingHelper.LicenseDataStruct>(); this.Description = Messages.LICENSE_UPDATING_LICENSES; foreach (IXenObject xo in xos) { Connection = xo.Connection; if (!Connection.IsConnected) { continue; } Host host = null; Pool pool = null; if(xo is Host) host = xo as Host; if(xo is Pool) { pool = xo as Pool; host = xo.Connection.Resolve(pool.master); } string previousLicenseServerAddress = null; string previousLicenseServerPort = null; CollectionChangeEventHandler alertsChangeHandler = null; string alertText = null; object lck = new object(); if (host != null && host.license_server.ContainsKey("address")) { previousLicenseServerAddress = host.license_server["address"]; } if (host != null && host.license_server.ContainsKey("port")) { previousLicenseServerPort = host.license_server["port"]; } try { if(pool != null) pool.Connection.Cache.Hosts.ToList().ForEach(h=>SetLicenseServer(h, _licenseServerAddress, _licenseServerPort)); else SetLicenseServer(host, _licenseServerAddress, _licenseServerPort); IXenObject xoClosure = xo; alertsChangeHandler = delegate(object sender, CollectionChangeEventArgs e) { if (e.Action == CollectionChangeAction.Add) { lock (lck) { Alert alert = (Alert)e.Element; if (host != null && host.uuid == alert.HostUuid) { if (alert.Title == PropertyManager.GetFriendlyName("Message.name-license_not_available")) { // the license server reported there were no licenses available. alertText = string.Format(PropertyManager.GetFriendlyName("Message.body-license_not_available"), xoClosure.Name); } else if (alert.Title == PropertyManager.GetFriendlyName("Message.name-license_server_unreachable")) { // couldn't check out license because couldn't contact license server alertText = string.Format(PropertyManager.GetFriendlyName("Message.body-license_server_unreachable"), xoClosure.Name); } else if (alert.Title == PropertyManager.GetFriendlyName("Message.name-grace_license")) { alertText = string.Empty; } } } } }; Alert.RegisterAlertCollectionChanged(alertsChangeHandler); // PR-1102: catch the host's license data, before applying the new one, so it can be sent later to the licensing server LicensingHelper.LicenseDataStruct previousLicenseData = new LicensingHelper.LicenseDataStruct(host); if(xo is Host && host != null) { if (Helpers.ClearwaterOrGreater(host)) Host.apply_edition(host.Connection.Session, host.opaque_ref, Host.GetEditionText(_edition), false); else Host.apply_edition(host.Connection.Session, host.opaque_ref, Host.GetEditionText(_edition)); // PR-1102: populate the list of updated hosts updatedHosts.Add(host, previousLicenseData); } if (xo is Pool) { if(!Helpers.ClearwaterOrGreater(xo.Connection)) { foreach (Host poolHost in xo.Connection.Cache.Hosts) { Host.apply_edition(host.Connection.Session, poolHost.opaque_ref, Host.GetEditionText(_edition)); } } else { Pool.apply_edition(xo.Connection.Session, pool.opaque_ref, Host.GetEditionText(_edition)); //TODO: Look into why this is required. Event.Next returning late? XAPI returning before updated? Thread.Sleep(200); } xo.Connection.Cache.Hosts.ToList().ForEach(h => updatedHosts.Add(h, previousLicenseData)); } Description = Messages.APPLYLICENSE_UPDATED; } catch (Failure e) { for (int i = 0; i < 50; i++) { Thread.Sleep(100); lock (lck) { if (alertText != null) break; } } LicenseFailures.Add(new LicenseFailure(host, alertText ?? e.Message)); if (pool != null) pool.Connection.Cache.Hosts.ToList().ForEach(h => SetLicenseServer(h, previousLicenseServerAddress, previousLicenseServerPort)); else SetLicenseServer(host, previousLicenseServerAddress, previousLicenseServerPort); } finally { Alert.DeregisterAlertCollectionChanged(alertsChangeHandler); } } // PR-1102: Send licensing data to the activation server if (updatedHosts.Count > 0) { LicensingHelper.SendLicenseEditionData(updatedHosts, Host.GetEditionText(_edition)); } if (LicenseFailures.Count > 0) { string exceptionText = LicenseFailures.Count == 1 ? string.Format(Messages.LICENSE_ERROR_1, LicenseFailures[0].Host.Name) : string.Format(Messages.LICENSE_ERROR_MANY, LicenseFailures.Count, new List<IXenObject>(xos).Count); if (DoOnLicensingFailure != null) DoOnLicensingFailure(LicenseFailures, exceptionText); throw new InvalidOperationException(exceptionText); } } } public class LicenseFailure { public Host Host; public string AlertText; public LicenseFailure(Host host, string alertText) { Host = host; AlertText = alertText; } } }
bsd-2-clause
ErshKUS/OpenStreetMap.ru
www/js/page.map/validators.js
6276
osm.validators = { sources: [{ "name": "Адресный и роутинговый валидатор Zkir", "url": "http://osm.alno.name/validators/zkir?minlat={minlat}&minlon={minlon}&maxlat={maxlat}&maxlon={maxlon}&types={filtered_types}", "types": { "city_without_population": {"text": "Город без населения"}, "city_without_place_polygon": {"text": "Город без полигональной границы"}, "city_without_place_node": {"text": "Город без точечного центра"}, "routing_subgraph": {"text": "Изолированный подграф"}, "routing_subgraph_trunk": {"text": "Изолированный подграф на уровне trunk"}, "routing_subgraph_primary": {"text": "Изолированный подграф на уровне primary"}, "routing_subgraph_secondary": {"text": "Изолированный подграф на уровне secondary"}, "routing_subgraph_tertiary": {"text": "Изолированный подграф на уровне tertiary"}, "duplicate_point": {"text": "Точка-дубликат"}, "building_not_in_place": {"text": "Здание за пределами населенного пункта"}, "address_without_street": {"text": "Адрес без улицы"}, "address_street_not_found": {"text": "Адресная улица не найдена"}, "address_street_not_in_place": {"text": "Улица из адреса не связана с городом"}, "address_by_territory": {"text": "Здание нумеруется по территории"}, "address_street_not_routed": {"text": "Не-рутинговая улица"}, "street_not_in_place": {"text": "Улица за пределами города"} }, "jsonp": true, "offset_limit": true },{ "name": "Проверка параметров городов по Википедии", "url": "http://osm.alno.name/validators/cupivan_places?minlat={minlat}&minlon={minlon}&maxlat={maxlat}&maxlon={maxlon}&types={filtered_types}", "types": { "place": { "text": "Тип населенного пункта" }, "wikipedia": { "text": "Ссылка на википедию" }, "population": { "text": "Население" }, "province": { "text": "Область/край/республика" }, "district": { "text": "Район" }, "official_status": { "text": "Статус населенного пункта" }, "name": { "text": "Название населенного пункта" }, "old_name": { "text": "Прежнее название населенного пункта" }, "website": { "text": "Вебсайт" } }, "jsonp": true, "offset_limit": true }], errors: [{ name: "Роутинг", children: [{ name: "Изолированный подграф", type: "routing_subgraph" },{ name: "Изолированный подграф trunk", type: "routing_subgraph_trunk" },{ name: "Изолированный подграф primary", type: "routing_subgraph_primary" },{ name: "Изолированный подграф secondary", type: "routing_subgraph_secondary" },{ name: "Изолированный подграф tertiary", type: "routing_subgraph_tertiary" }] },{ name: "Адресация", children: [{ name: "Города", children: [{ name: "Без населения", type: "city_without_population" },{ name: "Без границы", type: "city_without_place_polygon" },{ name: "Без центра", type: "city_without_place_node" }] },{ name: "Улицы", children: [{ name: "За пределами города", type: "street_not_in_place" }] },{ name: "Здания", children: [{ name: "За пределами города", type: "building_not_in_place" },{ name: "Без улицы", type: "address_without_street" },{ name: "Улица не найдена", type: "address_street_not_found" },{ name: "Улица не связана с городом", type: "address_street_not_in_place" },{ name: "Здание нумеруется по территории", type: "address_by_territory" },{ name: "Улица не является рутинговой", type: "address_street_not_routed" }] },{ name: "Другие", children: [{ name: "Точка-дубликат", type: "duplicate_point" }] }] },{ name: "Населенные пункты", children: [{ name: "Тип", type: "place" },{ name: "Статус", type: "official_status" },{ name: "Название", type: "name" },{ name: "Старое название", type: "old_name" },{ name: "Регион", type: "region" },{ name: "Район", type: "district" },{ name: "Население", type: "population" },{ name: "Вебсайт", type: "website" },{ name: "Ссылка на википедию", type: "wikipedia" }] }], i18n: { errors: 'Ошибки', objects: 'Объекты', params: 'Параметры', error_info: 'Информация об ошибке', edit_in_potlatch: 'Редактировать в Potlatch', edit_in_josm: 'Редактировать в JOSM', created_at: 'Обнаружена', updated_at: 'Обновлена' }, dateFormat: 'YYYY-MM-DD', initialize: function() { this.layer = new OsmJs.Validators.LeafletLayer({sources: this.sources, i18n: this.i18n, dateFormat: this.dateFormat}); $('#validationerrors').validatorErrorsControl(this.layer, {errors: this.errors}); }, enable: function() { osm.map.addLayer(this.layer); }, disable: function() { osm.map.removeLayer(this.layer); } }
bsd-2-clause
HaiboZhu/openh264
codec/console/dec/src/h264dec.cpp
16244
/*! * \copy * Copyright (c) 2004-2013, Cisco Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * h264dec.cpp: Wels Decoder Console Implementation file */ #if defined (_WIN32) #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <tchar.h> #else #include <string.h> #endif #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #if defined (ANDROID_NDK) #include <android/log.h> #endif #include "codec_def.h" #include "codec_app_def.h" #include "codec_api.h" #include "read_config.h" #include "typedefs.h" #include "measure_time.h" #include "d3d9_utils.h" using namespace std; #if defined (WINDOWS_PHONE) double g_dDecTime = 0.0; float g_fDecFPS = 0.0; int g_iDecodedFrameNum = 0; #endif #if defined(ANDROID_NDK) #define LOG_TAG "welsdec" #define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define printf LOGI #define fprintf(a, ...) LOGI(__VA_ARGS__) #endif //using namespace WelsDec; //#define NO_DELAY_DECODING // For Demo interfaces test with no delay decoding void H264DecodeInstance (ISVCDecoder* pDecoder, const char* kpH264FileName, const char* kpOuputFileName, int32_t& iWidth, int32_t& iHeight, const char* pOptionFileName, const char* pLengthFileName) { FILE* pH264File = NULL; FILE* pYuvFile = NULL; FILE* pOptionFile = NULL; // Lenght input mode support FILE* fpTrack = NULL; if (pLengthFileName != NULL) { fpTrack = fopen (pLengthFileName, "rb"); if (fpTrack == NULL) printf ("Length file open ERROR!\n"); } int32_t pInfo[4]; unsigned long long uiTimeStamp = 0; int64_t iStart = 0, iEnd = 0, iTotal = 0; int32_t iSliceSize; int32_t iSliceIndex = 0; uint8_t* pBuf = NULL; uint8_t uiStartCode[4] = {0, 0, 0, 1}; uint8_t* pData[3] = {NULL}; uint8_t* pDst[3] = {NULL}; SBufferInfo sDstBufInfo; int32_t iBufPos = 0; int32_t iFileSize; int32_t i = 0; int32_t iLastWidth = 0, iLastHeight = 0; int32_t iFrameCount = 0; int32_t iEndOfStreamFlag = 0; int32_t iColorFormat = videoFormatInternal; //for coverage test purpose int32_t iErrorConMethod = (int32_t) ERROR_CON_SLICE_MV_COPY_CROSS_IDR_FREEZE_RES_CHANGE; pDecoder->SetOption (DECODER_OPTION_ERROR_CON_IDC, &iErrorConMethod); //~end for CUtils cOutputModule; double dElapsed = 0; if (pDecoder == NULL) return; if (kpH264FileName) { pH264File = fopen (kpH264FileName, "rb"); if (pH264File == NULL) { fprintf (stderr, "Can not open h264 source file, check its legal path related please..\n"); return; } fprintf (stderr, "H264 source file name: %s..\n", kpH264FileName); } else { fprintf (stderr, "Can not find any h264 bitstream file to read..\n"); fprintf (stderr, "----------------decoder return------------------------\n"); return; } if (kpOuputFileName) { pYuvFile = fopen (kpOuputFileName, "wb"); if (pYuvFile == NULL) { fprintf (stderr, "Can not open yuv file to output result of decoding..\n"); // any options //return; // can let decoder work in quiet mode, no writing any output } else fprintf (stderr, "Sequence output file name: %s..\n", kpOuputFileName); } else { fprintf (stderr, "Can not find any output file to write..\n"); // any options } if (pOptionFileName) { pOptionFile = fopen (pOptionFileName, "wb"); if (pOptionFile == NULL) { fprintf (stderr, "Can not open optional file for write..\n"); } else fprintf (stderr, "Extra optional file: %s..\n", pOptionFileName); } printf ("------------------------------------------------------\n"); fseek (pH264File, 0L, SEEK_END); iFileSize = (int32_t) ftell (pH264File); if (iFileSize <= 0) { fprintf (stderr, "Current Bit Stream File is too small, read error!!!!\n"); goto label_exit; } fseek (pH264File, 0L, SEEK_SET); pBuf = new uint8_t[iFileSize + 4]; if (pBuf == NULL) { fprintf (stderr, "new buffer failed!\n"); goto label_exit; } if (fread (pBuf, 1, iFileSize, pH264File) != (uint32_t)iFileSize) { fprintf (stderr, "Unable to read whole file\n"); goto label_exit; } memcpy (pBuf + iFileSize, &uiStartCode[0], 4); //confirmed_safe_unsafe_usage if (pDecoder->SetOption (DECODER_OPTION_DATAFORMAT, &iColorFormat)) { fprintf (stderr, "SetOption() failed, opt_id : %d ..\n", DECODER_OPTION_DATAFORMAT); goto label_exit; } while (true) { if (iBufPos >= iFileSize) { iEndOfStreamFlag = true; if (iEndOfStreamFlag) pDecoder->SetOption (DECODER_OPTION_END_OF_STREAM, (void*)&iEndOfStreamFlag); break; } // Read length from file if needed if (fpTrack) { if (fread (pInfo, 4, sizeof (int32_t), fpTrack) < 4) return; iSliceSize = static_cast<int32_t> (pInfo[2]); } else { for (i = 0; i < iFileSize; i++) { if ((pBuf[iBufPos + i] == 0 && pBuf[iBufPos + i + 1] == 0 && pBuf[iBufPos + i + 2] == 0 && pBuf[iBufPos + i + 3] == 1 && i > 0) || (pBuf[iBufPos + i] == 0 && pBuf[iBufPos + i + 1] == 0 && pBuf[iBufPos + i + 2] == 1 && i > 0)) { break; } } iSliceSize = i; } if (iSliceSize < 4) { //too small size, no effective data, ignore iBufPos += iSliceSize; continue; } //for coverage test purpose int32_t iOutputColorFormat; pDecoder->GetOption (DECODER_OPTION_DATAFORMAT, &iOutputColorFormat); int32_t iEndOfStreamFlag; pDecoder->GetOption (DECODER_OPTION_END_OF_STREAM, &iEndOfStreamFlag); int32_t iCurIdrPicId; pDecoder->GetOption (DECODER_OPTION_IDR_PIC_ID, &iCurIdrPicId); int32_t iFrameNum; pDecoder->GetOption (DECODER_OPTION_FRAME_NUM, &iFrameNum); int32_t bCurAuContainLtrMarkSeFlag; pDecoder->GetOption (DECODER_OPTION_LTR_MARKING_FLAG, &bCurAuContainLtrMarkSeFlag); int32_t iFrameNumOfAuMarkedLtr; pDecoder->GetOption (DECODER_OPTION_LTR_MARKED_FRAME_NUM, &iFrameNumOfAuMarkedLtr); int32_t iFeedbackVclNalInAu; pDecoder->GetOption (DECODER_OPTION_VCL_NAL, &iFeedbackVclNalInAu); int32_t iFeedbackTidInAu; pDecoder->GetOption (DECODER_OPTION_TEMPORAL_ID, &iFeedbackTidInAu); //~end for iStart = WelsTime(); pData[0] = NULL; pData[1] = NULL; pData[2] = NULL; uiTimeStamp ++; memset (&sDstBufInfo, 0, sizeof (SBufferInfo)); sDstBufInfo.uiInBsTimeStamp = uiTimeStamp; #ifndef NO_DELAY_DECODING pDecoder->DecodeFrameNoDelay (pBuf + iBufPos, iSliceSize, pData, &sDstBufInfo); #else pDecoder->DecodeFrame2 (pBuf + iBufPos, iSliceSize, pData, &sDstBufInfo); #endif if (sDstBufInfo.iBufferStatus == 1) { pDst[0] = pData[0]; pDst[1] = pData[1]; pDst[2] = pData[2]; } iEnd = WelsTime(); iTotal += iEnd - iStart; if (sDstBufInfo.iBufferStatus == 1) { cOutputModule.Process ((void**)pDst, &sDstBufInfo, pYuvFile); iWidth = sDstBufInfo.UsrData.sSystemBuffer.iWidth; iHeight = sDstBufInfo.UsrData.sSystemBuffer.iHeight; if (pOptionFile != NULL) { if (iWidth != iLastWidth && iHeight != iLastHeight) { fwrite (&iFrameCount, sizeof (iFrameCount), 1, pOptionFile); fwrite (&iWidth , sizeof (iWidth) , 1, pOptionFile); fwrite (&iHeight, sizeof (iHeight), 1, pOptionFile); iLastWidth = iWidth; iLastHeight = iHeight; } } ++ iFrameCount; } #ifdef NO_DELAY_DECODING iStart = WelsTime(); pData[0] = NULL; pData[1] = NULL; pData[2] = NULL; memset (&sDstBufInfo, 0, sizeof (SBufferInfo)); sDstBufInfo.uiInBsTimeStamp = uiTimeStamp; pDecoder->DecodeFrame2 (NULL, 0, pData, &sDstBufInfo); if (sDstBufInfo.iBufferStatus == 1) { pDst[0] = pData[0]; pDst[1] = pData[1]; pDst[2] = pData[2]; } iEnd = WelsTime(); iTotal += iEnd - iStart; if (sDstBufInfo.iBufferStatus == 1) { cOutputModule.Process ((void**)pDst, &sDstBufInfo, pYuvFile); iWidth = sDstBufInfo.UsrData.sSystemBuffer.iWidth; iHeight = sDstBufInfo.UsrData.sSystemBuffer.iHeight; if (pOptionFile != NULL) { if (iWidth != iLastWidth && iHeight != iLastHeight) { fwrite (&iFrameCount, sizeof (iFrameCount), 1, pOptionFile); fwrite (&iWidth , sizeof (iWidth) , 1, pOptionFile); fwrite (&iHeight, sizeof (iHeight), 1, pOptionFile); iLastWidth = iWidth; iLastHeight = iHeight; } } ++ iFrameCount; } #endif iBufPos += iSliceSize; ++ iSliceIndex; } if (fpTrack) { fclose (fpTrack); fpTrack = NULL; } dElapsed = iTotal / 1e6; fprintf (stderr, "-------------------------------------------------------\n"); fprintf (stderr, "iWidth:\t\t%d\nheight:\t\t%d\nFrames:\t\t%d\ndecode time:\t%f sec\nFPS:\t\t%f fps\n", iWidth, iHeight, iFrameCount, dElapsed, (iFrameCount * 1.0) / dElapsed); fprintf (stderr, "-------------------------------------------------------\n"); #if defined (WINDOWS_PHONE) g_dDecTime = dElapsed; g_fDecFPS = (iFrameCount * 1.0f) / (float) dElapsed; g_iDecodedFrameNum = iFrameCount; #endif // coverity scan uninitial label_exit: if (pBuf) { delete[] pBuf; pBuf = NULL; } if (pH264File) { fclose (pH264File); pH264File = NULL; } if (pYuvFile) { fclose (pYuvFile); pYuvFile = NULL; } if (pOptionFile) { fclose (pOptionFile); pOptionFile = NULL; } } #if (defined(ANDROID_NDK)||defined(APPLE_IOS) || defined (WINDOWS_PHONE)) int32_t DecMain (int32_t iArgC, char* pArgV[]) { #else int32_t main (int32_t iArgC, char* pArgV[]) { #endif ISVCDecoder* pDecoder = NULL; SDecodingParam sDecParam = {0}; string strInputFile (""), strOutputFile (""), strOptionFile (""), strLengthFile (""); int iLevelSetting = (int) WELS_LOG_WARNING; sDecParam.sVideoProperty.size = sizeof (sDecParam.sVideoProperty); if (iArgC < 2) { printf ("usage 1: h264dec.exe welsdec.cfg\n"); printf ("usage 2: h264dec.exe welsdec.264 out.yuv\n"); printf ("usage 3: h264dec.exe welsdec.264\n"); return 1; } else if (iArgC == 2) { if (strstr (pArgV[1], ".cfg")) { // read config file //confirmed_safe_unsafe_usage CReadConfig cReadCfg (pArgV[1]); string strTag[4]; string strReconFile (""); if (!cReadCfg.ExistFile()) { printf ("Specified file: %s not exist, maybe invalid path or parameter settting.\n", cReadCfg.GetFileName().c_str()); return 1; } while (!cReadCfg.EndOfFile()) { long nRd = cReadCfg.ReadLine (&strTag[0]); if (nRd > 0) { if (strTag[0].compare ("InputFile") == 0) { strInputFile = strTag[1]; } else if (strTag[0].compare ("OutputFile") == 0) { strOutputFile = strTag[1]; } else if (strTag[0].compare ("RestructionFile") == 0) { strReconFile = strTag[1]; int32_t iLen = (int32_t)strReconFile.length(); sDecParam.pFileNameRestructed = new char[iLen + 1]; if (sDecParam.pFileNameRestructed != NULL) { sDecParam.pFileNameRestructed[iLen] = 0; } strncpy (sDecParam.pFileNameRestructed, strReconFile.c_str(), iLen); //confirmed_safe_unsafe_usage } else if (strTag[0].compare ("TargetDQID") == 0) { sDecParam.uiTargetDqLayer = (uint8_t)atol (strTag[1].c_str()); } else if (strTag[0].compare ("OutColorFormat") == 0) { sDecParam.eOutputColorFormat = (EVideoFormatType) atoi (strTag[1].c_str()); } else if (strTag[0].compare ("ErrorConcealmentIdc") == 0) { sDecParam.eEcActiveIdc = (ERROR_CON_IDC)atol (strTag[1].c_str()); } else if (strTag[0].compare ("CPULoad") == 0) { sDecParam.uiCpuLoad = (uint32_t)atol (strTag[1].c_str()); } else if (strTag[0].compare ("VideoBitstreamType") == 0) { sDecParam.sVideoProperty.eVideoBsType = (VIDEO_BITSTREAM_TYPE)atol (strTag[1].c_str()); } } } if (strOutputFile.empty()) { printf ("No output file specified in configuration file.\n"); return 1; } } else if (strstr (pArgV[1], ".264")) { // no output dump yuv file, just try to render the decoded pictures //confirmed_safe_unsafe_usage strInputFile = pArgV[1]; sDecParam.eOutputColorFormat = videoFormatI420; sDecParam.uiTargetDqLayer = (uint8_t) - 1; sDecParam.eEcActiveIdc = ERROR_CON_SLICE_COPY; sDecParam.sVideoProperty.eVideoBsType = VIDEO_BITSTREAM_DEFAULT; } } else { //iArgC > 2 strInputFile = pArgV[1]; strOutputFile = pArgV[2]; sDecParam.eOutputColorFormat = videoFormatI420; sDecParam.uiTargetDqLayer = (uint8_t) - 1; sDecParam.eEcActiveIdc = ERROR_CON_SLICE_COPY; sDecParam.sVideoProperty.eVideoBsType = VIDEO_BITSTREAM_DEFAULT; if (iArgC > 3) { for (int i = 3; i < iArgC; i++) { char* cmd = pArgV[i]; if (!strcmp (cmd, "-options")) { if (i + 1 < iArgC) strOptionFile = pArgV[++i]; else { printf ("options file not specified.\n"); return 1; } } else if (!strcmp (cmd, "-trace")) { if (i + 1 < iArgC) iLevelSetting = atoi (pArgV[++i]); else { printf ("trace level not specified.\n"); return 1; } } else if (!strcmp (cmd, "-length")) { if (i + 1 < iArgC) strLengthFile = pArgV[++i]; else { printf ("lenght file not specified.\n"); return 1; } } } } if (strOutputFile.empty()) { printf ("No output file specified in configuration file.\n"); return 1; } } if (strInputFile.empty()) { printf ("No input file specified in configuration file.\n"); return 1; } if (WelsCreateDecoder (&pDecoder) || (NULL == pDecoder)) { printf ("Create Decoder failed.\n"); return 1; } if (iLevelSetting >= 0) { pDecoder->SetOption (DECODER_OPTION_TRACE_LEVEL, &iLevelSetting); } if (pDecoder->Initialize (&sDecParam)) { printf ("Decoder initialization failed.\n"); return 1; } int32_t iWidth = 0; int32_t iHeight = 0; H264DecodeInstance (pDecoder, strInputFile.c_str(), !strOutputFile.empty() ? strOutputFile.c_str() : NULL, iWidth, iHeight, (!strOptionFile.empty() ? strOptionFile.c_str() : NULL), (!strLengthFile.empty() ? strLengthFile.c_str() : NULL)); if (sDecParam.pFileNameRestructed != NULL) { delete []sDecParam.pFileNameRestructed; sDecParam.pFileNameRestructed = NULL; } if (pDecoder) { pDecoder->Uninitialize(); WelsDestroyDecoder (pDecoder); } return 0; }
bsd-2-clause
zhangjunfang/eclipse-dir
restlet/src/org/restlet/util/WrapperMap.java
6572
/** * Copyright 2005-2013 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.util; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Map wrapper. Modifiable map that delegates all methods to a wrapped map. This * allows an easy subclassing. * * @author Jerome Louvel * @see <a href="http://c2.com/cgi/wiki?DecoratorPattern">The decorator (aka * wrapper) pattern</a> * @see java.util.Collections * @see java.util.List */ public class WrapperMap<K, V> implements Map<K, V> { /** The delegate map. */ private final Map<K, V> delegate; /** * Constructor. */ public WrapperMap() { this.delegate = new ConcurrentHashMap<K, V>(); } /** * Constructor. * * @param delegate * The delegate list. */ public WrapperMap(Map<K, V> delegate) { this.delegate = delegate; } /** * Removes all mappings from this Map. */ public void clear() { getDelegate().clear(); } /** * Returns true if this map contains a mapping for the specified key. * * @param key * The key to look up. * @return True if this map contains a mapping for the specified key. */ public boolean containsKey(Object key) { return getDelegate().containsKey(key); } /** * Returns true if this map maps one or more keys to the specified value. * * @param value * The value to look up * @return True if this map maps one or more keys to the specified value. */ public boolean containsValue(Object value) { return getDelegate().containsValue(value); } /** * Returns a set view of the mappings contained in this map. * * @return A set view of the mappings contained in this map. */ public Set<Entry<K, V>> entrySet() { return getDelegate().entrySet(); } /** * Compares the specified object with this map for equality. * * @param o * Object to be compared for equality with this map. * @return True if the specified object is equal to this map. */ @Override public boolean equals(Object o) { return getDelegate().equals(o); } /** * Returns the value to which this map maps the specified key. * * @param key * Key whose associated value is to be returned. * @return The value to which this map maps the specified key, or null if * the map contains no mapping for this key. */ public V get(Object key) { return getDelegate().get(key); } /** * Returns the delegate list. * * @return The delegate list. */ protected Map<K, V> getDelegate() { return this.delegate; } /** * Returns the hash code value for this map. * * @return The hash code value for this map. */ @Override public int hashCode() { return getDelegate().hashCode(); } /** * Returns true if this map contains no key-value mappings. * * @return True if this map contains no key-value mappings. */ public boolean isEmpty() { return getDelegate().isEmpty(); } /** * Returns a set view of the keys contained in this map. * * @return A set view of the keys contained in this map. */ public Set<K> keySet() { return getDelegate().keySet(); } /** * Associates the specified value with the specified key in this map * (optional operation). * * @param key * Key with which the specified value is to be associated. * @param value * Value to be associated with the specified key. * @return The previous value associated with specified key, or null if * there was no mapping for key. A null return can also indicate * that the map previously associated null with the specified key, * if the implementation supports null values. */ public V put(K key, V value) { return getDelegate().put(key, value); } /** * Copies all of the mappings from the specified map to this map (optional * operation). * * @param t * Mappings to be stored in this map. */ public void putAll(Map<? extends K, ? extends V> t) { getDelegate().putAll(t); } /** * Removes the mapping for this key from this map if it is present (optional * operation). * * @param key * Key whose mapping is to be removed from the map. * @return The previous value associated with specified key, or null if * there was no mapping for key. */ public V remove(Object key) { return getDelegate().remove(key); } /** * Returns the number of key-value mappings in this map. * * @return The number of key-value mappings in this map. */ public int size() { return getDelegate().size(); } /** * Returns a collection view of the values contained in this map. * * @return A collection view of the values contained in this map. */ public Collection<V> values() { return getDelegate().values(); } }
bsd-2-clause
Treeeater/WebPermission
src_chrome_Release_obj_global_intermediate_webcore/bindings/V8WorkerContext.cpp
30719
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include "V8WorkerContext.h" #if ENABLE(WORKERS) #include "EventListener.h" #include "ExceptionCode.h" #include "RuntimeEnabledFeatures.h" #include "V8AbstractEventListener.h" #include "V8ArrayBuffer.h" #include "V8Binding.h" #include "V8BindingMacros.h" #include "V8BindingState.h" #include "V8DOMFileSystemSync.h" #include "V8DOMURL.h" #include "V8DOMWrapper.h" #include "V8DataView.h" #include "V8Database.h" #include "V8DatabaseCallback.h" #include "V8DatabaseSync.h" #include "V8EntryCallback.h" #include "V8EntrySync.h" #include "V8ErrorCallback.h" #include "V8Event.h" #include "V8EventListenerList.h" #include "V8EventSource.h" #include "V8FileError.h" #include "V8FileException.h" #include "V8FileReader.h" #include "V8FileReaderSync.h" #include "V8FileSystemCallback.h" #include "V8Float32Array.h" #include "V8Float64Array.h" #include "V8Int16Array.h" #include "V8Int32Array.h" #include "V8Int8Array.h" #include "V8IsolatedContext.h" #include "V8MessageChannel.h" #include "V8MessageEvent.h" #include "V8NotificationCenter.h" #include "V8Proxy.h" #include "V8Uint16Array.h" #include "V8Uint32Array.h" #include "V8Uint8Array.h" #include "V8WebKitBlobBuilder.h" #include "V8WebKitFlags.h" #include "V8WebSocket.h" #include "V8WorkerContextErrorHandler.h" #include "V8WorkerLocation.h" #include "V8WorkerNavigator.h" #include "V8XMLHttpRequest.h" #include <wtf/GetPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> namespace WebCore { WrapperTypeInfo V8WorkerContext::info = { V8WorkerContext::GetTemplate, V8WorkerContext::derefObject, 0, 0 }; namespace WorkerContextInternal { template <typename T> void V8_USE(T) { } static v8::Handle<v8::Value> selfAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.self._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); return toV8(imp->self()); } static v8::Handle<v8::Value> locationAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.location._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); RefPtr<WorkerLocation> result = imp->location(); v8::Handle<v8::Value> wrapper = result.get() ? getDOMObjectMap().get(result.get()) : v8::Handle<v8::Value>(); if (wrapper.IsEmpty()) { wrapper = toV8(result.get()); if (!wrapper.IsEmpty()) V8DOMWrapper::setNamedHiddenReference(info.Holder(), "location", wrapper); } return wrapper; } static v8::Handle<v8::Value> onerrorAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.onerror._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); return imp->onerror() ? v8::Handle<v8::Value>(static_cast<V8AbstractEventListener*>(imp->onerror())->getListenerObject(imp->scriptExecutionContext())) : v8::Handle<v8::Value>(v8::Null()); } static void onerrorAttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.onerror._set"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); transferHiddenDependency(info.Holder(), imp->onerror(), value, V8WorkerContext::eventListenerCacheIndex); imp->setOnerror(V8EventListenerList::findOrCreateWrapper<V8WorkerContextErrorHandler>(value, true)); return; } static v8::Handle<v8::Value> navigatorAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.navigator._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); RefPtr<WorkerNavigator> result = imp->navigator(); v8::Handle<v8::Value> wrapper = result.get() ? getDOMObjectMap().get(result.get()) : v8::Handle<v8::Value>(); if (wrapper.IsEmpty()) { wrapper = toV8(result.get()); if (!wrapper.IsEmpty()) V8DOMWrapper::setNamedHiddenReference(info.Holder(), "navigator", wrapper); } return wrapper; } static v8::Handle<v8::Value> webkitNotificationsAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.webkitNotifications._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); RefPtr<NotificationCenter> result = imp->webkitNotifications(); v8::Handle<v8::Value> wrapper = result.get() ? getDOMObjectMap().get(result.get()) : v8::Handle<v8::Value>(); if (wrapper.IsEmpty()) { wrapper = toV8(result.get()); if (!wrapper.IsEmpty()) V8DOMWrapper::setNamedHiddenReference(info.Holder(), "webkitNotifications", wrapper); } return wrapper; } #if ENABLE(BLOB) static v8::Handle<v8::Value> webkitURLAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.webkitURL._get"); WorkerContext* imp = V8WorkerContext::toNative(info.Holder()); RefPtr<DOMURL> result = imp->webkitURL(); v8::Handle<v8::Value> wrapper = result.get() ? getDOMObjectMap().get(result.get()) : v8::Handle<v8::Value>(); if (wrapper.IsEmpty()) { wrapper = toV8(result.get()); if (!wrapper.IsEmpty()) V8DOMWrapper::setNamedHiddenReference(info.Holder(), "webkitURL", wrapper); } return wrapper; } #endif // ENABLE(BLOB) static v8::Handle<v8::Value> WorkerContextConstructorGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.WorkerContext.constructors._get"); v8::Handle<v8::Value> data = info.Data(); ASSERT(data->IsExternal() || data->IsNumber()); WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data); return V8DOMWrapper::getConstructor(type, V8WorkerContext::toNative(info.Holder())); } static v8::Handle<v8::Value> closeCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.close"); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); imp->close(); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> openDatabaseCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.openDatabase"); if (args.Length() < 4) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, version, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, displayName, MAYBE_MISSING_PARAMETER(args, 2, MissingIsUndefined)); EXCEPTION_BLOCK(unsigned, estimatedSize, toUInt32(MAYBE_MISSING_PARAMETER(args, 3, MissingIsUndefined))); RefPtr<DatabaseCallback> creationCallback; if (args.Length() > 4 && !args[4]->IsNull() && !args[4]->IsUndefined()) { if (!args[4]->IsObject()) return throwError(TYPE_MISMATCH_ERR); creationCallback = V8DatabaseCallback::create(args[4], getScriptExecutionContext()); } RefPtr<Database> result = imp->openDatabase(name, version, displayName, estimatedSize, creationCallback, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> openDatabaseSyncCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.openDatabaseSync"); if (args.Length() < 4) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, version, MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, displayName, MAYBE_MISSING_PARAMETER(args, 2, MissingIsUndefined)); EXCEPTION_BLOCK(unsigned, estimatedSize, toUInt32(MAYBE_MISSING_PARAMETER(args, 3, MissingIsUndefined))); RefPtr<DatabaseCallback> creationCallback; if (args.Length() > 4 && !args[4]->IsNull() && !args[4]->IsUndefined()) { if (!args[4]->IsObject()) return throwError(TYPE_MISMATCH_ERR); creationCallback = V8DatabaseCallback::create(args[4], getScriptExecutionContext()); } RefPtr<DatabaseSync> result = imp->openDatabaseSync(name, version, displayName, estimatedSize, creationCallback, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> clearTimeoutCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.clearTimeout"); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); EXCEPTION_BLOCK(int, handle, toInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); imp->clearTimeout(handle); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> clearIntervalCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.clearInterval"); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); EXCEPTION_BLOCK(int, handle, toInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); imp->clearInterval(handle); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> addEventListenerCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.addEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOrCreate); if (listener) { V8WorkerContext::toNative(args.Holder())->addEventListener(v8ValueToAtomicWebCoreString(args[0]), listener, args[2]->BooleanValue()); createHiddenDependency(args.Holder(), args[1], V8WorkerContext::eventListenerCacheIndex); } return v8::Undefined(); } static v8::Handle<v8::Value> removeEventListenerCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.removeEventListener()"); RefPtr<EventListener> listener = V8DOMWrapper::getEventListener(args[1], false, ListenerFindOnly); if (listener) { V8WorkerContext::toNative(args.Holder())->removeEventListener(v8ValueToAtomicWebCoreString(args[0]), listener.get(), args[2]->BooleanValue()); removeHiddenDependency(args.Holder(), args[1], V8WorkerContext::eventListenerCacheIndex); } return v8::Undefined(); } static v8::Handle<v8::Value> dispatchEventCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.dispatchEvent"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); ExceptionCode ec = 0; { EXCEPTION_BLOCK(Event*, evt, V8Event::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)) ? V8Event::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))) : 0); bool result = imp->dispatchEvent(evt, ec); if (UNLIKELY(ec)) goto fail; return v8Boolean(result); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> webkitRequestFileSystemCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.webkitRequestFileSystem"); if (args.Length() < 2) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); EXCEPTION_BLOCK(int, type, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); EXCEPTION_BLOCK(long long, size, toInt64(MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined))); RefPtr<FileSystemCallback> successCallback; if (args.Length() > 2 && !args[2]->IsNull() && !args[2]->IsUndefined()) { if (!args[2]->IsObject()) return throwError(TYPE_MISMATCH_ERR); successCallback = V8FileSystemCallback::create(args[2], getScriptExecutionContext()); } RefPtr<ErrorCallback> errorCallback; if (args.Length() > 3 && !args[3]->IsNull() && !args[3]->IsUndefined()) { if (!args[3]->IsObject()) return throwError(TYPE_MISMATCH_ERR); errorCallback = V8ErrorCallback::create(args[3], getScriptExecutionContext()); } imp->webkitRequestFileSystem(type, size, successCallback, errorCallback); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> webkitRequestFileSystemSyncCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.webkitRequestFileSystemSync"); if (args.Length() < 2) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); ExceptionCode ec = 0; { EXCEPTION_BLOCK(int, type, toUInt32(MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined))); EXCEPTION_BLOCK(long long, size, toInt64(MAYBE_MISSING_PARAMETER(args, 1, MissingIsUndefined))); RefPtr<DOMFileSystemSync> result = imp->webkitRequestFileSystemSync(type, size, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> webkitResolveLocalFileSystemURLCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.webkitResolveLocalFileSystemURL"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, url, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); RefPtr<EntryCallback> successCallback; if (args.Length() > 1 && !args[1]->IsNull() && !args[1]->IsUndefined()) { if (!args[1]->IsObject()) return throwError(TYPE_MISMATCH_ERR); successCallback = V8EntryCallback::create(args[1], getScriptExecutionContext()); } RefPtr<ErrorCallback> errorCallback; if (args.Length() > 2 && !args[2]->IsNull() && !args[2]->IsUndefined()) { if (!args[2]->IsObject()) return throwError(TYPE_MISMATCH_ERR); errorCallback = V8ErrorCallback::create(args[2], getScriptExecutionContext()); } imp->webkitResolveLocalFileSystemURL(url, successCallback, errorCallback); return v8::Handle<v8::Value>(); } static v8::Handle<v8::Value> webkitResolveLocalFileSystemSyncURLCallback(const v8::Arguments& args) { INC_STATS("DOM.WorkerContext.webkitResolveLocalFileSystemSyncURL"); if (args.Length() < 1) return throwError("Not enough arguments", V8Proxy::TypeError); WorkerContext* imp = V8WorkerContext::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, url, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); RefPtr<EntrySync> result = imp->webkitResolveLocalFileSystemSyncURL(url, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release()); } fail: V8Proxy::setDOMException(ec); return v8::Handle<v8::Value>(); } } // namespace WorkerContextInternal static const BatchedAttribute WorkerContextAttrs[] = { // Attribute 'self' (Type: 'attribute' ExtAttr: 'Replaceable') {"self", WorkerContextInternal::selfAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::ReadOnly), 0 /* on instance */}, // Attribute 'location' (Type: 'attribute' ExtAttr: 'Replaceable') {"location", WorkerContextInternal::locationAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::ReadOnly), 0 /* on instance */}, // Attribute 'onerror' (Type: 'attribute' ExtAttr: '') {"onerror", WorkerContextInternal::onerrorAttrGetter, WorkerContextInternal::onerrorAttrSetter, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'navigator' (Type: 'attribute' ExtAttr: 'Replaceable') {"navigator", WorkerContextInternal::navigatorAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None | v8::ReadOnly), 0 /* on instance */}, // Attribute 'MessageEvent' (Type: 'attribute' ExtAttr: '') {"MessageEvent", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8MessageEvent::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'WorkerLocation' (Type: 'attribute' ExtAttr: '') {"WorkerLocation", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8WorkerLocation::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'MessageChannel' (Type: 'attribute' ExtAttr: 'JSCCustomGetter') {"MessageChannel", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8MessageChannel::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'EventSource' (Type: 'attribute' ExtAttr: 'JSCCustomGetter') {"EventSource", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8EventSource::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'XMLHttpRequest' (Type: 'attribute' ExtAttr: 'JSCCustomGetter') {"XMLHttpRequest", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8XMLHttpRequest::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'WebKitBlobBuilder' (Type: 'attribute' ExtAttr: '') {"WebKitBlobBuilder", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8WebKitBlobBuilder::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'FileReader' (Type: 'attribute' ExtAttr: '') {"FileReader", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8FileReader::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'FileReaderSync' (Type: 'attribute' ExtAttr: '') {"FileReaderSync", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8FileReaderSync::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, #if ENABLE(BLOB) // Attribute 'webkitURL' (Type: 'readonly attribute' ExtAttr: 'Conditional') {"webkitURL", WorkerContextInternal::webkitURLAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, #endif // ENABLE(BLOB) // Attribute 'ArrayBuffer' (Type: 'attribute' ExtAttr: '') {"ArrayBuffer", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8ArrayBuffer::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Int8Array' (Type: 'attribute' ExtAttr: '') {"Int8Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Int8Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Uint8Array' (Type: 'attribute' ExtAttr: '') {"Uint8Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Uint8Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Int16Array' (Type: 'attribute' ExtAttr: '') {"Int16Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Int16Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Uint16Array' (Type: 'attribute' ExtAttr: '') {"Uint16Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Uint16Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Int32Array' (Type: 'attribute' ExtAttr: '') {"Int32Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Int32Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Uint32Array' (Type: 'attribute' ExtAttr: '') {"Uint32Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Uint32Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Float32Array' (Type: 'attribute' ExtAttr: '') {"Float32Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Float32Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'Float64Array' (Type: 'attribute' ExtAttr: '') {"Float64Array", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8Float64Array::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, // Attribute 'DataView' (Type: 'attribute' ExtAttr: '') {"DataView", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8DataView::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}, }; static const BatchedCallback WorkerContextCallbacks[] = { {"close", WorkerContextInternal::closeCallback}, {"importScripts", V8WorkerContext::importScriptsCallback}, {"setTimeout", V8WorkerContext::setTimeoutCallback}, {"clearTimeout", WorkerContextInternal::clearTimeoutCallback}, {"setInterval", V8WorkerContext::setIntervalCallback}, {"clearInterval", WorkerContextInternal::clearIntervalCallback}, {"addEventListener", WorkerContextInternal::addEventListenerCallback}, {"removeEventListener", WorkerContextInternal::removeEventListenerCallback}, }; static const BatchedConstant WorkerContextConsts[] = { {"TEMPORARY", static_cast<signed int>(0)}, {"PERSISTENT", static_cast<signed int>(1)}, }; COMPILE_ASSERT(0 == WorkerContext::TEMPORARY, WorkerContextEnumTEMPORARYIsWrongUseDontCheckEnums); COMPILE_ASSERT(1 == WorkerContext::PERSISTENT, WorkerContextEnumPERSISTENTIsWrongUseDontCheckEnums); static v8::Persistent<v8::FunctionTemplate> ConfigureV8WorkerContextTemplate(v8::Persistent<v8::FunctionTemplate> desc) { desc->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature = configureTemplate(desc, "WorkerContext", v8::Persistent<v8::FunctionTemplate>(), V8WorkerContext::internalFieldCount, WorkerContextAttrs, WTF_ARRAY_LENGTH(WorkerContextAttrs), WorkerContextCallbacks, WTF_ARRAY_LENGTH(WorkerContextCallbacks)); v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate(); v8::Local<v8::ObjectTemplate> proto = desc->PrototypeTemplate(); if (RuntimeEnabledFeatures::webkitNotificationsEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'webkitNotifications' (Type: 'readonly attribute' ExtAttr: 'EnabledAtRuntime') {"webkitNotifications", WorkerContextInternal::webkitNotificationsAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } if (RuntimeEnabledFeatures::webSocketEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'WebSocket' (Type: 'attribute' ExtAttr: 'JSCCustomGetter EnabledAtRuntime') {"WebSocket", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8WebSocket::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } if (RuntimeEnabledFeatures::fileSystemEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'WebKitFlags' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime') {"WebKitFlags", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8WebKitFlags::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } if (RuntimeEnabledFeatures::fileSystemEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'FileError' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime') {"FileError", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8FileError::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } if (RuntimeEnabledFeatures::fileSystemEnabled()) { static const BatchedAttribute attrData =\ // Attribute 'FileException' (Type: 'attribute' ExtAttr: 'EnabledAtRuntime') {"FileException", WorkerContextInternal::WorkerContextConstructorGetter, 0, &V8FileException::info, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::ReadOnly), 0 /* on instance */}; configureAttribute(instance, proto, attrData); } if (RuntimeEnabledFeatures::openDatabaseEnabled()) proto->Set(v8::String::New("openDatabase"), v8::FunctionTemplate::New(WorkerContextInternal::openDatabaseCallback, v8::Handle<v8::Value>(), defaultSignature)); if (RuntimeEnabledFeatures::openDatabaseSyncEnabled()) proto->Set(v8::String::New("openDatabaseSync"), v8::FunctionTemplate::New(WorkerContextInternal::openDatabaseSyncCallback, v8::Handle<v8::Value>(), defaultSignature)); // Custom Signature 'dispatchEvent' const int dispatchEventArgc = 1; v8::Handle<v8::FunctionTemplate> dispatchEventArgv[dispatchEventArgc] = { V8Event::GetRawTemplate() }; v8::Handle<v8::Signature> dispatchEventSignature = v8::Signature::New(desc, dispatchEventArgc, dispatchEventArgv); proto->Set(v8::String::New("dispatchEvent"), v8::FunctionTemplate::New(WorkerContextInternal::dispatchEventCallback, v8::Handle<v8::Value>(), dispatchEventSignature)); if (RuntimeEnabledFeatures::fileSystemEnabled()) proto->Set(v8::String::New("webkitRequestFileSystem"), v8::FunctionTemplate::New(WorkerContextInternal::webkitRequestFileSystemCallback, v8::Handle<v8::Value>(), defaultSignature)); if (RuntimeEnabledFeatures::fileSystemEnabled()) proto->Set(v8::String::New("webkitRequestFileSystemSync"), v8::FunctionTemplate::New(WorkerContextInternal::webkitRequestFileSystemSyncCallback, v8::Handle<v8::Value>(), defaultSignature)); if (RuntimeEnabledFeatures::fileSystemEnabled()) proto->Set(v8::String::New("webkitResolveLocalFileSystemURL"), v8::FunctionTemplate::New(WorkerContextInternal::webkitResolveLocalFileSystemURLCallback, v8::Handle<v8::Value>(), defaultSignature)); if (RuntimeEnabledFeatures::fileSystemEnabled()) proto->Set(v8::String::New("webkitResolveLocalFileSystemSyncURL"), v8::FunctionTemplate::New(WorkerContextInternal::webkitResolveLocalFileSystemSyncURLCallback, v8::Handle<v8::Value>(), defaultSignature)); batchConfigureConstants(desc, proto, WorkerContextConsts, WTF_ARRAY_LENGTH(WorkerContextConsts)); // Custom toString template desc->Set(getToStringName(), getToStringTemplate()); return desc; } v8::Persistent<v8::FunctionTemplate> V8WorkerContext::GetRawTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } v8::Persistent<v8::FunctionTemplate> V8WorkerContext::GetTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info); if (result != data->templateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = ConfigureV8WorkerContextTemplate(GetRawTemplate()); data->templateMap().add(&info, templ); return templ; } bool V8WorkerContext::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } v8::Handle<v8::Object> V8WorkerContext::wrapSlow(WorkerContext* impl) { v8::Handle<v8::Object> wrapper; V8Proxy* proxy = 0; wrapper = V8DOMWrapper::instantiateV8Object(proxy, &info, impl); if (wrapper.IsEmpty()) return wrapper; impl->ref(); v8::Persistent<v8::Object> wrapperHandle = v8::Persistent<v8::Object>::New(wrapper); if (!hasDependentLifetime) wrapperHandle.MarkIndependent(); getDOMObjectMap().set(impl, wrapperHandle); return wrapper; } void V8WorkerContext::derefObject(void* object) { static_cast<WorkerContext*>(object)->deref(); } } // namespace WebCore #endif // ENABLE(WORKERS)
bsd-2-clause
johnmay/efficient-bits
impl-conversion/src/main/scala/BlogExamples.scala
2676
import org.RDKit._ import org.openscience.cdk.exception.InvalidSmilesException import org.openscience.cdk.fingerprint.{PubchemFingerprinter, CircularFingerprinter} import org.openscience.cdk.fingerprint.CircularFingerprinter.CLASS_ECFP4 import org.openscience.cdk.inchi.InChIGeneratorFactory import org.openscience.cdk.interfaces.IAtomContainer import org.openscience.cdk.silent.{AtomContainer, SilentChemObjectBuilder} import org.openscience.cdk.smiles.{SmilesGenerator, SmilesParser} import org.rdkit.RDKit import uk.ac.cam.ch.wwmm.opsin.NameToStructure object BlogExamples extends App { val bldr = SilentChemObjectBuilder.getInstance val sp = new SmilesParser(bldr) val igf = InChIGeneratorFactory.getInstance RDKit.activate() println(unismi("caffeine")) println(unismi("CN1C=NC2=C1C(=O)N(C)C(=O)N2C")) println(unismi("InChI=1S/C8H10N4O2/c1-10-4-9-6-5(10)7(13)12(3)8(14)11(6)2/h4H,1-3H3")) println(unismi("1S/C8H10N4O2/c1-10-4-9-6-5(10)7(13)12(3)8(14)11(6)2/h4H,1-3H3")) val fp1 = new CircularFingerprinter(CLASS_ECFP4).getCountFingerprint("porphyrin") println(unismi("(R)-butan-2-ol")) val fp2 = new ExplicitBitVect(512) RDKFuncs.getAvalonFP("caffeine", fp2) val caffeine : RWMol = "caffeine" new PubchemFingerprinter(bldr).getBitFingerprint(caffeine) // String -> CDK,RDkit Structures implicit def autoParseRDKit(str: String): RWMol = cdk2rdkit(autoParseCDK(str)) implicit def autoParseCDK(str: String): IAtomContainer = { if (str.startsWith("InChI=")) { inchipar(str) } else if (str.startsWith("1S/")) { inchipar("InChI=" + str) } else { try { cdksmipar(str) } catch { case _: InvalidSmilesException => nompar(str) } } } // CDK <-> RDKit implicit def cdk2rdkit(ac : IAtomContainer) : RWMol = rdsmipar(SmilesGenerator.isomeric.create(ac)) implicit def rdkit2cdk(romol : RWMol) : IAtomContainer = cdksmipar(RDKFuncs.getCanonSmiles(romol)) // String -> Structure def inchipar(inchi: String) = igf.getInChIToStructure(inchi, bldr).getAtomContainer def cdksmipar(smi: String) = sp.parseSmiles(smi) def nompar(nom: String) = cdksmipar(NameToStructure.getInstance.parseToSmiles(nom)) def rdsmipar(smi: String) = RWMol.MolFromSmiles(smi) // Structure -> String def cdksmi(ac: IAtomContainer) = SmilesGenerator.isomeric().create(ac) def rdsmi(romol: ROMol) = RDKFuncs.getCanonSmiles(romol) def cansmi(ac: IAtomContainer) = SmilesGenerator.unique().create(ac) // uses InChI to canonicalise the SMILES (O'Boyle N, 2012) def unismi(ac: IAtomContainer) = SmilesGenerator.absolute().create(ac) }
bsd-2-clause
ASMlover/study
3rdparty/boost/include/boost/asio/detail/win_iocp_socket_service_base.hpp
23493
// // detail/win_iocp_socket_service_base.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP #define BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_IOCP) #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/socket_base.hpp> #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/buffer_sequence_adapter.hpp> #include <boost/asio/detail/fenced_block.hpp> #include <boost/asio/detail/handler_alloc_helpers.hpp> #include <boost/asio/detail/handler_invoke_helpers.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/detail/mutex.hpp> #include <boost/asio/detail/operation.hpp> #include <boost/asio/detail/reactor_op.hpp> #include <boost/asio/detail/select_reactor.hpp> #include <boost/asio/detail/socket_holder.hpp> #include <boost/asio/detail/socket_ops.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/win_iocp_io_context.hpp> #include <boost/asio/detail/win_iocp_null_buffers_op.hpp> #include <boost/asio/detail/win_iocp_socket_connect_op.hpp> #include <boost/asio/detail/win_iocp_socket_send_op.hpp> #include <boost/asio/detail/win_iocp_socket_recv_op.hpp> #include <boost/asio/detail/win_iocp_socket_recvmsg_op.hpp> #include <boost/asio/detail/win_iocp_wait_op.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { class win_iocp_socket_service_base { public: // The implementation type of the socket. struct base_implementation_type { // The native socket representation. socket_type socket_; // The current state of the socket. socket_ops::state_type state_; // We use a shared pointer as a cancellation token here to work around the // broken Windows support for cancellation. MSDN says that when you call // closesocket any outstanding WSARecv or WSASend operations will complete // with the error ERROR_OPERATION_ABORTED. In practice they complete with // ERROR_NETNAME_DELETED, which means you can't tell the difference between // a local cancellation and the socket being hard-closed by the peer. socket_ops::shared_cancel_token_type cancel_token_; // Per-descriptor data used by the reactor. select_reactor::per_descriptor_data reactor_data_; #if defined(BOOST_ASIO_ENABLE_CANCELIO) // The ID of the thread from which it is safe to cancel asynchronous // operations. 0 means no asynchronous operations have been started yet. // ~0 means asynchronous operations have been started from more than one // thread, and cancellation is not supported for the socket. DWORD safe_cancellation_thread_id_; #endif // defined(BOOST_ASIO_ENABLE_CANCELIO) // Pointers to adjacent socket implementations in linked list. base_implementation_type* next_; base_implementation_type* prev_; }; // Constructor. BOOST_ASIO_DECL win_iocp_socket_service_base(execution_context& context); // Destroy all user-defined handler objects owned by the service. BOOST_ASIO_DECL void base_shutdown(); // Construct a new socket implementation. BOOST_ASIO_DECL void construct(base_implementation_type& impl); // Move-construct a new socket implementation. BOOST_ASIO_DECL void base_move_construct(base_implementation_type& impl, base_implementation_type& other_impl) BOOST_ASIO_NOEXCEPT; // Move-assign from another socket implementation. BOOST_ASIO_DECL void base_move_assign(base_implementation_type& impl, win_iocp_socket_service_base& other_service, base_implementation_type& other_impl); // Destroy a socket implementation. BOOST_ASIO_DECL void destroy(base_implementation_type& impl); // Determine whether the socket is open. bool is_open(const base_implementation_type& impl) const { return impl.socket_ != invalid_socket; } // Destroy a socket implementation. BOOST_ASIO_DECL boost::system::error_code close( base_implementation_type& impl, boost::system::error_code& ec); // Release ownership of the socket. BOOST_ASIO_DECL socket_type release( base_implementation_type& impl, boost::system::error_code& ec); // Cancel all operations associated with the socket. BOOST_ASIO_DECL boost::system::error_code cancel( base_implementation_type& impl, boost::system::error_code& ec); // Determine whether the socket is at the out-of-band data mark. bool at_mark(const base_implementation_type& impl, boost::system::error_code& ec) const { return socket_ops::sockatmark(impl.socket_, ec); } // Determine the number of bytes available for reading. std::size_t available(const base_implementation_type& impl, boost::system::error_code& ec) const { return socket_ops::available(impl.socket_, ec); } // Place the socket into the state where it will listen for new connections. boost::system::error_code listen(base_implementation_type& impl, int backlog, boost::system::error_code& ec) { socket_ops::listen(impl.socket_, backlog, ec); return ec; } // Perform an IO control command on the socket. template <typename IO_Control_Command> boost::system::error_code io_control(base_implementation_type& impl, IO_Control_Command& command, boost::system::error_code& ec) { socket_ops::ioctl(impl.socket_, impl.state_, command.name(), static_cast<ioctl_arg_type*>(command.data()), ec); return ec; } // Gets the non-blocking mode of the socket. bool non_blocking(const base_implementation_type& impl) const { return (impl.state_ & socket_ops::user_set_non_blocking) != 0; } // Sets the non-blocking mode of the socket. boost::system::error_code non_blocking(base_implementation_type& impl, bool mode, boost::system::error_code& ec) { socket_ops::set_user_non_blocking(impl.socket_, impl.state_, mode, ec); return ec; } // Gets the non-blocking mode of the native socket implementation. bool native_non_blocking(const base_implementation_type& impl) const { return (impl.state_ & socket_ops::internal_non_blocking) != 0; } // Sets the non-blocking mode of the native socket implementation. boost::system::error_code native_non_blocking(base_implementation_type& impl, bool mode, boost::system::error_code& ec) { socket_ops::set_internal_non_blocking(impl.socket_, impl.state_, mode, ec); return ec; } // Wait for the socket to become ready to read, ready to write, or to have // pending error conditions. boost::system::error_code wait(base_implementation_type& impl, socket_base::wait_type w, boost::system::error_code& ec) { switch (w) { case socket_base::wait_read: socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); break; case socket_base::wait_write: socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); break; case socket_base::wait_error: socket_ops::poll_error(impl.socket_, impl.state_, -1, ec); break; default: ec = boost::asio::error::invalid_argument; break; } return ec; } // Asynchronously wait for the socket to become ready to read, ready to // write, or to have pending error conditions. template <typename Handler, typename IoExecutor> void async_wait(base_implementation_type& impl, socket_base::wait_type w, Handler& handler, const IoExecutor& io_ex) { bool is_continuation = boost_asio_handler_cont_helpers::is_continuation(handler); // Allocate and construct an operation to wrap the handler. typedef win_iocp_wait_op<Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_wait")); switch (w) { case socket_base::wait_read: start_null_buffers_receive_op(impl, 0, p.p); break; case socket_base::wait_write: start_reactor_op(impl, select_reactor::write_op, p.p); break; case socket_base::wait_error: start_reactor_op(impl, select_reactor::except_op, p.p); break; default: p.p->ec_ = boost::asio::error::invalid_argument; iocp_service_.post_immediate_completion(p.p, is_continuation); break; } p.v = p.p = 0; } // Send the given data to the peer. Returns the number of bytes sent. template <typename ConstBufferSequence> size_t send(base_implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { buffer_sequence_adapter<boost::asio::const_buffer, ConstBufferSequence> bufs(buffers); return socket_ops::sync_send(impl.socket_, impl.state_, bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); } // Wait until data can be sent without blocking. size_t send(base_implementation_type& impl, const null_buffers&, socket_base::message_flags, boost::system::error_code& ec) { // Wait for socket to become ready. socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); return 0; } // Start an asynchronous send. The data being sent must be valid for the // lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename Handler, typename IoExecutor> void async_send(base_implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_socket_send_op< ConstBufferSequence, Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, buffers, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_send")); buffer_sequence_adapter<boost::asio::const_buffer, ConstBufferSequence> bufs(buffers); start_send_op(impl, bufs.buffers(), bufs.count(), flags, (impl.state_ & socket_ops::stream_oriented) != 0 && bufs.all_empty(), p.p); p.v = p.p = 0; } // Start an asynchronous wait until data can be sent without blocking. template <typename Handler, typename IoExecutor> void async_send(base_implementation_type& impl, const null_buffers&, socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_null_buffers_op<Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_send(null_buffers)")); start_reactor_op(impl, select_reactor::write_op, p.p); p.v = p.p = 0; } // Receive some data from the peer. Returns the number of bytes received. template <typename MutableBufferSequence> size_t receive(base_implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { buffer_sequence_adapter<boost::asio::mutable_buffer, MutableBufferSequence> bufs(buffers); return socket_ops::sync_recv(impl.socket_, impl.state_, bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); } // Wait until data can be received without blocking. size_t receive(base_implementation_type& impl, const null_buffers&, socket_base::message_flags, boost::system::error_code& ec) { // Wait for socket to become ready. socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); return 0; } // Start an asynchronous receive. The buffer for the data being received // must be valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename Handler, typename IoExecutor> void async_receive(base_implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_socket_recv_op< MutableBufferSequence, Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.state_, impl.cancel_token_, buffers, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_receive")); buffer_sequence_adapter<boost::asio::mutable_buffer, MutableBufferSequence> bufs(buffers); start_receive_op(impl, bufs.buffers(), bufs.count(), flags, (impl.state_ & socket_ops::stream_oriented) != 0 && bufs.all_empty(), p.p); p.v = p.p = 0; } // Wait until data can be received without blocking. template <typename Handler, typename IoExecutor> void async_receive(base_implementation_type& impl, const null_buffers&, socket_base::message_flags flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_null_buffers_op<Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_receive(null_buffers)")); start_null_buffers_receive_op(impl, flags, p.p); p.v = p.p = 0; } // Receive some data with associated flags. Returns the number of bytes // received. template <typename MutableBufferSequence> size_t receive_with_flags(base_implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, boost::system::error_code& ec) { buffer_sequence_adapter<boost::asio::mutable_buffer, MutableBufferSequence> bufs(buffers); return socket_ops::sync_recvmsg(impl.socket_, impl.state_, bufs.buffers(), bufs.count(), in_flags, out_flags, ec); } // Wait until data can be received without blocking. size_t receive_with_flags(base_implementation_type& impl, const null_buffers&, socket_base::message_flags, socket_base::message_flags& out_flags, boost::system::error_code& ec) { // Wait for socket to become ready. socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); // Clear out_flags, since we cannot give it any other sensible value when // performing a null_buffers operation. out_flags = 0; return 0; } // Start an asynchronous receive. The buffer for the data being received // must be valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename Handler, typename IoExecutor> void async_receive_with_flags(base_implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_socket_recvmsg_op< MutableBufferSequence, Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, buffers, out_flags, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_receive_with_flags")); buffer_sequence_adapter<boost::asio::mutable_buffer, MutableBufferSequence> bufs(buffers); start_receive_op(impl, bufs.buffers(), bufs.count(), in_flags, false, p.p); p.v = p.p = 0; } // Wait until data can be received without blocking. template <typename Handler, typename IoExecutor> void async_receive_with_flags(base_implementation_type& impl, const null_buffers&, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef win_iocp_null_buffers_op<Handler, IoExecutor> op; typename op::ptr p = { boost::asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket", &impl, impl.socket_, "async_receive_with_flags(null_buffers)")); // Reset out_flags since it can be given no sensible value at this time. out_flags = 0; start_null_buffers_receive_op(impl, in_flags, p.p); p.v = p.p = 0; } // Helper function to restart an asynchronous accept operation. BOOST_ASIO_DECL void restart_accept_op(socket_type s, socket_holder& new_socket, int family, int type, int protocol, void* output_buffer, DWORD address_length, operation* op); protected: // Open a new socket implementation. BOOST_ASIO_DECL boost::system::error_code do_open( base_implementation_type& impl, int family, int type, int protocol, boost::system::error_code& ec); // Assign a native socket to a socket implementation. BOOST_ASIO_DECL boost::system::error_code do_assign( base_implementation_type& impl, int type, socket_type native_socket, boost::system::error_code& ec); // Helper function to start an asynchronous send operation. BOOST_ASIO_DECL void start_send_op(base_implementation_type& impl, WSABUF* buffers, std::size_t buffer_count, socket_base::message_flags flags, bool noop, operation* op); // Helper function to start an asynchronous send_to operation. BOOST_ASIO_DECL void start_send_to_op(base_implementation_type& impl, WSABUF* buffers, std::size_t buffer_count, const socket_addr_type* addr, int addrlen, socket_base::message_flags flags, operation* op); // Helper function to start an asynchronous receive operation. BOOST_ASIO_DECL void start_receive_op(base_implementation_type& impl, WSABUF* buffers, std::size_t buffer_count, socket_base::message_flags flags, bool noop, operation* op); // Helper function to start an asynchronous null_buffers receive operation. BOOST_ASIO_DECL void start_null_buffers_receive_op( base_implementation_type& impl, socket_base::message_flags flags, reactor_op* op); // Helper function to start an asynchronous receive_from operation. BOOST_ASIO_DECL void start_receive_from_op(base_implementation_type& impl, WSABUF* buffers, std::size_t buffer_count, socket_addr_type* addr, socket_base::message_flags flags, int* addrlen, operation* op); // Helper function to start an asynchronous accept operation. BOOST_ASIO_DECL void start_accept_op(base_implementation_type& impl, bool peer_is_open, socket_holder& new_socket, int family, int type, int protocol, void* output_buffer, DWORD address_length, operation* op); // Start an asynchronous read or write operation using the reactor. BOOST_ASIO_DECL void start_reactor_op(base_implementation_type& impl, int op_type, reactor_op* op); // Start the asynchronous connect operation using the reactor. BOOST_ASIO_DECL void start_connect_op(base_implementation_type& impl, int family, int type, const socket_addr_type* remote_addr, std::size_t remote_addrlen, win_iocp_socket_connect_op_base* op); // Helper function to close a socket when the associated object is being // destroyed. BOOST_ASIO_DECL void close_for_destruction(base_implementation_type& impl); // Update the ID of the thread from which cancellation is safe. BOOST_ASIO_DECL void update_cancellation_thread_id( base_implementation_type& impl); // Helper function to get the reactor. If no reactor has been created yet, a // new one is obtained from the execution context and a pointer to it is // cached in this service. BOOST_ASIO_DECL select_reactor& get_reactor(); // The type of a ConnectEx function pointer, as old SDKs may not provide it. typedef BOOL (PASCAL *connect_ex_fn)(SOCKET, const socket_addr_type*, int, void*, DWORD, DWORD*, OVERLAPPED*); // Helper function to get the ConnectEx pointer. If no ConnectEx pointer has // been obtained yet, one is obtained using WSAIoctl and the pointer is // cached. Returns a null pointer if ConnectEx is not available. BOOST_ASIO_DECL connect_ex_fn get_connect_ex( base_implementation_type& impl, int type); // The type of a NtSetInformationFile function pointer. typedef LONG (NTAPI *nt_set_info_fn)(HANDLE, ULONG_PTR*, void*, ULONG, ULONG); // Helper function to get the NtSetInformationFile function pointer. If no // NtSetInformationFile pointer has been obtained yet, one is obtained using // GetProcAddress and the pointer is cached. Returns a null pointer if // NtSetInformationFile is not available. BOOST_ASIO_DECL nt_set_info_fn get_nt_set_info(); // Helper function to emulate InterlockedCompareExchangePointer functionality // for: // - very old Platform SDKs; and // - platform SDKs where MSVC's /Wp64 option causes spurious warnings. BOOST_ASIO_DECL void* interlocked_compare_exchange_pointer( void** dest, void* exch, void* cmp); // Helper function to emulate InterlockedExchangePointer functionality for: // - very old Platform SDKs; and // - platform SDKs where MSVC's /Wp64 option causes spurious warnings. BOOST_ASIO_DECL void* interlocked_exchange_pointer(void** dest, void* val); // The execution context used to obtain the reactor, if required. execution_context& context_; // The IOCP service used for running asynchronous operations and dispatching // handlers. win_iocp_io_context& iocp_service_; // The reactor used for performing connect operations. This object is created // only if needed. select_reactor* reactor_; // Pointer to ConnectEx implementation. void* connect_ex_; // Pointer to NtSetInformationFile implementation. void* nt_set_info_; // Mutex to protect access to the linked list of implementations. boost::asio::detail::mutex mutex_; // The head of a linked list of all implementations. base_implementation_type* impl_list_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/detail/impl/win_iocp_socket_service_base.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // defined(BOOST_ASIO_HAS_IOCP) #endif // BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP
bsd-2-clause
ffan-fe/fancyui
lib/Nav/submenu/menu.submenu.controller.js
1298
/** * @description xxxx * * @author fuzhiyuan1@wandan.cn * @date Tue Jan 03 2017 17:29:57 GMT+0800 (CST) * @example: http://www.fancyui.org/#/zh-cn/component/menu */ class MenuItemController { constructor($timeout, $rootScope, $element) { 'ngInject' this.$timeout = $timeout; this.$rootScope = $rootScope; this.$element = $element; this.onTitleClick = this.onTitleClick || noop; this.state = {}; this.state.isOpen = false; this.state.timerId = null; } $onInit() { this.state.isOpen = this.fMenu.defaultOpenKeys && Array.isArray(this.fMenu.defaultOpenKeys) && this.fMenu.defaultOpenKeys.includes(this.key) if (this.fMenu.mode == 'inline') { this.onMouseEnter = noop; this.onMouseLeave = noop; } else { this.onClick = noop; } this.$element.find('div').html(this.titleName); } onMouseEnter(e) { if (this.state.timerId) { this.$timeout.cancel(this.state.timerId); } this.open(); } onMouseLeave(e) { this.state.timerId = this.$timeout(this.close.bind(this), 300) } onClick(e) { this.state.isOpen = !this.state.isOpen; } open() { this.state.isOpen = true; } close() { this.state.isOpen = false; } } function noop() { } export default MenuItemController;
bsd-2-clause
CloudMade/Crude
crude.js
7219
/** * @preserve Copyright (c) 2011, Vladimir Agafonkin, CloudMade * Crude (v0.1) is a clever JavaScript library for working with RESTful services. * See https://github.com/CloudMade/Crude for more information. */ /*jslint regexp: true, browser: true, node: true */ (function (global) { "use strict"; var Crude = {version: '0.1'}, oldCrude = global.Crude; if (typeof module !== 'undefined' && module.exports) { module.exports = Crude; } else { global.Crude = Crude; } // restores the original global Crude property Crude.noConflict = function () { global.Crude = oldCrude; return this; }; Crude.api = function (baseUrl, format, requestFn) { return new Crude.Api(baseUrl, format, requestFn); }; // the root class of the API (handles basic configuration) Crude.Api = function (baseUrl, format, requestFn) { this.baseUrl = baseUrl; this.format = format; this.requestFn = requestFn; // create a Resources-inherited class to allow extending nested resources api-wide this.NestedResources = function () { Crude.Resources.apply(this, arguments); }; Crude.inherit(this.NestedResources, Crude.Resources); this.nestedResources = this.NestedResources.prototype; }; Crude.Api.prototype = { request: function (path, method, data) { // (path, data) signature if (!data && typeof method !== 'string') { data = method; method = 'get'; } data = Crude.extend({}, data, this.baseData); var url = this.baseUrl + '/' + path + '.' + this.format; // evaluate {stuff} in the url url = Crude.template(url, data, true); return this.requestFn(url, method, data); }, // set api-wide request data data: function (data) { this.baseData = data; }, // example: api.resources('post') creates Crude.Resources instance as api.posts resources: function (name, pluralName) { pluralName = pluralName || Crude.pluralize(name); var resources = this[pluralName] = new Crude.Resources(this, name, pluralName); return resources; } }; // the class where most of the magic happens (all the RESTful stuff) Crude.Resources = function (api, name, pluralName, prefix) { this.api = api; this.name = name; this.pluralName = pluralName; this.prefix = prefix; }; Crude.Resources.prototype = { request: function (path, method, data) { var prefix = (this.prefix ? this.prefix + '/' : ''), postfix = (path ? '/' + path : ''); return this.api.request(prefix + this.pluralName + postfix, method, data); }, get: function (id, data) { // get(data) signature if (!data && typeof id === 'object') { data = id; id = null; } return this.request(id || '', 'get', data); }, create: function (props, data) { props = Crude.wrapKeys(props, this.name); data = Crude.extend({}, data, props); return this.request('', 'post', data); }, update: function (id, props, data) { props = Crude.wrapKeys(props, this.name); data = Crude.extend({}, data, props); return this.request(id, 'put', data); }, del: function (id, data) { return this.request(id, 'delete', data); }, // e.g. after api.comments.belongTo(api.posts), // api.comments.inPost(id) returns NestedResources instance belongTo: function (parent) { var methodName = 'in' + Crude.capitalize(parent.name), ApiNestedResources = this.api.NestedResources, protoAccessName = parent.name + Crude.capitalize(this.pluralName); // created a separate inherited class to allow extending this resource pair function NestedResources() { ApiNestedResources.apply(this, arguments); } Crude.inherit(NestedResources, ApiNestedResources); // e.g. allow prototype access through api.postComments this.api[protoAccessName] = NestedResources.prototype; this[methodName] = function (id) { var prefix = parent.pluralName + '/' + id; return new NestedResources(this.api, this.name, this.pluralName, prefix); }; return this; }, // for custom actions on collections, e.g. /posts/delete_all collectionAction: function (name, options) { options = Crude.extend({ method: 'get', path: name }, options); this[name] = function (data) { if (options.argsToData) { data = options.argsToData.apply(null, arguments); } return this.request(options.path, options.method, data); }; return this; }, // for custom actions on members, e.g. /posts/1/voteup // TODO remove repetition with collectionAction memberAction: function (name, options) { options = Crude.extend({ method: 'get', path: name }, options); this[name] = function (id, data) { if (options.argsToData) { var args = Array.prototype.slice.call(arguments, 1); data = options.argsToData.apply(null, args); } return this.request(id + '/' + options.path, options.method, data); }; return this; } }; // various utility functions // classical inheritance for internal use Crude.inherit = function (Child, Parent) { function F() {} F.prototype = Parent.prototype; var proto = new F(); proto.constructor = Child; Child.prototype = proto; }; // feel free to add more rules from outside Crude.pluralRules = [[/$/, 's'], [/s$/i, 's'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|s|sh)$/i, '$1es'], ['child', 'children']]; Crude.pluralize = function (name) { var rules = Crude.pluralRules, i = rules.length, rule; while (i) { i -= 1; // conforming to strict JSLint for fun :) rule = rules[i]; if (typeof rule[0] === 'string') { if (name === rule[0]) { return rule[1]; } } else { if (rule[0].test(name)) { return name.replace(rule[0], rule[1]); } } } return name; }; Crude.capitalize = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }; Crude.extend = function (dest) { var sources = Array.prototype.slice.call(arguments, 1), len = sources.length, src, i, j; for (j = 0; j < len; j += 1) { src = sources[j] || {}; for (i in src) { if (src.hasOwnProperty(i)) { dest[i] = src[i]; } } } return dest; }; // turns {foo: 'bar'} into {'property[foo]': 'bar'} Crude.wrapKeys = function (props, name) { var obj = {}, i; for (i in props) { if (props.hasOwnProperty(i)) { obj[name + '[' + i + ']'] = props[i]; } } return obj; }; // Crude.template("Hello {foo}", {foo: "World"}) -> "Hello world" Crude.template = function (str, data, cleanupData) { return str.replace(/\{ *([^} ]+) *\}/g, function (str, key) { var value = data[key]; if (!data.hasOwnProperty(key)) { throw new Error('No value provided for variable ' + str); } if (cleanupData) { delete data[key]; } return value; }); }; }(this));
bsd-2-clause
aletheia7/norm
norm/src/java/jni/normEventJni.cpp
890
#include "normJni.h" #include "normEventJni.h" JNIEXPORT jobject JNICALL PKGNAME(NormEvent_getObject) (JNIEnv *env, jobject obj) { NormObjectHandle objectHandle; jobject object = NULL; objectHandle = (NormObjectHandle)env->GetLongField(obj, fid_NormEvent_objectHandle); switch (NormObjectGetType(objectHandle)) { case NORM_OBJECT_DATA: object = env->NewObject((jclass)env->NewLocalRef(jw_NormData), mid_NormData_init, (jlong)objectHandle); break; case NORM_OBJECT_FILE: object = env->NewObject((jclass)env->NewLocalRef(jw_NormFile), mid_NormFile_init, (jlong)objectHandle); break; case NORM_OBJECT_STREAM: object = env->NewObject((jclass)env->NewLocalRef(jw_NormStream), mid_NormStream_init, (jlong)objectHandle); break; default: case NORM_OBJECT_NONE: break; } return object; }
bsd-2-clause
zoetrope/RosSharp
Test/RosSharp.MemoryLeakTest/NodeTest.cs
530
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosSharp.MemoryLeakTest { class NodeTest : ITest { public void Initialize() { } public void Do(int index) { var nodeName = "test" + index; var node = Ros.InitNodeAsync(nodeName, enableLogger: false).Result; node.Dispose(); } public void Cleanup() { } } }
bsd-2-clause
jbooth/flotilla
lib.go
4410
package flotilla import ( "fmt" mdb "github.com/jbooth/gomdb" ) // some default commands func defaultCommands() map[string]Command { return map[string]Command{ "Put": put, "PutIfAbsent": putIfAbsent, "CompareAndSwap": compareAndSwap, "CompareAndRemove": compareAndRemove, "Remove": remove, "Noop": noop, } } // wrapper for default commands type dbOps struct { DB } func (d dbOps) Put(dbName string, key, val []byte) <-chan Result { args := [][]byte{[]byte(dbName), key, val} return d.Command("Put", args) } func (d dbOps) PutIfAbsent(dbName string, key, val []byte) <-chan Result { args := [][]byte{[]byte(dbName), key, val} return d.Command("PutIfAbsent", args) } func (d dbOps) CompareAndSwap(dbName string, key, expectedVal, setVal []byte) <-chan Result { args := [][]byte{[]byte(dbName), key, expectedVal, setVal} return d.Command("CompareAndSwap", args) } func (d dbOps) Remove(dbName string, key []byte) <-chan Result { args := [][]byte{[]byte(dbName), key} return d.Command("Remove", args) } func (d dbOps) CompareAndRemove(dbName string, key, expectedVal []byte) <-chan Result { args := [][]byte{[]byte(dbName), key, expectedVal} return d.Command("Remove", args) } func (d dbOps) Barrier() <-chan Result { args := [][]byte{} return d.Command("Noop", args) } // put // arg0: dbName // arg1: key // arg2: value // returns nil func put(args [][]byte, txn *mdb.Txn) ([]byte, error) { if len(args) < 3 { return nil, fmt.Errorf("Put needs 3 arguments! Got %d args", len(args)) } dbName := string(args[0]) dbi, err := txn.DBIOpen(&dbName, mdb.CREATE) // create if not exists if err != nil { txn.Abort() return nil, err } err = txn.Put(dbi, args[1], args[2], 0) if err != nil { txn.Abort() return nil, err } err = txn.Commit() return nil, err } // put if not already set // arg0: dbName // arg1: key // arg2: value // return: [1] if added, [0] otherwise func putIfAbsent(args [][]byte, txn *mdb.Txn) ([]byte, error) { dbName := string(args[0]) dbi, err := txn.DBIOpen(&dbName, mdb.CREATE) // create if not exists if err != nil { txn.Abort() return nil, err } err = txn.Put(dbi, args[1], args[2], mdb.NOOVERWRITE) if err == mdb.KeyExist { txn.Abort() return []byte{0}, nil } if err != nil { txn.Abort() return nil, err } err = txn.Commit() return []byte{1}, err } // compare and swap // arg0: dbName // arg1: key // arg2: expectedValue // arg3: newValue // return: new row contents as []byte func compareAndSwap(args [][]byte, txn *mdb.Txn) ([]byte, error) { dbName := string(args[0]) dbi, err := txn.DBIOpen(&dbName, mdb.CREATE) // create if not exists existingVal, err := txn.Get(dbi, args[1]) if err != nil && err != mdb.NotFound { txn.Abort() return nil, err } if err == mdb.NotFound || bytesEqual(args[2], existingVal) { err = txn.Put(dbi, args[1], args[3], 0) if err != nil { return nil, err } err = txn.Commit() return args[3], err } else { txn.Abort() return existingVal, nil } } // remove // arg0: dbName // arg1: key // returns nil func remove(args [][]byte, txn *mdb.Txn) ([]byte, error) { dbName := string(args[0]) dbi, err := txn.DBIOpen(&dbName, mdb.CREATE) // create if not exists if err != nil { txn.Abort() return nil, err } err = txn.Del(dbi, args[1], nil) if err != nil { txn.Abort() return nil, err } return nil, txn.Commit() } // remove if set to expected val // arg0: dbName // arg1: key // arg2: expectedVal // ret: [1] if removed, [0] otherwise func compareAndRemove(args [][]byte, txn *mdb.Txn) ([]byte, error) { dbName := string(args[0]) dbi, err := txn.DBIOpen(&dbName, mdb.CREATE) // create if not exists existingVal, err := txn.Get(dbi, args[1]) if err != nil && err != mdb.NotFound { txn.Abort() return nil, err } if err == mdb.NotFound || bytesEqual(args[2], existingVal) { err = txn.Del(dbi, args[1], nil) if err != nil { return nil, err } err = txn.Commit() return args[3], err } else { txn.Abort() return existingVal, nil } } func noop(args [][]byte, txn *mdb.Txn) ([]byte, error) { return nil, nil } func bytesEqual(a []byte, b []byte) bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } if len(a) != len(b) { return false } for i := 0; i < len(a); i++ { if a[i] != b[i] { return false } } return true }
bsd-2-clause
bbqsrc/sgit
sgit/__main__.py
2548
import argparse import os import os.path import shlex import subprocess import sys from . import Sgit PATHS = [ os.environ.get('SGIT_PATH', None), os.path.expanduser('~/.sgit'), '/etc/sgit' ] GIT_CMDS = { 'git-receive-pack': 'push', 'git-upload-pack': 'pull' } def get_cfg_path(): for path in PATHS: if path is None: continue if os.path.isdir(path): return path raise Exception("No config path found!") def get_ssh_cmd(): return os.environ.get('SSH_ORIGINAL_COMMAND', None) def get_sgit_shell_argparse(): a = argparse.ArgumentParser() s = a.add_subparsers(dest='cmd') n = s.add_parser('create-repo') n.add_argument('path') n = s.add_parser('create-user') n.add_argument('username') n.add_argument('ssh_key') n = s.add_parser('add-users-to-repo') n.add_argument('path') n.add_argument('users', nargs='+') return a def sgit_shell(): if len(sys.argv) < 3 or sys.argv[1] != '-c': return 255 a = get_sgit_shell_argparse() user = sys.argv[2] sgit = Sgit(user, get_cfg_path()) orig_cmd = get_ssh_cmd() if orig_cmd is None: return 1 # Handle ordinary git ssh calls cmd_args = shlex.split(orig_cmd) first = cmd_args[0] if first in GIT_CMDS: if GIT_CMDS[first] == 'push': if sgit.can_push_repo(cmd_args[1]): subprocess.check_call(['git-shell', '-c', orig_cmd]) return 0 else: sys.stderr.write("Cannot push.\n") return 2 elif GIT_CMDS[first] == 'pull': if sgit.can_pull_repo(cmd_args[1]): subprocess.check_call(['git-shell', '-c', orig_cmd]) return 0 else: sys.stderr.write("Cannot pull.\n") return 2 sys.stderr.write("Should not get here.\n") return 100 # Handle sgit world args = a.parse_args(shlex.split(orig_cmd)) if args.cmd == 'create-repo': sgit.create_repo(args.path) elif args.cmd == 'create-user': sgit.create_user(args.username, args.ssh_key) elif args.cmd == 'add-users-to-repo': sgit.add_users_to_repo(args.path, args.users) else: return 3 def sgit(): print("TODO!") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {sgit,sgit-shell} [-h] ...") if sys.argv[1] == 'sgit': sgit() elif sys.argv[1] == 'sgit-shell': sgit_shell(sys.argv[2])
bsd-2-clause
nikhilmat/helpful-web
spec/models/conversations_archive_spec.rb
1741
require 'spec_helper' describe ConversationsArchive do before do @account = build(:account) @conversations = [] @messages = [] # Create three conversations and three unique messages 0.upto(2) do |i| @conversations.push create(:conversation, account: @account) message = create(:message, conversation: @conversations[i], content: "test #{i}") # Need to have consistent ids for VCR to work message.id = "c91d36fb-c406-4a06-a9b0-808c64b80e8#{i}" message.save! @messages.push message end # Create indices in Elasticsearch if not provided from VCR if !File.exists? Rails.root.join('spec', 'vcr', 'update_search_index.yml') VCR.use_cassette('update_search_index') do @messages.each { |message| message.update_search_index } end end end describe "search" do it "should get conversations in elastic search order" do @archive = ConversationsArchive.new(@account, 'test') VCR.use_cassette('search_all') do # Test for messages/conversations in order of most recently updated assert_equal @archive.search_messages, @messages.sort { |a,b| b.updated_at <=> a.updated_at }.map { |m| m.id } assert_equal @archive.conversations, @conversations.sort { |a,b| b.updated_at <=> a.updated_at } end end it "should get specific conversations by message content" do @archive = ConversationsArchive.new(@account, '0') VCR.use_cassette('search_specific') do # Test for messages/conversations that match the query term assert_equal @archive.search_messages, [@messages.first.id] assert_equal @archive.conversations, [@conversations.first] end end end end
bsd-2-clause
biotty/rmg
sound/synth/musicm.hpp
259
// © Christian Sommerfeldt Øien // All rights reserved #ifndef MUSICM_HPP #define MUSICM_HPP double p_of(double f); double c_at(double f); double a_of(double l); double l_of(double a); double f_of(double p); double f_of_just(unsigned p); #endif
bsd-2-clause
poste9/crud
deps/npm/@angular/compiler@2.4.4/src/ml_parser/ast.js
6182
/* */ "format cjs"; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export var Text = (function () { /** * @param {?} value * @param {?} sourceSpan */ function Text(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return Text; }()); function Text_tsickle_Closure_declarations() { /** @type {?} */ Text.prototype.value; /** @type {?} */ Text.prototype.sourceSpan; } export var Expansion = (function () { /** * @param {?} switchValue * @param {?} type * @param {?} cases * @param {?} sourceSpan * @param {?} switchValueSourceSpan */ function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan) { this.switchValue = switchValue; this.type = type; this.cases = cases; this.sourceSpan = sourceSpan; this.switchValueSourceSpan = switchValueSourceSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); }; return Expansion; }()); function Expansion_tsickle_Closure_declarations() { /** @type {?} */ Expansion.prototype.switchValue; /** @type {?} */ Expansion.prototype.type; /** @type {?} */ Expansion.prototype.cases; /** @type {?} */ Expansion.prototype.sourceSpan; /** @type {?} */ Expansion.prototype.switchValueSourceSpan; } export var ExpansionCase = (function () { /** * @param {?} value * @param {?} expression * @param {?} sourceSpan * @param {?} valueSourceSpan * @param {?} expSourceSpan */ function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) { this.value = value; this.expression = expression; this.sourceSpan = sourceSpan; this.valueSourceSpan = valueSourceSpan; this.expSourceSpan = expSourceSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); }; return ExpansionCase; }()); function ExpansionCase_tsickle_Closure_declarations() { /** @type {?} */ ExpansionCase.prototype.value; /** @type {?} */ ExpansionCase.prototype.expression; /** @type {?} */ ExpansionCase.prototype.sourceSpan; /** @type {?} */ ExpansionCase.prototype.valueSourceSpan; /** @type {?} */ ExpansionCase.prototype.expSourceSpan; } export var Attribute = (function () { /** * @param {?} name * @param {?} value * @param {?} sourceSpan * @param {?=} valueSpan */ function Attribute(name, value, sourceSpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); }; return Attribute; }()); function Attribute_tsickle_Closure_declarations() { /** @type {?} */ Attribute.prototype.name; /** @type {?} */ Attribute.prototype.value; /** @type {?} */ Attribute.prototype.sourceSpan; /** @type {?} */ Attribute.prototype.valueSpan; } export var Element = (function () { /** * @param {?} name * @param {?} attrs * @param {?} children * @param {?} sourceSpan * @param {?} startSourceSpan * @param {?} endSourceSpan */ function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan) { this.name = name; this.attrs = attrs; this.children = children; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); }; return Element; }()); function Element_tsickle_Closure_declarations() { /** @type {?} */ Element.prototype.name; /** @type {?} */ Element.prototype.attrs; /** @type {?} */ Element.prototype.children; /** @type {?} */ Element.prototype.sourceSpan; /** @type {?} */ Element.prototype.startSourceSpan; /** @type {?} */ Element.prototype.endSourceSpan; } export var Comment = (function () { /** * @param {?} value * @param {?} sourceSpan */ function Comment(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } /** * @param {?} visitor * @param {?} context * @return {?} */ Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); }; return Comment; }()); function Comment_tsickle_Closure_declarations() { /** @type {?} */ Comment.prototype.value; /** @type {?} */ Comment.prototype.sourceSpan; } /** * @param {?} visitor * @param {?} nodes * @param {?=} context * @return {?} */ export function visitAll(visitor, nodes, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; nodes.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; } //# sourceMappingURL=ast.js.map
bsd-2-clause
KaltZK/mao-project-vote
public/bower_components/bootstrap-material-design/js/src/baseInput.js
10716
import Base from './base' import Util from './util' const BaseInput = (($) => { const ClassName = { FORM_GROUP: 'form-group', MDB_FORM_GROUP: 'mdb-form-group', MDB_LABEL: 'mdb-label', MDB_LABEL_STATIC: 'mdb-label-static', MDB_LABEL_PLACEHOLDER: 'mdb-label-placeholder', MDB_LABEL_FLOATING: 'mdb-label-floating', HAS_DANGER: 'has-danger', IS_FILLED: 'is-filled', IS_FOCUSED: 'is-focused' } const Selector = { FORM_GROUP: `.${ClassName.FORM_GROUP}`, MDB_FORM_GROUP: `.${ClassName.MDB_FORM_GROUP}`, MDB_LABEL_WILDCARD: `label[class^='${ClassName.MDB_LABEL}'], label[class*=' ${ClassName.MDB_LABEL}']` // match any label variant if specified } const Default = { validate: false, formGroup: { required: false }, mdbFormGroup: { template: `<span class='${ClassName.MDB_FORM_GROUP}'></span>`, create: true, // create a wrapper if form-group not found required: true // not recommended to turn this off, only used for inline components }, label: { required: false, // Prioritized find order for resolving the label to be used as an mdb-label if not specified in the markup // - a function(thisComponent); or // - a string selector used like $mdbFormGroup.find(selector) // // Note this only runs if $mdbFormGroup.find(Selector.MDB_LABEL_WILDCARD) fails to find a label (as authored in the markup) // selectors: [ `.form-control-label`, // in the case of horizontal or inline forms, this will be marked `> label` // usual case for text inputs, first child. Deeper would find toggle labels so don't do that. ], className: ClassName.MDB_LABEL_STATIC }, requiredClasses: [], invalidComponentMatches: [], convertInputSizeVariations: true } const FormControlSizeMarkers = { 'form-control-lg': 'mdb-form-group-lg', 'form-control-sm': 'mdb-form-group-sm' } /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ class BaseInput extends Base { /** * * @param element * @param config * @param properties - anything that needs to be set as this[key] = value. Works around the need to call `super` before using `this` */ constructor($element, config, properties = {}) { super($element, $.extend(true, {}, Default, config), properties) // Enforce no overlap between components to prevent side effects this._rejectInvalidComponentMatches() // Enforce expected structure (if any) this.rejectWithoutRequiredStructure() // Enforce required classes for a consistent rendering this._rejectWithoutRequiredClasses() // Resolve the form-group first, it will be used for mdb-form-group if possible // note: different components have different rules this.$formGroup = this.findFormGroup(this.config.formGroup.required) // Will add mdb-form-group to form-group or create an mdb-form-group // Performance Note: for those forms that are really performance driven, create the markup with the .mdb-form-group to avoid // rendering changes once added. this.$mdbFormGroup = this.resolveMdbFormGroup() // Resolve and mark the mdbLabel if necessary as defined by the config this.$mdbLabel = this.resolveMdbLabel() // Signal to the mdb-form-group that a form-control-* variation is being used this.resolveMdbFormGroupSizing() this.addFocusListener() this.addChangeListener() } dispose(dataKey) { super.dispose(dataKey) this.$mdbFormGroup = null this.$formGroup = null } // ------------------------------------------------------------------------ // protected rejectWithoutRequiredStructure() { // implement } addFocusListener() { this.$element .on('focus', () => { this.addFormGroupFocus() }) .on('blur', () => { this.removeFormGroupFocus() }) } addChangeListener() { this.$element .on('keydown paste', (event) => { if (Util.isChar(event)) { this.addIsFilled() } }) .on('keyup change', () => { // make sure empty is added back when there is a programmatic value change. // NOTE: programmatic changing of value using $.val() must trigger the change event i.e. $.val('x').trigger('change') if (this.isEmpty()) { this.removeIsFilled() } else { this.addIsFilled() } if (this.config.validate) { // Validation events do not bubble, so they must be attached directly to the text: http://jsfiddle.net/PEpRM/1/ // Further, even the bind method is being caught, but since we are already calling #checkValidity here, just alter // the form-group on change. // // NOTE: I'm not sure we should be intervening regarding validation, this seems better as a README and snippet of code. // BUT, I've left it here for backwards compatibility. let isValid = (typeof this.$element[0].checkValidity === 'undefined' || this.$element[0].checkValidity()) if (isValid) { this.removeHasDanger() } else { this.addHasDanger() } } }) } addHasDanger() { this.$mdbFormGroup.addClass(ClassName.HAS_DANGER) } removeHasDanger() { this.$mdbFormGroup.removeClass(ClassName.HAS_DANGER) } isEmpty() { return (this.$element.val() === null || this.$element.val() === undefined || this.$element.val() === '') } // Will add mdb-form-group to form-group or create a mdb-form-group if necessary resolveMdbFormGroup() { let mfg = this.findMdbFormGroup(false) if (mfg === undefined || mfg.length === 0) { if (this.config.mdbFormGroup.create && (this.$formGroup === undefined || this.$formGroup.length === 0)) { // If a form-group doesn't exist (not recommended), take a guess and wrap the element (assuming no label). // note: it's possible to make this smarter, but I need to see valid cases before adding any complexity. this.outerElement().wrap(this.config.mdbFormGroup.template) } else { // a form-group does exist, add our marker class to it this.$formGroup.addClass(ClassName.MDB_FORM_GROUP) // OLD: may want to implement this after all, see how the styling turns out, but using an existing form-group is less manipulation of the dom and therefore preferable // A form-group does exist, so add an mdb-form-group wrapping it's internal contents //fg.wrapInner(this.config.mdbFormGroup.template) } mfg = this.findMdbFormGroup(this.config.mdbFormGroup.required) } return mfg } // Demarcation element (e.g. first child of a form-group) // Subclasses such as file inputs may have different structures outerElement() { return this.$element } // Will add mdb-label to mdb-form-group if not already specified resolveMdbLabel() { let label = this.$mdbFormGroup.find(Selector.MDB_LABEL_WILDCARD) if (label === undefined || label.length === 0) { // we need to find it based on the configured selectors label = this.findMdbLabel(this.config.label.required) if (label === undefined || label.length === 0) { // no label found, and finder did not require one } else { // a candidate label was found, add the configured default class name label.addClass(this.config.label.className) } } return label } // Find mdb-label variant based on the config selectors findMdbLabel(raiseError = true) { let label = null // use the specified selector order for (let selector of this.config.label.selectors) { if ($.isFunction(selector)) { label = selector(this) } else { label = this.$mdbFormGroup.find(selector) } if (label !== undefined && label.length > 0) { break } } if (label.length === 0 && raiseError) { $.error(`Failed to find ${Selector.MDB_LABEL_WILDCARD} within form-group for ${Util.describe(this.$element)}`) } return label } // Find mdb-form-group findFormGroup(raiseError = true) { let fg = this.$element.closest(Selector.FORM_GROUP) if (fg.length === 0 && raiseError) { $.error(`Failed to find ${Selector.FORM_GROUP} for ${Util.describe(this.$element)}`) } return fg } // Due to the interconnected nature of labels/inputs/help-blocks, signal the mdb-form-group-* size variation based on // a found form-control-* size resolveMdbFormGroupSizing() { if (!this.config.convertInputSizeVariations) { return } // Modification - Change text-sm/lg to form-group-sm/lg instead (preferred standard and simpler css/less variants) for (let inputSize in FormControlSizeMarkers) { if (this.$element.hasClass(inputSize)) { //this.$element.removeClass(inputSize) this.$mdbFormGroup.addClass(FormControlSizeMarkers[inputSize]) } } } // ------------------------------------------------------------------------ // private _rejectInvalidComponentMatches() { for (let otherComponent of this.config.invalidComponentMatches) { otherComponent.rejectMatch(this.constructor.name, this.$element) } } _rejectWithoutRequiredClasses() { for (let requiredClass of this.config.requiredClasses) { let found = false // allow one of several classes to be passed in x||y if (requiredClass.indexOf('||') !== -1) { let oneOf = requiredClass.split('||') for (let requiredClass of oneOf) { if (this.$element.hasClass(requiredClass)) { found = true break } } } else if (this.$element.hasClass(requiredClass)) { found = true } // error if not found if (!found) { $.error(`${this.constructor.name} element: ${Util.describe(this.$element)} requires class: ${requiredClass}`) } } } // ------------------------------------------------------------------------ // static } return BaseInput })(jQuery) export default BaseInput
bsd-2-clause
brunolauze/MonoNative
MonoNative/mscorlib/System/Diagnostics/mscorlib_System_Diagnostics_DebuggerVisualizerAttribute.cpp
3736
#include <mscorlib/System/Diagnostics/mscorlib_System_Diagnostics_DebuggerVisualizerAttribute.h> namespace mscorlib { namespace System { namespace Diagnostics { //Public Methods //Get Set Properties Methods // Get/Set:Description mscorlib::System::String DebuggerVisualizerAttribute::get_Description() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "get_Description", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } void DebuggerVisualizerAttribute::set_Description(mscorlib::System::String value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "set_Description", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:Target mscorlib::System::Type DebuggerVisualizerAttribute::get_Target() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "get_Target", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::Type(__result__); } void DebuggerVisualizerAttribute::set_Target(mscorlib::System::Type value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "set_Target", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get/Set:TargetTypeName mscorlib::System::String DebuggerVisualizerAttribute::get_TargetTypeName() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "get_TargetTypeName", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } void DebuggerVisualizerAttribute::set_TargetTypeName(mscorlib::System::String value) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(value).name()); __parameters__[0] = (MonoObject*)value; Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "set_TargetTypeName", __native_object__, 1, __parameter_types__, __parameters__, NULL); } // Get:VisualizerObjectSourceTypeName mscorlib::System::String DebuggerVisualizerAttribute::get_VisualizerObjectSourceTypeName() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "get_VisualizerObjectSourceTypeName", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } // Get:VisualizerTypeName mscorlib::System::String DebuggerVisualizerAttribute::get_VisualizerTypeName() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Diagnostics", "DebuggerVisualizerAttribute", 0, NULL, "get_VisualizerTypeName", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::String(__result__); } // Get:TypeId mscorlib::System::Object DebuggerVisualizerAttribute::get_TypeId() const { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Attribute", 0, NULL, "get_TypeId", __native_object__, 0, NULL, NULL, NULL); return mscorlib::System::Object(__result__); } } } }
bsd-2-clause
plan3/annoyance
src/main/java/annoyance/model/PullRequest.java
1909
package annoyance.model; import java.io.IOException; import java.util.UUID; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; public class PullRequest implements Task { private final Source source; private final Destination destination; private final String title; public PullRequest(final String title, final Source source, final Destination destination) { this.title = title.replace('_', ' '); this.source = source; this.destination = destination; } @Override public boolean execute(final GitHub github) { try { final GHRepository repository = this.destination.from(github); final String branch = "annoyance-" + UUID.randomUUID().toString(); final String master = repository.getRef("heads/master").getObject().getSha(); repository.createRef("refs/heads/".concat(branch), master); repository.createContent( this.source.from(github).render(), this.source.toString(), this.destination.getPath(), branch); // Creating the PR occasionally fails with the message... // "No commits between master and annoyance-08baaeca-7b27-480c-b838-de7e00f188fb" // ...which I assume is an eventual consistency thing, i.e.: the branch commit hasn't been fully propagated // and therefore the branch doesn't differ from 'master' and creating the PR fails. repository.createPullRequest(this.title, branch, "master", this.destination.getMessage()); return true; } catch(final IOException e) { e.printStackTrace(); } return false; } @Override public String toString() { return getClass().getSimpleName() + '[' + this.source + " => " + this.destination + ']'; } }
bsd-2-clause
ibudiselic/contest-problem-solutions
tc 160+/TeamPhoto.cpp
3591
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; class TeamPhoto { public: int eval(vector<int>::const_iterator beg, vector<int>::const_iterator end) { int ret = 0; while (++beg!=end) ret += abs(*beg-*(beg-1)); return ret; } int go(int a, int b, int c, int d, int e, int f, int g, int h) { return abs(a-b)+abs(c-d)+abs(d-e)+abs(e-f)+abs(g-h); } int minDiff(vector <int> height) { vector<int> players(height.begin()+3, height.end()); const int hc=height[0], as1=height[1], as2=height[2]; sort(players.begin(), players.end()); const int pll = players[0]; const int plr = players[players.size()/2-1]; const int mid = (players.size()%2==0 ? hc:players[players.size()/2]); const int prl = (players.size()%2==0 ? players[players.size()/2]:players[players.size()/2+1]); const int prr = players[players.size()-1]; const int left = eval(players.begin(), players.begin()+players.size()/2); const int right = eval(players.size()%2==0 ? players.begin()+players.size()/2:players.begin()+players.size()/2+1, players.end()); int best = 0x7fff; best <?= go(as1, pll, plr, mid, hc, prl, prr, as2); best <?= go(as2, pll, plr, mid, hc, prl, prr, as1); best <?= go(as1, pll, plr, hc, mid, prl, prr, as2); best <?= go(as2, pll, plr, hc, mid, prl, prr, as1); best <?= go(as1, prl, prr, mid, hc, pll, plr, as2); best <?= go(as2, prl, prr, mid, hc, pll, plr, as1); best <?= go(as1, prl, prr, hc, mid, pll, plr, as2); best <?= go(as2, prl, prr, hc, mid, pll, plr, as1); best <?= go(as1, plr, pll, mid, hc, prl, prr, as2); best <?= go(as2, plr, pll, mid, hc, prl, prr, as1); best <?= go(as1, plr, pll, hc, mid, prl, prr, as2); best <?= go(as2, plr, pll, hc, mid, prl, prr, as1); best <?= go(as1, prl, prr, mid, hc, plr, pll, as2); best <?= go(as2, prl, prr, mid, hc, plr, pll, as1); best <?= go(as1, prl, prr, hc, mid, plr, pll, as2); best <?= go(as2, prl, prr, hc, mid, plr, pll, as1); return left+best+right; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {80, 82, 81, 50, 90, 65}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 79; verify_case(0, Arg1, minDiff(Arg0)); } void test_case_1() { int Arr0[] = {70,82,91,50,50,50,50,50,50}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 113; verify_case(1, Arg1, minDiff(Arg0)); } void test_case_2() { int Arr0[] = {13, 17, 11, 12, 10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 10; verify_case(2, Arg1, minDiff(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TeamPhoto ___test; ___test.run_test(-1); } // END CUT HERE
bsd-2-clause
ahomescu/phpy
tests/small/test1.php
20
<?php $x = 2; ?>
bsd-2-clause
ShawnMilo/bitmap
doc.go
450
/* Package bitmap provides a simple bitmap which allows individual bits to be set and read within a slice of bytes. The package was inspired by the book "Programming Pearls," by Jon Bentley. The first example in the book is a clever sorting solution which uses a bitmap to sort a file containing up 10 million numeric values in a single pass without loading them all into memory. http://www.cs.bell-labs.com/cm/cs/pearls/cto.html */ package bitmap
bsd-2-clause
ASMlover/study
3rdparty/boost/include/boost/geometry/srs/projections/proj/aeqd.hpp
22153
// Boost.Geometry - gis-projections (based on PROJ4) // Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017, 2018, 2019. // Modifications copyright (c) 2017-2019, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by Gerald Evenden (then of the USGS) // PROJ4 is maintained by Frank Warmerdam // PROJ4 is converted to Boost.Geometry by Barend Gehrels // Last updated version of proj: 5.0.0 // Original copyright notice: // Purpose: Implementation of the aeqd (Azimuthal Equidistant) projection. // Author: Gerald Evenden // Copyright (c) 1995, Gerald Evenden // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef BOOST_GEOMETRY_PROJECTIONS_AEQD_HPP #define BOOST_GEOMETRY_PROJECTIONS_AEQD_HPP #include <boost/config.hpp> #include <boost/geometry/formulas/vincenty_direct.hpp> #include <boost/geometry/formulas/vincenty_inverse.hpp> #include <boost/geometry/srs/projections/impl/aasincos.hpp> #include <boost/geometry/srs/projections/impl/base_static.hpp> #include <boost/geometry/srs/projections/impl/base_dynamic.hpp> #include <boost/geometry/srs/projections/impl/factory_entry.hpp> #include <boost/geometry/srs/projections/impl/pj_mlfn.hpp> #include <boost/geometry/srs/projections/impl/pj_param.hpp> #include <boost/geometry/srs/projections/impl/projects.hpp> #include <boost/geometry/util/math.hpp> #include <boost/math/special_functions/hypot.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace geometry { namespace projections { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace aeqd { static const double epsilon10 = 1.e-10; static const double tolerance = 1.e-14; enum mode_type { n_pole = 0, s_pole = 1, equit = 2, obliq = 3 }; template <typename T> struct par_aeqd { T sinph0; T cosph0; detail::en<T> en; T M1; //T N1; T Mp; //T He; //T G; T b; mode_type mode; }; template <typename T, typename Par, typename ProjParm> inline void e_forward(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y, Par const& par, ProjParm const& proj_parm) { T coslam, cosphi, sinphi, rho; //T azi1, s12; //T lam1, phi1, lam2, phi2; coslam = cos(lp_lon); cosphi = cos(lp_lat); sinphi = sin(lp_lat); switch (proj_parm.mode) { case n_pole: coslam = - coslam; BOOST_FALLTHROUGH; case s_pole: xy_x = (rho = fabs(proj_parm.Mp - pj_mlfn(lp_lat, sinphi, cosphi, proj_parm.en))) * sin(lp_lon); xy_y = rho * coslam; break; case equit: case obliq: if (fabs(lp_lon) < epsilon10 && fabs(lp_lat - par.phi0) < epsilon10) { xy_x = xy_y = 0.; break; } //phi1 = par.phi0; lam1 = par.lam0; //phi2 = lp_lat; lam2 = lp_lon + par.lam0; formula::result_inverse<T> const inv = formula::vincenty_inverse < T, true, true >::apply(par.lam0, par.phi0, lp_lon + par.lam0, lp_lat, srs::spheroid<T>(par.a, proj_parm.b)); //azi1 = inv.azimuth; s12 = inv.distance; xy_x = inv.distance * sin(inv.azimuth) / par.a; xy_y = inv.distance * cos(inv.azimuth) / par.a; break; } } template <typename T, typename Par, typename ProjParm> inline void e_inverse(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm) { T c; if ((c = boost::math::hypot(xy_x, xy_y)) < epsilon10) { lp_lat = par.phi0; lp_lon = 0.; return; } if (proj_parm.mode == obliq || proj_parm.mode == equit) { T const x2 = xy_x * par.a; T const y2 = xy_y * par.a; //T const lat1 = par.phi0; //T const lon1 = par.lam0; T const azi1 = atan2(x2, y2); T const s12 = sqrt(x2 * x2 + y2 * y2); formula::result_direct<T> const dir = formula::vincenty_direct < T, true >::apply(par.lam0, par.phi0, s12, azi1, srs::spheroid<T>(par.a, proj_parm.b)); lp_lat = dir.lat2; lp_lon = dir.lon2; lp_lon -= par.lam0; } else { /* Polar */ lp_lat = pj_inv_mlfn(proj_parm.mode == n_pole ? proj_parm.Mp - c : proj_parm.Mp + c, par.es, proj_parm.en); lp_lon = atan2(xy_x, proj_parm.mode == n_pole ? -xy_y : xy_y); } } template <typename T, typename Par, typename ProjParm> inline void e_guam_fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y, Par const& par, ProjParm const& proj_parm) { T cosphi, sinphi, t; cosphi = cos(lp_lat); sinphi = sin(lp_lat); t = 1. / sqrt(1. - par.es * sinphi * sinphi); xy_x = lp_lon * cosphi * t; xy_y = pj_mlfn(lp_lat, sinphi, cosphi, proj_parm.en) - proj_parm.M1 + .5 * lp_lon * lp_lon * cosphi * sinphi * t; } template <typename T, typename Par, typename ProjParm> inline void e_guam_inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm) { T x2, t = 0.0; int i; x2 = 0.5 * xy_x * xy_x; lp_lat = par.phi0; for (i = 0; i < 3; ++i) { t = par.e * sin(lp_lat); lp_lat = pj_inv_mlfn(proj_parm.M1 + xy_y - x2 * tan(lp_lat) * (t = sqrt(1. - t * t)), par.es, proj_parm.en); } lp_lon = xy_x * t / cos(lp_lat); } template <typename T, typename Par, typename ProjParm> inline void s_forward(T const& lp_lon, T lp_lat, T& xy_x, T& xy_y, Par const& /*par*/, ProjParm const& proj_parm) { static const T half_pi = detail::half_pi<T>(); T coslam, cosphi, sinphi; sinphi = sin(lp_lat); cosphi = cos(lp_lat); coslam = cos(lp_lon); switch (proj_parm.mode) { case equit: xy_y = cosphi * coslam; goto oblcon; case obliq: xy_y = proj_parm.sinph0 * sinphi + proj_parm.cosph0 * cosphi * coslam; oblcon: if (fabs(fabs(xy_y) - 1.) < tolerance) if (xy_y < 0.) BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); else xy_x = xy_y = 0.; else { xy_y = acos(xy_y); xy_y /= sin(xy_y); xy_x = xy_y * cosphi * sin(lp_lon); xy_y *= (proj_parm.mode == equit) ? sinphi : proj_parm.cosph0 * sinphi - proj_parm.sinph0 * cosphi * coslam; } break; case n_pole: lp_lat = -lp_lat; coslam = -coslam; BOOST_FALLTHROUGH; case s_pole: if (fabs(lp_lat - half_pi) < epsilon10) BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); xy_x = (xy_y = (half_pi + lp_lat)) * sin(lp_lon); xy_y *= coslam; break; } } template <typename T, typename Par, typename ProjParm> inline void s_inverse(T xy_x, T xy_y, T& lp_lon, T& lp_lat, Par const& par, ProjParm const& proj_parm) { static const T pi = detail::pi<T>(); static const T half_pi = detail::half_pi<T>(); T cosc, c_rh, sinc; if ((c_rh = boost::math::hypot(xy_x, xy_y)) > pi) { if (c_rh - epsilon10 > pi) BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) ); c_rh = pi; } else if (c_rh < epsilon10) { lp_lat = par.phi0; lp_lon = 0.; return; } if (proj_parm.mode == obliq || proj_parm.mode == equit) { sinc = sin(c_rh); cosc = cos(c_rh); if (proj_parm.mode == equit) { lp_lat = aasin(xy_y * sinc / c_rh); xy_x *= sinc; xy_y = cosc * c_rh; } else { lp_lat = aasin(cosc * proj_parm.sinph0 + xy_y * sinc * proj_parm.cosph0 / c_rh); xy_y = (cosc - proj_parm.sinph0 * sin(lp_lat)) * c_rh; xy_x *= sinc * proj_parm.cosph0; } lp_lon = xy_y == 0. ? 0. : atan2(xy_x, xy_y); } else if (proj_parm.mode == n_pole) { lp_lat = half_pi - c_rh; lp_lon = atan2(xy_x, -xy_y); } else { lp_lat = c_rh - half_pi; lp_lon = atan2(xy_x, xy_y); } } // Azimuthal Equidistant template <typename Params, typename Parameters, typename T> inline void setup_aeqd(Params const& params, Parameters& par, par_aeqd<T>& proj_parm, bool is_sphere, bool is_guam) { static const T half_pi = detail::half_pi<T>(); par.phi0 = pj_get_param_r<T, srs::spar::lat_0>(params, "lat_0", srs::dpar::lat_0); if (fabs(fabs(par.phi0) - half_pi) < epsilon10) { proj_parm.mode = par.phi0 < 0. ? s_pole : n_pole; proj_parm.sinph0 = par.phi0 < 0. ? -1. : 1.; proj_parm.cosph0 = 0.; } else if (fabs(par.phi0) < epsilon10) { proj_parm.mode = equit; proj_parm.sinph0 = 0.; proj_parm.cosph0 = 1.; } else { proj_parm.mode = obliq; proj_parm.sinph0 = sin(par.phi0); proj_parm.cosph0 = cos(par.phi0); } if (is_sphere) { /* empty */ } else { proj_parm.en = pj_enfn<T>(par.es); if (is_guam) { proj_parm.M1 = pj_mlfn(par.phi0, proj_parm.sinph0, proj_parm.cosph0, proj_parm.en); } else { switch (proj_parm.mode) { case n_pole: proj_parm.Mp = pj_mlfn<T>(half_pi, 1., 0., proj_parm.en); break; case s_pole: proj_parm.Mp = pj_mlfn<T>(-half_pi, -1., 0., proj_parm.en); break; case equit: case obliq: //proj_parm.N1 = 1. / sqrt(1. - par.es * proj_parm.sinph0 * proj_parm.sinph0); //proj_parm.G = proj_parm.sinph0 * (proj_parm.He = par.e / sqrt(par.one_es)); //proj_parm.He *= proj_parm.cosph0; break; } // Boost.Geometry specific, in proj4 geodesic is initialized at the beginning proj_parm.b = math::sqrt(math::sqr(par.a) * (1. - par.es)); } } } template <typename T, typename Parameters> struct base_aeqd_e { par_aeqd<T> m_proj_parm; // FORWARD(e_forward) elliptical // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(Parameters const& par, T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const { e_forward(lp_lon, lp_lat, xy_x, xy_y, par, this->m_proj_parm); } // INVERSE(e_inverse) elliptical // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(Parameters const& par, T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const { e_inverse(xy_x, xy_y, lp_lon, lp_lat, par, this->m_proj_parm); } static inline std::string get_name() { return "aeqd_e"; } }; template <typename T, typename Parameters> struct base_aeqd_e_guam { par_aeqd<T> m_proj_parm; // FORWARD(e_guam_fwd) Guam elliptical // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(Parameters const& par, T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const { e_guam_fwd(lp_lon, lp_lat, xy_x, xy_y, par, this->m_proj_parm); } // INVERSE(e_guam_inv) Guam elliptical // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(Parameters const& par, T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const { e_guam_inv(xy_x, xy_y, lp_lon, lp_lat, par, this->m_proj_parm); } static inline std::string get_name() { return "aeqd_e_guam"; } }; template <typename T, typename Parameters> struct base_aeqd_s { par_aeqd<T> m_proj_parm; // FORWARD(s_forward) spherical // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(Parameters const& par, T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const { s_forward(lp_lon, lp_lat, xy_x, xy_y, par, this->m_proj_parm); } // INVERSE(s_inverse) spherical // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(Parameters const& par, T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const { s_inverse(xy_x, xy_y, lp_lon, lp_lat, par, this->m_proj_parm); } static inline std::string get_name() { return "aeqd_s"; } }; }} // namespace detail::aeqd #endif // doxygen /*! \brief Azimuthal Equidistant projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Azimuthal - Spheroid - Ellipsoid \par Projection parameters - lat_0: Latitude of origin (degrees) - guam (boolean) \par Example \image html ex_aeqd.gif */ template <typename T, typename Parameters> struct aeqd_e : public detail::aeqd::base_aeqd_e<T, Parameters> { template <typename Params> inline aeqd_e(Params const& params, Parameters & par) { detail::aeqd::setup_aeqd(params, par, this->m_proj_parm, false, false); } }; /*! \brief Azimuthal Equidistant projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Azimuthal - Spheroid - Ellipsoid \par Projection parameters - lat_0: Latitude of origin (degrees) - guam (boolean) \par Example \image html ex_aeqd.gif */ template <typename T, typename Parameters> struct aeqd_e_guam : public detail::aeqd::base_aeqd_e_guam<T, Parameters> { template <typename Params> inline aeqd_e_guam(Params const& params, Parameters & par) { detail::aeqd::setup_aeqd(params, par, this->m_proj_parm, false, true); } }; /*! \brief Azimuthal Equidistant projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Azimuthal - Spheroid - Ellipsoid \par Projection parameters - lat_0: Latitude of origin (degrees) - guam (boolean) \par Example \image html ex_aeqd.gif */ template <typename T, typename Parameters> struct aeqd_s : public detail::aeqd::base_aeqd_s<T, Parameters> { template <typename Params> inline aeqd_s(Params const& params, Parameters & par) { detail::aeqd::setup_aeqd(params, par, this->m_proj_parm, true, false); } }; #ifndef DOXYGEN_NO_DETAIL namespace detail { // Static projection template <typename BGP, typename CT, typename P> struct static_projection_type<srs::spar::proj_aeqd, srs_sphere_tag, BGP, CT, P> { typedef static_wrapper_fi<aeqd_s<CT, P>, P> type; }; template <typename BGP, typename CT, typename P> struct static_projection_type<srs::spar::proj_aeqd, srs_spheroid_tag, BGP, CT, P> { typedef static_wrapper_fi < typename boost::mpl::if_c < boost::is_same < typename srs::spar::detail::tuples_find_if < BGP, //srs::par4::detail::is_guam srs::spar::detail::is_param<srs::spar::guam>::pred >::type, void >::value, aeqd_e<CT, P>, aeqd_e_guam<CT, P> >::type , P > type; }; BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_BEGIN(aeqd_entry) { bool const guam = pj_get_param_b<srs::spar::guam>(params, "guam", srs::dpar::guam); if (parameters.es && ! guam) return new dynamic_wrapper_fi<aeqd_e<T, Parameters>, T, Parameters>(params, parameters); else if (parameters.es && guam) return new dynamic_wrapper_fi<aeqd_e_guam<T, Parameters>, T, Parameters>(params, parameters); else return new dynamic_wrapper_fi<aeqd_s<T, Parameters>, T, Parameters>(params, parameters); } BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_END BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(aeqd_init) { BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(aeqd, aeqd_entry) } } // namespace detail #endif // doxygen } // namespace projections }} // namespace boost::geometry #endif // BOOST_GEOMETRY_PROJECTIONS_AEQD_HPP
bsd-2-clause
fire-rs-laas/fire-rs-saop
cpp/IMC/Spec/ControlLoops.hpp
4646
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // Automatically generated. * //*************************************************************************** // IMC XML MD5: 4d8734a1111656aac56f803acdc90c22 * //*************************************************************************** #ifndef IMC_CONTROLLOOPS_HPP_INCLUDED_ #define IMC_CONTROLLOOPS_HPP_INCLUDED_ // ISO C++ 98 headers. #include <ostream> #include <string> #include <vector> // IMC headers. #include "../Base/Config.hpp" #include "../Base/Message.hpp" #include "../Base/InlineMessage.hpp" #include "../Base/MessageList.hpp" #include "../Base/JSON.hpp" #include "../Base/Serialization.hpp" #include "../Spec/Enumerations.hpp" #include "../Spec/Bitfields.hpp" namespace IMC { //! Control Loops. class ControlLoops: public Message { public: //! Enable. enum EnableEnum { //! Disable. CL_DISABLE = 0, //! Enable. CL_ENABLE = 1 }; //! Enable. uint8_t enable; //! Control Loop Mask. uint32_t mask; //! Scope Time Reference. uint32_t scope_ref; static uint16_t getIdStatic(void) { return 507; } static ControlLoops* cast(Message* msg__) { return (ControlLoops*)msg__; } ControlLoops(void) { m_header.mgid = ControlLoops::getIdStatic(); clear(); } ControlLoops* clone(void) const { return new ControlLoops(*this); } void clear(void) { enable = 0; mask = 0; scope_ref = 0; } bool fieldsEqual(const Message& msg__) const { const IMC::ControlLoops& other__ = static_cast<const ControlLoops&>(msg__); if (enable != other__.enable) return false; if (mask != other__.mask) return false; if (scope_ref != other__.scope_ref) return false; return true; } uint8_t* serializeFields(uint8_t* bfr__) const { uint8_t* ptr__ = bfr__; ptr__ += IMC::serialize(enable, ptr__); ptr__ += IMC::serialize(mask, ptr__); ptr__ += IMC::serialize(scope_ref, ptr__); return ptr__; } size_t deserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::deserialize(enable, bfr__, size__); bfr__ += IMC::deserialize(mask, bfr__, size__); bfr__ += IMC::deserialize(scope_ref, bfr__, size__); return bfr__ - start__; } size_t reverseDeserializeFields(const uint8_t* bfr__, size_t size__) { const uint8_t* start__ = bfr__; bfr__ += IMC::deserialize(enable, bfr__, size__); bfr__ += IMC::reverseDeserialize(mask, bfr__, size__); bfr__ += IMC::reverseDeserialize(scope_ref, bfr__, size__); return bfr__ - start__; } uint16_t getId(void) const { return ControlLoops::getIdStatic(); } const char* getName(void) const { return "ControlLoops"; } size_t getFixedSerializationSize(void) const { return 9; } void fieldsToJSON(std::ostream& os__, unsigned nindent__) const { IMC::toJSON(os__, "enable", enable, nindent__); IMC::toJSON(os__, "mask", mask, nindent__); IMC::toJSON(os__, "scope_ref", scope_ref, nindent__); } }; } #endif
bsd-2-clause
snazzware/zfext
Snazzware/View/Helper/Form/Date.php
2358
<?php /** * Snazzware Extensions for the Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.snazzware.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to josh@snazzware.com so we can send you a copy immediately. * * @category Snazzware * @copyright Copyright (c) 2011-2012 Josh M. McKee * @license http://www.snazzware.com/license/new-bsd New BSD License */ class Snazzware_View_Helper_Form_Date extends Zend_View_Helper_FormElement { public function Form_Date($name, $value = null, $attribs = null, $options = array()) { if ((isset($options['readonly']) && $options['readonly']===true) || (isset($options['editable']) && $options['editable']===false)) { $xhtml = ''; if (!((isset($options['readonly']) && $options['readonly']===true))) { $xhtml .= "<input type=hidden name='{$name}' value='{$value}' />"; } $xhtml .= $value; return $xhtml; } else { $info = $this->_getInfo($name, $value, $attribs); extract($info); // name, value, attribs, options, listsep, disable // build the element $disabled = ''; if ($disable) { // disabled $disabled = ' disabled="disabled"'; } // XHTML or HTML end tag? $endTag = ' />'; if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) { $endTag= '>'; } $xhtml = '<input type="text"' . ' name="' . $this->view->escape($name) . '"' . ' id="' . $this->view->escape($id) . '"' . ' value="' . $this->view->escape($value) . '"' . $disabled . $this->_htmlAttribs($attribs) . $endTag; $xhtml .= '<script> $(function() { $( "#'. $this->view->escape($id).'" ).datepicker({ showButtonPanel: true, dateFormat: \''.ConfigUtils::get('global','jqueryuiDateFormat','yy-mm-dd').'\' }); }); </script>'; return $xhtml; } } }
bsd-2-clause
danaugrs/gokoban
vendor/github.com/g3n/engine/audio/audio_file.go
6764
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package audio import ( "fmt" "github.com/g3n/engine/audio/al" "github.com/g3n/engine/audio/ov" "io" "os" "unsafe" ) // AudioInfo represents the information associated to an audio file type AudioInfo struct { Format int // OpenAl Format Channels int // Number of channels SampleRate int // Sample rate in hz BitsSample int // Number of bits per sample (8 or 16) DataSize int // Total data size in bytes BytesSec int // Bytes per second TotalTime float64 // Total time in seconds } // AudioFile represents an audio file type AudioFile struct { wavef *os.File // Pointer to wave file opened filed (nil for vorbis) vorbisf *ov.File // Pointer to vorbis file structure (nil for wave) info AudioInfo // Audio information structure looping bool // Looping flag } // NewAudioFile creates and returns a pointer to a new audio file object and an error func NewAudioFile(filename string) (*AudioFile, error) { // Checks if file exists _, err := os.Stat(filename) if err != nil { return nil, err } af := new(AudioFile) // Try to open as a wave file if af.openWave(filename) == nil { return af, nil } // Try to open as an ogg vorbis file if af.openVorbis(filename) == nil { return af, nil } return nil, fmt.Errorf("Unsuported file type") } // Close closes the audiofile func (af *AudioFile) Close() error { if af.wavef != nil { return af.wavef.Close() } return ov.Clear(af.vorbisf) } // Read reads decoded data from the audio file func (af *AudioFile) Read(pdata unsafe.Pointer, nbytes int) (int, error) { // Slice to access buffer bs := (*[1 << 30]byte)(pdata)[0:nbytes:nbytes] // Reads wave file directly if af.wavef != nil { n, err := af.wavef.Read(bs) if err != nil { return 0, err } if !af.looping { return n, nil } if n == nbytes { return n, nil } // EOF reached. Position file at the beginning _, err = af.wavef.Seek(int64(waveHeaderSize), 0) if err != nil { return 0, nil } // Reads next data into the remaining buffer space n2, err := af.wavef.Read(bs[n:]) if err != nil { return 0, err } return n + n2, err } // Decodes Ogg vorbis decoded := 0 for decoded < nbytes { n, _, err := ov.Read(af.vorbisf, unsafe.Pointer(&bs[decoded]), nbytes-decoded, false, 2, true) // Error if err != nil { return 0, err } // EOF if n == 0 { if !af.looping { break } // Position file at the beginning err = ov.PcmSeek(af.vorbisf, 0) if err != nil { return 0, err } } decoded += n } if nbytes > 0 && decoded == 0 { return 0, io.EOF } return decoded, nil } // Seek sets the file reading position relative to the origin func (af *AudioFile) Seek(pos uint) error { if af.wavef != nil { _, err := af.wavef.Seek(int64(waveHeaderSize+pos), 0) return err } return ov.PcmSeek(af.vorbisf, int64(pos)) } // Info returns the audio info structure for this audio file func (af *AudioFile) Info() AudioInfo { return af.info } // CurrentTime returns the current time in seconds for the current file read position func (af *AudioFile) CurrentTime() float64 { if af.vorbisf != nil { pos, _ := ov.TimeTell(af.vorbisf) return pos } pos, err := af.wavef.Seek(0, 1) if err != nil { return 0 } return float64(pos) / float64(af.info.BytesSec) } // Looping returns the current looping state of this audio file func (af *AudioFile) Looping() bool { return af.looping } // SetLooping sets the looping state of this audio file func (af *AudioFile) SetLooping(looping bool) { af.looping = looping } // openWave tries to open the specified file as a wave file // and if succesfull, sets the file pointer positioned after the header. func (af *AudioFile) openWave(filename string) error { // Open file osf, err := os.Open(filename) if err != nil { return err } // Reads header header := make([]uint8, waveHeaderSize) n, err := osf.Read(header) if err != nil { osf.Close() return err } if n < waveHeaderSize { osf.Close() return fmt.Errorf("File size less than header") } // Checks file marks if string(header[0:4]) != fileMark { osf.Close() return fmt.Errorf("'RIFF' mark not found") } if string(header[8:12]) != fileHead { osf.Close() return fmt.Errorf("'WAVE' mark not found") } // Decodes header fields af.info.Format = -1 af.info.Channels = int(header[22]) + int(header[23])<<8 af.info.SampleRate = int(header[24]) + int(header[25])<<8 + int(header[26])<<16 + int(header[27])<<24 af.info.BitsSample = int(header[34]) + int(header[35])<<8 af.info.DataSize = int(header[40]) + int(header[41])<<8 + int(header[42])<<16 + int(header[43])<<24 // Sets OpenAL format field if possible if af.info.Channels == 1 { if af.info.BitsSample == 8 { af.info.Format = al.FormatMono8 } else if af.info.BitsSample == 16 { af.info.Format = al.FormatMono16 } } else if af.info.Channels == 2 { if af.info.BitsSample == 8 { af.info.Format = al.FormatStereo8 } else if af.info.BitsSample == 16 { af.info.Format = al.FormatStereo16 } } if af.info.Format == -1 { osf.Close() return fmt.Errorf("Unsupported OpenAL format") } // Calculates bytes/sec and total time var bytesChannel int if af.info.BitsSample == 8 { bytesChannel = 1 } else { bytesChannel = 2 } af.info.BytesSec = af.info.SampleRate * af.info.Channels * bytesChannel af.info.TotalTime = float64(af.info.DataSize) / float64(af.info.BytesSec) // Seeks after the header _, err = osf.Seek(waveHeaderSize, 0) if err != nil { osf.Close() return err } af.wavef = osf return nil } // openVorbis tries to open the specified file as an ogg vorbis file // and if succesfull, sets up the player for playing this file func (af *AudioFile) openVorbis(filename string) error { // Try to open file as ogg vorbis vf, err := ov.Fopen(filename) if err != nil { return err } // Get info for opened vorbis file var info ov.VorbisInfo err = ov.Info(vf, -1, &info) if err != nil { return err } if info.Channels == 1 { af.info.Format = al.FormatMono16 } else if info.Channels == 2 { af.info.Format = al.FormatStereo16 } else { return fmt.Errorf("Unsupported number of channels") } totalSamples, err := ov.PcmTotal(vf, -1) if err != nil { ov.Clear(vf) return nil } timeTotal, err := ov.TimeTotal(vf, -1) if err != nil { ov.Clear(vf) return nil } af.vorbisf = vf af.info.SampleRate = info.Rate af.info.BitsSample = 16 af.info.Channels = info.Channels af.info.DataSize = int(totalSamples) * info.Channels * 2 af.info.TotalTime = timeTotal return nil }
bsd-2-clause
robohack/homebrew-core
Formula/influxdb.rb
3544
class Influxdb < Formula desc "Time series, events, and metrics database" homepage "https://influxdata.com/time-series-platform/influxdb/" url "https://github.com/influxdata/influxdb.git", :tag => "v1.3.7", :revision => "2d474a3089bcfce6b472779be9470a1f0ef3d5e4" head "https://github.com/influxdata/influxdb.git" bottle do sha256 "dd015a25882fae3b8b153dae453e93ca51d44b4c397f4da5989cb3411aa6514d" => :high_sierra sha256 "83d2f828a9c5d33699e5a5f3343c63aa1f849a6896d6df4cc7a92ed0e4163889" => :sierra sha256 "8bf5a99e32430483125d00d11c506866c9761faaac22c5d2036546e06da236e9" => :el_capitan end depends_on "gdm" => :build depends_on "go" => :build def install ENV["GOPATH"] = buildpath influxdb_path = buildpath/"src/github.com/influxdata/influxdb" influxdb_path.install Dir["*"] revision = `git rev-parse HEAD`.strip version = `git describe --tags`.strip cd influxdb_path do system "gdm", "restore" system "go", "install", "-ldflags", "-X main.version=#{version} -X main.commit=#{revision} -X main.branch=master", "./..." end inreplace influxdb_path/"etc/config.sample.toml" do |s| s.gsub! "/var/lib/influxdb/data", "#{var}/influxdb/data" s.gsub! "/var/lib/influxdb/meta", "#{var}/influxdb/meta" s.gsub! "/var/lib/influxdb/wal", "#{var}/influxdb/wal" end bin.install "bin/influxd" bin.install "bin/influx" bin.install "bin/influx_tsm" bin.install "bin/influx_stress" bin.install "bin/influx_inspect" etc.install influxdb_path/"etc/config.sample.toml" => "influxdb.conf" (var/"influxdb/data").mkpath (var/"influxdb/meta").mkpath (var/"influxdb/wal").mkpath end plist_options :manual => "influxd -config #{HOMEBREW_PREFIX}/etc/influxdb.conf" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/influxd</string> <string>-config</string> <string>#{HOMEBREW_PREFIX}/etc/influxdb.conf</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/influxdb.log</string> <key>StandardOutPath</key> <string>#{var}/log/influxdb.log</string> <key>SoftResourceLimits</key> <dict> <key>NumberOfFiles</key> <integer>10240</integer> </dict> </dict> </plist> EOS end test do (testpath/"config.toml").write shell_output("#{bin}/influxd config") inreplace testpath/"config.toml" do |s| s.gsub! %r{/.*/.influxdb/data}, "#{testpath}/influxdb/data" s.gsub! %r{/.*/.influxdb/meta}, "#{testpath}/influxdb/meta" s.gsub! %r{/.*/.influxdb/wal}, "#{testpath}/influxdb/wal" end begin pid = fork do exec "#{bin}/influxd -config #{testpath}/config.toml" end sleep 1 output = shell_output("curl -Is localhost:8086/ping") sleep 1 assert_match /X-Influxdb-Version:/, output ensure Process.kill("SIGINT", pid) Process.wait(pid) end end end
bsd-2-clause
mvbattista/homebrew-core
Formula/monetdb.rb
2336
class RRequirement < Requirement fatal true satisfy { which("r") } def message; <<-EOS.undent R not found. The R integration module requires R. Do one of the following: - install R -- run brew install r or brew cask install r-app - remove the --with-r option EOS end end class Monetdb < Formula desc "Column-store database" homepage "https://www.monetdb.org/" url "https://www.monetdb.org/downloads/sources/Jul2017-SP1/MonetDB-11.27.5.tar.xz" sha256 "871ce08f3c4d9113f50a43fb396892b9c52ae891e8bf16431c80416cac0f6bef" bottle do sha256 "d557a98aba92cf4903da6be105616dcff2e2834fb4a451433b833cda389ee664" => :sierra sha256 "0424e83c65eff82b0cd4b53a4cf2b800badc3d4fec6ae0cdc3c24fbf5fc2552a" => :el_capitan sha256 "cc914fbe74bf59327c268c65cd70fbc7a84b6b734af44e5281bbd5592c2b7924" => :yosemite end head do url "https://dev.monetdb.org/hg/MonetDB", :using => :hg depends_on "libtool" => :build depends_on "gettext" => :build depends_on "automake" => :build depends_on "autoconf" => :build end option "with-java", "Build the JDBC driver" option "with-ruby", "Build the Ruby driver" option "with-r", "Build the R integration module" depends_on RRequirement => :optional depends_on "pkg-config" => :build depends_on :ant => :build depends_on "libatomic_ops" => [:build, :recommended] depends_on "pcre" depends_on "readline" # Compilation fails with libedit. depends_on "openssl" depends_on "unixodbc" => :optional # Build the ODBC driver depends_on "geos" => :optional # Build the GEOM module depends_on "gsl" => :optional depends_on "cfitsio" => :optional depends_on "homebrew/php/libsphinxclient" => :optional def install ENV["M4DIRS"] = "#{Formula["gettext"].opt_share}/aclocal" if build.head? system "./bootstrap" if build.head? args = ["--prefix=#{prefix}", "--enable-debug=no", "--enable-assert=no", "--enable-optimize=yes", "--enable-testing=no", "--with-readline=#{Formula["readline"].opt_prefix}"] args << "--with-java=no" if build.without? "java" args << "--with-rubygem=no" if build.without? "ruby" args << "--disable-rintegration" if build.without? "r" system "./configure", *args system "make", "install" end end
bsd-2-clause
Samsung/Dexter
project/dexter-cs/DexterCS/Src/ICLIResultFile.cs
2234
#region Copyright notice /** * Copyright (c) 2018 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System.Collections.Generic; using System.IO; namespace DexterCS { public interface ICLIResultFile { void WriteJsonResultFilePrefix(FileInfo file); void WriteXmlResultFilePrefix(FileInfo xmlResultFile); void WriteXml2ResultFilePrefix(FileInfo xml2ResultFile); void WriteJsonResultFilePostfix(FileInfo file); void WriteXmlResultFilePostfix(FileInfo xmlResultFile); void WriteXml2ResultFilePostfix(FileInfo xml2ResultFile); void WriteJsonResultFileBody(FileInfo jsonResultFile, List<Defect> allDefectList); void WriteXml2ResultFileBody(FileInfo xml2ResultFile, List<Defect> allDefectList, string sourceFileFullPath); void WriteXmlResultFileBody(FileInfo xmlResultFile, List<Defect> allDefectList, string sourceFileFullPath); } }
bsd-2-clause
noahwilliamsson/protokollen
tools/import-registrars.php
1291
#!/usr/bin/env php <?php /** * Import data from http://www.dnssecandipv6.se/rdns/ */ require_once('../php/ProtokollenBase.class.php'); mb_internal_encoding('utf-8'); if($argc != 2) die("Usage: ${argv[0]} <www.dnssecandipv6.se-rdns.html>\n"); $p = new ProtokollenBase(); $filename = $argv[1]; $data = file_get_contents($filename); if(preg_match_all('@>([a-z0-9.-]*)</a>@', $data, $matches)) foreach($matches[1] as $apex) { $rrset = dns_get_record($apex, DNS_SOA); if(empty($rrset)) { echo "Skipping site $apex because of missing SOA in DNS\n"; continue; } $emailDomain = mb_convert_case($apex, MB_CASE_LOWER); $rrset = dns_get_record($apex, DNS_MX); if(empty($rrset)) $emailDomain = NULL; $url = NULL; $hosts = array('www.'. $apex, $apex); foreach($hosts as $host) { $rrset = dns_get_record($host, DNS_ANY); if(empty($rrset)) continue; $url = 'http://'. mb_convert_case($host, MB_CASE_LOWER); break; } $e = $p->getEntityByDomain($apex); if($e === NULL) { echo "Creating entity for $apex\n"; $id = $p->addEntity($apex, $emailDomain, $url, $apex); $e = $p->getEntityById($id); } $p->addEntityTag($e->id, 'Domänregistrarer (.SE)'); $p->addEntitySource($e->id, 'http://www.dnssecandipv6.se/rdns/', NULL, 'http://www.dnssecandipv6.se/rdns/'); }
bsd-2-clause
dtrebbien/homebrew
Library/Homebrew/cmd/audit.rb
30018
require 'formula' require 'utils' require 'extend/ENV' require 'formula_cellar_checks' module Homebrew def audit formula_count = 0 problem_count = 0 strict = ARGV.include? "--strict" if strict && ARGV.formulae.any? && MacOS.version >= :mavericks require "cmd/style" ohai "brew style #{ARGV.formulae.join " "}" style end ENV.activate_extensions! ENV.setup_build_environment ff = if ARGV.named.empty? Formula else ARGV.formulae end output_header = !strict ff.each do |f| fa = FormulaAuditor.new(f, :strict => strict) fa.audit unless fa.problems.empty? unless output_header puts ohai "audit problems" output_header = true end formula_count += 1 problem_count += fa.problems.size puts "#{f.name}:", fa.problems.map { |p| " * #{p}" }, "" end end unless problem_count.zero? ofail "#{problem_count} problems in #{formula_count} formulae" end end end class FormulaText def initialize path @text = path.open("rb", &:read) end def without_patch @text.split("\n__END__").first end def has_DATA? /^[^#]*\bDATA\b/ =~ @text end def has_END? /^__END__$/ =~ @text end def has_trailing_newline? /\Z\n/ =~ @text end def =~ regex regex =~ @text end end class FormulaAuditor include FormulaCellarChecks attr_reader :formula, :text, :problems BUILD_TIME_DEPS = %W[ autoconf automake boost-build bsdmake cmake imake intltool libtool pkg-config scons smake swig ] FILEUTILS_METHODS = FileUtils.singleton_methods(false).join "|" def initialize(formula, options={}) @formula = formula @strict = !!options[:strict] @problems = [] @text = FormulaText.new(formula.path) @specs = %w{stable devel head}.map { |s| formula.send(s) }.compact end def audit_file unless formula.path.stat.mode == 0100644 problem "Incorrect file permissions: chmod 644 #{formula.path}" end if text.has_DATA? and not text.has_END? problem "'DATA' was found, but no '__END__'" end if text.has_END? and not text.has_DATA? problem "'__END__' was found, but 'DATA' is not used" end unless text.has_trailing_newline? problem "File should end with a newline" end end def audit_class if @strict unless formula.test_defined? problem "A `test do` test block should be added" end end if formula.class < GithubGistFormula problem "GithubGistFormula is deprecated, use Formula instead" end if formula.class < ScriptFileFormula problem "ScriptFileFormula is deprecated, use Formula instead" end if formula.class < AmazonWebServicesFormula problem "AmazonWebServicesFormula is deprecated, use Formula instead" end end @@aliases ||= Formula.aliases def audit_deps @specs.each do |spec| # Check for things we don't like to depend on. # We allow non-Homebrew installs whenever possible. spec.deps.each do |dep| begin dep_f = dep.to_formula rescue TapFormulaUnavailableError # Don't complain about missing cross-tap dependencies next rescue FormulaUnavailableError problem "Can't find dependency #{dep.name.inspect}." next end if @@aliases.include?(dep.name) problem "Dependency '#{dep.name}' is an alias; use the canonical name '#{dep.to_formula.name}'." end dep.options.reject do |opt| next true if dep_f.option_defined?(opt) dep_f.requirements.detect do |r| if r.recommended? opt.name == "with-#{r.name}" elsif r.optional? opt.name == "without-#{r.name}" end end end.each do |opt| problem "Dependency #{dep} does not define option #{opt.name.inspect}" end case dep.name when *BUILD_TIME_DEPS next if dep.build? or dep.run? problem <<-EOS.undent #{dep} dependency should be depends_on "#{dep}" => :build Or if it is indeed a runtime denpendency depends_on "#{dep}" => :run EOS when "git" problem "Don't use git as a dependency" when "mercurial" problem "Use `depends_on :hg` instead of `depends_on 'mercurial'`" when "ruby" problem "Don't use ruby as a dependency. We allow non-Homebrew ruby installations." when 'gfortran' problem "Use `depends_on :fortran` instead of `depends_on 'gfortran'`" when 'open-mpi', 'mpich2' problem <<-EOS.undent There are multiple conflicting ways to install MPI. Use an MPIDependency: depends_on :mpi => [<lang list>] Where <lang list> is a comma delimited list that can include: :cc, :cxx, :f77, :f90 EOS end end end end def audit_java_home if text =~ /JAVA_HOME/i && !formula.requirements.map(&:class).include?(JavaDependency) problem "Use `depends_on :java` to set JAVA_HOME" end end def audit_conflicts formula.conflicts.each do |c| begin Formulary.factory(c.name) rescue TapFormulaUnavailableError # Don't complain about missing cross-tap conflicts. next rescue FormulaUnavailableError problem "Can't find conflicting formula #{c.name.inspect}." end end end def audit_options formula.options.each do |o| next unless @strict if o.name !~ /with(out)?-/ && o.name != "c++11" && o.name != "universal" && o.name != "32-bit" problem "Options should begin with with/without. Migrate '--#{o.name}' with `deprecated_option`." end end end def audit_homepage homepage = formula.homepage unless homepage =~ %r[^https?://] problem "The homepage should start with http or https (URL is #{homepage})." end # Check for http:// GitHub homepage urls, https:// is preferred. # Note: only check homepages that are repo pages, not *.github.com hosts if homepage =~ %r[^http://github\.com/] problem "Use https:// URLs for homepages on GitHub (URL is #{homepage})." end # Google Code homepages should end in a slash if homepage =~ %r[^https?://code\.google\.com/p/[^/]+[^/]$] problem "Google Code homepage should end with a slash (URL is #{homepage})." end # Automatic redirect exists, but this is another hugely common error. if homepage =~ %r[^http://code\.google\.com/] problem "Google Code homepages should be https:// links (URL is #{homepage})." end # GNU has full SSL/TLS support but no auto-redirect. if homepage =~ %r[^http://www\.gnu\.org/] problem "GNU homepages should be https:// links (URL is #{homepage})." end # Savannah has full SSL/TLS support but no auto-redirect. # Doesn't apply to the download links (boo), only the homepage. if homepage =~ %r[^http://savannah\.nongnu\.org/] problem "Savannah homepages should be https:// links (URL is #{homepage})." end if homepage =~ %r[^http://((?:trac|tools|www)\.)?ietf\.org] problem "ietf homepages should be https:// links (URL is #{homepage})." end if homepage =~ %r[^http://((?:www)\.)?gnupg.org/] problem "GnuPG homepages should be https:// links (URL is #{homepage})." end # Freedesktop is complicated to handle - It has SSL/TLS, but only on certain subdomains. # To enable https Freedesktop change the url from http://project.freedesktop.org/wiki to # https://wiki.freedesktop.org/project_name. # "Software" is redirected to https://wiki.freedesktop.org/www/Software/project_name if homepage =~ %r[^http://((?:www|nice|libopenraw|liboil|telepathy|xorg)\.)?freedesktop\.org/(?:wiki/)?] if homepage =~ /Software/ problem "The url should be styled `https://wiki.freedesktop.org/www/Software/project_name`, not #{homepage})." else problem "The url should be styled `https://wiki.freedesktop.org/project_name`, not #{homepage})." end end if homepage =~ %r[^http://wiki\.freedesktop\.org/] problem "Freedesktop's Wiki subdomain should be https:// (URL is #{homepage})." end # There's an auto-redirect here, but this mistake is incredibly common too. if homepage =~ %r[^http://packages\.debian\.org] problem "Debian homepage should be https:// links (URL is #{homepage})." end # People will run into mixed content sometimes, but we should enforce and then add # exemptions as they are discovered. Treat mixed content on homepages as a bug. # Justify each exemptions with a code comment so we can keep track here. if homepage =~ %r[^http://[^/]*github\.io/] problem "Github Pages links should be https:// (URL is #{homepage})." end if homepage =~ %r[^http://[^/]*\.apache\.org] problem "Apache homepages should be https:// links (URL is #{homepage})." end # There's an auto-redirect here, but this mistake is incredibly common too. # Only applies to the homepage and subdomains for now, not the FTP links. if homepage =~ %r[^http://((?:build|cloud|developer|download|extensions|git|glade|help|library|live|nagios|news|people|projects|rt|static|wiki|www)\.)?gnome\.org] problem "Gnome homepages should be https:// links (URL is #{homepage})." end end def audit_specs if head_only?(formula) && formula.tap.downcase != "homebrew/homebrew-head-only" problem "Head-only (no stable download)" end if devel_only?(formula) && formula.tap.downcase != "homebrew/homebrew-devel-only" problem "Devel-only (no stable download)" end %w[Stable Devel HEAD].each do |name| next unless spec = formula.send(name.downcase) ra = ResourceAuditor.new(spec).audit problems.concat ra.problems.map { |problem| "#{name}: #{problem}" } spec.resources.each_value do |resource| ra = ResourceAuditor.new(resource).audit problems.concat ra.problems.map { |problem| "#{name} resource #{resource.name.inspect}: #{problem}" } end spec.patches.select(&:external?).each { |p| audit_patch(p) } end if formula.stable && formula.devel if formula.devel.version < formula.stable.version problem "devel version #{formula.devel.version} is older than stable version #{formula.stable.version}" elsif formula.devel.version == formula.stable.version problem "stable and devel versions are identical" end end stable = formula.stable if stable && stable.url =~ /#{Regexp.escape("ftp.gnome.org/pub/GNOME/sources")}/i minor_version = stable.version.to_s[/\d\.(\d+)/, 1].to_i if minor_version.odd? problem "#{stable.version} is a development release" end end end def audit_patches legacy_patches = Patch.normalize_legacy_patches(formula.patches).grep(LegacyPatch) if legacy_patches.any? problem "Use the patch DSL instead of defining a 'patches' method" legacy_patches.each { |p| audit_patch(p) } end end def audit_patch(patch) case patch.url when %r[raw\.github\.com], %r[gist\.github\.com/raw], %r[gist\.github\.com/.+/raw], %r[gist\.githubusercontent\.com/.+/raw] unless patch.url =~ /[a-fA-F0-9]{40}/ problem "GitHub/Gist patches should specify a revision:\n#{patch.url}" end when %r[macports/trunk] problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}" when %r[^http://trac\.macports\.org] problem "Patches from MacPorts Trac should be https://, not http:\n#{patch.url}" when %r[^http://bugs\.debian\.org] problem "Patches from Debian should be https://, not http:\n#{patch.url}" end end def audit_text if text =~ /system\s+['"]scons/ problem "use \"scons *args\" instead of \"system 'scons', *args\"" end if text =~ /system\s+['"]xcodebuild/ problem %{use "xcodebuild *args" instead of "system 'xcodebuild', *args"} end if text =~ /xcodebuild[ (]["'*]/ && text !~ /SYMROOT=/ problem %{xcodebuild should be passed an explicit "SYMROOT"} end if text =~ /Formula\.factory\(/ problem "\"Formula.factory(name)\" is deprecated in favor of \"Formula[name]\"" end end def audit_line(line, lineno) if line =~ /<(Formula|AmazonWebServicesFormula|ScriptFileFormula|GithubGistFormula)/ problem "Use a space in class inheritance: class Foo < #{$1}" end # Commented-out cmake support from default template if line =~ /# system "cmake/ problem "Commented cmake call found" end # Comments from default template if line =~ /# PLEASE REMOVE/ problem "Please remove default template comments" end if line =~ /# Documentation:/ problem "Please remove default template comments" end if line =~ /# if this fails, try separate make\/make install steps/ problem "Please remove default template comments" end if line =~ /# The url of the archive/ problem "Please remove default template comments" end if line =~ /## Naming --/ problem "Please remove default template comments" end if line =~ /# if your formula requires any X11\/XQuartz components/ problem "Please remove default template comments" end if line =~ /# if your formula fails when building in parallel/ problem "Please remove default template comments" end if line =~ /# Remove unrecognized options if warned by configure/ problem "Please remove default template comments" end # FileUtils is included in Formula # encfs modifies a file with this name, so check for some leading characters if line =~ /[^'"\/]FileUtils\.(\w+)/ problem "Don't need 'FileUtils.' before #{$1}." end # Check for long inreplace block vars if line =~ /inreplace .* do \|(.{2,})\|/ problem "\"inreplace <filenames> do |s|\" is preferred over \"|#{$1}|\"." end # Check for string interpolation of single values. if line =~ /(system|inreplace|gsub!|change_make_var!).*[ ,]"#\{([\w.]+)\}"/ problem "Don't need to interpolate \"#{$2}\" with #{$1}" end # Check for string concatenation; prefer interpolation if line =~ /(#\{\w+\s*\+\s*['"][^}]+\})/ problem "Try not to concatenate paths in string interpolation:\n #{$1}" end # Prefer formula path shortcuts in Pathname+ if line =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share|Frameworks)[/'"])} problem "\"(#{$1}...#{$2})\" should be \"(#{$3.downcase}+...)\"" end if line =~ %r[((man)\s*\+\s*(['"])(man[1-8])(['"]))] problem "\"#{$1}\" should be \"#{$4}\"" end # Prefer formula path shortcuts in strings if line =~ %r[(\#\{prefix\}/(bin|include|libexec|lib|sbin|share|Frameworks))] problem "\"#{$1}\" should be \"\#{#{$2.downcase}}\"" end if line =~ %r[((\#\{prefix\}/share/man/|\#\{man\}/)(man[1-8]))] problem "\"#{$1}\" should be \"\#{#{$3}}\"" end if line =~ %r[((\#\{share\}/(man)))[/'"]] problem "\"#{$1}\" should be \"\#{#{$3}}\"" end if line =~ %r[(\#\{prefix\}/share/(info|man))] problem "\"#{$1}\" should be \"\#{#{$2}}\"" end if line =~ %r[depends_on :(automake|autoconf|libtool)] problem ":#{$1} is deprecated. Usage should be \"#{$1}\"" end # Commented-out depends_on if line =~ /#\s*depends_on\s+(.+)\s*$/ problem "Commented-out dep #{$1}" end # No trailing whitespace, please if line =~ /[\t ]+$/ problem "#{lineno}: Trailing whitespace was found" end if line =~ /if\s+ARGV\.include\?\s+'--(HEAD|devel)'/ problem "Use \"if build.#{$1.downcase}?\" instead" end if line =~ /make && make/ problem "Use separate make calls" end if line =~ /^[ ]*\t/ problem "Use spaces instead of tabs for indentation" end if line =~ /ENV\.x11/ problem "Use \"depends_on :x11\" instead of \"ENV.x11\"" end # Avoid hard-coding compilers if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?(gcc|llvm-gcc|clang)['" ]} problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{$3}\"" end if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?((g|llvm-g|clang)\+\+)['" ]} problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{$3}\"" end if line =~ /system\s+['"](env|export)(\s+|['"])/ problem "Use ENV instead of invoking '#{$1}' to modify the environment" end if line =~ /version == ['"]HEAD['"]/ problem "Use 'build.head?' instead of inspecting 'version'" end if line =~ /build\.include\?[\s\(]+['"]\-\-(.*)['"]/ problem "Reference '#{$1}' without dashes" end if line =~ /build\.include\?[\s\(]+['"]with(out)?-(.*)['"]/ problem "Use build.with#{$1}? \"#{$2}\" instead of build.include? 'with#{$1}-#{$2}'" end if line =~ /build\.with\?[\s\(]+['"]-?-?with-(.*)['"]/ problem "Don't duplicate 'with': Use `build.with? \"#{$1}\"` to check for \"--with-#{$1}\"" end if line =~ /build\.without\?[\s\(]+['"]-?-?without-(.*)['"]/ problem "Don't duplicate 'without': Use `build.without? \"#{$1}\"` to check for \"--without-#{$1}\"" end if line =~ /unless build\.with\?(.*)/ problem "Use if build.without?#{$1} instead of unless build.with?#{$1}" end if line =~ /unless build\.without\?(.*)/ problem "Use if build.with?#{$1} instead of unless build.without?#{$1}" end if line =~ /(not\s|!)\s*build\.with?\?/ problem "Don't negate 'build.without?': use 'build.with?'" end if line =~ /(not\s|!)\s*build\.without?\?/ problem "Don't negate 'build.with?': use 'build.without?'" end if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/ problem "Use build instead of ARGV to check options" end if line =~ /def options/ problem "Use new-style option definitions" end if line =~ /def test$/ problem "Use new-style test definitions (test do)" end if line =~ /MACOS_VERSION/ problem "Use MacOS.version instead of MACOS_VERSION" end cats = %w{leopard snow_leopard lion mountain_lion}.join("|") if line =~ /MacOS\.(?:#{cats})\?/ problem "\"#{$&}\" is deprecated, use a comparison to MacOS.version instead" end if line =~ /skip_clean\s+:all/ problem "`skip_clean :all` is deprecated; brew no longer strips symbols\n" + "\tPass explicit paths to prevent Homebrew from removing empty folders." end if line =~ /depends_on [A-Z][\w:]+\.new$/ problem "`depends_on` can take requirement classes instead of instances" end if line =~ /^def (\w+).*$/ problem "Define method #{$1.inspect} in the class body, not at the top-level" end if line =~ /ENV.fortran/ problem "Use `depends_on :fortran` instead of `ENV.fortran`" end if line =~ /depends_on :(.+) (if.+|unless.+)$/ audit_conditional_dep($1.to_sym, $2, $&) end if line =~ /depends_on ['"](.+)['"] (if.+|unless.+)$/ audit_conditional_dep($1, $2, $&) end if line =~ /(Dir\[("[^\*{},]+")\])/ problem "#{$1} is unnecessary; just use #{$2}" end if line =~ /system (["'](#{FILEUTILS_METHODS})["' ])/o system = $1 method = $2 problem "Use the `#{method}` Ruby method instead of `system #{system}`" end if @strict if line =~ /system (["'][^"' ]*(?:\s[^"' ]*)+["'])/ bad_system = $1 unless %w[| < > & ; *].any? { |c| bad_system.include? c } good_system = bad_system.gsub(" ", "\", \"") problem "Use `system #{good_system}` instead of `system #{bad_system}` " end end if line =~ /(require ["']formula["'])/ problem "`#{$1}` is now unnecessary" end end end def audit_caveats caveats = formula.caveats if caveats =~ /setuid/ problem "Don't recommend setuid in the caveats, suggest sudo instead." end end def audit_prefix_has_contents return unless formula.prefix.directory? Pathname.glob("#{formula.prefix}/**/*") do |file| next if file.directory? basename = file.basename.to_s next if Metafiles.copy?(basename) next if %w[.DS_Store INSTALL_RECEIPT.json].include?(basename) return end problem <<-EOS.undent The installation seems to be empty. Please ensure the prefix is set correctly and expected files are installed. The prefix configure/make argument may be case-sensitive. EOS end def audit_conditional_dep(dep, condition, line) quoted_dep = quote_dep(dep) dep = Regexp.escape(dep.to_s) case condition when /if build\.include\? ['"]with-#{dep}['"]$/, /if build\.with\? ['"]#{dep}['"]$/ problem %{Replace #{line.inspect} with "depends_on #{quoted_dep} => :optional"} when /unless build\.include\? ['"]without-#{dep}['"]$/, /unless build\.without\? ['"]#{dep}['"]$/ problem %{Replace #{line.inspect} with "depends_on #{quoted_dep} => :recommended"} end end def quote_dep(dep) Symbol === dep ? dep.inspect : "'#{dep}'" end def audit_check_output(output) problem(output) if output end def audit audit_file audit_class audit_specs audit_homepage audit_deps audit_java_home audit_conflicts audit_options audit_patches audit_text audit_caveats text.without_patch.split("\n").each_with_index { |line, lineno| audit_line(line, lineno+1) } audit_installed audit_prefix_has_contents end private def problem p @problems << p end def head_only?(formula) formula.head && formula.devel.nil? && formula.stable.nil? end def devel_only?(formula) formula.devel && formula.stable.nil? end end class ResourceAuditor attr_reader :problems attr_reader :version, :checksum, :using, :specs, :url, :mirrors, :name def initialize(resource) @name = resource.name @version = resource.version @checksum = resource.checksum @url = resource.url @mirrors = resource.mirrors @using = resource.using @specs = resource.specs @problems = [] end def audit audit_version audit_checksum audit_download_strategy audit_urls self end def audit_version if version.nil? problem "missing version" elsif version.to_s.empty? problem "version is set to an empty string" elsif not version.detected_from_url? version_text = version version_url = Version.detect(url, specs) if version_url.to_s == version_text.to_s && version.instance_of?(Version) problem "version #{version_text} is redundant with version scanned from URL" end end if version.to_s =~ /^v/ problem "version #{version} should not have a leading 'v'" end if version.to_s =~ /_\d+$/ problem "version #{version} should not end with a underline and a number" end end def audit_checksum return unless checksum case checksum.hash_type when :md5 problem "MD5 checksums are deprecated, please use SHA256" return when :sha1 if ARGV.include? "--strict" problem "SHA1 checksums are deprecated, please use SHA256" return else len = 40 end when :sha256 then len = 64 end if checksum.empty? problem "#{checksum.hash_type} is empty" else problem "#{checksum.hash_type} should be #{len} characters" unless checksum.hexdigest.length == len problem "#{checksum.hash_type} contains invalid characters" unless checksum.hexdigest =~ /^[a-fA-F0-9]+$/ problem "#{checksum.hash_type} should be lowercase" unless checksum.hexdigest == checksum.hexdigest.downcase end end def audit_download_strategy if url =~ %r[^(cvs|bzr|hg|fossil)://] || url =~ %r[^(svn)\+http://] problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{$1}` instead" end url_strategy = DownloadStrategyDetector.detect(url) if using == :git || url_strategy == GitDownloadStrategy if specs[:tag] && !specs[:revision] problem "Git should specify :revision when a :tag is specified." end end return unless using if using == :ssl3 || using == CurlSSL3DownloadStrategy problem "The SSL3 download strategy is deprecated, please choose a different URL" elsif using == CurlUnsafeDownloadStrategy || using == UnsafeSubversionDownloadStrategy problem "#{using.name} is deprecated, please choose a different URL" end if using == :cvs mod = specs[:module] if mod == name problem "Redundant :module value in URL" end if url =~ %r[:[^/]+$] mod = url.split(":").last if mod == name problem "Redundant CVS module appended to URL" else problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL" end end end using_strategy = DownloadStrategyDetector.detect('', using) if url_strategy == using_strategy problem "Redundant :using value in URL" end end def audit_urls # Check GNU urls; doesn't apply to mirrors if url =~ %r[^(?:https?|ftp)://(?!alpha).+/gnu/] problem "\"http://ftpmirror.gnu.org\" is preferred for GNU software (url is #{url})." end if mirrors.include?(url) problem "URL should not be duplicated as a mirror: #{url}" end urls = [url] + mirrors # Check a variety of SSL/TLS links that don't consistently auto-redirect # or are overly common errors that need to be reduced & fixed over time. urls.each do |p| # Skip the main url link, as it can't be made SSL/TLS yet. next if p =~ %r[/ftpmirror\.gnu\.org] case p when %r[^http://ftp\.gnu\.org/] problem "ftp.gnu.org mirrors should be https://, not http:// (mirror is #{p})." when %r[^http://[^/]*\.apache\.org/] problem "Apache urls should be https://, not http (url is #{p})." when %r[^http://code\.google\.com/] problem "code.google.com urls should be https://, not http (url is #{p})." when %r[^http://fossies\.org/] problem "Fossies urls should be https://, not http (url is #{p})." when %r[^http://mirrors\.kernel\.org/] problem "mirrors.kernel urls should be https://, not http (url is #{p})." when %r[^http://([^/]*\.|)bintray\.com/] problem "Bintray urls should be https://, not http (url is #{p})." when %r[^http://tools\.ietf\.org/] problem "ietf urls should be https://, not http (url is #{p})." when %r[^http://search\.mcpan\.org/CPAN/(.*)]i problem "MetaCPAN url should be `https://cpan.metacpan.org/#{$1}` (url is #{p})." end end # Check SourceForge urls urls.each do |p| # Skip if the URL looks like a SVN repo next if p =~ %r[/svnroot/] next if p =~ %r[svn\.sourceforge] # Is it a sourceforge http(s) URL? next unless p =~ %r[^https?://.*\b(sourceforge|sf)\.(com|net)] if p =~ /(\?|&)use_mirror=/ problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})." end if p =~ /\/download$/ problem "Don't use /download in SourceForge urls (url is #{p})." end if p =~ %r[^https?://sourceforge\.] problem "Use http://downloads.sourceforge.net to get geolocation (url is #{p})." end if p =~ %r[^https?://prdownloads\.] problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" + "\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/" end if p =~ %r[^http://\w+\.dl\.] problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})." end if p.start_with? "http://downloads" problem "Use https:// URLs for downloads from SourceForge (url is #{p})." end end # Check for Google Code download urls, https:// is preferred # Intentionally not extending this to SVN repositories due to certificate # issues. urls.grep(%r[^http://.*\.googlecode\.com/files.*]) do |u| problem "Use https:// URLs for downloads from Google Code (url is #{u})." end # Check for new-url Google Code download urls, https:// is preferred urls.grep(%r[^http://code\.google\.com/]) do |u| problem "Use https:// URLs for downloads from code.google (url is #{u})." end # Check for git:// GitHub repo urls, https:// is preferred. urls.grep(%r[^git://[^/]*github\.com/]) do |u| problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." end # Check for git:// Gitorious repo urls, https:// is preferred. urls.grep(%r[^git://[^/]*gitorious\.org/]) do |u| problem "Use https:// URLs for accessing Gitorious repositories (url is #{u})." end # Check for http:// GitHub repo urls, https:// is preferred. urls.grep(%r[^http://github\.com/.*\.git$]) do |u| problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." end # Use new-style archive downloads urls.select { |u| u =~ %r[https://.*github.*/(?:tar|zip)ball/] && u !~ %r[\.git$] }.each do |u| problem "Use /archive/ URLs for GitHub tarballs (url is #{u})." end # Don't use GitHub .zip files urls.select { |u| u =~ %r[https://.*github.*/(archive|releases)/.*\.zip$] && u !~ %r[releases/download] }.each do |u| problem "Use GitHub tarballs rather than zipballs (url is #{u})." end end def problem text @problems << text end end
bsd-2-clause
radai-rosenblatt/li-apache-kafka-clients
li-apache-kafka-clients/src/main/java/com/linkedin/kafka/clients/producer/LiKafkaProducer.java
1107
/* * Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
 See License in the project root for license information. */ package com.linkedin.kafka.clients.producer; import com.linkedin.kafka.clients.annotations.InterfaceOrigin; import java.util.concurrent.TimeUnit; import org.apache.kafka.clients.producer.Producer; /** * The general producer interface that allows allows pluggable serializers and deserializers. * LiKafkaProducer has the same interface as open source {@link Producer}. We define the interface separately to allow * future extensions. * @see LiKafkaProducerImpl */ public interface LiKafkaProducer<K, V> extends Producer<K, V> { /** * Flush any accumulated records from the producer. If the close does not complete within the timeout, throws exception. * If the underlying producer does not support bounded flush, this method defaults to {@link #flush()} * TODO: This API is added as a HOTFIX until the API change is available in apache/kafka */ @InterfaceOrigin.LiKafkaClients void flush(long timeout, TimeUnit timeUnit); }
bsd-2-clause
mhowto/crowbar
crowbar/string.cpp
537
#include "crowbar.h" std::stringstream StringLiteral::ss; const char* StringLiteral::getStringLiteral() { return ss.str().c_str(); } void StringLiteral::addToString(char ch) { ss << ch; } void StringLiteral::createStringLiteral() { ss.str(std::string()); ss.clear(); } char* StringLiteral::closeStringLiteral() { std::string temp(ss.str()); ss.str(std::string()); ss.clear(); char* str = new char[temp.length() + 1]; std::strcpy(str, temp.c_str()); return str; }
bsd-2-clause
lattera/freshports
include/tags/FreshPorts-VuXML/header.php
599
<?php # # $Id: header.php,v 1.1.2.4 2003-11-11 16:29:16 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # ?> <body bgcolor="#ffffff" link="#0000cc"> <? # get the minutes (well, actually it's seconds now...) $Minutes = date("s"); if ($Minutes >= 0 and $Minutes < 20) { $Image = "bsdcon-banner1.gif"; } else { if ($Minutes >= 20 and $Minutes < 40) { $Image = "bsdcon-banner2.gif"; } else { $Image = "bsdcon-banner3.gif"; } } ?> <a href="/"> <img src="/images/freshports.jpg" alt="freshports.org - the place for ports" width="512" height="110" border="0"></a>
bsd-2-clause
bramp/p2psim
src/sim/workload/MultiTest.java
1391
package sim.workload; import sim.collections.IntVector; import sim.events.Events; import sim.main.Global; import sim.net.Host; import sim.net.SimpleHost; import sim.net.events.SendEvent; import sim.net.links.NormalLink; import sim.net.multicast.MulticastJoinPacket; import sim.net.multicast.MulticastPacket; import sim.net.router.Router; public class MultiTest { public MultiTest(String[] arglist) throws Exception { IntVector v = new IntVector(); v.add(1); v.add(2); v.add(3); v.remove(0); System.out.println(v); System.exit(0); int lastAddress = Global.hosts.last().getAddress(); Host a = new SimpleHost(lastAddress+1); Host b = new SimpleHost(lastAddress+2); Host c = new SimpleHost(lastAddress+3); new NormalLink(a,Global.hosts.get(0)); new NormalLink(b,Global.hosts.get(100)); new NormalLink(c,Global.hosts.get(3)); Router.createRoutingTables(); int groupAddress = Global.groups.addGroup(a.getAddress()); MulticastJoinPacket p = MulticastJoinPacket.newPacket(b.getAddress(),groupAddress); MulticastJoinPacket p2 = MulticastJoinPacket.newPacket(c.getAddress(),groupAddress); MulticastPacket p3 = MulticastPacket.newPacket(b.getAddress(),groupAddress); Events.add(SendEvent.newEvent(b,p),0); Events.add(SendEvent.newEvent(c,p2),1000); Events.add(SendEvent.newEvent(b,p3),10000); } }
bsd-2-clause
ntkme/github-buttons
test/unit/event.spec.js
995
import { onEvent, onceEvent } from '@/event' describe('Event', () => { let input beforeEach(() => { input = document.body.appendChild(document.createElement('input')) }) afterEach(() => { input.parentNode.removeChild(input) }) describe('onEvent(target, eventName, func)', () => { it('should call the function on event', () => { const spy = sinon.spy() onEvent(input, 'click', spy) input.click() expect(spy) .to.have.been.calledOnce input.click() expect(spy) .to.have.been.calledTwice }) }) describe('onceEvent(target, eventName, func)', () => { it('should call the function on event only once', () => { const spy = sinon.spy() onceEvent(input, 'click', spy) input.click() expect(spy) .to.have.been.calledOnce input.click() expect(spy) .to.have.been.calledOnce input.click() expect(spy) .to.have.been.calledOnce }) }) })
bsd-2-clause
coypoop/npfUI
tests/csrf/test-utility.lua
633
package.path = '../../lib/?.lua' require 'libcsrf' -- it's statistically improbable that it will match this value. local badval = 'd3268e11-e07e-480a-80d1-7c9f4b38b497' local goodval, goodval1, goodval2 assert(not valid_token(badval)) goodval = generate_token() assert(valid_token(goodval)) for i = 1, 50 do goodval1 = generate_token() for i = 1,18 do generate_token() end goodval2 = generate_token() -- token from a while back is still good. assert(valid_token(goodval1)) -- latest token good. assert(valid_token(goodval2)) end -- by now, the initial token expired. assert(not valid_token(goodval)) print("success!")
bsd-2-clause
parenthetical-e/wheelerexp
meta/reproduce_fir.py
5061
"""Reproduce by simulation of FIR estimation using wheelerdata""" import sys, os import numpy as np from numpy.random import RandomState import argparse import json from simfMRI.noise import white from fmrilearn.analysis import fir from wheelerdata.load.meta import get_data from wheelerexp.base import AverageTime from wheelerexp.base import DecomposeExpReproduction from wheelerexp.common import process_exp_argv # --------------------------------------------------------------------------- # Process argv # --------------------------------------------------------------------------- parser = argparse.ArgumentParser( description="Calculate average FIRs using simulated Wheelerdata") parser.add_argument("--name", help="The basename of this experiment") parser.add_argument("--cond", help=("Name from data to use as labels")) parser.add_argument("--index", help=("Name from data for a trial index")) parser.add_argument("--data", help=("The name of the Wheelerdata set")) parser.add_argument("--TR", type=float, help=("The TR of the data")) parser.add_argument("--trname", default="TR", help=("Name of the TRs in data")) parser.add_argument("--smooth", default=False, help=("Smooth data before averaging")) parser.add_argument("--filtfile", default=None, help=("Filter the labels using based on a json file")) parser.add_argument("--n_features", default=10, type=int, help=("The total number of features")) parser.add_argument("--n_univariate", default=None, type=int, help=("The number of boxcar features")) parser.add_argument("--n_accumulator", default=None, type=int, help=("The number of accumulator features")) parser.add_argument("--n_decision", default=None, type=int, help=("The number of decision features")) parser.add_argument("--n_noise", default=None, type=int, help=("The number of noise features")) parser.add_argument("--drift_noise", default=False, type=bool, help=("Add noise to accumulator drift rate")) parser.add_argument("--step_noise", default=False, type=bool, help=("Add noise to accumulator drift rate")) parser.add_argument("--z_noise", default=False, type=bool, help=("Add noise to accumulator drift rate")) parser.add_argument("--drift_noise_param", default='{"loc": 0, "scale" : 0.5}', type=json.loads, help=("Modify Gaussian drift noise")) parser.add_argument("--step_noise_param", default='{"loc" : 0, "scale" : 0.2, "size" : 1}', type=json.loads, help=("Modify Gaussian step noise")) parser.add_argument("--z_noise_param", default='{"low" : 0.01, "high" : 0.5, "size" : 1}', type=json.loads, help=("Modify uniform start value noise")) parser.add_argument("--seed", default=None, help=("Random seed value (initalizes a RandomState() instance")) args = parser.parse_args() prng = None if args.seed != None: prng = RandomState(int(args.seed)) # RTs for Wheelerdata def lookup_cond_to_dt(data): lookup = { "fh" : { "fast" : 2, "slow" : 4, "nan": 0, 1 : 2, 2 : 4, 0 : 0 }, "butterfly" : { "fast" : 4, "slow" : 6, "nan": 0, 1 : 4, 2 : 6, 0 : 0 }, "clock" : { "fast" : 4, "slow" : 6, "nan": 0, 1 : 4, 2 : 6, 0 : 0 }, "polygon" : { "fast" : 1, "slow" : 2, "nan": 0, 1 : 1, 2 : 2, 0 : 0 }, "redgreen" : { "fast" : 1, "slow" : 3, "nan": 0, 1 : 1, 2 : 3, 0 : 0 }, "biasbox" : { "fast" : 1, "slow" : 2, "nan": 0, 1 : 1, 2 : 2, 0 : 0 } } return lookup[data] # Lookup cond_to_rt cond_to_rt = lookup_cond_to_dt(args.data) # --------------------------------------------------------------------------- # BOLD creation vars # --------------------------------------------------------------------------- noise_f=white hrf_f=None hrf_params=None # --------------------------------------------------------------------------- # Setup exp and run # --------------------------------------------------------------------------- data = get_data(args.data) spacetime = AverageTime(fir) exp = DecomposeExpReproduction(spacetime, data, window=15, nsig=3, tr=args.TR) exp.run(args.name, args.cond, args.index, data, cond_to_rt, smooth=args.smooth, filtfile=args.filtfile, TR=args.TR, trname=args.trname, n_features=args.n_features, n_univariate=args.n_univariate, n_accumulator=args.n_accumulator, n_decision=args.n_decision, n_noise=args.n_noise, drift_noise=args.drift_noise, step_noise=args.step_noise, z_noise=args.z_noise, drift_noise_param=args.drift_noise_param, step_noise_param=args.step_noise_param, z_noise_param=args.z_noise_param, noise_f=white, hrf_f=hrf_f, hrf_params=hrf_params, prng=prng)
bsd-2-clause
Bodigrim/katas
src/python/7-List-Filtering.py
186
# http://www.codewars.com/kata/53dbd5315a3c69eed20002dd def filter_list(xs): 'return a new list with the strings filtered out' return [x for x in xs if not isinstance(x, basestring)]
bsd-2-clause
rohe/pysaml2-3
tests/test_75_mongodb.py
2507
from saml2 import BINDING_HTTP_POST from saml2.authn_context import INTERNETPROTOCOLPASSWORD from saml2.client import Saml2Client from saml2.server import Server from saml2.mongo_store import EptidMDB __author__ = 'rolandh' AUTHN = { "class_ref": INTERNETPROTOCOLPASSWORD, "authn_auth": "http://www.example.com/login" } def _eq(l1, l2): return set(l1) == set(l2) def test_flow(): sp = Saml2Client(config_file="servera_conf") idp1 = Server(config_file="idp_conf_mdb") idp2 = Server(config_file="idp_conf_mdb") # clean out database idp1.ident.mdb.db.drop() # -- dummy request --- req_id, orig_req = sp.create_authn_request(idp1.config.entityid) # == Create an AuthnRequest response rinfo = idp1.response_args(orig_req, [BINDING_HTTP_POST]) #name_id = idp1.ident.transient_nameid("id12", rinfo["sp_entity_id"]) resp = idp1.create_authn_response({"eduPersonEntitlement": "Short stop", "surName": "Jeter", "givenName": "Derek", "mail": "derek.jeter@nyy.mlb.com", "title": "The man"}, userid="jeter", authn=AUTHN, **rinfo) # What's stored away is the assertion a_info = idp2.session_db.get_assertion(resp.assertion.id) # Make sure what I got back from MongoDB is the same as I put in assert a_info["assertion"] == resp.assertion # By subject nid = resp.assertion.subject.name_id _assertion = idp2.session_db.get_assertions_by_subject(nid) assert len(_assertion) == 1 assert _assertion[0] == resp.assertion nids = idp2.ident.find_nameid("jeter") assert len(nids) == 1 def test_eptid_mongo_db(): edb = EptidMDB("secret", "idp") e1 = edb.get("idp_entity_id", "sp_entity_id", "user_id", "some other data") print(e1) assert e1.startswith("idp_entity_id!sp_entity_id!") e2 = edb.get("idp_entity_id", "sp_entity_id", "user_id", "some other data") assert e1 == e2 e3 = edb.get("idp_entity_id", "sp_entity_id", "user_2", "some other data") print(e3) assert e1 != e3 e4 = edb.get("idp_entity_id", "sp_entity_id2", "user_id", "some other data") assert e4 != e1 assert e4 != e3 if __name__ == "__main__": test_flow()
bsd-2-clause
elvman/ouzel
ouzel/scene/TextRenderer.hpp
2896
// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_SCENE_TEXTRENDERER_HPP #define OUZEL_SCENE_TEXTRENDERER_HPP #include <string> #include "scene/Component.hpp" #include "math/Color.hpp" #include "gui/BMFont.hpp" #include "graphics/BlendState.hpp" #include "graphics/Buffer.hpp" #include "graphics/Shader.hpp" #include "graphics/Texture.hpp" namespace ouzel { namespace scene { class TextRenderer: public Component { public: static constexpr uint32_t CLASS = Component::TEXT_RENDERER; TextRenderer(const std::string& fontFile, float initFontSize = 1.0F, const std::string& initText = std::string(), Color initColor = Color::WHITE, const Vector2F& initTextAnchor = Vector2F(0.5F, 0.5F)); void draw(const Matrix4F& transformMatrix, float opacity, const Matrix4F& renderViewProjection, bool wireframe) override; void setFont(const std::string& fontFile); inline float getFontSize() const { return fontSize; } void setFontSize(float newFontSize); inline const Vector2F& getTextAnchor() const { return textAnchor; } void setTextAnchor(const Vector2F& newTextAnchor); inline const std::string& getText() const { return text; } void setText(const std::string& newText); inline Color getColor() const { return color; } void setColor(Color newColor); inline const std::shared_ptr<graphics::Shader>& getShader() const { return shader; } inline void setShader(const std::shared_ptr<graphics::Shader>& newShader) { shader = newShader; } inline const std::shared_ptr<graphics::BlendState>& getBlendState() const { return blendState; } inline void setBlendState(const std::shared_ptr<graphics::BlendState>& newBlendState) { blendState = newBlendState; } private: void updateText(); std::shared_ptr<graphics::Shader> shader; std::shared_ptr<graphics::BlendState> blendState; std::shared_ptr<graphics::Buffer> indexBuffer; std::shared_ptr<graphics::Buffer> vertexBuffer; std::shared_ptr<graphics::Texture> texture; std::shared_ptr<graphics::Texture> whitePixelTexture; std::shared_ptr<gui::Font> font; std::string text; float fontSize = 1.0F; Vector2F textAnchor; std::vector<uint16_t> indices; std::vector<graphics::Vertex> vertices; Color color = Color::WHITE; bool needsMeshUpdate = false; }; } // namespace scene } // namespace ouzel #endif // OUZEL_SCENE_TEXTRENDERER_HPP
bsd-2-clause
aletheia7/norm
norm/protolib/src/common/protoVif.cpp
312
/** * @file protoVif.cpp * * @brief Extends ProtoChannel to provide virtual interface access. */ #include "protoVif.h" ProtoVif::ProtoVif() : user_data(NULL) { vif_name[0] = '\0'; vif_name[VIF_NAME_MAX] = '\0'; // to guarantee null termination } ProtoVif::~ProtoVif() { if (IsOpen()) Close(); }
bsd-2-clause
eslint/espree
tests/fixtures/ecma-version/11/bigint/octal.result.js
1683
export default { "type": "Program", "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 6 } }, "range": [ 0, 6 ], "body": [ { "type": "ExpressionStatement", "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 6 } }, "range": [ 0, 6 ], "expression": { "type": "Literal", "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 6 } }, "range": [ 0, 6 ], "value": 0o755n, "raw": "0o755n", "bigint": "0o755" } } ], "sourceType": "script", "tokens": [ { "type": "Numeric", "value": "0o755n", "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 6 } }, "range": [ 0, 6 ] } ] };
bsd-2-clause
goodsenses/Lf
app/partials/pages/index.php
55
<h1>Light Framework</h1> Description and Examples ...
bsd-2-clause
apronchenkov/perfmon
cpu_frequency.cpp
1758
#include "public/perfmon/cpu_frequency.h" #include "public/perfmon.h" #include "public/perfmon/ticks.h" #include <algorithm> #include <chrono> #include <thread> #include <vector> namespace perfmon { namespace internal { namespace { /** Simple estimation of the cpu frequency. */ template <class ClockType, class Rep, class Period> double GetCpuFrequencySampleImpl( const std::chrono::duration<Rep, Period> &sleep_duration) { const auto startTick = ReadTickCounter(); const auto startClock = ClockType::now(); std::this_thread::sleep_for(sleep_duration); const auto stopTick = ReadTickCounter(); const auto stopClock = ClockType::now(); const auto secondsElapsed = std::chrono::duration_cast<std::chrono::duration<double>>(stopClock - startClock) .count(); return TicksElapsed(startTick, stopTick) / secondsElapsed; } template <class Rep, class Period> double GetCpuFrequencySample( const std::chrono::duration<Rep, Period> &sleep_duration) { return GetCpuFrequencySampleImpl<std::chrono::high_resolution_clock>( sleep_duration); } /** Estimation based on median. */ template <class Rep, class Period> double EstimateCpuFrequency( const std::chrono::duration<Rep, Period> &sleep_duration, size_t sample_size) { std::vector<double> sample(sample_size); for (auto &value : sample) { value = GetCpuFrequencySample(sleep_duration); } std::sort(sample.begin(), sample.end()); return sample.at(sample.size() / 2); } } // namespace double EstimateCpuFrequency() { static const auto result = EstimateCpuFrequency(std::chrono::milliseconds(5), 11); return result; } } // namespace internal } // namespace perfmon
bsd-2-clause
gdinwiddie/JdbcLib
test/com/idiacomputing/jdbc/MockUncloseableResultSetJdbcReader.java
3519
/* * MockUncloseableResultSetJdbcReader * * Copyright(c) 2002 by George Dinwiddie Copyright(c) 2005 iDIA Computing, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <UL><LI> Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. <LI> * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. <LI> Neither the name * of the iDIA Computing, LLC nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior * written permission. </UL> * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package com.idiacomputing.jdbc; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import junit.framework.AssertionFailedError; import org.easymock.MockControl; public class MockUncloseableResultSetJdbcReader extends MockJdbcReader { private Collection exceptionsThrown; private Collection exceptionsLogged; public MockUncloseableResultSetJdbcReader() { super(); exceptionsThrown = new HashSet(); exceptionsLogged = new HashSet(); } protected void logUnthrownException(String message, Exception caught) { exceptionsLogged.add(caught); } private void verifyExceptions() throws AssertionFailedError { Iterator it = exceptionsThrown.iterator(); while (it.hasNext()) { Exception thrown = (Exception) it.next(); if (!exceptionsLogged.contains(thrown)) { throw new AssertionFailedError("Unlogged Exception: " + thrown.getMessage()); } } } public void verify() { super.verify(); verifyExceptions(); } protected ResultSet makeMockResultSet() throws SQLException { MockControl resultSetControl = fetchResultSetControl(); ResultSet mockResultSet = (ResultSet) resultSetControl.getMock(); mockResultSet.next(); resultSetControl.setReturnValue(true, 3); resultSetControl.setReturnValue(false); mockResultSet.close(); SQLException e = new SQLException("broken ResultSet"); exceptionsThrown.add(e); resultSetControl.setThrowable(e); resultSetControl.replay(); return mockResultSet; } }
bsd-2-clause
poste9/crud
deps/npm/@angular/forms@2.4.4/src/directives/radio_control_value_accessor.js
8674
/* */ "format cjs"; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Directive, ElementRef, Injectable, Injector, Input, Renderer, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR } from './control_value_accessor'; import { NgControl } from './ng_control'; export var /** @type {?} */ RADIO_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return RadioControlValueAccessor; }), multi: true }; /** * Internal class used by Angular to uncheck radio buttons with the matching name. */ export var RadioControlRegistry = (function () { function RadioControlRegistry() { this._accessors = []; } /** * @param {?} control * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.add = function (control, accessor) { this._accessors.push([control, accessor]); }; /** * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.remove = function (accessor) { for (var /** @type {?} */ i = this._accessors.length - 1; i >= 0; --i) { if (this._accessors[i][1] === accessor) { this._accessors.splice(i, 1); return; } } }; /** * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.select = function (accessor) { var _this = this; this._accessors.forEach(function (c) { if (_this._isSameGroup(c, accessor) && c[1] !== accessor) { c[1].fireUncheck(accessor.value); } }); }; /** * @param {?} controlPair * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype._isSameGroup = function (controlPair, accessor) { if (!controlPair[0].control) return false; return controlPair[0]._parent === accessor._control._parent && controlPair[1].name === accessor.name; }; RadioControlRegistry.decorators = [ { type: Injectable }, ]; /** @nocollapse */ RadioControlRegistry.ctorParameters = function () { return []; }; return RadioControlRegistry; }()); function RadioControlRegistry_tsickle_Closure_declarations() { /** @type {?} */ RadioControlRegistry.decorators; /** * @nocollapse * @type {?} */ RadioControlRegistry.ctorParameters; /** @type {?} */ RadioControlRegistry.prototype._accessors; } /** * \@whatItDoes Writes radio control values and listens to radio control changes. * * Used by {\@link NgModel}, {\@link FormControlDirective}, and {\@link FormControlName} * to keep the view synced with the {\@link FormControl} model. * * \@howToUse * * If you have imported the {\@link FormsModule} or the {\@link ReactiveFormsModule}, this * value accessor will be active on any radio control that has a form directive. You do * **not** need to add a special selector to activate it. * * ### How to use radio buttons with form directives * * To use radio buttons in a template-driven form, you'll want to ensure that radio buttons * in the same group have the same `name` attribute. Radio buttons with different `name` * attributes do not affect each other. * * {\@example forms/ts/radioButtons/radio_button_example.ts region='TemplateDriven'} * * When using radio buttons in a reactive form, radio buttons in the same group should have the * same `formControlName`. You can also add a `name` attribute, but it's optional. * * {\@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'} * * * **npm package**: `\@angular/forms` * * \@stable */ export var RadioControlValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef * @param {?} _registry * @param {?} _injector */ function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) { this._renderer = _renderer; this._elementRef = _elementRef; this._registry = _registry; this._injector = _injector; this.onChange = function () { }; this.onTouched = function () { }; } /** * @return {?} */ RadioControlValueAccessor.prototype.ngOnInit = function () { this._control = this._injector.get(NgControl); this._checkName(); this._registry.add(this._control, this); }; /** * @return {?} */ RadioControlValueAccessor.prototype.ngOnDestroy = function () { this._registry.remove(this); }; /** * @param {?} value * @return {?} */ RadioControlValueAccessor.prototype.writeValue = function (value) { this._state = value === this.value; this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', this._state); }; /** * @param {?} fn * @return {?} */ RadioControlValueAccessor.prototype.registerOnChange = function (fn) { var _this = this; this._fn = fn; this.onChange = function () { fn(_this.value); _this._registry.select(_this); }; }; /** * @param {?} value * @return {?} */ RadioControlValueAccessor.prototype.fireUncheck = function (value) { this.writeValue(value); }; /** * @param {?} fn * @return {?} */ RadioControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ RadioControlValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; /** * @return {?} */ RadioControlValueAccessor.prototype._checkName = function () { if (this.name && this.formControlName && this.name !== this.formControlName) { this._throwNameError(); } if (!this.name && this.formControlName) this.name = this.formControlName; }; /** * @return {?} */ RadioControlValueAccessor.prototype._throwNameError = function () { throw new Error("\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type=\"radio\" formControlName=\"food\" name=\"food\">\n "); }; RadioControlValueAccessor.decorators = [ { type: Directive, args: [{ selector: 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]', host: { '(change)': 'onChange()', '(blur)': 'onTouched()' }, providers: [RADIO_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ RadioControlValueAccessor.ctorParameters = function () { return [ { type: Renderer, }, { type: ElementRef, }, { type: RadioControlRegistry, }, { type: Injector, }, ]; }; RadioControlValueAccessor.propDecorators = { 'name': [{ type: Input },], 'formControlName': [{ type: Input },], 'value': [{ type: Input },], }; return RadioControlValueAccessor; }()); function RadioControlValueAccessor_tsickle_Closure_declarations() { /** @type {?} */ RadioControlValueAccessor.decorators; /** * @nocollapse * @type {?} */ RadioControlValueAccessor.ctorParameters; /** @type {?} */ RadioControlValueAccessor.propDecorators; /** * \@internal * @type {?} */ RadioControlValueAccessor.prototype._state; /** * \@internal * @type {?} */ RadioControlValueAccessor.prototype._control; /** * \@internal * @type {?} */ RadioControlValueAccessor.prototype._fn; /** @type {?} */ RadioControlValueAccessor.prototype.onChange; /** @type {?} */ RadioControlValueAccessor.prototype.onTouched; /** @type {?} */ RadioControlValueAccessor.prototype.name; /** @type {?} */ RadioControlValueAccessor.prototype.formControlName; /** @type {?} */ RadioControlValueAccessor.prototype.value; /** @type {?} */ RadioControlValueAccessor.prototype._renderer; /** @type {?} */ RadioControlValueAccessor.prototype._elementRef; /** @type {?} */ RadioControlValueAccessor.prototype._registry; /** @type {?} */ RadioControlValueAccessor.prototype._injector; } //# sourceMappingURL=radio_control_value_accessor.js.map
bsd-2-clause
yerenkow/copse
copse-core/src/main/java/org/javaz/copse/model/beans/User.java
2881
package org.javaz.copse.model.beans; import org.javaz.copse.model.iface.*; import java.util.*; import java.sql.*; import java.io.Serializable; public class User implements UserI { public static final String F_ID = "id"; public static final String F_COMMENTS = "comments"; public static final String F_ENABLED = "enabled"; public static final String F_NAME = "name"; public static final String F_OAUTH_ID = "oauth_id"; public static final String F_PARENT_ID = "parent_id"; private java.lang.Integer id; private java.lang.String comments; private java.lang.Boolean enabled; private java.lang.String name; private java.lang.String oauthId; private java.lang.Integer parentId; public User () { } public User createNewInstance() { return new User(); } public java.lang.Integer getId() { return id; } public void setId(java.lang.Integer id) { this.id = id; } public Comparable getPrimaryKey() { return id; } public void setGeneratedPrimaryKey(Comparable key) { this.id = ((java.lang.Number) key).intValue(); } public java.lang.String getComments() { return comments; } public void setComments(java.lang.String comments) { this.comments = comments; } public java.lang.Boolean getEnabled() { return enabled; } public void setEnabled(java.lang.Boolean enabled) { this.enabled = enabled; } public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public java.lang.String getOauthId() { return oauthId; } public void setOauthId(java.lang.String oauthId) { this.oauthId = oauthId; } public java.lang.Integer getParentId() { return parentId; } public void setParentId(java.lang.Integer parentId) { this.parentId = parentId; } public Object clone() throws CloneNotSupportedException { User clone = createNewInstance(); clone.setId(getId()); clone.setComments(getComments()); clone.setEnabled(getEnabled()); clone.setName(getName()); clone.setOauthId(getOauthId()); clone.setParentId(getParentId()); return clone; } public Map<String, String> toStringMap() { Map<String, String> h = new HashMap<String, String>(); if(id != null) { h.put(F_ID, "" + getId()); } if(comments != null) { h.put(F_COMMENTS, "" + getComments()); } if(enabled != null) { h.put(F_ENABLED, "" + getEnabled()); } if(name != null) { h.put(F_NAME, "" + getName()); } if(oauthId != null) { h.put(F_OAUTH_ID, "" + getOauthId()); } if(parentId != null) { h.put(F_PARENT_ID, "" + getParentId()); } return h; } }
bsd-2-clause
brunolauze/MonoNative
MonoNative/mscorlib/System/Threading/mscorlib_System_Threading_Monitor.cpp
10370
#include <mscorlib/System/Threading/mscorlib_System_Threading_Monitor.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_TimeSpan.h> namespace mscorlib { namespace System { namespace Threading { //Public Methods void Monitor::Enter(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Enter", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); } void Monitor::Exit(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Exit", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); } void Monitor::Pulse(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Pulse", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); } void Monitor::PulseAll(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "PulseAll", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); } mscorlib::System::Boolean Monitor::TryEnter(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::TryEnter(mscorlib::System::Object obj, mscorlib::System::Int32 millisecondsTimeout) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(millisecondsTimeout).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &millisecondsTimeout; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::TryEnter(mscorlib::System::Object obj, mscorlib::System::TimeSpan timeout) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(timeout).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = (MonoObject*)timeout; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::Wait(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Wait", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::Wait(mscorlib::System::Object obj, mscorlib::System::Int32 millisecondsTimeout) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(millisecondsTimeout).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &millisecondsTimeout; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Wait", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::Wait(mscorlib::System::Object obj, mscorlib::System::TimeSpan timeout) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(timeout).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = (MonoObject*)timeout; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Wait", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::Wait(mscorlib::System::Object obj, mscorlib::System::Int32 millisecondsTimeout, mscorlib::System::Boolean exitContext) { MonoType *__parameter_types__[3]; void *__parameters__[3]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(millisecondsTimeout).name()); __parameter_types__[2] = Global::GetType(typeid(exitContext).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &millisecondsTimeout; __parameters__[2] = reinterpret_cast<void*>(exitContext); MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Wait", NullMonoObject, 3, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } mscorlib::System::Boolean Monitor::Wait(mscorlib::System::Object obj, mscorlib::System::TimeSpan timeout, mscorlib::System::Boolean exitContext) { MonoType *__parameter_types__[3]; void *__parameters__[3]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(timeout).name()); __parameter_types__[2] = Global::GetType(typeid(exitContext).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = (MonoObject*)timeout; __parameters__[2] = reinterpret_cast<void*>(exitContext); MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Wait", NullMonoObject, 3, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } void Monitor::Enter(mscorlib::System::Object obj, mscorlib::System::Boolean lockTaken) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(lockTaken).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &lockTaken; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "Enter", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); } void Monitor::TryEnter(mscorlib::System::Object obj, mscorlib::System::Boolean lockTaken) { MonoType *__parameter_types__[2]; void *__parameters__[2]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(lockTaken).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &lockTaken; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 2, __parameter_types__, __parameters__, NULL); } void Monitor::TryEnter(mscorlib::System::Object obj, mscorlib::System::TimeSpan timeout, mscorlib::System::Boolean lockTaken) { MonoType *__parameter_types__[3]; void *__parameters__[3]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(timeout).name()); __parameter_types__[2] = Global::GetType(typeid(lockTaken).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = (MonoObject*)timeout; __parameters__[2] = &lockTaken; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 3, __parameter_types__, __parameters__, NULL); } void Monitor::TryEnter(mscorlib::System::Object obj, mscorlib::System::Int32 millisecondsTimeout, mscorlib::System::Boolean lockTaken) { MonoType *__parameter_types__[3]; void *__parameters__[3]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameter_types__[1] = Global::GetType(typeid(millisecondsTimeout).name()); __parameter_types__[2] = Global::GetType(typeid(lockTaken).name()); __parameters__[0] = (MonoObject*)obj; __parameters__[1] = &millisecondsTimeout; __parameters__[2] = &lockTaken; Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "TryEnter", NullMonoObject, 3, __parameter_types__, __parameters__, NULL); } mscorlib::System::Boolean Monitor::IsEntered(mscorlib::System::Object obj) { MonoType *__parameter_types__[1]; void *__parameters__[1]; __parameter_types__[0] = Global::GetType(typeid(obj).name()); __parameters__[0] = (MonoObject*)obj; MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Threading", "Monitor", 0, NULL, "IsEntered", NullMonoObject, 1, __parameter_types__, __parameters__, NULL); return *(mscorlib::System::Boolean*)mono_object_unbox(__result__); } } } }
bsd-2-clause
vrutkovs/beehive
beehive4cmd0/__init__.py
118
# -*- coding: utf-8 -*- """ Predecessor of beehive4cmd library. Currently used to provide self-tests for beehive. """
bsd-2-clause
danaugrs/gokoban
vendor/github.com/g3n/engine/camera/orthographic.go
2644
// Copyright 2016 The G3N Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package camera import ( "github.com/g3n/engine/math32" "github.com/g3n/engine/core" ) // Orthographic is an orthographic camera. type Orthographic struct { Camera // Embedded camera left float32 // left plane x coordinate right float32 // right plane x coordinate top float32 // top plane y coordinate bottom float32 // bottom plane y coordinate near float32 // near plane z coordinate far float32 // far plane z coordinate zoom float32 projChanged bool // camera projection parameters changed (needs to recalculates projection matrix) projMatrix math32.Matrix4 // last calculated projection matrix } // NewOrthographic creates and returns a pointer to a new orthographic camera with the specified parameters. func NewOrthographic(left, right, top, bottom, near, far float32) *Orthographic { cam := new(Orthographic) cam.Camera.Initialize() cam.left = left cam.right = right cam.top = top cam.bottom = bottom cam.near = near cam.far = far cam.zoom = 1.0 cam.projChanged = true return cam } // SetZoom sets the zoom factor of the camera. func (cam *Orthographic) SetZoom(zoom float32) { cam.zoom = math32.Abs(zoom) cam.projChanged = true } // Zoom returns the zoom factor of the camera. func (cam *Orthographic) Zoom() float32 { return cam.zoom } // Planes returns the coordinates of the camera planes. func (cam *Orthographic) Planes() (left, right, top, bottom, near, far float32) { return cam.left, cam.right, cam.top, cam.bottom, cam.near, cam.far } // ProjMatrix satisfies the ICamera interface. func (cam *Orthographic) ProjMatrix(m *math32.Matrix4) { if cam.projChanged { cam.projMatrix.MakeOrthographic(cam.left/cam.zoom, cam.right/cam.zoom, cam.top/cam.zoom, cam.bottom/cam.zoom, cam.near, cam.far) cam.projChanged = false } *m = cam.projMatrix } // Project satisfies the ICamera interface and must // be implemented for specific camera types. func (cam *Camera) Project(v *math32.Vector3) (*math32.Vector3, error) { panic("Not implemented") } // Unproject satisfies the ICamera interface and must // be implemented for specific camera types. func (cam *Camera) Unproject(v *math32.Vector3) (*math32.Vector3, error) { panic("Not implemented") } // SetRaycaster satisfies the ICamera interface and must // be implemented for specific camera types. func (cam *Camera) SetRaycaster(rc *core.Raycaster, x, y float32) error { panic("Not implemented") }
bsd-2-clause
fabric-colors/fabric-colors
docs/source/conf.py
10051
# # fabric_colors documentation build configuration file, created by # sphinx-quickstart on Sun Jun 9 14:07:12 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('../../fabric_colors')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'fabric_colors' copyright = u'2013, Calvin Cheng' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import fabric_colors version = fabric_colors.__version__ # The full version, including alpha/beta/rc tags. release = fabric_colors.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'armstrong' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["../_themes", ] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'fabric_colorsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'fabric_colors.tex', u'fabric\\_colors Documentation', u'Calvin Cheng', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'fabric_colors', u'fabric_colors Documentation', [u'Calvin Cheng'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'fabric_colors', u'fabric_colors Documentation', u'Calvin Cheng', 'fabric_colors', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'fabric_colors' epub_author = u'Calvin Cheng' epub_publisher = u'Calvin Cheng' epub_copyright = u'2013, Calvin Cheng' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # If 'no', URL addresses will not be shown. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
bsd-2-clause
MD2Korg/mCerebrum-Utilities
utilities/src/main/java/org/md2k/utilities/storage/StorageType.java
2390
/* * Copyright (c) 2018, The University of Memphis, MD2K Center of Excellence * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.md2k.utilities.storage; /** * Enumeration of storage types * <p> * <ul> * <li><code>"ASSET"</code></li> * <li><code>"SDCARD_APPLICATION"</code></li> * <li><code>"SDCARD_INTERNAL"</code></li> * <li><code>"SDCARD_EXTERNAL"</code></li> * <li><code>"SDCARD_EXTERNAL_PREFERRED"</code></li> * </ul> * </p> */ public enum StorageType { ASSET("ASSET"), SDCARD_APPLICATION("SDCARD_APPLICATION"), SDCARD_INTERNAL("SDCARD_INTERNAL"), SDCARD_EXTERNAL("SDCARD_EXTERNAL"), SDCARD_EXTERNAL_PREFERRED("SDCARD_EXTERNAL_PREFERRED"); private String stringValue; /** * Constructor * @param toString Storage type as a string. */ StorageType(String toString) { stringValue = toString; } /** * Returns the storage type as a string. * @return The storage type as a string. */ @Override public String toString() { return stringValue; } }
bsd-2-clause
angea/corkami
src/HexII/hexII2bin.py
1273
#converts a HexII output back to a file #Ange Albertini, BSD Licence 2014 from sys import argv hexii, bin = argv[1:3] def _3g(s): """splits a string in trigrams""" for i in range(0, len(s), 3): yield s[i:i+2] # we don't need the space separator def convert_char(c): """converts HexII characters to HEX""" if c.startswith("."): return "%02X" % ord(c[1:]) if c == " ": return "00" if c == "##": return "FF" return c with open(hexii, "rb") as f: r = f.readlines() cur_off = 0 d = [] for l in r: if l.strip() == "": continue offset, _, content = l.strip().partition(":") offset = int(offset, 16) # add skipped line(s) if cur_off != offset: d += ["00" ] * (offset - cur_off) cur_off = offset content = content[1:] # there is a space after the offset ':' # "|" is just a delimiter if content.endswith("|"): content = content[:-1] for c in _3g(content): cur_off += 1 d += [convert_char(c)] d = d[:-1] # remove the "]" char # writes the file with open(bin, "wb") as f: f.write("".join(chr(int(c, 16)) for c in d)) # at this stage, we have a HEX representation
bsd-2-clause
EIDSS/EIDSS-Legacy
EIDSS v6/eidss.webclient/Controllers/CommonAggregateController.cs
4113
using System; using System.Collections.Generic; using System.Web.Mvc; using Kendo.Mvc.UI; using bv.model.BLToolkit; using bv.model.Model.Core; using eidss.model.Core; using eidss.model.Reports; using eidss.model.Reports.Common; using eidss.model.Schema; using eidss.web.common.Controllers; using eidss.web.common.Utils; using eidss.webclient.Utils; namespace eidss.webclient.Controllers { [AuthorizeEIDSS] public class CommonAggregateController : BvController { public ActionResult GetFlexFormCase(long root) { var aggCase = ModelStorage.Get(Session.SessionID, root, null, false) as AggregateCaseHeader; if ((aggCase != null) && (aggCase.FFPresenterCase != null) && (aggCase.FFPresenterCase.CurrentObservation.HasValue)) { ModelStorage.Put(Session.SessionID, aggCase.idfAggrCase, aggCase.idfAggrCase, aggCase.FFPresenterCase.CurrentObservation.Value.ToString(), aggCase.FFPresenterCase); var ffDivContent = this.RenderPartialView("FlexFormCase", aggCase); return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ffDivContent }; } return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = Translator.GetMessageString("msgNowTemplate") }; } public ActionResult GetFlexFormDiagnostic(long root) { var aggCase = ModelStorage.Get(Session.SessionID, root, null, false) as AggregateCaseHeader; if ((aggCase != null) && (aggCase.FFPresenterDiagnostic != null) && (aggCase.FFPresenterDiagnostic.CurrentObservation.HasValue)) { ModelStorage.Put(Session.SessionID, aggCase.idfAggrCase, aggCase.idfAggrCase, aggCase.FFPresenterDiagnostic.CurrentObservation.Value.ToString(), aggCase.FFPresenterDiagnostic); var ffDivContent = this.RenderPartialView("FlexFormDiagnostic", aggCase); return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ffDivContent }; } return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = Translator.GetMessageString("msgNowTemplate") }; } public ActionResult GetFlexFormProphylactic(long root) { var aggCase = ModelStorage.Get(Session.SessionID, root, null, false) as AggregateCaseHeader; if ((aggCase != null) && (aggCase.FFPresenterProphylactic != null) && (aggCase.FFPresenterProphylactic.CurrentObservation.HasValue)) { ModelStorage.Put(Session.SessionID, aggCase.idfAggrCase, aggCase.idfAggrCase, aggCase.FFPresenterProphylactic.CurrentObservation.Value.ToString(), aggCase.FFPresenterProphylactic); var ffDivContent = this.RenderPartialView("FlexFormProphylactic", aggCase); return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ffDivContent }; } return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = Translator.GetMessageString("msgNowTemplate") }; } public ActionResult GetFlexFormSanitary(long root) { var aggCase = ModelStorage.Get(Session.SessionID, root, null, false) as AggregateCaseHeader; if ((aggCase != null) && (aggCase.FFPresenterSanitary != null) && (aggCase.FFPresenterSanitary.CurrentObservation.HasValue)) { ModelStorage.Put(Session.SessionID, aggCase.idfAggrCase, aggCase.idfAggrCase, aggCase.FFPresenterSanitary.CurrentObservation.Value.ToString(), aggCase.FFPresenterSanitary); var ffDivContent = this.RenderPartialView("FlexFormSanitary", aggCase); return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = ffDivContent }; } return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = Translator.GetMessageString("msgNowTemplate") }; } } }
bsd-2-clause
d10n/ico2py
example/nano_icon.py
25773
# file generated by ico2py.py import wx import base64 import StringIO b64_nano_90_png = ( 'iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAYAAAA4qEECAAAgAElEQVR42uWdd3gc1b33P2dmt' 'mq16r24ykXGFReKjcHYxjg2YMCmY3qohpCQ0HMhyaWFC+Em3IQ3pAIXQg+9O3RwNy7YsnovVl' 'mttszOzHn/2GLJlmTJGJK87zzPPs9qNTN75nt+51e/57eCf53DDiQDqUA2kCeEGKWq6ghFUfI' 'URSkUQmQIIVIAD+ACJNAjpWy1LKvOsmStaRp7LMuqAGqBvbFXJ9Dzz3w48S8A8FHARcBYl8s1' 'IisrOy81NTXJ7XbjcDiw2+3YbHY0TUPTVBRFRVEUFEUBwLJMDMMgEjGIRCKEwyFCoTCRSJjub' 'r/s7Oxoa25urgC+Bv4CvP//C9ACcABLhRB32e32I0pLJzF+/AScTqeUUgopZZ8L4n8LMdhwJV' 'IeeI4QAtM0+eqrr/j66x2Ew+FyYA3wDhD5fxXoOcC5DofzjKKiooLi4mIKC4ukqqrCNE2klAc' 'B89APVdUwTUPW1dWKqqoq6upqq3Vdfwp4Atjx/wrQKcBfNE1bOmPGTK2kpARFURKgfpsA914V' 'vb5PRiK62L59O199tTUIPANcClj/rkCnAZe5XK7/HDNmrDZ9+nSpqpowTXMIquDbP1RVIxQKs' 'G7dOsrLyxqlZAXwxb8b0IuA34wdW1Iydeo0PB5PQv8OFWAppRSxk3u//xakXDY3N4m1a98Ph8' 'P6vcB//DsA7QTucbvdN8ydexyFhYUYhnHIIAQDPRGH06UoiqJ+22olHA7Ld999R+zd2/YmcC7' 'QcdhWz2Ee84nAK6Wlk5Ydd9x8UlPTpGmahySI0Wuk/uabryu5uXma0+n89gyVEEgp0TRNjBs3' 'TlqWVdLS0vw94GOg5XB8h3IYx/ug3W5/d+nSZeNnzpyFzWbnUFe7jPpzsq21mZ6egCb39/e+J' 'bBj3y1mzDhSzps3fxLwGXD04bi/dhgGqEop/5Sfn3/+vHnzpdPpxLKsb6BOo7Oj66FIZVWlFo' 'kYUlG+O6sphMCyLDF27FicTkfS+++/94JpmscAlf80iVYUxSGlXD9mzNjzTzjhRBwOh/hmIEN' 'UXQqrqbHBqq+vV5xO+3fumgghMAyDvLx8OWvWnFzgS2DcPwtot2VZr48ZM3ba/PnHS1VVD4vL' 'JoQgGOzRKyrL7WsuX01KcjKGYQ6oV79lvS0mTZokZ82anQm8CKT/M4B+Y+LE0gXHHjsXwzD6h' 'M1DAWCQc8yGhjo14A+IG6+8RFqWRcToGylHIhHKysq+dT9cCIGu66K0dBLTp88oBd7+LoG2A+' '8VFBQdN2fOUXJ/CZNS4nQ6BwU77k719PixLKvP5+FwyNq0eYt61cXnybTCApGWmkJEPxDojRv' 'XoygK37adjD/XtGnTZV5e/pHA/35XQP921KjRCxYtWiQty4oHE4kHTkpyY7PZDjr4cDjMu+++' '0xtoKYSgtrbGyslIF7fecJUgHCbF6+kzGQC6rhMKhWhubkpk8b7t8N00TbFo0WKZlZW1Ejj12' 'wb6z1lZWRcfc8yxWJYl4gCrqooQAkVRcLnc+Hy+QZe1qqrs2LGdrKws7HZ7wq0C5KZNm5TfP3' 'yPMC0LLIsUr5fIfgFPd3c3ABUV5aiq+p1JNSCOPvoY1WazPQfYvi2gL8zKyrpw8eIlMj09LfF' 'wqqqQlZUFgMPhwO/3H3RJSykpKytj1KjR9J6surpaOXPqJG3a5NKoFJsGOVmZ6OFwb0+H5uZG' 'Vp5yMlXV1d9JQqq3kU9LS5djx5ZowBtJSUnicAOd63A4frd8+amMG1ci0tJS48uJgoJCfD4fp' 'mni8SQTCoUO6n00NNQTCgUpLCxMAGUYhvzggw+UO350nbDbbBLANCWZ6Wnoup6YIFVV6WhvZ8' '0VqwmHQnR1dX2nrp+UUsyePUdmZmae0NPTc/bhBvrLZcuWOydMGC8dDgctLW0IIUhOTsayTHw' '+H2lpaXR3H/yhLctiw4b1FBQUoCj7lv2WLZvF3NkzWDR/biKiNC2TnOwsdF3vPSHo4QDjx4zm' 'lCULaWhsHMSrkcNSK1LKxGoc6LrY/8TcuccpQnDLUDEcykk/LikpKTr66KOlZVkiFAoRDAYRQ' 'uB2u2hoaETTNAKBAMFgaEBJjuUS2L59G3v37mXMmLGJZJNhGFRUlPP4I/cSCAQSDyktSV5OJu' 'GYRAshqKurIzsrm+RkDzd8fzUNDQ30V5ERQrB16xbiBYUhBkt4vcl98uT7XxvX1x6Ph7y8/Mn' 'AGYcD6GK73X77BRdcKMPhsAiHw+zd2048n9ze3tFH0gbzAIQQdHR0sHnzJoryc8nKyk5IUG1t' 'DatOWUJudhZWL51rSUmq15tQHYqiUF1dyVFHTsVm05g4vgQFq18wox5MHVJaw9DDoOuRhIGOG' '/j9ff/456WlkwD+ZyhZ0IMB/eypp56WbJqmKC+vIBgM0tHRkZhVy7KGHJxIafHhRx9y6w1XUZ' 'Cf18cF3LJ5ExeeteKA1SAti9zsTHQ9nJD8quoazjptGboewe10UpibhWEY/dYKg8HAsDPBgUA' 'Al8uZMO4pKd4D4oP4q7h4hMzLy88gWoM8ZKDvHjly5OwJEyZQUVFJJBKhoaERIcQBr4NFfUII' 'Oju7yMtK40fXXMaOsgpUNVrJ3rR5E+PHjuLoWTP6vY/H48E0o1Lp8/mQlslJJx6HaZoIITh61' 'nTKK/b0u5oCgQA+X9eQvZJYQgm73YGUEq83meTk5MRY0tJSsSwrcT/DMMTcufMALiNKlRg20I' 'WKoly1YsUKWVtb22egg+ngUChEdXXlAeeoqsqnn37MHTdew86ycmw2B4qiEgqF2LF9O7++96d' 'Y1oH6UAJupzP2Dlrb2jj3jFMwDCOhso6dfSQVe/YQz7X0DogAysr6/m8oBQApLRRFIS0tDY8n' 'CSHiKySE3W5P2BspJS6Xi+Li4iOAKYcC9OlTp07N7Oz0CdO0huSrCiFobGygo6Nz/wwfO3fuI' 'Ds9ldOXLeGjz9aRlpaWOP+0pQuZPmVSv8s/euOokQKor69j1aknEw7riXPnHzObYDBAW1tbn4' 'sCgQCjigupqa4csjGM39M0TVJTU7HZbEgJDocrsaI8Hk8CYIfDAcCIESMBbhgW0EIIRdO0W0e' 'MGJXwCg4GctyoNTc3k5GRuc9rkBJdD7NhwwZ+/6t70ZwOvtiwhWSPB1VVKS8v57pLL+wDXH/u' 'YHzCLCPMxHFjE5/Fl/f3Fp3Anj17EvcQAoLBIEdOnUTpuLHs3r1rWOojHA6Tn58XU5cNpKZ6E' '3FDXF2GQiEcjqiKyc7OwW53nEG0jDc0oKWUtxQVFeV4vV45kA7ub3BCCHw+H263u9cDC6qqa1' 'h+0gLmzJgKAmrqG3C5XLS3t5PstjNh3OgBJU4ICIXCqJpKfX0dIwvzyUhLTRg4IQR6WOfyC8+' 'hvKIiMQFCRCXam+zhhqsuZuvWr4bh4kl0PYJhGJimSXt7Z0JdRHW4mSDlaJoWiye8MjMzQwDn' 'DxVoF/CTyZOnyoOZ6/5812AwQLy2F4/idu/aya03XEkwFAKh0BMI4nK5+PTTjzn9eyeR0stvP' 'VBrCPz+Huw2Gxs3buCkBfNwOhz0Pt0wTY6eOZ3kJBfBYCABiN/vx+v1csE5ZyIx6e7u7nfM/R' 'nuSCSCYZi0t3egKIK6uvqEsTUMA1WNBjV2uy3uUYkJEyYCXDJUoFdkZma6s7KyRH8SEP+st+V' 'NJJFNk1AonJh9VVWprKxg4tiRjBlZHL029hCdXZ20trZy3eWriUQGrpALRdDp66a72097ezsX' 'rjodwzQPGJPb5WD65In09PQkfNyOjnZGFBagB4Ncvfoc6uvr+oxZURTKysooL9/T70R3dnbS2' 'dmZ8ER66+949NhbhRUWFklFUUYCRQcDWgFOnTVrjjoQPUAIQVlZGQ0N9f26UooiEstJSotPPv' '2EH11zeSIAiE6SpLq6mnPPOIWsjPRBl7QQCns7Ouj2dbJi6WIK83P7PS+sRzjphHk0NDQkAPH' '5uhhVXEgkYnDKkoU0Njb0yfRFA6j2BJj7H+3t7QmAe6vC3o7Bfl6IyMnJyQFGHgxop9frXZSe' 'nt6vxEopsdlslJXtIjk5uQ9AQgi6u304HI7EdeUVFZSMGsEpS07cl0+WElVVaGtt4forLiIYG' 'jxkV1WFsspqAG79wVUEQ+EBfd8jpx5Bc3MTqqoSiUQIBAKJlTRmVDEOTdDd3X2AVPenIXsDu/' '+YoqzVqCCGw2GcTkdCpYwcOVohyo4dFOj5OTm5ab05cQdGWkF6enpwudx9zlFVlbKyMpKSkhI' 'Pvn37dh762a0EQ+EDpLaoII8RhXlYBzFQNpeLt97/kGlHTKRk9MhE6N+v45+fi4JFKBSmp6eH' 'cDhMyeiocKWnprL4hHl8/vnnCZdsoMBqKAFNXHAikQjBYDBxr8zMTBRFnDAo0EKI63Jzcwc2T' 'ELQ3NyMy+U+YLA+Xxd19XVomh3LsgiFQuRmpHLsnCOxLKsPodFhtzOldEJU+gdVGwJ/Zxcbt2' '7nvDNPTRQXBjq3KD+Pwvw8amuraWlpYc6MqdjttoReXXP5aurqati0aSOWFc2PRF8GgUCA5uY' 'm6uvrBs3c9faw4mOJRIzE3w6HA5craUZ/18V5HUlCiJOzs3MGWcYqjY31ZGVl9alACyGor28g' 'ous0NNTxxhuvY1kWbofGDbf9goK8HArzcynIzWHKpAlkZ2YwY8okUrxeLMvCiD1wPG8SfwBFU' 'fjo83XokQhnrfjegRIS8wJEbAw2m8aqU5fy0GN/xelyc93FZyGcTkQgRGVtPa1t7eTlZLF+/T' 'qam5sJBgN0dnaiqird3T6Skjzk5eUfckEAwGazYbfbc3p68AD+/oBenJSUREpKijQMQwx0s9b' 'WVsaPn9AnIBFCUF1TxZUXncvf3/mQE45fwNNPP8Fd/3knelinrKKKf3z6JfWNjTS1tNHt72Hr' 'zq/5YsNmJowbw7QjJnLE+HGMGlGU0Hfx73z272+w5vKLyMvOJhQLqaWUWFJSXlWLrocxTQtfd' 'zd1jc1U1tRSX1+Hy+Xm0T88wS8e+g2tbe14PEnkZWcxpXQ8jc2tOBwO5s07ji1bNlFXV8eJJy' '4asvoYVNXZNGw2DSBrIKAXjRo1isHYnoZh4Pf7SUtL7yPNgUCAguwMigryUISgvHwPU0sncu2' 'lFxCJRNBUDaGpWIZBT0+ALl83VbV1VNbUUVPXwIefreOl19/lussuYM6R0/alSC2L0cWFXHXJ' 'eftAjqmeXzz0G15/Zy12ux2324Xb5SI9NYWM9DScDgfJSS5+cdsPKcjNYURxAclJSSQluQmHd' 'WYvXsHu8irmzz8+MUldXV2kpKQcBk6KgqpqxDyPyv2BdgClJSXjEyFmv2QL00TXdVJSUhKSZb' 'fbWb9+PWctX4gnyY1pmuz8eieP/fIuwqEweiQChFFVFafdRrI3GZfTSVpqCtMnTzqAprB/6H3' '99y9O/E8IgQD0SIQfXHkJa664CEVR0FQVVVFAgNuTzCfr1nPk1CmcsewkhCKAaDIoEAgipWTu' '7Jls27mb+vo6/H4/WelptLa2kJqaelhKXQ6HHaC4P2PodTgcI71e76BcQsOIACJhCOPRV1VVB' 'eeeeUqiOm3XFFYsPQk9EkHTNFr3tvPkcy9z2uqrmXrcUi65/mY2b9sByIRR6u9797cDfaRD03' 'DY7dhiPrslJZYliYSCTJk4gT88+TfcRUfgLjyCGScs5+Hf/ZGKqhpUVeXs05dx/LFzqKysZG/' '7Xi49fxX19XWHjSMSYxfb+gM6My8vL/9gnDnDMGPpxn2DqaioYNLEcUyZNgW7zYbf383KU5Zg' 'mAZul5Pf/ukpjjl5JVfceBuvvPUeu/ZU89e/vcjc753Ff9z/CMnJnsPGu1AVhTvufZjH/vI0w' 'WCIjKxsMnNy2VVRw60//yXHfm8Vl6z5CZMmlPC/v3uY+oZ6goEAc+fMRFOignQ4qumxlGxaf1' '5HUVpaui2enRrYjwYlthTjS7uquopH77kdMxgkIz1675MWRJPy//X7v/Dju+5D02ycctpKLr7' 'sSpmWkYlpRFj/5efccetNIj8vhytXnztwinQYOeR3P/xU3v/fj4npR86Sd951HwWFRTGyTYhP' 'P/6QB+65Szzz0mvs3L2HtS89xZjiArZs/5rZ06cwuriQmtpaRo8aPaj6HMpwlChI6f1J9AyPx' '0MkorNu3ZcH9SH36WwDu6aw+IR5hPUII4sKcdjtjBlRTFlFFT+5+z6KikbIR377R/kfP79PTp' 'symREFuXJvSxPZ2Tn877Ov8M7HG6mtq//metFu564HHhEXX361fPHlNwn5u1j/6Vq2rPsUt12' 'T55xzrvzTUy/IxUuWs3XHLrnkrEuYdkQpKcnJZBbms+j4uZTt3s1Qs5WDHZGIDtB2gERrmjYu' 'OTmZTZs2kZSUNGCBVcq+kVQwGGLG5IkJ6R43dhRJSW5GjSxi8tyTSUvPko/+/q+iZPRoa0RRg' 'Xjl7y9x9dWXi46ODhGrv8mlp5wh/vH5Bs47Y/kBtK+hHpqmsm7zVnTsXH/tGo6ZPUU0Nu7LeW' 'iaJn7607vlFd+/lptuuUOGwyHxjw/eYfP2HZyxfAkyEGDZSSfyk7vv/0YrK45RJBJhf9cOQFF' 'VrbSrq4uvv96Jw+GQg0mzYZhIGQ0WqqoqmTVtSmJgNlXjhT89yl+feZGK6lp+fMudHDFhvDWy' 'qED59X8/LFatWiHa2tpEPDgJBALiuaf/ys9++QgOh/2QDZHDbpd33vsw9917vzzzjFNEQ0O9j' 'GfWLMtC13Vuu+1mfvnAPeKoI6dz8+13yazsHKnrEU47eRGhUJjxY0eRlZFOS0vLN7QVlhVLE4' 'T6UR1y1I4d2wE+N01TDCY5pmlgWRY2m43q6moml45PeAemZTJ10gT+/PTzTJ46Q555xkqZkZY' 'mNm7cwE9/etsB9ztqzkwmThhHbX0jH366Dk07tM0Huq6Liy75vrV1yyZRVraL/bNEI0cWc8Sk' 'ieK++34h33n7dXH0zJnc88AjApDVtXUIRUERgsUnzKOpqekbAW1ZlohV7A/Qh4qu65ldXV3VQ' 'og/D7Z84/uxfb4uQqEQoWAPpePH9NHdDc2trN/8Fdde/0OyM9KFzaaJ//7vhwgEAv2mVVvb9g' 'Lw/CtvJJLow5IgwIhE5KqzzrMeeOC+AYoHMUsO4oYb1kiP2yYWnrDAmjn7aPHwY3/G6XKhRwy' 'OnT2DLp/vkFeWlFKapiFjHJRdBwAtpVQsy/ofwD24LtRISkqio6OD1tZWPElJFObn7XNrFIVt' 'O3bh9qSwcMFCqSpCWJYln332mURuwtUrxN761Q7aYkBv3LodaQ2frCikRHO45Jtvv63u3dsmv' 'f24i5VVNWzbtiOWQmgRX65bT2ZaijjllNNkQ2MzlZVVCBFlKA2HbNOPVyYMw7BiuXx/f15HF/' 'C+lDI0ULUjXnz1elPYu7eNjo6OWPjrRrKPDbpp2w7mL1hIeqpXCEVh27atIl5EGDOy+ABDG8e' '1qaU1Wuo6FGNod1pr174HIAry+k+KpaV6URSFUCjEli2bsaQUC46fL4SisnN3Oaqi0tnVhc1m' '+wbGUBAOhaQVzf0G+wP6UWATUBYOhxgoPLQsi/z8fFpbW+jp8RPRdXy+bkRMJSqqQmtbG1OnT' 'pd2TUNRFMrL9yTmqrgwj55AsM+9U1NSSPZ46Pb7E/y64QcImrozamNIT+9/i4nXk5xQTbt37w' 'agpGQ8aampdHT5UDWNmrpG7HbHN9LRgYBfmobROIAx5DbAAMpDoRBSIgZKeOfnF9Dd7ae7u5t' 'QKEzr3vYDosdRRYVYUgpFQTbGmJ5Oh10UFRcfUPCNspUElhWtPA9bL4JECBEIBgUgx4wZTZ/Q' 'NX6ekNhixra1tQUpJenpqdgdjij9SxFUVtfidrkO2eGIbRVRIobxxUCJ//jAOsLhcDhOde1NY' 'Y2rj/T0dGlZFj5fl9RNg5bWvfsmwrTIy8nG6XTGC7silsnCptnweDykp/eNTJOTvXLatOnSZr' 'fH/Wg5vMWKMA1DCpCKIkRKSrLVDzlcHjGpVNpinOs4aynu5OTnREn0za17cbkPGWgBmJ1dXTZ' 'g28FKWf6OjvaGpqbGRIeXTz/9pI/OMgxD5OXnmR0dHcLlclHf1Nyn7H/MrOmJupxpSkaNGhmT' 'PAlSMr5kbB9T9vLf3+C5518Vf3vmBctutx2U4tCfBQoGAzIYCiIQhIIh5h49Z38jLmZMm4KIz' 'WFmZmZsfFEDnpudjWUYNDa34HIeMtCYpmHGtnzsPBjQZjgc/mr79u3Y7Xba29upqak+gLaanu' 'qNACS53bK8sroPBaFk7Gga66PXmKbJlClTgSgJpr19LytOXSaPnjNb5ufnyQvOO1uUjB0v7XY' '7Y0aPxtWLYzecJRvs8SnbvtoqENDU1CSOP36eHDmiGLvdjsNh57KLL2DK1Jly+44K3n57LUcd' 'dUyMTtCN3WZj5MgidF2npq6BpKRDT3Lpum7F3Nj6wUpZEG0K8nEoFFyuKIpoaKgnPz+/T0XYN' 'E3dbrNpyR6PmZWVoZZX1fTR43nZWbK2skxomko4rMvCwgIxZcoUtm7dKltb22jfu1euOvM0JZ' 'pX1uVtN19LY2uXrKupUF5/4neAGK5Ui+zMDEpGj2LL9p20t3fg7+6W37/sYtHY2ITL5SQ9I42' 's7FxyctPFotz5BIMWhmFQVlbGiqUnYpkm7e1dhHWdpCT3Ibp2gnA4SI8/0E20UdaBRnt/ioRp' 'mqsnT56qbty4XowZMzaR6AfoCfgjihBmUVEBpmmqgZ4Aq05d2rvOJ2ZNLZWm5rHsDpdiGCaZm' 'Vm88MJzoqvbL5JdTrq7u+nydcndu3ZTXV2t/P3V1zlycqk4f+Vp6JHIIXdCeP3dtVGqlcMmnC' '6nzMnJweVy0dLcLF979WXxyqtviS/XbeSEE05ESsmGDV/KJcdOx+N2iU3bdvDsK28xZcqUQwp' 'YhBCytaXJ3FNe0Qn8CugeTKIBNkQikc66uppcv99Pfn5+Yi8IQiEcCpKSmq60tTWpiqKwu7Kq' 'TwVESikzM9OFFWlDWkkWiqYsWLBQjh8/UezatVPuLq8UoyIRNJsqQiGdbTt3S0DcedMaguHwI' 'fmweiTCBatWcNcvH6G2vlEUF+VjGAZ7xG6EUAiFwsqmrdtpaGqR9957vzAMg+7ubmaVjrZyU+' '2KZUl2l1eSkpqCEAqH0u3Hskyzq6vLDrTZ7fYGvR9Xtb8Ew1M7duy40Waz43K5921rEKAqash' 'ms3uRSEVRZF1Dk/B1+0lLTYnPrLAkUli6KruqLOEdaaakpKpPPvk0M2dOFdt27mZPZTVOh4Oe' 'QJBIJCL++uiDjBsz8pDzwFJKFCH4zX13sfKSa/l83SaZl5stsjMz6QkEqKmrl8FgWFxzzfXC6' '/Wy9oP3kEjeeuM1ZcaEQnHxOWeyedtOMjMyiXtcwxyHjEQidHR0KsA2fYB4oL+c6O9ra2vIyc' 'npQ1OVUuJJTrFZlhlnMolkTxKvvbMWu21fnkKAQAgpzIgi23cpZneTMWnCBOuzT9dZpaWTZCg' 'UprPLR252Jn/41b2sPOXkb5Rsj5eylp90Ivfc/iOSXG5RV9/Exi3b2FVWgaraWbPmB3LOnNly' '9erLWLR4CYsWLeHXj/5aPP3qBzS1tlFWXklOTk6/DK2hDCGihy1f1OMYsB9TfxK9E2gqLh6Ru' '98+balpWpKu64aU0bKX1+vllbfe5cpLz9s/shNSCCmEIgi2qpFwh5wyIoW3/vYHvvhyHW6Xiw' 'njxlCQm0NY1w9LR4SIrvODqy5l8fFzefnN96iqrUNTNc5ZdaY8orSUB/7nD+KCC84lEDBjrqq' 'KaUSbEra2dzBh0ohD0s9SQigUwO/3A2wcDtA4nc6epKSkPssobqUsy1QsaSEQpHiT+cenXwIH' 'tlZTBEJKgQSBZQpTD5HqcXHSguMS5+mRyOHb9Rpjqo4bO5qb14xFRN1SaRiGoqoKWR6Vs1et5' 'Oprb0RIyaOP/oo7b7gM07Bo7+jE6/USGeZ4ogRZKTu7OkWs1cWwgC5JSkoa43K5+v1Sy7IsaU' 'lFKIKkJDc9gSCVlVUJZqimaVRU1bC7opLRo0ZQMqK4X47dt7mtOL6PPO4qGobBTddcQXllFTv' 'LNhMKhbn7xsspzM/j6z2VWFI5pAqPEKCHdd3f3e2wLKu8v2TSYDr6/JycHDRN63cdGRHdiF/n' 'dkf9zp279+xj/Xf7mb5gOaevvpqLrr6Jb7Pp1PBqeRF27NrDE8+9QnFRIS6XCwmUV1aR7E0Zt' 'hGMtYeju7tThkJhLMtaO2iWsZ/PVuXm5jNQ4BAOh2RvzkVGehrbvy7j+GOPQkpJe0cHv/rFHS' 'iKwtKFJxAMBb+zjfEHKyp//0d30N7RyXN/f4OX/vJbli48nq07dpGWljZs/SyEEFJKy+/3KT0' '9AYBhAT1JUdQRBQWFMtbWoU+uTAgVXQ+pvTN6qWmpVNfWJ/zpooJ8Vp99RiIstyz5T+/YGPW3' 'Db5463mCoTChsM7YUcWoqsK6zV/h9XoPSRhCoUAEsPu6/RBt3TZkoE8uKSlx2mya2N8wxHZGS' 'F3Xzd6fJ7ldNDa39nGNeuu7fwWQo1GrICM9rS9lwrL4enc5U6bPPJRxykCPX0gp6fH7awDfoN' '+/X6rviHHjxouBtvxKywxJKZ29PQybzU5PoIfvoDXdYVMhcUPW5eumqq6BpKSkYdcHLcsiHA6' 'JnkAPpmXt6q98NRDQqqqqU/ffNrFfuKsK0Vd3K6rAMK1/C6D7SrjKZ+s34XYdvDVRf/rZMAwz' 'EtGVttZ2AWwF9KECnZKVlT11MLZORA+Z+9tIaTEgjexf+dA0lX988gXZ2VnD6ssU9zZ6/D4DU' 'FujO3YP2mW9t46enJzsEQN9aTQVqGtxrRH3SizLwmG3/9sBbVM13v7go16Js+F4G1hdne2KYR' 'oEonXQjw66gnq9X+D1pg7arUBK0yqylf8AAAuISURBVIgzJfaBHyY9NeXfDujW9naaW9vIyck' 'ZVp8+y7JMX1d7GCHtnZ1dAF/1lxYdEGghxDEHo9FK+ic+HCpv7p91SCmpa2girEcGrJz3l3MG' '8HW1h/w93TYhFDqj/ZxeHJJN6PV+nNudNKi1Ng1T3X/ADqeT1r3t/3ZgNzQ143K7EWIoBHQpA' 'RGJ6Lrf3y2NiK5YlkWPPwDw7HCBLjqI9bUsyzqg8YXb5aKtvZ1QP/sJ/5XdvKraetLS0gfdu9' 'gLZiGEoKO91TQMPcmyLMW0LALBYCuwfVhAx/bJyUH0k0Dp63LEd7dW1tTTurf9W2/MejiPyqo' 'aMjOzh5SDjtVLI6FQyCGEIoSIVtwjkcjaIbuTvb2PGFu9f/UMQlO0cH8qJS09jYuu+zGq+q/v' '5sUrMpW19cPJcUg9HEJKSxAjy8QM4RfDBdo6iFETsYnor78HhQX5bN+1h0vW3IzNpn0nUq2qC' 'qqqoqpqwo8frI3a/gJSXVsf6zAzNI8jEOyJs+WEIgTtHR36UNVGbz/aijYE0fv024jjmhiM6L' 'djTYIp+twrb+Jxu7n9h9eQm5M1aIuI3g8Rv4eqKqiKQiisD3p+TyDAo398ks7OLkzTIiXFS1Z' 'GepRekJpCTnYmGWmpFOTm9In6pJQ47HY2bt3OzrJKxk6YPKTuOoAM9vhFR0enUFQFp8MpOzu7' 'QvRDzx1KwLLd7/dPimeyVFWlpaUZwzDJzc1FSlBVzeoVq+wLzXUdX7efmUdO59X3/sGbH3zIf' '972Q84941SCodCAmbH49zjsdj76Yj3vf/gpO3aV8V8/u420tNQBCR52m415R81CD0cwLAN/d4' 'CG5hb2VFTR3tFJVU0duyqquOnay7ni/LOwevU/3fb1bpafdzkej2dQ8ntszFIIIQIBf3hvR7t' 'z+46vjajmECrQClQfCtDv9vR0T4r7jG1treL1118LZ2ZmqkuXLtNA4nA4ldgE91qm4Pf3SEVR' 'RVKSS5ZOGCfqG5q48JqbeOal17jvpzdTXJDXR3r35RsUKqprWLDiAqSUzJ42mZMXHY/Hk5RIF' '/a3gux2O0fPnN4nQSRElLkvFIFN01AcDoxQKNFdUkrYun0np15wJe2dXRQVFR809G5vbxeZmZ' 'lWW1uT0tLcJizLugM4D+ReIMwwuAlarxl8r7Oz63pA+nw+8dZbb4aB09va2n4aiURm2Ww2keT' '2KKqqGFLuu04I8Pl8QtfD1NU3kp+XixBw6aVXMH36kZxx6RpKxxRz+w+vY/qUSQQCwYSll1KS' 'k5nJm0//gdEji0nxeogYxrCZpdGNTBYWII0YMzUQbevpcjmpqWvgll88yBtvvYcpBQuOO57qX' 'h1p9t+9q6oqW7ZsYteuXXLFaSsidbX1DrO7m2SHY013OGwS/TGzV4eVxOr1flOs75BYu/Z9Ip' 'HIOcDrwKbKykqhaRo1tTXax598oYVC4T406o6OLhM4v7q6RpimKXt6ApSUjGf16ov5/PNNTJx' '2DHOXncX5V/6A5pZWadP2GUyXy8m4saPQNBV/T4BwWP9GRrI3eLoe4Y57HmLc7BPJtwlSk5Pk' 'D9bcgGmZJCUlJSpFDQ31iTZBQghaW1vYunWrzMjIlOXle5Ty8kr+z6rTZdVtP85be9XlhWdNm' 'zLdoWm3Ae8B04cLdIvP56v5+OOP6Ozs/H2v0PKpbdu2AkJu2bJZGIaxsaOjQwgh2Lu3HX9PD8' 'FQqBXID4XCtO3dK4KhEHl5ebEsmY2f/ewu9uypl560fGPJOd8Xy8+/gqdffJX6xiYcdlsfXXm' 'oJBrY111gx+49/OzBXzN57hJ2btjAuw/fzc7KWjlh8nRxzqqzjS1ffSW93hQhhMLGjRt45523' 'qajYg6bZCIVCrFu3jvT0DCEE8vN169RjRo6Q80ePEmHDYGJONo+vPJ1dP75RuXfpkgXTC/I3A' 'm8S/WW7IQFt+HxdH1dWVkCUnB4/PvT7/dWbNm0QPp9PBy5sam4JR/vctVBf34gmZc718465/4' '3LLqK9vlGGQiEKCwsTN+jp0fF6k7n+2uvlw/c/yFlnXcjzr63l6JNXcuLpF/DCq2/FlrkLIRh' 'W6zQRi05N0+SPTz3HjIWnce6l1/K7Pz7BeQvn8cgPruSLHbvlXlMTN994kzlibInV5esiOTlZ' 'fvjhB8R2pJGRkUEwGODFF5/n6quvIz09nZqaGgXLUh4/6wwRjO4fxJISXziMw6Zx8ewj5fOrz' '+OxlStOcmjaB8BDt5x4/MD+ca/j9KiyP6BV7zIhxCtSynuB3wHv5ufnjTGDQdo6u1g8voS/nr' 'MKBFz41LO8vaec7dvLyM8v6HOTvS3N+p6vd9jjoPr93fz6t4/y99deJTcjjbnHHsWqU5cysWQ' 'MKd5kUlO8/XoGlmXR2eWjvbOLXXsq+OuzL/H55+soyEjjkuWLWXbMLKZceB3v/urndPp75PJb' '7hFPPP4nY/6Ji420zDSny6lRVFSEoqjk5eXR2NhIaekkPvnkI6699gbOPvtcFi6cj9ebwuLMF' 'G5buKBPF+AD8j2aRmtPjzzvyWfEhrr6VxUhzrSkDA8GtEaUYRruZ1I+A5pcmjb3gVOWZt715r' 'vMGzOKE8eO4clNm3n2wvNwqCpnPv5nTrz8Km644Uf9Zf+MdR9/iLSseCSKz+fjrHNX8vL9d1L' 'b3MIbn2/k/c3bKSrIQ7PbOWJ8CRPGjSEl2YMeiVBV28AXG7fQ0dGBQ8DEwnxOmjOD8SMKKMrO' 'jDKHdJ2XPvycpcfMksdf/RNx/Y0/iVx3/Q+x2e02h8Mm7XbB2WefJx566BFqa6s5+uhZJCcn8' '9hjf2DZslNpbGzgs88+Yc2Vl/HOZavJ83oHVWnxaDNiWVzz/Mv8fcfOt+46aeGSn7717oBADx' 'iIAS/OLCxY/sQ5Z8m0JJdo9fdww8uv8pdzVqKbJg5Nw6YqnPa7x/nJbx9n4cIlfZg/UkqpKIp' 'obqwPlH+90x3f4uByu1l59pk8esOlHDF6BE67ncU/uJNVC+Yyp7SEj7bsYE9dI109ATRVoSg7' 'i3nTSpk8eiRpXk+sVZDVm9GaMGr3/OUZOuyp+pNPPoseidjjPUZefPE5Vqw4E9M0eeml53nww' 'ft57bV38XqTMc1oF4eTTl7IdDPE3UsWExrGr9c5NU3Of/QxsbWx6X7g5lj6YshA/+bkCeOu/t' 'PZK6WUUlixGXRoWp9BaIrCdc++wMRV53PrLbcQDOr7VdKlFEJh59aNuq+z0w7gdDrFfQ/ez/x' 'RWayYfwyKIiiraeC8n/0X7z70M9K9HhQlFl7LqI40YtucrX76ecRbSrR3+znppp/Lzz7fJHNz' 'c5X47yHGwdZjnD/TNHE4HIm+TkII1n74AbdecTHvX3EJxjDSv4nfl9EjLP7d76lo75hHjIYwl' 'H6/p6e7XQ+8fulFIv6zRon+yf0Mojus88LWrVx6ySUYhnWASRAC4UlOka3NTYLohlIkgm2b1n' 'P8jMkAZKWmEArrrPt6D0dNGoduGBhmrNFVr+bg+9c3E/1DpeT0W/5Trr7iGnHykqWi949O9u7' 'MGE8z9M7xuN12Tll2Mg8uOoGcZM+w+B7xe9o1VY7OSBcvbttxHvBfQORgVUk3cPdT552NM5qA' 'GZSRb0nJskmlbNqwnpqahn4GgpBSSrfHYxtdMl63ogfjxoxlc0UtWqznp2GanL/keF7+6HM6u' 'v1DLp467Ta+2L6LxT+8i0WnrRJ33H5nHCgxmM8dnySXy87td9xBcSTE1Py8QyLVxIVxeelEee' 'zIEQ4Jt+/v3vUrzedOmzppWn6eiAyBwyyBdLeLFRPH88xzzwxY3LRMk4zsHMeokvGGlNLyeDz' 'oqoPKxhbUWCYuLTmZhbOm8tjLb2EfwoZ8KSW/+Muz/OTxv/Ho409w370PoOuRYfWO/ujjT/j9' 'o4/wm7NXon7D3h3BSETcfdIigGMA5/8FK5cnyi3MCJIAAAAASUVORK5CYII=' ) b64_nano_48_png = ( 'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAASc0lEQVRo3r1aeXRV9bX+9u+cc' '+cpNyMZyAQhQDQQDCCgolUEEVGoMx2gWp9jp9e+1UFdr6/D07f6atulr1h9tvqsrTOo4ARIW0' 'XmIQxCAoSQBHJzM97xjPv9cQeTkDC8dr2zVlbuujn33P3t/e29v71/Ifz9lyKElBMM5kwyTfM' 'yIcRkh8NRYbfbi2VZyZUk4WEGDMPoVdVkeyKROGaa5nEi+iQSiWzVdT0MQPu/fjn9HYa7ASyt' 'rp5wXTAYvCEQCHj9/gDcbjeEEGN+iNmCqmro7+9DT09Pore39+2WluY1AN4AEP//AnBLZWXVY' '/X19eOcTpddUZSsfZlnMjOIzv14XdcQjyf0Xbt2dpw82XY3gA8vxBDpAg0vCARyXpg1a/bD06' 'ZND9hsdlkIkTU0bTRZlsVEBDoPBEIIOBwOMXHixBwifLm3t08yTeNvAKx/KABFsd1bV1f32sy' 'ZsxoKC4vYsiwAZ9hIkiTxsaMtptvtFbIsnRMAEYGZybIsLikpRUFB/hWxWGxGJBL5EEDsnA44' 'H+NtNvurX/jCF56sr5+W63Q62TAMGkk/ZmYiQjIZNw4cPCgRMaUphfMBQUSk6zrl5eXj8svnX' '5ebm/fx+Xz2XAAUt9u9YfHi65cXFY0b8n2fU2bom0RkNe3bK02pqSLDTEXIsqxh951HNGCz2f' 'jaaxdO8Pn8ewG4LphCkiSBmUV+fv4L8+dfdYPf72fLskiWZViWleU8EUFVVWTyoKOzw5pdP1n' 'MvmQamk90ktvlQijUBdM04XA4LgQESZLEZWXji8Lh7rJ4PL52rGiOGgHTNGGz2f4wc+bs230+' 'H5iZ7Hb7GfdZloWOjnYYhgHLslhPxvGNr38FJASZhgkhBE6caEV3d/eFlcY0CLfbjbq6i7/sc' 'Dhvu1AKfX/hwkUrxo8vZ0kS8Pt9WYOHJq2madB1HbIsI5FI4Kq5jaKoIJ9yfD5oeqo3SQQU5g' 'WzNBr5+8w+wdkSzMyorKxEcXHxiwAKzxfA3JtuWvbo3LnzWNc18vv9GBgYhGVZSFceMDMkScK' 'R5iPpJLfhVGc73bJkIYGIg8EANE1HIpnErIY61E6ogK7rWe9GIpFRewQzI9NTMiAMw+A5c+bC' '5XI9fz4AnA0NDT+pra21h8PdUFUVfX39YGYYhpF9sBAC4Z4w1NgggsFchHt6MG9GHSZWV8KyL' 'AoG/DAMA21tbVh67dUYlx8EcyqZZVlGU9M+yLI8ahSICEJIsNmUTDRIkiSeNevSOQDmnRVAbm' '7uipqaSfM7O09xONxDQ2ljmmb2CyzLQufJVty8ZBGcLhcOHWjCD799P5KqCmaG3+dJ58dJLLx' '6PirHlyKZSKSNE+jqOg1d18+IQtrjcDodKCwsAgDY7TYwMxUWFnpKS8tWAZDHAuAKBoNPeb0+' 'WJYFwzAy9RnMjPb2dmhaitfHjx/HfzzyXexsOoj+/gE8uOoO2O32rEcVWUEkGsVlMxsgCcKcx' 'ukIdZ2CJEnQNB0lRYVoaWmGEOKMKBARfD4fnE5HuhoCsizB7XajsLDwBgA5YwH4eUPDDFlVVU' '7X9GFVSdd1CCGgaRomlBdjTuN0tLS2wWkTWHzNlcM8apoW2tvbceeyJVA1DQG/HxPKS1J5kUj' 'g6vlzYZMAa4ReyiSwosjo6OiEy+VM09eEy+VCMJibGwgE5owGIHfq1Lo7XS43M3NWjGWS1rJM' 'EBEkSYKqJjGv8WLY3W5Eo3FMmViJYI5/mDqMxGLwuu2YMqkapmlB13UsW7wAx1uPIamqKC4sw' 'FduWYqOjo6sg2KxWJaefX39SCaTiEZjEILSmolQUFAAIrp3NACLJ06s8ZmmSRnahEIhDA4OpA' 'EwmC3YbDaEuzpx43ULAGbouoaGukmw2WyfAxCEU6dDuLShHj6vB0QE3TCwYP48nOrsRDwex8S' 'qClw5bzYMTU0rUh2dnZ1ZykYiEZimCWaGmeroiMcTcLmcyM3NvXYkAKmqqvoyh8OhZPgohEBb' '2wl4van6r6oqNE1DW1sbbl+6ELk5AUBIkGXC7EumZSOV6eIHDx/B4mvmDyuJdrsd06bWoKcnj' 'NqJVfB7PaitLkM8Hocsy5BlGbqun9FrMkBUVYWuG1xaWoah1UgA8Pl8/nmKomQTNiURkrDb7R' 'BC4NChA2hra8X27VsR6unDf//xVWzZsg0TKipgt9nR3dMLTUvVeVmSsWPffty0eAGYGYORKHr' '7+tF5ugvzZl0CNRFHIpFAy/ETYEPHhg0f4JNPPkZT0z7s2bM7W64z0ci8TldEKigoBIBLMgBk' 'r9eb63K5aoferGkabLaUdIjFYphcXY6BeBEua5yGu790K8I9vejpH8B37luFdz7YBDBw+dyZK' 'C0qhKqq+Oqty+F0OmBZjL99uh3h3j7YbDZoahL5AQ+aj51ATsCH25YtwZ/eXIfGxkbs2rULl1' 'zSiHMNQ06nEwDGZyPudruvq6mZtMzlcmWnqUQijmg0iuLiEnz8yRY8/vC38dxLr+KnP/gWios' 'K8fKad/D0H/4IWZJw78oVuGjKJHjdbljpKlJdWQ7DSIW+qmI86qdOxsVTa1FVMR6/eOoZfLxt' 'B/oHBnDjogUoys/Fxo+3wS4BObn5GDogjTUA7dmz+xCAtRkKzfN6vchUn1QzMSHLMjRNQ2VpA' 'SZNrMa0qZPg93pw5Y13YvUf12LOVTdwa6+Ohx/7NXTdyHptKA0zOZGZkb+46iHMv3ox33X/d9' 'nmL+FpV92IyTXVSEYHcMWcRmhq4lxjKAOALMveLCBFsdV3dnZA13Ue2VA6Ojux6vblME0DSxd' 'dg/u/9whPnTGP33jzHXbYZUQjg9h58Diaj7Vmy91o+sZus2H1H17CgsXLALbw103vY0J1NZ79' '/YtY+a0fwef14M7lS9EdCp11IZBiCMMwjOzwL1uWNeHEiRN6SUmp8rlQE9B1HWoygRnT6uD1e' 'FCYH2S2++nnP/05/+THD+M3v3mCALDP56Unn/Xjd7/8KVRNG03bsGWZVFI1BY99+585FDpNAL' 'Bz5zbcd99D/Isn/oseuHsFz5hWRw5FACMiOPJKq4HsqCnC4W5IkvT+8ERxIRKJoDAvCJfDASL' 'CX7fsoHvv+4YVHeynZ55ZneEq6bqBN9e9D8UmYzSFzMwkhMQdp7qsjPGp8mjg+eefowVXXsWN' 's+fR1h17UF1eCk3TxjSeiBCNRgHg5NAy+qosK58N1ek2mw2xeAyySHVfXddBigO1k2ro6NEWJ' 'BIJcqfbvGkaGIhEEBmMYSz6KnYH1q17mwryc7MQB/oH0dzczF2h07Ry5SpuPt4KVdMgy/JZB5' '3BgX4AODUUwDdjsUic2Ro6DbHb5cGRlqOcnrZQkJ/PToeDTp06xfl5wWz3daR/RxPxUT1HAIM' 'E9fT00ITqquyg7/a4AYBOnjyBmTNnE5jR2zcAkabQKJFkIspMd9uGAlBPnz7dHo1GTU3TMDg4' 'AMuyqKio0Np/6BDphsGKoqAoPw/MjGAwF5qmYfasmSzLMm69fQV/uOEvDIsxKoeISNdUVlWVA' '34fFxYUEAC+bO5sVFVWcF5ePgQBAb8X0UQSAI3uiNSbVv/AAAAcGqaFTNPcGwqFYqFQiDOTk8' 'vpMFwut9V5OkSSJKGkMIeImGtqakiSFVSUjuN/unsljy8uwCt/fgmBgG+sHQpLxERsUijUTbf' 'dfBN/6c5b6bqFi3jd+o00efJUPrC/CROrKjipGThbFdV1XcTj8dBoW4kOu912j2maOZWVVQAI' 'uq4akiRJuTk+mtUwDcGAD3ZFZlewmI62tGDjpg3I8Xuw6aPNYD1BK26+EUZ66BmZxFJ6wnr6h' 'T+jvLSI7IqE997/EIePtNCcufPIgyjbJaJ3N2+Fz+8fc16OxaI4cuTwOl3XXzljrRKNxircbv' 'fsqqoqWJYFIYSRTMSkUChEdyxbAtNiJiMhJFMzZ865EmveWkuffLqdSovH0Uu/ewKCxgw9DMP' 'ApTMbcLj5KN5+bxOajx6HYnfiwQe/RTmBHN536Ajt3L6FO7r7yeFwjtnEurtDdPJk22913cjm' 'QDblDUPfPG5c8TfTiyiWJdkhy5K5bXdTqrkwk8vlYrAuFdoN/stbf8KOnTtRXzcZNkUZpkhHu' '6LRGJ77zeP44KOPEe7pxcJrr8XOA0fR0XGSfG4n9veljD/btiIt73cOfX9ozbqyvLw8I2fJNE' '2T2RKmZaGltQ0VZSX45g//jRRFweOP/AslVRWN0y/m9F7zrBIgIy8Mw8RVl10KAthiprJcB+t' 'GL02qyMcupwsmh0dtYszMzBZFIoPxRCJxYtSRsqSkdLGiKFkPqFrSYgblBnOwa+9+qKqG5dcv' 'xMrbvwhN17Mbg6Fy91zLquykx0xEhC3bd9MNd9yF7nAf+gajYwo5IiJN06xYNNrCPPwMIQNgZ' 'm1tbX5mLQ4AuqYRAHi8HrQcPwGH3Y7ZM6ahumI8TNM8L6PPdlmWhVV3fBGdBz9FYUEeQj19kC' 'VpzPrf39fDSVU7NPIQJA2ALgoGc12WZQ1RpCkAkiQhFk8ABBimiXPR5ULWh6qmIRqNIZFIINz' 'bD2kUAKnzBrYGB/tFNBrdPfI4SgBAeXn5VCGEnDIsRSFN15gIYMuCw24/z0X5hYNI0VVDV7h3' 'DMcQopEBS9f1eCKR3D3aYsvh8Xgqh6BngGBZJgMEwzThcTnPe0V+oZcQAvsOHYHDMfoW3TA0P' 'RLpo3C4Nw5g72gAZEWR8z7X4Sm/s2UJAHA4HGht68is3P/hAGRJwo7dTcjJCYx2IMh9fT1kmq' 'YU6g63A+gaDYAkhOzKho+ZARIg4tQwomDz1h0IhcNjCq2hS6mhf8+8zkxqqZ/h90uShAOHW+D' '3+c8YvSzLgpqMk6qqSCQSa8Zc7g49RRGSRCBAkMjuhBxOJ+777qOIxGKw22zDDM0MQG6XE870' '7DCUHi3HW/H8n1/HK2vXY/2Gj7Bj737EE8nUokwIqJqGltaTUBR52HMJgJpMmtFoVOoKdQPAu' 'rFOaEReXt7CgoLCGlVV0dLSjLzcPMSiEcs0TUFEiMaiCIV78fuXXuO8YIBm1NdBN4zstnnHnv' '340c/+EwePtGBG/dRh1cThsKNkXBEK8nJhmhaOtbZB03VUlJaAwVi64h4kNBMlJSXpJgYAxEI' 'Iam9vVbdu29nV19cvmPmBsQCYbrensaioaPb69e9s1zR9Q1lZWX0sGmHTNIQkSTh29LjmdLnU' '7p5e26Kld+DJp3+HmuoKtisK2e02mIaJ5UsW4pr5c4cpamaGTVHg9biR4/ehvLQY0y+egmDAj' '8PNx/jWrz1A0YTJHq+PAoFARoNh7949JCTSjzY1KRU+b0I3rc+csrwmYRj6yONXKU2h6o6O9o' 'a+vr5ZkcigUVFRsXzTpo1Nfp+3cCASpXBXd1fQpkSEwxV49tmnUd8wB2++86H16fYd4rMjRzC' 'uqADjy4rBANgangtCCNgUBU6nA8fbO/DaW+/i5VfeQPvBA6R4gtwwczafDnXR7t274Ha7EI1G' 'EA53Y9feffTU9QvFv1+/yDOvqrys2O97MKZp5R0Dg00A+kee1E8BUAvgdQB2p9N5KpFI3KM4n' 'c8GFcW7vG4Kz68sp+e6+vitd9+jZNJANBIxtv1ts6zrOv/6qV9TwCEwrWE6li68GnW1NZAkAo' 'PQ3dODt9/fhLfXf4Daonw4JIFZUyby8+/9BQ89+pi1YdNGsXr1kzR58hS0trZi8eIl6Bsc5NC' 'Wv9L/3H4za6ZJlBqVaCCZxCPvfjD48t6mmwBsPONfDTw2G6KaBpsknlk1s/FrcyrGw6XY2GO3' 'UTQSwbh7HkJ946WwLAuyLPOebVtMXdPkV9a8ieWT8tF88hTe2LwFAZ8XksMOXTfgkQXmT78IV' '0y/KCXqwHhh/Ub46i83Hrj/69KaNe/Q5Ml1WLv2DeTm5uGrX12BJ375K1zRcQzFXs/IisZ+hw' 'N3vfx67KU9e2cBODha61v4xNLr37xrVqM9qevMYAIIn3V0Yt+kenzt/oeg6xoDRPFYzPxs3x7' 'qPH1KbF37Ir7/lVvxg9Uv4Du33Ygcb2pTB6QkiGFakITA3sPNePdEH5787WqORjVSFBtbVmor' 'LoRAR0cHXvzeQ1g5eSKkEeIuA0I1DLrv9TUfrP/syNKRWyTvysYZP1xaN8U+mEyyZppkWAzDs' 'jClZBw+euNlyEqqsjMzu9xuUVZZxeNLy/hQVx90w8A3brkBj7/4GixmJDUdSU2HYVoQRNi89w' 'C2DQg8+uPHOBbTCQAbhk6WZcE0TQgB/Opn/4olJUWQJWnUIygA5FQULJ5ce01Nfl7N/wJXFUx' 'mPrWJMAAAAABJRU5ErkJggg==' ) b64_nano_16_png = ( 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADRUlEQVQ4y2WRW2ibdRjGf+8/S' 'Zvm2KWhbdrZdoeaNl0Pw7VG1FTYxuaq6Oamgu5iKujFEBx44YWol7vY1WCwCxU8ouKt4BScY0' '48lA1k7XqIodo0adouzeFrvib5vr83tgz2XL0vPM/Ly+8R7lcokRh/LxAIHlFKPQC4tdYrpmn' '+cevWzfMrK7nr95rl3mVgYN+5WCx2wePxAuj8ep7mYPOWR9u2LdPTty9PTk6+sZVxbA1DQ8MX' 'R0fH3lXKoavVqihd1z6vR93Nr+N2uxERAWhvjxwQkUA2m7kCoADi8fhLiUTiLIBSSrLZrD594' 'kllW5bubG2mVqtvf6m1pr8/dq6hoWFg+0Bn587PCoWiLhQKBL2NtLYE5fDBxxFtycvHJ9gwSp' 'hmBRGhpSWE2+3W4+NPnAdQIyP73wwEglQqFTGMDc6cmiC+f4C6WWVsOMYjoyM0NbqI7e2mVCq' 'xurqGZVni8/knAFRbW/szlmXpsmHgsE2yy8tEd/dgbm5y9GCCm39NEWxy4mtUJJPziAi2beP3' '+wG6neVy+aFwOCxBr5vnjh7hx8kUmYVZDo0/Sji0A6/Hw+1UTitfq4yPDZM3bZQS/mfaoAyjf' 'K2x0a1DAS+Rrl5+u/EzX3z9DU6XExEhvbymf7n+k8zNThON9mHZNgAbGwZAzlkul78sFtefrl' 'WKVt/eLtXb+6Ds6unWtWpVADaMksQfPsDJk88TdNVRStBa62KxKEBBzc/PXVHKwVJuTRqoyjt' 'nz+hXTh2TWt0CYHRkkNdePEG0p4OFxSUcDgciIqZZmQRwRqN9h71eH0oJ6cwynZF2iYQHt3uv' '1mq8cPwpFpeyWJYFWqOUYnUldwNAdXR0PKa11pZVx+V0bcG5T3t2dZH6Nw2AYZRIp9PfAyin0' '+Wt1ari9Xi4+NGnKAHbtvlncQmlFHfmkkzNzGGaJpmVPA6Hg+mZO6wXit8BOLSmM5vNXMuurQ' '3nZuZJPHva9efvv0qkLUwotAPLtllIprj8ybd6am5eVvN5/f5gf72/rdV/Nfn3D85UKnnp9fj' 'oq28ljrVlbIgN7cMoG/bVrz5WwYCf3p0RauVNPrhwiermpp79/EOJFu+6Ent2v93kdPn/Aw+m' 'YmKFWQebAAAAAElFTkSuQmCC' ) def _get_icon(b64): image_bytes = base64.b64decode(b64) image_stream = StringIO.StringIO(image_bytes) image = wx.ImageFromStream(image_stream) bitmap = wx.BitmapFromImage(image) icon = wx.EmptyIcon() icon.CopyFromBitmap(bitmap) return icon def get_icon_bundle(): icon_bundle = wx.IconBundle() nano_90_png = _get_icon(b64_nano_90_png) nano_48_png = _get_icon(b64_nano_48_png) nano_16_png = _get_icon(b64_nano_16_png) icon_bundle.AddIcon(nano_90_png) icon_bundle.AddIcon(nano_48_png) icon_bundle.AddIcon(nano_16_png) return icon_bundle
bsd-2-clause
Submanifold/psalm
FairingAlgorithms/FairingAlgorithm.cpp
301
/*! * @file FairingAlgorithm.cpp * @brief Implementation of generic functions for fairing algorithms */ #include "FairingAlgorithm.h" namespace psalm { /*! * Empty constructor */ FairingAlgorithm::FairingAlgorithm() { } FairingAlgorithm::~FairingAlgorithm() { } } // end of namespace "libpsalm"
bsd-2-clause
WojciechMula/toys
000helpers/linux-perf-events-demo.cpp
522
#include "linux-perf-events.h" #include <cstdio> int main() { LinuxEvents<PERF_TYPE_HARDWARE> misses(PERF_COUNT_HW_BRANCH_MISSES); LinuxEvents<PERF_TYPE_HARDWARE> branches(PERF_COUNT_HW_BRANCH_INSTRUCTIONS); misses.start(); branches.start(); for (int i=0; i < 100; i++) { printf("sample instruction %d\n", i); } const auto b = branches.end(); const auto m = misses.end(); puts(""); printf("branches: %lu, misses: %lu (miss ratio: %0.2f%%)\n", b, m, (100.0 * m)/b); }
bsd-2-clause
crdschurch/crds-signin-checkin
front_end/src/app/shared/services/http-client.service.ts
2776
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { CookieService } from 'angular2-cookie/core'; import { User, MachineConfiguration } from '../models'; import { Observable } from 'rxjs/Observable'; import { UserService } from './user.service'; @Injectable() export class HttpClientService { constructor(private http: Http, private cookie: CookieService, private userService: UserService) {} get(url: string, options?: RequestOptions) { let requestOptions = this.getRequestOption(options); return this.extractAuthToken(this.http.get(url, requestOptions)); } put(url: string, data: any, options?: RequestOptions) { let requestOptions = this.getRequestOption(options); return this.extractAuthToken(this.http.put(url, data, requestOptions)); } post(url: string, data: any, options?: RequestOptions) { let requestOptions = this.getRequestOption(options); return this.extractAuthToken(this.http.post(url, data, requestOptions)); } private getUser(): User { return this.userService.getUser(); } private extractAuthToken(o: any) { let sharable = o.share(); sharable.subscribe( (res: Response) => { let user = this.getUser(); if (res.headers.get('Authorization')) { user.token = res.headers.get('Authorization'); }; if (res.headers.get('RefreshToken')) { user.refreshToken = res.headers.get('RefreshToken'); } this.userService.setUser(user); }, (error) => { return Observable.throw(error || 'Server error'); }); return sharable; } private getRequestOption(options?: RequestOptions): RequestOptions { let reqOptions = options || new RequestOptions(); reqOptions.headers = this.createAuthorizationHeader(reqOptions.headers); return reqOptions; } private createAuthorizationHeader(headers?: Headers) { let reqHeaders = headers || new Headers(); let user = this.getUser(); reqHeaders.set('Authorization', user.token); reqHeaders.set('RefreshToken', user.refreshToken); reqHeaders.set('Content-Type', 'application/json'); reqHeaders.set('Accept', 'application/json, text/plain, */*'); reqHeaders.set('Crds-Api-Key', process.env.ECHECK_API_TOKEN); const machineConfig = MachineConfiguration.fromJson( this.cookie.getObject(MachineConfiguration.COOKIE_NAME_DETAILS) ); if (machineConfig) { if (machineConfig.CongregationId) { reqHeaders.set('Crds-Site-Id', machineConfig.CongregationId.toString()); } if (machineConfig.KioskIdentifier) { reqHeaders.set('Crds-Kiosk-Identifier', machineConfig.KioskIdentifier); } } return reqHeaders; } }
bsd-2-clause
jriehl/numba
numba/cuda/cudadrv/drvapi.py
14667
from __future__ import print_function, absolute_import, division from ctypes import * from . import _extras cu_device = c_int cu_device_attribute = c_int # enum cu_context = c_void_p # an opaque handle cu_module = c_void_p # an opaque handle cu_jit_option = c_int # enum cu_jit_input_type = c_int # enum cu_function = c_void_p # an opaque handle cu_device_ptr = c_size_t # defined as unsigned int on 32-bit # and unsigned long long on 64-bit machine cu_stream = c_void_p # an opaque handle cu_event = c_void_p cu_link_state = c_void_p cu_function_attribute = c_int cu_ipc_mem_handle = (c_byte * _extras.CUDA_IPC_HANDLE_SIZE) # 64 bytes wide cu_occupancy_b2d_size = CFUNCTYPE(c_size_t, c_int) API_PROTOTYPES = { # CUresult cuInit(unsigned int Flags); 'cuInit' : (c_int, c_uint), # CUresult cuDriverGetVersion ( int* driverVersion ) 'cuDriverGetVersion': (c_int, POINTER(c_int)), # CUresult cuDeviceGetCount(int *count); 'cuDeviceGetCount': (c_int, POINTER(c_int)), # CUresult cuDeviceGet(CUdevice *device, int ordinal); 'cuDeviceGet': (c_int, POINTER(cu_device), c_int), # CUresult cuDeviceGetName ( char* name, int len, CUdevice dev ) 'cuDeviceGetName': (c_int, c_char_p, c_int, cu_device), # CUresult cuDeviceGetAttribute(int *pi, CUdevice_attribute attrib, # CUdevice dev); 'cuDeviceGetAttribute': (c_int, POINTER(c_int), cu_device_attribute, cu_device), # CUresult cuDeviceComputeCapability(int *major, int *minor, # CUdevice dev); 'cuDeviceComputeCapability': (c_int, POINTER(c_int), POINTER(c_int), cu_device), # CUresult cuDevicePrimaryCtxGetState ( CUdevice dev, unsigned int* flags, int* active ) 'cuDevicePrimaryCtxGetState': (c_int, cu_device, POINTER(c_uint), POINTER(c_int)), # CUresult cuDevicePrimaryCtxRelease ( CUdevice dev ) 'cuDevicePrimaryCtxRelease': (c_int, cu_device), # CUresult cuDevicePrimaryCtxReset ( CUdevice dev ) 'cuDevicePrimaryCtxReset': (c_int, cu_device), # CUresult cuDevicePrimaryCtxRetain ( CUcontext* pctx, CUdevice dev ) 'cuDevicePrimaryCtxRetain': (c_int, POINTER(cu_context), cu_device), # CUresult cuDevicePrimaryCtxSetFlags ( CUdevice dev, unsigned int flags ) 'cuDevicePrimaryCtxSetFlags': (c_int, cu_device, c_uint), # CUresult cuCtxCreate(CUcontext *pctx, unsigned int flags, # CUdevice dev); 'cuCtxCreate': (c_int, POINTER(cu_context), c_uint, cu_device), # CUresult cuCtxGetDevice ( CUdevice * device ) 'cuCtxGetDevice': (c_int, POINTER(cu_device)), # CUresult cuCtxGetCurrent (CUcontext *pctx); 'cuCtxGetCurrent': (c_int, POINTER(cu_context)), # CUresult cuCtxPushCurrent (CUcontext pctx); 'cuCtxPushCurrent': (c_int, cu_context), # CUresult cuCtxPopCurrent (CUcontext *pctx); 'cuCtxPopCurrent': (c_int, POINTER(cu_context)), # CUresult cuCtxDestroy(CUcontext pctx); 'cuCtxDestroy': (c_int, cu_context), # CUresult cuModuleLoadDataEx(CUmodule *module, const void *image, # unsigned int numOptions, # CUjit_option *options, # void **optionValues); 'cuModuleLoadDataEx': (c_int, cu_module, c_void_p, c_uint, POINTER(cu_jit_option), POINTER(c_void_p)), # CUresult cuModuleUnload(CUmodule hmod); 'cuModuleUnload': (c_int, cu_module), # CUresult cuModuleGetFunction(CUfunction *hfunc, CUmodule hmod, # const char *name); 'cuModuleGetFunction': (c_int, cu_function, cu_module, c_char_p), # CUresult cuModuleGetGlobal ( CUdeviceptr* dptr, size_t* bytes, CUmodule # hmod, const char* name ) 'cuModuleGetGlobal': (c_int, POINTER(cu_device_ptr), POINTER(c_size_t), cu_module, c_char_p), # CUresult CUDAAPI cuFuncSetCacheConfig(CUfunction hfunc, # CUfunc_cache config); 'cuFuncSetCacheConfig': (c_int, cu_function, c_uint), # CUresult cuMemAlloc(CUdeviceptr *dptr, size_t bytesize); 'cuMemAlloc': (c_int, POINTER(cu_device_ptr), c_size_t), # CUresult cuMemsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N) 'cuMemsetD8': (c_int, cu_device_ptr, c_uint8, c_size_t), # CUresult cuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc, # size_t N, CUstream hStream); 'cuMemsetD8Async': (c_int, cu_device_ptr, c_uint8, c_size_t, cu_stream), # CUresult cuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, # size_t ByteCount); 'cuMemcpyHtoD': (c_int, cu_device_ptr, c_void_p, c_size_t), # CUresult cuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, # size_t ByteCount, CUstream hStream); 'cuMemcpyHtoDAsync': (c_int, cu_device_ptr, c_void_p, c_size_t, cu_stream), # CUresult cuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, # size_t ByteCount); 'cuMemcpyDtoD': (c_int, cu_device_ptr, cu_device_ptr, c_size_t), # CUresult cuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, # size_t ByteCount, CUstream hStream); 'cuMemcpyDtoDAsync': (c_int, cu_device_ptr, cu_device_ptr, c_size_t, cu_stream), # CUresult cuMemcpyDtoH(void *dstHost, CUdeviceptr srcDevice, # size_t ByteCount); 'cuMemcpyDtoH': (c_int, c_void_p, cu_device_ptr, c_size_t), # CUresult cuMemcpyDtoHAsync(void *dstHost, CUdeviceptr srcDevice, # size_t ByteCount, CUstream hStream); 'cuMemcpyDtoHAsync': (c_int, c_void_p, cu_device_ptr, c_size_t, cu_stream), # CUresult cuMemFree(CUdeviceptr dptr); 'cuMemFree': (c_int, cu_device_ptr), # CUresult cuStreamCreate(CUstream *phStream, unsigned int Flags); 'cuStreamCreate': (c_int, POINTER(cu_stream), c_uint), # CUresult cuStreamDestroy(CUstream hStream); 'cuStreamDestroy': (c_int, cu_stream), # CUresult cuStreamSynchronize(CUstream hStream); 'cuStreamSynchronize': (c_int, cu_stream), # CUresult cuLaunchKernel(CUfunction f, unsigned int gridDimX, # unsigned int gridDimY, # unsigned int gridDimZ, # unsigned int blockDimX, # unsigned int blockDimY, # unsigned int blockDimZ, # unsigned int sharedMemBytes, # CUstream hStream, void **kernelParams, # void ** extra) 'cuLaunchKernel': (c_int, cu_function, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, c_uint, cu_stream, POINTER(c_void_p), POINTER(c_void_p)), # CUresult cuMemHostAlloc ( void ** pp, # size_t bytesize, # unsigned int Flags # ) 'cuMemHostAlloc': (c_int, c_void_p, c_size_t, c_uint), # CUresult cuMemFreeHost ( void * p ) 'cuMemFreeHost': (c_int, c_void_p), # CUresult cuMemHostRegister(void * p, # size_t bytesize, # unsigned int Flags) 'cuMemHostRegister': (c_int, c_void_p, c_size_t, c_uint), # CUresult cuMemHostUnregister(void * p) 'cuMemHostUnregister': (c_int, c_void_p), # CUresult cuMemHostGetDevicePointer(CUdeviceptr * pdptr, # void * p, # unsigned int Flags) 'cuMemHostGetDevicePointer': (c_int, POINTER(cu_device_ptr), c_void_p, c_uint), # CUresult cuMemGetInfo(size_t * free, size_t * total) 'cuMemGetInfo' : (c_int, POINTER(c_size_t), POINTER(c_size_t)), # CUresult cuEventCreate ( CUevent * phEvent, # unsigned int Flags ) 'cuEventCreate': (c_int, POINTER(cu_event), c_uint), # CUresult cuEventDestroy ( CUevent hEvent ) 'cuEventDestroy': (c_int, cu_event), # CUresult cuEventElapsedTime ( float * pMilliseconds, # CUevent hStart, # CUevent hEnd ) 'cuEventElapsedTime': (c_int, POINTER(c_float), cu_event, cu_event), # CUresult cuEventQuery ( CUevent hEvent ) 'cuEventQuery': (c_int, cu_event), # CUresult cuEventRecord ( CUevent hEvent, # CUstream hStream ) 'cuEventRecord': (c_int, cu_event, cu_stream), # CUresult cuEventSynchronize ( CUevent hEvent ) 'cuEventSynchronize': (c_int, cu_event), # CUresult cuStreamWaitEvent ( CUstream hStream, # CUevent hEvent, # unsigned int Flags ) 'cuStreamWaitEvent': (c_int, cu_stream, cu_event, c_uint), # CUresult cuPointerGetAttribute (void *data, CUpointer_attribute attribute, CUdeviceptr ptr) 'cuPointerGetAttribute': (c_int, c_void_p, c_uint, cu_device_ptr), # CUresult cuMemGetAddressRange ( CUdeviceptr * pbase, # size_t * psize, # CUdeviceptr dptr # ) 'cuMemGetAddressRange': (c_int, POINTER(cu_device_ptr), POINTER(c_size_t), cu_device_ptr), # CUresult cuMemHostGetFlags ( unsigned int * pFlags, # void * p ) 'cuMemHostGetFlags': (c_int, POINTER(c_uint), c_void_p), # CUresult cuCtxSynchronize ( void ) 'cuCtxSynchronize' : (c_int,), # CUresult # cuLinkCreate(unsigned int numOptions, CUjit_option *options, # void **optionValues, CUlinkState *stateOut); 'cuLinkCreate': (c_int, c_uint, POINTER(cu_jit_option), POINTER(c_void_p), POINTER(cu_link_state)), # CUresult # cuLinkAddData(CUlinkState state, CUjitInputType type, void *data, # size_t size, const char *name, unsigned # int numOptions, CUjit_option *options, # void **optionValues); 'cuLinkAddData': (c_int, cu_link_state, cu_jit_input_type, c_void_p, c_size_t, c_char_p, c_uint, POINTER(cu_jit_option), POINTER(c_void_p)), # CUresult # cuLinkAddFile(CUlinkState state, CUjitInputType type, # const char *path, unsigned int numOptions, # CUjit_option *options, void **optionValues); 'cuLinkAddFile': (c_int, cu_link_state, cu_jit_input_type, c_char_p, c_uint, POINTER(cu_jit_option), POINTER(c_void_p)), # CUresult CUDAAPI # cuLinkComplete(CUlinkState state, void **cubinOut, size_t *sizeOut) 'cuLinkComplete': (c_int, cu_link_state, POINTER(c_void_p), POINTER(c_size_t)), # CUresult CUDAAPI # cuLinkDestroy(CUlinkState state) 'cuLinkDestroy': (c_int, cu_link_state), # cuProfilerInitialize ( const char* configFile, const char* # outputFile, CUoutput_mode outputMode ) # 'cuProfilerInitialize': (c_int, c_char_p, c_char_p, cu_output_mode), # cuProfilerStart ( void ) 'cuProfilerStart': (c_int,), # cuProfilerStop ( void ) 'cuProfilerStop': (c_int,), # CUresult cuFuncGetAttribute ( int* pi, CUfunction_attribute attrib, # CUfunction hfunc ) 'cuFuncGetAttribute': (c_int, POINTER(c_int), cu_function_attribute, cu_function), # CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks, # CUfunction func, # int blockSize, # size_t dynamicSMemSize); 'cuOccupancyMaxActiveBlocksPerMultiprocessor': (c_int, POINTER(c_int), cu_function, c_size_t, c_uint), # CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int *numBlocks, # CUfunction func, # int blockSize, # size_t dynamicSMemSize, # unsigned int flags); 'cuOccupancyMaxActiveBlocksPerMultiprocessor': (c_int, POINTER(c_int), cu_function, c_size_t, c_uint), # CUresult CUDAAPI cuOccupancyMaxPotentialBlockSize(int *minGridSize, int *blockSize, # CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, # size_t dynamicSMemSize, int blockSizeLimit); 'cuOccupancyMaxPotentialBlockSize': (c_int, POINTER(c_int), POINTER(c_int), cu_function, cu_occupancy_b2d_size, c_size_t, c_int), # CUresult CUDAAPI cuOccupancyMaxPotentialBlockSizeWithFlags(int *minGridSize, int *blockSize, # CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, # size_t dynamicSMemSize, int blockSizeLimit, unsigned int flags); 'cuOccupancyMaxPotentialBlockSizeWithFlags': (c_int, POINTER(c_int), POINTER(c_int), cu_function, cu_occupancy_b2d_size, c_size_t, c_int, c_uint), # CUresult cuIpcGetMemHandle ( CUipcMemHandle* pHandle, CUdeviceptr dptr ) 'cuIpcGetMemHandle': (c_int, POINTER(cu_ipc_mem_handle), cu_device_ptr), # CUresult cuIpcOpenMemHandle ( CUdeviceptr* pdptr, CUipcMemHandle handle, unsigned int Flags ) 'cuIpcOpenMemHandle': (c_int, POINTER(cu_device_ptr), cu_ipc_mem_handle, c_uint), # CUresult cuIpcCloseMemHandle ( CUdeviceptr dptr ) 'cuIpcCloseMemHandle': (c_int, cu_device_ptr), # CUresult cuCtxEnablePeerAccess ( CUcontext peerContext, unsigned int Flags ) 'cuCtxEnablePeerAccess': (c_int, cu_context, c_int), # CUresult cuDeviceCanAccessPeer ( int* canAccessPeer, # CUdevice dev, CUdevice peerDev ) 'cuDeviceCanAccessPeer': (c_int, POINTER(c_int), cu_device, cu_device), }
bsd-2-clause
steven-maasch/spotsome
de.bht.ebus.spotsome/src/main/java/de/bht/ebus/spotsome/util/MessageDateComperator.java
660
package de.bht.ebus.spotsome.util; import java.io.Serializable; import java.util.Comparator; import java.util.Date; import de.bht.ebus.spotsome.model.Message; /** * Note: this comparator imposes orderings that are inconsistent with equals. * * @author Steven Maasch * */ public class MessageDateComperator implements Comparator<Message>, Serializable { private static final long serialVersionUID = 7192152288257703225L; @Override public int compare(Message msg1, Message msg2) { final Date msg1CreationDate = msg1.getCreatedOn(); final Date msg2CreationDate = msg2.getCreatedOn(); return msg1CreationDate.compareTo(msg2CreationDate); } }
bsd-2-clause
zhester/hzphp
Util/NestedAssoc.php
12144
<?php /***************************************************************************** Extends the Assoc Class to Support Additional Features for Nested Arrays ======================================================================== This object allows two additional forms of dereferencing array elements. In addition to the normal string key indexes, users may also pass "paths" into the array. Key paths are given as either an array of keys that successively descends into nested arrays, or as a key-path string where successive keys are superated by forward slashes. Normal shallow indexing: $value = $my_array[ 'my_key' ]; Normal nested indexing: $value = $my_array[ 'my_key' ][ 'my_nested_key' ]; Extended nested indexing: $value = $my_array[ [ 'my_key' ][ 'my_nested_key' ] ]; Path-style nested indexing: $value = $my_array[ 'my_key/my_nested_key' ]; As far as literal notation goes, neither of these are a huge savings. The real power comes from automated construction of paths into the array. Furthermore, when using the recursive merging features, custom resolver functions can receive these paths in a single argument, and do not have to implement the looping to descend into the array. *****************************************************************************/ /*---------------------------------------------------------------------------- Default Namespace ----------------------------------------------------------------------------*/ namespace hzphp\Util; /*---------------------------------------------------------------------------- Dependencies ----------------------------------------------------------------------------*/ require_once __DIR__ . '/Assoc.php'; /*---------------------------------------------------------------------------- Classes ----------------------------------------------------------------------------*/ /** * Extends the Assoc class for nested arrays. */ class NestedAssoc extends Assoc { /*------------------------------------------------------------------------ Public Properties ------------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Protected Properties ------------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Private Properties ------------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Public Methods ------------------------------------------------------------------------*/ /** * Recursively merges data from another Assoc object or an associative * array. * * @param incoming The incoming object or array from which to merge * @param resolver A callback function to resolve merge conflicts. The * default resolver assumes the incoming values override * the current values. * @param depth Optionally, request recursive merging. By default, * only shallow merging is performed (depth: 0). To * recurse to all scalar values, use -1. To recurse to * any given depth, pass that value. When recursing, the * `key` parameter to the resolver becomes an array of * keys indicating the "path" into the array where the * first item is the key into the outermost array, * followed by the key of the first nested array, and so * on. */ public function merge( $incoming, $resolver = null, $depth = 0 ) { //check for default resolver if( $resolver === null ) { $resolver = function( $key, $mine, $theirs ) { return $theirs; }; } //see if we are currently recursing through all nested arrays if( $depth != 0 ) { //use the recursive merge method $this->submerge( $this->data, $incoming, $resolver, $depth ); } //not currently recursing else { //perform shallow merge parent::merge( $incoming, $resolver ); } } /** * Tests if an element in the array exists. * * @param key The key to test * @return True if the key exists in the array */ public function offsetExists( $key ) { if( is_array( $key ) ) { if( count( $key ) == 0 ) { return false; } $node = &$this->data; foreach( $key as $k ) { if( isset( $node[ $k ] ) == false ) { return false; } $node = &$node[ $k ]; } return true; } return parent::offsetExists( $key ); } /** * Provides array subscript access to the elements in the array. * * @param key The key into the associative array * @return The value at the requested key * @throws OutOfBoundsException if the key is not valid */ public function offsetGet( $key ) { if( is_array( $key ) ) { if( count( $key ) == 0 ) { throw new \OutOfBoundsException( "Invalid offset (empty array) into array." ); } $node = &$this->data; foreach( $key as $k ) { if( isset( $node[ $k ] ) == false ) { $path = implode( '/', $key ); throw new \OutOfBoundsException( "Unknown offset \"$path\" into array." ); } $node = &$node[ $k ]; } return $node; } else if( is_string( $key ) && ( strpos( $key, '/' ) !== false ) ) { return $this->offsetGet( explode( '/', $key ) ); } return parent::offsetGet( $key ); } /** * Sets values of elements in the array. * * @param key The key of the element to set * @param value The value of the element */ public function offsetSet( $key, $value ) { if( is_array( $key ) ) { if( count( $key ) == 0 ) { throw new \OutOfBoundsException( "Invalid offset (empty array) into array." ); } $node = &$this->data; $last_key = array_pop( $key ); foreach( $key as $k ) { if( isset( $node[ $k ] ) == false ) { $node[ $k ] = []; } $node = &$node[ $k ]; } $node[ $last_key ] = $value; } else if( is_string( $key ) && ( strpos( $key, '/' ) !== false ) ) { $this->offsetSet( explode( '/', $key ), $value ); } else { parent::offsetSet( $key, $value ); } } /** * Deletes elements in the array. * * @param key The key of the element to delete * @throws OutOfBoundsException if the key is not valid */ public function offsetUnset( $key ) { if( is_array( $key ) ) { if( count( $key ) == 0 ) { throw new \OutOfBoundsException( "Invalid offset (empty array) into array." ); } $node = &$this->data; $last_key = array_pop( $key ); foreach( $key as $k ) { if( isset( $node[ $k ] ) == false ) { $key[] = $last_key; $path = implode( '/', $key ); throw new \OutOfBoundsException( "Unknown offset \"$path\" into array." ); } $node = &$node[ $k ]; } unset( $node[ $last_key ] ); } else if( is_string( $key ) && ( strpos( $key, '/' ) !== false ) ) { $this->offsetUnset( explode( '/', $key ) ); } else { parent::offsetUnset( $key ); } } /*------------------------------------------------------------------------ Protected Methods ------------------------------------------------------------------------*/ /** * Recursively merges nested arrays into the target array. * * @param target The target array to which we are merging * @param source The source array from which we are merging * @param resolver The conflict resolution function * @param depth The maximum depth of merging * @param path Array of keys that can resolve the current element */ protected function submerge( &$target, $source, $resolver, $depth, $path = null ) { //set up the nested key path $subpath = $path; $subpath_index = count( $subpath ); $subpath[] = null; //iterate through the incoming data foreach( $source as $key => $value ) { //set the key at the end of the nested key path $subpath[ $subpath_index ] = $key; //check for scalar values, or if we are past the recursion limit if( is_scalar( $value ) || ( $depth == 0 ) ) { //check for merge conflict if( isset( $target[ $key ] ) ) { $target[ $key ] = $resolver( $subpath, $target[ $key ], $source[ $key ] ); } else { $target[ $key ] = $source[ $key ]; } } //this is a vector value, and we are within the recursion limit else { //merge vectors $this->submerge( $target[ $key ], $source[ $key ], $resolver, ( $depth - 1 ), $subpath ); } } } /*------------------------------------------------------------------------ Private Methods ------------------------------------------------------------------------*/ } /*---------------------------------------------------------------------------- Functions ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Execution ----------------------------------------------------------------------------*/ if( $_SERVER[ 'SCRIPT_FILENAME' ] == __FILE__ ) { header( 'Content-Type: text/plain; charset=utf-8' ); //initializer array $init = [ 'a' => 1, 'b' => 2, 'c' => 0, 'd' => '', 'e' => '0', 'f' => '0.0', 'g' => false, 'h' => null, 'n' => [ 'na' => 10, 'nb' => 11, 'nc' => 12 ] ]; //typical construction $assoc = new NestedAssoc( $init ); //nested array accessors echo "Nested Array Access\n"; echo $assoc[ [ 'n', 'nb' ] ], " == {$init['n']['nb']}\n"; $assoc[ [ 'n', 'nc' ] ] = 112; echo $assoc[ [ 'n', 'nc' ] ], " != {$init['n']['nc']}\n"; $assoc[ [ 'n', 'nd' ] ] = 42; unset( $assoc[ [ 'n', 'na' ] ] ); if( isset( $assoc[ 'n' ][ 'na' ] ) ) { echo "## NESTED ACCESS FAILED (UNSET) ##\n"; } echo "\n"; //proper error handling echo "Exception-based Error Handling\n"; try { $unknown = $assoc[ [ 'a', 'q' ] ]; } catch( \OutOfBoundsException $e ) { echo $e->getMessage(), "\n"; } echo "\n"; //recursive merging $merge_failed = false; $merge = [ 'b' => 29, 'n' => [ 'nb' => 39 ] ]; $assoc->merge( $merge, null, -1 ); if( $assoc[ 'n' ][ 'nb' ] != $merge[ 'n' ][ 'nb' ] ) { $merge_failed = true; echo "## MERGE FAILED (RECURSION) ##\n"; } if( $merge_failed == false ) { echo "All merge tests paseed.\n"; } echo "\n"; }
bsd-2-clause
alerque/homebrew-fonts
Casks/font-bitstream-vera-sans-mono-nerd-font.rb
969
cask "font-bitstream-vera-sans-mono-nerd-font" do version "2.1.0" sha256 "b31595d1e717156a1f42b0ff635b93d5da631312e4f0bd5c581259171e4a42d8" url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/BitstreamVeraSansMono.zip" appcast "https://github.com/ryanoasis/nerd-fonts/releases.atom" name "BitstreamVeraSansMono Nerd Font (Bitstream Vera Sans Mono)" homepage "https://github.com/ryanoasis/nerd-fonts" font "Bitstream Vera Sans Mono Bold Nerd Font Complete.ttf" font "Bitstream Vera Sans Mono Bold Nerd Font Complete Mono.ttf" font "Bitstream Vera Sans Mono Bold Oblique Nerd Font Complete.ttf" font "Bitstream Vera Sans Mono Bold Oblique Nerd Font Complete Mono.ttf" font "Bitstream Vera Sans Mono Nerd Font Complete Mono.ttf" font "Bitstream Vera Sans Mono Nerd Font Complete.ttf" font "Bitstream Vera Sans Mono Oblique Nerd Font Complete.ttf" font "Bitstream Vera Sans Mono Oblique Nerd Font Complete Mono.ttf" end
bsd-2-clause
feserr/CrossEngine
CrossEngine/scripts/genie.lua
3105
-- -- Copyright 2010-2017 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- newoption { trigger = "with-amalgamated", description = "Enable amalgamated build.", } newoption { trigger = "with-ovr", description = "Enable OculusVR integration.", } newoption { trigger = "with-sdl", description = "Enable SDL entry.", } newoption { trigger = "with-glfw", description = "Enable GLFW entry.", } newoption { trigger = "with-profiler", description = "Enable build with intrusive profiler.", } newoption { trigger = "with-scintilla", description = "Enable building with Scintilla editor.", } newoption { trigger = "with-shared-lib", description = "Enable building shared library.", } newoption { trigger = "with-tools", description = "Enable building tools.", } newoption { trigger = "with-examples", description = "Enable building examples.", } solution "crossengine" configurations { "Debug", "Release", } if _ACTION == "xcode4" then platforms { "Universal", } else platforms { "x32", "x64", -- "Xbox360", "Native", -- for targets where bitness is not specified } end language "C++" startproject "crossengine" MODULE_DIR = path.getabsolute("../") EXTERNAL_DIR = path.getabsolute("../../external/") BGFX_DIR = path.getabsolute(path.join(EXTERNAL_DIR, "bgfx")) BIMG_DIR = path.getabsolute(path.join(EXTERNAL_DIR, "bimg")) BX_DIR = os.getenv("BX_DIR") EIGEN_DIR = path.getabsolute(path.join(EXTERNAL_DIR, "eigen")) CROSSENGINE_DIR = path.getabsolute("../") local BGFX_BUILD_DIR = path.join(MODULE_DIR, "build") local BGFX_THIRD_PARTY_DIR = path.join(BGFX_DIR, "3rdparty") if not BX_DIR then BX_DIR = path.getabsolute(path.join(EXTERNAL_DIR, "bx")) end if not os.isdir(BX_DIR) then print("bx not found at " .. BX_DIR) print("For more info see: https://bkaradzic.github.io/bgfx/build.html") os.exit() end dofile (path.join(BX_DIR, "scripts/toolchain.lua")) if not toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) then return -- no action specified end function copyLib() end if _OPTIONS["with-sdl"] then if os.is("windows") then if not os.getenv("SDL2_DIR") then print("Set SDL2_DIR enviroment variable.") end end end if _OPTIONS["with-profiler"] then defines { "ENTRY_CONFIG_PROFILER=1", "BGFX_CONFIG_PROFILER_REMOTERY=1", "_WINSOCKAPI_" } end dofile(path.join(BGFX_DIR, "scripts/bgfx.lua")) group "libs" bgfxProject("", "StaticLib", {}) dofile(path.join(BX_DIR, "scripts/bx.lua")) dofile(path.join(BIMG_DIR, "scripts/bimg.lua")) dofile(path.join(BIMG_DIR, "scripts/bimg_decode.lua")) dofile(path.join(CROSSENGINE_DIR, "scripts/crossengine.lua")) if _OPTIONS["with-tools"] then dofile(path.join(BIMG_DIR, "scripts/bimg_encode.lua")) end if _OPTIONS["with-shared-lib"] then group "libs" bgfxProject("-shared-lib", "SharedLib", {}) end if _OPTIONS["with-tools"] then group "tools" dofile "shaderc.lua" dofile "texturec.lua" dofile "texturev.lua" dofile "geometryc.lua" dofile(path.join(BIMG_DIR, "scripts/bimg_encode.lua")) end
bsd-2-clause
khchine5/book
lino_book/projects/actions/models.py
674
from django.db import models from django.utils.translation import ugettext_lazy as _ from lino.api import dd, rt class A(dd.Action): label = _("a") def run_from_ui(self,ar,**kw): obj = ar.selected_rows[0] return ar.success("Called a() on %s" % obj) class Moo(dd.Model): a = A() @dd.action(_("m")) def m(self,ar,**kw): return ar.success("Called m() on %s" % self) class Moos(dd.Table): model = Moo b = A() @dd.action(_("t")) def t(obj,ar,**kw): return ar.success("Called t() on %s" % obj) class S1(Moos): pass class S2(Moos): a = None b = None m = None t = None
bsd-2-clause
nyaki-HUN/DESIRE
DESIRE-Modules/ResourceLoader-Assimp/Externals/Assimp/code/AssetLib/OFF/OFFLoader.cpp
11328
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2021, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file OFFLoader.cpp * @brief Implementation of the OFF importer class */ #ifndef ASSIMP_BUILD_NO_OFF_IMPORTER // internal headers #include "OFFLoader.h" #include <assimp/ParsingUtils.h> #include <assimp/fast_atof.h> #include <memory> #include <assimp/IOSystem.hpp> #include <assimp/scene.h> #include <assimp/DefaultLogger.hpp> #include <assimp/importerdesc.h> using namespace Assimp; static const aiImporterDesc desc = { "OFF Importer", "", "", "", aiImporterFlags_SupportBinaryFlavour, 0, 0, 0, 0, "off" }; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer OFFImporter::OFFImporter() {} // ------------------------------------------------------------------------------------------------ // Destructor, private as well OFFImporter::~OFFImporter() {} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. bool OFFImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const { const std::string extension = GetExtension(pFile); if (extension == "off") return true; else if (!extension.length() || checkSig) { if (!pIOHandler)return true; const char* tokens[] = {"off"}; return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1,3); } return false; } // ------------------------------------------------------------------------------------------------ const aiImporterDesc* OFFImporter::GetInfo () const { return &desc; } // skip blank space, lines and comments static void NextToken(const char **car, const char* end) { SkipSpacesAndLineEnd(car); while (*car < end && (**car == '#' || **car == '\n' || **car == '\r')) { SkipLine(car); SkipSpacesAndLineEnd(car); } } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void OFFImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); // Check whether we can read from the file if( file.get() == nullptr) { throw DeadlyImportError( "Failed to open OFF file ", pFile, "."); } // allocate storage and copy the contents of the file to a memory buffer std::vector<char> mBuffer2; TextFileToBuffer(file.get(),mBuffer2); const char* buffer = &mBuffer2[0]; // Proper OFF header parser. We only implement normal loading for now. bool hasTexCoord = false, hasNormals = false, hasColors = false; bool hasHomogenous = false, hasDimension = false; unsigned int dimensions = 3; const char* car = buffer; const char* end = buffer + mBuffer2.size(); NextToken(&car, end); if (car < end - 2 && car[0] == 'S' && car[1] == 'T') { hasTexCoord = true; car += 2; } if (car < end - 1 && car[0] == 'C') { hasColors = true; car++; } if (car < end- 1 && car[0] == 'N') { hasNormals = true; car++; } if (car < end - 1 && car[0] == '4') { hasHomogenous = true; car++; } if (car < end - 1 && car[0] == 'n') { hasDimension = true; car++; } if (car < end - 3 && car[0] == 'O' && car[1] == 'F' && car[2] == 'F') { car += 3; NextToken(&car, end); } else { // in case there is no OFF header (which is allowed by the // specification...), then we might have unintentionally read an // additional dimension from the primitive count fields dimensions = 3; hasHomogenous = false; NextToken(&car, end); // at this point the next token should be an integer number if (car >= end - 1 || *car < '0' || *car > '9') { throw DeadlyImportError("OFF: Header is invalid"); } } if (hasDimension) { dimensions = strtoul10(car, &car); NextToken(&car, end); } if (dimensions > 3) { throw DeadlyImportError ("OFF: Number of vertex coordinates higher than 3 unsupported"); } NextToken(&car, end); const unsigned int numVertices = strtoul10(car, &car); NextToken(&car, end); const unsigned int numFaces = strtoul10(car, &car); NextToken(&car, end); strtoul10(car, &car); // skip edge count NextToken(&car, end); if (!numVertices) { throw DeadlyImportError("OFF: There are no valid vertices"); } if (!numFaces) { throw DeadlyImportError("OFF: There are no valid faces"); } pScene->mNumMeshes = 1; pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ]; aiMesh* mesh = new aiMesh(); pScene->mMeshes[0] = mesh; mesh->mNumFaces = numFaces; aiFace* faces = new aiFace[mesh->mNumFaces]; mesh->mFaces = faces; mesh->mNumVertices = numVertices; mesh->mVertices = new aiVector3D[numVertices]; mesh->mNormals = hasNormals ? new aiVector3D[numVertices] : nullptr; mesh->mColors[0] = hasColors ? new aiColor4D[numVertices] : nullptr; if (hasTexCoord) { mesh->mNumUVComponents[0] = 2; mesh->mTextureCoords[0] = new aiVector3D[numVertices]; } char line[4096]; buffer = car; const char *sz = car; // now read all vertex lines for (unsigned int i = 0; i < numVertices; ++i) { if(!GetNextLine(buffer, line)) { ASSIMP_LOG_ERROR("OFF: The number of verts in the header is incorrect"); break; } aiVector3D& v = mesh->mVertices[i]; sz = line; // helper array to write a for loop over possible dimension values ai_real* vec[3] = {&v.x, &v.y, &v.z}; // stop at dimensions: this allows loading 1D or 2D coordinate vertices for (unsigned int dim = 0; dim < dimensions; ++dim ) { SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, *vec[dim]); } // if has homogenous coordinate, divide others by this one if (hasHomogenous) { SkipSpaces(&sz); ai_real w = 1.; sz = fast_atoreal_move<ai_real>(sz, w); for (unsigned int dim = 0; dim < dimensions; ++dim ) { *(vec[dim]) /= w; } } // read optional normals if (hasNormals) { aiVector3D& n = mesh->mNormals[i]; SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)n.x); SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)n.y); SkipSpaces(&sz); fast_atoreal_move<ai_real>(sz,(ai_real&)n.z); } // reading colors is a pain because the specification says it can be // integers or floats, and any number of them between 1 and 4 included, // until the next comment or end of line // in theory should be testing type ! if (hasColors) { aiColor4D& c = mesh->mColors[0][i]; SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)c.r); if (*sz != '#' && *sz != '\n' && *sz != '\r') { SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)c.g); } else { c.g = 0.; } if (*sz != '#' && *sz != '\n' && *sz != '\r') { SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)c.b); } else { c.b = 0.; } if (*sz != '#' && *sz != '\n' && *sz != '\r') { SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)c.a); } else { c.a = 1.; } } if (hasTexCoord) { aiVector3D& t = mesh->mTextureCoords[0][i]; SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz,(ai_real&)t.x); SkipSpaces(&sz); fast_atoreal_move<ai_real>(sz,(ai_real&)t.y); } } // load faces with their indices faces = mesh->mFaces; for (unsigned int i = 0; i < numFaces; ) { if(!GetNextLine(buffer,line)) { ASSIMP_LOG_ERROR("OFF: The number of faces in the header is incorrect"); break; } unsigned int idx; sz = line; SkipSpaces(&sz); idx = strtoul10(sz,&sz); if(!idx || idx > 9) { ASSIMP_LOG_ERROR("OFF: Faces with zero indices aren't allowed"); --mesh->mNumFaces; continue; } faces->mNumIndices = idx; faces->mIndices = new unsigned int[faces->mNumIndices]; for (unsigned int m = 0; m < faces->mNumIndices;++m) { SkipSpaces(&sz); idx = strtoul10(sz,&sz); if (idx >= numVertices) { ASSIMP_LOG_ERROR("OFF: Vertex index is out of range"); idx = numVertices - 1; } faces->mIndices[m] = idx; } ++i; ++faces; } // generate the output node graph pScene->mRootNode = new aiNode(); pScene->mRootNode->mName.Set("<OFFRoot>"); pScene->mRootNode->mNumMeshes = 1; pScene->mRootNode->mMeshes = new unsigned int [pScene->mRootNode->mNumMeshes]; pScene->mRootNode->mMeshes[0] = 0; // generate a default material pScene->mNumMaterials = 1; pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]; aiMaterial* pcMat = new aiMaterial(); aiColor4D clr( ai_real( 0.6 ), ai_real( 0.6 ), ai_real( 0.6 ), ai_real( 1.0 ) ); pcMat->AddProperty(&clr,1,AI_MATKEY_COLOR_DIFFUSE); pScene->mMaterials[0] = pcMat; const int twosided = 1; pcMat->AddProperty(&twosided, 1, AI_MATKEY_TWOSIDED); } #endif // !! ASSIMP_BUILD_NO_OFF_IMPORTER
bsd-2-clause
jesstelford/time-prototype
Renderer/Abstract.lua
105
--- Renderable class implementing Visitor Pattern Renderer_Abstract = Class {} return Renderer_Abstract
bsd-2-clause
stweil/ol3
examples/layer-group.js
2012
import Map from '../src/ol/Map.js'; import OSM from '../src/ol/source/OSM.js'; import TileJSON from '../src/ol/source/TileJSON.js'; import View from '../src/ol/View.js'; import {Group as LayerGroup, Tile as TileLayer} from '../src/ol/layer.js'; import {fromLonLat} from '../src/ol/proj.js'; const key = 'pk.eyJ1IjoiYWhvY2V2YXIiLCJhIjoiY2pzbmg0Nmk5MGF5NzQzbzRnbDNoeHJrbiJ9.7_-_gL8ur7ZtEiNwRfCy7Q'; const map = new Map({ layers: [ new TileLayer({ source: new OSM(), }), new LayerGroup({ layers: [ new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v4/mapbox.20110804-hoa-foodinsecurity-3month.json?secure&access_token=' + key, crossOrigin: 'anonymous', }), }), new TileLayer({ source: new TileJSON({ url: 'https://api.tiles.mapbox.com/v4/mapbox.world-borders-light.json?secure&access_token=' + key, crossOrigin: 'anonymous', }), }), ], }), ], target: 'map', view: new View({ center: fromLonLat([37.4057, 8.81566]), zoom: 4, }), }); function bindInputs(layerid, layer) { const visibilityInput = $(layerid + ' input.visible'); visibilityInput.on('change', function () { layer.setVisible(this.checked); }); visibilityInput.prop('checked', layer.getVisible()); const opacityInput = $(layerid + ' input.opacity'); opacityInput.on('input', function () { layer.setOpacity(parseFloat(this.value)); }); opacityInput.val(String(layer.getOpacity())); } function setup(id, group) { group.getLayers().forEach(function (layer, i) { const layerid = id + i; bindInputs(layerid, layer); if (layer instanceof LayerGroup) { setup(layerid, layer); } }); } setup('#layer', map.getLayerGroup()); $('#layertree li > span') .click(function () { $(this).siblings('fieldset').toggle(); }) .siblings('fieldset') .hide();
bsd-2-clause
fpsw/Servo
servo/urls/products.py
2450
# -*- coding: utf-8 -*- from django.conf.urls import url from servo.views.product import * urlpatterns = [ url(r'^tags/$', tags, name="products-tags"), url(r'^all/$', list_products, {'group': 'all'}, name="products-list_products"), url(r'^(?P<group>[\w\-/]*)/download/$', download_products, name="products-download"), url(r'^inventory_report/$', get_inventory_report, name="products-get_inventory_report"), url(r'^upload/$', upload_products, name="products-upload_products"), url(r'^upload/parts/$', upload_gsx_parts, name="products-upload_gsx_parts"), url(r'^upload/prices/$', upload_prices, name="products-upload_prices"), url(r'^update_price/(\d+)/$', update_price, name="products-update_price"), url(r'^all/(?P<pk>\d+)/$', view_product, {'group': 'all'}, name="products-view_product"), url(r'^(?P<group>[\w\-/]*)/(?P<pk>\d+)/view/$', view_product, name="products-view_product"), # Editing product categories url(r'^categories/create/$', edit_category, name="products-create_category"), url(r'^categories/(?P<slug>[\w\-]+)/edit/$', edit_category, name="products-edit_category"), url(r'^categories/(?P<slug>[\w\-]+)/delete/$', delete_category, name="products-delete_category"), url(r'^categories/(?P<parent_slug>[\w\-]+)/create/$', edit_category, name="products-create_category"), # Editing products url(r'^create/$', edit_product, name="products-create"), url(r'^(?P<group>[\w\-]+)/create/$', edit_product, name="products-create"), url(r'^(?P<group>[\w\-/]*)/(?P<pk>\d+)/edit/$', edit_product, name="products-edit_product"), url(r'^(?P<group>[\w\-/]*)/(?P<pk>\d+)/delete/$', delete_product, name="products-delete_product"), # Choosing a product for an order url(r'^choose/order/(?P<order_id>\d+)/$', choose_product, name="products-choose"), url(r'^(?P<group>[\w\-]+)/(?P<code>[\w\-/]+)/create/$', edit_product, name="products-create"), url(r'^all/(?P<code>[\w\-/]+)/view/$', view_product, {'group': 'all'}, name="products-view_product"), url(r'^(?P<code>[\w\-/]+)/new/$', edit_product, {'group': None}, name="products-create"), url(r'^code/(?P<code>[\w\-/]+)/location/(?P<location>\d+)/get_info/$', get_info, name="products-get_info"), url(r'^(?P<group>[\w\-]+)/$', list_products, name="products-list_products"), ]
bsd-2-clause
delfiramirez/beta-ciproject
03/public_html/libs/vendor/foundation/js/foundation.core.js
13347
!function($) { "use strict"; var FOUNDATION_VERSION = '6.2.3'; // Global Foundation object // This is attached to the window, or used as a module for AMD/Browserify var Foundation = { version: FOUNDATION_VERSION, /** * Stores initialized plugins. */ _plugins: {}, /** * Stores generated unique ids for plugin instances */ _uuids: [], /** * Returns a boolean for RTL support */ rtl: function(){ return $('html').attr('dir') === 'rtl'; }, /** * Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing. * @param {Object} plugin - The constructor of the plugin. */ plugin: function(plugin, name) { // Object key to use when adding to global Foundation object // Examples: Foundation.Reveal, Foundation.OffCanvas var className = (name || functionName(plugin)); // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin // Examples: data-reveal, data-off-canvas var attrName = hyphenate(className); // Add to the Foundation object and the plugins list (for reflowing) this._plugins[attrName] = this[className] = plugin; }, /** * @function * Populates the _uuids array with pointers to each individual plugin instance. * Adds the `zfPlugin` data-attribute to programmatically created plugins to allow use of $(selector).foundation(method) calls. * Also fires the initialization event for each plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @param {String} name - the name of the plugin, passed as a camelCased string. * @fires Plugin#init */ registerPlugin: function(plugin, name){ var pluginName = name ? hyphenate(name) : functionName(plugin.constructor).toLowerCase(); plugin.uuid = this.GetYoDigits(6, pluginName); if(!plugin.$element.attr(`data-${pluginName}`)){ plugin.$element.attr(`data-${pluginName}`, plugin.uuid); } if(!plugin.$element.data('zfPlugin')){ plugin.$element.data('zfPlugin', plugin); } /** * Fires when the plugin has initialized. * @event Plugin#init */ plugin.$element.trigger(`init.zf.${pluginName}`); this._uuids.push(plugin.uuid); return; }, /** * @function * Removes the plugins uuid from the _uuids array. * Removes the zfPlugin data attribute, as well as the data-plugin-name attribute. * Also fires the destroyed event for the plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @fires Plugin#destroyed */ unregisterPlugin: function(plugin){ var pluginName = hyphenate(functionName(plugin.$element.data('zfPlugin').constructor)); this._uuids.splice(this._uuids.indexOf(plugin.uuid), 1); plugin.$element.removeAttr(`data-${pluginName}`).removeData('zfPlugin') /** * Fires when the plugin has been destroyed. * @event Plugin#destroyed */ .trigger(`destroyed.zf.${pluginName}`); for(var prop in plugin){ plugin[prop] = null;//clean up script to prep for garbage collection. } return; }, /** * @function * Causes one or more active plugins to re-initialize, resetting event listeners, recalculating positions, etc. * @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'` * @default If no argument is passed, reflow all currently active plugins. */ reInit: function(plugins){ var isJQ = plugins instanceof $; try{ if(isJQ){ plugins.each(function(){ $(this).data('zfPlugin')._init(); }); }else{ var type = typeof plugins, _this = this, fns = { 'object': function(plgs){ plgs.forEach(function(p){ p = hyphenate(p); $('[data-'+ p +']').foundation('_init'); }); }, 'string': function(){ plugins = hyphenate(plugins); $('[data-'+ plugins +']').foundation('_init'); }, 'undefined': function(){ this['object'](Object.keys(_this._plugins)); } }; fns[type](plugins); } }catch(err){ console.error(err); }finally{ return plugins; } }, /** * returns a random base-36 uid with namespacing * @function * @param {Number} length - number of random base-36 digits desired. Increase for more random strings. * @param {String} namespace - name of plugin to be incorporated in uid, optional. * @default {String} '' - if no plugin name is provided, nothing is appended to the uid. * @returns {String} - unique id */ GetYoDigits: function(length, namespace){ length = length || 6; return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1) + (namespace ? `-${namespace}` : ''); }, /** * Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized. * @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object. * @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything. */ reflow: function(elem, plugins) { // If plugins is undefined, just grab everything if (typeof plugins === 'undefined') { plugins = Object.keys(this._plugins); } // If plugins is a string, convert it to an array with one item else if (typeof plugins === 'string') { plugins = [plugins]; } var _this = this; // Iterate through each plugin $.each(plugins, function(i, name) { // Get the current plugin var plugin = _this._plugins[name]; // Localize the search to all elements inside elem, as well as elem itself, unless elem === document var $elem = $(elem).find('[data-'+name+']').addBack('[data-'+name+']'); // For each plugin found, initialize it $elem.each(function() { var $el = $(this), opts = {}; // Don't double-dip on plugins if ($el.data('zfPlugin')) { console.warn("Tried to initialize "+name+" on an element that already has a Foundation plugin."); return; } if($el.attr('data-options')){ var thing = $el.attr('data-options').split(';').forEach(function(e, i){ var opt = e.split(':').map(function(el){ return el.trim(); }); if(opt[0]) opts[opt[0]] = parseValue(opt[1]); }); } try{ $el.data('zfPlugin', new plugin($(this), opts)); }catch(er){ console.error(er); }finally{ return; } }); }); }, getFnName: functionName, transitionend: function($elem){ var transitions = { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'otransitionend' }; var elem = document.createElement('div'), end; for (var t in transitions){ if (typeof elem.style[t] !== 'undefined'){ end = transitions[t]; } } if(end){ return end; }else{ end = setTimeout(function(){ $elem.triggerHandler('transitionend', [$elem]); }, 1); return 'transitionend'; } } }; Foundation.util = { /** * Function for applying a debounce effect to a function call. * @function * @param {Function} func - Function to be called at end of timeout. * @param {Number} delay - Time in ms to delay the call of `func`. * @returns function */ throttle: function (func, delay) { var timer = null; return function () { var context = this, args = arguments; if (timer === null) { timer = setTimeout(function () { func.apply(context, args); timer = null; }, delay); } }; } }; // TODO: consider not making this a jQuery function // TODO: need way to reflow vs. re-initialize /** * The Foundation jQuery method. * @param {String|Array} method - An action to perform on the current jQuery object. */ var foundation = function(method) { var type = typeof method, $meta = $('meta.foundation-mq'), $noJS = $('.no-js'); if(!$meta.length){ $('<meta class="foundation-mq">').appendTo(document.head); } if($noJS.length){ $noJS.removeClass('no-js'); } if(type === 'undefined'){//needs to initialize the Foundation object, or an individual plugin. Foundation.MediaQuery._init(); Foundation.reflow(this); }else if(type === 'string'){//an individual method to invoke on a plugin or group of plugins var args = Array.prototype.slice.call(arguments, 1);//collect all the arguments, if necessary var plugClass = this.data('zfPlugin');//determine the class of plugin if(plugClass !== undefined && plugClass[method] !== undefined){//make sure both the class and method exist if(this.length === 1){//if there's only one, call it directly. plugClass[method].apply(plugClass, args); }else{ this.each(function(i, el){//otherwise loop through the jQuery collection and invoke the method on each plugClass[method].apply($(el).data('zfPlugin'), args); }); } }else{//error for no class or no method throw new ReferenceError("We're sorry, '" + method + "' is not an available method for " + (plugClass ? functionName(plugClass) : 'this element') + '.'); } }else{//error for invalid argument type throw new TypeError(`We're sorry, ${type} is not a valid parameter. You must use a string representing the method you wish to invoke.`); } return this; }; window.Foundation = Foundation; $.fn.foundation = foundation; // Polyfill for requestAnimationFrame (function() { if (!Date.now || !window.Date.now) window.Date.now = Date.now = function() { return new Date().getTime(); }; var vendors = ['webkit', 'moz']; for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) { var vp = vendors[i]; window.requestAnimationFrame = window[vp+'RequestAnimationFrame']; window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame'] || window[vp+'CancelRequestAnimationFrame']); } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var lastTime = 0; window.requestAnimationFrame = function(callback) { var now = Date.now(); var nextTime = Math.max(lastTime + 16, now); return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); }; window.cancelAnimationFrame = clearTimeout; } /** * Polyfill for performance.now, required by rAF */ if(!window.performance || !window.performance.now){ window.performance = { start: Date.now(), now: function(){ return Date.now() - this.start; } }; } })(); if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; } // Polyfill to get the name of a function in IE9 function functionName(fn) { if (Function.prototype.name === undefined) { var funcNameRegex = /function\s([^(]{1,})\(/; var results = (funcNameRegex).exec((fn).toString()); return (results && results.length > 1) ? results[1].trim() : ""; } else if (fn.prototype === undefined) { return fn.constructor.name; } else { return fn.prototype.constructor.name; } } function parseValue(str){ if(/true/.test(str)) return true; else if(/false/.test(str)) return false; else if(!isNaN(str * 1)) return parseFloat(str); return str; } // Convert PascalCase to kebab-case // Thank you: http://stackoverflow.com/a/8955580 function hyphenate(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } }(jQuery);
bsd-2-clause
timob/ec2
com_amazonaws_services_ec2_model_SlotStartTimeRangeRequest.go
7185
package ec2 import "time" import "github.com/timob/javabind" type ServicesEc2ModelSlotStartTimeRangeRequestInterface interface { JavaLangObjectInterface // public void setEarliestTime(java.util.Date) SetEarliestTime(a time.Time) // public java.util.Date getEarliestTime() GetEarliestTime() time.Time // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest withEarliestTime(java.util.Date) WithEarliestTime(a time.Time) *ServicesEc2ModelSlotStartTimeRangeRequest // public void setLatestTime(java.util.Date) SetLatestTime(a time.Time) // public java.util.Date getLatestTime() GetLatestTime() time.Time // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest withLatestTime(java.util.Date) WithLatestTime(a time.Time) *ServicesEc2ModelSlotStartTimeRangeRequest // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest clone() Clone() *ServicesEc2ModelSlotStartTimeRangeRequest } type ServicesEc2ModelSlotStartTimeRangeRequest struct { JavaLangObject } // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest() func NewServicesEc2ModelSlotStartTimeRangeRequest() (*ServicesEc2ModelSlotStartTimeRangeRequest) { obj, err := javabind.GetEnv().NewObject("com/amazonaws/services/ec2/model/SlotStartTimeRangeRequest") if err != nil { panic(err) } x := &ServicesEc2ModelSlotStartTimeRangeRequest{} x.Callable = &javabind.Callable{obj} return x } // public void setEarliestTime(java.util.Date) func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) SetEarliestTime(a time.Time) { conv_a := javabind.NewGoToJavaDate() if err := conv_a.Convert(a); err != nil { panic(err) } _, err := jbobject.CallMethod(javabind.GetEnv(), "setEarliestTime", javabind.Void, conv_a.Value().Cast("java/util/Date")) if err != nil { panic(err) } conv_a.CleanUp() } // public java.util.Date getEarliestTime() func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) GetEarliestTime() time.Time { jret, err := jbobject.CallMethod(javabind.GetEnv(), "getEarliestTime", "java/util/Date") if err != nil { panic(err) } retconv := javabind.NewJavaToGoDate() dst := new(time.Time) retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() return *dst } // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest withEarliestTime(java.util.Date) func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) WithEarliestTime(a time.Time) *ServicesEc2ModelSlotStartTimeRangeRequest { conv_a := javabind.NewGoToJavaDate() if err := conv_a.Convert(a); err != nil { panic(err) } jret, err := jbobject.CallMethod(javabind.GetEnv(), "withEarliestTime", "com/amazonaws/services/ec2/model/SlotStartTimeRangeRequest", conv_a.Value().Cast("java/util/Date")) if err != nil { panic(err) } conv_a.CleanUp() retconv := javabind.NewJavaToGoCallable() dst := &javabind.Callable{} retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() unique_x := &ServicesEc2ModelSlotStartTimeRangeRequest{} unique_x.Callable = dst return unique_x } // public void setLatestTime(java.util.Date) func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) SetLatestTime(a time.Time) { conv_a := javabind.NewGoToJavaDate() if err := conv_a.Convert(a); err != nil { panic(err) } _, err := jbobject.CallMethod(javabind.GetEnv(), "setLatestTime", javabind.Void, conv_a.Value().Cast("java/util/Date")) if err != nil { panic(err) } conv_a.CleanUp() } // public java.util.Date getLatestTime() func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) GetLatestTime() time.Time { jret, err := jbobject.CallMethod(javabind.GetEnv(), "getLatestTime", "java/util/Date") if err != nil { panic(err) } retconv := javabind.NewJavaToGoDate() dst := new(time.Time) retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() return *dst } // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest withLatestTime(java.util.Date) func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) WithLatestTime(a time.Time) *ServicesEc2ModelSlotStartTimeRangeRequest { conv_a := javabind.NewGoToJavaDate() if err := conv_a.Convert(a); err != nil { panic(err) } jret, err := jbobject.CallMethod(javabind.GetEnv(), "withLatestTime", "com/amazonaws/services/ec2/model/SlotStartTimeRangeRequest", conv_a.Value().Cast("java/util/Date")) if err != nil { panic(err) } conv_a.CleanUp() retconv := javabind.NewJavaToGoCallable() dst := &javabind.Callable{} retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() unique_x := &ServicesEc2ModelSlotStartTimeRangeRequest{} unique_x.Callable = dst return unique_x } // public java.lang.String toString() func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) ToString() string { jret, err := jbobject.CallMethod(javabind.GetEnv(), "toString", "java/lang/String") if err != nil { panic(err) } retconv := javabind.NewJavaToGoString() dst := new(string) retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() return *dst } // public boolean equals(java.lang.Object) func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) Equals(a interface{}) bool { conv_a := javabind.NewGoToJavaCallable() if err := conv_a.Convert(a); err != nil { panic(err) } jret, err := jbobject.CallMethod(javabind.GetEnv(), "equals", javabind.Boolean, conv_a.Value().Cast("java/lang/Object")) if err != nil { panic(err) } conv_a.CleanUp() return jret.(bool) } // public int hashCode() func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) HashCode() int { jret, err := jbobject.CallMethod(javabind.GetEnv(), "hashCode", javabind.Int) if err != nil { panic(err) } return jret.(int) } // public com.amazonaws.services.ec2.model.SlotStartTimeRangeRequest clone() func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) Clone() *ServicesEc2ModelSlotStartTimeRangeRequest { jret, err := jbobject.CallMethod(javabind.GetEnv(), "clone", "com/amazonaws/services/ec2/model/SlotStartTimeRangeRequest") if err != nil { panic(err) } retconv := javabind.NewJavaToGoCallable() dst := &javabind.Callable{} retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() unique_x := &ServicesEc2ModelSlotStartTimeRangeRequest{} unique_x.Callable = dst return unique_x } // public java.lang.Object clone() throws java.lang.CloneNotSupportedException func (jbobject *ServicesEc2ModelSlotStartTimeRangeRequest) Clone2() (*JavaLangObject, error) { jret, err := jbobject.CallMethod(javabind.GetEnv(), "clone", "java/lang/Object") if err != nil { var zero *JavaLangObject return zero, err } retconv := javabind.NewJavaToGoCallable() dst := &javabind.Callable{} retconv.Dest(dst) if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil { panic(err) } retconv.CleanUp() unique_x := &JavaLangObject{} unique_x.Callable = dst return unique_x, nil }
bsd-2-clause
kidaa/pySDC
examples/heat1d/TransferClass.py
4842
from __future__ import division import numpy as np from pySDC.Transfer import transfer from pySDC.datatype_classes.mesh import mesh, rhs_imex_mesh import pySDC.Plugins.transfer_helper as th # FIXME: extend this to ndarrays class mesh_to_mesh_1d(transfer): """ Custon transfer class, implements Transfer.py This implementation can restrict and prolong between 1d meshes, using weigthed restriction and 7th-order prologation via matrix-vector multiplication. Attributes: fine: reference to the fine level coarse: reference to the coarse level init_f: number of variables on the fine level (whatever init represents there) init_c: number of variables on the coarse level (whatever init represents there) Rspace: spatial restriction matrix, dim. Nf x Nc Pspace: spatial prolongation matrix, dim. Nc x Nf """ def __init__(self,fine_level,coarse_level,params): """ Initialization routine Args: fine_level: fine level connected with the transfer operations (passed to parent) coarse_level: coarse level connected with the transfer operations (passed to parent) params: parameters for the transfer operators """ # invoke super initialization super(mesh_to_mesh_1d,self).__init__(fine_level,coarse_level,params) assert params['iorder'] == 6 assert params['rorder'] == 2 # if number of variables is the same on both levels, Rspace and Pspace are identity if self.init_c == self.init_f: self.Rspace = np.eye(self.init_c) # assemble weighted restriction by hand else: self.Rspace = np.zeros((self.init_f,self.init_c)) np.fill_diagonal(self.Rspace[1::2,:],1) np.fill_diagonal(self.Rspace[0::2,:],1/2) np.fill_diagonal(self.Rspace[2::2,:],1/2) self.Rspace = 1/2*self.Rspace.T # if number of variables is the same on both levels, Rspace and Pspace are identity if self.init_f == self.init_c: self.Pspace = np.eye(self.init_f) # assemble 7th-order prolongation by hand else: self.Pspace = np.zeros((self.init_f,self.init_c)) np.fill_diagonal(self.Pspace[1::2,:],1) # np.fill_diagonal(self.Pspace[0::2,:],1/2) # np.fill_diagonal(self.Pspace[2::2,:],1/2) # this would be 3rd-order accurate # c1 = -0.0625 # c2 = 0.5625 # c3 = c2 # c4 = c1 # np.fill_diagonal(self.Pspace[0::2,:],c3) # np.fill_diagonal(self.Pspace[2::2,:],c2) # np.fill_diagonal(self.Pspace[0::2,1:],c4) # np.fill_diagonal(self.Pspace[4::2,:],c1) # self.Pspace[0,0:3] = [0.9375, -0.3125, 0.0625] # self.Pspace[-1,-3:self.init_c] = [0.0625, -0.3125, 0.9375] np.fill_diagonal(self.Pspace[0::2,:],0.5859375) np.fill_diagonal(self.Pspace[2::2,:],0.5859375) np.fill_diagonal(self.Pspace[0::2,1:],-0.09765625) np.fill_diagonal(self.Pspace[4::2,:],-0.09765625) np.fill_diagonal(self.Pspace[0::2,2:],0.01171875) np.fill_diagonal(self.Pspace[6::2,:],0.01171875) self.Pspace[0,0:5] = [1.23046875, -0.8203125, 0.4921875, -0.17578125, 0.02734375] self.Pspace[2,0:5] = [0.41015625, 0.8203125, -0.2734375, 0.08203125, -0.01171875] self.Pspace[-1,-5:self.init_c] = [0.02734375, -0.17578125, 0.4921875, -0.8203125, 1.23046875] self.Pspace[-3,-5:self.init_c] = [-0.01171875, 0.08203125, -0.2734375, 0.8203125, 0.41015625] pass def restrict_space(self,F): """ Restriction implementation Args: F: the fine level data (easier to access than via the fine attribute) """ if isinstance(F,mesh): u_coarse = mesh(self.init_c,val=0) u_coarse.values = self.Rspace.dot(F.values) elif isinstance(F,rhs_imex_mesh): u_coarse = rhs_imex_mesh(self.init_c) u_coarse.impl.values = self.Rspace.dot(F.impl.values) u_coarse.expl.values = self.Rspace.dot(F.expl.values) return u_coarse def prolong_space(self,G): """ Prolongation implementation Args: G: the coarse level data (easier to access than via the coarse attribute) """ if isinstance(G,mesh): u_fine = mesh(self.init_c,val=0) u_fine.values = self.Pspace.dot(G.values) elif isinstance(G,rhs_imex_mesh): u_fine = rhs_imex_mesh(self.init_c) u_fine.impl.values = self.Pspace.dot(G.impl.values) u_fine.expl.values = self.Pspace.dot(G.expl.values) return u_fine
bsd-2-clause
ragnar-johannsson/coreos-pam-sshd
onetime-keypairs/generate_secret.py
114
#!/usr/bin/env python import uuid with open('/var/secret', 'w') as f: f.write('SECRET=%s\n' % uuid.uuid4())
bsd-2-clause
imagej/workflow
src/test/java/imagej/workflow/DummyComponent.java
8962
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2010 - 2014 Board of Regents of the University of * Wisconsin-Madison. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.workflow; import imagej.workflow.plugin.IPluginLauncher; import imagej.workflow.plugin.ItemWrapper; import imagej.workflow.plugin.annotations.Input; import imagej.workflow.plugin.annotations.Output; import imagej.workflow.util.xmllight.XMLException; import imagej.workflow.util.xmllight.XMLParser; import imagej.workflow.util.xmllight.XMLTag; import imagej.workflow.util.xmllight.XMLWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author aivar */ public class DummyComponent implements IModule { public static final String TESTCOMPONENT = "testcomponent"; String m_name; List<String> m_inputNames = new ArrayList<String>(); List<String> m_outputNames = new ArrayList<String>(); public void setInputNames(String[] inputNames) { for (String name: inputNames) { m_inputNames.add(name); } } public void setOutputNames(String[] outputNames) { for (String name: outputNames) { m_outputNames.add(name); } } /** * Gets name of component. * * @return */ public String getName() { return m_name; } /** * Sets name of component. * * @param name */ public void setName(String name) { m_name = name; } public IPluginLauncher getLauncher() { return null; } /** * Saves component as XML string representation. * * @return */ public String toXML() { StringBuilder xmlBuilder = new StringBuilder(); XMLWriter xmlHelper = new XMLWriter(xmlBuilder); // add workflow tag and name xmlHelper.addTag(TESTCOMPONENT); xmlHelper.addTagWithContent(Workflow.NAME, getName()); // add inputs xmlHelper.addTag(Workflow.INPUTS); for (String name : m_inputNames) { xmlHelper.addTag(Workflow.INPUT); xmlHelper.addTagWithContent(Workflow.NAME, name); xmlHelper.addEndTag(Workflow.INPUT); } xmlHelper.addEndTag(Workflow.INPUTS); // add outputs xmlHelper.addTag(Workflow.OUTPUTS); for (String name : m_outputNames) { xmlHelper.addTag(Workflow.OUTPUT); xmlHelper.addTagWithContent(Workflow.NAME, name); xmlHelper.addEndTag(Workflow.OUTPUT); } xmlHelper.addEndTag(Workflow.OUTPUTS); // end workflow xmlHelper.addEndTag(TESTCOMPONENT); return xmlBuilder.toString(); } /** * Restores component from XML string representation. * * @param xml * @return whether successfully parsed */ public boolean fromXML(String xml) { boolean success = false; XMLParser xmlHelper = new XMLParser(); try { // handle test tag and name // // <testcomponent> // <name>A</name> XMLTag tag = xmlHelper.getNextTag(xml); if (!TESTCOMPONENT.equals(tag.getName())) { throw new XMLException("Missing <testcomponent> tag"); } xml = tag.getContent(); tag = xmlHelper.getNextTag(xml); if (!Workflow.NAME.equals(tag.getName())) { throw new XMLException("Missing <name> for <workflow>"); } setName(tag.getContent()); xml = tag.getRemainder(); // handle inputs // // <inputs> // <input> // <name>RED</name> // </input> // </inputs> tag = xmlHelper.getNextTag(xml); if (!Workflow.INPUTS.equals(tag.getName())) { throw new XMLException("Missing <inputs> within <testcomponent>"); } String inputsXML = tag.getContent(); xml = tag.getRemainder(); while (!inputsXML.isEmpty()) { tag = xmlHelper.getNextTag(inputsXML); inputsXML = tag.getRemainder(); if (tag.getName().isEmpty()) { //TODO don't think these are necessary break; } if (!Workflow.INPUT.equals(tag.getName())) { throw new XMLException("Missing <input> within <inputs"); } String inputXML = tag.getContent(); tag = xmlHelper.getNextTag(inputXML); inputXML = tag.getRemainder(); if (!Workflow.NAME.equals(tag.getName())) { throw new XMLException("Missing <name> within <input>"); } String inName = tag.getContent(); m_inputNames.add(inName); } // handle outputs // <outputs> // <output> // <name>OUTPUT</name> // </output> // </outputs> tag = xmlHelper.getNextTag(xml); if (!Workflow.OUTPUTS.equals(tag.getName())) { throw new XMLException("Missing <outputs> within <testcomponent>"); } String outputsXML = tag.getContent(); xml = tag.getRemainder(); while (!outputsXML.isEmpty()) { tag = xmlHelper.getNextTag(outputsXML); outputsXML = tag.getRemainder(); if (tag.getName().isEmpty()) { //TODO don't think these are necessary break; } if (!Workflow.OUTPUT.equals(tag.getName())) { throw new XMLException("Missing <output> within <outputs>"); } String outputXML = tag.getContent(); tag = xmlHelper.getNextTag(outputXML); outputXML = tag.getRemainder(); if (!Workflow.NAME.equals(tag.getName())) { throw new XMLException("Missing <name> within <output>"); } String outName = tag.getContent(); m_outputNames.add(outName); } success = true; } catch (XMLException e) { System.out.println("XML Exception"); } return success; } /** * Gets input image names. * * @return */ public String[] getInputNames() { return m_inputNames.toArray(new String[0]); } /** * Gets output names. * * @return */ public String[] getOutputNames() { return m_outputNames.toArray(new String[0]); } /** * Sets input settings. * * @param inputs */ public void setInputs(Map<String, Object> inputs) { //TODO } /** * Furnish input image * * @param image */ public void input(ItemWrapper image) { input(image, Input.DEFAULT); } /** * Furnish input image * * @param image * @param name */ public void input(ItemWrapper image, String name) { //TODO } /** * Listen for output image. * * @param name * @param listener */ public void setOutputListener(IOutputListener listener) { setOutputListener(Output.DEFAULT, listener); } /** * Listen for output image. * * @param name * @param listener */ public void setOutputListener(String name, IOutputListener listener) { //TODO } }
bsd-2-clause
winlolo/frapi
src/frapi/custom/AllFiles.php
556
<?php // If you remove this. You might die. define('FRAPI_CACHE_ADAPTER', 'apc'); // Use the constant CUSTOM_MODEL to access the custom model directory // IE: require CUSTOM_MODEL . DIRECTORY_SEPARATOR . 'ModelName.php'; // Or add an autolaoder if you are brave. // Other data defined('CUSTOM_LIBRARY') || define('CUSTOM_LIBRARY', CUSTOM_PATH. DIRECTORY_SEPARATOR . 'Library'); defined('CUSTOM_LIBRARY_FRAPI_PLUGINS') || define('CUSTOM_LIBRARY_FRAPI_PLUGINS', CUSTOM_LIBRARY . DIRECTORY_SEPARATOR . 'Frapi' . DIRECTORY_SEPARATOR . 'Plugins');
bsd-2-clause
ibrarahmad/cstore
src/OptPlan/Opt_Agg_Max.cpp
803
/* * Opt_Agg_Max.h * C-Store - Optimimzation * * Created by Nga Tran on 11/01/05. * * Questions, ask Nga Tran at nga@brandeis.edu or Tien Hoang at hoangt@brandeis.edu * * This class implements max aggregate */ #include "Opt_Agg_Max.h" // Default constructor Opt_Agg_Max::Opt_Agg_Max() : Opt_Agg() { } // Provide column and table names Opt_Agg_Max::Opt_Agg_Max(string sColumnName, string sTableName) : Opt_Agg(sColumnName, sTableName, "max") { } // Provide a column Opt_Agg_Max::Opt_Agg_Max(Opt_Object* ptrAgg) : Opt_Agg(ptrAgg, "max") { } // Default Destructor Opt_Agg_Max::~Opt_Agg_Max() { } // Clone Opt_Agg_Max* Opt_Agg_Max::clone() { Opt_Object* ptrAgg = NULL; if (m_ptrAggExpression != NULL) ptrAgg = m_ptrAggExpression->clone(); return new Opt_Agg_Max(ptrAgg); }
bsd-2-clause
chriskl/phpssrs
library/PhpSsrs/ReportingService2005/ParameterFieldReference.php
548
<?php namespace PhpSsrs\ReportingService2005; class ParameterFieldReference { /** * * @var string $ParameterName * @access public */ public $ParameterName = null; /** * * @var string $FieldAlias * @access public */ public $FieldAlias = null; /** * * @param string $ParameterName * @param string $FieldAlias * @access public */ public function __construct($ParameterName = null, $FieldAlias = null) { $this->ParameterName = $ParameterName; $this->FieldAlias = $FieldAlias; } }
bsd-2-clause
baixuexue123/note
python/tornado/helloworld1.py
911
#!/usr/bin/env python import pprint import tornado.web import tornado.gen import tornado.escape import tornado.httpserver from tornado.ioloop import IOLoop from tornado.concurrent import Future from tornado.options import define, options, parse_command_line from tornado.log import app_log def handle_request(request): print(type(request)) message = "You requested %s\n" % request.uri request.write(tornado.escape.utf8("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % (len(message), message))) request.finish() def main(): define("port", default=8000, help="run on the given port", type=int) parse_command_line() server = tornado.httpserver.HTTPServer(handle_request) server.listen(options.port, address='127.0.0.1') pprint.pprint(server.io_loop._handlers) IOLoop.current().start() if __name__ == "__main__": main()
bsd-2-clause
zoetrope/ReactiveRTM
Sample/ObservableSensor/Program.cs
899
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Text; using Microsoft.Research.Kinect.Nui; /// <summary> /// センサを監視するサンプル /// </summary> class Program { public static void Main(string[] args) { var runtime = new Runtime(); runtime.Initialize(RuntimeOptions.UseSkeletalTracking); var observer = runtime.SkeletonFrameReadyAsObservable(); } } internal static class KinectExtensions { public static IObservable<SkeletonFrameReadyEventArgs> SkeletonFrameReadyAsObservable(this Runtime nui) { return Observable.FromEventPattern<SkeletonFrameReadyEventArgs>( h => nui.SkeletonFrameReady += h, h => nui.SkeletonFrameReady -= h) .Select(e => e.EventArgs); } }
bsd-2-clause
hurricane1026/highway
src/toller/packet.go
4362
package toller import ( "bufio" "io" //"fmt" ) type pktReader struct { rd *bufio.Reader seq *byte remain int last bool buf [8]byte ibuf [3]byte } func (my *BackConn) newPktReader() *pktReader { return &pktReader{rd: my.rd, seq: &my.seq} } func (fc *FrontConn) newPktReader() *pktReader { return &pktReader{rd: fc.rd, seq: &fc.seq} } func (pr *pktReader) readHeader() { // Read next packet header buf := pr.ibuf[:] for { n, err := pr.rd.Read(buf) if err != nil { panic(err) } buf = buf[n:] if len(buf) == 0 { break } } pr.remain = int(DecodeU24(pr.ibuf[:])) seq, err := pr.rd.ReadByte() if err != nil { panic(err) } // Chceck sequence number if *pr.seq != seq { panic(ErrSeq) } *pr.seq++ // Last packet? pr.last = (pr.remain != 0xffffff) } func (pr *pktReader) readFull(buf []byte) { for len(buf) > 0 { if pr.remain == 0 { if pr.last { // No more packets panic(io.EOF) } pr.readHeader() } n := len(buf) if n > pr.remain { n = pr.remain } n, err := pr.rd.Read(buf[:n]) pr.remain -= n if err != nil { panic(err) } buf = buf[n:] } return } func (pr *pktReader) readByte() byte { if pr.remain == 0 { if pr.last { // No more packets panic(io.EOF) } pr.readHeader() } b, err := pr.rd.ReadByte() if err != nil { panic(err) } pr.remain-- return b } func (pr *pktReader) readAll() (buf []byte) { m := 0 for { if pr.remain == 0 { if pr.last { break } pr.readHeader() } new_buf := make([]byte, m+pr.remain) copy(new_buf, buf) buf = new_buf n, err := pr.rd.Read(buf[m:]) pr.remain -= n m += n if err != nil { panic(err) } } return } var skipBuf [4069]byte func (pr *pktReader) skipAll() { for { if pr.remain == 0 { if pr.last { break } pr.readHeader() } n := len(skipBuf) if n > pr.remain { n = pr.remain } n, err := pr.rd.Read(skipBuf[:n]) pr.remain -= n if err != nil { panic(err) } } return } // works only for n <= len(skipBuf) func (pr *pktReader) skipN(n int) { for n > 0 { if pr.remain == 0 { if pr.last { panic(io.EOF) } pr.readHeader() } m := n if m > len(skipBuf) { m = len(skipBuf) } if m > pr.remain { m = pr.remain } m, err := pr.rd.Read(skipBuf[:m]) pr.remain -= m n -= m if err != nil { panic(err) } } return } func (pr *pktReader) unreadByte() { if err := pr.rd.UnreadByte(); err != nil { panic(err) } pr.remain++ } func (pr *pktReader) eof() bool { return pr.remain == 0 && pr.last } func (pr *pktReader) checkEof() { if !pr.eof() { panic(ErrPktLong) } } type pktWriter struct { wr *bufio.Writer seq *byte remain int to_write int last bool buf [23]byte ibuf [3]byte } func (my *BackConn) newPktWriter(to_write int) *pktWriter { return &pktWriter{wr: my.wr, seq: &my.seq, to_write: to_write} } func (fc *FrontConn) newPktWriter(to_write int) *pktWriter { return &pktWriter{wr: fc.wr, seq: &fc.seq, to_write: to_write} } func (pw *pktWriter) writeHeader(l int) { buf := pw.ibuf[:] EncodeU24(buf, uint32(l)) if _, err := pw.wr.Write(buf); err != nil { panic(err) } if err := pw.wr.WriteByte(*pw.seq); err != nil { panic(err) } // Update sequence number *pw.seq++ } func (pw *pktWriter) write(buf []byte) { if len(buf) == 0 { return } var nn int for len(buf) != 0 { //fmt.Printf("count len of buf: %d\n", len(buf)) if pw.remain == 0 { if pw.to_write == 0 { panic("too many data for write as packet") } if pw.to_write >= 0xffffff { pw.remain = 0xffffff } else { pw.remain = pw.to_write pw.last = true } pw.to_write -= pw.remain pw.writeHeader(pw.remain) } nn = len(buf) if nn > pw.remain { nn = pw.remain } var err error nn, err = pw.wr.Write(buf[0:nn]) pw.remain -= nn if err != nil { panic(err) } buf = buf[nn:] } if pw.remain+pw.to_write == 0 { if !pw.last { // Write header for empty packet pw.writeHeader(0) } // Flush bufio buffers if err := pw.wr.Flush(); err != nil { panic(err) } } return } func (pw *pktWriter) writeByte(b byte) { pw.buf[0] = b pw.write(pw.buf[:1]) } // n should be <= 23 func (pw *pktWriter) writeZeros(n int) { buf := pw.buf[:n] for i := range buf { buf[i] = 0 } pw.write(buf) }
bsd-2-clause
Carllawrence/StarsMobileApp
www/bower_components/angular-material/modules/js/fabSpeedDial/fabSpeedDial.js
18542
/*! * AngularJS Material Design * https://github.com/angular/material * @license MIT * v1.1.9 */ (function( window, angular, undefined ){ "use strict"; (function() { 'use strict'; MdFabController['$inject'] = ["$scope", "$element", "$animate", "$mdUtil", "$mdConstant", "$timeout"]; angular.module('material.components.fabShared', ['material.core']) .controller('MdFabController', MdFabController); function MdFabController($scope, $element, $animate, $mdUtil, $mdConstant, $timeout) { var vm = this; var initialAnimationAttempts = 0; // NOTE: We use async eval(s) below to avoid conflicts with any existing digest loops vm.open = function() { $scope.$evalAsync("vm.isOpen = true"); }; vm.close = function() { // Async eval to avoid conflicts with existing digest loops $scope.$evalAsync("vm.isOpen = false"); // Focus the trigger when the element closes so users can still tab to the next item $element.find('md-fab-trigger')[0].focus(); }; // Toggle the open/close state when the trigger is clicked vm.toggle = function() { $scope.$evalAsync("vm.isOpen = !vm.isOpen"); }; /* * AngularJS Lifecycle hook for newer AngularJS versions. * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook. */ vm.$onInit = function() { setupDefaults(); setupListeners(); setupWatchers(); fireInitialAnimations(); }; // For AngularJS 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned, // manually call the $onInit hook. if (angular.version.major === 1 && angular.version.minor <= 4) { this.$onInit(); } function setupDefaults() { // Set the default direction to 'down' if none is specified vm.direction = vm.direction || 'down'; // Set the default to be closed vm.isOpen = vm.isOpen || false; // Start the keyboard interaction at the first action resetActionIndex(); // Add an animations waiting class so we know not to run $element.addClass('md-animations-waiting'); } function setupListeners() { var eventTypes = [ 'click', 'focusin', 'focusout' ]; // Add our listeners angular.forEach(eventTypes, function(eventType) { $element.on(eventType, parseEvents); }); // Remove our listeners when destroyed $scope.$on('$destroy', function() { angular.forEach(eventTypes, function(eventType) { $element.off(eventType, parseEvents); }); // remove any attached keyboard handlers in case element is removed while // speed dial is open disableKeyboard(); }); } var closeTimeout; function parseEvents(event) { // If the event is a click, just handle it if (event.type == 'click') { handleItemClick(event); } // If we focusout, set a timeout to close the element if (event.type == 'focusout' && !closeTimeout) { closeTimeout = $timeout(function() { vm.close(); }, 100, false); } // If we see a focusin and there is a timeout about to run, cancel it so we stay open if (event.type == 'focusin' && closeTimeout) { $timeout.cancel(closeTimeout); closeTimeout = null; } } function resetActionIndex() { vm.currentActionIndex = -1; } function setupWatchers() { // Watch for changes to the direction and update classes/attributes $scope.$watch('vm.direction', function(newDir, oldDir) { // Add the appropriate classes so we can target the direction in the CSS $animate.removeClass($element, 'md-' + oldDir); $animate.addClass($element, 'md-' + newDir); // Reset the action index since it may have changed resetActionIndex(); }); var trigger, actions; // Watch for changes to md-open $scope.$watch('vm.isOpen', function(isOpen) { // Reset the action index since it may have changed resetActionIndex(); // We can't get the trigger/actions outside of the watch because the component hasn't been // linked yet, so we wait until the first watch fires to cache them. if (!trigger || !actions) { trigger = getTriggerElement(); actions = getActionsElement(); } if (isOpen) { enableKeyboard(); } else { disableKeyboard(); } var toAdd = isOpen ? 'md-is-open' : ''; var toRemove = isOpen ? '' : 'md-is-open'; // Set the proper ARIA attributes trigger.attr('aria-haspopup', true); trigger.attr('aria-expanded', isOpen); actions.attr('aria-hidden', !isOpen); // Animate the CSS classes $animate.setClass($element, toAdd, toRemove); }); } function fireInitialAnimations() { // If the element is actually visible on the screen if ($element[0].scrollHeight > 0) { // Fire our animation $animate.addClass($element, '_md-animations-ready').then(function() { // Remove the waiting class $element.removeClass('md-animations-waiting'); }); } // Otherwise, try for up to 1 second before giving up else if (initialAnimationAttempts < 10) { $timeout(fireInitialAnimations, 100); // Increment our counter initialAnimationAttempts = initialAnimationAttempts + 1; } } function enableKeyboard() { $element.on('keydown', keyPressed); // On the next tick, setup a check for outside clicks; we do this on the next tick to avoid // clicks/touches that result in the isOpen attribute changing (e.g. a bound radio button) $mdUtil.nextTick(function() { angular.element(document).on('click touchend', checkForOutsideClick); }); // TODO: On desktop, we should be able to reset the indexes so you cannot tab through, but // this breaks accessibility, especially on mobile, since you have no arrow keys to press //resetActionTabIndexes(); } function disableKeyboard() { $element.off('keydown', keyPressed); angular.element(document).off('click touchend', checkForOutsideClick); } function checkForOutsideClick(event) { if (event.target) { var closestTrigger = $mdUtil.getClosest(event.target, 'md-fab-trigger'); var closestActions = $mdUtil.getClosest(event.target, 'md-fab-actions'); if (!closestTrigger && !closestActions) { vm.close(); } } } function keyPressed(event) { switch (event.which) { case $mdConstant.KEY_CODE.ESCAPE: vm.close(); event.preventDefault(); return false; case $mdConstant.KEY_CODE.LEFT_ARROW: doKeyLeft(event); return false; case $mdConstant.KEY_CODE.UP_ARROW: doKeyUp(event); return false; case $mdConstant.KEY_CODE.RIGHT_ARROW: doKeyRight(event); return false; case $mdConstant.KEY_CODE.DOWN_ARROW: doKeyDown(event); return false; } } function doActionPrev(event) { focusAction(event, -1); } function doActionNext(event) { focusAction(event, 1); } function focusAction(event, direction) { var actions = resetActionTabIndexes(); // Increment/decrement the counter with restrictions vm.currentActionIndex = vm.currentActionIndex + direction; vm.currentActionIndex = Math.min(actions.length - 1, vm.currentActionIndex); vm.currentActionIndex = Math.max(0, vm.currentActionIndex); // Focus the element var focusElement = angular.element(actions[vm.currentActionIndex]).children()[0]; angular.element(focusElement).attr('tabindex', 0); focusElement.focus(); // Make sure the event doesn't bubble and cause something else event.preventDefault(); event.stopImmediatePropagation(); } function resetActionTabIndexes() { // Grab all of the actions var actions = getActionsElement()[0].querySelectorAll('.md-fab-action-item'); // Disable all other actions for tabbing angular.forEach(actions, function(action) { angular.element(angular.element(action).children()[0]).attr('tabindex', -1); }); return actions; } function doKeyLeft(event) { if (vm.direction === 'left') { doActionNext(event); } else { doActionPrev(event); } } function doKeyUp(event) { if (vm.direction === 'down') { doActionPrev(event); } else { doActionNext(event); } } function doKeyRight(event) { if (vm.direction === 'left') { doActionPrev(event); } else { doActionNext(event); } } function doKeyDown(event) { if (vm.direction === 'up') { doActionPrev(event); } else { doActionNext(event); } } function isTrigger(element) { return $mdUtil.getClosest(element, 'md-fab-trigger'); } function isAction(element) { return $mdUtil.getClosest(element, 'md-fab-actions'); } function handleItemClick(event) { if (isTrigger(event.target)) { vm.toggle(); } if (isAction(event.target)) { vm.close(); } } function getTriggerElement() { return $element.find('md-fab-trigger'); } function getActionsElement() { return $element.find('md-fab-actions'); } } })(); (function() { 'use strict'; /** * The duration of the CSS animation in milliseconds. * * @type {number} */ MdFabSpeedDialFlingAnimation['$inject'] = ["$timeout"]; MdFabSpeedDialScaleAnimation['$inject'] = ["$timeout"]; var cssAnimationDuration = 300; /** * @ngdoc module * @name material.components.fabSpeedDial */ angular // Declare our module .module('material.components.fabSpeedDial', [ 'material.core', 'material.components.fabShared', 'material.components.fabActions' ]) // Register our directive .directive('mdFabSpeedDial', MdFabSpeedDialDirective) // Register our custom animations .animation('.md-fling', MdFabSpeedDialFlingAnimation) .animation('.md-scale', MdFabSpeedDialScaleAnimation) // Register a service for each animation so that we can easily inject them into unit tests .service('mdFabSpeedDialFlingAnimation', MdFabSpeedDialFlingAnimation) .service('mdFabSpeedDialScaleAnimation', MdFabSpeedDialScaleAnimation); /** * @ngdoc directive * @name mdFabSpeedDial * @module material.components.fabSpeedDial * * @restrict E * * @description * The `<md-fab-speed-dial>` directive is used to present a series of popup elements (usually * `<md-button>`s) for quick access to common actions. * * There are currently two animations available by applying one of the following classes to * the component: * * - `md-fling` - The speed dial items appear from underneath the trigger and move into their * appropriate positions. * - `md-scale` - The speed dial items appear in their proper places by scaling from 0% to 100%. * * You may also easily position the trigger by applying one one of the following classes to the * `<md-fab-speed-dial>` element: * - `md-fab-top-left` * - `md-fab-top-right` * - `md-fab-bottom-left` * - `md-fab-bottom-right` * * These CSS classes use `position: absolute`, so you need to ensure that the container element * also uses `position: absolute` or `position: relative` in order for them to work. * * Additionally, you may use the standard `ng-mouseenter` and `ng-mouseleave` directives to * open or close the speed dial. However, if you wish to allow users to hover over the empty * space where the actions will appear, you must also add the `md-hover-full` class to the speed * dial element. Without this, the hover effect will only occur on top of the trigger. * * See the demos for more information. * * ## Troubleshooting * * If your speed dial shows the closing animation upon launch, you may need to use `ng-cloak` on * the parent container to ensure that it is only visible once ready. We have plans to remove this * necessity in the future. * * @usage * <hljs lang="html"> * <md-fab-speed-dial md-direction="up" class="md-fling"> * <md-fab-trigger> * <md-button aria-label="Add..."><md-icon md-svg-src="/img/icons/plus.svg"></md-icon></md-button> * </md-fab-trigger> * * <md-fab-actions> * <md-button aria-label="Add User"> * <md-icon md-svg-src="/img/icons/user.svg"></md-icon> * </md-button> * * <md-button aria-label="Add Group"> * <md-icon md-svg-src="/img/icons/group.svg"></md-icon> * </md-button> * </md-fab-actions> * </md-fab-speed-dial> * </hljs> * * @param {string} md-direction From which direction you would like the speed dial to appear * relative to the trigger element. * @param {expression=} md-open Programmatically control whether or not the speed-dial is visible. */ function MdFabSpeedDialDirective() { return { restrict: 'E', scope: { direction: '@?mdDirection', isOpen: '=?mdOpen' }, bindToController: true, controller: 'MdFabController', controllerAs: 'vm', link: FabSpeedDialLink }; function FabSpeedDialLink(scope, element) { // Prepend an element to hold our CSS variables so we can use them in the animations below element.prepend('<div class="_md-css-variables"></div>'); } } function MdFabSpeedDialFlingAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } function runAnimation(element) { // Don't run if we are still waiting and we are not ready if (element.hasClass('md-animations-waiting') && !element.hasClass('_md-animations-ready')) { return; } var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our trigger element var triggerElement = el.querySelector('md-fab-trigger'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style; styles.transform = styles.webkitTransform = ''; styles.transitionDelay = ''; styles.opacity = 1; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); // Set the trigger to be above all of the actions so they disappear behind it. triggerElement.style.zIndex = startZIndex + items.length + 1; // If the control is closed, hide the items behind the trigger if (!ctrl.isOpen) { angular.forEach(items, function(item, index) { var newPosition, axis; var styles = item.style; // Make sure to account for differences in the dimensions of the trigger verses the items // so that we can properly center everything; this helps hide the item's shadows behind // the trigger. var triggerItemHeightOffset = (triggerElement.clientHeight - item.clientHeight) / 2; var triggerItemWidthOffset = (triggerElement.clientWidth - item.clientWidth) / 2; switch (ctrl.direction) { case 'up': newPosition = (item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'down': newPosition = -(item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'left': newPosition = (item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; case 'right': newPosition = -(item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; } var newTranslate = 'translate' + axis + '(' + newPosition + 'px)'; styles.transform = styles.webkitTransform = newTranslate; }); } } return { addClass: function(element, className, done) { if (element.hasClass('md-fling')) { runAnimation(element); delayDone(done); } else { done(); } }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } }; } function MdFabSpeedDialScaleAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } var delay = 65; function runAnimation(element) { var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style, offsetDelay = index * delay; styles.opacity = ctrl.isOpen ? 1 : 0; styles.transform = styles.webkitTransform = ctrl.isOpen ? 'scale(1)' : 'scale(0)'; styles.transitionDelay = (ctrl.isOpen ? offsetDelay : (items.length - offsetDelay)) + 'ms'; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); } return { addClass: function(element, className, done) { runAnimation(element); delayDone(done); }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } }; } })(); })(window, window.angular);
bsd-2-clause
rwhogg/brew
Library/Homebrew/os/linux/elf.rb
3846
require "os/linux/architecture_list" module ELF # @private LDD_RX = /\t.* => (.*) \(.*\)|\t(.*) => not found/ # ELF data # @private def elf_data @elf_data ||= begin header = read(8).unpack("N2") case header[0] when 0x7f454c46 # ELF arch = case read(2, 18).unpack("v")[0] when 3 then :i386 when 62 then :x86_64 else :dunno end type = case read(2, 16).unpack("v")[0] when 2 then :executable when 3 then :dylib else :dunno end [{ arch: arch, type: type }] else raise "Not an ELF binary." end rescue [] end end # @private class Metadata attr_reader :path, :dylib_id, :dylibs def initialize(path) @path = path @dylib_id, needed = if DevelopmentTools.locate "readelf" elf_soname_needed_readelf path elsif DevelopmentTools.locate "patchelf" elf_soname_needed_patchelf path else odie "patchelf must be installed: brew install patchelf" end if needed.empty? || path.arch != Hardware::CPU.arch @dylibs = [] return end begin ldd = Formula["glibc"].bin/"ldd" ldd = "ldd" unless ldd.executable? rescue FormulaUnavailableError ldd = "ldd" end command = [ldd, path.expand_path.to_s] libs = Utils.popen_read(*command).split("\n") raise ErrorDuringExecution, command unless $?.success? needed << "not found" libs.select! { |lib| needed.any? { |soname| lib.include? soname } } @dylibs = libs.map { |lib| lib[LDD_RX, 1] || lib[LDD_RX, 2] }.compact end private def elf_soname_needed_patchelf(path) patchelf = DevelopmentTools.locate "patchelf" if path.dylib? command = [patchelf, "--print-soname", path.expand_path.to_s] soname = Utils.popen_read(*command).chomp raise ErrorDuringExecution, command unless $?.success? end command = [patchelf, "--print-needed", path.expand_path.to_s] needed = Utils.popen_read(*command).split("\n") raise ErrorDuringExecution, command unless $?.success? [soname, needed] end def elf_soname_needed_readelf(path) soname = nil needed = [] command = ["readelf", "-d", path.expand_path.to_s] lines = Utils.popen_read(*command).split("\n") raise ErrorDuringExecution, command unless $?.success? lines.each do |s| case s when /\(SONAME\)/ soname = s[/\[(.*)\]/, 1] when /\(NEEDED\)/ needed << s[/\[(.*)\]/, 1] end end [soname, needed] end end # @private def metadata @metadata ||= Metadata.new(self) end # Returns an array containing all dynamically-linked libraries, based on the # output of ldd. # Returns an empty array both for software that links against no libraries, # and for non-ELF objects. # @private def dynamically_linked_libraries(except: :none) # The argument except is unused. puts if except == :unused metadata.dylibs end # Return the SONAME of an ELF shared library. # @private def dylib_id metadata.dylib_id end def archs elf_data.map { |m| m.fetch :arch }.extend(ArchitectureListExtension) end def arch archs.length == 1 ? archs.first : :dunno end def universal? false end def i386? arch == :i386 end def x86_64? arch == :x86_64 end def ppc7400? arch == :ppc7400 end def ppc64? arch == :ppc64 end # @private def dylib? elf_data.any? { |m| m.fetch(:type) == :dylib } end # @private def mach_o_executable? elf_data.any? { |m| m.fetch(:type) == :executable } end # @private def mach_o_bundle? elf_data.any? { |m| m.fetch(:type) == :bundle } end end
bsd-2-clause
applesrc/WebCore
dom/Event.cpp
4837
/* * Copyright (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de) * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * Copyright (C) 2003, 2005, 2006, 2008, 2013 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "Event.h" #include "EventNames.h" #include "EventPath.h" #include "EventTarget.h" #include "UserGestureIndicator.h" #include <wtf/CurrentTime.h> namespace WebCore { Event::Event() : m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { } Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg) : m_type(eventType) , m_isInitialized(true) , m_canBubble(canBubbleArg) , m_cancelable(cancelableArg) , m_isTrusted(true) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { } Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, double timestamp) : m_type(eventType) , m_isInitialized(true) , m_canBubble(canBubbleArg) , m_cancelable(cancelableArg) , m_isTrusted(true) , m_createTime(convertSecondsToDOMTimeStamp(timestamp)) { } Event::Event(const AtomicString& eventType, const EventInit& initializer) : m_type(eventType) , m_isInitialized(true) , m_canBubble(initializer.bubbles) , m_cancelable(initializer.cancelable) , m_composed(initializer.composed) , m_createTime(convertSecondsToDOMTimeStamp(currentTime())) { } Event::~Event() { } void Event::initEvent(const AtomicString& eventTypeArg, bool canBubbleArg, bool cancelableArg) { if (dispatched()) return; m_isInitialized = true; m_propagationStopped = false; m_immediatePropagationStopped = false; m_defaultPrevented = false; m_isTrusted = false; m_type = eventTypeArg; m_canBubble = canBubbleArg; m_cancelable = cancelableArg; } bool Event::composed() const { if (m_composed) return true; // http://w3c.github.io/webcomponents/spec/shadow/#scoped-flag if (!isTrusted()) return false; return m_type == eventNames().inputEvent || m_type == eventNames().textInputEvent || m_type == eventNames().DOMActivateEvent || isCompositionEvent() || isClipboardEvent() || isFocusEvent() || isKeyboardEvent() || isMouseEvent() || isTouchEvent(); } EventInterface Event::eventInterface() const { return EventInterfaceType; } bool Event::isUIEvent() const { return false; } bool Event::isMouseEvent() const { return false; } bool Event::isFocusEvent() const { return false; } bool Event::isKeyboardEvent() const { return false; } bool Event::isCompositionEvent() const { return false; } bool Event::isTouchEvent() const { return false; } bool Event::isDragEvent() const { return false; } bool Event::isClipboardEvent() const { return false; } bool Event::isBeforeTextInsertedEvent() const { return false; } bool Event::isBeforeUnloadEvent() const { return false; } bool Event::isErrorEvent() const { return false; } bool Event::isTextEvent() const { return false; } bool Event::isWheelEvent() const { return false; } Ref<Event> Event::cloneFor(HTMLIFrameElement*) const { return Event::create(type(), bubbles(), cancelable()); } void Event::setTarget(RefPtr<EventTarget>&& target) { if (m_target == target) return; m_target = WTFMove(target); if (m_target) receivedTarget(); } Vector<EventTarget*> Event::composedPath() const { if (!m_eventPath) return Vector<EventTarget*>(); return m_eventPath->computePathUnclosedToTarget(*m_currentTarget); } void Event::receivedTarget() { } void Event::setUnderlyingEvent(Event* underlyingEvent) { // Prohibit creation of a cycle -- just do nothing in that case. for (Event* event = underlyingEvent; event; event = event->underlyingEvent()) { if (event == this) return; } m_underlyingEvent = underlyingEvent; } } // namespace WebCore
bsd-2-clause
jackstraw66/web
livescribe/lsregistration/src/main/java/com/livescribe/web/registration/response/RegistrationHistoryListResponse.java
1767
package com.livescribe.web.registration.response; import java.util.ArrayList; import java.util.List; import com.livescribe.framework.orm.vectordb.RegistrationHistory; import com.livescribe.framework.web.response.ResponseCode; import com.livescribe.framework.web.response.ServiceResponse; import com.livescribe.web.registration.dto.RegistrationHistoryDTO; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("response") public class RegistrationHistoryListResponse extends ServiceResponse { @XStreamAlias("registrations") private List<RegistrationHistoryDTO> registrationHistories; /** * Constructor * * @param responseCode */ public RegistrationHistoryListResponse() { super(); registrationHistories = new ArrayList<RegistrationHistoryDTO>(); } /** * Constructor * * @param responseCode */ public RegistrationHistoryListResponse(ResponseCode responseCode) { super(responseCode); registrationHistories = new ArrayList<RegistrationHistoryDTO>(); } /** * Constructor * * @param responseCode * @param regs */ public RegistrationHistoryListResponse(ResponseCode responseCode, List<RegistrationHistory> regHistories) { super(responseCode); this.registrationHistories = new ArrayList<RegistrationHistoryDTO>(); if (regHistories != null) { for (RegistrationHistory regHistory : regHistories) { RegistrationHistoryDTO regDTO = new RegistrationHistoryDTO(regHistory); this.registrationHistories.add(regDTO); } } } public List<RegistrationHistoryDTO> getRegistrationHistories() { return registrationHistories; } public void setRegistrationHistories( List<RegistrationHistoryDTO> registrationHistories) { this.registrationHistories = registrationHistories; } }
bsd-2-clause
LinuxbrewTestBot/homebrew-core
Formula/pnpm.rb
1001
class Pnpm < Formula require "language/node" desc "📦🚀 Fast, disk space efficient package manager" homepage "https://pnpm.js.org" url "https://registry.npmjs.org/pnpm/-/pnpm-4.7.1.tgz" sha256 "957e573ac1552c0c8793a72eab192e11e7473b84e7c6bfde1c31d0224d234f20" bottle do cellar :any_skip_relocation sha256 "443c20c378d924da19765f3cc780e99e463f004364675db8257779f5880ed0b5" => :catalina sha256 "74e864c4f16e4bab9efcdd7545bea790b90f19e998815789aa404ae7cb5af566" => :mojave sha256 "4512b756e24d008a252abd0b68bbdffc3b3818e224a905c2b0912f144008c0f3" => :high_sierra sha256 "981f413f8ae8ccfe51bb6d18548509c01e477479232d2a71adb8e349b91a69af" => :x86_64_linux end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do system "#{bin}/pnpm", "init", "-y" assert_predicate testpath/"package.json", :exist?, "package.json must exist" end end
bsd-2-clause
jeffque/Syncthia-SQL-DBCreator
src/main/java/br/com/jq/syncthia/bdcreator/schema/ExistingSchemaCollection.java
2852
package br.com.jq.syncthia.bdcreator.schema; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import br.com.jq.syncthia.bdcreator.table.MigratableSelectable; import br.com.jq.syncthia.bdcreator.table.Table; import br.com.jq.syncthia.bdcreator.table.View; class ExistingSchemaCollection extends SchemaCollectionInternal { protected List<ExistingSchema> schemasFromDB; public ExistingSchemaCollection(Connection sqlConnection) { setConnection(sqlConnection); schemasFromDB = new ArrayList<ExistingSchema>(); if (sqlConnection != null) { searchMetadata(); } } private void searchMetadata() { try { searchSchemas(); searchTables(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void searchSchemas() throws SQLException { Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM REGISTERED_SCHEMA"); while(rs.next()) { ExistingSchema schema = new ExistingSchema(); String schemaName = rs.getString("SCHEMA_NAME"); String schemaVersion = rs.getString("SCHEMA_VERSION"); schema.setName(schemaName); schema.setRegisteredVersion(schemaVersion); registerExistingSchema(schema); } rs.close(); stmt.close(); } private void searchTables() throws SQLException { Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM MIGRATABLE_VERSION"); while (rs.next()) { String schemaName = rs.getString("MIGRATABLE_SCHEMA_NAME"); String schemaVersion = rs.getString("MIGRATABLE_SCHEMA_VERSION"); ExistingSchema schema = getExistingSchema(schemaName); String migratableName = rs.getString("MIGRATABLE_NAME"); String migratableType = rs.getString("MIGRATABLE_TYPE"); MigratableSelectable m; switch (migratableType) { case "T": m = new Table(); break; case "V": m = new View(); break; default: m = null; } if (m != null) { m.setName(migratableName); m.setRegisteredVersion(schemaVersion); switch (migratableType) { case "T": schema.addTable((Table) m); break; case "V": schema.addView((View) m); } } } rs.close(); stmt.close(); } private ExistingSchema getExistingSchema(String schemaName) { for (ExistingSchema schema: schemasFromDB) { if (schemaName.equals(schema.getName())) { return schema; } } return null; } public void registerExistingSchema(ExistingSchema schema) { registerDefinitor(schema); schemasFromDB.add(schema); } public List<ExistingSchema> getExistingSchemas() { return schemasFromDB; } }
bsd-2-clause
sroycode/Project-OSRM-Server
prepare.cpp
18618
/* Copyright (c) 2013, Project OSRM, Dennis Luxen, others All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Algorithms/IteratorBasedCRC32.h" #include "Contractor/Contractor.h" #include "Contractor/EdgeBasedGraphFactory.h" #include "DataStructures/BinaryHeap.h" #include "DataStructures/DeallocatingVector.h" #include "DataStructures/QueryEdge.h" #include "DataStructures/StaticGraph.h" #include "DataStructures/StaticRTree.h" #include "Util/GitDescription.h" #include "Util/GraphLoader.h" #include "Util/InputFileUtil.h" #include "Util/LuaUtil.h" #include "Util/OpenMPWrapper.h" #include "Util/OSRMException.h" #include "Util/ProgramOptions.h" #include "Util/SimpleLogger.h" #include "Util/StringUtil.h" #include "typedefs.h" #include <boost/foreach.hpp> #include <luabind/luabind.hpp> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> typedef QueryEdge::EdgeData EdgeData; typedef DynamicGraph<EdgeData>::InputEdge InputEdge; typedef StaticGraph<EdgeData>::InputEdge StaticEdge; std::vector<NodeInfo> internalToExternalNodeMapping; std::vector<TurnRestriction> inputRestrictions; std::vector<NodeID> bollardNodes; std::vector<NodeID> trafficLightNodes; std::vector<ImportEdge> edgeList; int main (int argc, char *argv[]) { try { LogPolicy::GetInstance().Unmute(); double startupTime = get_timestamp(); boost::filesystem::path config_file_path, input_path, restrictions_path, profile_path; int requested_num_threads; // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options() ("version,v", "Show version") ("help,h", "Show this help message") ("config,c", boost::program_options::value<boost::filesystem::path>(&config_file_path)->default_value("contractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); config_options.add_options() ("restrictions,r", boost::program_options::value<boost::filesystem::path>(&restrictions_path), "Restrictions file in .osrm.restrictions format") ("profile,p", boost::program_options::value<boost::filesystem::path>(&profile_path)->default_value("profile.lua"), "Path to LUA routing profile") ("threads,t", boost::program_options::value<int>(&requested_num_threads)->default_value(8), "Number of threads to use"); // hidden options, will be allowed both on command line and in config file, but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options() ("input,i", boost::program_options::value<boost::filesystem::path>(&input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); // combine above options for parsing boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); boost::program_options::options_description config_file_options; config_file_options.add(config_options).add(hidden_options); boost::program_options::options_description visible_options("Usage: " + boost::filesystem::basename(argv[0]) + " <input.osrm> [options]"); visible_options.add(generic_options).add(config_options); // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv). options(cmdline_options).positional(positional_options).run(), option_variables); if(option_variables.count("version")) { SimpleLogger().Write() << g_GIT_DESCRIPTION; return 0; } if(option_variables.count("help")) { SimpleLogger().Write() << std::endl << visible_options; return 0; } boost::program_options::notify(option_variables); if(boost::filesystem::is_regular_file(config_file_path)) { SimpleLogger().Write() << "Reading options from: " << config_file_path.c_str(); std::string config_str; PrepareConfigFile( config_file_path.c_str(), config_str ); std::stringstream config_stream( config_str ); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); boost::program_options::notify(option_variables); } if(!option_variables.count("restrictions")) { restrictions_path = std::string( input_path.c_str()) + ".restrictions"; } if(!option_variables.count("input")) { SimpleLogger().Write(logWARNING) << "No input file specified"; return -1; } if(1 > requested_num_threads) { SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return -1; } SimpleLogger().Write() << "Input file: " << input_path.filename().string(); SimpleLogger().Write() << "Restrictions file: " << restrictions_path.filename().string(); SimpleLogger().Write() << "Profile: " << profile_path.filename().string(); SimpleLogger().Write() << "Threads: " << requested_num_threads; omp_set_num_threads( std::min( omp_get_num_procs(), requested_num_threads) ); LogPolicy::GetInstance().Unmute(); std::ifstream restrictionsInstream( restrictions_path.c_str(), std::ios::binary); TurnRestriction restriction; UUID uuid_loaded, uuid_orig; unsigned usableRestrictionsCounter(0); restrictionsInstream.read((char*)&uuid_loaded, sizeof(UUID)); if( !uuid_loaded.TestPrepare(uuid_orig) ) { SimpleLogger().Write(logWARNING) << ".restrictions was prepared with different build.\n" "Reprocess to get rid of this warning."; } restrictionsInstream.read( (char*)&usableRestrictionsCounter, sizeof(unsigned) ); inputRestrictions.resize(usableRestrictionsCounter); restrictionsInstream.read( (char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(TurnRestriction) ); restrictionsInstream.close(); std::ifstream in; in.open (input_path.c_str(), std::ifstream::in | std::ifstream::binary); std::string nodeOut(input_path.c_str()); nodeOut += ".nodes"; std::string edgeOut(input_path.c_str()); edgeOut += ".edges"; std::string graphOut(input_path.c_str()); graphOut += ".hsgr"; std::string rtree_nodes_path(input_path.c_str()); rtree_nodes_path += ".ramIndex"; std::string rtree_leafs_path(input_path.c_str()); rtree_leafs_path += ".fileIndex"; /*** Setup Scripting Environment ***/ // Create a new lua state lua_State *myLuaState = luaL_newstate(); // Connect LuaBind to this lua state luabind::open(myLuaState); //open utility libraries string library; luaL_openlibs(myLuaState); //adjust lua load path luaAddScriptFolderToLoadPath( myLuaState, profile_path.c_str() ); // Now call our function in a lua script if(0 != luaL_dofile(myLuaState, profile_path.c_str() )) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; } EdgeBasedGraphFactory::SpeedProfileProperties speedProfile; if(0 != luaL_dostring( myLuaState, "return traffic_signal_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.trafficSignalPenalty = 10*lua_tointeger(myLuaState, -1); if(0 != luaL_dostring( myLuaState, "return u_turn_penalty\n")) { std::cerr << lua_tostring(myLuaState,-1) << " occured in scripting block" << std::endl; return -1; } speedProfile.uTurnPenalty = 10*lua_tointeger(myLuaState, -1); speedProfile.has_turn_penalty_function = lua_function_exists( myLuaState, "turn_function" ); std::vector<ImportEdge> edgeList; NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions); in.close(); SimpleLogger().Write() << inputRestrictions.size() << " restrictions, " << bollardNodes.size() << " bollard nodes, " << trafficLightNodes.size() << " traffic lights"; if( edgeList.empty() ) { SimpleLogger().Write(logWARNING) << "The input data is broken. " "It is impossible to do any turns in this graph"; return -1; } /*** * Building an edge-expanded graph from node-based input an turn restrictions */ SimpleLogger().Write() << "Generating edge-expanded graph representation"; EdgeBasedGraphFactory * edgeBasedGraphFactory = new EdgeBasedGraphFactory (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping, speedProfile); std::vector<ImportEdge>().swap(edgeList); edgeBasedGraphFactory->Run(edgeOut.c_str(), myLuaState); std::vector<TurnRestriction>().swap(inputRestrictions); std::vector<NodeID>().swap(bollardNodes); std::vector<NodeID>().swap(trafficLightNodes); NodeID edgeBasedNodeNumber = edgeBasedGraphFactory->GetNumberOfNodes(); DeallocatingVector<EdgeBasedEdge> edgeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedEdges(edgeBasedEdgeList); std::vector<EdgeBasedNode> nodeBasedEdgeList; edgeBasedGraphFactory->GetEdgeBasedNodes(nodeBasedEdgeList); delete edgeBasedGraphFactory; /*** * Writing info on original (node-based) nodes */ SimpleLogger().Write() << "writing node map ..."; std::ofstream mapOutFile(nodeOut.c_str(), std::ios::binary); const unsigned size_of_mapping = internalToExternalNodeMapping.size(); mapOutFile.write((char *)&size_of_mapping, sizeof(unsigned)); mapOutFile.write( (char *)&(internalToExternalNodeMapping[0]), size_of_mapping*sizeof(NodeInfo) ); mapOutFile.close(); std::vector<NodeInfo>().swap(internalToExternalNodeMapping); double expansionHasFinishedTime = get_timestamp() - startupTime; /*** * Building grid-like nearest-neighbor data structure */ SimpleLogger().Write() << "building r-tree ..."; StaticRTree<EdgeBasedNode> * rtree = new StaticRTree<EdgeBasedNode>( nodeBasedEdgeList, rtree_nodes_path.c_str(), rtree_leafs_path.c_str() ); delete rtree; IteratorbasedCRC32<std::vector<EdgeBasedNode> > crc32; unsigned crc32OfNodeBasedEdgeList = crc32(nodeBasedEdgeList.begin(), nodeBasedEdgeList.end() ); nodeBasedEdgeList.clear(); SimpleLogger().Write() << "CRC32: " << crc32OfNodeBasedEdgeList; /*** * Contracting the edge-expanded graph */ SimpleLogger().Write() << "initializing contractor"; Contractor* contractor = new Contractor( edgeBasedNodeNumber, edgeBasedEdgeList ); double contractionStartedTimestamp(get_timestamp()); contractor->Run(); const double contraction_duration = (get_timestamp() - contractionStartedTimestamp); SimpleLogger().Write() << "Contraction took " << contraction_duration << " sec"; DeallocatingVector< QueryEdge > contractedEdgeList; contractor->GetEdges( contractedEdgeList ); delete contractor; /*** * Sorting contracted edges in a way that the static query graph can read some in in-place. */ SimpleLogger().Write() << "Building Node Array"; std::sort(contractedEdgeList.begin(), contractedEdgeList.end()); unsigned numberOfNodes = 0; unsigned numberOfEdges = contractedEdgeList.size(); SimpleLogger().Write() << "Serializing compacted graph of " << numberOfEdges << " edges"; std::ofstream hsgr_output_stream(graphOut.c_str(), std::ios::binary); hsgr_output_stream.write((char*)&uuid_orig, sizeof(UUID) ); BOOST_FOREACH(const QueryEdge & edge, contractedEdgeList) { if(edge.source > numberOfNodes) { numberOfNodes = edge.source; } if(edge.target > numberOfNodes) { numberOfNodes = edge.target; } } numberOfNodes+=1; std::vector< StaticGraph<EdgeData>::_StrNode > _nodes; _nodes.resize( numberOfNodes + 1 ); StaticGraph<EdgeData>::EdgeIterator edge = 0; StaticGraph<EdgeData>::EdgeIterator position = 0; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { StaticGraph<EdgeData>::EdgeIterator lastEdge = edge; while ( edge < numberOfEdges && contractedEdgeList[edge].source == node ) ++edge; _nodes[node].firstEdge = position; //=edge position += edge - lastEdge; //remove } _nodes.back().firstEdge = numberOfEdges; //sentinel element ++numberOfNodes; BOOST_ASSERT_MSG( _nodes.size() == numberOfNodes, "no. of nodes dont match" ); //serialize crc32, aka checksum hsgr_output_stream.write((char*) &crc32OfNodeBasedEdgeList, sizeof(unsigned)); //serialize number f nodes hsgr_output_stream.write((char*) &numberOfNodes, sizeof(unsigned)); //serialize number of edges hsgr_output_stream.write((char*) &position, sizeof(unsigned)); //serialize all nodes hsgr_output_stream.write((char*) &_nodes[0], sizeof(StaticGraph<EdgeData>::_StrNode)*(numberOfNodes)); //serialize all edges --numberOfNodes; edge = 0; int usedEdgeCounter = 0; StaticGraph<EdgeData>::_StrEdge currentEdge; for ( StaticGraph<EdgeData>::NodeIterator node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator i = _nodes[node].firstEdge, e = _nodes[node+1].firstEdge; i != e; ++i ) { assert(node != contractedEdgeList[edge].target); currentEdge.target = contractedEdgeList[edge].target; currentEdge.data = contractedEdgeList[edge].data; if(currentEdge.data.distance <= 0) { SimpleLogger().Write(logWARNING) << "Edge: " << i << ",source: " << contractedEdgeList[edge].source << ", target: " << contractedEdgeList[edge].target << ", dist: " << currentEdge.data.distance; SimpleLogger().Write(logWARNING) << "Failed at edges of node " << node << " of " << numberOfNodes; return -1; } //Serialize edges hsgr_output_stream.write((char*) &currentEdge, sizeof(StaticGraph<EdgeData>::_StrEdge)); ++edge; ++usedEdgeCounter; } } SimpleLogger().Write() << "Preprocessing : " << (get_timestamp() - startupTime) << " seconds"; SimpleLogger().Write() << "Expansion : " << (nodeBasedNodeNumber/expansionHasFinishedTime) << " nodes/sec and " << (edgeBasedNodeNumber/expansionHasFinishedTime) << " edges/sec"; SimpleLogger().Write() << "Contraction: " << (edgeBasedNodeNumber/contraction_duration) << " nodes/sec and " << usedEdgeCounter/contraction_duration << " edges/sec"; hsgr_output_stream.close(); //cleanedEdgeList.clear(); _nodes.clear(); SimpleLogger().Write() << "finished preprocessing"; } catch(boost::program_options::too_many_positional_options_error& e) { SimpleLogger().Write(logWARNING) << "Only one file can be specified"; return -1; } catch(boost::program_options::error& e) { SimpleLogger().Write(logWARNING) << e.what(); return -1; } catch ( const std::exception &e ) { SimpleLogger().Write(logWARNING) << "Exception occured: " << e.what() << std::endl; return -1; } return 0; }
bsd-2-clause
talho/sum_times
app/helpers/admin/timesheets_helper.rb
35
module Admin::TimesheetsHelper end
bsd-2-clause
theoneone/CH-SS16-Project
StuntCarRacer/Common/DXUT.cpp
233046
//-------------------------------------------------------------------------------------- // File: DXUT.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // 21/02/2012 Reluctantly made one change to this file, in function DXUTCreateWindow(), // to prevent the window from being resized (because the Backdrop.cpp code can't handle // larger window sizes and so the output looks wrong). //-------------------------------------------------------------------------------------- #include "dxstdafx.h" #define DXUT_MIN_WINDOW_SIZE_X 200 #define DXUT_MIN_WINDOW_SIZE_Y 200 #undef min // use __min instead inside this source file #undef max // use __max instead inside this source file //-------------------------------------------------------------------------------------- // Thread safety //-------------------------------------------------------------------------------------- CRITICAL_SECTION g_cs; bool g_bThreadSafe = true; //-------------------------------------------------------------------------------------- // Automatically enters & leaves the CS upon object creation/deletion //-------------------------------------------------------------------------------------- class DXUTLock { public: inline DXUTLock() { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); } inline ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); } }; //-------------------------------------------------------------------------------------- // Helper macros to build member functions that access member variables with thread safety //-------------------------------------------------------------------------------------- #define SET_ACCESSOR( x, y ) inline void Set##y( x t ) { DXUTLock l; m_state.m_##y = t; }; #define GET_ACCESSOR( x, y ) inline x Get##y() { DXUTLock l; return m_state.m_##y; }; #define GET_SET_ACCESSOR( x, y ) SET_ACCESSOR( x, y ) GET_ACCESSOR( x, y ) #define SETP_ACCESSOR( x, y ) inline void Set##y( x* t ) { DXUTLock l; m_state.m_##y = *t; }; #define GETP_ACCESSOR( x, y ) inline x* Get##y() { DXUTLock l; return &m_state.m_##y; }; #define GETP_SETP_ACCESSOR( x, y ) SETP_ACCESSOR( x, y ) GETP_ACCESSOR( x, y ) //-------------------------------------------------------------------------------------- // Stores timer callback info //-------------------------------------------------------------------------------------- struct DXUT_TIMER { LPDXUTCALLBACKTIMER pCallbackTimer; void* pCallbackUserContext; float fTimeoutInSecs; float fCountdown; bool bEnabled; UINT nID; }; //-------------------------------------------------------------------------------------- // Stores DXUT state and data access is done with thread safety (if g_bThreadSafe==true) //-------------------------------------------------------------------------------------- class DXUTState { protected: struct STATE { IDirect3D9* m_D3D; // the main D3D object IDirect3DDevice9* m_D3DDevice; // the D3D rendering device CD3DEnumeration* m_D3DEnumeration; // CD3DEnumeration object DXUTDeviceSettings* m_CurrentDeviceSettings; // current device settings D3DSURFACE_DESC m_BackBufferSurfaceDesc; // back buffer surface description D3DCAPS9 m_Caps; // D3D caps for current device HWND m_HWNDFocus; // the main app focus window HWND m_HWNDDeviceFullScreen; // the main app device window in fullscreen mode HWND m_HWNDDeviceWindowed; // the main app device window in windowed mode HMONITOR m_AdapterMonitor; // the monitor of the adapter HMENU m_Menu; // handle to menu UINT m_FullScreenBackBufferWidthAtModeChange; // back buffer size of fullscreen mode right before switching to windowed mode. Used to restore to same resolution when toggling back to fullscreen UINT m_FullScreenBackBufferHeightAtModeChange; // back buffer size of fullscreen mode right before switching to windowed mode. Used to restore to same resolution when toggling back to fullscreen UINT m_WindowBackBufferWidthAtModeChange; // back buffer size of windowed mode right before switching to fullscreen mode. Used to restore to same resolution when toggling back to windowed mode UINT m_WindowBackBufferHeightAtModeChange; // back buffer size of windowed mode right before switching to fullscreen mode. Used to restore to same resolution when toggling back to windowed mode DWORD m_WindowedStyleAtModeChange; // window style WINDOWPLACEMENT m_WindowedPlacement; // record of windowed HWND position/show state/etc bool m_TopmostWhileWindowed; // if true, the windowed HWND is topmost bool m_Minimized; // if true, the HWND is minimized bool m_Maximized; // if true, the HWND is maximized bool m_MinimizedWhileFullscreen; // if true, the HWND is minimized due to a focus switch away when fullscreen mode bool m_IgnoreSizeChange; // if true, DXUT won't reset the device upon HWND size change double m_Time; // current time in seconds double m_AbsoluteTime; // absolute time in seconds float m_ElapsedTime; // time elapsed since last frame HINSTANCE m_HInstance; // handle to the app instance double m_LastStatsUpdateTime; // last time the stats were updated DWORD m_LastStatsUpdateFrames; // frames count since last time the stats were updated float m_FPS; // frames per second int m_CurrentFrameNumber; // the current frame number HHOOK m_KeyboardHook; // handle to keyboard hook bool m_AllowShortcutKeysWhenFullscreen; // if true, when fullscreen enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) bool m_AllowShortcutKeysWhenWindowed; // if true, when windowed enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) bool m_AllowShortcutKeys; // if true, then shortcut keys are currently disabled (Windows key, etc) bool m_CallDefWindowProc; // if true, DXUTStaticWndProc will call DefWindowProc for unhandled messages. Applications rendering to a dialog may need to set this to false. STICKYKEYS m_StartupStickyKeys; // StickyKey settings upon startup so they can be restored later TOGGLEKEYS m_StartupToggleKeys; // ToggleKey settings upon startup so they can be restored later FILTERKEYS m_StartupFilterKeys; // FilterKey settings upon startup so they can be restored later bool m_HandleDefaultHotkeys; // if true, then DXUT will handle some default hotkeys bool m_HandleAltEnter; // if true, then DXUT will handle Alt-Enter bool m_ShowMsgBoxOnError; // if true, then msgboxes are displayed upon errors bool m_NoStats; // if true, then DXUTGetFrameStats() and DXUTGetDeviceStats() will return blank strings bool m_ClipCursorWhenFullScreen; // if true, then DXUT will keep the cursor from going outside the window when full screen bool m_ShowCursorWhenFullScreen; // if true, then DXUT will show a cursor when full screen bool m_ConstantFrameTime; // if true, then elapsed frame time will always be 0.05f seconds which is good for debugging or automated capture float m_TimePerFrame; // the constant time per frame in seconds, only valid if m_ConstantFrameTime==true bool m_WireframeMode; // if true, then D3DRS_FILLMODE==D3DFILL_WIREFRAME else D3DRS_FILLMODE==D3DFILL_SOLID bool m_AutoChangeAdapter; // if true, then the adapter will automatically change if the window is different monitor bool m_WindowCreatedWithDefaultPositions; // if true, then CW_USEDEFAULT was used and the window should be moved to the right adapter int m_ExitCode; // the exit code to be returned to the command line bool m_DXUTInited; // if true, then DXUTInit() has succeeded bool m_WindowCreated; // if true, then DXUTCreateWindow() or DXUTSetWindow() has succeeded bool m_DeviceCreated; // if true, then DXUTCreateDevice*() or DXUTSetDevice() has succeeded bool m_DXUTInitCalled; // if true, then DXUTInit() was called bool m_WindowCreateCalled; // if true, then DXUTCreateWindow() or DXUTSetWindow() was called bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice*() or DXUTSetDevice() was called bool m_DeviceObjectsCreated; // if true, then DeviceCreated callback has been called (if non-NULL) bool m_DeviceObjectsReset; // if true, then DeviceReset callback has been called (if non-NULL) bool m_InsideDeviceCallback; // if true, then the framework is inside an app device callback bool m_InsideMainloop; // if true, then the framework is inside the main loop bool m_Active; // if true, then the app is the active top level window bool m_TimePaused; // if true, then time is paused bool m_RenderingPaused; // if true, then rendering is paused int m_PauseRenderingCount; // pause rendering ref count int m_PauseTimeCount; // pause time ref count bool m_DeviceLost; // if true, then the device is lost and needs to be reset bool m_NotifyOnMouseMove; // if true, include WM_MOUSEMOVE in mousecallback bool m_Automation; // if true, automation is enabled bool m_InSizeMove; // if true, app is inside a WM_ENTERSIZEMOVE UINT m_TimerLastID; // last ID of the DXUT timer int m_OverrideAdapterOrdinal; // if != -1, then override to use this adapter ordinal bool m_OverrideWindowed; // if true, then force to start windowed bool m_OverrideFullScreen; // if true, then force to start full screen int m_OverrideStartX; // if != -1, then override to this X position of the window int m_OverrideStartY; // if != -1, then override to this Y position of the window int m_OverrideWidth; // if != 0, then override to this width int m_OverrideHeight; // if != 0, then override to this height bool m_OverrideForceHAL; // if true, then force to HAL device (failing if one doesn't exist) bool m_OverrideForceREF; // if true, then force to REF device (failing if one doesn't exist) bool m_OverrideForcePureHWVP; // if true, then force to use pure HWVP (failing if device doesn't support it) bool m_OverrideForceHWVP; // if true, then force to use HWVP (failing if device doesn't support it) bool m_OverrideForceSWVP; // if true, then force to use SWVP bool m_OverrideConstantFrameTime; // if true, then force to constant frame time float m_OverrideConstantTimePerFrame; // the constant time per frame in seconds if m_OverrideConstantFrameTime==true int m_OverrideQuitAfterFrame; // if != 0, then it will force the app to quit after that frame int m_OverrideForceVsync; // if == 0, then it will force the app to use D3DPRESENT_INTERVAL_IMMEDIATE, if == 1 force use of D3DPRESENT_INTERVAL_DEFAULT bool m_OverrideRelaunchMCE; // if true, then force relaunch of MCE at exit LPDXUTCALLBACKISDEVICEACCEPTABLE m_IsDeviceAcceptableFunc; // is device acceptable callback LPDXUTCALLBACKMODIFYDEVICESETTINGS m_ModifyDeviceSettingsFunc; // modify device settings callback LPDXUTCALLBACKDEVICECREATED m_DeviceCreatedFunc; // device created callback LPDXUTCALLBACKDEVICERESET m_DeviceResetFunc; // device reset callback LPDXUTCALLBACKDEVICELOST m_DeviceLostFunc; // device lost callback LPDXUTCALLBACKDEVICEDESTROYED m_DeviceDestroyedFunc; // device destroyed callback LPDXUTCALLBACKFRAMEMOVE m_FrameMoveFunc; // frame move callback LPDXUTCALLBACKFRAMERENDER m_FrameRenderFunc; // frame render callback LPDXUTCALLBACKKEYBOARD m_KeyboardFunc; // keyboard callback LPDXUTCALLBACKMOUSE m_MouseFunc; // mouse callback LPDXUTCALLBACKMSGPROC m_WindowMsgFunc; // window messages callback void* m_IsDeviceAcceptableFuncUserContext; // user context for is device acceptable callback void* m_ModifyDeviceSettingsFuncUserContext; // user context for modify device settings callback void* m_DeviceCreatedUserContext; // user context for device created callback void* m_DeviceCreatedFuncUserContext; // user context for device created callback void* m_DeviceResetFuncUserContext; // user context for device reset callback void* m_DeviceLostFuncUserContext; // user context for device lost callback void* m_DeviceDestroyedFuncUserContext; // user context for device destroyed callback void* m_FrameMoveFuncUserContext; // user context for frame move callback void* m_FrameRenderFuncUserContext; // user context for frame render callback void* m_KeyboardFuncUserContext; // user context for keyboard callback void* m_MouseFuncUserContext; // user context for mouse callback void* m_WindowMsgFuncUserContext; // user context for window messages callback bool m_Keys[256]; // array of key state bool m_MouseButtons[5]; // array of mouse states CGrowableArray<DXUT_TIMER>* m_TimerList; // list of DXUT_TIMER structs WCHAR m_StaticFrameStats[256]; // static part of frames stats WCHAR m_FPSStats[64]; // fps stats WCHAR m_FrameStats[256]; // frame stats (fps, width, etc) WCHAR m_DeviceStats[256]; // device stats (description, device type, etc) WCHAR m_WindowTitle[256]; // window title }; STATE m_state; public: DXUTState() { Create(); } ~DXUTState() { Destroy(); } void Create() { // Make sure these are created before DXUTState so they // destroyed last because DXUTState cleanup needs them DXUTGetGlobalResourceCache(); ZeroMemory( &m_state, sizeof(STATE) ); g_bThreadSafe = true; InitializeCriticalSection( &g_cs ); m_state.m_OverrideStartX = -1; m_state.m_OverrideStartY = -1; m_state.m_OverrideAdapterOrdinal = -1; m_state.m_OverrideForceVsync = -1; m_state.m_AutoChangeAdapter = true; m_state.m_ShowMsgBoxOnError = true; m_state.m_AllowShortcutKeysWhenWindowed = true; m_state.m_Active = true; m_state.m_CallDefWindowProc = true; } void Destroy() { DXUTShutdown(); DeleteCriticalSection( &g_cs ); } // Macros to define access functions for thread safe access into m_state GET_SET_ACCESSOR( IDirect3D9*, D3D ); GET_SET_ACCESSOR( IDirect3DDevice9*, D3DDevice ); GET_SET_ACCESSOR( CD3DEnumeration*, D3DEnumeration ); GET_SET_ACCESSOR( DXUTDeviceSettings*, CurrentDeviceSettings ); GETP_SETP_ACCESSOR( D3DSURFACE_DESC, BackBufferSurfaceDesc ); GETP_SETP_ACCESSOR( D3DCAPS9, Caps ); GET_SET_ACCESSOR( HWND, HWNDFocus ); GET_SET_ACCESSOR( HWND, HWNDDeviceFullScreen ); GET_SET_ACCESSOR( HWND, HWNDDeviceWindowed ); GET_SET_ACCESSOR( HMONITOR, AdapterMonitor ); GET_SET_ACCESSOR( HMENU, Menu ); GET_SET_ACCESSOR( UINT, FullScreenBackBufferWidthAtModeChange ); GET_SET_ACCESSOR( UINT, FullScreenBackBufferHeightAtModeChange ); GET_SET_ACCESSOR( UINT, WindowBackBufferWidthAtModeChange ); GET_SET_ACCESSOR( UINT, WindowBackBufferHeightAtModeChange ); GETP_SETP_ACCESSOR( WINDOWPLACEMENT, WindowedPlacement ); GET_SET_ACCESSOR( DWORD, WindowedStyleAtModeChange ); GET_SET_ACCESSOR( bool, TopmostWhileWindowed ); GET_SET_ACCESSOR( bool, Minimized ); GET_SET_ACCESSOR( bool, Maximized ); GET_SET_ACCESSOR( bool, MinimizedWhileFullscreen ); GET_SET_ACCESSOR( bool, IgnoreSizeChange ); GET_SET_ACCESSOR( double, Time ); GET_SET_ACCESSOR( double, AbsoluteTime ); GET_SET_ACCESSOR( float, ElapsedTime ); GET_SET_ACCESSOR( HINSTANCE, HInstance ); GET_SET_ACCESSOR( double, LastStatsUpdateTime ); GET_SET_ACCESSOR( DWORD, LastStatsUpdateFrames ); GET_SET_ACCESSOR( float, FPS ); GET_SET_ACCESSOR( int, CurrentFrameNumber ); GET_SET_ACCESSOR( HHOOK, KeyboardHook ); GET_SET_ACCESSOR( bool, AllowShortcutKeysWhenFullscreen ); GET_SET_ACCESSOR( bool, AllowShortcutKeysWhenWindowed ); GET_SET_ACCESSOR( bool, AllowShortcutKeys ); GET_SET_ACCESSOR( bool, CallDefWindowProc ); GET_SET_ACCESSOR( STICKYKEYS, StartupStickyKeys ); GET_SET_ACCESSOR( TOGGLEKEYS, StartupToggleKeys ); GET_SET_ACCESSOR( FILTERKEYS, StartupFilterKeys ); GET_SET_ACCESSOR( bool, HandleDefaultHotkeys ); GET_SET_ACCESSOR( bool, HandleAltEnter ); GET_SET_ACCESSOR( bool, ShowMsgBoxOnError ); GET_SET_ACCESSOR( bool, NoStats ); GET_SET_ACCESSOR( bool, ClipCursorWhenFullScreen ); GET_SET_ACCESSOR( bool, ShowCursorWhenFullScreen ); GET_SET_ACCESSOR( bool, ConstantFrameTime ); GET_SET_ACCESSOR( float, TimePerFrame ); GET_SET_ACCESSOR( bool, WireframeMode ); GET_SET_ACCESSOR( bool, AutoChangeAdapter ); GET_SET_ACCESSOR( bool, WindowCreatedWithDefaultPositions ); GET_SET_ACCESSOR( int, ExitCode ); GET_SET_ACCESSOR( bool, DXUTInited ); GET_SET_ACCESSOR( bool, WindowCreated ); GET_SET_ACCESSOR( bool, DeviceCreated ); GET_SET_ACCESSOR( bool, DXUTInitCalled ); GET_SET_ACCESSOR( bool, WindowCreateCalled ); GET_SET_ACCESSOR( bool, DeviceCreateCalled ); GET_SET_ACCESSOR( bool, InsideDeviceCallback ); GET_SET_ACCESSOR( bool, InsideMainloop ); GET_SET_ACCESSOR( bool, DeviceObjectsCreated ); GET_SET_ACCESSOR( bool, DeviceObjectsReset ); GET_SET_ACCESSOR( bool, Active ); GET_SET_ACCESSOR( bool, RenderingPaused ); GET_SET_ACCESSOR( bool, TimePaused ); GET_SET_ACCESSOR( int, PauseRenderingCount ); GET_SET_ACCESSOR( int, PauseTimeCount ); GET_SET_ACCESSOR( bool, DeviceLost ); GET_SET_ACCESSOR( bool, NotifyOnMouseMove ); GET_SET_ACCESSOR( bool, Automation ); GET_SET_ACCESSOR( bool, InSizeMove ); GET_SET_ACCESSOR( UINT, TimerLastID ); GET_SET_ACCESSOR( int, OverrideAdapterOrdinal ); GET_SET_ACCESSOR( bool, OverrideWindowed ); GET_SET_ACCESSOR( bool, OverrideFullScreen ); GET_SET_ACCESSOR( int, OverrideStartX ); GET_SET_ACCESSOR( int, OverrideStartY ); GET_SET_ACCESSOR( int, OverrideWidth ); GET_SET_ACCESSOR( int, OverrideHeight ); GET_SET_ACCESSOR( bool, OverrideForceHAL ); GET_SET_ACCESSOR( bool, OverrideForceREF ); GET_SET_ACCESSOR( bool, OverrideForcePureHWVP ); GET_SET_ACCESSOR( bool, OverrideForceHWVP ); GET_SET_ACCESSOR( bool, OverrideForceSWVP ); GET_SET_ACCESSOR( bool, OverrideConstantFrameTime ); GET_SET_ACCESSOR( float, OverrideConstantTimePerFrame ); GET_SET_ACCESSOR( int, OverrideQuitAfterFrame ); GET_SET_ACCESSOR( int, OverrideForceVsync ); GET_SET_ACCESSOR( bool, OverrideRelaunchMCE ); GET_SET_ACCESSOR( LPDXUTCALLBACKISDEVICEACCEPTABLE, IsDeviceAcceptableFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMODIFYDEVICESETTINGS, ModifyDeviceSettingsFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICECREATED, DeviceCreatedFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICERESET, DeviceResetFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICELOST, DeviceLostFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICEDESTROYED, DeviceDestroyedFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKFRAMEMOVE, FrameMoveFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKFRAMERENDER, FrameRenderFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKKEYBOARD, KeyboardFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMOUSE, MouseFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMSGPROC, WindowMsgFunc ); GET_SET_ACCESSOR( void*, IsDeviceAcceptableFuncUserContext ); GET_SET_ACCESSOR( void*, ModifyDeviceSettingsFuncUserContext ); GET_SET_ACCESSOR( void*, DeviceCreatedFuncUserContext ); GET_SET_ACCESSOR( void*, DeviceResetFuncUserContext ); GET_SET_ACCESSOR( void*, DeviceLostFuncUserContext ); GET_SET_ACCESSOR( void*, DeviceDestroyedFuncUserContext ); GET_SET_ACCESSOR( void*, FrameMoveFuncUserContext ); GET_SET_ACCESSOR( void*, FrameRenderFuncUserContext ); GET_SET_ACCESSOR( void*, KeyboardFuncUserContext ); GET_SET_ACCESSOR( void*, MouseFuncUserContext ); GET_SET_ACCESSOR( void*, WindowMsgFuncUserContext ); GET_SET_ACCESSOR( CGrowableArray<DXUT_TIMER>*, TimerList ); GET_ACCESSOR( bool*, Keys ); GET_ACCESSOR( bool*, MouseButtons ); GET_ACCESSOR( WCHAR*, StaticFrameStats ); GET_ACCESSOR( WCHAR*, FPSStats ); GET_ACCESSOR( WCHAR*, FrameStats ); GET_ACCESSOR( WCHAR*, DeviceStats ); GET_ACCESSOR( WCHAR*, WindowTitle ); }; //-------------------------------------------------------------------------------------- // Global state class //-------------------------------------------------------------------------------------- DXUTState& GetDXUTState() { // Using an accessor function gives control of the construction order static DXUTState state; return state; } //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- typedef IDirect3D9* (WINAPI* LPDIRECT3DCREATE9)(UINT SDKVersion); typedef DECLSPEC_IMPORT UINT (WINAPI* LPTIMEBEGINPERIOD)( UINT uPeriod ); int DXUTMapButtonToArrayIndex( BYTE vButton ); void DXUTSetProcessorAffinity(); void DXUTParseCommandLine(); CD3DEnumeration* DXUTPrepareEnumerationObject( bool bEnumerate = false ); void DXUTBuildOptimalDeviceSettings( DXUTDeviceSettings* pOptimalDeviceSettings, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ); bool DXUTDoesDeviceComboMatchPreserveOptions( CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ); float DXUTRankDeviceCombo( CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTDeviceSettings* pDeviceSettingsIn, D3DDISPLAYMODE* pAdapterDesktopDisplayMode ); void DXUTBuildValidDeviceSettings( DXUTDeviceSettings* pDeviceSettings, CD3DEnumDeviceSettingsCombo* pBestDeviceSettingsCombo, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ); HRESULT DXUTFindValidResolution( CD3DEnumDeviceSettingsCombo* pBestDeviceSettingsCombo, D3DDISPLAYMODE displayModeIn, D3DDISPLAYMODE* pBestDisplayMode ); HRESULT DXUTFindAdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, BOOL Windowed, D3DFORMAT* pAdapterFormat ); HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, IDirect3DDevice9* pd3dDeviceFromApp, bool bForceRecreate, bool bClipWindowToSingleAdapter ); void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pNewDeviceSettings ); HRESULT DXUTCreate3DEnvironment( IDirect3DDevice9* pd3dDeviceFromApp ); HRESULT DXUTReset3DEnvironment(); void DXUTRender3DEnvironment(); void DXUTCleanup3DEnvironment( bool bReleaseSettings = true ); void DXUTUpdateFrameStats(); void DXUTUpdateDeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ); void DXUTUpdateStaticFrameStats(); void DXUTHandleTimers(); bool DXUTIsNextArg( WCHAR*& strCmdLine, WCHAR* strArg ); bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ); void DXUTDisplayErrorMessage( HRESULT hr ); LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); void DXUTCheckForWindowSizeChange(); void DXUTCheckForWindowChangingMonitors(); UINT DXUTColorChannelBits( D3DFORMAT fmt ); UINT DXUTStencilBits( D3DFORMAT fmt ); UINT DXUTDepthBits( D3DFORMAT fmt ); HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ); void DXUTAllowShortcutKeys( bool bAllowKeys ); void DXUTUpdateBackBufferDesc(); void DXUTSetupCursor(); HRESULT DXUTSetDeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ); //-------------------------------------------------------------------------------------- // External callback setup functions //-------------------------------------------------------------------------------------- void DXUTSetCallbackDeviceCreated( LPDXUTCALLBACKDEVICECREATED pCallbackDeviceCreated, void* pUserContext ) { GetDXUTState().SetDeviceCreatedFunc( pCallbackDeviceCreated ); GetDXUTState().SetDeviceCreatedFuncUserContext( pUserContext ); } void DXUTSetCallbackDeviceReset( LPDXUTCALLBACKDEVICERESET pCallbackDeviceReset, void* pUserContext ) { GetDXUTState().SetDeviceResetFunc( pCallbackDeviceReset ); GetDXUTState().SetDeviceResetFuncUserContext( pUserContext ); } void DXUTSetCallbackDeviceLost( LPDXUTCALLBACKDEVICELOST pCallbackDeviceLost, void* pUserContext ) { GetDXUTState().SetDeviceLostFunc( pCallbackDeviceLost ); GetDXUTState().SetDeviceLostFuncUserContext( pUserContext ); } void DXUTSetCallbackDeviceDestroyed( LPDXUTCALLBACKDEVICEDESTROYED pCallbackDeviceDestroyed, void* pUserContext ) { GetDXUTState().SetDeviceDestroyedFunc( pCallbackDeviceDestroyed ); GetDXUTState().SetDeviceDestroyedFuncUserContext( pUserContext ); } void DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings, void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallbackModifyDeviceSettings ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); } void DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove, void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallbackFrameMove ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); } void DXUTSetCallbackFrameRender( LPDXUTCALLBACKFRAMERENDER pCallbackFrameRender, void* pUserContext ) { GetDXUTState().SetFrameRenderFunc( pCallbackFrameRender ); GetDXUTState().SetFrameRenderFuncUserContext( pUserContext ); } void DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallbackKeyboard, void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallbackKeyboard ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); } void DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallbackMouse, bool bIncludeMouseMove, void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallbackMouse ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); } void DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallbackMsgProc, void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallbackMsgProc ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); } //-------------------------------------------------------------------------------------- // Optionally parses the command line and sets if default hotkeys are handled // // Possible command line parameters are: // -adapter:# forces app to use this adapter # (fails if the adapter doesn't exist) // -windowed forces app to start windowed // -fullscreen forces app to start full screen // -forcehal forces app to use HAL (fails if HAL doesn't exist) // -forceref forces app to use REF (fails if REF doesn't exist) // -forcepurehwvp forces app to use pure HWVP (fails if device doesn't support it) // -forcehwvp forces app to use HWVP (fails if device doesn't support it) // -forceswvp forces app to use SWVP // -forcevsync:# if # is 0, forces app to use D3DPRESENT_INTERVAL_IMMEDIATE otherwise force use of D3DPRESENT_INTERVAL_DEFAULT // -width:# forces app to use # for width. for full screen, it will pick the closest possible supported mode // -height:# forces app to use # for height. for full screen, it will pick the closest possible supported mode // -startx:# forces app to use # for the x coord of the window position for windowed mode // -starty:# forces app to use # for the y coord of the window position for windowed mode // -constantframetime:# forces app to use constant frame time, where # is the time/frame in seconds // -quitafterframe:x forces app to quit after # frames // -noerrormsgboxes prevents the display of message boxes generated by the framework so the application can be run without user interaction // -nostats prevents the display of the stats // -relaunchmce re-launches the MCE UI after the app exits // -automation every CDXUTDialog created will have EnableKeyboardInput(true) called, enabling UI navigation with keyboard // This is useful when automating application testing. // // Hotkeys handled by default are: // Alt-Enter toggle between full screen & windowed (hotkey always enabled) // ESC exit app // F3 toggle HAL/REF // F8 toggle wire-frame mode // Pause pause time //-------------------------------------------------------------------------------------- HRESULT DXUTInit( bool bParseCommandLine, bool bHandleDefaultHotkeys, bool bShowMsgBoxOnError, bool bHandleAltEnter ) { GetDXUTState().SetDXUTInitCalled( true ); // Not always needed, but lets the app create GDI dialogs InitCommonControls(); // Save the current sticky/toggle/filter key settings so DXUT can restore them later STICKYKEYS sk = {sizeof(STICKYKEYS), 0}; SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0); GetDXUTState().SetStartupStickyKeys( sk ); TOGGLEKEYS tk = {sizeof(TOGGLEKEYS), 0}; SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0); GetDXUTState().SetStartupToggleKeys( tk ); FILTERKEYS fk = {sizeof(FILTERKEYS), 0}; SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0); GetDXUTState().SetStartupFilterKeys( fk ); // Increase the accuracy of Sleep() without needing to link to winmm.lib HINSTANCE hInstWinMM = LoadLibrary( L"winmm.dll" ); if( hInstWinMM ) { LPTIMEBEGINPERIOD pTimeBeginPeriod = (LPTIMEBEGINPERIOD)GetProcAddress( hInstWinMM, "timeBeginPeriod" ); if( NULL != pTimeBeginPeriod ) pTimeBeginPeriod(1); FreeLibrary(hInstWinMM); } GetDXUTState().SetShowMsgBoxOnError( bShowMsgBoxOnError ); GetDXUTState().SetHandleDefaultHotkeys( bHandleDefaultHotkeys ); GetDXUTState().SetHandleAltEnter( bHandleAltEnter ); if( bParseCommandLine ) DXUTParseCommandLine(); // Verify D3DX version if( !D3DXCheckVersion( D3D_SDK_VERSION, D3DX_SDK_VERSION ) ) { DXUTDisplayErrorMessage( DXUTERR_INCORRECTVERSION ); return DXUT_ERR( L"D3DXCheckVersion", DXUTERR_INCORRECTVERSION ); } // Create a Direct3D object if one has not already been created IDirect3D9* pD3D = DXUTGetD3DObject(); if( pD3D == NULL ) { // This may fail if DirectX 9 isn't installed // This may fail if the DirectX headers are out of sync with the installed DirectX DLLs pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); GetDXUTState().SetD3D( pD3D ); } if( pD3D == NULL ) { // If still NULL, then something went wrong DXUTDisplayErrorMessage( DXUTERR_NODIRECT3D ); return DXUT_ERR( L"Direct3DCreate9", DXUTERR_NODIRECT3D ); } // Reset the timer DXUTGetGlobalTimer()->Reset(); GetDXUTState().SetDXUTInited( true ); return S_OK; } //-------------------------------------------------------------------------------------- // Parses the command line for parameters. See DXUTInit() for list //-------------------------------------------------------------------------------------- void DXUTParseCommandLine() { WCHAR* strCmdLine; WCHAR strFlag[MAX_PATH]; int nNumArgs; WCHAR** pstrArgList = CommandLineToArgvW( GetCommandLine(), &nNumArgs ); for( int iArg=1; iArg<nNumArgs; iArg++ ) { strCmdLine = pstrArgList[iArg]; // Handle flag args if( *strCmdLine == L'/' || *strCmdLine == L'-' ) { strCmdLine++; if( DXUTIsNextArg( strCmdLine, L"adapter" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nAdapter = _wtoi(strFlag); GetDXUTState().SetOverrideAdapterOrdinal( nAdapter ); continue; } } if( DXUTIsNextArg( strCmdLine, L"windowed" ) ) { GetDXUTState().SetOverrideWindowed( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"fullscreen" ) ) { GetDXUTState().SetOverrideFullScreen( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forcehal" ) ) { GetDXUTState().SetOverrideForceHAL( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forceref" ) ) { GetDXUTState().SetOverrideForceREF( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forcepurehwvp" ) ) { GetDXUTState().SetOverrideForcePureHWVP( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forcehwvp" ) ) { GetDXUTState().SetOverrideForceHWVP( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forceswvp" ) ) { GetDXUTState().SetOverrideForceSWVP( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"forcevsync" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nOn = _wtoi(strFlag); GetDXUTState().SetOverrideForceVsync( nOn ); continue; } } if( DXUTIsNextArg( strCmdLine, L"width" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nWidth = _wtoi(strFlag); GetDXUTState().SetOverrideWidth( nWidth ); continue; } } if( DXUTIsNextArg( strCmdLine, L"height" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nHeight = _wtoi(strFlag); GetDXUTState().SetOverrideHeight( nHeight ); continue; } } if( DXUTIsNextArg( strCmdLine, L"startx" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nX = _wtoi(strFlag); GetDXUTState().SetOverrideStartX( nX ); continue; } } if( DXUTIsNextArg( strCmdLine, L"starty" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nY = _wtoi(strFlag); GetDXUTState().SetOverrideStartY( nY ); continue; } } if( DXUTIsNextArg( strCmdLine, L"constantframetime" ) ) { float fTimePerFrame; if( DXUTGetCmdParam( strCmdLine, strFlag ) ) fTimePerFrame = (float)wcstod( strFlag, NULL ); else fTimePerFrame = 0.0333f; GetDXUTState().SetOverrideConstantFrameTime( true ); GetDXUTState().SetOverrideConstantTimePerFrame( fTimePerFrame ); DXUTSetConstantFrameTime( true, fTimePerFrame ); continue; } if( DXUTIsNextArg( strCmdLine, L"quitafterframe" ) ) { if( DXUTGetCmdParam( strCmdLine, strFlag ) ) { int nFrame = _wtoi(strFlag); GetDXUTState().SetOverrideQuitAfterFrame( nFrame ); continue; } } if( DXUTIsNextArg( strCmdLine, L"noerrormsgboxes" ) ) { GetDXUTState().SetShowMsgBoxOnError( false ); continue; } if( DXUTIsNextArg( strCmdLine, L"nostats" ) ) { GetDXUTState().SetNoStats( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"relaunchmce" ) ) { GetDXUTState().SetOverrideRelaunchMCE( true ); continue; } if( DXUTIsNextArg( strCmdLine, L"automation" ) ) { GetDXUTState().SetAutomation( true ); continue; } } // Unrecognized flag StringCchCopy( strFlag, 256, strCmdLine ); WCHAR* strSpace = strFlag; while (*strSpace && (*strSpace > L' ')) strSpace++; *strSpace = 0; DXUTOutputDebugString( L"Unrecognized flag: %s", strFlag ); strCmdLine += wcslen(strFlag); } } //-------------------------------------------------------------------------------------- // Helper function for DXUTParseCommandLine //-------------------------------------------------------------------------------------- bool DXUTIsNextArg( WCHAR*& strCmdLine, WCHAR* strArg ) { int nArgLen = (int) wcslen(strArg); int nCmdLen = (int) wcslen(strCmdLine); if( nCmdLen >= nArgLen && _wcsnicmp( strCmdLine, strArg, nArgLen ) == 0 && (strCmdLine[nArgLen] == 0 || strCmdLine[nArgLen] == L':') ) { strCmdLine += nArgLen; return true; } return false; } //-------------------------------------------------------------------------------------- // Helper function for DXUTParseCommandLine. Updates strCmdLine and strFlag // Example: if strCmdLine=="-width:1024 -forceref" // then after: strCmdLine==" -forceref" and strFlag=="1024" //-------------------------------------------------------------------------------------- bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ) { if( *strCmdLine == L':' ) { strCmdLine++; // Skip ':' // Place NULL terminator in strFlag after current token StringCchCopy( strFlag, 256, strCmdLine ); WCHAR* strSpace = strFlag; while (*strSpace && (*strSpace > L' ')) strSpace++; *strSpace = 0; // Update strCmdLine strCmdLine += wcslen(strFlag); return true; } else { strFlag[0] = 0; return false; } } //-------------------------------------------------------------------------------------- // Creates a window with the specified window title, icon, menu, and // starting position. If DXUTInit() has not already been called, it will // call it with the default parameters. Instead of calling this, you can // call DXUTSetWindow() to use an existing window. //-------------------------------------------------------------------------------------- HRESULT DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstance, HICON hIcon, HMENU hMenu, int x, int y ) { HRESULT hr; // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); GetDXUTState().SetWindowCreateCalled( true ); if( !GetDXUTState().GetDXUTInited() ) { // If DXUTInit() was already called and failed, then fail. // DXUTInit() must first succeed for this function to succeed if( GetDXUTState().GetDXUTInitCalled() ) return E_FAIL; // If DXUTInit() hasn't been called, then automatically call it // with default params hr = DXUTInit(); if( FAILED(hr) ) return hr; } if( DXUTGetHWNDFocus() == NULL ) { if( hInstance == NULL ) hInstance = (HINSTANCE)GetModuleHandle(NULL); GetDXUTState().SetHInstance( hInstance ); WCHAR szExePath[MAX_PATH]; GetModuleFileName( NULL, szExePath, MAX_PATH ); if( hIcon == NULL ) // If the icon is NULL, then use the first one found in the exe hIcon = ExtractIcon( hInstance, szExePath, 0 ); // Register the windows class WNDCLASS wndClass; wndClass.style = CS_DBLCLKS; wndClass.lpfnWndProc = DXUTStaticWndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = hIcon; wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = L"Direct3DWindowClass"; if( !RegisterClass( &wndClass ) ) { DWORD dwError = GetLastError(); if( dwError != ERROR_CLASS_ALREADY_EXISTS ) return DXUT_ERR_MSGBOX( L"RegisterClass", HRESULT_FROM_WIN32(dwError) ); } RECT rc; // Override the window's initial & size position if there were cmd line args if( GetDXUTState().GetOverrideStartX() != -1 ) x = GetDXUTState().GetOverrideStartX(); if( GetDXUTState().GetOverrideStartY() != -1 ) y = GetDXUTState().GetOverrideStartY(); GetDXUTState().SetWindowCreatedWithDefaultPositions( false ); if( x == CW_USEDEFAULT && y == CW_USEDEFAULT ) GetDXUTState().SetWindowCreatedWithDefaultPositions( true ); // Find the window's initial size, but it might be changed later int nDefaultWidth = 640; int nDefaultHeight = 480; if( GetDXUTState().GetOverrideWidth() != 0 ) nDefaultWidth = GetDXUTState().GetOverrideWidth(); if( GetDXUTState().GetOverrideHeight() != 0 ) nDefaultHeight = GetDXUTState().GetOverrideHeight(); SetRect( &rc, 0, 0, nDefaultWidth, nDefaultHeight ); AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu != NULL ) ? true : false ); WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle(); StringCchCopy( strCachedWindowTitle, 256, strWindowTitle ); // Create the render window // 21/02/2012 changed to prevent window from being resized (original line is below) // re-enabled window resizing // HWND hWnd = CreateWindow( L"Direct3DWindowClass", strWindowTitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, HWND hWnd = CreateWindow( L"Direct3DWindowClass", strWindowTitle, WS_OVERLAPPEDWINDOW, x, y, (rc.right-rc.left), (rc.bottom-rc.top), 0, hMenu, hInstance, 0 ); if( hWnd == NULL ) { DWORD dwError = GetLastError(); return DXUT_ERR_MSGBOX( L"CreateWindow", HRESULT_FROM_WIN32(dwError) ); } GetDXUTState().SetWindowCreated( true ); GetDXUTState().SetHWNDFocus( hWnd ); GetDXUTState().SetHWNDDeviceFullScreen( hWnd ); GetDXUTState().SetHWNDDeviceWindowed( hWnd ); } return S_OK; } //-------------------------------------------------------------------------------------- // Sets a previously created window for the framework to use. If DXUTInit() // has not already been called, it will call it with the default parameters. // Instead of calling this, you can call DXUTCreateWindow() to create a new window. //-------------------------------------------------------------------------------------- HRESULT DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages ) { HRESULT hr; // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); GetDXUTState().SetWindowCreateCalled( true ); // To avoid confusion, we do not allow any HWND to be NULL here. The // caller must pass in valid HWND for all three parameters. The same // HWND may be used for more than one parameter. if( hWndFocus == NULL || hWndDeviceFullScreen == NULL || hWndDeviceWindowed == NULL ) return DXUT_ERR_MSGBOX( L"DXUTSetWindow", E_INVALIDARG ); // If subclassing the window, set the pointer to the local window procedure if( bHandleMessages ) { // Switch window procedures #ifdef _WIN64 LONG_PTR nResult = SetWindowLongPtr( hWndFocus, GWLP_WNDPROC, (LONG_PTR)DXUTStaticWndProc ); #else LONG_PTR nResult = SetWindowLongPtr( hWndFocus, GWLP_WNDPROC, (LONG)(LONG_PTR)DXUTStaticWndProc ); #endif DWORD dwError = GetLastError(); if( nResult == 0 ) return DXUT_ERR_MSGBOX( L"SetWindowLongPtr", HRESULT_FROM_WIN32(dwError) ); } if( !GetDXUTState().GetDXUTInited() ) { // If DXUTInit() was already called and failed, then fail. // DXUTInit() must first succeed for this function to succeed if( GetDXUTState().GetDXUTInitCalled() ) return E_FAIL; // If DXUTInit() hasn't been called, then automatically call it // with default params hr = DXUTInit(); if( FAILED(hr) ) return hr; } WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle(); GetWindowText( hWndFocus, strCachedWindowTitle, 255 ); strCachedWindowTitle[255] = 0; HINSTANCE hInstance = (HINSTANCE) (LONG_PTR) GetWindowLongPtr( hWndFocus, GWLP_HINSTANCE ); GetDXUTState().SetHInstance( hInstance ); GetDXUTState().SetWindowCreatedWithDefaultPositions( false ); GetDXUTState().SetWindowCreated( true ); GetDXUTState().SetHWNDFocus( hWndFocus ); GetDXUTState().SetHWNDDeviceFullScreen( hWndDeviceFullScreen ); GetDXUTState().SetHWNDDeviceWindowed( hWndDeviceWindowed ); return S_OK; } //-------------------------------------------------------------------------------------- // Creates a Direct3D device. If DXUTCreateWindow() or DXUTSetWindow() has not already // been called, it will call DXUTCreateWindow() with the default parameters. // Instead of calling this, you can call DXUTSetDevice() or DXUTCreateDeviceFromSettings() //-------------------------------------------------------------------------------------- HRESULT DXUTCreateDevice( UINT AdapterOrdinal, bool bWindowed, int nSuggestedWidth, int nSuggestedHeight, LPDXUTCALLBACKISDEVICEACCEPTABLE pCallbackIsDeviceAcceptable, LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings, void* pUserContext ) { HRESULT hr; // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); // Record the function arguments in the global state GetDXUTState().SetIsDeviceAcceptableFunc( pCallbackIsDeviceAcceptable ); GetDXUTState().SetModifyDeviceSettingsFunc( pCallbackModifyDeviceSettings ); GetDXUTState().SetIsDeviceAcceptableFuncUserContext( pUserContext ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); GetDXUTState().SetDeviceCreateCalled( true ); // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, // then call DXUTCreateWindow() with the default parameters. if( !GetDXUTState().GetWindowCreated() ) { // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. // DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed if( GetDXUTState().GetWindowCreateCalled() ) return E_FAIL; // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then // automatically call DXUTCreateWindow() with default params hr = DXUTCreateWindow(); if( FAILED(hr) ) return hr; } // Force an enumeration with the new IsDeviceAcceptable callback DXUTPrepareEnumerationObject( true ); DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT; matchOptions.eDeviceType = DXUTMT_IGNORE_INPUT; matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT; matchOptions.eAdapterFormat = DXUTMT_IGNORE_INPUT; matchOptions.eVertexProcessing = DXUTMT_IGNORE_INPUT; if( bWindowed || (nSuggestedWidth != 0 && nSuggestedHeight != 0) ) matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; else matchOptions.eResolution = DXUTMT_IGNORE_INPUT; matchOptions.eBackBufferFormat = DXUTMT_IGNORE_INPUT; matchOptions.eBackBufferCount = DXUTMT_IGNORE_INPUT; matchOptions.eMultiSample = DXUTMT_IGNORE_INPUT; matchOptions.eSwapEffect = DXUTMT_IGNORE_INPUT; matchOptions.eDepthFormat = DXUTMT_IGNORE_INPUT; matchOptions.eStencilFormat = DXUTMT_IGNORE_INPUT; matchOptions.ePresentFlags = DXUTMT_IGNORE_INPUT; matchOptions.eRefreshRate = DXUTMT_IGNORE_INPUT; matchOptions.ePresentInterval = DXUTMT_IGNORE_INPUT; DXUTDeviceSettings deviceSettings; ZeroMemory( &deviceSettings, sizeof(DXUTDeviceSettings) ); deviceSettings.AdapterOrdinal = AdapterOrdinal; deviceSettings.pp.Windowed = bWindowed; deviceSettings.pp.BackBufferWidth = nSuggestedWidth; deviceSettings.pp.BackBufferHeight = nSuggestedHeight; // Override with settings from the command line if( GetDXUTState().GetOverrideWidth() != 0 ) deviceSettings.pp.BackBufferWidth = GetDXUTState().GetOverrideWidth(); if( GetDXUTState().GetOverrideHeight() != 0 ) deviceSettings.pp.BackBufferHeight = GetDXUTState().GetOverrideHeight(); if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 ) deviceSettings.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); if( GetDXUTState().GetOverrideFullScreen() ) { deviceSettings.pp.Windowed = FALSE; if( GetDXUTState().GetOverrideWidth() == 0 && GetDXUTState().GetOverrideHeight() == 0 ) matchOptions.eResolution = DXUTMT_IGNORE_INPUT; } if( GetDXUTState().GetOverrideWindowed() ) deviceSettings.pp.Windowed = TRUE; if( GetDXUTState().GetOverrideForceHAL() ) { deviceSettings.DeviceType = D3DDEVTYPE_HAL; matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT; } if( GetDXUTState().GetOverrideForceREF() ) { deviceSettings.DeviceType = D3DDEVTYPE_REF; matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT; } if( GetDXUTState().GetOverrideForcePureHWVP() ) { deviceSettings.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE; matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT; } else if( GetDXUTState().GetOverrideForceHWVP() ) { deviceSettings.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT; } else if( GetDXUTState().GetOverrideForceSWVP() ) { deviceSettings.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; matchOptions.eVertexProcessing = DXUTMT_PRESERVE_INPUT; } if( GetDXUTState().GetOverrideForceVsync() == 0 ) { deviceSettings.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; matchOptions.ePresentInterval = DXUTMT_PRESERVE_INPUT; } else if( GetDXUTState().GetOverrideForceVsync() == 1 ) { deviceSettings.pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; matchOptions.ePresentInterval = DXUTMT_PRESERVE_INPUT; } hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); if( FAILED(hr) ) // the call will fail if no valid devices were found { DXUTDisplayErrorMessage( hr ); return DXUT_ERR( L"DXUTFindValidDeviceSettings", hr ); } // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreated the scene hr = DXUTChangeDevice( &deviceSettings, NULL, false, true ); if( FAILED(hr) ) return hr; return S_OK; } //-------------------------------------------------------------------------------------- // Passes a previously created Direct3D device for use by the framework. // If DXUTCreateWindow() has not already been called, it will call it with the // default parameters. Instead of calling this, you can call DXUTCreateDevice() or // DXUTCreateDeviceFromSettings() //-------------------------------------------------------------------------------------- HRESULT DXUTSetDevice( IDirect3DDevice9* pd3dDevice ) { HRESULT hr; if( pd3dDevice == NULL ) return DXUT_ERR_MSGBOX( L"DXUTSetDevice", E_INVALIDARG ); // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); GetDXUTState().SetDeviceCreateCalled( true ); // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, // then call DXUTCreateWindow() with the default parameters. if( !GetDXUTState().GetWindowCreated() ) { // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. // DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed if( GetDXUTState().GetWindowCreateCalled() ) return E_FAIL; // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then // automatically call DXUTCreateWindow() with default params hr = DXUTCreateWindow(); if( FAILED(hr) ) return hr; } DXUTDeviceSettings* pDeviceSettings = new DXUTDeviceSettings; if( pDeviceSettings == NULL ) return E_OUTOFMEMORY; ZeroMemory( pDeviceSettings, sizeof(DXUTDeviceSettings) ); // Get the present params from the swap chain IDirect3DSurface9* pBackBuffer = NULL; hr = pd3dDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); if( SUCCEEDED(hr) ) { IDirect3DSwapChain9* pSwapChain = NULL; hr = pBackBuffer->GetContainer( IID_IDirect3DSwapChain9, (void**) &pSwapChain ); if( SUCCEEDED(hr) ) { pSwapChain->GetPresentParameters( &pDeviceSettings->pp ); SAFE_RELEASE( pSwapChain ); } SAFE_RELEASE( pBackBuffer ); } D3DDEVICE_CREATION_PARAMETERS d3dCreationParams; pd3dDevice->GetCreationParameters( &d3dCreationParams ); // Fill out the rest of the device settings struct pDeviceSettings->AdapterOrdinal = d3dCreationParams.AdapterOrdinal; pDeviceSettings->DeviceType = d3dCreationParams.DeviceType; DXUTFindAdapterFormat( pDeviceSettings->AdapterOrdinal, pDeviceSettings->DeviceType, pDeviceSettings->pp.BackBufferFormat, pDeviceSettings->pp.Windowed, &pDeviceSettings->AdapterFormat ); pDeviceSettings->BehaviorFlags = d3dCreationParams.BehaviorFlags; // Change to the Direct3D device passed in hr = DXUTChangeDevice( pDeviceSettings, pd3dDevice, false, false ); delete pDeviceSettings; if( FAILED(hr) ) return hr; return S_OK; } //-------------------------------------------------------------------------------------- // Tells the framework to change to a device created from the passed in device settings // If DXUTCreateWindow() has not already been called, it will call it with the // default parameters. Instead of calling this, you can call DXUTCreateDevice() // or DXUTSetDevice() //-------------------------------------------------------------------------------------- HRESULT DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput, bool bClipWindowToSingleAdapter ) { HRESULT hr; GetDXUTState().SetDeviceCreateCalled( true ); // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, // then call DXUTCreateWindow() with the default parameters. if( !GetDXUTState().GetWindowCreated() ) { // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. // DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed if( GetDXUTState().GetWindowCreateCalled() ) return E_FAIL; // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then // automatically call DXUTCreateWindow() with default params hr = DXUTCreateWindow(); if( FAILED(hr) ) return hr; } if( !bPreserveInput ) { // If not preserving the input, then find the closest valid to it DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT; hr = DXUTFindValidDeviceSettings( pDeviceSettings, pDeviceSettings, &matchOptions ); if( FAILED(hr) ) // the call will fail if no valid devices were found { DXUTDisplayErrorMessage( hr ); return DXUT_ERR( L"DXUTFindValidDeviceSettings", hr ); } } // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreate the scene hr = DXUTChangeDevice( pDeviceSettings, NULL, false, bClipWindowToSingleAdapter ); if( FAILED(hr) ) return hr; return S_OK; } //-------------------------------------------------------------------------------------- // Toggle between full screen and windowed //-------------------------------------------------------------------------------------- HRESULT DXUTToggleFullScreen() { HRESULT hr; // Get the current device settings and flip the windowed state then // find the closest valid device settings with this change DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); deviceSettings.pp.Windowed = !deviceSettings.pp.Windowed; DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT; matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT; matchOptions.eAdapterFormat = DXUTMT_IGNORE_INPUT; matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferFormat = DXUTMT_IGNORE_INPUT; matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eRefreshRate = DXUTMT_IGNORE_INPUT; matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT; // Go back to previous state UINT nWidth = ( deviceSettings.pp.Windowed ) ? GetDXUTState().GetWindowBackBufferWidthAtModeChange() : GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(); UINT nHeight = ( deviceSettings.pp.Windowed ) ? GetDXUTState().GetWindowBackBufferHeightAtModeChange() : GetDXUTState().GetFullScreenBackBufferHeightAtModeChange(); if( nWidth > 0 && nHeight > 0 ) { matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; deviceSettings.pp.BackBufferWidth = nWidth; deviceSettings.pp.BackBufferHeight = nHeight; } else { // No previous data, so just switch to defaults matchOptions.eResolution = DXUTMT_IGNORE_INPUT; } hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); if( SUCCEEDED(hr) ) { // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. hr = DXUTChangeDevice( &deviceSettings, NULL, false, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED(hr) && (hr != E_ABORT) ) { // Failed creating device, try to switch back. deviceSettings.pp.Windowed = !deviceSettings.pp.Windowed; nWidth = ( deviceSettings.pp.Windowed ) ? GetDXUTState().GetWindowBackBufferWidthAtModeChange() : GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(); nHeight = ( deviceSettings.pp.Windowed ) ? GetDXUTState().GetWindowBackBufferHeightAtModeChange() : GetDXUTState().GetFullScreenBackBufferHeightAtModeChange(); if( nWidth > 0 && nHeight > 0 ) { matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; deviceSettings.pp.BackBufferWidth = nWidth; deviceSettings.pp.BackBufferHeight = nHeight; } else { matchOptions.eResolution = DXUTMT_IGNORE_INPUT; } DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); HRESULT hr2 = DXUTChangeDevice( &deviceSettings, NULL, false, false ); if( FAILED(hr2) ) { // If this failed, then shutdown DXUTShutdown(); } } } return hr; } //-------------------------------------------------------------------------------------- // Toggle between HAL and REF //-------------------------------------------------------------------------------------- HRESULT DXUTToggleREF() { HRESULT hr; DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); if( deviceSettings.DeviceType == D3DDEVTYPE_HAL ) deviceSettings.DeviceType = D3DDEVTYPE_REF; else if( deviceSettings.DeviceType == D3DDEVTYPE_REF ) deviceSettings.DeviceType = D3DDEVTYPE_HAL; DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT; matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT; matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT; hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); if( SUCCEEDED(hr) ) { // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. hr = DXUTChangeDevice( &deviceSettings, NULL, false, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && (hr != E_ABORT) ) { // Failed creating device, try to switch back. if( deviceSettings.DeviceType == D3DDEVTYPE_HAL ) deviceSettings.DeviceType = D3DDEVTYPE_REF; else if( deviceSettings.DeviceType == D3DDEVTYPE_REF ) deviceSettings.DeviceType = D3DDEVTYPE_HAL; DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); HRESULT hr2 = DXUTChangeDevice( &deviceSettings, NULL, false, false ); if( FAILED(hr2) ) { // If this failed, then shutdown DXUTShutdown(); } } } return hr; } //-------------------------------------------------------------------------------------- // Internal helper function to prepare the enumeration object by creating it if it // didn't already exist and enumerating if desired. //-------------------------------------------------------------------------------------- CD3DEnumeration* DXUTPrepareEnumerationObject( bool bEnumerate ) { // Create a new CD3DEnumeration object and enumerate all devices unless its already been done CD3DEnumeration* pd3dEnum = GetDXUTState().GetD3DEnumeration(); if( pd3dEnum == NULL ) { pd3dEnum = DXUTGetEnumeration(); GetDXUTState().SetD3DEnumeration( pd3dEnum ); bEnumerate = true; } if( bEnumerate ) { // Enumerate for each adapter all of the supported display modes, // device types, adapter formats, back buffer formats, window/full screen support, // depth stencil formats, multisampling types/qualities, and presentations intervals. // // For each combination of device type (HAL/REF), adapter format, back buffer format, and // IsWindowed it will call the app's ConfirmDevice callback. This allows the app // to reject or allow that combination based on its caps/etc. It also allows the // app to change the BehaviorFlags. The BehaviorFlags defaults non-pure HWVP // if supported otherwise it will default to SWVP, however the app can change this // through the ConfirmDevice callback. IDirect3D9* pD3D = DXUTGetD3DObject(); pd3dEnum->Enumerate( pD3D, GetDXUTState().GetIsDeviceAcceptableFunc(), GetDXUTState().GetIsDeviceAcceptableFuncUserContext() ); } return pd3dEnum; } //-------------------------------------------------------------------------------------- // This function tries to find valid device settings based upon the input device settings // struct and the match options. For each device setting a match option in the // DXUTMatchOptions struct specifies how the function makes decisions. For example, if // the caller wants a HAL device with a back buffer format of D3DFMT_A2B10G10R10 but the // HAL device on the system does not support D3DFMT_A2B10G10R10 however a REF device is // installed that does, then the function has a choice to either use REF or to change to // a back buffer format to compatible with the HAL device. The match options lets the // caller control how these choices are made. // // Each match option must be one of the following types: // DXUTMT_IGNORE_INPUT: Uses the closest valid value to a default // DXUTMT_PRESERVE_INPUT: Uses the input without change, but may cause no valid device to be found // DXUTMT_CLOSEST_TO_INPUT: Uses the closest valid value to the input // // If pMatchOptions is NULL then, all of the match options are assumed to be DXUTMT_IGNORE_INPUT. // The function returns failure if no valid device settings can be found otherwise // the function returns success and the valid device settings are written to pOut. //-------------------------------------------------------------------------------------- HRESULT DXUTFindValidDeviceSettings( DXUTDeviceSettings* pOut, DXUTDeviceSettings* pIn, DXUTMatchOptions* pMatchOptions ) { if( pOut == NULL ) return DXUT_ERR_MSGBOX( L"DXUTFindValidDeviceSettings", E_INVALIDARG ); CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject( false ); IDirect3D9* pD3D = DXUTGetD3DObject(); // Default to DXUTMT_IGNORE_INPUT for everything unless pMatchOptions isn't NULL DXUTMatchOptions defaultMatchOptions; if( NULL == pMatchOptions ) { ZeroMemory( &defaultMatchOptions, sizeof(DXUTMatchOptions) ); pMatchOptions = &defaultMatchOptions; } // Build an optimal device settings structure based upon the match // options. If the match option is set to ignore, then a optimal default value is used. // The default value may not exist on the system, but later this will be taken // into account. DXUTDeviceSettings optimalDeviceSettings; DXUTBuildOptimalDeviceSettings( &optimalDeviceSettings, pIn, pMatchOptions ); // Find the best combination of: // Adapter Ordinal // Device Type // Adapter Format // Back Buffer Format // Windowed // given what's available on the system and the match options combined with the device settings input. // This combination of settings is encapsulated by the CD3DEnumDeviceSettingsCombo class. float fBestRanking = -1.0f; CD3DEnumDeviceSettingsCombo* pBestDeviceSettingsCombo = NULL; D3DDISPLAYMODE adapterDesktopDisplayMode; CGrowableArray<CD3DEnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); for( int iAdapter=0; iAdapter<pAdapterList->GetSize(); iAdapter++ ) { CD3DEnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt(iAdapter); // Get the desktop display mode of adapter pD3D->GetAdapterDisplayMode( pAdapterInfo->AdapterOrdinal, &adapterDesktopDisplayMode ); // Enum all the device types supported by this adapter to find the best device settings for( int iDeviceInfo=0; iDeviceInfo<pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) { CD3DEnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt(iDeviceInfo); // Enum all the device settings combinations. A device settings combination is // a unique set of an adapter format, back buffer format, and IsWindowed. for( int iDeviceCombo=0; iDeviceCombo<pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) { CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt(iDeviceCombo); // If windowed mode the adapter format has to be the same as the desktop // display mode format so skip any that don't match if (pDeviceSettingsCombo->Windowed && (pDeviceSettingsCombo->AdapterFormat != adapterDesktopDisplayMode.Format)) continue; // Skip any combo that doesn't meet the preserve match options if( false == DXUTDoesDeviceComboMatchPreserveOptions( pDeviceSettingsCombo, pIn, pMatchOptions ) ) continue; // Get a ranking number that describes how closely this device combo matches the optimal combo float fCurRanking = DXUTRankDeviceCombo( pDeviceSettingsCombo, &optimalDeviceSettings, &adapterDesktopDisplayMode ); // If this combo better matches the input device settings then save it if( fCurRanking > fBestRanking ) { pBestDeviceSettingsCombo = pDeviceSettingsCombo; fBestRanking = fCurRanking; } } } } // If no best device combination was found then fail if( pBestDeviceSettingsCombo == NULL ) return DXUTERR_NOCOMPATIBLEDEVICES; // Using the best device settings combo found, build valid device settings taking heed of // the match options and the input device settings DXUTDeviceSettings validDeviceSettings; DXUTBuildValidDeviceSettings( &validDeviceSettings, pBestDeviceSettingsCombo, pIn, pMatchOptions ); *pOut = validDeviceSettings; return S_OK; } //-------------------------------------------------------------------------------------- // Internal helper function to build a device settings structure based upon the match // options. If the match option is set to ignore, then a optimal default value is used. // The default value may not exist on the system, but later this will be taken // into account. //-------------------------------------------------------------------------------------- void DXUTBuildOptimalDeviceSettings( DXUTDeviceSettings* pOptimalDeviceSettings, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ) { IDirect3D9* pD3D = DXUTGetD3DObject(); D3DDISPLAYMODE adapterDesktopDisplayMode; ZeroMemory( pOptimalDeviceSettings, sizeof(DXUTDeviceSettings) ); //--------------------- // Adapter ordinal //--------------------- if( pMatchOptions->eAdapterOrdinal == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->AdapterOrdinal = D3DADAPTER_DEFAULT; else pOptimalDeviceSettings->AdapterOrdinal = pDeviceSettingsIn->AdapterOrdinal; //--------------------- // Device type //--------------------- if( pMatchOptions->eDeviceType == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->DeviceType = D3DDEVTYPE_HAL; else pOptimalDeviceSettings->DeviceType = pDeviceSettingsIn->DeviceType; //--------------------- // Windowed //--------------------- if( pMatchOptions->eWindowed == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.Windowed = TRUE; else pOptimalDeviceSettings->pp.Windowed = pDeviceSettingsIn->pp.Windowed; //--------------------- // Adapter format //--------------------- if( pMatchOptions->eAdapterFormat == DXUTMT_IGNORE_INPUT ) { // If windowed, default to the desktop display mode // If fullscreen, default to the desktop display mode for quick mode change or // default to D3DFMT_X8R8G8B8 if the desktop display mode is < 32bit pD3D->GetAdapterDisplayMode( pOptimalDeviceSettings->AdapterOrdinal, &adapterDesktopDisplayMode ); if( pOptimalDeviceSettings->pp.Windowed || DXUTColorChannelBits(adapterDesktopDisplayMode.Format) >= 8 ) pOptimalDeviceSettings->AdapterFormat = adapterDesktopDisplayMode.Format; else pOptimalDeviceSettings->AdapterFormat = D3DFMT_X8R8G8B8; } else { pOptimalDeviceSettings->AdapterFormat = pDeviceSettingsIn->AdapterFormat; } //--------------------- // Vertex processing //--------------------- if( pMatchOptions->eVertexProcessing == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; else pOptimalDeviceSettings->BehaviorFlags = pDeviceSettingsIn->BehaviorFlags; //--------------------- // Resolution //--------------------- if( pMatchOptions->eResolution == DXUTMT_IGNORE_INPUT ) { // If windowed, default to 640x480 // If fullscreen, default to the desktop res for quick mode change if( pOptimalDeviceSettings->pp.Windowed ) { pOptimalDeviceSettings->pp.BackBufferWidth = 640; pOptimalDeviceSettings->pp.BackBufferHeight = 480; } else { pD3D->GetAdapterDisplayMode( pOptimalDeviceSettings->AdapterOrdinal, &adapterDesktopDisplayMode ); pOptimalDeviceSettings->pp.BackBufferWidth = adapterDesktopDisplayMode.Width; pOptimalDeviceSettings->pp.BackBufferHeight = adapterDesktopDisplayMode.Height; } } else { pOptimalDeviceSettings->pp.BackBufferWidth = pDeviceSettingsIn->pp.BackBufferWidth; pOptimalDeviceSettings->pp.BackBufferHeight = pDeviceSettingsIn->pp.BackBufferHeight; } //--------------------- // Back buffer format //--------------------- if( pMatchOptions->eBackBufferFormat == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.BackBufferFormat = pOptimalDeviceSettings->AdapterFormat; // Default to match the adapter format else pOptimalDeviceSettings->pp.BackBufferFormat = pDeviceSettingsIn->pp.BackBufferFormat; //--------------------- // Back buffer count //--------------------- if( pMatchOptions->eBackBufferCount == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.BackBufferCount = 2; // Default to triple buffering for perf gain else pOptimalDeviceSettings->pp.BackBufferCount = pDeviceSettingsIn->pp.BackBufferCount; //--------------------- // Multisample //--------------------- if( pMatchOptions->eMultiSample == DXUTMT_IGNORE_INPUT ) { // Default to no multisampling pOptimalDeviceSettings->pp.MultiSampleType = D3DMULTISAMPLE_NONE; pOptimalDeviceSettings->pp.MultiSampleQuality = 0; } else { pOptimalDeviceSettings->pp.MultiSampleType = pDeviceSettingsIn->pp.MultiSampleType; pOptimalDeviceSettings->pp.MultiSampleQuality = pDeviceSettingsIn->pp.MultiSampleQuality; } //--------------------- // Swap effect //--------------------- if( pMatchOptions->eSwapEffect == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.SwapEffect = D3DSWAPEFFECT_DISCARD; else pOptimalDeviceSettings->pp.SwapEffect = pDeviceSettingsIn->pp.SwapEffect; //--------------------- // Depth stencil //--------------------- if( pMatchOptions->eDepthFormat == DXUTMT_IGNORE_INPUT && pMatchOptions->eStencilFormat == DXUTMT_IGNORE_INPUT ) { UINT nBackBufferBits = DXUTColorChannelBits( pOptimalDeviceSettings->pp.BackBufferFormat ); if( nBackBufferBits >= 8 ) pOptimalDeviceSettings->pp.AutoDepthStencilFormat = D3DFMT_D32; else pOptimalDeviceSettings->pp.AutoDepthStencilFormat = D3DFMT_D16; } else { pOptimalDeviceSettings->pp.AutoDepthStencilFormat = pDeviceSettingsIn->pp.AutoDepthStencilFormat; } //--------------------- // Present flags //--------------------- if( pMatchOptions->ePresentFlags == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; else pOptimalDeviceSettings->pp.Flags = pDeviceSettingsIn->pp.Flags; //--------------------- // Refresh rate //--------------------- if( pMatchOptions->eRefreshRate == DXUTMT_IGNORE_INPUT ) pOptimalDeviceSettings->pp.FullScreen_RefreshRateInHz = 0; else pOptimalDeviceSettings->pp.FullScreen_RefreshRateInHz = pDeviceSettingsIn->pp.FullScreen_RefreshRateInHz; //--------------------- // Present interval //--------------------- if( pMatchOptions->ePresentInterval == DXUTMT_IGNORE_INPUT ) { // For windowed and fullscreen, default to D3DPRESENT_INTERVAL_DEFAULT // which will wait for the vertical retrace period to prevent tearing. // For benchmarking, use D3DPRESENT_INTERVAL_DEFAULT which will // will wait not for the vertical retrace period but may introduce tearing. pOptimalDeviceSettings->pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; } else { pOptimalDeviceSettings->pp.PresentationInterval = pDeviceSettingsIn->pp.PresentationInterval; } } //-------------------------------------------------------------------------------------- // Returns false for any CD3DEnumDeviceSettingsCombo that doesn't meet the preserve // match options against the input pDeviceSettingsIn. //-------------------------------------------------------------------------------------- bool DXUTDoesDeviceComboMatchPreserveOptions( CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ) { //--------------------- // Adapter ordinal //--------------------- if( pMatchOptions->eAdapterOrdinal == DXUTMT_PRESERVE_INPUT && (pDeviceSettingsCombo->AdapterOrdinal != pDeviceSettingsIn->AdapterOrdinal) ) return false; //--------------------- // Device type //--------------------- if( pMatchOptions->eDeviceType == DXUTMT_PRESERVE_INPUT && (pDeviceSettingsCombo->DeviceType != pDeviceSettingsIn->DeviceType) ) return false; //--------------------- // Windowed //--------------------- if( pMatchOptions->eWindowed == DXUTMT_PRESERVE_INPUT && (pDeviceSettingsCombo->Windowed != pDeviceSettingsIn->pp.Windowed) ) return false; //--------------------- // Adapter format //--------------------- if( pMatchOptions->eAdapterFormat == DXUTMT_PRESERVE_INPUT && (pDeviceSettingsCombo->AdapterFormat != pDeviceSettingsIn->AdapterFormat) ) return false; //--------------------- // Vertex processing //--------------------- // If keep VP and input has HWVP, then skip if this combo doesn't have HWTL if( pMatchOptions->eVertexProcessing == DXUTMT_PRESERVE_INPUT && ((pDeviceSettingsIn->BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) != 0) && ((pDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0) ) return false; //--------------------- // Resolution //--------------------- // If keep resolution then check that width and height supported by this combo if( pMatchOptions->eResolution == DXUTMT_PRESERVE_INPUT ) { bool bFound = false; for( int i=0; i< pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); i++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( i ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; // Skip this display mode if it doesn't match the combo's adapter format if( displayMode.Width == pDeviceSettingsIn->pp.BackBufferWidth && displayMode.Height == pDeviceSettingsIn->pp.BackBufferHeight ) { bFound = true; break; } } // If the width and height are not supported by this combo, return false if( !bFound ) return false; } //--------------------- // Back buffer format //--------------------- if( pMatchOptions->eBackBufferFormat == DXUTMT_PRESERVE_INPUT && pDeviceSettingsCombo->BackBufferFormat != pDeviceSettingsIn->pp.BackBufferFormat ) return false; //--------------------- // Back buffer count //--------------------- // No caps for the back buffer count //--------------------- // Multisample //--------------------- if( pMatchOptions->eMultiSample == DXUTMT_PRESERVE_INPUT ) { bool bFound = false; for( int i=0; i<pDeviceSettingsCombo->multiSampleTypeList.GetSize(); i++ ) { D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt(i); DWORD msQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt(i); if( msType == pDeviceSettingsIn->pp.MultiSampleType && msQuality >= pDeviceSettingsIn->pp.MultiSampleQuality ) { bFound = true; break; } } // If multisample type/quality not supported by this combo, then return false if( !bFound ) return false; } //--------------------- // Swap effect //--------------------- // No caps for swap effects //--------------------- // Depth stencil //--------------------- // If keep depth stencil format then check that the depth stencil format is supported by this combo if( pMatchOptions->eDepthFormat == DXUTMT_PRESERVE_INPUT && pMatchOptions->eStencilFormat == DXUTMT_PRESERVE_INPUT ) { if( pDeviceSettingsIn->pp.AutoDepthStencilFormat != D3DFMT_UNKNOWN && !pDeviceSettingsCombo->depthStencilFormatList.Contains( pDeviceSettingsIn->pp.AutoDepthStencilFormat ) ) return false; } // If keep depth format then check that the depth format is supported by this combo if( pMatchOptions->eDepthFormat == DXUTMT_PRESERVE_INPUT && pDeviceSettingsIn->pp.AutoDepthStencilFormat != D3DFMT_UNKNOWN ) { bool bFound = false; UINT dwDepthBits = DXUTDepthBits( pDeviceSettingsIn->pp.AutoDepthStencilFormat ); for( int i=0; i<pDeviceSettingsCombo->depthStencilFormatList.GetSize(); i++ ) { D3DFORMAT depthStencilFmt = pDeviceSettingsCombo->depthStencilFormatList.GetAt(i); UINT dwCurDepthBits = DXUTDepthBits( depthStencilFmt ); if( dwCurDepthBits - dwDepthBits == 0) bFound = true; } if( !bFound ) return false; } // If keep depth format then check that the depth format is supported by this combo if( pMatchOptions->eStencilFormat == DXUTMT_PRESERVE_INPUT && pDeviceSettingsIn->pp.AutoDepthStencilFormat != D3DFMT_UNKNOWN ) { bool bFound = false; UINT dwStencilBits = DXUTStencilBits( pDeviceSettingsIn->pp.AutoDepthStencilFormat ); for( int i=0; i<pDeviceSettingsCombo->depthStencilFormatList.GetSize(); i++ ) { D3DFORMAT depthStencilFmt = pDeviceSettingsCombo->depthStencilFormatList.GetAt(i); UINT dwCurStencilBits = DXUTStencilBits( depthStencilFmt ); if( dwCurStencilBits - dwStencilBits == 0) bFound = true; } if( !bFound ) return false; } //--------------------- // Present flags //--------------------- // No caps for the present flags //--------------------- // Refresh rate //--------------------- // If keep refresh rate then check that the resolution is supported by this combo if( pMatchOptions->eRefreshRate == DXUTMT_PRESERVE_INPUT ) { bool bFound = false; for( int i=0; i<pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); i++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( i ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; if( displayMode.RefreshRate == pDeviceSettingsIn->pp.FullScreen_RefreshRateInHz ) { bFound = true; break; } } // If refresh rate not supported by this combo, then return false if( !bFound ) return false; } //--------------------- // Present interval //--------------------- // If keep present interval then check that the present interval is supported by this combo if( pMatchOptions->ePresentInterval == DXUTMT_PRESERVE_INPUT && !pDeviceSettingsCombo->presentIntervalList.Contains( pDeviceSettingsIn->pp.PresentationInterval ) ) return false; return true; } //-------------------------------------------------------------------------------------- // Returns a ranking number that describes how closely this device // combo matches the optimal combo based on the match options and the optimal device settings //-------------------------------------------------------------------------------------- float DXUTRankDeviceCombo( CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTDeviceSettings* pOptimalDeviceSettings, D3DDISPLAYMODE* pAdapterDesktopDisplayMode ) { float fCurRanking = 0.0f; // Arbitrary weights. Gives preference to the ordinal, device type, and windowed const float fAdapterOrdinalWeight = 1000.0f; const float fDeviceTypeWeight = 100.0f; const float fWindowWeight = 10.0f; const float fAdapterFormatWeight = 1.0f; const float fVertexProcessingWeight = 1.0f; const float fResolutionWeight = 1.0f; const float fBackBufferFormatWeight = 1.0f; const float fMultiSampleWeight = 1.0f; const float fDepthStencilWeight = 1.0f; const float fRefreshRateWeight = 1.0f; const float fPresentIntervalWeight = 1.0f; //--------------------- // Adapter ordinal //--------------------- if( pDeviceSettingsCombo->AdapterOrdinal == pOptimalDeviceSettings->AdapterOrdinal ) fCurRanking += fAdapterOrdinalWeight; //--------------------- // Device type //--------------------- if( pDeviceSettingsCombo->DeviceType == pOptimalDeviceSettings->DeviceType ) fCurRanking += fDeviceTypeWeight; // Slightly prefer HAL if( pDeviceSettingsCombo->DeviceType == D3DDEVTYPE_HAL ) fCurRanking += 0.1f; //--------------------- // Windowed //--------------------- if( pDeviceSettingsCombo->Windowed == pOptimalDeviceSettings->pp.Windowed ) fCurRanking += fWindowWeight; //--------------------- // Adapter format //--------------------- if( pDeviceSettingsCombo->AdapterFormat == pOptimalDeviceSettings->AdapterFormat ) { fCurRanking += fAdapterFormatWeight; } else { int nBitDepthDelta = abs( (long) DXUTColorChannelBits(pDeviceSettingsCombo->AdapterFormat) - (long) DXUTColorChannelBits(pOptimalDeviceSettings->AdapterFormat) ); float fScale = __max(0.9f - (float)nBitDepthDelta*0.2f, 0.0f); fCurRanking += fScale * fAdapterFormatWeight; } if( !pDeviceSettingsCombo->Windowed ) { // Slightly prefer when it matches the desktop format or is D3DFMT_X8R8G8B8 bool bAdapterOptimalMatch; if( DXUTColorChannelBits(pAdapterDesktopDisplayMode->Format) >= 8 ) bAdapterOptimalMatch = (pDeviceSettingsCombo->AdapterFormat == pAdapterDesktopDisplayMode->Format); else bAdapterOptimalMatch = (pDeviceSettingsCombo->AdapterFormat == D3DFMT_X8R8G8B8); if( bAdapterOptimalMatch ) fCurRanking += 0.1f; } //--------------------- // Vertex processing //--------------------- if( (pOptimalDeviceSettings->BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) != 0 || (pOptimalDeviceSettings->BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING) != 0 ) { if( (pDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0 ) fCurRanking += fVertexProcessingWeight; } // Slightly prefer HW T&L if( (pDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0 ) fCurRanking += 0.1f; //--------------------- // Resolution //--------------------- bool bResolutionFound = false; for( int idm = 0; idm < pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); idm++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( idm ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; if( displayMode.Width == pOptimalDeviceSettings->pp.BackBufferWidth && displayMode.Height == pOptimalDeviceSettings->pp.BackBufferHeight ) bResolutionFound = true; } if( bResolutionFound ) fCurRanking += fResolutionWeight; //--------------------- // Back buffer format //--------------------- if( pDeviceSettingsCombo->BackBufferFormat == pOptimalDeviceSettings->pp.BackBufferFormat ) { fCurRanking += fBackBufferFormatWeight; } else { int nBitDepthDelta = abs( (long) DXUTColorChannelBits(pDeviceSettingsCombo->BackBufferFormat) - (long) DXUTColorChannelBits(pOptimalDeviceSettings->pp.BackBufferFormat) ); float fScale = __max(0.9f - (float)nBitDepthDelta*0.2f, 0.0f); fCurRanking += fScale * fBackBufferFormatWeight; } // Check if this back buffer format is the same as // the adapter format since this is preferred. bool bAdapterMatchesBB = (pDeviceSettingsCombo->BackBufferFormat == pDeviceSettingsCombo->AdapterFormat); if( bAdapterMatchesBB ) fCurRanking += 0.1f; //--------------------- // Back buffer count //--------------------- // No caps for the back buffer count //--------------------- // Multisample //--------------------- bool bMultiSampleFound = false; for( int i=0; i<pDeviceSettingsCombo->multiSampleTypeList.GetSize(); i++ ) { D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt(i); DWORD msQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt(i); if( msType == pOptimalDeviceSettings->pp.MultiSampleType && msQuality >= pOptimalDeviceSettings->pp.MultiSampleQuality ) { bMultiSampleFound = true; break; } } if( bMultiSampleFound ) fCurRanking += fMultiSampleWeight; //--------------------- // Swap effect //--------------------- // No caps for swap effects //--------------------- // Depth stencil //--------------------- if( pDeviceSettingsCombo->depthStencilFormatList.Contains( pOptimalDeviceSettings->pp.AutoDepthStencilFormat ) ) fCurRanking += fDepthStencilWeight; //--------------------- // Present flags //--------------------- // No caps for the present flags //--------------------- // Refresh rate //--------------------- bool bRefreshFound = false; for( int idm = 0; idm < pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); idm++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( idm ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; if( displayMode.RefreshRate == pOptimalDeviceSettings->pp.FullScreen_RefreshRateInHz ) bRefreshFound = true; } if( bRefreshFound ) fCurRanking += fRefreshRateWeight; //--------------------- // Present interval //--------------------- // If keep present interval then check that the present interval is supported by this combo if( pDeviceSettingsCombo->presentIntervalList.Contains( pOptimalDeviceSettings->pp.PresentationInterval ) ) fCurRanking += fPresentIntervalWeight; return fCurRanking; } //-------------------------------------------------------------------------------------- // Builds valid device settings using the match options, the input device settings, and the // best device settings combo found. //-------------------------------------------------------------------------------------- void DXUTBuildValidDeviceSettings( DXUTDeviceSettings* pValidDeviceSettings, CD3DEnumDeviceSettingsCombo* pBestDeviceSettingsCombo, DXUTDeviceSettings* pDeviceSettingsIn, DXUTMatchOptions* pMatchOptions ) { IDirect3D9* pD3D = DXUTGetD3DObject(); D3DDISPLAYMODE adapterDesktopDisplayMode; pD3D->GetAdapterDisplayMode( pBestDeviceSettingsCombo->AdapterOrdinal, &adapterDesktopDisplayMode ); // For each setting pick the best, taking into account the match options and // what's supported by the device //--------------------- // Adapter Ordinal //--------------------- // Just using pBestDeviceSettingsCombo->AdapterOrdinal //--------------------- // Device Type //--------------------- // Just using pBestDeviceSettingsCombo->DeviceType //--------------------- // Windowed //--------------------- // Just using pBestDeviceSettingsCombo->Windowed //--------------------- // Adapter Format //--------------------- // Just using pBestDeviceSettingsCombo->AdapterFormat //--------------------- // Vertex processing //--------------------- DWORD dwBestBehaviorFlags = 0; if( pMatchOptions->eVertexProcessing == DXUTMT_PRESERVE_INPUT ) { dwBestBehaviorFlags = pDeviceSettingsIn->BehaviorFlags; } else if( pMatchOptions->eVertexProcessing == DXUTMT_IGNORE_INPUT ) { // The framework defaults to HWVP if available otherwise use SWVP if ((pBestDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0) dwBestBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; else dwBestBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } else // if( pMatchOptions->eVertexProcessing == DXUTMT_CLOSEST_TO_INPUT ) { // Default to input, and fallback to SWVP if HWVP not available dwBestBehaviorFlags = pDeviceSettingsIn->BehaviorFlags; if ((pBestDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 && ( (dwBestBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) != 0 || (dwBestBehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING) != 0) ) { dwBestBehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; dwBestBehaviorFlags &= ~D3DCREATE_MIXED_VERTEXPROCESSING; dwBestBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // One of these must be selected if( (dwBestBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) == 0 && (dwBestBehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING) == 0 && (dwBestBehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING) == 0 ) { if ((pBestDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) != 0) dwBestBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; else dwBestBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } } //--------------------- // Resolution //--------------------- D3DDISPLAYMODE bestDisplayMode; if( pMatchOptions->eResolution == DXUTMT_PRESERVE_INPUT ) { bestDisplayMode.Width = pDeviceSettingsIn->pp.BackBufferWidth; bestDisplayMode.Height = pDeviceSettingsIn->pp.BackBufferHeight; } else { D3DDISPLAYMODE displayModeIn; if( pMatchOptions->eResolution == DXUTMT_CLOSEST_TO_INPUT && pDeviceSettingsIn ) { displayModeIn.Width = pDeviceSettingsIn->pp.BackBufferWidth; displayModeIn.Height = pDeviceSettingsIn->pp.BackBufferHeight; } else // if( pMatchOptions->eResolution == DXUTMT_IGNORE_INPUT ) { if( pBestDeviceSettingsCombo->Windowed ) { // The framework defaults to 640x480 for windowed displayModeIn.Width = 640; displayModeIn.Height = 480; } else { // The framework defaults to desktop resolution for fullscreen to try to avoid slow mode change displayModeIn.Width = adapterDesktopDisplayMode.Width; displayModeIn.Height = adapterDesktopDisplayMode.Height; } } // Call a helper function to find the closest valid display mode to the optimal DXUTFindValidResolution( pBestDeviceSettingsCombo, displayModeIn, &bestDisplayMode ); } //--------------------- // Back Buffer Format //--------------------- // Just using pBestDeviceSettingsCombo->BackBufferFormat //--------------------- // Back buffer count //--------------------- UINT bestBackBufferCount; if( pMatchOptions->eBackBufferCount == DXUTMT_PRESERVE_INPUT ) { bestBackBufferCount = pDeviceSettingsIn->pp.BackBufferCount; } else if( pMatchOptions->eBackBufferCount == DXUTMT_IGNORE_INPUT ) { // The framework defaults to triple buffering bestBackBufferCount = 2; } else // if( pMatchOptions->eBackBufferCount == DXUTMT_CLOSEST_TO_INPUT ) { bestBackBufferCount = pDeviceSettingsIn->pp.BackBufferCount; if( bestBackBufferCount > 3 ) bestBackBufferCount = 3; if( bestBackBufferCount < 1 ) bestBackBufferCount = 1; } //--------------------- // Multisample //--------------------- D3DMULTISAMPLE_TYPE bestMultiSampleType; DWORD bestMultiSampleQuality; if( pDeviceSettingsIn && pDeviceSettingsIn->pp.SwapEffect != D3DSWAPEFFECT_DISCARD ) { // Swap effect is not set to discard so multisampling has to off bestMultiSampleType = D3DMULTISAMPLE_NONE; bestMultiSampleQuality = 0; } else { if( pMatchOptions->eMultiSample == DXUTMT_PRESERVE_INPUT ) { bestMultiSampleType = pDeviceSettingsIn->pp.MultiSampleType; bestMultiSampleQuality = pDeviceSettingsIn->pp.MultiSampleQuality; } else if( pMatchOptions->eMultiSample == DXUTMT_IGNORE_INPUT ) { // Default to no multisampling (always supported) bestMultiSampleType = D3DMULTISAMPLE_NONE; bestMultiSampleQuality = 0; } else if( pMatchOptions->eMultiSample == DXUTMT_CLOSEST_TO_INPUT ) { // Default to no multisampling (always supported) bestMultiSampleType = D3DMULTISAMPLE_NONE; bestMultiSampleQuality = 0; for( int i=0; i < pBestDeviceSettingsCombo->multiSampleTypeList.GetSize(); i++ ) { D3DMULTISAMPLE_TYPE type = pBestDeviceSettingsCombo->multiSampleTypeList.GetAt(i); DWORD qualityLevels = pBestDeviceSettingsCombo->multiSampleQualityList.GetAt(i); // Check whether supported type is closer to the input than our current best if( abs(type - pDeviceSettingsIn->pp.MultiSampleType) < abs(bestMultiSampleType - pDeviceSettingsIn->pp.MultiSampleType) ) { bestMultiSampleType = type; bestMultiSampleQuality = __min( qualityLevels-1, pDeviceSettingsIn->pp.MultiSampleQuality ); } } } else { // Error case bestMultiSampleType = D3DMULTISAMPLE_NONE; bestMultiSampleQuality = 0; } } //--------------------- // Swap effect //--------------------- D3DSWAPEFFECT bestSwapEffect; if( pMatchOptions->eSwapEffect == DXUTMT_PRESERVE_INPUT ) { bestSwapEffect = pDeviceSettingsIn->pp.SwapEffect; } else if( pMatchOptions->eSwapEffect == DXUTMT_IGNORE_INPUT ) { bestSwapEffect = D3DSWAPEFFECT_DISCARD; } else // if( pMatchOptions->eSwapEffect == DXUTMT_CLOSEST_TO_INPUT ) { bestSwapEffect = pDeviceSettingsIn->pp.SwapEffect; // Swap effect has to be one of these 3 if( bestSwapEffect != D3DSWAPEFFECT_DISCARD && bestSwapEffect != D3DSWAPEFFECT_FLIP && bestSwapEffect != D3DSWAPEFFECT_COPY ) { bestSwapEffect = D3DSWAPEFFECT_DISCARD; } } //--------------------- // Depth stencil //--------------------- D3DFORMAT bestDepthStencilFormat; BOOL bestEnableAutoDepthStencil; CGrowableArray< int > depthStencilRanking; depthStencilRanking.SetSize( pBestDeviceSettingsCombo->depthStencilFormatList.GetSize() ); UINT dwBackBufferBitDepth = DXUTColorChannelBits( pBestDeviceSettingsCombo->BackBufferFormat ); UINT dwInputDepthBitDepth = 0; if( pDeviceSettingsIn ) dwInputDepthBitDepth = DXUTDepthBits( pDeviceSettingsIn->pp.AutoDepthStencilFormat ); for( int i=0; i<pBestDeviceSettingsCombo->depthStencilFormatList.GetSize(); i++ ) { D3DFORMAT curDepthStencilFmt = pBestDeviceSettingsCombo->depthStencilFormatList.GetAt(i); DWORD dwCurDepthBitDepth = DXUTDepthBits( curDepthStencilFmt ); int nRanking; if( pMatchOptions->eDepthFormat == DXUTMT_PRESERVE_INPUT ) { // Need to match bit depth of input if(dwCurDepthBitDepth == dwInputDepthBitDepth) nRanking = 0; else nRanking = 10000; } else if( pMatchOptions->eDepthFormat == DXUTMT_IGNORE_INPUT ) { // Prefer match of backbuffer bit depth nRanking = abs((int)dwCurDepthBitDepth - (int)dwBackBufferBitDepth*4); } else // if( pMatchOptions->eDepthFormat == DXUTMT_CLOSEST_TO_INPUT ) { // Prefer match of input depth format bit depth nRanking = abs((int)dwCurDepthBitDepth - (int)dwInputDepthBitDepth); } depthStencilRanking.Add( nRanking ); } UINT dwInputStencilBitDepth = 0; if( pDeviceSettingsIn ) dwInputStencilBitDepth = DXUTStencilBits( pDeviceSettingsIn->pp.AutoDepthStencilFormat ); for( int i=0; i<pBestDeviceSettingsCombo->depthStencilFormatList.GetSize(); i++ ) { D3DFORMAT curDepthStencilFmt = pBestDeviceSettingsCombo->depthStencilFormatList.GetAt(i); int nRanking = depthStencilRanking.GetAt(i); DWORD dwCurStencilBitDepth = DXUTStencilBits( curDepthStencilFmt ); if( pMatchOptions->eStencilFormat == DXUTMT_PRESERVE_INPUT ) { // Need to match bit depth of input if(dwCurStencilBitDepth == dwInputStencilBitDepth) nRanking += 0; else nRanking += 10000; } else if( pMatchOptions->eStencilFormat == DXUTMT_IGNORE_INPUT ) { // Prefer 0 stencil bit depth nRanking += dwCurStencilBitDepth; } else // if( pMatchOptions->eStencilFormat == DXUTMT_CLOSEST_TO_INPUT ) { // Prefer match of input stencil format bit depth nRanking += abs((int)dwCurStencilBitDepth - (int)dwInputStencilBitDepth); } depthStencilRanking.SetAt( i, nRanking ); } int nBestRanking = 100000; int nBestIndex = -1; for( int i=0; i<pBestDeviceSettingsCombo->depthStencilFormatList.GetSize(); i++ ) { int nRanking = depthStencilRanking.GetAt(i); if( nRanking < nBestRanking ) { nBestRanking = nRanking; nBestIndex = i; } } if( nBestIndex >= 0 ) { bestDepthStencilFormat = pBestDeviceSettingsCombo->depthStencilFormatList.GetAt(nBestIndex); bestEnableAutoDepthStencil = true; } else { bestDepthStencilFormat = D3DFMT_UNKNOWN; bestEnableAutoDepthStencil = false; } //--------------------- // Present flags //--------------------- DWORD dwBestFlags; if( pMatchOptions->ePresentFlags == DXUTMT_PRESERVE_INPUT ) { dwBestFlags = pDeviceSettingsIn->pp.Flags; } else if( pMatchOptions->ePresentFlags == DXUTMT_IGNORE_INPUT ) { dwBestFlags = 0; if( bestEnableAutoDepthStencil ) dwBestFlags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; } else // if( pMatchOptions->ePresentFlags == DXUTMT_CLOSEST_TO_INPUT ) { dwBestFlags = pDeviceSettingsIn->pp.Flags; if( bestEnableAutoDepthStencil ) dwBestFlags |= D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; } //--------------------- // Refresh rate //--------------------- if( pBestDeviceSettingsCombo->Windowed ) { // Must be 0 for windowed bestDisplayMode.RefreshRate = 0; } else { if( pMatchOptions->eRefreshRate == DXUTMT_PRESERVE_INPUT ) { bestDisplayMode.RefreshRate = pDeviceSettingsIn->pp.FullScreen_RefreshRateInHz; } else { UINT refreshRateMatch; if( pMatchOptions->eRefreshRate == DXUTMT_CLOSEST_TO_INPUT ) { refreshRateMatch = pDeviceSettingsIn->pp.FullScreen_RefreshRateInHz; } else // if( pMatchOptions->eRefreshRate == DXUTMT_IGNORE_INPUT ) { refreshRateMatch = adapterDesktopDisplayMode.RefreshRate; } bestDisplayMode.RefreshRate = 0; if( refreshRateMatch != 0 ) { int nBestRefreshRanking = 100000; CGrowableArray<D3DDISPLAYMODE>* pDisplayModeList = &pBestDeviceSettingsCombo->pAdapterInfo->displayModeList; for( int iDisplayMode=0; iDisplayMode<pDisplayModeList->GetSize(); iDisplayMode++ ) { D3DDISPLAYMODE displayMode = pDisplayModeList->GetAt(iDisplayMode); if( displayMode.Format != pBestDeviceSettingsCombo->AdapterFormat || displayMode.Height != bestDisplayMode.Height || displayMode.Width != bestDisplayMode.Width ) continue; // Skip display modes that don't match // Find the delta between the current refresh rate and the optimal refresh rate int nCurRanking = abs((int)displayMode.RefreshRate - (int)refreshRateMatch); if( nCurRanking < nBestRefreshRanking ) { bestDisplayMode.RefreshRate = displayMode.RefreshRate; nBestRefreshRanking = nCurRanking; // Stop if perfect match found if( nBestRefreshRanking == 0 ) break; } } } } } //--------------------- // Present interval //--------------------- UINT bestPresentInterval; if( pMatchOptions->ePresentInterval == DXUTMT_PRESERVE_INPUT ) { bestPresentInterval = pDeviceSettingsIn->pp.PresentationInterval; } else if( pMatchOptions->ePresentInterval == DXUTMT_IGNORE_INPUT ) { // For windowed and fullscreen, default to D3DPRESENT_INTERVAL_DEFAULT // which will wait for the vertical retrace period to prevent tearing. // For benchmarking, use D3DPRESENT_INTERVAL_DEFAULT which will // will wait not for the vertical retrace period but may introduce tearing. bestPresentInterval = D3DPRESENT_INTERVAL_DEFAULT; } else // if( pMatchOptions->ePresentInterval == DXUTMT_CLOSEST_TO_INPUT ) { if( pBestDeviceSettingsCombo->presentIntervalList.Contains( pDeviceSettingsIn->pp.PresentationInterval ) ) { bestPresentInterval = pDeviceSettingsIn->pp.PresentationInterval; } else { bestPresentInterval = D3DPRESENT_INTERVAL_DEFAULT; } } // Fill the device settings struct ZeroMemory( pValidDeviceSettings, sizeof(DXUTDeviceSettings) ); pValidDeviceSettings->AdapterOrdinal = pBestDeviceSettingsCombo->AdapterOrdinal; pValidDeviceSettings->DeviceType = pBestDeviceSettingsCombo->DeviceType; pValidDeviceSettings->AdapterFormat = pBestDeviceSettingsCombo->AdapterFormat; pValidDeviceSettings->BehaviorFlags = dwBestBehaviorFlags; pValidDeviceSettings->pp.BackBufferWidth = bestDisplayMode.Width; pValidDeviceSettings->pp.BackBufferHeight = bestDisplayMode.Height; pValidDeviceSettings->pp.BackBufferFormat = pBestDeviceSettingsCombo->BackBufferFormat; pValidDeviceSettings->pp.BackBufferCount = bestBackBufferCount; pValidDeviceSettings->pp.MultiSampleType = bestMultiSampleType; pValidDeviceSettings->pp.MultiSampleQuality = bestMultiSampleQuality; pValidDeviceSettings->pp.SwapEffect = bestSwapEffect; pValidDeviceSettings->pp.hDeviceWindow = pBestDeviceSettingsCombo->Windowed ? DXUTGetHWNDDeviceWindowed() : DXUTGetHWNDDeviceFullScreen(); pValidDeviceSettings->pp.Windowed = pBestDeviceSettingsCombo->Windowed; pValidDeviceSettings->pp.EnableAutoDepthStencil = bestEnableAutoDepthStencil; pValidDeviceSettings->pp.AutoDepthStencilFormat = bestDepthStencilFormat; pValidDeviceSettings->pp.Flags = dwBestFlags; pValidDeviceSettings->pp.FullScreen_RefreshRateInHz = bestDisplayMode.RefreshRate; pValidDeviceSettings->pp.PresentationInterval = bestPresentInterval; } //-------------------------------------------------------------------------------------- // Internal helper function to find the closest allowed display mode to the optimal //-------------------------------------------------------------------------------------- HRESULT DXUTFindValidResolution( CD3DEnumDeviceSettingsCombo* pBestDeviceSettingsCombo, D3DDISPLAYMODE displayModeIn, D3DDISPLAYMODE* pBestDisplayMode ) { D3DDISPLAYMODE bestDisplayMode; ZeroMemory( &bestDisplayMode, sizeof(D3DDISPLAYMODE) ); if( pBestDeviceSettingsCombo->Windowed ) { // In windowed mode, all resolutions are valid but restritions still apply // on the size of the window. See DXUTChangeDevice() for details *pBestDisplayMode = displayModeIn; } else { int nBestRanking = 100000; int nCurRanking; CGrowableArray<D3DDISPLAYMODE>* pDisplayModeList = &pBestDeviceSettingsCombo->pAdapterInfo->displayModeList; for( int iDisplayMode=0; iDisplayMode<pDisplayModeList->GetSize(); iDisplayMode++ ) { D3DDISPLAYMODE displayMode = pDisplayModeList->GetAt(iDisplayMode); // Skip display modes that don't match the combo's adapter format if( displayMode.Format != pBestDeviceSettingsCombo->AdapterFormat ) continue; // Find the delta between the current width/height and the optimal width/height nCurRanking = abs((int)displayMode.Width - (int)displayModeIn.Width) + abs((int)displayMode.Height- (int)displayModeIn.Height); if( nCurRanking < nBestRanking ) { bestDisplayMode = displayMode; nBestRanking = nCurRanking; // Stop if perfect match found if( nBestRanking == 0 ) break; } } if( bestDisplayMode.Width == 0 ) { *pBestDisplayMode = displayModeIn; return E_FAIL; // No valid display modes found } *pBestDisplayMode = bestDisplayMode; } return S_OK; } //-------------------------------------------------------------------------------------- // Internal helper function to return the adapter format from the first device settings // combo that matches the passed adapter ordinal, device type, backbuffer format, and windowed. //-------------------------------------------------------------------------------------- HRESULT DXUTFindAdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, BOOL Windowed, D3DFORMAT* pAdapterFormat ) { CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject(); CD3DEnumDeviceInfo* pDeviceInfo = pd3dEnum->GetDeviceInfo( AdapterOrdinal, DeviceType ); if( pDeviceInfo ) { for( int iDeviceCombo=0; iDeviceCombo<pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) { CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt(iDeviceCombo); if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat && pDeviceSettingsCombo->Windowed == Windowed ) { // Return the adapter format from the first match *pAdapterFormat = pDeviceSettingsCombo->AdapterFormat; return S_OK; } } } *pAdapterFormat = BackBufferFormat; return E_FAIL; } //-------------------------------------------------------------------------------------- // Change to a Direct3D device created from the device settings or passed in. // The framework will only reset if the device is similar to the previous device // otherwise it will cleanup the previous device (if there is one) and recreate the // scene using the app's device callbacks. //-------------------------------------------------------------------------------------- HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, IDirect3DDevice9* pd3dDeviceFromApp, bool bForceRecreate, bool bClipWindowToSingleAdapter ) { HRESULT hr; DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( DXUTGetD3DObject() == NULL ) return S_FALSE; // Make a copy of the pNewDeviceSettings on the heap DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new DXUTDeviceSettings; if( pNewDeviceSettingsOnHeap == NULL ) return E_OUTOFMEMORY; memcpy( pNewDeviceSettingsOnHeap, pNewDeviceSettings, sizeof(DXUTDeviceSettings) ); pNewDeviceSettings = pNewDeviceSettingsOnHeap; // If the ModifyDeviceSettings callback is non-NULL, then call it to let the app // change the settings or reject the device change by returning false. LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings = GetDXUTState().GetModifyDeviceSettingsFunc(); if( pCallbackModifyDeviceSettings ) { D3DCAPS9 caps; IDirect3D9* pD3D = DXUTGetD3DObject(); pD3D->GetDeviceCaps( pNewDeviceSettings->AdapterOrdinal, pNewDeviceSettings->DeviceType, &caps ); bool bContinue = pCallbackModifyDeviceSettings( pNewDeviceSettings, &caps, GetDXUTState().GetModifyDeviceSettingsFuncUserContext() ); if( !bContinue ) { // The app rejected the device change by returning false, so just use the current device if there is one. if( pOldDeviceSettings == NULL ) DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); SAFE_DELETE( pNewDeviceSettings ); return E_ABORT; } if( GetDXUTState().GetD3D() == NULL ) { SAFE_DELETE( pNewDeviceSettings ); return S_FALSE; } } GetDXUTState().SetCurrentDeviceSettings( pNewDeviceSettings ); DXUTPause( true, true ); // When a WM_SIZE message is received, it calls DXUTCheckForWindowSizeChange(). // A WM_SIZE message might be sent when adjusting the window, so tell // DXUTCheckForWindowSizeChange() to ignore size changes temporarily GetDXUTState().SetIgnoreSizeChange( true ); // Update thread safety on/off depending on Direct3D device's thread safety g_bThreadSafe = ((pNewDeviceSettings->BehaviorFlags & D3DCREATE_MULTITHREADED) != 0 ); // Only apply the cmd line overrides if this is the first device created // and DXUTSetDevice() isn't used if( NULL == pd3dDeviceFromApp && NULL == pOldDeviceSettings ) { // Updates the device settings struct based on the cmd line args. // Warning: if the device doesn't support these new settings then CreateDevice() will fail. DXUTUpdateDeviceSettingsWithOverrides( pNewDeviceSettings ); } // Take note if the backbuffer width & height are 0 now as they will change after pd3dDevice->Reset() bool bKeepCurrentWindowSize = false; if( pNewDeviceSettings->pp.BackBufferWidth == 0 && pNewDeviceSettings->pp.BackBufferHeight == 0 ) bKeepCurrentWindowSize = true; ////////////////////////// // Before reset ///////////////////////// if( pNewDeviceSettings->pp.Windowed ) { // Going to windowed mode if( pOldDeviceSettings && !pOldDeviceSettings->pp.Windowed ) { // Going from fullscreen -> windowed GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( pOldDeviceSettings->pp.BackBufferWidth ); GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( pOldDeviceSettings->pp.BackBufferHeight ); // Restore windowed mode style SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() ); } // If different device windows are used for windowed mode and fullscreen mode, // hide the fullscreen window so that it doesn't obscure the screen. if( DXUTGetHWNDDeviceFullScreen() != DXUTGetHWNDDeviceWindowed() ) ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); // If using the same window for windowed and fullscreen mode, reattach menu if one exists if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) { if( GetDXUTState().GetMenu() != NULL ) SetMenu( DXUTGetHWNDDeviceWindowed(), GetDXUTState().GetMenu() ); } } else { // Going to fullscreen mode if( pOldDeviceSettings == NULL || (pOldDeviceSettings && pOldDeviceSettings->pp.Windowed) ) { // Transistioning to full screen mode from a standard window so // save current window position/size/style now in case the user toggles to windowed mode later WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); ZeroMemory( pwp, sizeof(WINDOWPLACEMENT) ); pwp->length = sizeof(WINDOWPLACEMENT); GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); bool bIsTopmost = ( (GetWindowLong(DXUTGetHWNDDeviceWindowed(),GWL_EXSTYLE) & WS_EX_TOPMOST) != 0); GetDXUTState().SetTopmostWhileWindowed( bIsTopmost ); DWORD dwStyle = GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ); dwStyle &= ~WS_MAXIMIZE & ~WS_MINIMIZE; // remove minimize/maximize style GetDXUTState().SetWindowedStyleAtModeChange( dwStyle ); if( pOldDeviceSettings ) { GetDXUTState().SetWindowBackBufferWidthAtModeChange( pOldDeviceSettings->pp.BackBufferWidth ); GetDXUTState().SetWindowBackBufferHeightAtModeChange( pOldDeviceSettings->pp.BackBufferHeight ); } } // Hide the window to avoid animation of blank windows ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); // Set FS window style SetWindowLong( DXUTGetHWNDDeviceFullScreen(), GWL_STYLE, WS_POPUP|WS_SYSMENU ); // If using the same window for windowed and fullscreen mode, save and remove menu if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) { HMENU hMenu = GetMenu( DXUTGetHWNDDeviceFullScreen() ); GetDXUTState().SetMenu( hMenu ); SetMenu( DXUTGetHWNDDeviceFullScreen(), NULL ); } WINDOWPLACEMENT wpFullscreen; ZeroMemory( &wpFullscreen, sizeof(WINDOWPLACEMENT) ); wpFullscreen.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); if( (wpFullscreen.flags & WPF_RESTORETOMAXIMIZED) != 0 ) { // Restore the window to normal if the window was maximized then minimized. This causes the // WPF_RESTORETOMAXIMIZED flag to be set which will cause SW_RESTORE to restore the // window from minimized to maxmized which isn't what we want wpFullscreen.flags &= ~WPF_RESTORETOMAXIMIZED; wpFullscreen.showCmd = SW_RESTORE; SetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); } } // If AdapterOrdinal and DeviceType are the same, we can just do a Reset(). // If they've changed, we need to do a complete device tear down/rebuild. // Also only allow a reset if pd3dDevice is the same as the current device if( !bForceRecreate && (pd3dDeviceFromApp == NULL || pd3dDeviceFromApp == DXUTGetD3DDevice()) && DXUTGetD3DDevice() && pOldDeviceSettings && pOldDeviceSettings->AdapterOrdinal == pNewDeviceSettings->AdapterOrdinal && pOldDeviceSettings->DeviceType == pNewDeviceSettings->DeviceType && pOldDeviceSettings->BehaviorFlags == pNewDeviceSettings->BehaviorFlags ) { // Reset the Direct3D device and call the app's device callbacks hr = DXUTReset3DEnvironment(); if( FAILED(hr) ) { if( D3DERR_DEVICELOST == hr ) { // The device is lost, just mark it as so and continue on with // capturing the state and resizing the window/etc. GetDXUTState().SetDeviceLost( true ); } else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr || DXUTERR_MEDIANOTFOUND == hr ) { // Something bad happened in the app callbacks SAFE_DELETE( pOldDeviceSettings ); DXUTDisplayErrorMessage( hr ); DXUTShutdown(); return hr; } else // DXUTERR_RESETTINGDEVICE { // Reset failed and the device wasn't lost and it wasn't the apps fault, // so recreate the device to try to recover GetDXUTState().SetCurrentDeviceSettings( pOldDeviceSettings ); if( FAILED( DXUTChangeDevice( pNewDeviceSettings, pd3dDeviceFromApp, true, bClipWindowToSingleAdapter ) ) ) { // If that fails, then shutdown DXUTShutdown(); return DXUTERR_CREATINGDEVICE; } else { DXUTPause( false, false ); return S_OK; } } } } else { // Cleanup if not first device created if( pOldDeviceSettings ) DXUTCleanup3DEnvironment( false ); // Create the D3D device and call the app's device callbacks hr = DXUTCreate3DEnvironment( pd3dDeviceFromApp ); if( FAILED(hr) ) { SAFE_DELETE( pOldDeviceSettings ); DXUTCleanup3DEnvironment(); DXUTDisplayErrorMessage( hr ); DXUTPause( false, false ); GetDXUTState().SetIgnoreSizeChange( false ); return hr; } } // Enable/disable StickKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut, and Windows key // to prevent accidental task switching DXUTAllowShortcutKeys( ( pNewDeviceSettings->pp.Windowed ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() : GetDXUTState().GetAllowShortcutKeysWhenFullscreen() ); IDirect3D9* pD3D = DXUTGetD3DObject(); HMONITOR hAdapterMonitor = pD3D->GetAdapterMonitor( pNewDeviceSettings->AdapterOrdinal ); GetDXUTState().SetAdapterMonitor( hAdapterMonitor ); // Update the device stats text DXUTUpdateStaticFrameStats(); if( pOldDeviceSettings && !pOldDeviceSettings->pp.Windowed && pNewDeviceSettings->pp.Windowed ) { // Going from fullscreen -> windowed // Restore the show state, and positions/size of the window to what it was // It is important to adjust the window size // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); SetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); // Also restore the z-order of window to previous state HWND hWndInsertAfter = GetDXUTState().GetTopmostWhileWindowed() ? HWND_TOPMOST : HWND_NOTOPMOST; SetWindowPos( DXUTGetHWNDDeviceWindowed(), hWndInsertAfter, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSIZE ); } // Check to see if the window needs to be resized. // Handle cases where the window is minimized and maxmimized as well. bool bNeedToResize = false; if( pNewDeviceSettings->pp.Windowed && // only resize if in windowed mode !bKeepCurrentWindowSize ) // only resize if pp.BackbufferWidth/Height were not 0 { UINT nClientWidth; UINT nClientHeight; if( IsIconic(DXUTGetHWNDDeviceWindowed()) ) { // Window is currently minimized. To tell if it needs to resize, // get the client rect of window when its restored the // hard way using GetWindowPlacement() WINDOWPLACEMENT wp; ZeroMemory( &wp, sizeof(WINDOWPLACEMENT) ); wp.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), &wp ); if( (wp.flags & WPF_RESTORETOMAXIMIZED) != 0 && wp.showCmd == SW_SHOWMINIMIZED ) { // WPF_RESTORETOMAXIMIZED means that when the window is restored it will // be maximized. So maximize the window temporarily to get the client rect // when the window is maximized. GetSystemMetrics( SM_CXMAXIMIZED ) will give this // information if the window is on the primary but this will work on multimon. ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE ); RECT rcClient; GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient ); nClientWidth = (UINT)(rcClient.right - rcClient.left); nClientHeight = (UINT)(rcClient.bottom - rcClient.top); ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_MINIMIZE ); } else { // Use wp.rcNormalPosition to get the client rect, but wp.rcNormalPosition // includes the window frame so subtract it RECT rcFrame = {0}; AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL ); LONG nFrameWidth = rcFrame.right - rcFrame.left; LONG nFrameHeight = rcFrame.bottom - rcFrame.top; nClientWidth = (UINT)(wp.rcNormalPosition.right - wp.rcNormalPosition.left - nFrameWidth); nClientHeight = (UINT)(wp.rcNormalPosition.bottom - wp.rcNormalPosition.top - nFrameHeight); } } else { // Window is restored or maximized so just get its client rect RECT rcClient; GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient ); nClientWidth = (UINT)(rcClient.right - rcClient.left); nClientHeight = (UINT)(rcClient.bottom - rcClient.top); } // Now that we know the client rect, compare it against the back buffer size // to see if the client rect is already the right size if( nClientWidth != pNewDeviceSettings->pp.BackBufferWidth || nClientHeight != pNewDeviceSettings->pp.BackBufferHeight ) { bNeedToResize = true; } if( bClipWindowToSingleAdapter && !IsIconic(DXUTGetHWNDDeviceWindowed()) ) { // Get the rect of the monitor attached to the adapter MONITORINFO miAdapter; miAdapter.cbSize = sizeof(MONITORINFO); hAdapterMonitor = DXUTGetD3DObject()->GetAdapterMonitor( pNewDeviceSettings->AdapterOrdinal ); DXUTGetMonitorInfo( hAdapterMonitor, &miAdapter ); HMONITOR hWindowMonitor = DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY ); // Get the rect of the window RECT rcWindow; GetWindowRect( DXUTGetHWNDDeviceWindowed(), &rcWindow ); // Check if the window rect is fully inside the adapter's vitural screen rect if( (rcWindow.left < miAdapter.rcWork.left || rcWindow.right > miAdapter.rcWork.right || rcWindow.top < miAdapter.rcWork.top || rcWindow.bottom > miAdapter.rcWork.bottom) ) { if( hWindowMonitor == hAdapterMonitor && IsZoomed(DXUTGetHWNDDeviceWindowed()) ) { // If the window is maximized and on the same monitor as the adapter, then // no need to clip to single adapter as the window is already clipped // even though the rcWindow rect is outside of the miAdapter.rcWork } else { bNeedToResize = true; } } } } // Only resize window if needed if( bNeedToResize ) { // Need to resize, so if window is maximized or minimized then restore the window if( IsIconic(DXUTGetHWNDDeviceWindowed()) ) ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE ); if( IsZoomed(DXUTGetHWNDDeviceWindowed()) ) // doing the IsIconic() check first also handles the WPF_RESTORETOMAXIMIZED case ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE ); if( bClipWindowToSingleAdapter ) { // Get the rect of the monitor attached to the adapter MONITORINFO miAdapter; miAdapter.cbSize = sizeof(MONITORINFO); DXUTGetMonitorInfo( DXUTGetD3DObject()->GetAdapterMonitor( pNewDeviceSettings->AdapterOrdinal ), &miAdapter ); // Get the rect of the monitor attached to the window MONITORINFO miWindow; miWindow.cbSize = sizeof(MONITORINFO); DXUTGetMonitorInfo( DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY ), &miWindow ); // Do something reasonable if the BackBuffer size is greater than the monitor size int nAdapterMonitorWidth = miAdapter.rcWork.right - miAdapter.rcWork.left; int nAdapterMonitorHeight = miAdapter.rcWork.bottom - miAdapter.rcWork.top; int nClientWidth = pNewDeviceSettings->pp.BackBufferWidth; int nClientHeight = pNewDeviceSettings->pp.BackBufferHeight; // Get the rect of the window RECT rcWindow; GetWindowRect( DXUTGetHWNDDeviceWindowed(), &rcWindow ); // Make a window rect with a client rect that is the same size as the backbuffer RECT rcResizedWindow; rcResizedWindow.left = 0; rcResizedWindow.right = nClientWidth; rcResizedWindow.top = 0; rcResizedWindow.bottom = nClientHeight; AdjustWindowRect( &rcResizedWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL ); int nWindowWidth = rcResizedWindow.right - rcResizedWindow.left; int nWindowHeight = rcResizedWindow.bottom - rcResizedWindow.top; if( nWindowWidth > nAdapterMonitorWidth ) nWindowWidth = (nAdapterMonitorWidth - 0); if( nWindowHeight > nAdapterMonitorHeight ) nWindowHeight = (nAdapterMonitorHeight - 0); if( rcResizedWindow.left < miAdapter.rcWork.left || rcResizedWindow.top < miAdapter.rcWork.top || rcResizedWindow.right > miAdapter.rcWork.right || rcResizedWindow.bottom > miAdapter.rcWork.bottom ) { int nWindowOffsetX = (nAdapterMonitorWidth - nWindowWidth) / 2; int nWindowOffsetY = (nAdapterMonitorHeight - nWindowHeight) / 2; rcResizedWindow.left = miAdapter.rcWork.left + nWindowOffsetX; rcResizedWindow.top = miAdapter.rcWork.top + nWindowOffsetY; rcResizedWindow.right = miAdapter.rcWork.left + nWindowOffsetX + nWindowWidth; rcResizedWindow.bottom = miAdapter.rcWork.top + nWindowOffsetY + nWindowHeight; } // Resize the window. It is important to adjust the window size // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, rcResizedWindow.left, rcResizedWindow.top, nWindowWidth, nWindowHeight, SWP_NOZORDER ); } else { // Make a window rect with a client rect that is the same size as the backbuffer RECT rcWindow = {0}; rcWindow.right = (long)(pNewDeviceSettings->pp.BackBufferWidth); rcWindow.bottom = (long)(pNewDeviceSettings->pp.BackBufferHeight); AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL ); // Resize the window. It is important to adjust the window size // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. int cx = (int)(rcWindow.right - rcWindow.left); int cy = (int)(rcWindow.bottom - rcWindow.top); SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, 0, 0, cx, cy, SWP_NOZORDER|SWP_NOMOVE ); } // Its possible that the new window size is not what we asked for. // No window can be sized larger than the desktop, so see if the Windows OS resized the // window to something smaller to fit on the desktop. Also if WM_GETMINMAXINFO // will put a limit on the smallest/largest window size. RECT rcClient; GetClientRect( DXUTGetHWNDDeviceWindowed(), &rcClient ); UINT nClientWidth = (UINT)(rcClient.right - rcClient.left); UINT nClientHeight = (UINT)(rcClient.bottom - rcClient.top); if( nClientWidth != pNewDeviceSettings->pp.BackBufferWidth || nClientHeight != pNewDeviceSettings->pp.BackBufferHeight ) { // If its different, then resize the backbuffer again. This time create a backbuffer that matches the // client rect of the current window w/o resizing the window. DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); deviceSettings.pp.BackBufferWidth = 0; deviceSettings.pp.BackBufferHeight = 0; hr = DXUTChangeDevice( &deviceSettings, NULL, false, bClipWindowToSingleAdapter ); if( FAILED( hr ) ) { SAFE_DELETE( pOldDeviceSettings ); DXUTCleanup3DEnvironment(); DXUTPause( false, false ); GetDXUTState().SetIgnoreSizeChange( false ); return hr; } } } // Make the window visible if( !IsWindowVisible( DXUTGetHWND() ) ) ShowWindow( DXUTGetHWND(), SW_SHOW ); // Ensure that the display doesn't power down when fullscreen but does when windowed if( !DXUTIsWindowed() ) SetThreadExecutionState( ES_DISPLAY_REQUIRED | ES_CONTINUOUS ); else SetThreadExecutionState( ES_CONTINUOUS ); SAFE_DELETE( pOldDeviceSettings ); GetDXUTState().SetIgnoreSizeChange( false ); DXUTPause( false, false ); GetDXUTState().SetDeviceCreated( true ); return S_OK; } //-------------------------------------------------------------------------------------- // Low level keyboard hook to disable Windows key to prevent accidental task switching. //-------------------------------------------------------------------------------------- LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam ) { if (nCode < 0 || nCode != HC_ACTION) // do not process message return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam); bool bEatKeystroke = false; KBDLLHOOKSTRUCT* p = (KBDLLHOOKSTRUCT*)lParam; switch (wParam) { case WM_KEYDOWN: case WM_KEYUP: { bEatKeystroke = ( !GetDXUTState().GetAllowShortcutKeys() && (p->vkCode == VK_LWIN || p->vkCode == VK_RWIN) ); break; } } if( bEatKeystroke ) return 1; else return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam ); } //-------------------------------------------------------------------------------------- // Controls how DXUT behaves when fullscreen and windowed mode with regard to // shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) //-------------------------------------------------------------------------------------- void DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWhenWindowed ) { GetDXUTState().SetAllowShortcutKeysWhenWindowed( bAllowWhenWindowed ); GetDXUTState().SetAllowShortcutKeysWhenFullscreen( bAllowWhenFullscreen ); // DXUTInit() records initial accessibility states so don't change them until then if( GetDXUTState().GetDXUTInited() ) { if( DXUTIsWindowed() ) DXUTAllowShortcutKeys( GetDXUTState().GetAllowShortcutKeysWhenWindowed() ); else DXUTAllowShortcutKeys( GetDXUTState().GetAllowShortcutKeysWhenFullscreen() ); } } //-------------------------------------------------------------------------------------- // Enables/disables Windows keys, and disables or restores the StickyKeys/ToggleKeys/FilterKeys // shortcut to help prevent accidental task switching //-------------------------------------------------------------------------------------- void DXUTAllowShortcutKeys( bool bAllowKeys ) { GetDXUTState().SetAllowShortcutKeys( bAllowKeys ); if( bAllowKeys ) { // Restore StickyKeys/etc to original state and enable Windows key STICKYKEYS sk = GetDXUTState().GetStartupStickyKeys(); TOGGLEKEYS tk = GetDXUTState().GetStartupToggleKeys(); FILTERKEYS fk = GetDXUTState().GetStartupFilterKeys(); SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0); SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0); SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0); // Remove the keyboard hoook when it isn't needed to prevent any slow down of other apps if( GetDXUTState().GetKeyboardHook() ) { UnhookWindowsHookEx( GetDXUTState().GetKeyboardHook() ); GetDXUTState().SetKeyboardHook( NULL ); } } else { // Set low level keyboard hook if haven't already if( GetDXUTState().GetKeyboardHook() == NULL ) { // Set the low-level hook procedure. Only works on Windows 2000 and above OSVERSIONINFO OSVersionInfo; OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo); GetVersionEx(&OSVersionInfo); if( OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && OSVersionInfo.dwMajorVersion > 4 ) { HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), 0 ); GetDXUTState().SetKeyboardHook( hKeyboardHook ); } } // Disable StickyKeys/etc shortcuts but if the accessibility feature is on, // then leave the settings alone as its probably being usefully used STICKYKEYS skOff = GetDXUTState().GetStartupStickyKeys(); if( (skOff.dwFlags & SKF_STICKYKEYSON) == 0 ) { // Disable the hotkey and the confirmation skOff.dwFlags &= ~SKF_HOTKEYACTIVE; skOff.dwFlags &= ~SKF_CONFIRMHOTKEY; SystemParametersInfo(SPI_SETSTICKYKEYS, sizeof(STICKYKEYS), &skOff, 0); } TOGGLEKEYS tkOff = GetDXUTState().GetStartupToggleKeys(); if( (tkOff.dwFlags & TKF_TOGGLEKEYSON) == 0 ) { // Disable the hotkey and the confirmation tkOff.dwFlags &= ~TKF_HOTKEYACTIVE; tkOff.dwFlags &= ~TKF_CONFIRMHOTKEY; SystemParametersInfo(SPI_SETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tkOff, 0); } FILTERKEYS fkOff = GetDXUTState().GetStartupFilterKeys(); if( (fkOff.dwFlags & FKF_FILTERKEYSON) == 0 ) { // Disable the hotkey and the confirmation fkOff.dwFlags &= ~FKF_HOTKEYACTIVE; fkOff.dwFlags &= ~FKF_CONFIRMHOTKEY; SystemParametersInfo(SPI_SETFILTERKEYS, sizeof(FILTERKEYS), &fkOff, 0); } } } //-------------------------------------------------------------------------------------- // Updates the device settings struct based on the cmd line args. //-------------------------------------------------------------------------------------- void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings ) { if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 ) pDeviceSettings->AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); if( GetDXUTState().GetOverrideFullScreen() ) pDeviceSettings->pp.Windowed = false; if( GetDXUTState().GetOverrideWindowed() ) pDeviceSettings->pp.Windowed = true; if( GetDXUTState().GetOverrideForceREF() ) pDeviceSettings->DeviceType = D3DDEVTYPE_REF; else if( GetDXUTState().GetOverrideForceHAL() ) pDeviceSettings->DeviceType = D3DDEVTYPE_HAL; if( GetDXUTState().GetOverrideWidth() != 0 ) pDeviceSettings->pp.BackBufferWidth = GetDXUTState().GetOverrideWidth(); if( GetDXUTState().GetOverrideHeight() != 0 ) pDeviceSettings->pp.BackBufferHeight = GetDXUTState().GetOverrideHeight(); if( GetDXUTState().GetOverrideForcePureHWVP() ) { pDeviceSettings->BehaviorFlags &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING; pDeviceSettings->BehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->BehaviorFlags |= D3DCREATE_PUREDEVICE; } else if( GetDXUTState().GetOverrideForceHWVP() ) { pDeviceSettings->BehaviorFlags &= ~D3DCREATE_SOFTWARE_VERTEXPROCESSING; pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->BehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; } else if( GetDXUTState().GetOverrideForceSWVP() ) { pDeviceSettings->BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } } //-------------------------------------------------------------------------------------- // Creates the 3D environment //-------------------------------------------------------------------------------------- HRESULT DXUTCreate3DEnvironment( IDirect3DDevice9* pd3dDeviceFromApp ) { HRESULT hr = S_OK; IDirect3DDevice9* pd3dDevice = NULL; DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); // Only create a Direct3D device if one hasn't been supplied by the app if( pd3dDeviceFromApp == NULL ) { // Try to create the device with the chosen settings IDirect3D9* pD3D = DXUTGetD3DObject(); hr = pD3D->CreateDevice( pNewDeviceSettings->AdapterOrdinal, pNewDeviceSettings->DeviceType, DXUTGetHWNDFocus(), pNewDeviceSettings->BehaviorFlags, &pNewDeviceSettings->pp, &pd3dDevice ); if( hr == D3DERR_DEVICELOST ) { GetDXUTState().SetDeviceLost( true ); return S_OK; } else if( FAILED(hr) ) { DXUT_ERR( L"CreateDevice", hr ); return DXUTERR_CREATINGDEVICE; } } else { pd3dDeviceFromApp->AddRef(); pd3dDevice = pd3dDeviceFromApp; } GetDXUTState().SetD3DDevice( pd3dDevice ); // If switching to REF, set the exit code to 11. If switching to HAL and exit code was 11, then set it back to 0. if( pNewDeviceSettings->DeviceType == D3DDEVTYPE_REF && GetDXUTState().GetExitCode() == 0 ) GetDXUTState().SetExitCode(11); else if( pNewDeviceSettings->DeviceType == D3DDEVTYPE_HAL && GetDXUTState().GetExitCode() == 11 ) GetDXUTState().SetExitCode(0); // Update back buffer desc before calling app's device callbacks DXUTUpdateBackBufferDesc(); // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) DXUTSetupCursor(); // Update GetDXUTState()'s copy of D3D caps D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); DXUTGetD3DDevice()->GetDeviceCaps( pd3dCaps ); // Update the device stats text CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject(); CD3DEnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->AdapterOrdinal ); DXUTUpdateDeviceStats( pNewDeviceSettings->DeviceType, pNewDeviceSettings->BehaviorFlags, &pAdapterInfo->AdapterIdentifier ); // Call the resource cache created function hr = DXUTGetGlobalResourceCache().OnCreateDevice( pd3dDevice ); if( FAILED(hr) ) return DXUT_ERR( L"OnCreateDevice", ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS ); // Call the app's device created callback if non-NULL const D3DSURFACE_DESC* pbackBufferSurfaceDesc = DXUTGetBackBufferSurfaceDesc(); GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKDEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetDeviceCreatedFunc(); hr = S_OK; if( pCallbackDeviceCreated != NULL ) hr = pCallbackDeviceCreated( DXUTGetD3DDevice(), pbackBufferSurfaceDesc, GetDXUTState().GetDeviceCreatedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); if( DXUTGetD3DDevice() == NULL ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED(hr) ) { DXUT_ERR( L"DeviceCreated callback", hr ); return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS; } GetDXUTState().SetDeviceObjectsCreated( true ); // Call the resource cache device reset function hr = DXUTGetGlobalResourceCache().OnResetDevice( pd3dDevice ); if( FAILED(hr) ) return DXUT_ERR( L"OnResetDevice", DXUTERR_RESETTINGDEVICEOBJECTS ); // Call the app's device reset callback if non-NULL GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKDEVICERESET pCallbackDeviceReset = GetDXUTState().GetDeviceResetFunc(); hr = S_OK; if( pCallbackDeviceReset != NULL ) hr = pCallbackDeviceReset( DXUTGetD3DDevice(), pbackBufferSurfaceDesc, GetDXUTState().GetDeviceResetFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); if( DXUTGetD3DDevice() == NULL ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED(hr) ) { DXUT_ERR( L"DeviceReset callback", hr ); return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_RESETTINGDEVICEOBJECTS; } GetDXUTState().SetDeviceObjectsReset( true ); return S_OK; } //-------------------------------------------------------------------------------------- // Resets the 3D environment by: // - Calls the device lost callback // - Resets the device // - Stores the back buffer description // - Sets up the full screen Direct3D cursor if requested // - Calls the device reset callback //-------------------------------------------------------------------------------------- HRESULT DXUTReset3DEnvironment() { HRESULT hr; IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); assert( pd3dDevice != NULL ); // Call the app's device lost callback if( GetDXUTState().GetDeviceObjectsReset() == true ) { GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKDEVICELOST pCallbackDeviceLost = GetDXUTState().GetDeviceLostFunc(); if( pCallbackDeviceLost != NULL ) pCallbackDeviceLost( GetDXUTState().GetDeviceLostFuncUserContext() ); GetDXUTState().SetDeviceObjectsReset( false ); GetDXUTState().SetInsideDeviceCallback( false ); // Call the resource cache device lost function DXUTGetGlobalResourceCache().OnLostDevice(); } // Reset the device DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); hr = pd3dDevice->Reset( &pDeviceSettings->pp ); if( FAILED(hr) ) { if( hr == D3DERR_DEVICELOST ) return D3DERR_DEVICELOST; // Reset could legitimately fail if the device is lost else return DXUT_ERR( L"Reset", DXUTERR_RESETTINGDEVICE ); } // Update back buffer desc before calling app's device callbacks DXUTUpdateBackBufferDesc(); // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) DXUTSetupCursor(); hr = DXUTGetGlobalResourceCache().OnResetDevice( pd3dDevice ); if( FAILED(hr) ) return DXUT_ERR( L"OnResetDevice", DXUTERR_RESETTINGDEVICEOBJECTS ); // Call the app's OnDeviceReset callback GetDXUTState().SetInsideDeviceCallback( true ); const D3DSURFACE_DESC* pbackBufferSurfaceDesc = DXUTGetBackBufferSurfaceDesc(); LPDXUTCALLBACKDEVICERESET pCallbackDeviceReset = GetDXUTState().GetDeviceResetFunc(); hr = S_OK; if( pCallbackDeviceReset != NULL ) hr = pCallbackDeviceReset( pd3dDevice, pbackBufferSurfaceDesc, GetDXUTState().GetDeviceResetFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); if( FAILED(hr) ) { // If callback failed, cleanup DXUT_ERR( L"DeviceResetCallback", hr ); if( hr != DXUTERR_MEDIANOTFOUND ) hr = DXUTERR_RESETTINGDEVICEOBJECTS; GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKDEVICELOST pCallbackDeviceLost = GetDXUTState().GetDeviceLostFunc(); if( pCallbackDeviceLost != NULL ) pCallbackDeviceLost( GetDXUTState().GetDeviceLostFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); DXUTGetGlobalResourceCache().OnLostDevice(); return hr; } // Success GetDXUTState().SetDeviceObjectsReset( true ); return S_OK; } //-------------------------------------------------------------------------------------- // Pauses time or rendering. Keeps a ref count so pausing can be layered //-------------------------------------------------------------------------------------- void DXUTPause( bool bPauseTime, bool bPauseRendering ) { int nPauseTimeCount = GetDXUTState().GetPauseTimeCount(); nPauseTimeCount += ( bPauseTime ? +1 : -1 ); if( nPauseTimeCount < 0 ) nPauseTimeCount = 0; GetDXUTState().SetPauseTimeCount( nPauseTimeCount ); int nPauseRenderingCount = GetDXUTState().GetPauseRenderingCount(); nPauseRenderingCount += ( bPauseRendering ? +1 : -1 ); if( nPauseRenderingCount < 0 ) nPauseRenderingCount = 0; GetDXUTState().SetPauseRenderingCount( nPauseRenderingCount ); if( nPauseTimeCount > 0 ) { // Stop the scene from animating DXUTGetGlobalTimer()->Stop(); } else { // Restart the timer DXUTGetGlobalTimer()->Start(); } GetDXUTState().SetRenderingPaused( nPauseRenderingCount > 0 ); GetDXUTState().SetTimePaused( nPauseTimeCount > 0 ); } //-------------------------------------------------------------------------------------- // Checks if the window client rect has changed and if it has, then reset the device //-------------------------------------------------------------------------------------- void DXUTCheckForWindowSizeChange() { // Skip the check for various reasons if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || !GetDXUTState().GetCurrentDeviceSettings()->pp.Windowed ) return; RECT rcCurrentClient; GetClientRect( DXUTGetHWND(), &rcCurrentClient ); if( (UINT)rcCurrentClient.right != GetDXUTState().GetCurrentDeviceSettings()->pp.BackBufferWidth || (UINT)rcCurrentClient.bottom != GetDXUTState().GetCurrentDeviceSettings()->pp.BackBufferHeight ) { // A new window size will require a new backbuffer size // size, so the device must be reset and the D3D structures updated accordingly. // Tell DXUTChangeDevice and D3D to size according to the HWND's client rect DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); deviceSettings.pp.BackBufferWidth = 0; deviceSettings.pp.BackBufferHeight = 0; DXUTChangeDevice( &deviceSettings, NULL, false, false ); } } //-------------------------------------------------------------------------------------- // Handles app's message loop and rendering when idle. If DXUTCreateDevice*() or DXUTSetDevice() // has not already been called, it will call DXUTCreateWindow() with the default parameters. //-------------------------------------------------------------------------------------- HRESULT DXUTMainLoop( HACCEL hAccel ) { HRESULT hr; // Not allowed to call this from inside the device callbacks or reenter if( GetDXUTState().GetInsideDeviceCallback() || GetDXUTState().GetInsideMainloop() ) { if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 11) ) GetDXUTState().SetExitCode(1); return DXUT_ERR_MSGBOX( L"DXUTMainLoop", E_FAIL ); } GetDXUTState().SetInsideMainloop( true ); // If DXUTCreateDevice*() or DXUTSetDevice() has not already been called, // then call DXUTCreateDevice() with the default parameters. if( !GetDXUTState().GetDeviceCreated() ) { if( GetDXUTState().GetDeviceCreateCalled() ) { if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 11) ) GetDXUTState().SetExitCode(1); return E_FAIL; // DXUTCreateDevice() must first succeed for this function to succeed } hr = DXUTCreateDevice(); if( FAILED(hr) ) { if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 11) ) GetDXUTState().SetExitCode(1); return hr; } } HWND hWnd = DXUTGetHWND(); // DXUTInit() must have been called and succeeded for this function to proceed // DXUTCreateWindow() or DXUTSetWindow() must have been called and succeeded for this function to proceed // DXUTCreateDevice() or DXUTCreateDeviceFromSettings() or DXUTSetDevice() must have been called and succeeded for this function to proceed if( !GetDXUTState().GetDXUTInited() || !GetDXUTState().GetWindowCreated() || !GetDXUTState().GetDeviceCreated() ) { if( (GetDXUTState().GetExitCode() == 0) || (GetDXUTState().GetExitCode() == 11) ) GetDXUTState().SetExitCode(1); return DXUT_ERR_MSGBOX( L"DXUTMainLoop", E_FAIL ); } // Now we're ready to receive and process Windows messages. bool bGotMsg; MSG msg; msg.message = WM_NULL; PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE ); while( WM_QUIT != msg.message ) { // Use PeekMessage() so we can use idle time to render the scene. bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 ); if( bGotMsg ) { // Translate and dispatch the message if( hAccel == NULL || hWnd == NULL || 0 == TranslateAccelerator( hWnd, hAccel, &msg ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { // Render a frame during idle time (no messages are waiting) DXUTRender3DEnvironment(); } } // Cleanup the accelerator table if( hAccel != NULL ) DestroyAcceleratorTable( hAccel ); GetDXUTState().SetInsideMainloop( false ); return S_OK; } //-------------------------------------------------------------------------------------- // Render the 3D environment by: // - Checking if the device is lost and trying to reset it if it is // - Get the elapsed time since the last frame // - Calling the app's framemove and render callback // - Calling Present() //-------------------------------------------------------------------------------------- void DXUTRender3DEnvironment() { HRESULT hr; if( GetDXUTState().GetDeviceLost() || DXUTIsRenderingPaused() || !DXUTIsActive() ) { // Window is minimized or paused so yield CPU time to other processes Sleep( 50 ); } IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( NULL == pd3dDevice ) { if( GetDXUTState().GetDeviceLost() ) { DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); DXUTChangeDevice( &deviceSettings, NULL, false, true ); } return; } if( GetDXUTState().GetDeviceLost() && !GetDXUTState().GetRenderingPaused() ) { // Test the cooperative level to see if it's okay to render if( FAILED( hr = pd3dDevice->TestCooperativeLevel() ) ) { if( D3DERR_DEVICELOST == hr ) { // The device has been lost but cannot be reset at this time. // So wait until it can be reset. return; } // If we are windowed, read the desktop format and // ensure that the Direct3D device is using the same format // since the user could have changed the desktop bitdepth if( DXUTIsWindowed() ) { D3DDISPLAYMODE adapterDesktopDisplayMode; IDirect3D9* pD3D = DXUTGetD3DObject(); DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); pD3D->GetAdapterDisplayMode( pDeviceSettings->AdapterOrdinal, &adapterDesktopDisplayMode ); if( pDeviceSettings->AdapterFormat != adapterDesktopDisplayMode.Format ) { DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT; matchOptions.eDeviceType = DXUTMT_PRESERVE_INPUT; matchOptions.eWindowed = DXUTMT_PRESERVE_INPUT; matchOptions.eAdapterFormat = DXUTMT_PRESERVE_INPUT; matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT; DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); deviceSettings.AdapterFormat = adapterDesktopDisplayMode.Format; hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); if( FAILED(hr) ) // the call will fail if no valid devices were found { DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); DXUTShutdown(); } // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreate the scene hr = DXUTChangeDevice( &deviceSettings, NULL, false, false ); if( FAILED(hr) ) { // If this fails, try to go fullscreen and if this fails also shutdown. if( FAILED(DXUTToggleFullScreen()) ) DXUTShutdown(); } return; } } // Try to reset the device if( FAILED( hr = DXUTReset3DEnvironment() ) ) { if( D3DERR_DEVICELOST == hr ) { // The device was lost again, so continue waiting until it can be reset. return; } else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr || DXUTERR_MEDIANOTFOUND == hr ) { DXUTDisplayErrorMessage( hr ); DXUTShutdown(); return; } else { // Reset failed, but the device wasn't lost so something bad happened, // so recreate the device to try to recover DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, true, false ) ) ) { DXUTShutdown(); return; } } } } GetDXUTState().SetDeviceLost( false ); } // Get the app's time, in seconds. Skip rendering if no time elapsed double fTime, fAbsTime; float fElapsedTime; DXUTGetGlobalTimer()->GetTimeValues( &fTime, &fAbsTime, &fElapsedTime ); // Store the time for the app if( GetDXUTState().GetConstantFrameTime() ) { fElapsedTime = GetDXUTState().GetTimePerFrame(); fTime = DXUTGetTime() + fElapsedTime; } GetDXUTState().SetTime( fTime ); GetDXUTState().SetAbsoluteTime( fAbsTime ); GetDXUTState().SetElapsedTime( fElapsedTime ); // Update the FPS stats DXUTUpdateFrameStats(); DXUTHandleTimers(); // Animate the scene by calling the app's frame move callback LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc(); if( pCallbackFrameMove != NULL ) { pCallbackFrameMove( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() ); pd3dDevice = DXUTGetD3DDevice(); if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback return; } if( !GetDXUTState().GetRenderingPaused() ) { // Render the scene by calling the app's render callback LPDXUTCALLBACKFRAMERENDER pCallbackFrameRender = GetDXUTState().GetFrameRenderFunc(); if( pCallbackFrameRender != NULL ) { pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetFrameRenderFuncUserContext() ); pd3dDevice = DXUTGetD3DDevice(); if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback return; } #if defined(DEBUG) || defined(_DEBUG) // The back buffer should always match the client rect // if the Direct3D backbuffer covers the entire window RECT rcClient; GetClientRect( DXUTGetHWND(), &rcClient ); if( !IsIconic( DXUTGetHWND() ) ) { GetClientRect( DXUTGetHWND(), &rcClient ); assert( DXUTGetBackBufferSurfaceDesc()->Width == (UINT)rcClient.right ); assert( DXUTGetBackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom ); } #endif // Show the frame on the primary surface. hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); if( FAILED(hr) ) { if( D3DERR_DEVICELOST == hr ) { GetDXUTState().SetDeviceLost( true ); } else if( D3DERR_DRIVERINTERNALERROR == hr ) { // When D3DERR_DRIVERINTERNALERROR is returned from Present(), // the application can do one of the following: // // - End, with the pop-up window saying that the application cannot continue // because of problems in the display adapter and that the user should // contact the adapter manufacturer. // // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message // that the user should contact the adapter manufacturer. // // The framework attempts the path of resetting the device // GetDXUTState().SetDeviceLost( true ); } } } // Update current frame # int nFrame = GetDXUTState().GetCurrentFrameNumber(); nFrame++; GetDXUTState().SetCurrentFrameNumber( nFrame ); // Check to see if the app should shutdown due to cmdline if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 ) { if( nFrame > GetDXUTState().GetOverrideQuitAfterFrame() ) DXUTShutdown(); } return; } //-------------------------------------------------------------------------------------- // Updates the string which describes the device //-------------------------------------------------------------------------------------- void DXUTUpdateDeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ) { if( GetDXUTState().GetNoStats() ) return; // Store device description WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats(); if( DeviceType == D3DDEVTYPE_REF ) StringCchCopy( pstrDeviceStats, 256, L"REF" ); else if( DeviceType == D3DDEVTYPE_HAL ) StringCchCopy( pstrDeviceStats, 256, L"HAL" ); else if( DeviceType == D3DDEVTYPE_SW ) StringCchCopy( pstrDeviceStats, 256, L"SW" ); if( BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING && BehaviorFlags & D3DCREATE_PUREDEVICE ) { if( DeviceType == D3DDEVTYPE_HAL ) StringCchCat( pstrDeviceStats, 256, L" (pure hw vp)" ); else StringCchCat( pstrDeviceStats, 256, L" (simulated pure hw vp)" ); } else if( BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) { if( DeviceType == D3DDEVTYPE_HAL ) StringCchCat( pstrDeviceStats, 256, L" (hw vp)" ); else StringCchCat( pstrDeviceStats, 256, L" (simulated hw vp)" ); } else if( BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) { if( DeviceType == D3DDEVTYPE_HAL ) StringCchCat( pstrDeviceStats, 256, L" (mixed vp)" ); else StringCchCat( pstrDeviceStats, 256, L" (simulated mixed vp)" ); } else if( BehaviorFlags & D3DCREATE_SOFTWARE_VERTEXPROCESSING ) { StringCchCat( pstrDeviceStats, 256, L" (sw vp)" ); } if( DeviceType == D3DDEVTYPE_HAL ) { // Be sure not to overflow m_strDeviceStats when appending the adapter // description, since it can be long. StringCchCat( pstrDeviceStats, 256, L": " ); // Try to get a unique description from the CD3DEnumDeviceSettingsCombo DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject(); CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->DeviceType, pDeviceSettings->AdapterFormat, pDeviceSettings->pp.BackBufferFormat, pDeviceSettings->pp.Windowed ); if( pDeviceSettingsCombo ) { StringCchCat( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription ); } else { const int cchDesc = sizeof(pAdapterIdentifier->Description); WCHAR szDescription[cchDesc]; MultiByteToWideChar( CP_ACP, 0, pAdapterIdentifier->Description, -1, szDescription, cchDesc ); szDescription[cchDesc-1] = 0; StringCchCat( pstrDeviceStats, 256, szDescription ); } } } //-------------------------------------------------------------------------------------- // Updates the frames/sec stat once per second //-------------------------------------------------------------------------------------- void DXUTUpdateFrameStats() { if( GetDXUTState().GetNoStats() ) return; // Keep track of the frame count double fLastTime = GetDXUTState().GetLastStatsUpdateTime(); DWORD dwFrames = GetDXUTState().GetLastStatsUpdateFrames(); double fAbsTime = GetDXUTState().GetAbsoluteTime(); dwFrames++; GetDXUTState().SetLastStatsUpdateFrames( dwFrames ); // Update the scene stats once per second if( fAbsTime - fLastTime > 1.0f ) { float fFPS = (float) (dwFrames / (fAbsTime - fLastTime)); GetDXUTState().SetFPS( fFPS ); GetDXUTState().SetLastStatsUpdateTime( fAbsTime ); GetDXUTState().SetLastStatsUpdateFrames( 0 ); WCHAR* pstrFPS = GetDXUTState().GetFPSStats(); StringCchPrintf( pstrFPS, 64, L"%0.2f fps ", fFPS ); } } //-------------------------------------------------------------------------------------- // Updates the static part of the frame stats so it doesn't have be generated every frame //-------------------------------------------------------------------------------------- void DXUTUpdateStaticFrameStats() { if( GetDXUTState().GetNoStats() ) return; DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( NULL == pDeviceSettings ) return; CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject(); if( NULL == pd3dEnum ) return; CD3DEnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->DeviceType, pDeviceSettings->AdapterFormat, pDeviceSettings->pp.BackBufferFormat, pDeviceSettings->pp.Windowed ); if( NULL == pDeviceSettingsCombo ) return; WCHAR strFmt[100]; D3DPRESENT_PARAMETERS* pPP = &pDeviceSettings->pp; if( pDeviceSettingsCombo->AdapterFormat == pDeviceSettingsCombo->BackBufferFormat ) { StringCchCopy( strFmt, 100, DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); } else { StringCchPrintf( strFmt, 100, L"backbuf %s, adapter %s", DXUTD3DFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ), DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); } WCHAR strDepthFmt[100]; if( pPP->EnableAutoDepthStencil ) { StringCchPrintf( strDepthFmt, 100, L" (%s)", DXUTD3DFormatToString( pPP->AutoDepthStencilFormat, false ) ); } else { // No depth buffer strDepthFmt[0] = 0; } WCHAR strMultiSample[100]; switch( pPP->MultiSampleType ) { case D3DMULTISAMPLE_NONMASKABLE: StringCchCopy( strMultiSample, 100, L" (Nonmaskable Multisample)" ); break; case D3DMULTISAMPLE_NONE: StringCchCopy( strMultiSample, 100, L"" ); break; default: StringCchPrintf( strMultiSample, 100, L" (%dx Multisample)", pPP->MultiSampleType ); break; } WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); StringCchPrintf( pstrStaticFrameStats, 256, L"%%sVsync %s (%dx%d), %s%s%s", ( pPP->PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ) ? L"off" : L"on", pPP->BackBufferWidth, pPP->BackBufferHeight, strFmt, strDepthFmt, strMultiSample ); } //-------------------------------------------------------------------------------------- LPCWSTR DXUTGetFrameStats( bool bShowFPS ) { WCHAR* pstrFrameStats = GetDXUTState().GetFrameStats(); WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L""; StringCchPrintf( pstrFrameStats, 256, GetDXUTState().GetStaticFrameStats(), pstrFPS ); return pstrFrameStats; } //-------------------------------------------------------------------------------------- // Handles window messages //-------------------------------------------------------------------------------------- LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // Consolidate the keyboard messages and pass them to the app's keyboard callback if( uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN || uMsg == WM_KEYUP || uMsg == WM_SYSKEYUP ) { bool bKeyDown = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN); DWORD dwMask = (1 << 29); bool bAltDown = ( (lParam & dwMask) != 0 ); bool* bKeys = GetDXUTState().GetKeys(); bKeys[ (BYTE) (wParam & 0xFF) ] = bKeyDown; LPDXUTCALLBACKKEYBOARD pCallbackKeyboard = GetDXUTState().GetKeyboardFunc(); if( pCallbackKeyboard ) pCallbackKeyboard( (UINT)wParam, bKeyDown, bAltDown, GetDXUTState().GetKeyboardFuncUserContext() ); } // Consolidate the mouse button messages and pass them to the app's mouse callback if( uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK || uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK || uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK || uMsg == WM_XBUTTONDOWN || uMsg == WM_XBUTTONUP || uMsg == WM_XBUTTONDBLCLK || uMsg == WM_MOUSEWHEEL || (GetDXUTState().GetNotifyOnMouseMove() && uMsg == WM_MOUSEMOVE) ) { int xPos = (short)LOWORD(lParam); int yPos = (short)HIWORD(lParam); if( uMsg == WM_MOUSEWHEEL ) { // WM_MOUSEWHEEL passes screen mouse coords // so convert them to client coords POINT pt; pt.x = xPos; pt.y = yPos; ScreenToClient( hWnd, &pt ); xPos = pt.x; yPos = pt.y; } int nMouseWheelDelta = 0; if( uMsg == WM_MOUSEWHEEL ) nMouseWheelDelta = (short) HIWORD(wParam); int nMouseButtonState = LOWORD(wParam); bool bLeftButton = ((nMouseButtonState & MK_LBUTTON) != 0); bool bRightButton = ((nMouseButtonState & MK_RBUTTON) != 0); bool bMiddleButton = ((nMouseButtonState & MK_MBUTTON) != 0); bool bSideButton1 = ((nMouseButtonState & MK_XBUTTON1) != 0); bool bSideButton2 = ((nMouseButtonState & MK_XBUTTON2) != 0); bool* bMouseButtons = GetDXUTState().GetMouseButtons(); bMouseButtons[0] = bLeftButton; bMouseButtons[1] = bMiddleButton; bMouseButtons[2] = bRightButton; bMouseButtons[3] = bSideButton1; bMouseButtons[4] = bSideButton2; LPDXUTCALLBACKMOUSE pCallbackMouse = GetDXUTState().GetMouseFunc(); if( pCallbackMouse ) pCallbackMouse( bLeftButton, bRightButton, bMiddleButton, bSideButton1, bSideButton2, nMouseWheelDelta, xPos, yPos, GetDXUTState().GetMouseFuncUserContext() ); } // Pass all messages to the app's MsgProc callback, and don't // process further messages if the apps says not to. LPDXUTCALLBACKMSGPROC pCallbackMsgProc = GetDXUTState().GetWindowMsgFunc(); if( pCallbackMsgProc ) { bool bNoFurtherProcessing = false; LRESULT nResult = pCallbackMsgProc( hWnd, uMsg, wParam, lParam, &bNoFurtherProcessing, GetDXUTState().GetWindowMsgFuncUserContext() ); if( bNoFurtherProcessing ) return nResult; } switch( uMsg ) { case WM_PAINT: { IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); // Handle paint messages when the app is paused if( pd3dDevice && DXUTIsRenderingPaused() && GetDXUTState().GetDeviceObjectsCreated() && GetDXUTState().GetDeviceObjectsReset() ) { HRESULT hr; double fTime = DXUTGetTime(); float fElapsedTime = DXUTGetElapsedTime(); LPDXUTCALLBACKFRAMERENDER pCallbackFrameRender = GetDXUTState().GetFrameRenderFunc(); if( pCallbackFrameRender != NULL ) pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, GetDXUTState().GetFrameRenderFuncUserContext() ); hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); if( D3DERR_DEVICELOST == hr ) { GetDXUTState().SetDeviceLost( true ); } else if( D3DERR_DRIVERINTERNALERROR == hr ) { // When D3DERR_DRIVERINTERNALERROR is returned from Present(), // the application can do one of the following: // // - End, with the pop-up window saying that the application cannot continue // because of problems in the display adapter and that the user should // contact the adapter manufacturer. // // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message // that the user should contact the adapter manufacturer. // // The framework attempts the path of resetting the device // GetDXUTState().SetDeviceLost( true ); } } break; } case WM_SIZE: if( SIZE_MINIMIZED == wParam ) { DXUTPause( true, true ); // Pause while we're minimized GetDXUTState().SetMinimized( true ); GetDXUTState().SetMaximized( false ); } else { RECT rcCurrentClient; GetClientRect( DXUTGetHWND(), &rcCurrentClient ); if( rcCurrentClient.top == 0 && rcCurrentClient.bottom == 0 ) { // Rapidly clicking the task bar to minimize and restore a window // can cause a WM_SIZE message with SIZE_RESTORED when // the window has actually become minimized due to rapid change // so just ignore this message } else if( SIZE_MAXIMIZED == wParam ) { if( GetDXUTState().GetMinimized() ) DXUTPause( false, false ); // Unpause since we're no longer minimized GetDXUTState().SetMinimized( false ); GetDXUTState().SetMaximized( true ); DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); } else if( SIZE_RESTORED == wParam ) { if( GetDXUTState().GetMaximized() ) { GetDXUTState().SetMaximized( false ); DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); } else if( GetDXUTState().GetMinimized() ) { DXUTPause( false, false ); // Unpause since we're no longer minimized GetDXUTState().SetMinimized( false ); DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); } else if( GetDXUTState().GetInSizeMove() ) { // If we're neither maximized nor minimized, the window size // is changing by the user dragging the window edges. In this // case, we don't reset the device yet -- we wait until the // user stops dragging, and a WM_EXITSIZEMOVE message comes. } else { // This WM_SIZE come from resizing the window via an API like SetWindowPos() so // resize and reset the device now. DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); } } } break; case WM_GETMINMAXINFO: ((MINMAXINFO*)lParam)->ptMinTrackSize.x = DXUT_MIN_WINDOW_SIZE_X; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = DXUT_MIN_WINDOW_SIZE_Y; break; case WM_ENTERSIZEMOVE: // Halt frame movement while the app is sizing or moving DXUTPause( true, true ); GetDXUTState().SetInSizeMove( true ); break; case WM_EXITSIZEMOVE: DXUTPause( false, false ); DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); GetDXUTState().SetInSizeMove( false ); break; case WM_MOUSEMOVE: if( DXUTIsActive() && !DXUTIsWindowed() ) { IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( pd3dDevice ) { POINT ptCursor; GetCursorPos( &ptCursor ); pd3dDevice->SetCursorPosition( ptCursor.x, ptCursor.y, 0 ); } } break; case WM_SETCURSOR: if( DXUTIsActive() && !DXUTIsWindowed() ) { IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( pd3dDevice && GetDXUTState().GetShowCursorWhenFullScreen() ) pd3dDevice->ShowCursor( true ); return true; // prevent Windows from setting cursor to window class cursor } break; case WM_ACTIVATEAPP: if( wParam == TRUE && !DXUTIsActive() ) // Handle only if previously not active { GetDXUTState().SetActive( true ); // Disable any controller rumble & input when de-activating app DXUTEnableXInput( true ); // The GetMinimizedWhileFullscreen() varible is used instead of !DXUTIsWindowed() // to handle the rare case toggling to windowed mode while the fullscreen application // is minimized and thus making the pause count wrong if( GetDXUTState().GetMinimizedWhileFullscreen() ) { DXUTPause( false, false ); // Unpause since we're no longer minimized GetDXUTState().SetMinimizedWhileFullscreen( false ); } // Upon returning to this app, potentially disable shortcut keys // (Windows key, accessibility shortcuts) DXUTAllowShortcutKeys( ( DXUTIsWindowed() ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() : GetDXUTState().GetAllowShortcutKeysWhenFullscreen() ); } else if( wParam == FALSE && DXUTIsActive() ) // Handle only if previously active { GetDXUTState().SetActive( false ); // Disable any controller rumble & input when de-activating app DXUTEnableXInput( false ); if( !DXUTIsWindowed() ) { // Going from full screen to a minimized state ClipCursor( NULL ); // don't limit the cursor anymore DXUTPause( true, true ); // Pause while we're minimized (take care not to pause twice by handling this message twice) GetDXUTState().SetMinimizedWhileFullscreen( true ); } // Restore shortcut keys (Windows key, accessibility shortcuts) to original state // // This is important to call here if the shortcuts are disabled, // because if this is not done then the Windows key will continue to // be disabled while this app is running which is very bad. // If the app crashes, the Windows key will return to normal. DXUTAllowShortcutKeys( true ); } break; case WM_ENTERMENULOOP: // Pause the app when menus are displayed DXUTPause( true, true ); break; case WM_EXITMENULOOP: DXUTPause( false, false ); break; case WM_MENUCHAR: // A menu is active and the user presses a key that does not correspond to any mnemonic or accelerator key // So just ignore and don't beep return MAKELRESULT(0,MNC_CLOSE); break; case WM_NCHITTEST: // Prevent the user from selecting the menu in full screen mode if( !DXUTIsWindowed() ) return HTCLIENT; break; case WM_POWERBROADCAST: switch( wParam ) { #ifndef PBT_APMQUERYSUSPEND #define PBT_APMQUERYSUSPEND 0x0000 #endif case PBT_APMQUERYSUSPEND: // At this point, the app should save any data for open // network connections, files, etc., and prepare to go into // a suspended mode. The app can use the MsgProc callback // to handle this if desired. return true; #ifndef PBT_APMRESUMESUSPEND #define PBT_APMRESUMESUSPEND 0x0007 #endif case PBT_APMRESUMESUSPEND: // At this point, the app should recover any data, network // connections, files, etc., and resume running from when // the app was suspended. The app can use the MsgProc callback // to handle this if desired. // QPC may lose consistency when suspending, so reset the timer // upon resume. DXUTGetGlobalTimer()->Reset(); GetDXUTState().SetLastStatsUpdateTime( 0 ); return true; } break; case WM_SYSCOMMAND: // Prevent moving/sizing in full screen mode switch( (wParam & 0xFFF0) ) { case SC_MOVE: case SC_SIZE: case SC_MAXIMIZE: case SC_KEYMENU: if( !DXUTIsWindowed() ) return 0; break; } break; case WM_SYSKEYDOWN: { switch( wParam ) { case VK_RETURN: { if( GetDXUTState().GetHandleAltEnter() ) { // Toggle full screen upon alt-enter DWORD dwMask = (1 << 29); if( (lParam & dwMask) != 0 ) // Alt is down also { // Toggle the full screen/window mode DXUTPause( true, true ); DXUTToggleFullScreen(); DXUTPause( false, false ); return 0; } } } } break; } case WM_KEYDOWN: { if( GetDXUTState().GetHandleDefaultHotkeys() ) { switch( wParam ) { case VK_F3: { DXUTPause( true, true ); DXUTToggleREF(); DXUTPause( false, false ); break; } case VK_F8: { bool bWireFrame = GetDXUTState().GetWireframeMode(); bWireFrame = !bWireFrame; GetDXUTState().SetWireframeMode( bWireFrame ); IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( pd3dDevice ) pd3dDevice->SetRenderState( D3DRS_FILLMODE, (bWireFrame) ? D3DFILL_WIREFRAME : D3DFILL_SOLID ); break; } case VK_ESCAPE: { // Received key to exit app SendMessage( hWnd, WM_CLOSE, 0, 0 ); } case VK_PAUSE: { bool bTimePaused = DXUTIsTimePaused(); bTimePaused = !bTimePaused; if( bTimePaused ) DXUTPause( true, false ); else DXUTPause( false, false ); break; } } } break; } case WM_CLOSE: { HMENU hMenu; hMenu = GetMenu(hWnd); if( hMenu != NULL ) DestroyMenu( hMenu ); DestroyWindow( hWnd ); UnregisterClass( L"Direct3DWindowClass", GetDXUTState().GetHInstance() ); GetDXUTState().SetHWNDFocus( NULL ); GetDXUTState().SetHWNDDeviceFullScreen( NULL ); GetDXUTState().SetHWNDDeviceWindowed( NULL ); return 0; } case WM_DESTROY: PostQuitMessage(0); break; } // Don't allow the F10 key to act as a shortcut to the menu bar // by not passing these messages to the DefWindowProc only when // there's no menu present if( !GetDXUTState().GetCallDefWindowProc() || GetDXUTState().GetMenu() == NULL && (uMsg == WM_SYSKEYDOWN || uMsg == WM_SYSKEYUP) && wParam == VK_F10 ) return 0; else return DefWindowProc( hWnd, uMsg, wParam, lParam ); } //-------------------------------------------------------------------------------------- // Resets the state associated with DXUT //-------------------------------------------------------------------------------------- void DXUTResetFrameworkState() { GetDXUTState().Destroy(); GetDXUTState().Create(); } //-------------------------------------------------------------------------------------- // Closes down the window. When the window closes, it will cleanup everything //-------------------------------------------------------------------------------------- void DXUTShutdown( int nExitCode ) { HWND hWnd = DXUTGetHWND(); if( hWnd != NULL ) SendMessage( hWnd, WM_CLOSE, 0, 0 ); GetDXUTState().SetExitCode(nExitCode); DXUTCleanup3DEnvironment( true ); // Restore shortcut keys (Windows key, accessibility shortcuts) to original state // This is important to call here if the shortcuts are disabled, // because accessibility setting changes are permanent. // This means that if this is not done then the accessibility settings // might not be the same as when the app was started. // If the app crashes without restoring the settings, this is also true so it // would be wise to backup/restore the settings from a file so they can be // restored when the crashed app is run again. DXUTAllowShortcutKeys( true ); GetDXUTState().SetD3DEnumeration( NULL ); IDirect3D9* pD3D = DXUTGetD3DObject(); SAFE_RELEASE( pD3D ); GetDXUTState().SetD3D( NULL ); if( GetDXUTState().GetOverrideRelaunchMCE() ) DXUTReLaunchMediaCenter(); } //-------------------------------------------------------------------------------------- // Cleans up the 3D environment by: // - Calls the device lost callback // - Calls the device destroyed callback // - Releases the D3D device //-------------------------------------------------------------------------------------- void DXUTCleanup3DEnvironment( bool bReleaseSettings ) { IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( pd3dDevice != NULL ) { GetDXUTState().SetInsideDeviceCallback( true ); // Call the app's device lost callback if( GetDXUTState().GetDeviceObjectsReset() == true ) { LPDXUTCALLBACKDEVICELOST pCallbackDeviceLost = GetDXUTState().GetDeviceLostFunc(); if( pCallbackDeviceLost != NULL ) pCallbackDeviceLost( GetDXUTState().GetDeviceLostFuncUserContext() ); GetDXUTState().SetDeviceObjectsReset( false ); // Call the resource cache device lost function DXUTGetGlobalResourceCache().OnLostDevice(); } // Call the app's device destroyed callback if( GetDXUTState().GetDeviceObjectsCreated() == true ) { LPDXUTCALLBACKDEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetDeviceDestroyedFunc(); if( pCallbackDeviceDestroyed != NULL ) pCallbackDeviceDestroyed( GetDXUTState().GetDeviceDestroyedFuncUserContext() ); GetDXUTState().SetDeviceObjectsCreated( false ); // Call the resource cache device destory function DXUTGetGlobalResourceCache().OnDestroyDevice(); } GetDXUTState().SetInsideDeviceCallback( false ); // Release the D3D device and in debug configs, displays a message box if there // are unrelease objects. if( pd3dDevice ) { if( pd3dDevice->Release() > 0 ) { DXUTDisplayErrorMessage( DXUTERR_NONZEROREFCOUNT ); DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT ); } } GetDXUTState().SetD3DDevice( NULL ); if( bReleaseSettings ) { DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); SAFE_DELETE(pOldDeviceSettings); GetDXUTState().SetCurrentDeviceSettings( NULL ); } D3DSURFACE_DESC* pbackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc(); ZeroMemory( pbackBufferSurfaceDesc, sizeof(D3DSURFACE_DESC) ); D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); ZeroMemory( pd3dCaps, sizeof(D3DCAPS9) ); GetDXUTState().SetDeviceCreated( false ); } } //-------------------------------------------------------------------------------------- // Stores back buffer surface desc in GetDXUTState().GetBackBufferSurfaceDesc() //-------------------------------------------------------------------------------------- void DXUTUpdateBackBufferDesc() { HRESULT hr; IDirect3DSurface9* pBackBuffer; hr = GetDXUTState().GetD3DDevice()->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); D3DSURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc(); ZeroMemory( pBBufferSurfaceDesc, sizeof(D3DSURFACE_DESC) ); if( SUCCEEDED(hr) ) { pBackBuffer->GetDesc( pBBufferSurfaceDesc ); SAFE_RELEASE( pBackBuffer ); } } //-------------------------------------------------------------------------------------- // Starts a user defined timer callback //-------------------------------------------------------------------------------------- HRESULT DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs, UINT* pnIDEvent, void* pCallbackUserContext ) { if( pCallbackTimer == NULL ) return DXUT_ERR_MSGBOX( L"DXUTSetTimer", E_INVALIDARG ); HRESULT hr; DXUT_TIMER DXUTTimer; DXUTTimer.pCallbackTimer = pCallbackTimer; DXUTTimer.pCallbackUserContext = pCallbackUserContext; DXUTTimer.fTimeoutInSecs = fTimeoutInSecs; DXUTTimer.fCountdown = fTimeoutInSecs; DXUTTimer.bEnabled = true; DXUTTimer.nID = GetDXUTState().GetTimerLastID() + 1; GetDXUTState().SetTimerLastID( DXUTTimer.nID ); CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); if( pTimerList == NULL ) { pTimerList = new CGrowableArray<DXUT_TIMER>; if( pTimerList == NULL ) return E_OUTOFMEMORY; GetDXUTState().SetTimerList( pTimerList ); } if( FAILED( hr = pTimerList->Add( DXUTTimer ) ) ) return hr; if( pnIDEvent ) *pnIDEvent = DXUTTimer.nID; return S_OK; } //-------------------------------------------------------------------------------------- // Stops a user defined timer callback //-------------------------------------------------------------------------------------- HRESULT DXUTKillTimer( UINT nIDEvent ) { CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); if( pTimerList == NULL ) return S_FALSE; bool bFound = false; for( int i=0; i<pTimerList->GetSize(); i++ ) { DXUT_TIMER DXUTTimer = pTimerList->GetAt(i); if( DXUTTimer.nID == nIDEvent ) { DXUTTimer.bEnabled = false; pTimerList->SetAt(i, DXUTTimer); bFound = true; break; } } if( !bFound ) return DXUT_ERR_MSGBOX( L"DXUTKillTimer", E_INVALIDARG ); return S_OK; } //-------------------------------------------------------------------------------------- // Internal helper function to handle calling the user defined timer callbacks //-------------------------------------------------------------------------------------- void DXUTHandleTimers() { float fElapsedTime = DXUTGetElapsedTime(); CGrowableArray<DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); if( pTimerList == NULL ) return; // Walk through the list of timer callbacks for( int i=0; i<pTimerList->GetSize(); i++ ) { DXUT_TIMER DXUTTimer = pTimerList->GetAt(i); if( DXUTTimer.bEnabled ) { DXUTTimer.fCountdown -= fElapsedTime; // Call the callback if count down expired if( DXUTTimer.fCountdown < 0 ) { DXUTTimer.pCallbackTimer( i, DXUTTimer.pCallbackUserContext ); DXUTTimer.fCountdown = DXUTTimer.fTimeoutInSecs; } pTimerList->SetAt(i, DXUTTimer); } } } //-------------------------------------------------------------------------------------- // External state access functions //-------------------------------------------------------------------------------------- IDirect3D9* DXUTGetD3DObject() { return GetDXUTState().GetD3D(); } IDirect3DDevice9* DXUTGetD3DDevice() { return GetDXUTState().GetD3DDevice(); } const D3DSURFACE_DESC* DXUTGetBackBufferSurfaceDesc() { return GetDXUTState().GetBackBufferSurfaceDesc(); } const D3DCAPS9* DXUTGetDeviceCaps() { return GetDXUTState().GetCaps(); } HINSTANCE DXUTGetHINSTANCE() { return GetDXUTState().GetHInstance(); } HWND DXUTGetHWND() { return DXUTIsWindowed() ? GetDXUTState().GetHWNDDeviceWindowed() : GetDXUTState().GetHWNDDeviceFullScreen(); } HWND DXUTGetHWNDFocus() { return GetDXUTState().GetHWNDFocus(); } HWND DXUTGetHWNDDeviceFullScreen() { return GetDXUTState().GetHWNDDeviceFullScreen(); } HWND DXUTGetHWNDDeviceWindowed() { return GetDXUTState().GetHWNDDeviceWindowed(); } RECT DXUTGetWindowClientRect() { RECT rc; GetClientRect( DXUTGetHWND(), &rc ); return rc; } RECT DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetWindowBackBufferWidthAtModeChange(), GetDXUTState().GetWindowBackBufferHeightAtModeChange() }; return rc; } RECT DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(), GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() }; return rc; } double DXUTGetTime() { return GetDXUTState().GetTime(); } float DXUTGetElapsedTime() { return GetDXUTState().GetElapsedTime(); } float DXUTGetFPS() { return GetDXUTState().GetFPS(); } LPCWSTR DXUTGetWindowTitle() { return GetDXUTState().GetWindowTitle(); } LPCWSTR DXUTGetDeviceStats() { return GetDXUTState().GetDeviceStats(); } bool DXUTIsRenderingPaused() { return GetDXUTState().GetPauseRenderingCount() > 0; } bool DXUTIsTimePaused() { return GetDXUTState().GetPauseTimeCount() > 0; } bool DXUTIsActive() { return GetDXUTState().GetActive(); } int DXUTGetExitCode() { return GetDXUTState().GetExitCode(); } bool DXUTGetShowMsgBoxOnError() { return GetDXUTState().GetShowMsgBoxOnError(); } bool DXUTGetAutomation() { return GetDXUTState().GetAutomation(); } bool DXUTGetHandleDefaultHotkeys() { return GetDXUTState().GetHandleDefaultHotkeys(); } bool DXUTIsKeyDown( BYTE vKey ) { bool* bKeys = GetDXUTState().GetKeys(); if( vKey >= 0xA0 && vKey <= 0xA5 ) // VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU return GetAsyncKeyState( vKey ) != 0; // these keys only are tracked via GetAsyncKeyState() else if( vKey >= 0x01 && vKey <= 0x06 && vKey != 0x03 ) // mouse buttons (VK_*BUTTON) return DXUTIsMouseButtonDown(vKey); else return bKeys[vKey]; } bool DXUTIsMouseButtonDown( BYTE vButton ) { bool* bMouseButtons = GetDXUTState().GetMouseButtons(); int nIndex = DXUTMapButtonToArrayIndex(vButton); return bMouseButtons[nIndex]; } void DXUTSetMultimonSettings( bool bAutoChangeAdapter ) { GetDXUTState().SetAutoChangeAdapter( bAutoChangeAdapter ); } void DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCursorWhenFullScreen ) { GetDXUTState().SetClipCursorWhenFullScreen(bClipCursorWhenFullScreen); GetDXUTState().SetShowCursorWhenFullScreen(bShowCursorWhenFullScreen); DXUTSetupCursor(); } void DXUTSetWindowSettings( bool bCallDefWindowProc ) { GetDXUTState().SetCallDefWindowProc( bCallDefWindowProc ); } void DXUTSetConstantFrameTime( bool bEnabled, float fTimePerFrame ) { if( GetDXUTState().GetOverrideConstantFrameTime() ) { bEnabled = GetDXUTState().GetOverrideConstantFrameTime(); fTimePerFrame = GetDXUTState().GetOverrideConstantTimePerFrame(); } GetDXUTState().SetConstantFrameTime(bEnabled); GetDXUTState().SetTimePerFrame(fTimePerFrame); } //-------------------------------------------------------------------------------------- // Return if windowed in the current device. If no device exists yet, then returns false //-------------------------------------------------------------------------------------- bool DXUTIsWindowed() { DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if(pDeviceSettings) return (pDeviceSettings->pp.Windowed != 0); else return false; } //-------------------------------------------------------------------------------------- // Return the present params of the current device. If no device exists yet, then // return blank present params //-------------------------------------------------------------------------------------- D3DPRESENT_PARAMETERS DXUTGetPresentParameters() { DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { return pDS->pp; } else { D3DPRESENT_PARAMETERS pp; ZeroMemory( &pp, sizeof(D3DPRESENT_PARAMETERS) ); return pp; } } //-------------------------------------------------------------------------------------- // Return the device settings of the current device. If no device exists yet, then // return blank device settings //-------------------------------------------------------------------------------------- DXUTDeviceSettings DXUTGetDeviceSettings() { DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { return *pDS; } else { DXUTDeviceSettings ds; ZeroMemory( &ds, sizeof(DXUTDeviceSettings) ); return ds; } } #ifndef SM_REMOTESESSION // needs WINVER >= 0x0500 #define SM_REMOTESESSION 0x1000 #endif //-------------------------------------------------------------------------------------- // Display an custom error msg box //-------------------------------------------------------------------------------------- void DXUTDisplayErrorMessage( HRESULT hr ) { WCHAR strBuffer[512]; int nExitCode; bool bFound = true; switch( hr ) { case DXUTERR_NODIRECT3D: nExitCode = 2; StringCchCopy( strBuffer, 512, L"Could not initialize Direct3D. You may want to check that the latest version of DirectX is correctly installed on your system. Also make sure that this program was compiled with header files that match the installed DirectX DLLs." ); break; case DXUTERR_INCORRECTVERSION: nExitCode = 10; StringCchCopy( strBuffer, 512, L"Incorrect version of Direct3D and/or D3DX." ); break; case DXUTERR_MEDIANOTFOUND: nExitCode = 4; StringCchCopy( strBuffer, 512, L"Could not find required media. Ensure that the DirectX SDK is correctly installed." ); break; case DXUTERR_NONZEROREFCOUNT: nExitCode = 5; StringCchCopy( strBuffer, 512, L"The D3D device has a non-zero reference count, meaning some objects were not released." ); break; case DXUTERR_CREATINGDEVICE: nExitCode = 6; StringCchCopy( strBuffer, 512, L"Failed creating the Direct3D device." ); break; case DXUTERR_RESETTINGDEVICE: nExitCode = 7; StringCchCopy( strBuffer, 512, L"Failed resetting the Direct3D device." ); break; case DXUTERR_CREATINGDEVICEOBJECTS: nExitCode = 8; StringCchCopy( strBuffer, 512, L"Failed creating Direct3D device objects." ); break; case DXUTERR_RESETTINGDEVICEOBJECTS: nExitCode = 9; StringCchCopy( strBuffer, 512, L"Failed resetting Direct3D device objects." ); break; case DXUTERR_NOCOMPATIBLEDEVICES: nExitCode = 3; if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) StringCchCopy( strBuffer, 512, L"Direct3D does not work over a remote session." ); else StringCchCopy( strBuffer, 512, L"Could not find any compatible Direct3D devices." ); break; default: bFound = false; nExitCode = 1;break; } GetDXUTState().SetExitCode(nExitCode); bool bShowMsgBoxOnError = GetDXUTState().GetShowMsgBoxOnError(); if( bFound && bShowMsgBoxOnError ) { if( DXUTGetWindowTitle()[0] == 0 ) MessageBox( DXUTGetHWND(), strBuffer, L"DirectX Application", MB_ICONERROR|MB_OK ); else MessageBox( DXUTGetHWND(), strBuffer, DXUTGetWindowTitle(), MB_ICONERROR|MB_OK ); } } //-------------------------------------------------------------------------------------- // Display error msg box to help debug //-------------------------------------------------------------------------------------- HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox ) { bool bShowMsgBoxOnError = GetDXUTState().GetShowMsgBoxOnError(); if( bPopMsgBox && bShowMsgBoxOnError == false ) bPopMsgBox = false; return DXTrace( strFile, dwLine, hr, strMsg, bPopMsgBox ); } //-------------------------------------------------------------------------------------- // Checks to see if the HWND changed monitors, and if it did it creates a device // from the monitor's adapter and recreates the scene. //-------------------------------------------------------------------------------------- void DXUTCheckForWindowChangingMonitors() { // Skip this check for various reasons if( !GetDXUTState().GetAutoChangeAdapter() || GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || !GetDXUTState().GetCurrentDeviceSettings()->pp.Windowed ) { return; } HRESULT hr; HMONITOR hWindowMonitor = DXUTMonitorFromWindow( DXUTGetHWND(), MONITOR_DEFAULTTOPRIMARY ); HMONITOR hAdapterMonitor = GetDXUTState().GetAdapterMonitor(); if( hWindowMonitor != hAdapterMonitor ) { UINT newOrdinal; if( SUCCEEDED( DXUTGetAdapterOrdinalFromMonitor( hWindowMonitor, &newOrdinal ) ) ) { // Find the closest valid device settings with the new ordinal DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); deviceSettings.AdapterOrdinal = newOrdinal; DXUTMatchOptions matchOptions; matchOptions.eAdapterOrdinal = DXUTMT_PRESERVE_INPUT; matchOptions.eDeviceType = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eWindowed = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eAdapterFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eVertexProcessing = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eBackBufferCount = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eMultiSample = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eSwapEffect = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eDepthFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eStencilFormat = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentFlags = DXUTMT_CLOSEST_TO_INPUT; matchOptions.eRefreshRate = DXUTMT_CLOSEST_TO_INPUT; matchOptions.ePresentInterval = DXUTMT_CLOSEST_TO_INPUT; hr = DXUTFindValidDeviceSettings( &deviceSettings, &deviceSettings, &matchOptions ); if( SUCCEEDED(hr) ) { // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. hr = DXUTChangeDevice( &deviceSettings, NULL, false, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback if( hr == E_ABORT ) { // so nothing changed and keep from attempting to switch adapters next time GetDXUTState().SetAutoChangeAdapter( false ); } else if( FAILED(hr) ) { DXUTShutdown(); DXUTPause( false, false ); return; } } } } } //-------------------------------------------------------------------------------------- // Look for an adapter ordinal that is tied to a HMONITOR //-------------------------------------------------------------------------------------- HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ) { *pAdapterOrdinal = 0; CD3DEnumeration* pd3dEnum = DXUTPrepareEnumerationObject(); IDirect3D9* pD3D = DXUTGetD3DObject(); CGrowableArray<CD3DEnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); for( int iAdapter=0; iAdapter<pAdapterList->GetSize(); iAdapter++ ) { CD3DEnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt(iAdapter); HMONITOR hAdapterMonitor = pD3D->GetAdapterMonitor( pAdapterInfo->AdapterOrdinal ); if( hAdapterMonitor == hMonitor ) { *pAdapterOrdinal = pAdapterInfo->AdapterOrdinal; return S_OK; } } return E_FAIL; } //-------------------------------------------------------------------------------------- // Internal function to map MK_* to an array index //-------------------------------------------------------------------------------------- int DXUTMapButtonToArrayIndex( BYTE vButton ) { switch( vButton ) { case MK_LBUTTON: return 0; case VK_MBUTTON: case MK_MBUTTON: return 1; case MK_RBUTTON: return 2; case VK_XBUTTON1: case MK_XBUTTON1: return 3; case VK_XBUTTON2: case MK_XBUTTON2: return 4; } return 0; } //-------------------------------------------------------------------------------------- // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) //-------------------------------------------------------------------------------------- void DXUTSetupCursor() { // Show the cursor again if returning to fullscreen IDirect3DDevice9* pd3dDevice = DXUTGetD3DDevice(); if( !DXUTIsWindowed() && pd3dDevice ) { if( GetDXUTState().GetShowCursorWhenFullScreen() ) { SetCursor( NULL ); // Turn off Windows cursor in full screen mode HCURSOR hCursor = (HCURSOR)(ULONG_PTR)GetClassLongPtr( DXUTGetHWNDDeviceFullScreen(), GCLP_HCURSOR ); DXUTSetDeviceCursor( pd3dDevice, hCursor, false ); DXUTGetD3DDevice()->ShowCursor( true ); } else { SetCursor( NULL ); // Turn off Windows cursor in full screen mode DXUTGetD3DDevice()->ShowCursor( false ); } } // Clip cursor if requested if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) { // Confine cursor to full screen window RECT rcWindow; GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); ClipCursor( &rcWindow ); } else { ClipCursor( NULL ); } } //-------------------------------------------------------------------------------------- // Gives the D3D device a cursor with image and hotspot from hCursor. //-------------------------------------------------------------------------------------- HRESULT DXUTSetDeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ) { HRESULT hr = E_FAIL; ICONINFO iconinfo; bool bBWCursor; LPDIRECT3DSURFACE9 pCursorSurface = NULL; HDC hdcColor = NULL; HDC hdcMask = NULL; HDC hdcScreen = NULL; BITMAP bm; DWORD dwWidth; DWORD dwHeightSrc; DWORD dwHeightDest; COLORREF crColor; COLORREF crMask; UINT x; UINT y; BITMAPINFO bmi; COLORREF* pcrArrayColor = NULL; COLORREF* pcrArrayMask = NULL; DWORD* pBitmap; HGDIOBJ hgdiobjOld; ZeroMemory( &iconinfo, sizeof(iconinfo) ); if( !GetIconInfo( hCursor, &iconinfo ) ) goto End; if (0 == GetObject((HGDIOBJ)iconinfo.hbmMask, sizeof(BITMAP), (LPVOID)&bm)) goto End; dwWidth = bm.bmWidth; dwHeightSrc = bm.bmHeight; if( iconinfo.hbmColor == NULL ) { bBWCursor = TRUE; dwHeightDest = dwHeightSrc / 2; } else { bBWCursor = FALSE; dwHeightDest = dwHeightSrc; } // Create a surface for the fullscreen cursor if( FAILED( hr = pd3dDevice->CreateOffscreenPlainSurface( dwWidth, dwHeightDest, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pCursorSurface, NULL ) ) ) { goto End; } pcrArrayMask = new DWORD[dwWidth * dwHeightSrc]; ZeroMemory(&bmi, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biWidth = dwWidth; bmi.bmiHeader.biHeight = dwHeightSrc; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; hdcScreen = GetDC( NULL ); hdcMask = CreateCompatibleDC( hdcScreen ); if( hdcMask == NULL ) { hr = E_FAIL; goto End; } hgdiobjOld = SelectObject(hdcMask, iconinfo.hbmMask); GetDIBits(hdcMask, iconinfo.hbmMask, 0, dwHeightSrc, pcrArrayMask, &bmi, DIB_RGB_COLORS); SelectObject(hdcMask, hgdiobjOld); if (!bBWCursor) { pcrArrayColor = new DWORD[dwWidth * dwHeightDest]; hdcColor = CreateCompatibleDC( hdcScreen ); if( hdcColor == NULL ) { hr = E_FAIL; goto End; } SelectObject(hdcColor, iconinfo.hbmColor); GetDIBits(hdcColor, iconinfo.hbmColor, 0, dwHeightDest, pcrArrayColor, &bmi, DIB_RGB_COLORS); } // Transfer cursor image into the surface D3DLOCKED_RECT lr; pCursorSurface->LockRect( &lr, NULL, 0 ); pBitmap = (DWORD*)lr.pBits; for( y = 0; y < dwHeightDest; y++ ) { for( x = 0; x < dwWidth; x++ ) { if (bBWCursor) { crColor = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x]; crMask = pcrArrayMask[dwWidth*(dwHeightSrc-1-y) + x]; } else { crColor = pcrArrayColor[dwWidth*(dwHeightDest-1-y) + x]; crMask = pcrArrayMask[dwWidth*(dwHeightDest-1-y) + x]; } if (crMask == 0) pBitmap[dwWidth*y + x] = 0xff000000 | crColor; else pBitmap[dwWidth*y + x] = 0x00000000; // It may be helpful to make the D3D cursor look slightly // different from the Windows cursor so you can distinguish // between the two when developing/testing code. When // bAddWatermark is TRUE, the following code adds some // small grey "D3D" characters to the upper-left corner of // the D3D cursor image. if( bAddWatermark && x < 12 && y < 5 ) { // 11.. 11.. 11.. .... CCC0 // 1.1. ..1. 1.1. .... A2A0 // 1.1. .1.. 1.1. .... A4A0 // 1.1. ..1. 1.1. .... A2A0 // 11.. 11.. 11.. .... CCC0 const WORD wMask[5] = { 0xccc0, 0xa2a0, 0xa4a0, 0xa2a0, 0xccc0 }; if( wMask[y] & (1 << (15 - x)) ) { pBitmap[dwWidth*y + x] |= 0xff808080; } } } } pCursorSurface->UnlockRect(); // Set the device cursor if( FAILED( hr = pd3dDevice->SetCursorProperties( iconinfo.xHotspot, iconinfo.yHotspot, pCursorSurface ) ) ) { goto End; } hr = S_OK; End: if( iconinfo.hbmMask != NULL ) DeleteObject( iconinfo.hbmMask ); if( iconinfo.hbmColor != NULL ) DeleteObject( iconinfo.hbmColor ); if( hdcScreen != NULL ) ReleaseDC( NULL, hdcScreen ); if( hdcColor != NULL ) DeleteDC( hdcColor ); if( hdcMask != NULL ) DeleteDC( hdcMask ); SAFE_DELETE_ARRAY( pcrArrayColor ); SAFE_DELETE_ARRAY( pcrArrayMask ); SAFE_RELEASE( pCursorSurface ); return hr; }
bsd-2-clause
wizzard/sdk
src/json.cpp
8421
/** * @file json.cpp * @brief Linear non-strict JSON scanner * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega/json.h" #include "mega/base64.h" #include "mega/megaclient.h" namespace mega { // store array or object in string s // reposition after object bool JSON::storeobject(string* s) { int openobject[2] = { 0 }; const char* ptr; bool escaped = false; while (*pos > 0 && *pos <= ' ') { pos++; } if (*pos == ',') { pos++; } ptr = pos; for (;;) { if ((*ptr == '[') || (*ptr == '{')) { openobject[*ptr == '[']++; } else if ((*ptr == ']') || (*ptr == '}')) { openobject[*ptr == ']']--; } else if (*ptr == '"') { ptr++; while (*ptr && (escaped || *ptr != '"')) { escaped = *ptr == '\\' && !escaped; ptr++; } if (!*ptr) { return false; } } else if ((*ptr >= '0' && *ptr <= '9') || *ptr == '-' || *ptr == '.') { ptr++; while ((*ptr >= '0' && *ptr <= '9') || *ptr == '.' || *ptr == 'e' || *ptr == 'E') { ptr++; } ptr--; } else if (*ptr != ':' && *ptr != ',') { return false; } ptr++; if (!openobject[0] && !openobject[1]) { if (s) { if (*pos == '"') { s->assign(pos + 1, ptr - pos - 2); } else { s->assign(pos, ptr - pos); } } pos = ptr; return true; } } } bool JSON::isnumeric() { if (*pos == ',') { pos++; } const char* ptr = pos; if (*ptr == '-') { ptr++; } return *ptr >= '0' && *ptr <= '9'; } nameid JSON::getnameid(const char* ptr) const { nameid id = EOO; while (*ptr && *ptr != '"') { id = (id << 8) + *ptr++; } return id; } // pos points to [,]"name":... // returns nameid and repositons pos after : // no unescaping supported nameid JSON::getnameid() { const char* ptr = pos; nameid id = 0; if (*ptr == ',' || *ptr == ':') { ptr++; } if (*ptr++ == '"') { while (*ptr && *ptr != '"') { id = (id << 8) + *ptr++; } pos = ptr + 2; } return id; } // specific string comparison/skipping bool JSON::is(const char* value) { if (*pos == ',') { pos++; } if (*pos != '"') { return false; } int t = strlen(value); if (memcmp(pos + 1, value, t) || pos[t + 1] != '"') { return false; } pos += t + 2; return true; } // base64-decode binary value to designated fixed-length buffer int JSON::storebinary(byte* dst, int dstlen) { int l = 0; if (*pos == ',') { pos++; } if (*pos == '"') { l = Base64::atob(pos + 1, dst, dstlen); // skip string storeobject(); } return l; } // base64-decode binary value to designated string bool JSON::storebinary(string* dst) { if (*pos == ',') { pos++; } if (*pos == '"') { const char* ptr; if (!(ptr = strchr(pos + 1, '"'))) { return false; } dst->resize((ptr - pos - 1) / 4 * 3 + 3); dst->resize(Base64::atob(pos + 1, (byte*)dst->data(), dst->size())); // skip string storeobject(); } return true; } // test for specific handle type bool JSON::ishandle(int size) { size = (size == 6) ? 8 : 11; if (*pos == ',') { pos++; } if (*pos == '"') { int i; // test for short string for (i = 0; i <= size; i++) { if (!pos[i]) { return false; } } return pos[i] == '"'; } return false; } // decode handle handle JSON::gethandle(int size) { byte buf[9] = { 0 }; // no arithmetic or semantic comparisons will be performed on handles, so // no endianness issues if (storebinary(buf, sizeof buf) == size) { return MemAccess::get<handle>((const char*)buf); } return UNDEF; } // decode integer m_off_t JSON::getint() { const char* ptr; if (*pos == ':' || *pos == ',') { pos++; } ptr = pos; if (*ptr == '"') { ptr++; } if ((*ptr < '0' || *ptr > '9') && *ptr != '-') { return -1; } handle r = atoll(ptr); storeobject(); return r; } // decode float double JSON::getfloat() { if (*pos == ':' || *pos == ',') { pos++; } if ((*pos < '0' || *pos > '9') && *pos != '-' && *pos != '.') { return -1; } double r = atof(pos); storeobject(); return r; } // return pointer to JSON payload data const char* JSON::getvalue() { const char* r; if (*pos == ':' || *pos == ',') { pos++; } if (*pos == '"') { r = pos + 1; } else { r = pos; } storeobject(); return r; } // try to to enter array bool JSON::enterarray() { if (*pos == ',' || *pos == ':') { pos++; } if (*pos == '[') { pos++; return true; } return false; } // leave array (must be at end of array) bool JSON::leavearray() { if (*pos == ']') { pos++; return true; } return false; } // try to enter object bool JSON::enterobject() { if (*pos == '}') { pos++; } if (*pos == ',') { pos++; } if (*pos == '{') { pos++; return true; } return false; } // leave object (skip remainder) bool JSON::leaveobject() { for (; ;) { if (*pos == ':' || *pos == ',') { pos++; } else if (*pos == '"' || (*pos >= '0' && *pos <= '9') || *pos == '-' || *pos == '[' || *pos == '{') { storeobject(); } else { break; } } if (*pos == '}') { pos++; return true; } return false; } // unescape JSON string (non-strict) void JSON::unescape(string* s) { char c; int l; for (unsigned i = 0; i + 1 < s->size(); i++) { if ((*s)[i] == '\\') { switch ((*s)[i + 1]) { case 'n': c = '\n'; l = 2; break; case 'r': c = '\r'; l = 2; break; case 'b': c = '\b'; l = 2; break; case 'f': c = '\f'; l = 2; break; case 't': c = '\t'; l = 2; break; case '\\': c = '\\'; l = 2; break; case 'u': c = (MegaClient::hexval((*s)[i + 4]) << 4) | MegaClient::hexval((*s)[i + 5]); l = 6; break; default: c = (*s)[i + 1]; l = 2; } s->replace(i, l, &c, 1); } } } // position at start of object void JSON::begin(const char* json) { pos = json; } } // namespace
bsd-2-clause
gosu-lang/tora
src/main/java/tora/plugin/JavascriptPlugin.java
7829
package tora.plugin; import gw.config.CommonServices; import gw.fs.IDirectory; import gw.fs.IFile; import gw.lang.reflect.IType; import gw.lang.reflect.RefreshKind; import gw.lang.reflect.RefreshRequest; import gw.lang.reflect.TypeLoaderBase; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.module.IModule; import gw.util.Pair; import gw.util.StreamUtil; import gw.util.concurrent.LockingLazyVar; import tora.parser.Parser; import tora.parser.TemplateParser; import tora.parser.TemplateTokenizer; import tora.parser.Tokenizer; import tora.parser.tree.ProgramNode; import tora.parser.tree.template.JSTNode; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class JavascriptPlugin extends TypeLoaderBase { private static final String JS_EXTENSION = ".js"; private static final String JST_EXTENSION = ".jst"; private Set<String> _namespaces; private final LockingLazyVar<Map<IFile, String>> _jsFileToName = new LockingLazyVar<Map<IFile, String>>() { @Override protected Map<IFile, String> init() { /*convert list of <IFile, String> to a map of file names to fully qualified names*/ return findAllFilesByExtension(JS_EXTENSION).stream() .collect(Collectors.toMap(Pair::getSecond, p -> fileToFqn(p.getFirst(), JS_EXTENSION), (p1, p2) -> p1)); } }; private final LockingLazyVar<Map<String, IFile>> _nameToJSFile = new LockingLazyVar<Map<String, IFile>>() { @Override protected Map<String, IFile> init() { //invert map of file names to fully qualified names return _jsFileToName.get().entrySet().stream() .collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey(), (e1, e2) -> e1 )); } }; private final LockingLazyVar<Map<IFile, String>> _jstFileToName = new LockingLazyVar<Map<IFile, String>>() { @Override protected Map<IFile, String> init() { /*convert list of <IFile, String> to a map of file names to fully qualified names*/ return findAllFilesByExtension(JST_EXTENSION).stream() .collect(Collectors.toMap(Pair::getSecond, p -> fileToFqn(p.getFirst(), JST_EXTENSION), (p1, p2) -> p1)); } }; private final LockingLazyVar<Map<String, IFile>> _nameToJSTFile = new LockingLazyVar<Map<String, IFile>>() { @Override protected Map<String, IFile> init() { //invert map of file names to fully qualified names return _jstFileToName.get().entrySet().stream() .collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey(), (e1, e2) -> e1 )); } }; private String fileToFqn(String fileName, String extension) { return fileName.substring( 0, fileName.length() - extension.length() ).replace( '/', '.' ); } public List<Pair<String, IFile>> findAllFilesByExtension( String extension ) { List<Pair<String, IFile>> results = new ArrayList<>(); for( IDirectory sourceEntry : _module.getSourcePath() ) { if( sourceEntry.exists() ) { String prefix = sourceEntry.getName().equals( IModule.CONFIG_RESOURCE_PREFIX ) ? IModule.CONFIG_RESOURCE_PREFIX : ""; addAllLocalResourceFilesByExtensionInternal( prefix, sourceEntry, extension, results ); } } return results; } private void addAllLocalResourceFilesByExtensionInternal( String relativePath, IDirectory dir, String extension, List<Pair<String, IFile>> results ) { List<IDirectory> excludedPath = Arrays.asList( _module.getFileRepository().getExcludedPath() ); if( excludedPath.contains( dir ) ) { return; } if( !CommonServices.getPlatformHelper().isPathIgnored( relativePath ) ) { for( IFile file : dir.listFiles() ) { if( file.getName().endsWith( extension ) ) { String path = appendResourceNameToPath( relativePath, file.getName() ); results.add( new Pair<String, IFile>( path, file ) ); } } for( IDirectory subdir : dir.listDirs() ) { String path = appendResourceNameToPath( relativePath, subdir.getName() ); addAllLocalResourceFilesByExtensionInternal( path, subdir, extension, results ); } } } private static String appendResourceNameToPath( String relativePath, String resourceName ) { String path; if( relativePath.length() > 0 ) { path = relativePath + '/' + resourceName; } else { path = resourceName; } return path; } public JavascriptPlugin( IModule currentModule ) { super( currentModule ); } @Override public IType getType( String name ) { IFile iFile = _nameToJSFile.get().get( name ); try { if (iFile == null) { //check to see if JST file iFile = _nameToJSTFile.get().get(name); if (iFile != null) { TemplateParser parser = new TemplateParser(new TemplateTokenizer( StreamUtil.getContent(new InputStreamReader(iFile.openInputStream())), true)); return new JavascriptTemplateType(this, name, iFile, (JSTNode) parser.parse()); } } else { Parser parser = new Parser(new Tokenizer(StreamUtil.getContent(new InputStreamReader(iFile.openInputStream())))); ProgramNode programNode = (ProgramNode) parser.parse(); if (programNode.errorCount() > 0) { programNode.printErrors(); return null; } if (parser.isES6Class()) { return new JavascriptClassType(this, name, iFile, programNode); } else { return new JavascriptProgramType(this, name, iFile, programNode); } } } catch (IOException e) { } return null; } @Override public Set<? extends CharSequence> getAllNamespaces() { if( _namespaces == null ) { try { _namespaces = TypeSystem.getNamespacesFromTypeNames( getAllTypeNames(), new HashSet<String>() ); } catch( NullPointerException e ) { //!! hack to get past dependency issue with tests return Collections.emptySet(); } } return _namespaces; } @Override public List<String> getHandledPrefixes() { return Collections.emptyList(); } @Override public boolean handlesNonPrefixLoads() { return true; } @Override public boolean handlesFile( IFile file ) { return JS_EXTENSION.substring( 1 ).equals( file.getExtension() ); } public String[] getTypesForFile( IFile file ) { String typeName = _jsFileToName.get().get( file ); if( typeName != null ) { return new String[]{typeName}; } return NO_TYPES; } @Override public void refreshedNamespace( String namespace, IDirectory iDirectory, RefreshKind kind ) { clear(); if( _namespaces != null ) { if( kind == RefreshKind.CREATION ) { _namespaces.add( namespace ); } else if( kind == RefreshKind.DELETION ) { _namespaces.remove( namespace ); } } } @Override protected void refreshedImpl() { clear(); } @Override public RefreshKind refreshedFile( IFile file, String[] types, RefreshKind kind ) { clear(); return kind; } @Override protected void refreshedTypesImpl( RefreshRequest request ) { clear(); } private void clear() { _nameToJSFile.clear(); _jsFileToName.clear(); } @Override public boolean hasNamespace( String namespace ) { return getAllNamespaces().contains( namespace ); } @Override public Set<String> computeTypeNames() { return _nameToJSFile.get().keySet(); } }
bsd-2-clause
ooici/marine-integrations
mi/instrument/seabird/sbe16plus_v2/ctdpf_jb/test/test_driver.py
73809
""" @package mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.test.test_driver @file marine-integrations/mi/instrument/seabird/sbe16plus_v2/ctdpf_jb/driver.py @author Tapana Gupta @brief Test cases for ctdpf_jb driver USAGE: Make tests verbose and provide stdout * From the IDK $ bin/test_driver $ bin/test_driver -u [-t testname] $ bin/test_driver -i [-t testname] $ bin/test_driver -q [-t testname] """ __author__ = 'Tapana Gupta' __license__ = 'Apache 2.0' import unittest import time from nose.plugins.attrib import attr from mock import Mock from mi.core.log import get_logger ; log = get_logger() # MI imports. from mi.idk.unit_test import InstrumentDriverTestCase from mi.idk.unit_test import DriverTestMixin from mi.idk.unit_test import ParameterTestConfigKey from mi.idk.unit_test import AgentCapabilityType from mi.core.exceptions import InstrumentParameterException from mi.core.exceptions import InstrumentProtocolException from mi.core.exceptions import InstrumentCommandException from mi.core.instrument.chunker import StringChunker from mi.core.instrument.instrument_driver import DriverConfigKey from mi.instrument.seabird.test.test_driver import SeaBirdUnitTest from mi.instrument.seabird.test.test_driver import SeaBirdIntegrationTest from mi.instrument.seabird.test.test_driver import SeaBirdQualificationTest from mi.instrument.seabird.test.test_driver import SeaBirdPublicationTest from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import InstrumentDriver from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import DataParticleType from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import ProtocolState from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import ProtocolEvent from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import Capability from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import Parameter from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import ConfirmedParameter from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import Command from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SendOptodeCommand from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import ScheduledJob from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19DataParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19ConfigurationParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19HardwareParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19StatusParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19CalibrationParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import OptodeSettingsParticleKey from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import Prompt from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import NEWLINE from mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver import SBE19Protocol from pyon.agent.agent import ResourceAgentEvent from pyon.agent.agent import ResourceAgentState ### # Driver parameters for the tests ### InstrumentDriverTestCase.initialize( driver_module='mi.instrument.seabird.sbe16plus_v2.ctdpf_jb.driver', driver_class="InstrumentDriver", instrument_agent_resource_id = 'JI22B5', instrument_agent_name = 'seabird_sbe16plus_v2_ctdpf_jb', instrument_agent_packet_config = DataParticleType(), driver_startup_config = {DriverConfigKey.PARAMETERS: { Parameter.PTYPE: 1, Parameter.VOLT0: True, Parameter.VOLT1: True, Parameter.VOLT2: False, Parameter.VOLT3: False, Parameter.VOLT4: False, Parameter.VOLT5: False, Parameter.SBE38: False, Parameter.WETLABS: False, Parameter.GTD: False, Parameter.DUAL_GTD: False, Parameter.SBE63: False, Parameter.OPTODE: True, Parameter.OUTPUT_FORMAT: 0, Parameter.NUM_AVG_SAMPLES: 4, Parameter.MIN_COND_FREQ: 500, Parameter.PUMP_DELAY: 60, Parameter.AUTO_RUN: False, Parameter.IGNORE_SWITCH: True, Parameter.CLOCK_INTERVAL: '00:00:00', Parameter.STATUS_INTERVAL: '00:00:00'}} ) #################################### RULES #################################### # # # Common capabilities in the base class # # # # Instrument specific stuff in the derived class # # # # Generator spits out either stubs or comments describing test this here, # # test that there. # # # # Qualification tests are driven through the instrument_agent # # # ############################################################################### ### # Driver constant definitions ### ############################################################################### # DRIVER TEST MIXIN # # Defines a set of constants and assert methods used for data particle # # verification # # # # In python mixin classes are classes designed such that they wouldn't be # # able to stand on their own, but are inherited by other classes generally # # using multiple inheritance. # # # # This class defines a configuration structure for testing and common assert # # methods for validating data particles. # ############################################################################### class SeaBird19plusMixin(DriverTestMixin): InstrumentDriver = InstrumentDriver ''' Mixin class used for storing data particle constants and common data assertion methods. ''' # Create some short names for the parameter test config TYPE = ParameterTestConfigKey.TYPE READONLY = ParameterTestConfigKey.READONLY STARTUP = ParameterTestConfigKey.STARTUP DA = ParameterTestConfigKey.DIRECT_ACCESS VALUE = ParameterTestConfigKey.VALUE REQUIRED = ParameterTestConfigKey.REQUIRED DEFAULT = ParameterTestConfigKey.DEFAULT STATES = ParameterTestConfigKey.STATES ### # Instrument output (driver input) Definitions ### VALID_SAMPLE = "04570F0A1E910828FC47BC59F199952C64C9" + NEWLINE VALID_GETHD_RESPONSE = "" + \ "<HardwareData DeviceType = 'SBE19plus' SerialNumber = '01906914'>" + NEWLINE + \ " <Manufacturer>Sea-Bird Electronics, Inc.</Manufacturer>" + NEWLINE + \ " <FirmwareVersion>2.3</FirmwareVersion>" + NEWLINE + \ " <FirmwareDate>16 March 2011 08:50</FirmwareDate>" + NEWLINE + \ " <CommandSetVersion>1.2</CommandSetVersion>" + NEWLINE + \ " <PCBAssembly PCBSerialNum = '49577' AssemblyNum = '41054H'/>" + NEWLINE + \ " <PCBAssembly PCBSerialNum = '46750' AssemblyNum = '41580B'/>" + NEWLINE + \ " <PCBAssembly PCBSerialNum = '49374' AssemblyNum = '41606'/>" + NEWLINE + \ " <PCBAssembly PCBSerialNum = '38071' AssemblyNum = '41057A'/>" + NEWLINE + \ " <MfgDate>29 SEP 2011</MfgDate>" + NEWLINE + \ " <InternalSensors>" + NEWLINE + \ " <Sensor id = 'Main Temperature'>" + NEWLINE + \ " <type>temperature0</type>" + NEWLINE + \ " <SerialNumber>01906914</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'Main Conductivity'>" + NEWLINE + \ " <type>conductivity-0</type>" + NEWLINE + \ " <SerialNumber>01906914</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'Main Pressure'>" + NEWLINE + \ " <type>strain-0</type>" + NEWLINE + \ " <SerialNumber>3313899</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " </InternalSensors>" + NEWLINE + \ " <ExternalSensors>" + NEWLINE + \ " <Sensor id = 'volt 0'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'volt 1'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'volt 2'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'volt 3'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'volt 4'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'volt 5'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " <Sensor id = 'serial'>" + NEWLINE + \ " <type>not assigned</type>" + NEWLINE + \ " <SerialNumber>not assigned</SerialNumber>" + NEWLINE + \ " </Sensor>" + NEWLINE + \ " </ExternalSensors>" + NEWLINE + \ "</HardwareData>" + NEWLINE VALID_GETCC_RESPONSE = "" + \ "<CalibrationCoefficients DeviceType = 'SBE19plus' SerialNumber = '01906914'>" + NEWLINE + \ " <Calibration format = 'TEMP1' id = 'Main Temperature'>" + NEWLINE + \ " <SerialNum>01906914</SerialNum>" + NEWLINE + \ " <CalDate>09-Oct-11</CalDate>" + NEWLINE + \ " <TA0>1.254755e-03</TA0>" + NEWLINE + \ " <TA1>2.758871e-04</TA1>" + NEWLINE + \ " <TA2>-1.368268e-06</TA2>" + NEWLINE + \ " <TA3>1.910795e-07</TA3>" + NEWLINE + \ " <TOFFSET>0.000000e+00</TOFFSET>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'WBCOND0' id = 'Main Conductivity'>" + NEWLINE + \ " <SerialNum>01906914</SerialNum>" + NEWLINE + \ " <CalDate>09-Oct-11</CalDate>" + NEWLINE + \ " <G>-9.761799e-01</G>" + NEWLINE + \ " <H>1.369994e-01</H>" + NEWLINE + \ " <I>-3.523860e-04</I>" + NEWLINE + \ " <J>4.404252e-05</J>" + NEWLINE + \ " <CPCOR>-9.570000e-08</CPCOR>" + NEWLINE + \ " <CTCOR>3.250000e-06</CTCOR>" + NEWLINE + \ " <CSLOPE>1.000000e+00</CSLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'STRAIN0' id = 'Main Pressure'>" + NEWLINE + \ " <SerialNum>3313899</SerialNum>" + NEWLINE + \ " <CalDate>06-Oct-11</CalDate>" + NEWLINE + \ " <PA0>-3.689246e-02</PA0>" + NEWLINE + \ " <PA1>1.545570e-03</PA1>" + NEWLINE + \ " <PA2>6.733197e-12</PA2>" + NEWLINE + \ " <PTCA0>5.249034e+05</PTCA0>" + NEWLINE + \ " <PTCA1>1.423189e+00</PTCA1>" + NEWLINE + \ " <PTCA2>-1.206562e-01</PTCA2>" + NEWLINE + \ " <PTCB0>2.501288e+01</PTCB0>" + NEWLINE + \ " <PTCB1>-2.250000e-04</PTCB1>" + NEWLINE + \ " <PTCB2>0.000000e+00</PTCB2>" + NEWLINE + \ " <PTEMPA0>-5.677620e+01</PTEMPA0>" + NEWLINE + \ " <PTEMPA1>5.424624e+01</PTEMPA1>" + NEWLINE + \ " <PTEMPA2>-2.278113e-01</PTEMPA2>" + NEWLINE + \ " <POFFSET>0.000000e+00</POFFSET>" + NEWLINE + \ " <PRANGE>5.080000e+02</PRANGE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 0'>" + NEWLINE + \ " <OFFSET>-4.650526e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.246381e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 1'>" + NEWLINE + \ " <OFFSET>-4.618105e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.247197e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 2'>" + NEWLINE + \ " <OFFSET>-4.659790e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.247601e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 3'>" + NEWLINE + \ " <OFFSET>-4.502421e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.246911e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 4'>" + NEWLINE + \ " <OFFSET>-4.589158e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.246346e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'VOLT0' id = 'Volt 5'>" + NEWLINE + \ " <OFFSET>-4.609895e-02</OFFSET>" + NEWLINE + \ " <SLOPE>1.247868e+00</SLOPE>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ " <Calibration format = 'FREQ0' id = 'external frequency channel'>" + NEWLINE + \ " <EXTFREQSF>1.000008e+00</EXTFREQSF>" + NEWLINE + \ " </Calibration>" + NEWLINE + \ "</CalibrationCoefficients>" + NEWLINE VALID_GETCD_RESPONSE = "" + \ "<ConfigurationData DeviceType = 'SBE19plus' SerialNumber = '01906914'>" + NEWLINE + \ " <ProfileMode>" + NEWLINE + \ " <ScansToAverage>4</ScansToAverage>" + NEWLINE + \ " <MinimumCondFreq>2500</MinimumCondFreq>" + NEWLINE + \ " <PumpDelay>15</PumpDelay>" + NEWLINE + \ " <AutoRun>no</AutoRun>" + NEWLINE + \ " <IgnoreSwitch>yes</IgnoreSwitch>" + NEWLINE + \ " </ProfileMode>" + NEWLINE + \ " <Battery>" + NEWLINE + \ " <Type>alkaline</Type>" + NEWLINE + \ " <CutOff>7.5</CutOff>" + NEWLINE + \ " </Battery>" + NEWLINE + \ " <DataChannels>" + NEWLINE + \ " <ExtVolt0>yes</ExtVolt0>" + NEWLINE + \ " <ExtVolt1>yes</ExtVolt1>" + NEWLINE + \ " <ExtVolt2>no</ExtVolt2>" + NEWLINE + \ " <ExtVolt3>no</ExtVolt3>" + NEWLINE + \ " <ExtVolt4>no</ExtVolt4>" + NEWLINE + \ " <ExtVolt5>no</ExtVolt5>" + NEWLINE + \ " <SBE38>no</SBE38>" + NEWLINE + \ " <WETLABS>no</WETLABS>" + NEWLINE + \ " <OPTODE>yes</OPTODE>" + NEWLINE + \ " <SBE63>no</SBE63>" + NEWLINE + \ " <GTD>no</GTD>" + NEWLINE + \ " </DataChannels>" + NEWLINE + \ " <EchoCharacters>yes</EchoCharacters>" + NEWLINE + \ " <OutputExecutedTag>no</OutputExecutedTag>" + NEWLINE + \ " <OutputFormat>raw HEX</OutputFormat>" + NEWLINE + \ "</ConfigurationData>" + NEWLINE VALID_GETSD_RESPONSE = "" + \ "<StatusData DeviceType = 'SBE19plus' SerialNumber = '01906914'>" + NEWLINE + \ " <DateTime>2014-03-20T09:09:06</DateTime>" + NEWLINE + \ " <LoggingState>not logging</LoggingState>" + NEWLINE + \ " <EventSummary numEvents = '260'/>" + NEWLINE + \ " <Power>" + NEWLINE + \ " <vMain>13.0</vMain>" + NEWLINE + \ " <vLith>8.6</vLith>" + NEWLINE + \ " <iMain>51.1</iMain>" + NEWLINE + \ " <iPump>145.6</iPump>" + NEWLINE + \ " <iExt01> 0.5</iExt01>" + NEWLINE + \ " <iSerial>45.1</iSerial>" + NEWLINE + \ " </Power>" + NEWLINE + \ " <MemorySummary>" + NEWLINE + \ " <Bytes>330</Bytes>" + NEWLINE + \ " <Samples>15</Samples>" + NEWLINE + \ " <SamplesFree>2990809</SamplesFree>" + NEWLINE + \ " <SampleLength>18</SampleLength>" + NEWLINE + \ " <Profiles>0</Profiles>" + NEWLINE + \ " </MemorySummary>" + NEWLINE + \ "</StatusData>" + NEWLINE VALID_SEND_OPTODE_RESPONSE = "" + \ 'Optode RX = Analog Output 4831 134 CalPhase' + NEWLINE + \ 'Optode RX = CalPhase[Deg] 4831 134 30.050' + NEWLINE + \ 'S>sendoptode=get enable temperature' + NEWLINE + \ 'Sending Optode: get enable temperature' + NEWLINE + NEWLINE + \ 'Optode RX = Enable Temperature 4831 134 No' + NEWLINE + \ 'S>sendoptode=get enable text' + NEWLINE + \ 'Sending Optode: get enable text' + NEWLINE + NEWLINE + \ 'Optode RX = Enable Text 4831 134 No' + NEWLINE + \ 'S>sendoptode=get enable humiditycomp' + NEWLINE + \ 'Sending Optode: get enable humiditycomp' + NEWLINE + NEWLINE + \ 'Optode RX = Enable HumidityComp 4831 134 Yes' + NEWLINE + \ 'S>sendoptode=get enable airsaturation' + NEWLINE + \ 'Sending Optode: get enable airsaturation' + NEWLINE + NEWLINE + \ 'Optode RX = Enable AirSaturation 4831 134 No' + NEWLINE + \ 'S>sendoptode=get enable rawdata' + NEWLINE + \ 'Sending Optode: get enable rawdata' + NEWLINE + NEWLINE + \ 'Optode RX = Enable Rawdata 4831 134 No' + NEWLINE + \ 'S>sendoptode=get interval' + NEWLINE + \ 'Sending Optode: get interval' + NEWLINE + NEWLINE + \ 'Optode RX = Interval 4831 134 5.000' + NEWLINE + \ 'S>sendoptode=get mode' + NEWLINE + \ 'Sending Optode: get mode' + NEWLINE + NEWLINE + \ 'Optode RX = Mode 4831 134 Smart Sensor Terminal' + NEWLINE VALID_DS_RESPONSE = 'SBE 19plus V 2.3 SERIAL NO. 6914 18 Apr 2014 19:14:13' + NEWLINE + \ 'vbatt = 23.3, vlith = 8.5, ioper = 62.1 ma, ipump = 71.7 ma, ' + NEWLINE + \ 'iext01 = 0.2 ma, iserial = 26.0 ma' + NEWLINE + \ 'status = not logging' + NEWLINE + \ 'number of scans to average = 4' + NEWLINE + \ 'samples = 1861, free = 3653591, casts = 7' + NEWLINE + \ 'mode = profile, minimum cond freq = 500, pump delay = 60 sec' + NEWLINE + \ 'autorun = no, ignore magnetic switch = yes' + NEWLINE + \ 'battery type = alkaline, battery cutoff = 7.5 volts' + NEWLINE + \ 'pressure sensor = strain gauge, range = 508.0' + NEWLINE + \ 'SBE 38 = no, WETLABS = no, OPTODE = yes, SBE63 = no, Gas Tension Device = no' + NEWLINE + \ 'Ext Volt 0 = yes, Ext Volt 1 = yes' + NEWLINE + \ 'Ext Volt 2 = no, Ext Volt 3 = no' + NEWLINE + \ 'Ext Volt 4 = no, Ext Volt 5 = no' + NEWLINE + \ 'echo characters = no' + NEWLINE + \ 'output format = raw HEX' + NEWLINE ### # Parameter and Type Definitions ### _sample_parameters = { SBE19DataParticleKey.TEMP: {TYPE: int, VALUE: 284431, REQUIRED: True }, SBE19DataParticleKey.CONDUCTIVITY: {TYPE: int, VALUE: 663185, REQUIRED: True }, SBE19DataParticleKey.PRESSURE: {TYPE: int, VALUE: 534780, REQUIRED: True }, SBE19DataParticleKey.PRESSURE_TEMP: {TYPE: int, VALUE: 18364, REQUIRED: True }, SBE19DataParticleKey.VOLT0: {TYPE: int, VALUE: 23025, REQUIRED: True }, SBE19DataParticleKey.VOLT1: {TYPE: int, VALUE: 39317, REQUIRED: True }, SBE19DataParticleKey.OXYGEN: {TYPE: int, VALUE: 2909385, REQUIRED: True }, } _configuration_parameters = { SBE19ConfigurationParticleKey.SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19ConfigurationParticleKey.SCANS_TO_AVERAGE: {TYPE: int, VALUE: 4, REQUIRED: True}, SBE19ConfigurationParticleKey.MIN_COND_FREQ: {TYPE: int, VALUE: 2500, REQUIRED: True}, SBE19ConfigurationParticleKey.PUMP_DELAY: {TYPE: int, VALUE: 15, REQUIRED: True}, SBE19ConfigurationParticleKey.AUTO_RUN: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.IGNORE_SWITCH: {TYPE: bool, VALUE: True, REQUIRED: True}, SBE19ConfigurationParticleKey.BATTERY_TYPE: {TYPE: unicode, VALUE: "alkaline", REQUIRED: True}, SBE19ConfigurationParticleKey.BATTERY_CUTOFF: {TYPE: float, VALUE: 7.5, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_0: {TYPE: bool, VALUE: True, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_1: {TYPE: bool, VALUE: True, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_2: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_3: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_4: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.EXT_VOLT_5: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.SBE38: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.WETLABS: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.OPTODE: {TYPE: bool, VALUE: True, REQUIRED: True}, SBE19ConfigurationParticleKey.SBE63: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.GAS_TENSION_DEVICE: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.ECHO_CHARACTERS: {TYPE: bool, VALUE: True, REQUIRED: True}, SBE19ConfigurationParticleKey.OUTPUT_EXECUTED_TAG: {TYPE: bool, VALUE: False, REQUIRED: True}, SBE19ConfigurationParticleKey.OUTPUT_FORMAT: {TYPE: unicode, VALUE: "raw HEX", REQUIRED: True}, } _status_parameters = { SBE19StatusParticleKey.SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19StatusParticleKey.DATE_TIME: {TYPE: unicode, VALUE: "2014-03-20T09:09:06", REQUIRED: True}, SBE19StatusParticleKey.LOGGING_STATE: {TYPE: unicode, VALUE: "not logging", REQUIRED: True}, SBE19StatusParticleKey.NUMBER_OF_EVENTS: {TYPE: int, VALUE: 260, REQUIRED: True}, SBE19StatusParticleKey.BATTERY_VOLTAGE_MAIN: {TYPE: float, VALUE: 13.0, REQUIRED: True}, SBE19StatusParticleKey.BATTERY_VOLTAGE_LITHIUM: {TYPE: float, VALUE: 8.6, REQUIRED: True}, SBE19StatusParticleKey.OPERATIONAL_CURRENT: {TYPE: float, VALUE: 51.1, REQUIRED: True}, SBE19StatusParticleKey.PUMP_CURRENT: {TYPE: float, VALUE: 145.6, REQUIRED: True}, SBE19StatusParticleKey.EXT_V01_CURRENT: {TYPE: float, VALUE: 0.5, REQUIRED: True}, SBE19StatusParticleKey.SERIAL_CURRENT: {TYPE: float, VALUE: 45.1, REQUIRED: True}, SBE19StatusParticleKey.MEMORY_FREE: {TYPE: int, VALUE: 330, REQUIRED: True}, SBE19StatusParticleKey.NUMBER_OF_SAMPLES: {TYPE: int, VALUE: 15, REQUIRED: True}, SBE19StatusParticleKey.SAMPLES_FREE: {TYPE: int, VALUE: 2990809, REQUIRED: True}, SBE19StatusParticleKey.SAMPLE_LENGTH: {TYPE: int, VALUE: 18, REQUIRED: True}, SBE19StatusParticleKey.PROFILES: {TYPE: int, VALUE: 0, REQUIRED: True}, } _hardware_parameters = { SBE19HardwareParticleKey.SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19HardwareParticleKey.FIRMWARE_VERSION: {TYPE: unicode, VALUE: '2.3', REQUIRED: True}, SBE19HardwareParticleKey.FIRMWARE_DATE: {TYPE: unicode, VALUE: '16 March 2011 08:50', REQUIRED: True}, SBE19HardwareParticleKey.COMMAND_SET_VERSION: {TYPE: unicode, VALUE: '1.2', REQUIRED: True}, SBE19HardwareParticleKey.PCB_SERIAL_NUMBER: {TYPE: list, VALUE: ['49577', '46750', '49374', '38071'], REQUIRED: True}, SBE19HardwareParticleKey.ASSEMBLY_NUMBER: {TYPE: list, VALUE: ['41054H', '41580B', '41606', '41057A'], REQUIRED: True}, SBE19HardwareParticleKey.MANUFACTURE_DATE: {TYPE: unicode, VALUE: '29 SEP 2011', REQUIRED: True}, SBE19HardwareParticleKey.TEMPERATURE_SENSOR_SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19HardwareParticleKey.CONDUCTIVITY_SENSOR_SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19HardwareParticleKey.PRESSURE_SENSOR_SERIAL_NUMBER: {TYPE: unicode, VALUE: '3313899', REQUIRED: True}, SBE19HardwareParticleKey.PRESSURE_SENSOR_TYPE: {TYPE: unicode, VALUE: 'strain-0', REQUIRED: True}, SBE19HardwareParticleKey.VOLT0_TYPE: {TYPE: unicode, VALUE: 'not assigned', REQUIRED: True}, SBE19HardwareParticleKey.VOLT0_SERIAL_NUMBER: {TYPE: unicode, VALUE: 'not assigned', REQUIRED: True}, SBE19HardwareParticleKey.VOLT1_TYPE: {TYPE: unicode, VALUE: 'not assigned', REQUIRED: True}, SBE19HardwareParticleKey.VOLT1_SERIAL_NUMBER: {TYPE: unicode, VALUE: 'not assigned', REQUIRED: True}, } _calibration_parameters = { SBE19CalibrationParticleKey.SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True}, SBE19CalibrationParticleKey.TEMP_SENSOR_SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True }, SBE19CalibrationParticleKey.TEMP_CAL_DATE: {TYPE: unicode, VALUE: "09-Oct-11", REQUIRED: True}, SBE19CalibrationParticleKey.TA0: {TYPE: float, VALUE: 1.254755e-03, REQUIRED: True}, SBE19CalibrationParticleKey.TA1: {TYPE: float, VALUE: 2.758871e-04, REQUIRED: True}, SBE19CalibrationParticleKey.TA2: {TYPE: float, VALUE: -1.368268e-06, REQUIRED: True}, SBE19CalibrationParticleKey.TA3: {TYPE: float, VALUE: 1.910795e-07, REQUIRED: True}, SBE19CalibrationParticleKey.TOFFSET: {TYPE: float, VALUE: 0.0, REQUIRED: True}, SBE19CalibrationParticleKey.COND_SENSOR_SERIAL_NUMBER: {TYPE: int, VALUE: 1906914, REQUIRED: True }, SBE19CalibrationParticleKey.COND_CAL_DATE: {TYPE: unicode, VALUE: '09-Oct-11', REQUIRED: True}, SBE19CalibrationParticleKey.CONDG: {TYPE: float, VALUE: -9.761799e-01, REQUIRED: True}, SBE19CalibrationParticleKey.CONDH: {TYPE: float, VALUE: 1.369994e-01, REQUIRED: True}, SBE19CalibrationParticleKey.CONDI: {TYPE: float, VALUE: -3.523860e-04, REQUIRED: True}, SBE19CalibrationParticleKey.CONDJ: {TYPE: float, VALUE: 4.404252e-05, REQUIRED: True}, SBE19CalibrationParticleKey.CPCOR: {TYPE: float, VALUE: -9.570000e-08, REQUIRED: True}, SBE19CalibrationParticleKey.CTCOR: {TYPE: float, VALUE: 3.250000e-06, REQUIRED: True}, SBE19CalibrationParticleKey.CSLOPE: {TYPE: float, VALUE: 1.0, REQUIRED: True}, SBE19CalibrationParticleKey.PRES_SERIAL_NUMBER: {TYPE: int, VALUE: 3313899, REQUIRED: True }, SBE19CalibrationParticleKey.PRES_CAL_DATE: {TYPE: unicode, VALUE: '06-Oct-11', REQUIRED: True }, SBE19CalibrationParticleKey.PA0: {TYPE: float, VALUE: -3.689246e-02, REQUIRED: True }, SBE19CalibrationParticleKey.PA1: {TYPE: float, VALUE: 1.545570e-03, REQUIRED: True }, SBE19CalibrationParticleKey.PA2: {TYPE: float, VALUE: 6.733197e-12, REQUIRED: True }, SBE19CalibrationParticleKey.PTCA0: {TYPE: float, VALUE: 5.249034e+05, REQUIRED: True }, SBE19CalibrationParticleKey.PTCA1: {TYPE: float, VALUE: 1.423189e+00, REQUIRED: True }, SBE19CalibrationParticleKey.PTCA2: {TYPE: float, VALUE: -1.206562e-01, REQUIRED: True }, SBE19CalibrationParticleKey.PTCB0: {TYPE: float, VALUE: 2.501288e+01, REQUIRED: True }, SBE19CalibrationParticleKey.PTCB1: {TYPE: float, VALUE: -2.250000e-04, REQUIRED: True }, SBE19CalibrationParticleKey.PTCB2: {TYPE: float, VALUE: 0.000000e+00, REQUIRED: True }, SBE19CalibrationParticleKey.PTEMPA0: {TYPE: float, VALUE: -5.677620e+01, REQUIRED: True }, SBE19CalibrationParticleKey.PTEMPA1: {TYPE: float, VALUE: 5.424624e+01, REQUIRED: True }, SBE19CalibrationParticleKey.PTEMPA2: {TYPE: float, VALUE: -2.278113e-01, REQUIRED: True }, SBE19CalibrationParticleKey.POFFSET: {TYPE: float, VALUE: 0.000000e+00, REQUIRED: True }, SBE19CalibrationParticleKey.PRES_RANGE: {TYPE: int, VALUE: 5.080000e+02, REQUIRED: True }, SBE19CalibrationParticleKey.EXT_VOLT0_OFFSET: {TYPE: float, VALUE: -4.650526e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT0_SLOPE: {TYPE: float, VALUE: 1.246381e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT1_OFFSET: {TYPE: float, VALUE: -4.618105e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT1_SLOPE: {TYPE: float, VALUE: 1.247197e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT2_OFFSET: {TYPE: float, VALUE: -4.659790e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT2_SLOPE: {TYPE: float, VALUE: 1.247601e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT3_OFFSET: {TYPE: float, VALUE: -4.502421e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT3_SLOPE: {TYPE: float, VALUE: 1.246911e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT4_OFFSET: {TYPE: float, VALUE: -4.589158e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT4_SLOPE: {TYPE: float, VALUE: 1.246346e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT5_OFFSET: {TYPE: float, VALUE: -4.609895e-02, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_VOLT5_SLOPE: {TYPE: float, VALUE: 1.247868e+00, REQUIRED: True}, SBE19CalibrationParticleKey.EXT_FREQ: {TYPE: float, VALUE: 1.000008e+00, REQUIRED: True}, } _send_optode_parameters = { OptodeSettingsParticleKey.ANALOG_OUTPUT: {TYPE: unicode, VALUE: 'CalPhase', REQUIRED: True}, OptodeSettingsParticleKey.CALPHASE: {TYPE: float, VALUE: 30.050, REQUIRED: True}, OptodeSettingsParticleKey.ENABLE_AIR_SAT: {TYPE: bool, VALUE: False, REQUIRED: True}, OptodeSettingsParticleKey.ENABLE_RAW_DATA: {TYPE: bool, VALUE: False, REQUIRED: True}, OptodeSettingsParticleKey.ENABLE_HUM_COMP: {TYPE: bool, VALUE: True, REQUIRED: True}, OptodeSettingsParticleKey.ENABLE_TEMP: {TYPE: bool, VALUE: False, REQUIRED: True}, OptodeSettingsParticleKey.ENABLE_TEXT: {TYPE: bool, VALUE: False, REQUIRED: True}, OptodeSettingsParticleKey.INTERVAL: {TYPE: float, VALUE: 5.000, REQUIRED: True}, OptodeSettingsParticleKey.MODE: {TYPE: unicode, VALUE: 'Smart Sensor Terminal', REQUIRED: True}, } ### # Parameter and Type Definitions ### _driver_parameters = { # Parameters defined in the IOS Parameter.DATE_TIME : {TYPE: str, READONLY: True, DA: False, STARTUP: False}, Parameter.PTYPE : {TYPE: int, READONLY: True, DA: True, STARTUP: True, DEFAULT: 1, VALUE: 1}, Parameter.VOLT0 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: True, VALUE: True}, Parameter.VOLT1 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: True, VALUE: True}, Parameter.VOLT2 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.VOLT3 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.VOLT4 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.VOLT5 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.SBE38 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.WETLABS : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.GTD : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.DUAL_GTD : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.SBE63 : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.OPTODE : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: True, VALUE: True}, Parameter.OUTPUT_FORMAT : {TYPE: int, READONLY: True, DA: True, STARTUP: True, DEFAULT: 0, VALUE: 0}, Parameter.NUM_AVG_SAMPLES : {TYPE: int, READONLY: False, DA: True, STARTUP: True, DEFAULT: 4, VALUE: 4}, Parameter.MIN_COND_FREQ : {TYPE: int, READONLY: True, DA: True, STARTUP: True, DEFAULT: 500, VALUE: 500}, Parameter.PUMP_DELAY : {TYPE: int, READONLY: False, DA: True, STARTUP: True, DEFAULT: 60, VALUE: 60}, Parameter.AUTO_RUN : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: False, VALUE: False}, Parameter.IGNORE_SWITCH : {TYPE: bool, READONLY: True, DA: True, STARTUP: True, DEFAULT: True, VALUE: True}, Parameter.LOGGING : {TYPE: bool, READONLY: True, DA: False, STARTUP: False}, Parameter.CLOCK_INTERVAL : {TYPE: str, READONLY: False, DA: False, STARTUP: True, DEFAULT: '00:00:00', VALUE: '00:00:00'}, Parameter.STATUS_INTERVAL : {TYPE: str, READONLY: False, DA: False, STARTUP: True, DEFAULT: '00:00:00', VALUE: '00:00:00'}, } _driver_capabilities = { # capabilities defined in the IOS Capability.ACQUIRE_SAMPLE : {STATES: [ProtocolState.COMMAND]}, Capability.START_AUTOSAMPLE : {STATES: [ProtocolState.COMMAND]}, Capability.STOP_AUTOSAMPLE : {STATES: [ProtocolState.AUTOSAMPLE]}, Capability.CLOCK_SYNC : {STATES: [ProtocolState.COMMAND]}, Capability.ACQUIRE_STATUS : {STATES: [ProtocolState.COMMAND, ProtocolState.AUTOSAMPLE]}, } def assert_driver_parameters(self, current_parameters, verify_values = False): """ Verify that all driver parameters are correct and potentially verify values. @param current_parameters: driver parameters read from the driver instance @param verify_values: should we verify values against definition? """ self.assert_parameters(current_parameters, self._driver_parameters, verify_values) def assert_particle_sample(self, data_particle, verify_values = False): ''' Verify sample particle @param data_particle: SBE19DataParticle data particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(SBE19DataParticleKey, self._sample_parameters) self.assert_data_particle_header(data_particle, DataParticleType.CTD_PARSED, require_instrument_timestamp=False) self.assert_data_particle_parameters(data_particle, self._sample_parameters, verify_values) def assert_particle_hardware(self, data_particle, verify_values = False): ''' Verify hardware particle @param data_particle: SBE19HardwareParticle data particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(SBE19HardwareParticleKey, self._hardware_parameters) self.assert_data_particle_header(data_particle, DataParticleType.DEVICE_HARDWARE) self.assert_data_particle_parameters(data_particle, self._hardware_parameters, verify_values) def assert_particle_calibration(self, data_particle, verify_values = False): ''' Verify sample particle @param data_particle: SBE19CalibrationParticle calibration particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(SBE19CalibrationParticleKey, self._calibration_parameters) self.assert_data_particle_header(data_particle, DataParticleType.DEVICE_CALIBRATION) self.assert_data_particle_parameters(data_particle, self._calibration_parameters, verify_values) def assert_particle_status(self, data_particle, verify_values = False): ''' Verify status particle @param data_particle: SBE19StatusParticle status particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(SBE19StatusParticleKey, self._status_parameters) self.assert_data_particle_header(data_particle, DataParticleType.DEVICE_STATUS) self.assert_data_particle_parameters(data_particle, self._status_parameters, verify_values) def assert_particle_configuration(self, data_particle, verify_values = False): ''' Verify configuration particle @param data_particle: SBE19ConfigurationParticle configuration particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(SBE19ConfigurationParticleKey, self._configuration_parameters) self.assert_data_particle_header(data_particle, DataParticleType.DEVICE_CONFIGURATION) self.assert_data_particle_parameters(data_particle, self._configuration_parameters, verify_values) def assert_particle_send_optode(self, data_particle, verify_values = False): ''' Verify send optode particle @param data_particle: SBE19EventCounterParticle event counter particle @param verify_values: bool, should we verify parameter values ''' self.assert_data_particle_keys(OptodeSettingsParticleKey, self._send_optode_parameters) self.assert_data_particle_header(data_particle, DataParticleType.OPTODE_SETTINGS) self.assert_data_particle_parameters(data_particle, self._send_optode_parameters, verify_values) ############################################################################### # UNIT TESTS # # Unit tests test the method calls and parameters using Mock. # # # # These tests are especially useful for testing parsers and other data # # handling. The tests generally focus on small segments of code, like a # # single function call, but more complex code using Mock objects. However # # if you find yourself mocking too much maybe it is better as an # # integration test. # # # # Unit tests do not start up external processes like the port agent or # # driver process. # ############################################################################### @attr('UNIT', group='mi') class SBE19UnitTestCase(SeaBirdUnitTest, SeaBird19plusMixin): def test_driver_enums(self): """ Verify that all driver enumeration has no duplicate values that might cause confusion. Also do a little extra validation for the Capabilites """ self.assert_enum_has_no_duplicates(ScheduledJob()) self.assert_enum_has_no_duplicates(Command()) self.assert_enum_has_no_duplicates(SendOptodeCommand()) self.assert_enum_has_no_duplicates(DataParticleType()) self.assert_enum_has_no_duplicates(ProtocolState()) self.assert_enum_has_no_duplicates(ProtocolEvent()) self.assert_enum_has_no_duplicates(Parameter()) self.assert_enum_complete(ConfirmedParameter(), Parameter()) # Test capabilites for duplicates, then verify that capabilities is a subset of proto events self.assert_enum_has_no_duplicates(Capability()) self.assert_enum_complete(Capability(), ProtocolEvent()) def test_driver_schema(self): """ get the driver schema and verify it is configured properly """ driver = self.InstrumentDriver(self._got_data_event_callback) self.assert_driver_schema(driver, self._driver_parameters, self._driver_capabilities) def test_chunker(self): """ Test the chunker and verify the particles created. """ chunker = StringChunker(SBE19Protocol.sieve_function) self.assert_chunker_sample(chunker, self.VALID_SAMPLE) self.assert_chunker_sample_with_noise(chunker, self.VALID_SAMPLE) self.assert_chunker_fragmented_sample(chunker, self.VALID_SAMPLE) self.assert_chunker_combined_sample(chunker, self.VALID_SAMPLE) self.assert_chunker_sample(chunker, self.VALID_GETHD_RESPONSE) self.assert_chunker_sample_with_noise(chunker, self.VALID_GETHD_RESPONSE) self.assert_chunker_fragmented_sample(chunker, self.VALID_GETHD_RESPONSE) self.assert_chunker_combined_sample(chunker, self.VALID_GETHD_RESPONSE) self.assert_chunker_sample(chunker, self.VALID_GETCC_RESPONSE) self.assert_chunker_sample_with_noise(chunker, self.VALID_GETCC_RESPONSE) self.assert_chunker_fragmented_sample(chunker, self.VALID_GETCC_RESPONSE) self.assert_chunker_combined_sample(chunker, self.VALID_GETCC_RESPONSE) self.assert_chunker_sample(chunker, self.VALID_GETSD_RESPONSE) self.assert_chunker_sample_with_noise(chunker, self.VALID_GETSD_RESPONSE) self.assert_chunker_fragmented_sample(chunker, self.VALID_GETSD_RESPONSE) self.assert_chunker_combined_sample(chunker, self.VALID_GETSD_RESPONSE) self.assert_chunker_sample(chunker, self.VALID_GETCD_RESPONSE) self.assert_chunker_sample_with_noise(chunker, self.VALID_GETCD_RESPONSE) self.assert_chunker_fragmented_sample(chunker, self.VALID_GETCD_RESPONSE) self.assert_chunker_combined_sample(chunker, self.VALID_GETCD_RESPONSE) self.assert_chunker_sample(chunker, self.VALID_SEND_OPTODE_RESPONSE) self.assert_chunker_sample_with_noise(chunker, self.VALID_SEND_OPTODE_RESPONSE) self.assert_chunker_fragmented_sample(chunker, self.VALID_SEND_OPTODE_RESPONSE) self.assert_chunker_combined_sample(chunker, self.VALID_SEND_OPTODE_RESPONSE) def test_got_data(self): """ Verify sample data passed through the got data method produces the correct data particles """ # Create and initialize the instrument driver with a mock port agent driver = InstrumentDriver(self._got_data_event_callback) self.assert_initialize_driver(driver) self.assert_raw_particle_published(driver, True) # Start validating data particles self.assert_particle_published(driver, self.VALID_SAMPLE, self.assert_particle_sample, True) self.assert_particle_published(driver, self.VALID_GETHD_RESPONSE, self.assert_particle_hardware, True) self.assert_particle_published(driver, self.VALID_GETCC_RESPONSE, self.assert_particle_calibration, True) self.assert_particle_published(driver, self.VALID_GETSD_RESPONSE, self.assert_particle_status, True) self.assert_particle_published(driver, self.VALID_GETCD_RESPONSE, self.assert_particle_configuration, True) self.assert_particle_published(driver, self.VALID_SEND_OPTODE_RESPONSE, self.assert_particle_send_optode, True) def test_protocol_filter_capabilities(self): """ This tests driver filter_capabilities. Iterate through available capabilities, and verify that they can pass successfully through the filter. Test silly made up capabilities to verify they are blocked by filter. """ my_event_callback = Mock() protocol = SBE19Protocol(Prompt, NEWLINE, my_event_callback) driver_capabilities = Capability.list() test_capabilities = Capability.list() # Add a bogus capability that will be filtered out. test_capabilities.append("BOGUS_CAPABILITY") # Verify "BOGUS_CAPABILITY was filtered out self.assertEquals(driver_capabilities, protocol._filter_capabilities(test_capabilities)) def test_capabilities(self): """ Verify the FSM reports capabilities as expected. All states defined in this dict must also be defined in the protocol FSM. """ capabilities = { ProtocolState.UNKNOWN: ['DRIVER_EVENT_DISCOVER'], ProtocolState.COMMAND: ['DRIVER_EVENT_ACQUIRE_SAMPLE', 'DRIVER_EVENT_ACQUIRE_STATUS', 'PROTOCOL_EVENT_SCHEDULED_ACQUIRE_STATUS', 'DRIVER_EVENT_CLOCK_SYNC', 'DRIVER_EVENT_GET', 'DRIVER_EVENT_SET', 'DRIVER_EVENT_START_AUTOSAMPLE', 'DRIVER_EVENT_START_DIRECT', 'PROTOCOL_EVENT_GET_CONFIGURATION', 'DRIVER_EVENT_SCHEDULED_CLOCK_SYNC'], ProtocolState.AUTOSAMPLE: ['DRIVER_EVENT_GET', 'DRIVER_EVENT_STOP_AUTOSAMPLE', 'PROTOCOL_EVENT_GET_CONFIGURATION', 'DRIVER_EVENT_SCHEDULED_CLOCK_SYNC', 'PROTOCOL_EVENT_SCHEDULED_ACQUIRE_STATUS', 'DRIVER_EVENT_ACQUIRE_STATUS'], ProtocolState.DIRECT_ACCESS: ['DRIVER_EVENT_STOP_DIRECT', 'EXECUTE_DIRECT'] } driver = InstrumentDriver(self._got_data_event_callback) self.assert_capabilities(driver, capabilities) def test_parse_ds(self): """ Verify that the DS command gets parsed correctly and check that the param dict gets updated """ driver = self.InstrumentDriver(self._got_data_event_callback) self.assert_initialize_driver(driver, ProtocolState.COMMAND) source = self.VALID_DS_RESPONSE baseline = driver._protocol._param_dict.get_current_timestamp() # First verify that parse ds sets all know parameters. driver._protocol._parse_dsdc_response(source, Prompt.COMMAND) # Set param dict values not parsed in from the instrument response driver._protocol._param_dict.set_value(Parameter.CLOCK_INTERVAL, "00:00:00") driver._protocol._param_dict.set_value(Parameter.STATUS_INTERVAL, "00:00:00") pd = driver._protocol._param_dict.get_all(baseline) log.debug("Param Dict Values: %s" % pd) log.debug("Param Sample: %s" % source) self.assert_driver_parameters(pd, True) # Now change some things and make sure they are parsed properly # Note: Only checking parameters that can change. # Logging source = source.replace("= not logging", "= logging") log.debug("Param Sample: %s" % source) driver._protocol._parse_dsdc_response(source, Prompt.COMMAND) pd = driver._protocol._param_dict.get_all(baseline) self.assertTrue(pd.get(Parameter.LOGGING)) # NAvg source = source.replace("scans to average = 4", "scans to average = 2") log.debug("Param Sample: %s" % source) driver._protocol._parse_dsdc_response(source, Prompt.COMMAND) pd = driver._protocol._param_dict.get_all(baseline) self.assertEqual(pd.get(Parameter.NUM_AVG_SAMPLES), 2) # Optode source = source.replace("OPTODE = yes", "OPTODE = no") log.debug("Param Sample: %s" % source) driver._protocol._parse_dsdc_response(source, Prompt.COMMAND) pd = driver._protocol._param_dict.get_all(baseline) self.assertFalse(pd.get(Parameter.OPTODE)) def test_parse_set_response(self): """ Test response from set commands. """ driver = self.InstrumentDriver(self._got_data_event_callback) self.assert_initialize_driver(driver, ProtocolState.COMMAND) response = "Not an error" driver._protocol._parse_set_response(response, Prompt.EXECUTED) driver._protocol._parse_set_response(response, Prompt.COMMAND) with self.assertRaises(InstrumentProtocolException): driver._protocol._parse_set_response(response, Prompt.BAD_COMMAND) response = "<ERROR type='INVALID ARGUMENT' msg='out of range'/>" with self.assertRaises(InstrumentParameterException): driver._protocol._parse_set_response(response, Prompt.EXECUTED) ############################################################################### # INTEGRATION TESTS # # Integration test test the direct driver / instrument interaction # # but making direct calls via zeromq. # # - Common Integration tests test the driver through the instrument agent # # and common for all drivers (minimum requirement for ION ingestion) # ############################################################################### @attr('INT', group='mi') class SBE19IntegrationTest(SeaBirdIntegrationTest, SeaBird19plusMixin): def test_connection(self): self.assert_initialize_driver() def test_set(self): """ Test all set commands. Verify all exception cases. """ self.assert_initialize_driver() # Verify we can set all parameters in bulk new_values = { Parameter.PUMP_DELAY: 55, Parameter.NUM_AVG_SAMPLES: 2 } self.assert_set_bulk(new_values) # Pump Delay: Range 0 - 600 seconds self.assert_set(Parameter.PUMP_DELAY, 0) self.assert_set(Parameter.PUMP_DELAY, 600) # Test bad values self.assert_set_exception(Parameter.PUMP_DELAY, -1) self.assert_set_exception(Parameter.PUMP_DELAY, 601) self.assert_set_exception(Parameter.PUMP_DELAY, 'bad') # Num Avg Samples: Range 1 - 32767 self.assert_set(Parameter.NUM_AVG_SAMPLES, 1) self.assert_set(Parameter.NUM_AVG_SAMPLES, 32767) # Test bad values self.assert_set_exception(Parameter.NUM_AVG_SAMPLES, 0) self.assert_set_exception(Parameter.NUM_AVG_SAMPLES, 32768) self.assert_set_exception(Parameter.NUM_AVG_SAMPLES, 'bad') # Set params back to their default values self.assert_set(Parameter.PUMP_DELAY, 60) self.assert_set(Parameter.NUM_AVG_SAMPLES, 4) # Attempt to set Read only params self.assert_set_readonly(Parameter.DATE_TIME, '06032014113000') self.assert_set_readonly(Parameter.PTYPE, 1) self.assert_set_readonly(Parameter.VOLT0, False) self.assert_set_readonly(Parameter.VOLT1, False) self.assert_set_readonly(Parameter.VOLT2, True) self.assert_set_readonly(Parameter.VOLT3, True) self.assert_set_readonly(Parameter.VOLT4, True) self.assert_set_readonly(Parameter.VOLT5, True) self.assert_set_readonly(Parameter.SBE38, True) self.assert_set_readonly(Parameter.SBE63, True) self.assert_set_readonly(Parameter.WETLABS, True) self.assert_set_readonly(Parameter.GTD, True) self.assert_set_readonly(Parameter.DUAL_GTD, True) self.assert_set_readonly(Parameter.OPTODE, False) self.assert_set_readonly(Parameter.MIN_COND_FREQ, 400) self.assert_set_readonly(Parameter.OUTPUT_FORMAT, 1) self.assert_set_readonly(Parameter.LOGGING, True) self.assert_set_readonly(Parameter.AUTO_RUN, True) self.assert_set_readonly(Parameter.IGNORE_SWITCH, False) def test_commands(self): """ Run instrument commands from both command and streaming mode. """ self.assert_initialize_driver() #### # First test in command mode #### self.assert_driver_command(ProtocolEvent.CLOCK_SYNC) self.assert_driver_command(ProtocolEvent.SCHEDULED_CLOCK_SYNC) self.assert_driver_command(ProtocolEvent.ACQUIRE_SAMPLE) self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE, state=ProtocolState.COMMAND, delay=1) self.assert_driver_command(ProtocolEvent.ACQUIRE_STATUS) self.assert_driver_command(ProtocolEvent.GET_CONFIGURATION) # Invalid command/state transition: try to stop autosampling in command mode self.assert_driver_command_exception(ProtocolEvent.STOP_AUTOSAMPLE, exception_class=InstrumentCommandException) #### # Test in streaming mode #### # Put us in streaming self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_driver_command(ProtocolEvent.SCHEDULED_CLOCK_SYNC) self.assert_driver_command(ProtocolEvent.ACQUIRE_STATUS) self.assert_driver_command(ProtocolEvent.GET_CONFIGURATION) # Invalid command/state transitions self.assert_driver_command_exception(ProtocolEvent.CLOCK_SYNC, exception_class=InstrumentCommandException) self.assert_driver_command_exception(ProtocolEvent.ACQUIRE_SAMPLE, exception_class=InstrumentCommandException) self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE, state=ProtocolState.COMMAND, delay=1) #### # Test a bad command #### self.assert_driver_command_exception('ima_bad_command', exception_class=InstrumentCommandException) def test_parameters(self): """ Test driver parameters and verify their type. Also verify the parameter values for startup params. This test confirms that parameters are being read/converted properly and that the startup has been applied. """ self.assert_initialize_driver() reply = self.driver_client.cmd_dvr('get_resource', Parameter.ALL) self.assert_driver_parameters(reply, True) def test_startup_params(self): """ Verify that startup parameters are applied correctly. Generally this happens in the driver discovery method. """ # Explicitly verify these values after discover. They should match # what the startup values should be get_values = { Parameter.PTYPE: 1, Parameter.VOLT0: True, Parameter.VOLT1: True, Parameter.VOLT2: False, Parameter.VOLT3: False, Parameter.VOLT4: False, Parameter.VOLT5: False, Parameter.SBE38: False, Parameter.WETLABS: False, Parameter.GTD: False, Parameter.DUAL_GTD: False, Parameter.SBE63: False, Parameter.OPTODE: True, Parameter.OUTPUT_FORMAT: 0, Parameter.NUM_AVG_SAMPLES: 4, Parameter.MIN_COND_FREQ: 500, Parameter.PUMP_DELAY: 60, Parameter.AUTO_RUN: False, Parameter.IGNORE_SWITCH: True, Parameter.CLOCK_INTERVAL: '00:00:00', Parameter.STATUS_INTERVAL: '00:00:00' } # Change the values of these parameters to something before the # driver is reinitialized. They should be blown away on reinit. new_values = { Parameter.PUMP_DELAY: 55, Parameter.NUM_AVG_SAMPLES: 2, Parameter.CLOCK_INTERVAL: '00:10:00', Parameter.STATUS_INTERVAL: '00:20:00' } self.assert_initialize_driver() self.assert_startup_parameters(self.assert_driver_parameters, new_values, get_values) self.assert_set_bulk(new_values) # Start autosample and try again self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_startup_parameters(self.assert_driver_parameters) self.assert_current_state(ProtocolState.AUTOSAMPLE) #stop autosampling self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE, state=ProtocolState.COMMAND, delay=1) def test_status(self): self.assert_initialize_driver() # test acquire_status particles self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_STATUS, self.assert_particle_status) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_HARDWARE, self.assert_particle_hardware) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_CONFIGURATION, self.assert_particle_configuration) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_CALIBRATION, self.assert_particle_calibration) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.OPTODE_SETTINGS, self.assert_particle_send_optode) def test_configuration(self): self.assert_initialize_driver() # test get_configuration particle self.assert_particle_generation(ProtocolEvent.GET_CONFIGURATION, DataParticleType.DEVICE_CALIBRATION, self.assert_particle_calibration) def test_polled(self): """ Test that we can generate particles with commands while in command mode """ self.assert_initialize_driver() # test acquire_sample data particle self.assert_particle_generation(ProtocolEvent.ACQUIRE_SAMPLE, DataParticleType.CTD_PARSED, self.assert_particle_sample) def test_autosample(self): """ Verify that we can enter streaming and that all particles are produced properly. Because we have to test for many different data particles we can't use the common assert_sample_autosample method """ self.assert_initialize_driver() self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_async_particle_generation(DataParticleType.CTD_PARSED, self.assert_particle_sample, timeout=60) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_STATUS, self.assert_particle_status) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_HARDWARE, self.assert_particle_hardware) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_CONFIGURATION, self.assert_particle_configuration) self.assert_particle_generation(ProtocolEvent.ACQUIRE_STATUS, DataParticleType.DEVICE_CALIBRATION, self.assert_particle_calibration) self.assert_particle_generation(ProtocolEvent.GET_CONFIGURATION, DataParticleType.DEVICE_CALIBRATION, self.assert_particle_calibration) self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE, state=ProtocolState.COMMAND, delay=1) def test_scheduled_status_command(self): """ Verify the device status command can be triggered and run in command """ self.assert_initialize_driver() self.assert_set(Parameter.STATUS_INTERVAL, "00:00:20") # Verify that the event got scheduled self.assert_async_particle_generation(DataParticleType.DEVICE_STATUS, self.assert_particle_status, timeout=60) # Reset the interval self.assert_set(Parameter.STATUS_INTERVAL, "00:00:10") # Verify that the event got scheduled self.assert_async_particle_generation(DataParticleType.DEVICE_STATUS, self.assert_particle_status, timeout=30) # This should unschedule the acquire status event self.assert_set(Parameter.STATUS_INTERVAL, "00:00:00") # Now verify that no more status particles get generated, provide generous timeout failed = False try: self.assert_async_particle_generation(DataParticleType.DEVICE_STATUS, self.assert_particle_status, timeout=100) # We should never get here, failed should remain False failed = True except AssertionError: pass self.assertFalse(failed) self.assert_current_state(ProtocolState.COMMAND) def test_scheduled_status_autosample(self): """ Verify the device status command can be triggered and run in autosample """ self.assert_initialize_driver() self.assert_set(Parameter.STATUS_INTERVAL, "00:01:15") self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_current_state(ProtocolState.AUTOSAMPLE) #verify that the event got scheduled self.assert_async_particle_generation(DataParticleType.DEVICE_STATUS, self.assert_particle_status, timeout=90) self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE) def test_scheduled_clock_sync_command(self): """ Verify the scheduled clock sync is triggered and functions as expected """ self.assert_initialize_driver() #Set the clock sync interval to 10 seconds self.assert_set(Parameter.CLOCK_INTERVAL, "00:00:10") # Verification: Search log for 'clock sync interval: 10' # Allow for a couple of clock syncs to happen time.sleep(25) # Verification: Search log for 'Performing Clock Sync', should be seen at 10 second intervals # Reset the interval self.assert_set(Parameter.CLOCK_INTERVAL, "00:00:20") # Verification: Search log for 'clock sync interval: 20' # Allow for a couple of clock syncs to happen time.sleep(50) # Verification: Search log for 'Performing Clock Sync', should be seen at 20 second intervals # Set the interval to 0 so that the event is unscheduled self.assert_set(Parameter.CLOCK_INTERVAL, "00:00:00") # Verification: Search log for 'Removed scheduler for clock sync' self.assert_current_state(ProtocolState.COMMAND) def test_scheduled_clock_sync_autosample(self): """ Verify the scheduled clock sync is triggered and functions as expected """ self.assert_initialize_driver() #Set the clock sync interval to 90 seconds self.assert_set(Parameter.CLOCK_INTERVAL, "00:01:30") # Verification: Search log for 'clock sync interval: 90' # Get into autosample mode self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_current_state(ProtocolState.AUTOSAMPLE) # Allow for a clock sync to happen time.sleep(100) # Verification: Search log for 'Performing Clock Sync in autosample mode', # should be seen roughly 90 seconds after the interval was set self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE) ############################################################################### # QUALIFICATION TESTS # # Device specific qualification tests are for doing final testing of ion # # integration. The generally aren't used for instrument debugging and should # # be tackled after all unit and integration tests are complete # ############################################################################### @attr('QUAL', group='mi') class SBE19QualificationTest(SeaBirdQualificationTest, SeaBird19plusMixin): def setUp(self): SeaBirdQualificationTest.setUp(self) def test_direct_access_telnet_mode(self): """ @brief This test verifies that the Instrument Driver properly supports direct access to the physical instrument. (telnet mode) """ ### # First test direct access and exit with a go command # call. Also add a parameter change to verify DA # parameters are restored on DA exit. ### self.assert_enter_command_mode() self.assert_get_parameter(Parameter.OUTPUT_FORMAT, 0) # go into direct access, and muck up a setting. self.assert_direct_access_start_telnet() self.tcp_client.send_data("%soutputformat=1%s" % (NEWLINE, NEWLINE)) #need to sleep as the instrument needs time to apply the new param value time.sleep(5) # Verfy the param value got changed on the instrument self.tcp_client.send_data("%sGetCD%s" % (NEWLINE, NEWLINE)) self.tcp_client.expect("<OutputFormat>converted HEX</OutputFormat>") self.assert_direct_access_stop_telnet() # verify the setting remained unchanged in the param dict self.assert_enter_command_mode() self.assert_get_parameter(Parameter.OUTPUT_FORMAT, 0) def test_direct_access_telnet_mode_autosample(self): """ @brief Same as the previous DA test except in this test we force the instrument into streaming when in DA. Then we need to verify the transition back to the driver works as expected. """ self.assert_enter_command_mode() # go into direct access, and muck up a setting. self.assert_direct_access_start_telnet() self.assertTrue(self.tcp_client) #start logging self.tcp_client.send_data("%sstartnow%s" % (NEWLINE, NEWLINE)) time.sleep(2) #verify we're logging self.tcp_client.send_data("%sGetSD%s" % (NEWLINE, NEWLINE)) self.tcp_client.expect("<LoggingState>logging</LoggingState>") #Assert if stopping DA while autosampling, discover will put driver into Autosample state self.assert_direct_access_stop_telnet() self.assert_state_change(ResourceAgentState.STREAMING, ProtocolState.AUTOSAMPLE, timeout=10) #now stop autosampling self.assert_stop_autosample() def test_direct_access_telnet_timeout(self): """ Verify that direct access times out as expected and the agent transitions back to command mode. """ self.assert_enter_command_mode() # go into direct access self.assert_direct_access_start_telnet(timeout=30) self.assertTrue(self.tcp_client) self.assert_state_change(ResourceAgentState.IDLE, ProtocolState.COMMAND, 180) def test_direct_access_telnet_closed(self): """ Verify that a disconnection from the DA server transitions the agent back to command mode. """ self.assert_enter_command_mode() # go into direct access self.assert_direct_access_start_telnet(timeout=600) self.assertTrue(self.tcp_client) self.tcp_client.disconnect() self.assert_state_change(ResourceAgentState.IDLE, ProtocolState.COMMAND, 120) def test_poll(self): ''' Verify that we can poll for a sample. Take sample for this instrument Also poll for other engineering data streams. ''' self.assert_enter_command_mode() self.assert_particle_polled(ProtocolEvent.ACQUIRE_SAMPLE, self.assert_particle_sample, DataParticleType.CTD_PARSED, sample_count=1, timeout=30) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_status, DataParticleType.DEVICE_STATUS, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_hardware, DataParticleType.DEVICE_HARDWARE, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_configuration, DataParticleType.DEVICE_CONFIGURATION, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_send_optode, DataParticleType.OPTODE_SETTINGS, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.GET_CONFIGURATION, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=30) def test_autosample(self): """ Verify autosample works and data particles are created """ self.assert_enter_command_mode() self.assert_start_autosample() self.assert_particle_async(DataParticleType.CTD_PARSED, self.assert_particle_sample) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_status, DataParticleType.DEVICE_STATUS, sample_count=1, timeout=30) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_hardware, DataParticleType.DEVICE_HARDWARE, sample_count=1, timeout=30) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_configuration, DataParticleType.DEVICE_CONFIGURATION, sample_count=1, timeout=30) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=30) self.assert_particle_polled(ProtocolEvent.GET_CONFIGURATION, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=30) # Stop autosample and do run a couple commands. self.assert_stop_autosample() self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_status, DataParticleType.DEVICE_STATUS, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_hardware, DataParticleType.DEVICE_HARDWARE, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_configuration, DataParticleType.DEVICE_CONFIGURATION, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.ACQUIRE_STATUS, self.assert_particle_send_optode, DataParticleType.OPTODE_SETTINGS, sample_count=1, timeout=90) self.assert_particle_polled(ProtocolEvent.GET_CONFIGURATION, self.assert_particle_calibration, DataParticleType.DEVICE_CALIBRATION, sample_count=1, timeout=30) # Restart autosample and gather a couple samples self.assert_sample_autosample(self.assert_particle_sample, DataParticleType.CTD_PARSED) def test_execute_clock_sync(self): """ Verify we can synchronize the instrument internal clock """ self.assert_enter_command_mode() # Perform a clock sync! self.assert_execute_resource(ProtocolEvent.CLOCK_SYNC) # Call discover so that the driver gets the updated DateTime value from the instrument self.assert_reset() self.assert_discover(ResourceAgentState.COMMAND) # get the time from the driver check_new_params = self.instrument_agent_client.get_resource([Parameter.DATE_TIME]) # convert driver's time from formatted date/time string to seconds integer instrument_time = time.mktime(time.strptime(check_new_params.get(Parameter.DATE_TIME).lower(), "%d %b %Y %H:%M:%S")) # need to convert local machine's time to date/time string and back to seconds to 'drop' the DST attribute so test passes # get time from local machine lt = time.strftime("%d %b %Y %H:%M:%S", time.gmtime(time.mktime(time.localtime()))) # convert local time from formatted date/time string to seconds integer to drop DST local_time = time.mktime(time.strptime(lt, "%d %b %Y %H:%M:%S")) # Now verify that the time matches to within 10 seconds # The instrument time will be slightly behind as assert_discover takes a few seconds to complete self.assertLessEqual(abs(instrument_time - local_time), 10) def test_get_set_parameters(self): ''' verify that all parameters can be get set properly ''' self.assert_enter_command_mode() #attempt to change some parameters self.assert_set_parameter(Parameter.NUM_AVG_SAMPLES, 2) self.assert_set_parameter(Parameter.PUMP_DELAY, 55) #get parameters and verify values self.assert_get_parameter(Parameter.NUM_AVG_SAMPLES, 2) self.assert_get_parameter(Parameter.PUMP_DELAY, 55) #set parameters back to their default values self.assert_set_parameter(Parameter.NUM_AVG_SAMPLES, 4) self.assert_set_parameter(Parameter.PUMP_DELAY, 60) #get parameters and verify values self.assert_get_parameter(Parameter.NUM_AVG_SAMPLES, 4) self.assert_get_parameter(Parameter.PUMP_DELAY, 60) def test_get_capabilities(self): """ @brief Verify that the correct capabilities are returned from get_capabilities at various driver/agent states. """ self.assert_enter_command_mode() ################## # Command Mode ################## capabilities = { AgentCapabilityType.AGENT_COMMAND: self._common_agent_commands(ResourceAgentState.COMMAND), AgentCapabilityType.AGENT_PARAMETER: self._common_agent_parameters(), AgentCapabilityType.RESOURCE_COMMAND: [ ProtocolEvent.ACQUIRE_SAMPLE, ProtocolEvent.CLOCK_SYNC, ProtocolEvent.ACQUIRE_STATUS, ProtocolEvent.START_AUTOSAMPLE, ], AgentCapabilityType.RESOURCE_INTERFACE: None, AgentCapabilityType.RESOURCE_PARAMETER: self._driver_parameters.keys() } self.assert_capabilities(capabilities) ################## # Streaming Mode ################## capabilities[AgentCapabilityType.AGENT_COMMAND] = self._common_agent_commands(ResourceAgentState.STREAMING) capabilities[AgentCapabilityType.RESOURCE_COMMAND] = [ ProtocolEvent.STOP_AUTOSAMPLE, ProtocolEvent.ACQUIRE_STATUS, ] self.assert_start_autosample() self.assert_capabilities(capabilities) self.assert_stop_autosample() ################## # DA Mode ################## capabilities[AgentCapabilityType.AGENT_COMMAND] = self._common_agent_commands(ResourceAgentState.DIRECT_ACCESS) capabilities[AgentCapabilityType.RESOURCE_COMMAND] = [] self.assert_direct_access_start_telnet() self.assert_capabilities(capabilities) self.assert_direct_access_stop_telnet() ####################### # Uninitialized Mode ####################### capabilities[AgentCapabilityType.AGENT_COMMAND] = self._common_agent_commands(ResourceAgentState.UNINITIALIZED) capabilities[AgentCapabilityType.RESOURCE_COMMAND] = [] capabilities[AgentCapabilityType.RESOURCE_INTERFACE] = [] capabilities[AgentCapabilityType.RESOURCE_PARAMETER] = [] self.assert_reset() self.assert_capabilities(capabilities)
bsd-2-clause
incuna/django-orderable
orderable/models.py
6710
from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError, models, transaction from django.utils.html import format_html from .managers import OrderableManager class Orderable(models.Model): """ An orderable object that keeps all the instances in an enforced order. If there's a unique_together which includes the sort_order field then that will be used when checking for collisions etc. This works well for inlines, which can be manually reordered by entering numbers, and the save function will prevent against collisions. For main objects, you would want to also use "OrderableAdmin", which will make a nice jquery admin interface. """ sort_order = models.IntegerField(blank=True, db_index=True) objects = OrderableManager() class Meta: abstract = True ordering = ['sort_order'] def get_unique_fields(self): """List field names that are unique_together with `sort_order`.""" for unique_together in self._meta.unique_together: if 'sort_order' in unique_together: unique_fields = list(unique_together) unique_fields.remove('sort_order') return ['%s_id' % f for f in unique_fields] return [] def get_filtered_manager(self): manager = self.__class__.objects kwargs = {field: getattr(self, field) for field in self.get_unique_fields()} return manager.filter(**kwargs) def next(self): if not self.sort_order: return None return self.get_filtered_manager().after(self) def prev(self): if not self.sort_order: return None return self.get_filtered_manager().before(self) def validate_unique(self, exclude=None): if self._is_sort_order_unique_together_with_something(): exclude = exclude or [] if 'sort_order' not in exclude: exclude.append('sort_order') return super(Orderable, self).validate_unique(exclude=exclude) def _is_sort_order_unique_together_with_something(self): """ Is the sort_order field unique_together with something """ unique_together = self._meta.unique_together for fields in unique_together: if 'sort_order' in fields and len(fields) > 1: return True return False @staticmethod def _update(qs): """ Increment the sort_order in a queryset. Handle IntegrityErrors caused by unique constraints. """ try: with transaction.atomic(): qs.update(sort_order=models.F('sort_order') + 1) except IntegrityError: for obj in qs.order_by('-sort_order'): qs.filter(pk=obj.pk).update(sort_order=models.F('sort_order') + 1) def _save(self, objects, old_pos, new_pos): """WARNING: Intensive giggery-pokery zone.""" to_shift = objects.exclude(pk=self.pk) if self.pk else objects # If not set, insert at end. if self.sort_order is None: self._move_to_end(objects) # New insert. elif not self.pk and not old_pos: # Increment `sort_order` on objects with: # sort_order > new_pos. to_shift = to_shift.filter(sort_order__gte=self.sort_order) self._update(to_shift) self.sort_order = new_pos # self.sort_order decreased. elif old_pos and new_pos < old_pos: self._move_to_end(objects) super(Orderable, self).save() # Increment `sort_order` on objects with: # sort_order >= new_pos and sort_order < old_pos to_shift = to_shift.filter(sort_order__gte=new_pos, sort_order__lt=old_pos) self._update(to_shift) self.sort_order = new_pos # self.sort_order increased. elif old_pos and new_pos > old_pos: self._move_to_end(objects) super(Orderable, self).save() # Decrement sort_order on objects with: # sort_order <= new_pos and sort_order > old_pos. to_shift = to_shift.filter(sort_order__lte=new_pos, sort_order__gt=old_pos) to_shift.update(sort_order=models.F('sort_order') - 1) self.sort_order = new_pos def _move_to_end(self, objects): """Temporarily save `self.sort_order` elsewhere (max_obj).""" max_obj = objects.all().aggregate(models.Max('sort_order'))['sort_order__max'] self.sort_order = max_obj + 1 if max_obj else 1 def _unique_togethers_changed(self): for field in self.get_unique_fields(): if getattr(self, '_original_%s' % field, False): return True return False def save(self, *args, **kwargs): """Keep the unique order in sync.""" objects = self.get_filtered_manager() old_pos = getattr(self, '_original_sort_order', None) new_pos = self.sort_order if old_pos is None and self._unique_togethers_changed(): self.sort_order = None new_pos = None try: with transaction.atomic(): self._save(objects, old_pos, new_pos) except IntegrityError: with transaction.atomic(): old_pos = objects.filter(pk=self.pk).values_list( 'sort_order', flat=True)[0] self._save(objects, old_pos, new_pos) # Call the "real" save() method. super(Orderable, self).save(*args, **kwargs) def sort_order_display(self): return format_html( '<span id="neworder_{}" class="sorthandle">{}</span>', self.id, self.sort_order, ) sort_order_display.allow_tags = True sort_order_display.short_description = 'Order' sort_order_display.admin_order_field = 'sort_order' def __setattr__(self, attr, value): """ Cache original value of `sort_order` when a change is made to it. Also cache values of other unique together fields. Greatly inspired by http://code.google.com/p/django-audit/ """ if attr == 'sort_order' or attr in self.get_unique_fields(): try: current = self.__dict__[attr] except (AttributeError, KeyError, ObjectDoesNotExist): pass else: previously_set = getattr(self, '_original_%s' % attr, False) if current != value and not previously_set: setattr(self, '_original_%s' % attr, current) super(Orderable, self).__setattr__(attr, value)
bsd-2-clause
m312z/Mercs
src/core/controller/KeyboardController.java
1538
package core.controller; import org.lwjgl.input.Keyboard; import core.Frame; public class KeyboardController extends ShipController { boolean pausing; public KeyboardController(String player, int playerID) { super(player, playerID); } @Override public void pollInput() { // movement if(Keyboard.isKeyDown(Keyboard.KEY_UP)) direction.y = -1; else if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)) direction.y = 1; else direction.y = 0; if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)) direction.x = -1; else if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) direction.x = 1; else direction.x = 0; // shooting shooting = (Keyboard.isKeyDown(Keyboard.KEY_T)); powerButtons[0] = (Keyboard.isKeyDown(Keyboard.KEY_Q)); powerButtons[1] = (Keyboard.isKeyDown(Keyboard.KEY_W)); powerButtons[2] = (Keyboard.isKeyDown(Keyboard.KEY_E)); powerButtons[3] = (Keyboard.isKeyDown(Keyboard.KEY_R)); pausing = (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)); cursorPosition.x += direction.x*Frame.SCREEN_SIZE[0]/160f; cursorPosition.y += direction.y*Frame.SCREEN_SIZE[0]/160f; cursorPosition.x = clampCursor(cursorPosition.x,0,Frame.SCREEN_SIZE[0]-10); cursorPosition.y = clampCursor(cursorPosition.y,0,Frame.SCREEN_SIZE[1]-10); } @Override public boolean isSelecting() { return (powerButtons[0] || powerButtons[1] || powerButtons[2] || powerButtons[3] || shooting); } @Override public boolean isPausing() { return pausing; } }
bsd-2-clause
lino-framework/avanti
lino_avanti/lib/cv/models.py
1437
# -*- coding: UTF-8 -*- # Copyright 2021 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from lino_xl.lib.cv.models import * from lino.api import _ class Study(Study): class Meta(Study.Meta): abstract = dd.is_abstract_model(__name__, 'Study') foreign_education_level = dd.ForeignKey( 'cv.EducationLevel', verbose_name=_("Foreign education level"), related_name="studies_by_foreign_education_level", null=True, blank=True) recognized = models.BooleanField(_("Recognized in Belgium"), default=False) class StudyDetail(StudyDetail): main = """ person #start_date #end_date duration_text language type content education_level state #success foreign_education_level recognized school country city remarks """ StudiesByPerson.column_names = 'type content duration_text language school country state education_level foreign_education_level recognized remarks *' StudiesByPerson.insert_layout = """ type content duration_text language """ Experiences.detail_layout = """ person company country city #sector #function title status duration regime is_training #start_date #end_date duration_text termination_reason remarks """ ExperiencesByPerson.column_names = "company country duration_text function status termination_reason remarks *" dd.update_field(Experience, 'company', verbose_name=_("Work area"))
bsd-2-clause
BiuroCo/mega
src/win32/waiter.cpp
2900
/** * @file win32/wait.cpp * @brief Win32 event/timeout handling * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "megawaiter.h" namespace mega { dstime Waiter::ds; PGTC pGTC; static ULONGLONG tickhigh; static DWORD prevt; WinWaiter::WinWaiter() { if (!pGTC) pGTC = (PGTC)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetTickCount64"); if (!pGTC) { tickhigh = 0; prevt = 0; } pcsHTTP = NULL; externalEvent = CreateEvent(NULL, FALSE, FALSE, NULL); } // update monotonously increasing timestamp in deciseconds // FIXME: restore thread safety for applications using multiple MegaClient objects void Waiter::bumpds() { if (pGTC) { ds = pGTC() / 100; } else { // emulate GetTickCount64() on XP DWORD t = GetTickCount(); if (t < prevt) { tickhigh += 0x100000000; } prevt = t; ds = (t + tickhigh) / 100; } } // wait for events (socket, I/O completion, timeout + application events) // ds specifies the maximum amount of time to wait in deciseconds (or ~0 if no // timeout scheduled) // (this assumes that the second call to addhandle() was coming from the // network layer) int WinWaiter::wait() { int r = 0; // only allow interaction of asynccallback() with the main process while // waiting (because WinHTTP is threaded) if (pcsHTTP) { LeaveCriticalSection(pcsHTTP); } addhandle(externalEvent, NEEDEXEC); DWORD dwWaitResult = WaitForMultipleObjectsEx((DWORD)handles.size(), &handles.front(), FALSE, maxds * 100, TRUE); if (pcsHTTP) { EnterCriticalSection(pcsHTTP); } if ((dwWaitResult == WAIT_TIMEOUT) || (dwWaitResult == WAIT_IO_COMPLETION)) { r = NEEDEXEC; } else if ((dwWaitResult >= WAIT_OBJECT_0) && (dwWaitResult < WAIT_OBJECT_0 + flags.size())) { r = flags[dwWaitResult - WAIT_OBJECT_0]; } handles.clear(); flags.clear(); return r; } // add handle to the list - must not be called twice with the same handle // return true if handle added bool WinWaiter::addhandle(HANDLE handle, int flag) { handles.push_back(handle); flags.push_back(flag); return true; } void WinWaiter::notify() { SetEvent(externalEvent); } } // namespace
bsd-2-clause
EIDSS/EIDSS-Legacy
EIDSS v6.1/vb/EIDSS/EIDSS.RAM/LayoutForm/LayoutDetailPresenter.cs
4046
using System; using System.Collections.Generic; using System.ComponentModel; using eidss.avr.BaseComponents; using eidss.avr.BaseComponents.Views; using eidss.avr.db.AvrEventArgs.AvrEventArgs; using eidss.avr.db.Common; using eidss.avr.db.DBService; using eidss.avr.db.DBService.DataSource; using eidss.model.Avr.Commands; using eidss.model.Avr.Commands.Layout; using eidss.model.Avr.Commands.Models; using eidss.model.Avr.Commands.Refresh; namespace eidss.avr.LayoutForm { public sealed class LayoutDetailPresenter : RelatedObjectPresenter { private readonly ILayoutDetailView m_LayoutDetailView; private readonly Layout_DB m_LayoutDbService; private readonly LayoutMediator m_LayoutMediator; public LayoutDetailPresenter(SharedPresenter sharedPresenter, ILayoutDetailView view) : base(sharedPresenter, view) { m_LayoutDbService = new WinLayout_DB(m_SharedPresenter.SharedModel); m_LayoutDetailView = view; m_LayoutDetailView.DBService = m_LayoutDbService; m_LayoutMediator = new LayoutMediator(this); m_SharedPresenter.SharedModel.PropertyChanged += SharedModel_PropertyChanged; } public override void Dispose() { try { m_SharedPresenter.SharedModel.PropertyChanged -= SharedModel_PropertyChanged; } finally { base.Dispose(); } } public bool StandardReports { get { return m_SharedPresenter.SharedModel.StandardReports; } } public Layout_DB LayoutDbService { get { return m_LayoutDbService; } } public bool NewClicked { get; set; } public override void Process(Command cmd) { if ((cmd is QueryLayoutCommand)) { var layoutCommand = (cmd as QueryLayoutCommand); m_LayoutDetailView.ProcessQueryLayoutCommand(layoutCommand); } if ((cmd is RefreshPivotCommand)) { var refreshCommand = (cmd as RefreshPivotCommand); refreshCommand.State = CommandState.Pending; m_LayoutDetailView.PivotDetailView.RaisePivotGridDataLoadedCommand(); refreshCommand.State = CommandState.Processed; } } private void SharedModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { var property = (SharedProperty) (Enum.Parse(typeof (SharedProperty), e.PropertyName)); switch (property) { case SharedProperty.SelectedLayoutId: long layoutId = (m_SharedPresenter.SharedModel.SelectedLayoutId != m_SharedPresenter.SharedModel.SelectedFolderId) ? m_SharedPresenter.SharedModel.SelectedLayoutId : -1L; m_LayoutDetailView.OnLayoutSelected(new LayoutEventArgs(layoutId)); break; } } public bool ParentHasChanges() { return m_SharedPresenter.SharedModel.ParentForm.HasChanges(); } internal void PrepareDbService() { LayoutDbService.SetQueryID(SharedPresenter.SharedModel.SelectedQueryId); } internal void PrepareLayoutSearchFieldsBeforePost(IList<IAvrPivotGridField> fields) { LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable = m_LayoutMediator.LayoutDataSet.LayoutSearchField; long idflQuery = m_SharedPresenter.SharedModel.SelectedQueryId; long idflLayout = m_LayoutMediator.LayoutRow.idflLayout; AvrPivotGridHelper.PrepareLayoutSearchFieldsBeforePost(fields, searchFieldTable, idflQuery, idflLayout); } } }
bsd-2-clause