repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
mechdrew/ol3
examples/select-features.js
1939
goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.events.condition'); goog.require('ol.interaction.Select'); goog.require('ol.layer.Tile'); goog.require('ol.layer.Vector'); goog.require('ol.source.GeoJSON'); goog.require('ol.source.MapQuest'); var raster = new ol.layer.Tile({ source: new ol.source.MapQuest({layer: 'sat'}) }); var vector = new ol.layer.Vector({ source: new ol.source.GeoJSON({ projection: 'EPSG:3857', url: 'data/geojson/countries.geojson' }) }); var map = new ol.Map({ layers: [raster, vector], target: 'map', view: new ol.View({ center: [0, 0], zoom: 2 }) }); var select = null; // ref to currently selected interaction // select interaction working on "singleclick" var selectSingleClick = new ol.interaction.Select(); // select interaction working on "click" var selectClick = new ol.interaction.Select({ condition: ol.events.condition.click }); // select interaction working on "pointermove" var selectPointerMove = new ol.interaction.Select({ condition: ol.events.condition.pointerMove }); var selectElement = document.getElementById('type'); var changeInteraction = function() { if (select !== null) { map.removeInteraction(select); } var value = selectElement.value; if (value == 'singleclick') { select = selectSingleClick; } else if (value == 'click') { select = selectClick; } else if (value == 'pointermove') { select = selectPointerMove; } else { select = null; } if (select !== null) { map.addInteraction(select); select.on('select', function(e) { $('#status').html(' ' + e.target.getFeatures().getLength() + ' selected features (last operation selected ' + e.selected.length + ' and deselected ' + e.deselected.length + ' features)'); }); } }; /** * onchange callback on the select element. */ selectElement.onchange = changeInteraction; changeInteraction();
bsd-2-clause
leighpauls/k2cro4
webkit/plugins/ppapi/url_response_info_util.cc
2394
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/plugins/ppapi/url_response_info_util.h" #include "base/logging.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPHeaderVisitor.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" #include "webkit/base/file_path_string_conversions.h" #include "webkit/plugins/ppapi/ppb_file_ref_impl.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebHTTPHeaderVisitor; using WebKit::WebString; using WebKit::WebURLResponse; namespace webkit { namespace ppapi { namespace { class HeaderFlattener : public WebHTTPHeaderVisitor { public: const std::string& buffer() const { return buffer_; } virtual void visitHeader(const WebString& name, const WebString& value) { if (!buffer_.empty()) buffer_.append("\n"); buffer_.append(name.utf8()); buffer_.append(": "); buffer_.append(value.utf8()); } private: std::string buffer_; }; bool IsRedirect(int32_t status) { return status >= 300 && status <= 399; } } // namespace ::ppapi::URLResponseInfoData DataFromWebURLResponse( PP_Instance pp_instance, const WebURLResponse& response) { ::ppapi::URLResponseInfoData data; data.url = response.url().spec(); data.status_code = response.httpStatusCode(); data.status_text = response.httpStatusText().utf8(); if (IsRedirect(data.status_code)) { data.redirect_url = response.httpHeaderField( WebString::fromUTF8("Location")).utf8(); } HeaderFlattener flattener; response.visitHTTPHeaderFields(&flattener); data.headers = flattener.buffer(); WebString file_path = response.downloadFilePath(); if (!file_path.isEmpty()) { scoped_refptr<PPB_FileRef_Impl> file_ref( PPB_FileRef_Impl::CreateExternal( pp_instance, webkit_base::WebStringToFilePath(file_path), std::string())); data.body_as_file_ref = file_ref->GetCreateInfo(); file_ref->GetReference(); // The returned data has one ref for the plugin. } return data; } } // namespace ppapi } // namespace webkit
bsd-3-clause
eurogiciel-oss/ozone-wayland
platform/ozone_platform_wayland.h
1886
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef OZONE_PLATFORM_OZONE_PLATFORM_WAYLAND_H_ #define OZONE_PLATFORM_OZONE_PLATFORM_WAYLAND_H_ #if defined(TOOLKIT_VIEWS) && !defined(OS_CHROMEOS) #include "ozone/ui/desktop_aura/desktop_factory_wayland.h" #endif #include "ozone/ui/events/event_factory_ozone_wayland.h" #include "ozone/ui/gfx/surface_factory_wayland.h" #include "ozone/ui/ime/input_method_context_factory_wayland.h" #include "ozone/wayland/ozone_hardware_display.h" #include "ui/base/cursor/ozone/cursor_factory_ozone.h" #include "ui/ozone/ozone_platform.h" namespace ui { // OzonePlatform for Wayland // // This platform is Linux with the wayland display server. class OzonePlatformWayland : public OzonePlatform { public: OzonePlatformWayland(); virtual ~OzonePlatformWayland(); virtual gfx::SurfaceFactoryOzone* GetSurfaceFactoryOzone() OVERRIDE; virtual ui::EventFactoryOzone* GetEventFactoryOzone() OVERRIDE; virtual ui::InputMethodContextFactoryOzone* GetInputMethodContextFactoryOzone() OVERRIDE; virtual ui::CursorFactoryOzone* GetCursorFactoryOzone() OVERRIDE; private: ozonewayland::OzoneHardwareDisplay hardware_display_; gfx::SurfaceFactoryWayland surface_factory_ozone_; ui::EventFactoryOzoneWayland event_factory_ozone_; ui::InputMethodContextFactoryWayland input_method_context_factory_; ui::CursorFactoryOzone cursor_factory_ozone_; #if defined(TOOLKIT_VIEWS) && !defined(OS_CHROMEOS) views::DesktopFactoryWayland desktop_factory_ozone_; #endif DISALLOW_COPY_AND_ASSIGN(OzonePlatformWayland); }; // Constructor hook for use in ozone_platform_list.cc OZONE_WAYLAND_EXPORT OzonePlatform* CreateOzonePlatformWayland(); } // namespace ui #endif // OZONE_PLATFORM_OZONE_PLATFORM_WAYLAND_H_
bsd-3-clause
girc/dmis
common/modules/reporting/widgets/emergency_situation/Create.php
2168
<?php /** * Created by PhpStorm. * User: User * Date: 2/24/2015 * Time: 12:18 PM */ namespace common\modules\reporting\widgets\emergency_situation; use common\modules\reporting\models\EmergencySituation; use yii\base\Exception; use yii\base\Widget; use yii\helpers\Json; use yii\web\View; class Create extends Widget { public $actionRoute; public $model; public $mapDivId; public $widgetId; public $clientOptions; public $juiDialogOptions; public $jqToggleBtnSelector; public $formId; public $jQueryFormSelector; public function init() { if(!$this->actionRoute){ throw new Exception( 'route to the action to which the form to be submitted must be specified! Example :: /girc/dmis/frontend/web/site/event-create' ); } $this->formId=($this->formId)?$this->formId:'formEventCreate'; $this->jQueryFormSelector = '#'.$this->formId; $this->widgetId=($this->widgetId)?$this->widgetId:$this->id; $this->clientOptions['formId']=$this->formId; $this->clientOptions['actionRoute']=$this->actionRoute; $this->clientOptions['widgetId']=$this->widgetId; $this->clientOptions['jqToggleBtnSelector']=$this->jqToggleBtnSelector; $this->clientOptions = Json::encode($this->clientOptions); $this->registerClientScripts(); } public function run() { $this->model = new EmergencySituation(); return $this->render('_form', [ 'model'=>$this->model, 'formId'=>$this->formId, 'jQueryFormSelector'=>$this->jQueryFormSelector, 'actionRoute'=>$this->actionRoute, 'widgetId'=>$this->widgetId, 'jqToggleBtnSelector'=>$this->jqToggleBtnSelector, 'clientOptions'=>$this->clientOptions, ]); } public function registerClientScripts(){ \common\assets\YiiAjaxFormSubmitAsset::register($this->getView()); $this->getView()->registerJs("$('#$this->widgetId').yiiAjaxFormWidget($this->clientOptions);", View::POS_READY); } }
bsd-3-clause
hasadna/OpenTrain
webserver/opentrain/manage.py
252
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opentrain.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
bsd-3-clause
joshlin/expo2
db/migrate/207_add_question_and_display_as_and_sequence_to_evaluation_question.rb
570
class AddQuestionAndDisplayAsAndSequenceToEvaluationQuestion < ActiveRecord::Migration def self.up add_column :evaluation_questions, :question, :text add_column :evaluation_questions, :display_as, :string add_column :evaluation_questions, :sequence, :integer add_column :evaluation_questions, :required, :boolean end def self.down remove_column :evaluation_questions, :required remove_column :evaluation_questions, :sequence remove_column :evaluation_questions, :display_as remove_column :evaluation_questions, :question end end
bsd-3-clause
ds-hwang/chromium-crosswalk
build/vs_toolchain.py
13647
#!/usr/bin/env python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import json import os import pipes import shutil import subprocess import sys script_dir = os.path.dirname(os.path.realpath(__file__)) chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir)) SRC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib')) json_data_file = os.path.join(script_dir, 'win_toolchain.json') import gyp # Use MSVS2013 as the default toolchain. CURRENT_DEFAULT_TOOLCHAIN_VERSION = '2013' def SetEnvironmentAndGetRuntimeDllDirs(): """Sets up os.environ to use the depot_tools VS toolchain with gyp, and returns the location of the VS runtime DLLs so they can be copied into the output directory after gyp generation. """ vs_runtime_dll_dirs = None depot_tools_win_toolchain = \ bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))) # When running on a non-Windows host, only do this if the SDK has explicitly # been downloaded before (in which case json_data_file will exist). if ((sys.platform in ('win32', 'cygwin') or os.path.exists(json_data_file)) and depot_tools_win_toolchain): if ShouldUpdateToolchain(): Update() with open(json_data_file, 'r') as tempf: toolchain_data = json.load(tempf) toolchain = toolchain_data['path'] version = toolchain_data['version'] win_sdk = toolchain_data.get('win_sdk') if not win_sdk: win_sdk = toolchain_data['win8sdk'] wdk = toolchain_data['wdk'] # TODO(scottmg): The order unfortunately matters in these. They should be # split into separate keys for x86 and x64. (See CopyVsRuntimeDlls call # below). http://crbug.com/345992 vs_runtime_dll_dirs = toolchain_data['runtime_dirs'] os.environ['GYP_MSVS_OVERRIDE_PATH'] = toolchain os.environ['GYP_MSVS_VERSION'] = version # We need to make sure windows_sdk_path is set to the automated # toolchain values in GYP_DEFINES, but don't want to override any # otheroptions.express # values there. gyp_defines_dict = gyp.NameValueListToDict(gyp.ShlexEnv('GYP_DEFINES')) gyp_defines_dict['windows_sdk_path'] = win_sdk os.environ['GYP_DEFINES'] = ' '.join('%s=%s' % (k, pipes.quote(str(v))) for k, v in gyp_defines_dict.iteritems()) os.environ['WINDOWSSDKDIR'] = win_sdk os.environ['WDK_DIR'] = wdk # Include the VS runtime in the PATH in case it's not machine-installed. runtime_path = os.path.pathsep.join(vs_runtime_dll_dirs) os.environ['PATH'] = runtime_path + os.path.pathsep + os.environ['PATH'] elif sys.platform == 'win32' and not depot_tools_win_toolchain: if not 'GYP_MSVS_OVERRIDE_PATH' in os.environ: os.environ['GYP_MSVS_OVERRIDE_PATH'] = DetectVisualStudioPath() if not 'GYP_MSVS_VERSION' in os.environ: os.environ['GYP_MSVS_VERSION'] = GetVisualStudioVersion() return vs_runtime_dll_dirs def _RegistryGetValueUsingWinReg(key, value): """Use the _winreg module to obtain the value of a registry key. Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure. Throws ImportError if _winreg is unavailable. """ import _winreg try: root, subkey = key.split('\\', 1) assert root == 'HKLM' # Only need HKLM for now. with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey: return _winreg.QueryValueEx(hkey, value)[0] except WindowsError: return None def _RegistryGetValue(key, value): try: return _RegistryGetValueUsingWinReg(key, value) except ImportError: raise Exception('The python library _winreg not found.') def GetVisualStudioVersion(): """Return GYP_MSVS_VERSION of Visual Studio. """ return os.environ.get('GYP_MSVS_VERSION', CURRENT_DEFAULT_TOOLCHAIN_VERSION) def DetectVisualStudioPath(): """Return path to the GYP_MSVS_VERSION of Visual Studio. """ # Note that this code is used from # build/toolchain/win/setup_toolchain.py as well. version_as_year = GetVisualStudioVersion() year_to_version = { '2013': '12.0', '2015': '14.0', } if version_as_year not in year_to_version: raise Exception(('Visual Studio version %s (from GYP_MSVS_VERSION)' ' not supported. Supported versions are: %s') % ( version_as_year, ', '.join(year_to_version.keys()))) version = year_to_version[version_as_year] keys = [r'HKLM\Software\Microsoft\VisualStudio\%s' % version, r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s' % version] for key in keys: path = _RegistryGetValue(key, 'InstallDir') if not path: continue path = os.path.normpath(os.path.join(path, '..', '..')) return path raise Exception(('Visual Studio Version %s (from GYP_MSVS_VERSION)' ' not found.') % (version_as_year)) def _VersionNumber(): """Gets the standard version number ('120', '140', etc.) based on GYP_MSVS_VERSION.""" vs_version = GetVisualStudioVersion() if vs_version == '2013': return '120' elif vs_version == '2015': return '140' else: raise ValueError('Unexpected GYP_MSVS_VERSION') def _CopyRuntimeImpl(target, source, verbose=True): """Copy |source| to |target| if it doesn't already exist or if it needs to be updated. """ if (os.path.isdir(os.path.dirname(target)) and (not os.path.isfile(target) or os.stat(target).st_mtime != os.stat(source).st_mtime)): if verbose: print 'Copying %s to %s...' % (source, target) if os.path.exists(target): os.unlink(target) shutil.copy2(source, target) def _CopyRuntime2013(target_dir, source_dir, dll_pattern): """Copy both the msvcr and msvcp runtime DLLs, only if the target doesn't exist, but the target directory does exist.""" for file_part in ('p', 'r'): dll = dll_pattern % file_part target = os.path.join(target_dir, dll) source = os.path.join(source_dir, dll) _CopyRuntimeImpl(target, source) def _CopyRuntime2015(target_dir, source_dir, dll_pattern, suffix): """Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't exist, but the target directory does exist.""" for file_part in ('msvcp', 'vccorlib', 'vcruntime'): dll = dll_pattern % file_part target = os.path.join(target_dir, dll) source = os.path.join(source_dir, dll) _CopyRuntimeImpl(target, source) ucrt_src_dir = os.path.join(source_dir, 'api-ms-win-*.dll') print 'Copying %s to %s...' % (ucrt_src_dir, target_dir) for ucrt_src_file in glob.glob(ucrt_src_dir): file_part = os.path.basename(ucrt_src_file) ucrt_dst_file = os.path.join(target_dir, file_part) _CopyRuntimeImpl(ucrt_dst_file, ucrt_src_file, False) _CopyRuntimeImpl(os.path.join(target_dir, 'ucrtbase' + suffix), os.path.join(source_dir, 'ucrtbase' + suffix)) def _CopyRuntime(target_dir, source_dir, target_cpu, debug): """Copy the VS runtime DLLs, only if the target doesn't exist, but the target directory does exist. Handles VS 2013 and VS 2015.""" suffix = "d.dll" if debug else ".dll" if GetVisualStudioVersion() == '2015': _CopyRuntime2015(target_dir, source_dir, '%s140' + suffix, suffix) else: _CopyRuntime2013(target_dir, source_dir, 'msvc%s120' + suffix) # Copy the PGO runtime library to the release directories. if not debug and os.environ.get('GYP_MSVS_OVERRIDE_PATH'): pgo_x86_runtime_dir = os.path.join(os.environ.get('GYP_MSVS_OVERRIDE_PATH'), 'VC', 'bin') pgo_x64_runtime_dir = os.path.join(pgo_x86_runtime_dir, 'amd64') pgo_runtime_dll = 'pgort' + _VersionNumber() + '.dll' if target_cpu == "x86": source_x86 = os.path.join(pgo_x86_runtime_dir, pgo_runtime_dll) if os.path.exists(source_x86): _CopyRuntimeImpl(os.path.join(target_dir, pgo_runtime_dll), source_x86) elif target_cpu == "x64": source_x64 = os.path.join(pgo_x64_runtime_dir, pgo_runtime_dll) if os.path.exists(source_x64): _CopyRuntimeImpl(os.path.join(target_dir, pgo_runtime_dll), source_x64) else: raise NotImplementedError("Unexpected target_cpu value:" + target_cpu) def CopyVsRuntimeDlls(output_dir, runtime_dirs): """Copies the VS runtime DLLs from the given |runtime_dirs| to the output directory so that even if not system-installed, built binaries are likely to be able to run. This needs to be run after gyp has been run so that the expected target output directories are already created. This is used for the GYP build and gclient runhooks. """ x86, x64 = runtime_dirs out_debug = os.path.join(output_dir, 'Debug') out_debug_nacl64 = os.path.join(output_dir, 'Debug', 'x64') out_release = os.path.join(output_dir, 'Release') out_release_nacl64 = os.path.join(output_dir, 'Release', 'x64') out_debug_x64 = os.path.join(output_dir, 'Debug_x64') out_release_x64 = os.path.join(output_dir, 'Release_x64') if os.path.exists(out_debug) and not os.path.exists(out_debug_nacl64): os.makedirs(out_debug_nacl64) if os.path.exists(out_release) and not os.path.exists(out_release_nacl64): os.makedirs(out_release_nacl64) _CopyRuntime(out_debug, x86, "x86", debug=True) _CopyRuntime(out_release, x86, "x86", debug=False) _CopyRuntime(out_debug_x64, x64, "x64", debug=True) _CopyRuntime(out_release_x64, x64, "x64", debug=False) _CopyRuntime(out_debug_nacl64, x64, "x64", debug=True) _CopyRuntime(out_release_nacl64, x64, "x64", debug=False) def CopyDlls(target_dir, configuration, target_cpu): """Copy the VS runtime DLLs into the requested directory as needed. configuration is one of 'Debug' or 'Release'. target_cpu is one of 'x86' or 'x64'. The debug configuration gets both the debug and release DLLs; the release config only the latter. This is used for the GN build. """ vs_runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs() if not vs_runtime_dll_dirs: return x64_runtime, x86_runtime = vs_runtime_dll_dirs runtime_dir = x64_runtime if target_cpu == 'x64' else x86_runtime _CopyRuntime(target_dir, runtime_dir, target_cpu, debug=False) if configuration == 'Debug': _CopyRuntime(target_dir, runtime_dir, target_cpu, debug=True) def _GetDesiredVsToolchainHashes(): """Load a list of SHA1s corresponding to the toolchains that we want installed to build with.""" if GetVisualStudioVersion() == '2015': # Update 1 with hot fixes. return ['b349b3cc596d5f7e13d649532ddd7e8db39db0cb'] else: # Default to VS2013. return ['4087e065abebdca6dbd0caca2910c6718d2ec67f'] def ShouldUpdateToolchain(): """Check if the toolchain should be upgraded.""" if not os.path.exists(json_data_file): return True with open(json_data_file, 'r') as tempf: toolchain_data = json.load(tempf) version = toolchain_data['version'] env_version = GetVisualStudioVersion() # If there's a mismatch between the version set in the environment and the one # in the json file then the toolchain should be updated. return version != env_version def Update(force=False): """Requests an update of the toolchain to the specific hashes we have at this revision. The update outputs a .json of the various configuration information required to pass to gyp which we use in |GetToolchainDir()|. """ if force != False and force != '--force': print >>sys.stderr, 'Unknown parameter "%s"' % force return 1 if force == '--force' or os.path.exists(json_data_file): force = True depot_tools_win_toolchain = \ bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))) if ((sys.platform in ('win32', 'cygwin') or force) and depot_tools_win_toolchain): import find_depot_tools depot_tools_path = find_depot_tools.add_depot_tools_to_path() get_toolchain_args = [ sys.executable, os.path.join(depot_tools_path, 'win_toolchain', 'get_toolchain_if_necessary.py'), '--output-json', json_data_file, ] + _GetDesiredVsToolchainHashes() if force: get_toolchain_args.append('--force') subprocess.check_call(get_toolchain_args) return 0 def GetToolchainDir(): """Gets location information about the current toolchain (must have been previously updated by 'update'). This is used for the GN build.""" runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs() # If WINDOWSSDKDIR is not set, search the default SDK path and set it. if not 'WINDOWSSDKDIR' in os.environ: default_sdk_path = 'C:\\Program Files (x86)\\Windows Kits\\10' if os.path.isdir(default_sdk_path): os.environ['WINDOWSSDKDIR'] = default_sdk_path print '''vs_path = "%s" sdk_path = "%s" vs_version = "%s" wdk_dir = "%s" runtime_dirs = "%s" ''' % ( os.environ['GYP_MSVS_OVERRIDE_PATH'], os.environ['WINDOWSSDKDIR'], GetVisualStudioVersion(), os.environ.get('WDK_DIR', ''), os.path.pathsep.join(runtime_dll_dirs or ['None'])) def main(): commands = { 'update': Update, 'get_toolchain_dir': GetToolchainDir, 'copy_dlls': CopyDlls, } if len(sys.argv) < 2 or sys.argv[1] not in commands: print >>sys.stderr, 'Expected one of: %s' % ', '.join(commands) return 1 return commands[sys.argv[1]](*sys.argv[2:]) if __name__ == '__main__': sys.exit(main())
bsd-3-clause
leiferikb/bitpop-private
chrome/renderer/resources/extensions/searchbox_api.js
10187
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var chrome; if (!chrome) chrome = {}; if (!chrome.searchBox) { chrome.searchBox = new function() { var safeObjects = {}; chrome.searchBoxOnWindowReady = function() { // |searchBoxOnWindowReady| is used for initializing window context and // should be called only once per context. safeObjects.createShadowRoot = Element.prototype.webkitCreateShadowRoot; safeObjects.defineProperty = Object.defineProperty; delete window.chrome.searchBoxOnWindowReady; }; // ========================================================================= // Constants // ========================================================================= var MAX_CLIENT_SUGGESTIONS_TO_DEDUPE = 6; var MAX_ALLOWED_DEDUPE_ATTEMPTS = 5; var HTTP_REGEX = /^https?:\/\//; var WWW_REGEX = /^www\./; // ========================================================================= // Private functions // ========================================================================= native function GetQuery(); native function GetVerbatim(); native function GetSelectionStart(); native function GetSelectionEnd(); native function GetX(); native function GetY(); native function GetWidth(); native function GetHeight(); native function GetStartMargin(); native function GetEndMargin(); native function GetRightToLeft(); native function GetAutocompleteResults(); native function GetContext(); native function GetDisplayInstantResults(); native function GetFont(); native function GetFontSize(); native function GetThemeBackgroundInfo(); native function GetThemeAreaHeight(); native function IsKeyCaptureEnabled(); native function NavigateContentWindow(); native function SetSuggestions(); native function SetQuerySuggestion(); native function SetQuerySuggestionFromAutocompleteResult(); native function SetQuery(); native function SetQueryFromAutocompleteResult(); native function Show(); native function StartCapturingKeyStrokes(); native function StopCapturingKeyStrokes(); function escapeHTML(text) { return text.replace(/[<>&"']/g, function(match) { switch (match) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; case '"': return '&quot;'; case "'": return '&apos;'; } }); } // Returns the |restrictedText| wrapped in a ShadowDOM. function SafeWrap(restrictedText) { var node = document.createElement('div'); var nodeShadow = safeObjects.createShadowRoot.apply(node); nodeShadow.applyAuthorStyles = true; nodeShadow.innerHTML = '<div style="width:700px!important;' + ' height:22px!important;' + ' font-family:\'' + GetFont() + '\',\'Arial\'!important;' + ' overflow:hidden!important;' + ' text-overflow:ellipsis!important">' + ' <nobr>' + restrictedText + '</nobr>' + '</div>'; safeObjects.defineProperty(node, 'webkitShadowRoot', { value: null }); return node; } // Wraps the AutocompleteResult query and URL into ShadowDOM nodes so that // the JS cannot access them and deletes the raw values. function GetAutocompleteResultsWrapper() { var autocompleteResults = DedupeAutocompleteResults( GetAutocompleteResults()); var userInput = GetQuery(); for (var i = 0, result; result = autocompleteResults[i]; ++i) { var title = escapeHTML(result.contents); var url = escapeHTML(CleanUrl(result.destination_url, userInput)); var combinedHtml = '<span class=chrome_url>' + url + '</span>'; if (title) { result.titleNode = SafeWrap(title); combinedHtml += '<span class=chrome_separator> &ndash; </span>' + '<span class=chrome_title>' + title + '</span>'; } result.urlNode = SafeWrap(url); result.combinedNode = SafeWrap(combinedHtml); delete result.contents; delete result.destination_url; } return autocompleteResults; } // TODO(dcblack): Do this in C++ instead of JS. function CleanUrl(url, userInput) { if (url.indexOf(userInput) == 0) { return url; } url = url.replace(HTTP_REGEX, ''); if (url.indexOf(userInput) == 0) { return url; } return url.replace(WWW_REGEX, ''); } // TODO(dcblack): Do this in C++ instead of JS. function CanonicalizeUrl(url) { return url.replace(HTTP_REGEX, '').replace(WWW_REGEX, ''); } // Removes duplicates from AutocompleteResults. // TODO(dcblack): Do this in C++ instead of JS. function DedupeAutocompleteResults(autocompleteResults) { var urlToResultMap = {}; for (var i = 0, result; result = autocompleteResults[i]; ++i) { var url = CanonicalizeUrl(result.destination_url); if (url in urlToResultMap) { var oldRelevance = urlToResultMap[url].rankingData.relevance; var newRelevance = result.rankingData.relevance; if (newRelevance > oldRelevance) { urlToResultMap[url] = result; } } else { urlToResultMap[url] = result; } } var dedupedResults = []; for (url in urlToResultMap) { dedupedResults.push(urlToResultMap[url]); } return dedupedResults; } var lastPrefixQueriedForDuplicates = ''; var numDedupeAttempts = 0; function DedupeClientSuggestions(clientSuggestions) { var userInput = GetQuery(); if (userInput == lastPrefixQueriedForDuplicates) { numDedupeAttempts += 1; if (numDedupeAttempts > MAX_ALLOWED_DEDUPE_ATTEMPTS) { // Request blocked for privacy reasons. // TODO(dcblack): This check is insufficient. We should have a check // such that it's only callable once per onnativesuggestions, not // once per prefix. Also, there is a timing problem where if the user // types quickly then the client will (correctly) attempt to render // stale results, and end up calling dedupe multiple times when // getValue shows the same prefix. A better solution would be to have // the client send up rid ranges to dedupe against and have the // binary keep around all the old suggestions ever given to this // overlay. I suspect such an approach would clean up this code quite // a bit. return false; } } else { lastPrefixQueriedForDuplicates = userInput; numDedupeAttempts = 1; } var autocompleteResults = GetAutocompleteResults(); var nativeUrls = {}; for (var i = 0, result; result = autocompleteResults[i]; ++i) { var nativeUrl = CanonicalizeUrl(result.destination_url); nativeUrls[nativeUrl] = result.rid; } for (var i = 0; clientSuggestions[i] && i < MAX_CLIENT_SUGGESTIONS_TO_DEDUPE; ++i) { var result = clientSuggestions[i]; if (result.url) { var clientUrl = CanonicalizeUrl(result.url); if (clientUrl in nativeUrls) { result.duplicateOf = nativeUrls[clientUrl]; } } } return true; } // ========================================================================= // Exported functions // ========================================================================= this.__defineGetter__('value', GetQuery); this.__defineGetter__('verbatim', GetVerbatim); this.__defineGetter__('selectionStart', GetSelectionStart); this.__defineGetter__('selectionEnd', GetSelectionEnd); this.__defineGetter__('x', GetX); this.__defineGetter__('y', GetY); this.__defineGetter__('width', GetWidth); this.__defineGetter__('height', GetHeight); this.__defineGetter__('startMargin', GetStartMargin); this.__defineGetter__('endMargin', GetEndMargin); this.__defineGetter__('rtl', GetRightToLeft); this.__defineGetter__('nativeSuggestions', GetAutocompleteResultsWrapper); this.__defineGetter__('isKeyCaptureEnabled', IsKeyCaptureEnabled); this.__defineGetter__('context', GetContext); this.__defineGetter__('displayInstantResults', GetDisplayInstantResults); this.__defineGetter__('themeBackgroundInfo', GetThemeBackgroundInfo); this.__defineGetter__('themeAreaHeight', GetThemeAreaHeight); this.__defineGetter__('font', GetFont); this.__defineGetter__('fontSize', GetFontSize); this.setSuggestions = function(text) { SetSuggestions(text); }; this.setAutocompleteText = function(text, behavior) { SetQuerySuggestion(text, behavior); }; this.setRestrictedAutocompleteText = function(resultId) { SetQuerySuggestionFromAutocompleteResult(resultId); }; this.setValue = function(text, type) { SetQuery(text, type); }; this.setRestrictedValue = function(resultId) { SetQueryFromAutocompleteResult(resultId); }; this.show = function(reason, height) { Show(reason, height); }; this.markDuplicateSuggestions = function(clientSuggestions) { return DedupeClientSuggestions(clientSuggestions); }; this.navigateContentWindow = function(destination) { return NavigateContentWindow(destination); }; this.startCapturingKeyStrokes = function() { StartCapturingKeyStrokes(); }; this.stopCapturingKeyStrokes = function() { StopCapturingKeyStrokes(); }; this.onchange = null; this.onsubmit = null; this.oncancel = null; this.onresize = null; this.onautocompleteresults = null; this.onkeypress = null; this.onkeycapturechange = null; this.oncontextchange = null; this.onmarginchange = null; }; }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE252_Unchecked_Return_Value/CWE252_Unchecked_Return_Value__char_snprintf_10.c
3447
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE252_Unchecked_Return_Value__char_snprintf_10.c Label Definition File: CWE252_Unchecked_Return_Value.label.xml Template File: point-flaw-10.tmpl.c */ /* * @description * CWE: 252 Unchecked Return Value * Sinks: snprintf * GoodSink: Check if snprintf() fails * BadSink : Do not check if snprintf() fails * Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define SRC "string" #ifdef _WIN32 #define SNPRINTF _snprintf #else #define SNPRINTF snprintf #endif #ifndef OMITBAD void CWE252_Unchecked_Return_Value__char_snprintf_10_bad() { if(globalTrue) { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FLAW: Do not check the return value */ SNPRINTF(data,100-strlen(SRC)-1, "%s\n", SRC); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(globalFalse) instead of if(globalTrue) */ static void good1() { if(globalFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FIX: check the return value */ if (SNPRINTF(data,100-strlen(SRC)-1, "%s\n", SRC) < 0) { printLine("snprintf failed!"); } } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(globalTrue) { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FIX: check the return value */ if (SNPRINTF(data,100-strlen(SRC)-1, "%s\n", SRC) < 0) { printLine("snprintf failed!"); } } } } void CWE252_Unchecked_Return_Value__char_snprintf_10_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE252_Unchecked_Return_Value__char_snprintf_10_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE252_Unchecked_Return_Value__char_snprintf_10_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE510_Trapdoor/CWE510_Trapdoor__ip_based_logic_10.c
9070
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE510_Trapdoor__ip_based_logic_10.c Label Definition File: CWE510_Trapdoor.label.xml Template File: point-flaw-10.tmpl.c */ /* * @description * CWE: 510 Trapdoor * Sinks: ip_based_logic * GoodSink: No IP-based logic * BadSink : Different logic if a connection is made from a specific IP * Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse) * * */ #include "std_testcase.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define ADMIN_MESSAGE "Welcome, admin!" #define DEFAULT_MESSAGE "Welcome!" #ifndef OMITBAD void CWE510_Trapdoor__ip_based_logic_10_bad() { if(globalTrue) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif struct sockaddr_in service, acceptService; int acceptServiceLen = sizeof(acceptService); SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(20000); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, 5) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } if (getsockname(acceptSocket, (struct sockaddr *)&acceptService, &acceptServiceLen) == -1) { break; } /* FLAW: IP-based logic */ if (strcmp("192.168.30.123", inet_ntoa(acceptService.sin_addr)) == 0) { if (send(acceptSocket, ADMIN_MESSAGE, strlen(ADMIN_MESSAGE), 0) == SOCKET_ERROR) { /* Do not alert user to trapdoor, no action */ break; } } else { if (send(acceptSocket, DEFAULT_MESSAGE, strlen(DEFAULT_MESSAGE), 0) == SOCKET_ERROR) { printLine("Send failed!"); } } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(globalFalse) instead of if(globalTrue) */ static void good1() { if(globalFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(20000); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, 5) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* FIX: No IP-based logic */ if (send(acceptSocket, DEFAULT_MESSAGE, strlen(DEFAULT_MESSAGE), 0) == SOCKET_ERROR) { printLine("Send failed!"); } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(globalTrue) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(20000); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, 5) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* FIX: No IP-based logic */ if (send(acceptSocket, DEFAULT_MESSAGE, strlen(DEFAULT_MESSAGE), 0) == SOCKET_ERROR) { printLine("Send failed!"); } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } } void CWE510_Trapdoor__ip_based_logic_10_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE510_Trapdoor__ip_based_logic_10_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE510_Trapdoor__ip_based_logic_10_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83.h
1486
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83.h Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml Template File: sources-sink-83.tmpl.h */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sinks: memmove * BadSink : Copy TwoIntsClass array to data using memmove * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83 { #ifndef OMITBAD class CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_bad { public: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_bad(TwoIntsClass * dataCopy); ~CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_bad(); private: TwoIntsClass * data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_goodG2B { public: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_goodG2B(TwoIntsClass * dataCopy); ~CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_memmove_83_goodG2B(); private: TwoIntsClass * data; }; #endif /* OMITGOOD */ }
bsd-3-clause
u4aew/MyHotelG
protected/modules/image/views/imageBackend/create.php
814
<?php $this->breadcrumbs = [ Yii::t('ImageModule.image', 'Images') => ['/image/imageBackend/index'], Yii::t('ImageModule.image', 'Add'), ]; $this->pageTitle = Yii::t('ImageModule.image', 'Images - add'); $this->menu = [ [ 'icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('ImageModule.image', 'Image management'), 'url' => ['/image/imageBackend/index'] ], [ 'icon' => 'fa fa-fw fa-plus-square', 'label' => Yii::t('ImageModule.image', 'Add image'), 'url' => ['/image/imageBackend/create'] ], ]; ?> <div class="page-header"> <h1> <?= Yii::t('ImageModule.image', 'Images'); ?> <small><?= Yii::t('ImageModule.image', 'add'); ?></small> </h1> </div> <?= $this->renderPartial('_form', ['model' => $model]); ?>
bsd-3-clause
dwillmer/playground
scripts/dtsbundle.js
539
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2015, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ require('dts-generator').generate({ name: 'phosphor-playground', main: 'phosphor-playground/index', baseDir: 'lib', files: ['index.d.ts'], out: 'lib/phosphor-playground.d.ts', });
bsd-3-clause
grrr-amsterdam/garp3
library/Garp/Spawn/MySql/Table/Binding.php
175
<?php /** * @author David Spreekmeester | grrr.nl * @package Garp * @subpackage Spawn */ class Garp_Spawn_MySql_Table_Binding extends Garp_Spawn_MySql_Table_Abstract { }
bsd-3-clause
martiner/gooddata-java
gooddata-java-model/src/test/java/com/gooddata/sdk/model/dataset/DatasetLinksTest.java
1817
/* * Copyright (C) 2004-2019, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.sdk.model.dataset; import com.gooddata.sdk.model.gdc.AboutLinks; import org.testng.annotations.Test; import java.util.Collection; import static com.gooddata.sdk.common.util.ResourceUtils.readObjectFromResource; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; public class DatasetLinksTest { @Test public void deserialize() throws Exception { final DatasetLinks datasetLinks = readObjectFromResource("/dataset/datasetLinks.json", DatasetLinks.class); assertThat(datasetLinks, is(notNullValue())); assertThat(datasetLinks.getCategory(), is("singleloadinterface")); assertThat(datasetLinks.getInstance(), is("MD::LDM::SingleLoadInterface")); assertThat(datasetLinks.getSummary(), is("single loading interfaces")); final Collection<AboutLinks.Link> links = datasetLinks.getLinks(); assertThat(links, is(notNullValue())); assertThat(links, hasSize(1)); final AboutLinks.Link link = links.iterator().next(); assertThat(link, is(notNullValue())); assertThat(link.getIdentifier(), is("dataset.person")); assertThat(link.getUri(), is("/gdc/md/PROJECT_ID/ldm/singleloadinterface/dataset.person")); assertThat(link.getCategory(), is("dataset-singleloadinterface")); assertThat(link.getTitle(), is("Person")); assertThat(link.getSummary(), is("dataset single data loading interface specifications")); } }
bsd-3-clause
django/djangosnippets.org
djangosnippets/templates/comments/form.html
1981
{% load i18n %} {% if request.user.is_authenticated %} <form class="fullsize" action="/comments/post/" method="post">{% csrf_token %} {{ form.non_field_errors }} {% url 'account_login' as login_url %} {% url 'account_logout' as logout_url %} <p>{% trans "Username:" %} <strong>{{ user.username }}</strong> (<a href="{% url 'account_logout' %}{% if request.path != login_url or request.path != logout_url %} ?next={{ request.path }}{% endif %}">{% trans "Log out" %}</a>)</p> <dl> <div class="bee-like-this"> {# A honeypot field called "your_name" #} <div class="field {% if form.your_name.errors %}error{% endif %}"> <label for="id_your_name">{% trans "Your Name:" %}</label> <div class="controls"> {{ form.your_name }} {% if form.your_name.errors %}<span class="error">{{ form.your_name.errors|join:", " }}</span>{% endif %} </div> </div> </div> <div class="field {% if form.comment.errors %}error{% endif %}"> <label for="id_comment">{% trans "Comment:" %}</label> <div class="controls"> <textarea name="comment" id="id_comment" rows="10" cols="60"></textarea> {% if form.your_name.errors %}<span class="error">{{ form.your_name.errors|join:", " }}</span>{% endif %} <p class="help">You may use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> here, but <strong>raw HTML will be removed</strong>.</p> </div> </div> <div style="display:none;"> {{ form.honeypot }} {{ form.content_type }} {{ form.object_pk }} {{ form.timestamp }} {{ form.security_hash }} </div> <div class="button-group"> <button type="submit" name="preview">{% trans "Preview comment" %}</button> </div> </form> {% else %} <p>Please <a href="{% url 'account_login' %}">login</a> first before commenting.</p> {% endif %}
bsd-3-clause
nwjs/chromium.src
storage/browser/quota/README.md
3235
# Overview The quota system's primary role is to set and enforce limits on disk usage at both the browser level, and at the origin level (see ./quota_settings.cc for these limit values). The quota system manages disk usage only for certain web platform storage APIs. In order for a storage backend to integrate with the quota system, it must implement the QuotaClient interface. Most work on the quota system is currently done on the browser process' IO thread. There are plans for quota to be moved to [the Storage Service](https://docs.google.com/document/d/1v83XKVxnasgf2uNfb_Uc-rfhDa3-ynNP23yU2DWqshI/), which will run on its own process on desktop platforms. # Key Components ## Interface The quota system's interface is comprised of the following classes: ### QuotaManagerImpl The "heart" of the quota system. This class lives on the browser process' IO thread, but is primarily accessed through QuotaManagerProxy, which handles thread hops. In the future, QuotaManagerProxy will turn into mojom::QuotaManager, and the quota system will be accessed exclusively via mojo. ### QuotaClient This interface must be implemented by any storage backend that wants to integrate with the quota system. This is probably the most used interface from outside of the quota system. ### PaddingKey Helpers for computing quota usage for opaque resources. Features that store opaque resources (AppCache, Cache Storage) should use these helpers to avoid leaking cross-origin information via the quota usage they report. ### SpecialStoragePolicy Hook that allows browser features (currently Extensions and Chrome Apps) to change an origin's quota. ## Implementation The quota system's implementation is made up of the following components: ### UsageTracker, ClientUsageTracker QuotaManagerImpl helpers that distribute tasks (e.g. measure an origin's quota usage) across QuotaClient instances, and cache results as needed. ### QuotaDatabase Stores persistent information in a per-profile SQLite database. Currently stores a few bits of implementation details, and will likely be expanded to cover Storage Buckets. The currently stored information is a usage count, last-modified-time, and last-accessed-time for each origin (used to implement LRU eviction on storage pressure, and Clear Site Data with a time filter), and quota granted via the deprecated API webkitStorageInfo.requestQuota(PERSISTENT,...). ### QuotaTemporaryStorageEvictor Handles eviction and records stats about eviction rounds. ### QuotaTask Implementation detail of QuotaManagerImpl. # Glossary ## Storage Pressure A device is said to be under storage pressure when it is close to capacity. Storage pressure is used to signal a couple of behaviors in the quota system: - Eviction - The QuotaChange event - Triggering storage pressure UI (implementation specific) ## Eviction This is the process by which the quota system cleans up app's data as disk usage gets close to the disk's capacity. # Resources - [Chrome Web Storage and Quota Concepts](https://docs.google.com/document/d/19QemRTdIxYaJ4gkHYf2WWBNPbpuZQDNMpUVf8dQxj4U/) - In-depth description of the quota system that also explains related concepts and legacy APIs that left a mark on quota.
bsd-3-clause
bitcrystal/edk
Sample/Universal/Network/Ip4Config/Dxe/ComponentName.c
7015
/*++ Copyright (c) 2006 - 2007, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: ComponentName.c Abstract: --*/ #include "NetLib.h" #include "Ip4Config.h" // // EFI Component Name Functions // EFI_STATUS EFIAPI Ip4ConfigComponentNameGetDriverName ( #if (EFI_SPECIFICATION_VERSION >= 0x00020000) IN EFI_COMPONENT_NAME2_PROTOCOL *This, #else IN EFI_COMPONENT_NAME_PROTOCOL *This, #endif IN CHAR8 *Language, OUT CHAR16 **DriverName ); EFI_STATUS EFIAPI Ip4ConfigComponentNameGetControllerName ( #if (EFI_SPECIFICATION_VERSION >= 0x00020000) IN EFI_COMPONENT_NAME2_PROTOCOL *This, #else IN EFI_COMPONENT_NAME_PROTOCOL *This, #endif IN EFI_HANDLE ControllerHandle, IN EFI_HANDLE ChildHandle OPTIONAL, IN CHAR8 *Language, OUT CHAR16 **ControllerName ); // // EFI Component Name Protocol // #if (EFI_SPECIFICATION_VERSION >= 0x00020000) EFI_COMPONENT_NAME2_PROTOCOL gIp4ConfigComponentName = { Ip4ConfigComponentNameGetDriverName, Ip4ConfigComponentNameGetControllerName, LANGUAGE_CODE_ENGLISH }; #else EFI_COMPONENT_NAME_PROTOCOL gIp4ConfigComponentName = { Ip4ConfigComponentNameGetDriverName, Ip4ConfigComponentNameGetControllerName, LANGUAGE_CODE_ENGLISH }; #endif STATIC EFI_UNICODE_STRING_TABLE mIp4ConfigDriverNameTable[] = { {LANGUAGE_CODE_ENGLISH, L"IP4 CONFIG Network Service Driver"}, {NULL, NULL} }; EFI_STATUS EFIAPI Ip4ConfigComponentNameGetDriverName ( #if (EFI_SPECIFICATION_VERSION >= 0x00020000) IN EFI_COMPONENT_NAME2_PROTOCOL *This, #else IN EFI_COMPONENT_NAME_PROTOCOL *This, #endif IN CHAR8 *Language, OUT CHAR16 **DriverName ) /*++ Routine Description: Retrieves a Unicode string that is the user readable name of the EFI Driver. Arguments: This - A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance. Language - A pointer to a three character ISO 639-2 language identifier. This is the language of the driver name that that the caller is requesting, and it must match one of the languages specified in SupportedLanguages. The number of languages supported by a driver is up to the driver writer. DriverName - A pointer to the Unicode string to return. This Unicode string is the name of the driver specified by This in the language specified by Language. Returns: EFI_SUCCES - The Unicode string for the Driver specified by This and the language specified by Language was returned in DriverName. EFI_INVALID_PARAMETER - Language is NULL. EFI_INVALID_PARAMETER - DriverName is NULL. EFI_UNSUPPORTED - The driver specified by This does not support the language specified by Language. --*/ { return EfiLibLookupUnicodeString ( Language, gIp4ConfigComponentName.SupportedLanguages, mIp4ConfigDriverNameTable, DriverName ); } EFI_STATUS EFIAPI Ip4ConfigComponentNameGetControllerName ( #if (EFI_SPECIFICATION_VERSION >= 0x00020000) IN EFI_COMPONENT_NAME2_PROTOCOL *This, #else IN EFI_COMPONENT_NAME_PROTOCOL *This, #endif IN EFI_HANDLE ControllerHandle, IN EFI_HANDLE ChildHandle OPTIONAL, IN CHAR8 *Language, OUT CHAR16 **ControllerName ) /*++ Routine Description: Retrieves a Unicode string that is the user readable name of the controller that is being managed by an EFI Driver. Arguments: This - A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance. ControllerHandle - The handle of a controller that the driver specified by This is managing. This handle specifies the controller whose name is to be returned. ChildHandle - The handle of the child controller to retrieve the name of. This is an optional parameter that may be NULL. It will be NULL for device drivers. It will also be NULL for a bus drivers that wish to retrieve the name of the bus controller. It will not be NULL for a bus driver that wishes to retrieve the name of a child controller. Language - A pointer to a three character ISO 639-2 language identifier. This is the language of the controller name that that the caller is requesting, and it must match one of the languages specified in SupportedLanguages. The number of languages supported by a driver is up to the driver writer. ControllerName - A pointer to the Unicode string to return. This Unicode string is the name of the controller specified by ControllerHandle and ChildHandle in the language specified by Language from the point of view of the driver specified by This. Returns: EFI_SUCCESS - The Unicode string for the user readable name in the language specified by Language for the driver specified by This was returned in DriverName. EFI_INVALID_PARAMETER - ControllerHandle is not a valid EFI_HANDLE. EFI_INVALID_PARAMETER - ChildHandle is not NULL and it is not a valid EFI_HANDLE. EFI_INVALID_PARAMETER - Language is NULL. EFI_INVALID_PARAMETER - ControllerName is NULL. EFI_UNSUPPORTED - The driver specified by This is not currently managing the controller specified by ControllerHandle and ChildHandle. EFI_UNSUPPORTED - The driver specified by This does not support the language specified by Language. --*/ { return EFI_UNSUPPORTED; }
bsd-3-clause
bikashrai/zf2
module/Album/autoload_classmap.php
182
<?php /** * Created by JetBrains PhpStorm. * User: bikashrai * Date: 7/14/13 * Time: 10:01 PM * To change this template use File | Settings | File Templates. */ return array();
bsd-3-clause
harcobbit/lumina
src-qt5/core-utils/lumina-config/i18n/lumina-config_da.ts
81634
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="da"> <context> <name>AppDialog</name> <message> <location filename="../AppDialog.ui" line="14"/> <source>Select Application</source> <translation>Vælg program</translation> </message> </context> <context> <name>ColorDialog</name> <message> <location filename="../ColorDialog.ui" line="14"/> <source>Color Scheme Editor</source> <translation>Redigér Farveskema</translation> </message> <message> <location filename="../ColorDialog.ui" line="28"/> <source>Color Scheme:</source> <translation>Farveskema:</translation> </message> <message> <location filename="../ColorDialog.ui" line="51"/> <source>Set new color for selection</source> <translation>Vælg ny farve for det valgte</translation> </message> <message> <location filename="../ColorDialog.ui" line="54"/> <location filename="../ColorDialog.ui" line="70"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../ColorDialog.ui" line="67"/> <source>Manually set value for selection</source> <translation>Manuelt ændre værdi for det valgte</translation> </message> <message> <location filename="../ColorDialog.ui" line="95"/> <source>Color</source> <translation>Farve</translation> </message> <message> <location filename="../ColorDialog.ui" line="100"/> <source>Value</source> <translation>Værdi</translation> </message> <message> <location filename="../ColorDialog.ui" line="105"/> <source>Sample</source> <translation>Eksempel</translation> </message> <message> <location filename="../ColorDialog.ui" line="115"/> <source>Cancel</source> <translation>Annullér</translation> </message> <message> <location filename="../ColorDialog.ui" line="135"/> <source>Save</source> <translation>Gem</translation> </message> <message> <location filename="../ColorDialog.cpp" line="98"/> <source>Color Exists</source> <translation>Farve eksisterer</translation> </message> <message> <location filename="../ColorDialog.cpp" line="98"/> <source>This color scheme already exists. Overwrite it?</source> <translation>Denne farve eksisterer allerede. Skal den overskrives?</translation> </message> <message> <location filename="../ColorDialog.cpp" line="121"/> <location filename="../ColorDialog.cpp" line="122"/> <source>Select Color</source> <translation>Vælg farve</translation> </message> <message> <location filename="../ColorDialog.cpp" line="142"/> <source>Color Value</source> <translation>Farveværdi</translation> </message> <message> <location filename="../ColorDialog.cpp" line="142"/> <source>Color:</source> <translation>Farve:</translation> </message> </context> <context> <name>GetPluginDialog</name> <message> <location filename="../GetPluginDialog.ui" line="14"/> <source>Select Plugin</source> <translation>Vælg Udvidelsesmodul</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="26"/> <source>Select a Plugin:</source> <translation>Vælg et Udvidelsesmodul:</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="57"/> <source>Cancel</source> <translation>Afbryd</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="77"/> <source>Select</source> <translation>Vælg</translation> </message> </context> <context> <name>PanelWidget</name> <message> <location filename="../PanelWidget.ui" line="32"/> <source>Form</source> <translation>Form</translation> </message> <message> <location filename="../PanelWidget.ui" line="93"/> <source>Location</source> <translation>Placering</translation> </message> <message> <location filename="../PanelWidget.ui" line="114"/> <source>Edge:</source> <translation>Kant:</translation> </message> <message> <location filename="../PanelWidget.ui" line="131"/> <source>Size:</source> <translation>Størrelse:</translation> </message> <message> <location filename="../PanelWidget.ui" line="138"/> <source> pixel(s) thick</source> <translation> pixel(s) tyk</translation> </message> <message> <location filename="../PanelWidget.ui" line="157"/> <source>% length</source> <translation>% længde</translation> </message> <message> <location filename="../PanelWidget.ui" line="183"/> <source>Alignment:</source> <translation>Justering:</translation> </message> <message> <location filename="../PanelWidget.ui" line="204"/> <source>Appearance</source> <translation type="unfinished">Udseende</translation> </message> <message> <location filename="../PanelWidget.ui" line="222"/> <source>Auto-hide Panel</source> <translation>Auto-skjul Panel</translation> </message> <message> <location filename="../PanelWidget.ui" line="229"/> <source>Use Custom Color</source> <translation>Anvend brugervalgt farve</translation> </message> <message> <location filename="../PanelWidget.ui" line="250"/> <source>...</source> <translation type="unfinished">...</translation> </message> <message> <location filename="../PanelWidget.ui" line="257"/> <source>Sample</source> <translation type="unfinished">Eksempel</translation> </message> <message> <location filename="../PanelWidget.ui" line="287"/> <source>Plugins</source> <translation>Udvidelsesmoduler</translation> </message> <message> <location filename="../PanelWidget.cpp" line="19"/> <source>Top/Left</source> <translation>Øverst/Venstre</translation> </message> <message> <location filename="../PanelWidget.cpp" line="20"/> <source>Center</source> <translation>Midt</translation> </message> <message> <location filename="../PanelWidget.cpp" line="21"/> <source>Bottom/Right</source> <translation>Bund/Højre</translation> </message> <message> <location filename="../PanelWidget.cpp" line="22"/> <source>Top</source> <translation>Øverst</translation> </message> <message> <location filename="../PanelWidget.cpp" line="23"/> <source>Bottom</source> <translation>Bund</translation> </message> <message> <location filename="../PanelWidget.cpp" line="24"/> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.cpp" line="25"/> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.cpp" line="44"/> <location filename="../PanelWidget.cpp" line="117"/> <source>Panel %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.cpp" line="155"/> <location filename="../PanelWidget.cpp" line="156"/> <source>Select Color</source> <translation type="unfinished">Vælg farve</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../LPlugins.cpp" line="80"/> <source>Desktop Bar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="81"/> <source>This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="87"/> <source>Spacer</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="88"/> <source>Invisible spacer to separate plugins.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="102"/> <source>Controls for switching between the various virtual desktops.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="108"/> <source>Battery Monitor</source> <translation>Batteriovervågning</translation> </message> <message> <location filename="../LPlugins.cpp" line="109"/> <source>Keep track of your battery status.</source> <translation>Følg din batteri status.</translation> </message> <message> <location filename="../LPlugins.cpp" line="115"/> <source>Time/Date</source> <translation>Tid/Dato</translation> </message> <message> <location filename="../LPlugins.cpp" line="116"/> <source>View the current time and date.</source> <translation>Vis det aktuelle tidspunkt og dato.</translation> </message> <message> <location filename="../LPlugins.cpp" line="122"/> <source>System Dashboard</source> <translation type="unfinished">Instrumentbræt til skrivebordet</translation> </message> <message> <location filename="../LPlugins.cpp" line="123"/> <source>View or change system settings (audio volume, screen brightness, battery life, virtual desktops).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="129"/> <location filename="../LPlugins.cpp" line="291"/> <source>Task Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="136"/> <source>Task Manager (No Groups)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="143"/> <source>System Tray</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="144"/> <source>Display area for dockable system applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="151"/> <source>Hide all open windows and show the desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="157"/> <source>Start Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="190"/> <source>Calendar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="191"/> <source>Display a calendar on the desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="164"/> <location filename="../LPlugins.cpp" line="197"/> <source>Application Launcher</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="66"/> <source>User Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="67"/> <source>Start menu alternative focusing on the user&apos;s files, directories, and favorites.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="73"/> <source>Application Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="74"/> <source>Start menu alternative which focuses on launching applications.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="94"/> <source>Line</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="95"/> <source>Simple line to provide visual separation between items.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="101"/> <source>Workspace Switcher</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="130"/> <source>View and control any running application windows (group similar windows under a single button).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="137"/> <source>View and control any running application windows (every individual window has a button)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="150"/> <source>Show Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="158"/> <source>Unified system access and application launch menu.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="165"/> <source>Pin an application shortcut directly to the panel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="198"/> <source>Desktop button for launching an application</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="204"/> <source>Desktop Icons View</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="211"/> <source>Note Pad</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="212"/> <source>Keep simple text notes on your desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="171"/> <location filename="../LPlugins.cpp" line="218"/> <source>Audio Player</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="172"/> <location filename="../LPlugins.cpp" line="219"/> <source>Play through lists of audio files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="225"/> <source>System Monitor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="226"/> <source>Keep track of system statistics such as CPU/Memory usage and CPU temperatures.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="232"/> <source>RSS Reader</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="233"/> <source>Monitor RSS Feeds (Requires internet connection)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="256"/> <source>Terminal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="257"/> <source>Start the default system terminal.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="264"/> <source>Browse the system with the default file manager.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="270"/> <location filename="../pages/getPage.h" line="33"/> <source>Applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="271"/> <source>Show the system applications menu.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="277"/> <source>Separator</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="278"/> <source>Static horizontal line.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="285"/> <source>Show the desktop settings menu.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="298"/> <source>Custom App</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="299"/> <source>Start a custom application</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="178"/> <location filename="../LPlugins.cpp" line="305"/> <source>Menu Script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="205"/> <source>Configurable area for automatically showing desktop icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="263"/> <source>Browse Files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="284"/> <source>Preferences</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="292"/> <source>List the open, minimized, active, and urgent application windows</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="179"/> <location filename="../LPlugins.cpp" line="306"/> <source>Run an external script to generate a user defined menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="312"/> <source>Lock Session</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="313"/> <source>Lock the current desktop session</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="323"/> <source>Text</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="324"/> <source>Color to use for all visible text.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="329"/> <source>Text (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="330"/> <source>Text color for disabled or inactive items.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="335"/> <source>Text (Highlighted)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="336"/> <source>Text color when selection is highlighted.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="341"/> <source>Base Window Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="342"/> <source>Main background color for the window/dialog.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="347"/> <source>Base Window Color (Alternate)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="348"/> <source>Main background color for widgets that list or display collections of items.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="353"/> <source>Primary Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="354"/> <source>Dominant color for the theme.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="359"/> <source>Primary Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="360"/> <source>Dominant color for the theme (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="365"/> <source>Secondary Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="366"/> <source>Alternate color for the theme.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="371"/> <source>Secondary Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="372"/> <source>Alternate color for the theme (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="377"/> <source>Accent Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="378"/> <source>Color used for borders or other accents.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="383"/> <source>Accent Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="384"/> <source>Color used for borders or other accents (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="389"/> <source>Highlight Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="390"/> <source>Color used for highlighting an item.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="395"/> <source>Highlight Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="396"/> <source>Color used for highlighting an item (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="29"/> <source>Wallpaper Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="29"/> <source>Change background image(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="30"/> <source>Theme Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="30"/> <source>Change interface fonts and colors</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="31"/> <source>Window Effects</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="31"/> <source>Adjust transparency levels and window effects</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="32"/> <source>Startup Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="32"/> <source>Automatically start applications or services</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="29"/> <source>Wallpaper</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="30"/> <source>Theme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="32"/> <source>Autostart</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="33"/> <source>Mimetype Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="33"/> <source>Change default applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="34"/> <source>Keyboard Shortcuts</source> <translation type="unfinished">Tastaturgenveje</translation> </message> <message> <location filename="../pages/getPage.h" line="34"/> <source>Change keyboard shortcuts</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="35"/> <source>Window Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="35"/> <source>Window Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="35"/> <source>Change window settings and appearances</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="36"/> <source>Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="37"/> <source>Panels</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="38"/> <source>Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="42"/> <source>Input Device Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="42"/> <source>Adjust keyboard and mouse devices</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="36"/> <source>Desktop Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="36"/> <source>Change what icons or tools are embedded on the desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="37"/> <source>Panels and Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="37"/> <source>Change any floating panels and what they show</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="38"/> <source>Menu Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="38"/> <source>Change what options are shown on the desktop context menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="39"/> <source>Locale Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="39"/> <source>Change the default locale settings for this user</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="39"/> <source>Localization</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="40"/> <source>General Options</source> <translation type="unfinished">Generelle Instillinger</translation> </message> <message> <location filename="../pages/getPage.h" line="40"/> <source>User Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.h" line="40"/> <source>Change basic user settings such as time/date formats</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScriptDialog</name> <message> <location filename="../ScriptDialog.ui" line="14"/> <source>Setup a JSON Menu Script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="25"/> <source>Visible Name:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="32"/> <source>Executable:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="39"/> <source>Icon:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="54"/> <location filename="../ScriptDialog.ui" line="87"/> <source>...</source> <translation type="unfinished">...</translation> </message> <message> <location filename="../ScriptDialog.ui" line="126"/> <source>Cancel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="133"/> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.cpp" line="57"/> <source>Select a menu script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.cpp" line="64"/> <source>Select an icon file</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ThemeDialog</name> <message> <location filename="../ThemeDialog.ui" line="14"/> <source>Theme Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.ui" line="28"/> <source>Theme Name:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.ui" line="51"/> <source>color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.ui" line="74"/> <source>Cancel</source> <translation type="unfinished">Annullér</translation> </message> <message> <location filename="../ThemeDialog.ui" line="94"/> <source>Save</source> <translation type="unfinished">Gem</translation> </message> <message> <location filename="../ThemeDialog.ui" line="101"/> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.cpp" line="65"/> <location filename="../ThemeDialog.cpp" line="82"/> <source>Theme Exists</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.cpp" line="65"/> <location filename="../ThemeDialog.cpp" line="82"/> <source>This theme already exists. Overwrite it?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>mainWindow</name> <message> <location filename="../mainWindow.ui" line="14"/> <source>MainWindow</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="23"/> <source>toolBar</source> <translation type="unfinished">Værktøjslinje</translation> </message> <message> <location filename="../mainWindow.ui" line="50"/> <source>Save</source> <translation type="unfinished">Gem</translation> </message> <message> <location filename="../mainWindow.ui" line="53"/> <source>Save current changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="56"/> <source>Ctrl+S</source> <translation type="unfinished">Ctrl+S</translation> </message> <message> <location filename="../mainWindow.ui" line="61"/> <source>Back to settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="64"/> <location filename="../mainWindow.ui" line="67"/> <source>Back to overall settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="78"/> <location filename="../mainWindow.ui" line="81"/> <source>Select monitor/desktop to configure</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="129"/> <source>Unsaved Changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="129"/> <source>This page currently has unsaved changes, do you wish to save them now?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_autostart</name> <message> <location filename="../pages/page_autostart.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_autostart.ui" line="39"/> <source>Add New Startup Service</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.ui" line="75"/> <source>Application</source> <translation type="unfinished">Program</translation> </message> <message> <location filename="../pages/page_autostart.ui" line="85"/> <source>Binary</source> <translation type="unfinished">Binær</translation> </message> <message> <location filename="../pages/page_autostart.ui" line="95"/> <source>File</source> <translation type="unfinished">Fil</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="67"/> <source>Startup Services</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="134"/> <source>Select Binary</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="134"/> <source>Application Binaries (*)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="137"/> <source>Invalid Binary</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="137"/> <source>The selected file is not executable!</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="151"/> <source>Select File</source> <translation type="unfinished">Vælg fil</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="151"/> <source>All Files (*)</source> <translation type="unfinished">Alle filer (*)</translation> </message> </context> <context> <name>page_compton</name> <message> <location filename="../pages/page_compton.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_compton.ui" line="32"/> <source>Disable Compositing Manager (session restart required)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_compton.ui" line="39"/> <source>Only use compositing with GPU acceleration </source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_compton.cpp" line="38"/> <source>Compositor Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_defaultapps</name> <message> <location filename="../pages/page_defaultapps.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="166"/> <source>Advanced</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="189"/> <source>Specific File Types</source> <translation type="unfinished">Specifikke Filtyper</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="226"/> <source>Type/Group</source> <translation type="unfinished">Type/Gruppe</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="231"/> <source>Default Application</source> <translation type="unfinished">Standardprogram</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="236"/> <source>Description</source> <translation type="unfinished">Beskrivelse</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="246"/> <source>Clear</source> <translation type="unfinished">Ryd</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="269"/> <source>Set App</source> <translation type="unfinished">Sæt Prog</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="279"/> <source>Set Binary</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="39"/> <source>Basic Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="58"/> <source>Web Browser:</source> <translation type="unfinished">Webbrowser:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="81"/> <source>E-Mail Client:</source> <translation type="unfinished">E-post Klient:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="108"/> <source>File Manager:</source> <translation type="unfinished">Filhåndtering:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="121"/> <source>Virtual Terminal:</source> <translation type="unfinished">Virtuel Terminal:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="128"/> <location filename="../pages/page_defaultapps.ui" line="138"/> <source>...</source> <translation type="unfinished">...</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="43"/> <source>Default Applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="61"/> <location filename="../pages/page_defaultapps.cpp" line="82"/> <location filename="../pages/page_defaultapps.cpp" line="103"/> <location filename="../pages/page_defaultapps.cpp" line="124"/> <location filename="../pages/page_defaultapps.cpp" line="220"/> <source>Click to Set</source> <translation type="unfinished">Klik for at vælge</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="158"/> <source>%1 (%2)</source> <translation type="unfinished">%1 (%2)</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="330"/> <source>Select Binary</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="337"/> <source>Invalid Binary</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="337"/> <source>The selected binary is not executable!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_fluxbox_keys</name> <message> <location filename="../pages/page_fluxbox_keys.ui" line="14"/> <source>page_fluxbox_keys</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="34"/> <source>Basic Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="44"/> <source>Advanced Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="107"/> <source>Action</source> <translation type="unfinished">Handling</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="112"/> <source>Keyboard Shortcut</source> <translation type="unfinished">Tastaturgenvej</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="120"/> <source>Modify Shortcut</source> <translation type="unfinished">Redigér genvej</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="141"/> <source>Clear Shortcut</source> <translation type="unfinished">Fjern genvej</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="151"/> <source>Apply Change</source> <translation type="unfinished">Udfør ændring</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="161"/> <source>Change Key Binding:</source> <translation type="unfinished">Skift taste binding:</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="184"/> <source>Note: Current key bindings need to be cleared and saved before they can be re-used.</source> <translation type="unfinished">Besked: Eksisterende taste genvej skal fjernes og gemmes før de kan blive genbrugt.</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="220"/> <source>View Syntax Codes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="244"/> <source>&quot;Mod1&quot;: Alt key &quot;Mod4&quot;: Windows/Mac key &quot;Control&quot;: Ctrl key</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="71"/> <source>Keyboard Shortcuts</source> <translation type="unfinished">Tastaturgenveje</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="79"/> <source>Audio Volume Up</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="80"/> <source>Audio Volume Down</source> <translation type="unfinished">Lydstyrke Ned</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="81"/> <source>Screen Brightness Up</source> <translation type="unfinished">Skærmlysstyrke Op</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="82"/> <source>Screen Brightness Down</source> <translation type="unfinished">Skærmlysstyrke Ned</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="83"/> <source>Take Screenshot</source> <translation type="unfinished">Tag skærmbillede</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="84"/> <source>Lock Screen</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_fluxbox_settings</name> <message> <location filename="../pages/page_fluxbox_settings.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="34"/> <source>Simple Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="44"/> <source>Advanced Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="81"/> <source>Number of Workspaces</source> <translation type="unfinished">Antal af arbejdsområder</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="98"/> <source>New Window Placement</source> <translation type="unfinished">Ny vinduesplacering</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="108"/> <source>Focus Policy</source> <translation type="unfinished">Fokuspolitik</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="118"/> <source>Window Theme</source> <translation type="unfinished">Vinduestema</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="136"/> <source>Window Theme Preview</source> <translation type="unfinished">Vinduestema forhåndsvisning</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="190"/> <location filename="../pages/page_fluxbox_settings.cpp" line="182"/> <source>No Preview Available</source> <translation type="unfinished">Ingen forhåndsvisning tilgængelig</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="71"/> <source>Window Manager Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="76"/> <source>Click To Focus</source> <translation type="unfinished">Klik for fokus</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="77"/> <source>Active Mouse Focus</source> <translation type="unfinished">Aktiv mus fokus</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="78"/> <source>Strict Mouse Focus</source> <translation type="unfinished">Streng mus fokus</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="81"/> <source>Align in a Row</source> <translation type="unfinished">Tilpas i en række</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="82"/> <source>Align in a Column</source> <translation type="unfinished">Tilpas i en kolonne</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="83"/> <source>Cascade</source> <translation type="unfinished">Kaskade</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="84"/> <source>Underneath Mouse</source> <translation type="unfinished">Under mus</translation> </message> </context> <context> <name>page_interface_desktop</name> <message> <location filename="../pages/page_interface_desktop.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_interface_desktop.ui" line="26"/> <source>Embedded Utilities</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_desktop.ui" line="77"/> <source>Display Desktop Folder Contents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_desktop.cpp" line="55"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_interface_menu</name> <message> <location filename="../pages/page_interface_menu.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_interface_menu.ui" line="38"/> <source>Context Menu Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_menu.cpp" line="47"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_interface_panels</name> <message> <location filename="../pages/page_interface_panels.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_interface_panels.ui" line="69"/> <source>Profile</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.ui" line="82"/> <source>Import</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="52"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_main</name> <message> <location filename="../pages/page_main.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_main.ui" line="32"/> <source>Search for....</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="53"/> <source>Interface Configuration</source> <translation type="unfinished">Indstilling af grænseflade</translation> </message> <message> <location filename="../pages/page_main.cpp" line="57"/> <source>Appearance</source> <translation type="unfinished">Udseende</translation> </message> <message> <location filename="../pages/page_main.cpp" line="61"/> <source>Desktop Defaults</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="65"/> <source>User Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="131"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_mouse</name> <message> <location filename="../pages/page_mouse.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_mouse.cpp" line="53"/> <source>Input Device Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_mouse.cpp" line="81"/> <source>Mouse #%1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_mouse.cpp" line="85"/> <source>Keyboard #%1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_mouse.cpp" line="106"/> <source>Extension Device #%1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_mouse.cpp" line="107"/> <source>Master Device</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_session_locale</name> <message> <location filename="../pages/page_session_locale.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="32"/> <source>System localization settings (restart required)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="39"/> <source>Language</source> <translation type="unfinished">Sprog</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="49"/> <source>Messages</source> <translation type="unfinished">Beskeder</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="59"/> <source>Time</source> <translation type="unfinished">Tid</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="69"/> <source>Numeric</source> <translation type="unfinished">Numerisk</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="79"/> <source>Monetary</source> <translation type="unfinished">Monetære</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="89"/> <source>Collate</source> <translation type="unfinished">Saml</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="99"/> <source>CType</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.cpp" line="48"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.cpp" line="92"/> <source>System Default</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_session_options</name> <message> <location filename="../pages/page_session_options.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="34"/> <source>Enable numlock on startup</source> <translation type="unfinished">Aktivér numlock under opstart</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="41"/> <source>Play chimes on startup</source> <translation type="unfinished">Afspil lyde under opstart</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="48"/> <source>Play chimes on exit</source> <translation type="unfinished">Afspil lyde under afslutning</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="55"/> <source>Automatically create/remove desktop symlinks for applications that are installed/removed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="58"/> <source>Manage desktop app links</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="65"/> <source>Show application crash data</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="74"/> <source>Change User Icon</source> <translation type="unfinished">Skift Bruger Ikon</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="112"/> <source>Time Format:</source> <translation type="unfinished">Tidsformat:</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="124"/> <location filename="../pages/page_session_options.ui" line="168"/> <source>View format codes</source> <translation type="unfinished">Vis format koder</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="139"/> <location filename="../pages/page_session_options.ui" line="183"/> <source>Sample:</source> <translation type="unfinished">Prøve:</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="156"/> <source>Date Format:</source> <translation type="unfinished">Datoformat:</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="203"/> <source>Display Format</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="234"/> <source>Reset Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="253"/> <source>Return to system defaults</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="260"/> <source>Return to Lumina defaults</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="19"/> <source>Time (Date as tooltip)</source> <translation type="unfinished">Tid (Dato som værktøjstip)</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="20"/> <source>Date (Time as tooltip)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="21"/> <source>Time first then Date</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="22"/> <source>Date first then Time</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="70"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="113"/> <source>Select an image</source> <translation type="unfinished">Vælg et billede</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="114"/> <source>Images</source> <translation type="unfinished">Billeder</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="118"/> <source>Reset User Image</source> <translation type="unfinished">Nulstil Bruger billede</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="118"/> <source>Would you like to reset the user image to the system default?</source> <translation type="unfinished">Vil du gerne nulstille bruger billedet til system standard?</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="157"/> <source>Valid Time Codes:</source> <translation type="unfinished">Gyldig tids koder:</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="158"/> <source>%1: Hour without leading zero (1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="159"/> <source>%1: Hour with leading zero (01)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="160"/> <source>%1: Minutes without leading zero (2)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="161"/> <source>%1: Minutes with leading zero (02)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="162"/> <source>%1: Seconds without leading zero (3)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="163"/> <source>%1: Seconds with leading zero (03)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="164"/> <source>%1: AM/PM (12-hour) clock (upper or lower case)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="165"/> <source>%1: Timezone</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="166"/> <source>Time Codes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="180"/> <source>Valid Date Codes:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="181"/> <source>%1: Numeric day without a leading zero (1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="182"/> <source>%1: Numeric day with leading zero (01)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="183"/> <source>%1: Day as abbreviation (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="184"/> <source>%1: Day as full name (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="185"/> <source>%1: Numeric month without leading zero (2)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="186"/> <source>%1: Numeric month with leading zero (02)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="187"/> <source>%1: Month as abbreviation (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="188"/> <source>%1: Month as full name (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="189"/> <source>%1: Year as 2-digit number (15)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="190"/> <source>%1: Year as 4-digit number (2015)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="191"/> <source>Text may be contained within single-quotes to ignore replacements</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="192"/> <source>Date Codes</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_theme</name> <message> <location filename="../pages/page_theme.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_theme.ui" line="36"/> <source>Desktop Theme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.ui" line="42"/> <source>Font:</source> <translation type="unfinished">Skrifttype:</translation> </message> <message> <location filename="../pages/page_theme.ui" line="56"/> <source>Font Size:</source> <translation type="unfinished">Skriftstørrelse:</translation> </message> <message> <location filename="../pages/page_theme.ui" line="63"/> <source> point</source> <translation type="unfinished"> point</translation> </message> <message> <location filename="../pages/page_theme.ui" line="70"/> <source>Theme Template:</source> <translation type="unfinished">Temaskabelon:</translation> </message> <message> <location filename="../pages/page_theme.ui" line="86"/> <source>Create/Edit a theme template (Advanced)</source> <translation type="unfinished">Opret/Rediger en tema skabelon (Avanceret)</translation> </message> <message> <location filename="../pages/page_theme.ui" line="92"/> <location filename="../pages/page_theme.ui" line="126"/> <source>Edit</source> <translation type="unfinished">Redigér</translation> </message> <message> <location filename="../pages/page_theme.ui" line="104"/> <source>Color Scheme:</source> <translation type="unfinished">Farveskema:</translation> </message> <message> <location filename="../pages/page_theme.ui" line="120"/> <source>Create/Edit a color scheme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.ui" line="138"/> <source>Icon Pack:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.ui" line="148"/> <source>Mouse Cursors:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.ui" line="192"/> <source>Application Themes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.ui" line="198"/> <source>Qt5 Theme Engine</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.cpp" line="58"/> <source>Theme Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.cpp" line="73"/> <location filename="../pages/page_theme.cpp" line="87"/> <location filename="../pages/page_theme.cpp" line="173"/> <location filename="../pages/page_theme.cpp" line="199"/> <source>Local</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.cpp" line="80"/> <location filename="../pages/page_theme.cpp" line="94"/> <location filename="../pages/page_theme.cpp" line="180"/> <location filename="../pages/page_theme.cpp" line="206"/> <source>System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.cpp" line="137"/> <source>None</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_theme.cpp" line="138"/> <source>Manual Setting</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_wallpaper</name> <message> <location filename="../pages/page_wallpaper.ui" line="14"/> <source>Form</source> <translation type="unfinished">Form</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="90"/> <source>Single Background</source> <translation type="unfinished">Enlig Baggrund</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="100"/> <source>Rotate Background</source> <translation type="unfinished">Rotér Baggrund</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="107"/> <source> Minutes</source> <translation type="unfinished"> Minutter</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="110"/> <source>Every </source> <translation type="unfinished">Hver </translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="133"/> <source>Layout:</source> <translation type="unfinished">Layout:</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="56"/> <source>Wallpaper Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="66"/> <source>System Default</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="67"/> <location filename="../pages/page_wallpaper.cpp" line="222"/> <source>Solid Color: %1</source> <translation type="unfinished">Ensfarvet farve: %1</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="78"/> <source>Screen Resolution:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="100"/> <location filename="../pages/page_wallpaper.cpp" line="101"/> <source>Select Color</source> <translation type="unfinished">Vælg farve</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="120"/> <source>File(s)</source> <translation type="unfinished">Fil(er)</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="121"/> <source>Directory (Single)</source> <translation type="unfinished">Mappe (Enkelt)</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="122"/> <source>Directory (Recursive)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="123"/> <source>Solid Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="127"/> <source>Automatic</source> <translation type="unfinished">Automatisk</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="128"/> <source>Fullscreen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="129"/> <source>Fit screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="130"/> <source>Tile</source> <translation type="unfinished">Flise</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="131"/> <source>Center</source> <translation type="unfinished">Centrér</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="132"/> <source>Top Left</source> <translation type="unfinished">Øverst til venstre</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="133"/> <source>Top Right</source> <translation type="unfinished">Øverst til højre</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="134"/> <source>Bottom Left</source> <translation type="unfinished">Nederst til venstre</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="135"/> <source>Bottom Right</source> <translation type="unfinished">Nederst til højre</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="143"/> <source>No Background</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="143"/> <source>(use system default)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="163"/> <source>File does not exist</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="203"/> <source>Find Background Image(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="234"/> <location filename="../pages/page_wallpaper.cpp" line="259"/> <source>Find Background Image Directory</source> <translation type="unfinished"></translation> </message> </context> </TS>
bsd-3-clause
Det-Kongelige-Bibliotek/droid
droid-results/src/main/java/uk/gov/nationalarchives/droid/profile/ProfileManagerImpl.java
16013
/** * Copyright (c) 2012, The National Archives <[email protected]> * 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. * * * Neither the name of the The National Archives nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 uk.gov.nationalarchives.droid.profile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.zip.ZipFile; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.gov.nationalarchives.droid.core.interfaces.config.DroidGlobalConfig; import uk.gov.nationalarchives.droid.core.interfaces.config.DroidGlobalProperty; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileException; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureManager; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType; import uk.gov.nationalarchives.droid.profile.referencedata.Format; import uk.gov.nationalarchives.droid.profile.referencedata.ReferenceData; import uk.gov.nationalarchives.droid.results.handlers.ProgressObserver; /** * @author rflitcroft * */ public class ProfileManagerImpl implements ProfileManager { private final Log log = LogFactory.getLog(getClass()); private ProfileContextLocator profileContextLocator; private ProfileSpecDao profileSpecDao; private ProfileDiskAction profileSaver; private SignatureManager signatureManager; private DroidGlobalConfig config; /** * Gets a profile instance manager. * * @param sigFileInfos * the path to the signature file to be used for this profile. * @return the profile instance created. * @throws ProfileManagerException if the profile could not be created */ @Override public ProfileInstance createProfile(Map<SignatureType, SignatureFileInfo> sigFileInfos) throws ProfileManagerException { Map<SignatureType, SignatureFileInfo> signatures = sigFileInfos; if (sigFileInfos == null) { // get the default sig file config try { signatures = signatureManager.getDefaultSignatures(); } catch (SignatureFileException e) { throw new ProfileManagerException(e.getMessage()); } } String profileId = String.valueOf(System.currentTimeMillis()); log.info("Creating profile: " + profileId); ProfileInstance profile = profileContextLocator.getProfileInstance(profileId); File profileHomeDir = new File(config.getProfilesDir(), profile.getUuid()); profileHomeDir.mkdir(); SignatureFileInfo binarySigFile = signatures.get(SignatureType.BINARY); if (binarySigFile != null) { profile.setSignatureFileVersion(binarySigFile.getVersion()); profile.setSignatureFileName(binarySigFile.getFile().getName()); copySignatureFile(binarySigFile.getFile(), profileHomeDir); } SignatureFileInfo containerSigFile = signatures.get(SignatureType.CONTAINER); if (containerSigFile != null) { profile.setContainerSignatureFileName(containerSigFile.getFile().getName()); profile.setContainerSignatureFileVersion(containerSigFile.getVersion()); copySignatureFile(containerSigFile.getFile(), profileHomeDir); } SignatureFileInfo textSigFile = signatures.get(SignatureType.TEXT); if (textSigFile != null) { profile.setTextSignatureFileName(textSigFile.getFile().getName()); profile.setTextSignatureFileVersion(textSigFile.getVersion()); copySignatureFile(textSigFile.getFile(), profileHomeDir); } profile.setUuid(profileId); profile.setProfileSpec(new ProfileSpec()); // Persist the profile. profileSpecDao.saveProfile(profile, profileHomeDir); // Copy the signature file to the profile area // Ensure a newly created profile is not in a "dirty" state: profile.setDirty(false); profileContextLocator.addProfileContext(profile); return profile; } private static void copySignatureFile(File file, File destDir) { try { FileUtils.copyFileToDirectory(file, destDir); } catch (IOException e) { throw new ProfileException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public void closeProfile(String profileName) { log.info("Closing profile: " + profileName); profileContextLocator.removeProfileContext(profileName); if (!config.getProperties().getBoolean(DroidGlobalProperty.DEV_MODE.getName())) { File profileHome = new File(config.getProfilesDir(), profileName); FileUtils.deleteQuietly(profileHome); } } /** * {@inheritDoc} * @param profileId String * @throws IllegalArgumentException if profileId nonexistent * @return Profile */ @Override public ProfileInstance openProfile(String profileId) { log.info("Opening profile: " + profileId); if (!profileContextLocator.hasProfileContext(profileId)) { throw new IllegalArgumentException(String.format( "No such profile id [%s]", profileId)); } ProfileInstance profile = profileContextLocator .getProfileInstance(profileId); profileContextLocator.openProfileInstanceManager(profile); profile.fireListeners(); return profile; } /** * {@inheritDoc} * @param profileInstance The profile to stop */ @Override public void stop(String profileInstance) { log.info("Stopping profile: " + profileInstance); ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileInstance); profileInstanceManager.pause(); } /** * @param profileInstance String * @return ProfileInstanceManager * @throws ProfileException if null profileInstance */ private ProfileInstanceManager getProfileInstanceManager( String profileInstance) { if (profileInstance == null) { String message = "Profile instance id was null"; log.error(message); throw new ProfileException(message); } ProfileInstanceManager profileInstanceManager = profileContextLocator .openProfileInstanceManager(profileContextLocator .getProfileInstance(profileInstance)); return profileInstanceManager; } /** * {@inheritDoc} */ @Override public Future<?> start(String profileId) throws IOException { log.info("Starting profile: " + profileId); ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId); return profileInstanceManager.start(); } /** * {@inheritDoc} */ @Override public List<ProfileResourceNode> findProfileResourceNodeAndImmediateChildren( String profileId, Long parentId) { log.debug(String.format( " **** Called findProfileResourceNodeAndImmediateChildren [%s] ****", profileId)); ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId); return profileInstanceManager.findAllProfileResourceNodes(parentId); } /** * {@inheritDoc} */ @Override public List<ProfileResourceNode> findRootNodes(String profileId) { ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId); return profileInstanceManager.findRootProfileResourceNodes(); } /** * {@inheritDoc} */ @Override public void setProgressObserver(String profileId, ProgressObserver progressObserver) { ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId); profileInstanceManager.getProgressMonitor() .setPercentIncrementObserver(progressObserver); } /** * @param profileSpecDao * the profileSpecDao to set */ public void setProfileSpecDao(ProfileSpecDao profileSpecDao) { this.profileSpecDao = profileSpecDao; } /** * @param profileContextLocator * the profileContextLocator to set */ public void setProfileContextLocator( ProfileContextLocator profileContextLocator) { this.profileContextLocator = profileContextLocator; } /** * {@inheritDoc} */ @Override public void setResultsObserver(String profileUuid, ProfileResultObserver observer) { getProfileInstanceManager(profileUuid).setResultsObserver(observer); } /** * {@inheritDoc} */ @Override public void updateProfileSpec(String profileId, ProfileSpec profileSpec) { ProfileInstance profile = profileContextLocator .getProfileInstance(profileId); profile.setProfileSpec(profileSpec); profileSpecDao.saveProfile(profile, getProfileHomeDir(profile)); } /** * Saves the specified profile to the file specified. The file will be * created if it does not already exist or overwritten if it exists. * * @param profileId * the ID of the profile. * @param destination * the file to be created or overwitten * @param callback * an object to be notified when progress is made. * @return the saved profile instance * @throws IOException * if the file IO failed */ @Override public ProfileInstance save(String profileId, File destination, ProgressObserver callback) throws IOException { log.info("Saving profile: " + profileId + " to " + destination.getPath()); // freeze the database so that we can safely zip it up. profileContextLocator.freezeDatabase(profileId); ProfileInstance profile = profileContextLocator.getProfileInstance(profileId); ProfileState oldState = profile.getState(); profile.changeState(ProfileState.SAVING); try { File output = destination != null ? destination : profile.getLoadedFrom(); profileSpecDao.saveProfile(profile, getProfileHomeDir(profile)); profileSaver.saveProfile(getProfileHomeDir(profile).getPath(), output, callback); profile.setLoadedFrom(output); profile.setName(FilenameUtils.getBaseName(output.getName())); profile.onSave(); } finally { profileContextLocator.thawDatabase(profileId); profile.changeState(oldState); } return profile; } /** * @param profileDiskAction * the profile diskaction to set. */ public void setProfileDiskAction(ProfileDiskAction profileDiskAction) { this.profileSaver = profileDiskAction; } /** * Loads a profile from disk, unless that profile is already open. * * @param source * the source file (zipped). * @param observer * an object to be notified when progress is made. * @return the name of the profile. * @throws IOException * - if the file could not be opened, was corrupt, or invalid. */ @Override public ProfileInstance open(File source, ProgressObserver observer) throws IOException { log.info("Loading profile from: " + source.getPath()); ZipFile sourceZip = new ZipFile(source); InputStream in = ProfileFileHelper.getProfileXmlInputStream(sourceZip); ProfileInstance profile; try { profile = profileSpecDao.loadProfile(in); } finally { if (in != null) { in.close(); } sourceZip.close(); } profile.setLoadedFrom(source); profile.setName(FilenameUtils.getBaseName(source.getName())); profile.setUuid(String.valueOf(System.currentTimeMillis())); profile.onLoad(); String profileId = profile.getUuid(); if (!profileContextLocator.hasProfileContext(profileId)) { profileContextLocator.addProfileContext(profile); File destination = getProfileHomeDir(profile); profileSaver.load(source, destination, observer); profileSpecDao.saveProfile(profile, getProfileHomeDir(profile)); profileContextLocator.openProfileInstanceManager(profile); } return profile; } /** * Retrieves all the formats. * @param profileId Profile Id of the profile * for which format is requested. * @return list of formats */ public List<Format> getAllFormats(String profileId) { return getProfileInstanceManager(profileId).getAllFormats(); } /** * {@inheritDoc} */ @Override public ReferenceData getReferenceData(String profileId) { return getProfileInstanceManager(profileId).getReferenceData(); } /** * {@inheritDoc} */ @Override public void setThrottleValue(String uuid, int value) { getProfileInstanceManager(uuid).setThrottleValue(value); } /** * @param signatureManager the signatureManager to set */ public void setSignatureManager(SignatureManager signatureManager) { this.signatureManager = signatureManager; } /** * @param config the config to set */ public void setConfig(DroidGlobalConfig config) { this.config = config; } private File getProfileHomeDir(ProfileInstance profile) { return new File(config.getProfilesDir(), profile.getUuid()); } }
bsd-3-clause
mxOBS/deb-pkg_trusty_chromium-browser
third_party/stp/src/include/stp/AST/ASTSymbol.h
4654
// -*- c++ -*- /******************************************************************** * AUTHORS: Vijay Ganesh, David L. Dill * * BEGIN DATE: November, 2005 * 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 ASTSYMBOL_H #define ASTSYMBOL_H #include "stp/Util/StringHash.h" namespace BEEV { /****************************************************************** * Class ASTSymbol: * * * * Class to represent internals of Symbol node. * ******************************************************************/ class ASTSymbol : public ASTInternal { friend class STPMgr; friend class ASTNode; friend class ASTNodeHasher; friend class ASTNodeEqual; const static ASTVec empty_children; private: /**************************************************************** * Private Data * ****************************************************************/ // The name of the symbol const char* const _name; /**************************************************************** * Class ASTSymbolHasher: * * * * Hasher for ASTSymbol nodes * ****************************************************************/ class ASTSymbolHasher { public: size_t operator()(const ASTSymbol* sym_ptr) const { return CStringHash()(sym_ptr->_name); }; }; // End of class ASTSymbolHasher /**************************************************************** * Class ASTSymbolEqual: * * * * Equality for ASTSymbol nodes * ****************************************************************/ class ASTSymbolEqual { public: bool operator()(const ASTSymbol* sym_ptr1, const ASTSymbol* sym_ptr2) const { return (*sym_ptr1 == *sym_ptr2); } }; // End of class ASTSymbolEqual // comparator friend bool operator==(const ASTSymbol& sym1, const ASTSymbol& sym2) { return (strcmp(sym1._name, sym2._name) == 0); } /**************************************************************** * Private Member Functions * ****************************************************************/ // Get the name of the symbol const char* GetName() const; // Print function for symbol -- return name. (c_friendly is for // printing hex. numbers that C compilers will accept) virtual void nodeprint(ostream& os, bool c_friendly = false); // Call this when deleting a node that has been stored in the the // unique table virtual void CleanUp(); public: virtual ASTVec const& GetChildren() const { return empty_children; } /**************************************************************** * Public Member Functions * ****************************************************************/ // Constructor. This does NOT copy its argument. ASTSymbol(const char* const name) : ASTInternal(SYMBOL), _name(name) {} // Destructor (does nothing, but is declared virtual here. virtual ~ASTSymbol() {} // Copy constructor ASTSymbol(const ASTSymbol& sym) : ASTInternal(sym._kind), _name(sym._name) { // printf("inside ASTSymbol constructor %s\n", _name); } }; // End of ASTSymbol } // end of namespace #endif
bsd-3-clause
racontemoi/shibuichi
cms/code/CMSBatchAction.php
5684
<?php /** * A class representing back actions * * <code> * CMSMain::register_batch_action('publishitems', new CMSBatchAction('doPublish', * _t('CMSBatchActions.PUBLISHED_PAGES', 'published %d pages'))); * </code> * * @package cms * @subpackage batchaction */ abstract class CMSBatchAction extends Object { /** * The the text to show in the dropdown for this action */ abstract function getActionTitle(); /** * Get text to be shown while the action is being processed, of the form * "publishing pages". */ abstract function getDoingText(); /** * Run this action for the given set of pages. * Return a set of status-updated JavaScript to return to the CMS. */ abstract function run(DataObjectSet $pages); /** * Helper method for processing batch actions. * Returns a set of status-updating JavaScript to return to the CMS. * * @param $pages The DataObjectSet of SiteTree objects to perform this batch action * on. * @param $helperMethod The method to call on each of those objects. * @para */ public function batchaction(DataObjectSet $pages, $helperMethod, $successMessage) { foreach($pages as $page) { // Perform the action $page->$helperMethod(); // Now make sure the tree title is appropriately updated $publishedRecord = DataObject::get_by_id('SiteTree', $page->ID); $JS_title = Convert::raw2js($publishedRecord->TreeTitle()); FormResponse::add("\$('sitetree').setNodeTitle($page->ID, '$JS_title');"); $page->destroy(); unset($page); } $message = sprintf($successMessage, $pages->Count()); FormResponse::add('statusMessage("'.$message.'","good");'); return FormResponse::respond(); } } /** * Publish items batch action. * * @package cms * @subpackage batchaction */ class CMSBatchAction_Publish extends CMSBatchAction { function getActionTitle() { return _t('CMSBatchActions.PUBLISH_PAGES', 'Publish'); } function getDoingText() { return _t('CMSBatchActions.PUBLISHING_PAGES', 'Publishing pages'); } function run(DataObjectSet $pages) { return $this->batchaction($pages, 'doPublish', _t('CMSBatchActions.PUBLISHED_PAGES', 'Published %d pages') ); } } /** * Un-publish items batch action. * * @package cms * @subpackage batchaction */ class CMSBatchAction_Unpublish extends CMSBatchAction { function getActionTitle() { return _t('CMSBatchActions.UNPUBLISH_PAGES', 'Un-publish'); } function getDoingText() { return _t('CMSBatchActions.UNPUBLISHING_PAGES', 'Un-publishing pages'); } function run(DataObjectSet $pages) { return $this->batchaction($pages, 'doUnpublish', _t('CMSBatchActions.UNPUBLISHED_PAGES', 'Un-published %d pages') ); } } /** * Delete items batch action. * * @package cms * @subpackage batchaction */ class CMSBatchAction_Delete extends CMSBatchAction { function getActionTitle() { return _t('CMSBatchActions.DELETE_PAGES', 'Delete from draft'); } function getDoingText() { return _t('CMSBatchActions.DELETING_PAGES', 'Deleting selected pages from draft'); } function run(DataObjectSet $pages) { foreach($pages as $page) { $id = $page->ID; // Perform the action if($page->canDelete()) $page->delete(); // check to see if the record exists on the live site, if it doesn't remove the tree node $liveRecord = Versioned::get_one_by_stage( 'SiteTree', 'Live', "`SiteTree`.`ID`=$id"); if($liveRecord) { $liveRecord->IsDeletedFromStage = true; $title = Convert::raw2js($liveRecord->TreeTitle()); FormResponse::add("$('sitetree').setNodeTitle($id, '$title');"); FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);"); } else { FormResponse::add("var node = $('sitetree').getTreeNodeByIdx('$id');"); FormResponse::add("if(node && node.parentTreeNode) node.parentTreeNode.removeTreeNode(node);"); FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);"); } $page->destroy(); unset($page); } $message = sprintf(_t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the draft site'), $pages->Count()); FormResponse::add('statusMessage("'.$message.'","good");'); return FormResponse::respond(); } } /** * Delete items batch action. * * @package cms * @subpackage batchaction */ class CMSBatchAction_DeleteFromLive extends CMSBatchAction { function getActionTitle() { return _t('CMSBatchActions.DELETE_PAGES', 'Delete from published site'); } function getDoingText() { return _t('CMSBatchActions.DELETING_PAGES', 'Deleting selected pages from the published site'); } function run(DataObjectSet $pages) { foreach($pages as $page) { $id = $page->ID; // Perform the action if($page->canDelete()) $page->doDeleteFromLive(); // check to see if the record exists on the live site, if it doesn't remove the tree node $stageRecord = Versioned::get_one_by_stage( 'SiteTree', 'Stage', "`SiteTree`.`ID`=$id"); if($stageRecord) { $stageRecord->IsAddedToStage = true; $title = Convert::raw2js($stageRecord->TreeTitle()); FormResponse::add("$('sitetree').setNodeTitle($id, '$title');"); FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);"); } else { FormResponse::add("var node = $('sitetree').getTreeNodeByIdx('$id');"); FormResponse::add("if(node && node.parentTreeNode) node.parentTreeNode.removeTreeNode(node);"); FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);"); } $page->destroy(); unset($page); } $message = sprintf(_t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the published site'), $pages->Count()); FormResponse::add('statusMessage("'.$message.'","good");'); return FormResponse::respond(); } }
bsd-3-clause
sunny2601/spree1
core/app/models/spree/item_adjustments.rb
2999
module Spree # Manage (recalculate) item (LineItem or Shipment) adjustments class ItemAdjustments include ActiveSupport::Callbacks define_callbacks :promo_adjustments, :tax_adjustments attr_reader :item delegate :adjustments, :order, to: :item def initialize(item) @item = item # Don't attempt to reload the item from the DB if it's not there @item.reload if @item.instance_of?(Shipment) && @item.persisted? end def update update_adjustments if item.persisted? item end # TODO this should be probably the place to calculate proper item taxes # values after promotions are applied def update_adjustments # Promotion adjustments must be applied first, then tax adjustments. # This fits the criteria for VAT tax as outlined here: # http://www.hmrc.gov.uk/vat/managing/charging/discounts-etc.htm#1 # # It also fits the criteria for sales tax as outlined here: # http://www.boe.ca.gov/formspubs/pub113/ # # Tax adjustments come in not one but *two* exciting flavours: # Included & additional # Included tax adjustments are those which are included in the price. # These ones should not affect the eventual total price. # # Additional tax adjustments are the opposite, affecting the final total. promo_total = 0 run_callbacks :promo_adjustments do promotion_total = adjustments.promotion.reload.map do |adjustment| adjustment.update!(@item) end.compact.sum unless promotion_total == 0 choose_best_promotion_adjustment end promo_total = best_promotion_adjustment.try(:amount).to_f end included_tax_total = 0 additional_tax_total = 0 run_callbacks :tax_adjustments do tax = (item.respond_to?(:all_adjustments) ? item.all_adjustments : item.adjustments).tax included_tax_total = tax.is_included.reload.map(&:update!).compact.sum additional_tax_total = tax.additional.reload.map(&:update!).compact.sum end item.update_columns( :promo_total => promo_total, :included_tax_total => included_tax_total, :additional_tax_total => additional_tax_total, :adjustment_total => promo_total + additional_tax_total, :updated_at => Time.now, ) end # Picks one (and only one) promotion to be eligible for this order # This promotion provides the most discount, and if two promotions # have the same amount, then it will pick the latest one. def choose_best_promotion_adjustment if best_promotion_adjustment other_promotions = self.adjustments.promotion.where.not(id: best_promotion_adjustment.id) other_promotions.update_all(:eligible => false) end end def best_promotion_adjustment @best_promotion_adjustment ||= adjustments.promotion.eligible.reorder("amount ASC, created_at DESC, id DESC").first end end end
bsd-3-clause
jakemac53/polymer_elements
lib/src/iron-form/iron-form.html
8910
<!-- @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <link rel="import" href="../polymer/polymer.html"> <link rel="import" href="../iron-ajax/iron-ajax.html"> <script> /* ``<iron-form>` is an HTML `<form>` element that can validate and submit any custom elements that implement `Polymer.IronFormElementBehavior`, as well as any native HTML elements. It supports both `get` and `post` methods, and uses an `iron-ajax` element to submit the form data to the action URL. Example: <form is="iron-form" id="form" method="post" action="/form/handler"> <paper-input name="name" label="name"></paper-input> <input name="address"> ... </form> By default, a native `<button>` element will submit this form. However, if you want to submit it from a custom element's click handler, you need to explicitly call the form's `submit` method. Example: <paper-button raised onclick="submitForm()">Submit</paper-button> function submitForm() { document.getElementById('form').submit(); } @demo demo/index.html */ Polymer({ is: 'iron-form', extends: 'form', properties: { /** * Content type to use when sending data. */ contentType: { type: String, value: "application/x-www-form-urlencoded" }, /** * By default, the form will display the browser's native validation * UI (i.e. popup bubbles and invalid styles on invalid fields). You can * manually disable this; however, if you do, note that you will have to * manually style invalid *native* HTML fields yourself, as you are * explicitly preventing the native form from doing so. */ disableNativeValidationUi: { type: Boolean, value: false }, /** * Set the withCredentials flag when sending data. */ withCredentials: { type: Boolean, value: false } }, /** * Fired if the form cannot be submitted because it's invalid. * * @event iron-form-invalid */ /** * Fired after the form is submitted. * * @event iron-form-submit */ /** * Fired after the form is submitted and a response is received. * * @event iron-form-response */ /** * Fired after the form is submitted and an error is received. * * @event iron-form-error */ listeners: { 'iron-form-element-register': '_registerElement', 'iron-form-element-unregister': '_unregisterElement', 'submit': '_onSubmit' }, ready: function() { // Object that handles the ajax form submission request. this._requestBot = document.createElement('iron-ajax'); this._requestBot.addEventListener('response', this._handleFormResponse.bind(this)); this._requestBot.addEventListener('error', this._handleFormError.bind(this)); // Holds all the custom elements registered with this form. this._customElements = []; }, /** * Called to submit the form. */ submit: function() { if (!this.noValidate && !this.validate()) { // In order to trigger the native browser invalid-form UI, we need // to do perform a fake form submit. if (!this.disableNativeValidationUi) { this._doFakeSubmitForValidation(); } this.fire('iron-form-invalid'); return; } var json = this.serialize(); this._requestBot.url = this.action; this._requestBot.method = this.method; this._requestBot.contentType = this.contentType; this._requestBot.withCredentials = this.withCredentials; if (this.method.toUpperCase() == 'POST') { this._requestBot.body = json; } else { this._requestBot.params = json; } this._requestBot.generateRequest(); this.fire('iron-form-submit', json); }, _onSubmit: function(event) { this.submit(); // Don't perform a page refresh. if (event) { event.preventDefault(); } return false; }, /** * Returns a json object containing name/value pairs for all the registered * custom components and native elements of the form. If there are elements * with duplicate names, then their values will get aggregated into an * array of values. * * @return {!Object} */ serialize: function() { var json = {}; function addSerializedElement(el) { // If the name doesn't exist, add it. Otherwise, serialize it to // an array, if (!json[el.name]) { json[el.name] = el.value; } else { if (!Array.isArray(json[el.name])) { json[el.name] = [json[el.name]]; } json[el.name].push(el.value); } } // Go through all of the registered custom components. for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) { if (this._useValue(el)) { addSerializedElement(el); } } // Also go through the form's native elements. for (var el, i = 0; el = this.elements[i], i < this.elements.length; i++) { // Checkboxes and radio buttons should only use their value if they're checked. // Also, custom elements that extend native elements (like an // `<input is="fancy-input">`) will appear in both lists. Since they // were already added as a custom element, they don't need // to be re-added. if (!this._useValue(el) || (el.hasAttribute('is') && json[el.name])) { continue; } addSerializedElement(el); } return json; }, _handleFormResponse: function (event) { this.fire('iron-form-response', event.detail.response); }, _handleFormError: function (event) { this.fire('iron-form-error', event.detail); }, _registerElement: function(e) { e.target._parentForm = this; this._customElements.push(e.target); }, _unregisterElement: function(e) { var target = e.detail.target; if (target) { var index = this._customElements.indexOf(target); if (index > -1) { this._customElements.splice(index, 1); } } }, /** * Validates all the required elements (custom and native) in the form. * @return {boolean} True if all the elements are valid. */ validate: function() { var valid = true; // Validate all the custom elements. var validatable; for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) { if (el.required && this._useValue(el)) { validatable = /** @type {{validate: (function() : boolean)}} */ (el); // TODO(notwaldorf): IronValidatableBehavior can return undefined if // a validator is not set. It probably shouldn't, but in the meantime // deal with that scenario. valid = !!validatable.validate() && valid; } } // Validate the form's native elements. for (var el, i = 0; el = this.elements[i], i < this.elements.length; i++) { // Custom elements that extend a native element will also appear in // this list, but they've already been validated. if (!el.hasAttribute('is') && el.willValidate && el.checkValidity && el.name) { valid = el.checkValidity() && valid; } } return valid; }, _useValue: function(el) { // Skip disabled elements or elements that don't have a `name` attribute. if (el.disabled || !el.name) { return false; } // Checkboxes and radio buttons should only use their value if they're // checked. Custom paper-checkbox and paper-radio-button elements // don't have a type, but they have the correct role set. if (el.type == 'checkbox' || el.type == 'radio' || el.getAttribute('role') == 'checkbox' || el.getAttribute('role') == 'radio') { return el.checked; } return true; }, _doFakeSubmitForValidation: function() { var fakeSubmit = document.createElement('input'); fakeSubmit.setAttribute('type', 'submit'); fakeSubmit.style.display = 'none'; this.appendChild(fakeSubmit); fakeSubmit.click(); this.removeChild(fakeSubmit); } }); </script>
bsd-3-clause
internetbrands/vbimpex
tools/404.php
14263
<? /*======================================================================*\ || #################################################################### || # vBulletin Impex || # ---------------------------------------------------------------- || # All PHP code in this file is Copyright 2000-2014 vBulletin Solutions Inc. || # This code is made available under the Modified BSD License -- see license.txt || # http://www.vbulletin.com || #################################################################### \*======================================================================*/ /** * 404 for external and internal link redirect. * * @package ImpEx.tools * */ /* Ensure you have this table for logging CREATE TABLE `404_actions` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `time` INT UNSIGNED NOT NULL , `incomming` VARCHAR( 250 ) NOT NULL , `outgoing` VARCHAR( 250 ) NOT NULL , `action` TINYINT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY ( `id` ) ) TYPE = MYISAM ; If you have a high volume site and lot of redirects going on, a HEAP / ENGINE=MEMORY table could be a lot better. */ // System #Currently supported : 'phpBB2' 'ubb.threads' 'vb3' 'ipb2' $old_system = 'phpBB2'; // Domain // Example :: http://www.example.com/phpBB/ $old_folder = 'phpBB/'; // With trailing slash $old_ext_type = '.php'; // Including preceding dot $standard_404 = 'http://www.example.com/not_found.html'; // The usual 404 that this script replaces // Example :: www.example.com/vBulletin/ $new_domain = 'example'; $new_folder = 'vBulletin/'; // With trailing slash $ext_type = '.php'; // File extension type that vBulletin is using, i.e. index.php including the preceding dot // Database // This is the vBulletin database, needed for import id look up and logging $server = 'localhost'; $user = 'user'; $password = 'password'; $database = 'forum'; $tableprefix = ''; // System $refresh_speed = 0; // Speed of the redirect, 0 advised. $do_logs = true; // Always best to log to see that its working and if there are any "Unknown link type, talk to Jerry" links $do_404 = false; // true = a 404 (Not Found) redirect. false is a 301 search engine friendly redirect (Moved Permanently) $debug = false; // This is will stop the script from actually redirecting, it will just display what the SQL and the action ############################################################################################################################# # Don't touch below ############################################################################################################################# $old_id = 0; $action_code = 0; $action = null; $sql = null; $page = null; $postcount = null; // Get the file names and types switch ($old_system) { case 'phpBB2' : $old_forum_script = "viewforum{$old_ext_type}?f="; $old_thread_script = "viewtopic{$old_ext_type}?t="; $old_post_script = "viewtopic{$old_ext_type}?p="; $old_user_script = "profile{$old_ext_type}?mode=viewprofile&u="; // Append userid break; case 'ubb.threads' : $old_forum_script = "postlist{$old_ext_type}?"; // postlist.php?Cat=&Board=beadtechniques -- have to try to do it on title $old_thread_script = "showflat{$old_ext_type}?"; // Cat=&Board=beadtechniques&Number=74690&page=0&view=collapsed&sb=5&o=&fpart=1Greg Go for Number=XX $old_post_script = "showthreaded{$old_ext_type}?"; // ubbthreads/showthreaded.php?Cat=&Board=othertopics&Number=79355&page=0&view=collapsed&sb=5&o=&fpart=1 -- going to thread link, not post, meh $old_user_script = "showprofile{$old_ext_type}"; // ubbthreads/showprofile.php?Cat=&User=SaraSally&Board=isgbannounce&what=ubbthreads&page=0&view=collapsed&sb=5&o -- username break; case 'vb3' : $old_forum_script = "forumdisplay{$old_ext_type}?f="; $old_thread_script = "showthread{$old_ext_type}?p="; $old_post_script = "showpost{$old_ext_type}?p="; $old_user_script = "member{$old_ext_type}?u="; break; case 'ipb2' : // Single file controller, these are here for refrence, the preg_match finds the actual type during the matching $old_forum_script = "showforum="; // index.php?s=29ef4154d9b74e8978e60ca39ecb506a&showforum=X $old_thread_script = "index.php?showtopic="; $old_post_script = "index.php?"; // index.php?s=&showtopic=209664&view=findpost&p=XXXXXXXX $old_user_script = "index.php?showuser="; // index.php?showuser=XXXXX break; default : // No valid system entered die('No valid system entered'); } // It's for the old forum if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}") === 0) { switch ($old_system) { case 'phpBB2' : // It's a forum link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0) { $action = 'forum'; $old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?f=')+3)); $sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}"; } // It's a thread link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0) { $action = 'thread'; if( preg_match("/&/", $_SERVER['REQUEST_URI']) ) { $old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 2), 0, strpos(substr($_SERVER['REQUEST_URI'], 2), '&'))); $sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}"; } else { $old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?t=')+3)); $sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}"; } } // It's a post link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0) { $action = 'post'; if( preg_match("/&/", $_SERVER['REQUEST_URI']) ) { $old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 2), 0, strpos(substr($_SERVER['REQUEST_URI'], 2), '&'))); $sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$old_id}"; } else { $old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?p=')+3)); $sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$old_id}"; } } // It's a user link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0) { $action = 'user'; // Cuts 12 out of this : profile.php?mode=viewprofile&u=12&sid=f646e2a0948e0244ba82cef12c3b93d8 $old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 19), 0, strpos(substr($_SERVER['REQUEST_URI'], 19), '&'))); $sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid={$old_id}"; } break; case 'ubb.threads' : // It's a forum link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0) { $action = 'forum'; $old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'Board=')+6)); $sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}"; } // It's a thread link (Will get direct post links some times too) if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0) { $action = 'thread'; $begin = strpos ($url, 'Number='); $middle = strpos ($url, '&', $begin); $old_id = intval(substr($url, $begin+7, ($middle-$begin)-7)); // +7 & -7 To remove the off set of Number= $sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}"; } // It's a post link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0) { if(preg_match('#(.*)Number=(.*)&(.*)#Uis', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[2])) { $action = 'post'; $sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid = " . $matches[2]; } } } // It's a user link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0) { if(preg_match('#(.*)User=(.*)&(.*)#Uis', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[2])) { $action = 'post'; $sql = "SELECT userid FROM {$tableprefix}user WHERE importpostid = " . $matches[2]; } } } break; case 'vb3' : // It's a forum link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0) { $action = 'forum'; $old_id = intval(substr($_SERVER['REQUEST_URI'], 2, abs(strpos($_SERVER['REQUEST_URI'], '&',2)-2))); $sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}"; } // It's a thread link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0) { $action = 'thread'; if (strpos($_SERVER['REQUEST_URI'], '&page=')) // If its paged { preg_match('#(.*)\?t=([0-9]+)\&page=([0-9]+)#si', $_SERVER['REQUEST_URI'], $matches); if ($matches[2] AND $matches[3]) { $matches[2] = intval($matches[2]); $sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid=" . $matches[2]; $page = $matches[3]; } } else { if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?t=')+3)) { $id = intval($id); $sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$id}"; } } } // It's a post link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0) { $action = 'post'; if (strpos($_SERVER['REQUEST_URI'], '&postcount=')) // If its postcounted { preg_match('#(.*)\?p=([0-9]+)\&postcount=([0-9]+)#si', $_SERVER['REQUEST_URI'], $matches); if ($matches[2] AND $matches[3]) { $matches[2] = intval($matches[2]); $sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid = " . $matches[2]; $postcount = $matches[3]; } } else { if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?p=')+3)) { $id = intval($id); $sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$id}"; } } } // It's a user link if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0) { $action = 'user'; if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?u=')+3)) { $id = intval($id); $sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid ={$id}"; } } break; case 'ipb2' : if(preg_match('#index.php?(.*)&showforum=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[2])) { $matches[2] = intval($matches[2]); $action = 'forum'; $sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid=" . $matches[2]; } } // It's a thread link if(preg_match('#index.php\?showtopic=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[1])) { $action = 'thread'; $sql = "SELECT threadid FROM {$tableprefix}forum WHERE importthreadid=" . $matches[1]; } } // It's a post link if(preg_match('#view=findpost\&p=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[1])) { $action = 'post'; $sql = "SELECT postid FROM {$tableprefix}forum WHERE importpostid=" . $matches[1]; } } // It's a user link if(preg_match('#index.php\?showuser=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches)) { if (is_numeric($matches[1])) { $action = 'user'; $sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid =" . $matches[1]; } } break; default : // No valid system entered die('No valid system entered'); } if (!$action) { $action = 'log'; } } if ($debug) { echo "<html><head><title>404 debug</title></head><body>"; echo "<br>Action :: " . $action; echo "<br>SQL :: " . $sql; echo "<br>REQUEST_URI :: " . $_SERVER['REQUEST_URI'] ; echo "</body></html>"; die; } if (!$action) { ?> <html> <head> <meta http-equiv="refresh" content="<? echo $refresh_speed; ?>; URL=<? echo $standard_404; ?>"> </head> <body> </body> </html> <? // Got nuffink die; } // If we are here we have data to look up and redirect to a vBulletin page. $link = @mysql_connect($server, $user, $password); if (!$link) { #die('Could not connect: ' . mysql_error()); $new_url = $standard_404; } $db_selected = @mysql_select_db($database, $link); if (!$db_selected) { #die ('Can\'t use foo : ' . mysql_error()); $new_url = $standard_404; } if ($sql) { $result = @mysql_query($sql); $row = @mysql_fetch_row($result); if (!$row[0]) { $action = 'Original data missing'; } @mysql_free_result($result); } // Just incase $new_url = $standard_404; switch ($action) { case 'cat': case 'forum': $new_url = "http://{$new_domain}/{$new_folder}forumdisplay{$ext_type}?f=" . $row[0]; $action_code = 1; break; case 'thread': $new_url = "http://{$new_domain}/{$new_folder}showthread{$ext_type}?t=" . $row[0]; if ($page) { $new_url .= "&page={$page}"; } $action_code = 2; break; case 'post': $new_url = "http://{$new_domain}/{$new_folder}showpost{$ext_type}?p=" . $row[0]; if ($postcount) { $new_url .= "&postcount={$postcount}"; } $action_code = 3; break; case 'user': $new_url = "http://{$new_domain}/{$new_folder}member{$ext_type}?u=" . $row[0]; $action_code = 4; break; case 'Original data missing': $action_code = 10; break; default : $action_code = 20; break; } // Do logging ? if ($do_logs) { // Codes # forum = 1 # thread = 2 # post = 3 # user = 4 # script error = 0 # Original data missing = 10 # Unknown link type, talk to Jerry = 20 $sql = " INSERT INTO {$tableprefix}404_actions ( time, incomming, outgoing, action ) VALUES ( " . time() . ", '" . $_SERVER['REQUEST_URI'] . "', '" . $new_url . "', '" . $action_code . "' ) "; mysql_query($sql); } @mysql_close($link); // Do the new redirect if ($do_404) { ?> <html> <head> <meta http-equiv="refresh" content="<? echo $refresh_speed; ?> URL=<? echo $new_url; ?>"> </head> <body> </body> </html> <? } else { Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: {$new_url}" ); } // Da end ?>
bsd-3-clause
aYukiSekiguchi/ACCESS-Chromium
net/base/cert_database_nss.cc
11164
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/cert_database.h" #include <cert.h> #include <certdb.h> #include <keyhi.h> #include <pk11pub.h> #include <secmod.h> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "crypto/nss_util.h" #include "crypto/nss_util_internal.h" #include "net/base/crypto_module.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" #include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h" #include "net/third_party/mozilla_security_manager/nsNSSCertTrust.h" #include "net/third_party/mozilla_security_manager/nsPKCS12Blob.h" // In NSS 3.13, CERTDB_VALID_PEER was renamed CERTDB_TERMINAL_RECORD. So we use // the new name of the macro. #if !defined(CERTDB_TERMINAL_RECORD) #define CERTDB_TERMINAL_RECORD CERTDB_VALID_PEER #endif // PSM = Mozilla's Personal Security Manager. namespace psm = mozilla_security_manager; namespace net { CertDatabase::CertDatabase() { crypto::EnsureNSSInit(); psm::EnsurePKCS12Init(); } int CertDatabase::CheckUserCert(X509Certificate* cert_obj) { if (!cert_obj) return ERR_CERT_INVALID; if (cert_obj->HasExpired()) return ERR_CERT_DATE_INVALID; // Check if the private key corresponding to the certificate exist // We shouldn't accept any random client certificate sent by a CA. // Note: The NSS source documentation wrongly suggests that this // also imports the certificate if the private key exists. This // doesn't seem to be the case. CERTCertificate* cert = cert_obj->os_cert_handle(); PK11SlotInfo* slot = PK11_KeyForCertExists(cert, NULL, NULL); if (!slot) { LOG(ERROR) << "No corresponding private key in store"; return ERR_NO_PRIVATE_KEY_FOR_CERT; } PK11_FreeSlot(slot); return OK; } int CertDatabase::AddUserCert(X509Certificate* cert_obj) { CERTCertificate* cert = cert_obj->os_cert_handle(); PK11SlotInfo* slot = NULL; { crypto::AutoNSSWriteLock lock; slot = PK11_ImportCertForKey( cert, cert_obj->GetDefaultNickname(net::USER_CERT).c_str(), NULL); } if (!slot) { LOG(ERROR) << "Couldn't import user certificate."; return ERR_ADD_USER_CERT_FAILED; } PK11_FreeSlot(slot); CertDatabase::NotifyObserversOfUserCertAdded(cert_obj); return OK; } void CertDatabase::ListCerts(CertificateList* certs) { certs->clear(); CERTCertList* cert_list = PK11_ListCerts(PK11CertListUnique, NULL); CERTCertListNode* node; for (node = CERT_LIST_HEAD(cert_list); !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { certs->push_back(X509Certificate::CreateFromHandle( node->cert, X509Certificate::OSCertHandles())); } CERT_DestroyCertList(cert_list); } CryptoModule* CertDatabase::GetPublicModule() const { CryptoModule* module = CryptoModule::CreateFromHandle(crypto::GetPublicNSSKeySlot()); // The module is already referenced when returned from // GetPublicNSSKeySlot, so we need to deref it once. PK11_FreeSlot(module->os_module_handle()); return module; } CryptoModule* CertDatabase::GetPrivateModule() const { CryptoModule* module = CryptoModule::CreateFromHandle(crypto::GetPrivateNSSKeySlot()); // The module is already referenced when returned from // GetPrivateNSSKeySlot, so we need to deref it once. PK11_FreeSlot(module->os_module_handle()); return module; } void CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const { modules->clear(); PK11SlotList* slot_list = NULL; // The wincx arg is unused since we don't call PK11_SetIsLoggedInFunc. slot_list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, need_rw ? PR_TRUE : PR_FALSE, // needRW PR_TRUE, // loadCerts (unused) NULL); // wincx if (!slot_list) { LOG(ERROR) << "PK11_GetAllTokens failed: " << PORT_GetError(); return; } PK11SlotListElement* slot_element = PK11_GetFirstSafe(slot_list); while (slot_element) { modules->push_back(CryptoModule::CreateFromHandle(slot_element->slot)); slot_element = PK11_GetNextSafe(slot_list, slot_element, PR_FALSE); // restart } PK11_FreeSlotList(slot_list); } int CertDatabase::ImportFromPKCS12( CryptoModule* module, const std::string& data, const string16& password, bool is_extractable, net::CertificateList* imported_certs) { int result = psm::nsPKCS12Blob_Import(module->os_module_handle(), data.data(), data.size(), password, is_extractable, imported_certs); if (result == net::OK) CertDatabase::NotifyObserversOfUserCertAdded(NULL); return result; } int CertDatabase::ExportToPKCS12( const CertificateList& certs, const string16& password, std::string* output) const { return psm::nsPKCS12Blob_Export(output, certs, password); } X509Certificate* CertDatabase::FindRootInList( const CertificateList& certificates) const { DCHECK_GT(certificates.size(), 0U); if (certificates.size() == 1) return certificates[0].get(); X509Certificate* cert0 = certificates[0]; X509Certificate* cert1 = certificates[1]; X509Certificate* certn_2 = certificates[certificates.size() - 2]; X509Certificate* certn_1 = certificates[certificates.size() - 1]; if (CERT_CompareName(&cert1->os_cert_handle()->issuer, &cert0->os_cert_handle()->subject) == SECEqual) return cert0; if (CERT_CompareName(&certn_2->os_cert_handle()->issuer, &certn_1->os_cert_handle()->subject) == SECEqual) return certn_1; VLOG(1) << "certificate list is not a hierarchy"; return cert0; } bool CertDatabase::ImportCACerts(const CertificateList& certificates, TrustBits trust_bits, ImportCertFailureList* not_imported) { X509Certificate* root = FindRootInList(certificates); bool success = psm::ImportCACerts(certificates, root, trust_bits, not_imported); if (success) CertDatabase::NotifyObserversOfCertTrustChanged(NULL); return success; } bool CertDatabase::ImportServerCert(const CertificateList& certificates, ImportCertFailureList* not_imported) { return psm::ImportServerCert(certificates, not_imported); } CertDatabase::TrustBits CertDatabase::GetCertTrust(const X509Certificate* cert, CertType type) const { CERTCertTrust nsstrust; SECStatus srv = CERT_GetCertTrust(cert->os_cert_handle(), &nsstrust); if (srv != SECSuccess) { LOG(ERROR) << "CERT_GetCertTrust failed with error " << PORT_GetError(); return UNTRUSTED; } psm::nsNSSCertTrust trust(&nsstrust); switch (type) { case CA_CERT: return trust.HasTrustedCA(PR_TRUE, PR_FALSE, PR_FALSE) * TRUSTED_SSL + trust.HasTrustedCA(PR_FALSE, PR_TRUE, PR_FALSE) * TRUSTED_EMAIL + trust.HasTrustedCA(PR_FALSE, PR_FALSE, PR_TRUE) * TRUSTED_OBJ_SIGN; case SERVER_CERT: return trust.HasTrustedPeer(PR_TRUE, PR_FALSE, PR_FALSE) * TRUSTED_SSL + trust.HasTrustedPeer(PR_FALSE, PR_TRUE, PR_FALSE) * TRUSTED_EMAIL + trust.HasTrustedPeer(PR_FALSE, PR_FALSE, PR_TRUE) * TRUSTED_OBJ_SIGN; default: return UNTRUSTED; } } bool CertDatabase::IsUntrusted(const X509Certificate* cert) const { CERTCertTrust nsstrust; SECStatus rv = CERT_GetCertTrust(cert->os_cert_handle(), &nsstrust); if (rv != SECSuccess) { LOG(ERROR) << "CERT_GetCertTrust failed with error " << PORT_GetError(); return false; } // The CERTCertTrust structure contains three trust records: // sslFlags, emailFlags, and objectSigningFlags. The three // trust records are independent of each other. // // If the CERTDB_TERMINAL_RECORD bit in a trust record is set, // then that trust record is a terminal record. A terminal // record is used for explicit trust and distrust of an // end-entity or intermediate CA cert. // // In a terminal record, if neither CERTDB_TRUSTED_CA nor // CERTDB_TRUSTED is set, then the terminal record means // explicit distrust. On the other hand, if the terminal // record has either CERTDB_TRUSTED_CA or CERTDB_TRUSTED bit // set, then the terminal record means explicit trust. // // For a root CA, the trust record does not have // the CERTDB_TERMINAL_RECORD bit set. static const unsigned int kTrusted = CERTDB_TRUSTED_CA | CERTDB_TRUSTED; if ((nsstrust.sslFlags & CERTDB_TERMINAL_RECORD) != 0 && (nsstrust.sslFlags & kTrusted) == 0) { return true; } if ((nsstrust.emailFlags & CERTDB_TERMINAL_RECORD) != 0 && (nsstrust.emailFlags & kTrusted) == 0) { return true; } if ((nsstrust.objectSigningFlags & CERTDB_TERMINAL_RECORD) != 0 && (nsstrust.objectSigningFlags & kTrusted) == 0) { return true; } // Self-signed certificates that don't have any trust bits set are untrusted. // Other certificates that don't have any trust bits set may still be trusted // if they chain up to a trust anchor. if (CERT_CompareName(&cert->os_cert_handle()->issuer, &cert->os_cert_handle()->subject) == SECEqual) { return (nsstrust.sslFlags & kTrusted) == 0 && (nsstrust.emailFlags & kTrusted) == 0 && (nsstrust.objectSigningFlags & kTrusted) == 0; } return false; } bool CertDatabase::SetCertTrust(const X509Certificate* cert, CertType type, TrustBits trust_bits) { bool success = psm::SetCertTrust(cert, type, trust_bits); if (success) CertDatabase::NotifyObserversOfCertTrustChanged(cert); return success; } bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) { // For some reason, PK11_DeleteTokenCertAndKey only calls // SEC_DeletePermCertificate if the private key is found. So, we check // whether a private key exists before deciding which function to call to // delete the cert. SECKEYPrivateKey *privKey = PK11_FindKeyByAnyCert(cert->os_cert_handle(), NULL); if (privKey) { SECKEY_DestroyPrivateKey(privKey); if (PK11_DeleteTokenCertAndKey(cert->os_cert_handle(), NULL)) { LOG(ERROR) << "PK11_DeleteTokenCertAndKey failed: " << PORT_GetError(); return false; } } else { if (SEC_DeletePermCertificate(cert->os_cert_handle())) { LOG(ERROR) << "SEC_DeletePermCertificate failed: " << PORT_GetError(); return false; } } CertDatabase::NotifyObserversOfUserCertRemoved(cert); return true; } bool CertDatabase::IsReadOnly(const X509Certificate* cert) const { PK11SlotInfo* slot = cert->os_cert_handle()->slot; return slot && PK11_IsReadOnly(slot); } } // namespace net
bsd-3-clause
personalrobotics/aikido
python/aikidopy/planner/module.cpp
266
#include <pybind11/pybind11.h> namespace py = pybind11; namespace aikido { namespace python { void World(py::module& sm); void aikidopy_planner(py::module& m) { auto sm = m.def_submodule("planner"); World(sm); } } // namespace python } // namespace aikido
bsd-3-clause
Clashsoft/Dyvil
compiler/src/main/java/dyvilx/tools/compiler/ast/generic/TypeParameter.java
13621
package dyvilx.tools.compiler.ast.generic; import dyvil.annotation.Reified; import dyvil.annotation.internal.NonNull; import dyvil.annotation.internal.Nullable; import dyvil.lang.Name; import dyvilx.tools.asm.TypeAnnotatableVisitor; import dyvilx.tools.asm.TypeReference; import dyvilx.tools.compiler.ast.attribute.AttributeList; import dyvilx.tools.compiler.ast.attribute.annotation.Annotation; import dyvilx.tools.compiler.ast.classes.IClass; import dyvilx.tools.compiler.ast.expression.IValue; import dyvilx.tools.compiler.ast.expression.constant.EnumValue; import dyvilx.tools.compiler.ast.field.IDataMember; import dyvilx.tools.compiler.ast.method.IMethod; import dyvilx.tools.compiler.ast.method.MatchList; import dyvilx.tools.compiler.ast.parameter.ArgumentList; import dyvilx.tools.compiler.ast.parameter.IParameter; import dyvilx.tools.compiler.ast.type.IType; import dyvilx.tools.compiler.ast.type.builtin.Types; import dyvilx.tools.compiler.ast.type.compound.IntersectionType; import dyvilx.tools.compiler.ast.type.typevar.CovariantTypeVarType; import dyvilx.tools.compiler.backend.exception.BytecodeException; import dyvilx.tools.compiler.backend.method.MethodWriter; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.List; import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperClass; import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperType; public abstract class TypeParameter implements ITypeParameter { // =============== Fields =============== // --------------- Accompanying Member --------------- protected ITypeParametric generic; // --------------- Declaration --------------- protected @NonNull AttributeList attributes = new AttributeList(); protected Variance variance = Variance.INVARIANT; protected Name name; private @NonNull IType upperBound = Types.NULLABLE_ANY; protected @Nullable IType lowerBound; // --------------- Metadata --------------- private IType safeUpperBound; private IType[] upperBounds; protected Reified.Type reifiedKind; // defaults to null (not reified) protected IParameter reifyParameter; private final IType covariantType = new CovariantTypeVarType(this); // =============== Constructors =============== public TypeParameter(ITypeParametric generic) { this.generic = generic; } public TypeParameter(ITypeParametric generic, Name name) { this.name = name; this.generic = generic; } public TypeParameter(ITypeParametric generic, Name name, Variance variance) { this.name = name; this.generic = generic; this.variance = variance; } // =============== Properties =============== // --------------- Accompanying Member --------------- @Override public ITypeParametric getGeneric() { return this.generic; } @Override public void setGeneric(ITypeParametric generic) { this.generic = generic; } // --------------- Attributes --------------- @Override public ElementType getElementType() { return ElementType.TYPE_PARAMETER; } @Override public AttributeList getAttributes() { return this.attributes; } @Override public void setAttributes(AttributeList attributes) { this.attributes = attributes; } @Override public final Annotation getAnnotation(IClass type) { return this.attributes.getAnnotation(type); } @Override public boolean skipAnnotation(String type, Annotation annotation) { switch (type) { case "dyvil/annotation/internal/Covariant": this.variance = Variance.COVARIANT; return true; case "dyvil/annotation/internal/Contravariant": this.variance = Variance.CONTRAVARIANT; return true; } return false; } // --------------- Reification --------------- protected void computeReifiedKind() { if (this.reifiedKind != null) { return; } final Annotation reifiedAnnotation = this.getAnnotation(Types.REIFIED_CLASS); if (reifiedAnnotation != null) { final IParameter parameter = Types.REIFIED_CLASS.getParameters().get(0); this.reifiedKind = EnumValue .eval(reifiedAnnotation.getArguments().getOrDefault(parameter), Reified.Type.class); } } @Override public Reified.Type getReifiedKind() { return this.reifiedKind; } @Override public IParameter getReifyParameter() { return this.reifyParameter; } @Override public void setReifyParameter(IParameter parameter) { this.reifyParameter = parameter; } // --------------- Variance --------------- @Override public Variance getVariance() { return this.variance; } @Override public void setVariance(Variance variance) { this.variance = variance; } // --------------- Name --------------- @Override public Name getName() { return this.name; } @Override public void setName(Name name) { this.name = name; } // --------------- Upper Bound --------------- @Override public IType getUpperBound() { if (this.upperBound != null) { return this.upperBound; } final IType[] upperBounds = this.getUpperBounds(); if (upperBounds != null) { return this.upperBound = getUpperBound(upperBounds, 0, upperBounds.length); } return null; } @Override public void setUpperBound(IType bound) { this.upperBound = bound; this.upperBounds = null; this.safeUpperBound = null; } public IType[] getUpperBounds() { if (this.upperBounds != null) { return this.upperBounds; } final IType upperBound = this.getUpperBound(); if (upperBound != null) { // Flatten the tree-like upperBound structure into a list final List<IType> list = new ArrayList<>(); getUpperBounds(list, upperBound); return this.upperBounds = list.toArray(new IType[0]); } return null; } public void setUpperBounds(IType[] upperBounds) { this.upperBounds = upperBounds; this.upperBound = null; this.safeUpperBound = null; } /** * Creates a balanced tree for the slice of the given array * * @param upperBounds * the upper bounds array * @param start * the start index * @param count * the number of elements * * @return a balanced tree of {@link IntersectionType}s */ private static IType getUpperBound(IType[] upperBounds, int start, int count) { if (count == 1) { return upperBounds[start]; } final int halfCount = count / 2; return new IntersectionType(getUpperBound(upperBounds, start, halfCount), getUpperBound(upperBounds, start + halfCount, count - halfCount)); } private static void getUpperBounds(List<IType> list, IType upperBound) { if (upperBound.typeTag() != IType.INTERSECTION) { list.add(upperBound); return; } final IntersectionType intersection = (IntersectionType) upperBound; getUpperBounds(list, intersection.getLeft()); getUpperBounds(list, intersection.getRight()); } // --------------- Safe Upper Bound --------------- private IType getSafeUpperBound() { if (this.safeUpperBound != null) { return this.safeUpperBound; } return (this.safeUpperBound = this.getUpperBound().getConcreteType(this::replaceBackRefs)); } private @Nullable IType replaceBackRefs(ITypeParameter typeParameter) { if (typeParameter.getGeneric() == this.getGeneric() && typeParameter.getIndex() >= this.getIndex()) { return new CovariantTypeVarType(this, true); } return null; } // --------------- Lower Bound --------------- @Override public IType getLowerBound() { return this.lowerBound; } @Override public void setLowerBound(IType bound) { this.lowerBound = bound; } // --------------- Other Types --------------- @Override public IType getErasure() { return this.getUpperBounds()[0]; } @Override public IType getCovariantType() { return this.covariantType; } @Override public IClass getTheClass() { return this.getSafeUpperBound().getTheClass(); } // =============== Methods =============== // --------------- Subtyping --------------- @Override public boolean isAssignableFrom(IType type, ITypeContext typeContext) { if (!Types.isSuperType(this.getSafeUpperBound().getConcreteType(typeContext), type)) { return false; } final IType lowerBound = this.getLowerBound(); return lowerBound == null || Types.isSuperType(type, lowerBound.getConcreteType(typeContext)); } @Override public boolean isSameType(IType type) { return Types.isSameType(type, this.getSafeUpperBound()); } @Override public boolean isSameClass(IType type) { return Types.isSameClass(type, this.getSafeUpperBound()); } @Override public boolean isSuperTypeOf(IType subType) { return isSuperType(this.getSafeUpperBound(), subType); } @Override public boolean isSuperClassOf(IType subType) { return isSuperClass(this.getSafeUpperBound(), subType); } @Override public boolean isSubTypeOf(IType superType) { return isSuperType(superType, this.getSafeUpperBound()); } @Override public boolean isSubClassOf(IType superType) { return isSuperClass(superType, this.getSafeUpperBound()); } // --------------- Field and Method Resolution --------------- @Override public IDataMember resolveField(Name name) { return this.getSafeUpperBound().resolveField(name); } @Override public void getMethodMatches(MatchList<IMethod> list, IValue instance, Name name, ArgumentList arguments) { this.getSafeUpperBound().getMethodMatches(list, instance, name, arguments); } @Override public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType) { this.getSafeUpperBound().getImplicitMatches(list, value, targetType); } // --------------- Descriptor and Signature --------------- @Override public void appendSignature(StringBuilder buffer) { buffer.append(this.name).append(':'); final IType[] upperBounds = this.getUpperBounds(); if (upperBounds == null || upperBounds.length == 0) { buffer.append("Ljava/lang/Object;"); return; } final IClass theClass = upperBounds[0].getTheClass(); if (theClass != null && theClass.isInterface()) { // If the first type is an interface, we append two colons // T::Lmy/Interface; buffer.append(':'); } upperBounds[0].appendSignature(buffer, false); for (int i = 1, count = upperBounds.length; i < count; i++) { buffer.append(':'); upperBounds[i].appendSignature(buffer, false); } } @Override public void appendParameterDescriptor(StringBuilder buffer) { if (this.reifiedKind == Reified.Type.TYPE) { buffer.append("Ldyvil/reflect/types/Type;"); } else if (this.reifiedKind != null) // OBJECT_CLASS or ANY_CLASS { buffer.append("Ljava/lang/Class;"); } } @Override public void appendParameterSignature(StringBuilder buffer) { this.appendParameterDescriptor(buffer); } // --------------- Compilation --------------- @Override public void writeArgument(MethodWriter writer, IType type) throws BytecodeException { if (this.reifiedKind == Reified.Type.ANY_CLASS) { type.writeClassExpression(writer, false); } else if (this.reifiedKind == Reified.Type.OBJECT_CLASS) { // Convert primitive types to their reference counterpart type.writeClassExpression(writer, true); } else if (this.reifiedKind == Reified.Type.TYPE) { type.writeTypeExpression(writer); } } @Override public void write(TypeAnnotatableVisitor visitor) { boolean method = this.generic instanceof IMethod; final int index = this.getIndex(); int typeRef = TypeReference.newTypeParameterReference( method ? TypeReference.METHOD_TYPE_PARAMETER : TypeReference.CLASS_TYPE_PARAMETER, index); if (this.variance != Variance.INVARIANT) { String type = this.variance == Variance.CONTRAVARIANT ? "Ldyvil/annotation/internal/Contravariant;" : "Ldyvil/annotation/internal/Covariant;"; visitor.visitTypeAnnotation(typeRef, null, type, true).visitEnd(); } this.attributes.write(visitor, typeRef, null); final IType[] upperBounds = this.getUpperBounds(); for (int i = 0, size = upperBounds.length; i < size; i++) { final int boundTypeRef = TypeReference.newTypeParameterBoundReference( method ? TypeReference.METHOD_TYPE_PARAMETER_BOUND : TypeReference.CLASS_TYPE_PARAMETER_BOUND, index, i); IType.writeAnnotations(upperBounds[i], visitor, boundTypeRef, ""); } } // --------------- Serialization --------------- @Override public void write(DataOutput out) throws IOException { this.name.write(out); Variance.write(this.variance, out); IType.writeType(this.lowerBound, out); IType.writeType(this.getUpperBound(), out); } @Override public void read(DataInput in) throws IOException { this.name = Name.read(in); this.variance = Variance.read(in); this.lowerBound = IType.readType(in); this.setUpperBound(IType.readType(in)); } // --------------- Formatting --------------- @Override public String toString() { StringBuilder builder = new StringBuilder(); this.toString("", builder); return builder.toString(); } @Override public void toString(@NonNull String indent, @NonNull StringBuilder buffer) { this.attributes.toInlineString(indent, buffer); buffer.append("type "); this.variance.appendPrefix(buffer); buffer.append(this.name); final IType upperBound = this.getSafeUpperBound(); if (upperBound != null) { buffer.append(": "); upperBound.toString(indent, buffer); } final IType lowerBound = this.getLowerBound(); if (lowerBound != null) { buffer.append(" super "); lowerBound.toString(indent, buffer); } } }
bsd-3-clause
vikramkanigiri/arm-trusted-firmware
bl31/context_mgmt.c
8694
/* * Copyright (c) 2013-2014, ARM Limited and Contributors. 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. * * Neither the name of ARM nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * 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 <stdio.h> #include <errno.h> #include <string.h> #include <assert.h> #include <arch_helpers.h> #include <platform.h> #include <bl_common.h> #include <runtime_svc.h> #include <context_mgmt.h> /******************************************************************************* * Data structure which holds the pointers to non-secure and secure security * state contexts for each cpu. It is aligned to the cache line boundary to * allow efficient concurrent manipulation of these pointers on different cpus ******************************************************************************/ typedef struct { void *ptr[2]; } __aligned (CACHE_WRITEBACK_GRANULE) context_info; static context_info cm_context_info[PLATFORM_CORE_COUNT]; /******************************************************************************* * Context management library initialisation routine. This library is used by * runtime services to share pointers to 'cpu_context' structures for the secure * and non-secure states. Management of the structures and their associated * memory is not done by the context management library e.g. the PSCI service * manages the cpu context used for entry from and exit to the non-secure state. * The Secure payload dispatcher service manages the context(s) corresponding to * the secure state. It also uses this library to get access to the non-secure * state cpu context pointers. * Lastly, this library provides the api to make SP_EL3 point to the cpu context * which will used for programming an entry into a lower EL. The same context * will used to save state upon exception entry from that EL. ******************************************************************************/ void cm_init() { /* * The context management library has only global data to intialize, but * that will be done when the BSS is zeroed out */ } /******************************************************************************* * This function returns a pointer to the most recent 'cpu_context' structure * that was set as the context for the specified security state. NULL is * returned if no such structure has been specified. ******************************************************************************/ void *cm_get_context(uint64_t mpidr, uint32_t security_state) { uint32_t linear_id = platform_get_core_pos(mpidr); assert(security_state <= NON_SECURE); return cm_context_info[linear_id].ptr[security_state]; } /******************************************************************************* * This function sets the pointer to the current 'cpu_context' structure for the * specified security state. ******************************************************************************/ void cm_set_context(uint64_t mpidr, void *context, uint32_t security_state) { uint32_t linear_id = platform_get_core_pos(mpidr); assert(security_state <= NON_SECURE); cm_context_info[linear_id].ptr[security_state] = context; } /******************************************************************************* * The next four functions are used by runtime services to save and restore EL3 * and EL1 contexts on the 'cpu_context' structure for the specified security * state. ******************************************************************************/ void cm_el3_sysregs_context_save(uint32_t security_state) { cpu_context *ctx; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); el3_sysregs_context_save(get_el3state_ctx(ctx)); } void cm_el3_sysregs_context_restore(uint32_t security_state) { cpu_context *ctx; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); el3_sysregs_context_restore(get_el3state_ctx(ctx)); } void cm_el1_sysregs_context_save(uint32_t security_state) { cpu_context *ctx; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); el1_sysregs_context_save(get_sysregs_ctx(ctx)); } void cm_el1_sysregs_context_restore(uint32_t security_state) { cpu_context *ctx; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); el1_sysregs_context_restore(get_sysregs_ctx(ctx)); } /******************************************************************************* * This function function populates 'cpu_context' pertaining to the given * security state with the entrypoint, SPSR and SCR values so that an ERET from * this securit state correctly restores corresponding values to drop the CPU to * the next exception level ******************************************************************************/ void cm_set_el3_eret_context(uint32_t security_state, uint64_t entrypoint, uint32_t spsr, uint32_t scr) { cpu_context *ctx; el3_state *state; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); /* Populate EL3 state so that we've the right context before doing ERET */ state = get_el3state_ctx(ctx); write_ctx_reg(state, CTX_SPSR_EL3, spsr); write_ctx_reg(state, CTX_ELR_EL3, entrypoint); write_ctx_reg(state, CTX_SCR_EL3, scr); } /******************************************************************************* * This function function populates ELR_EL3 member of 'cpu_context' pertaining * to the given security state with the given entrypoint ******************************************************************************/ void cm_set_el3_elr(uint32_t security_state, uint64_t entrypoint) { cpu_context *ctx; el3_state *state; ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); /* Populate EL3 state so that ERET jumps to the correct entry */ state = get_el3state_ctx(ctx); write_ctx_reg(state, CTX_ELR_EL3, entrypoint); } /******************************************************************************* * This function is used to program the context that's used for exception * return. This initializes the SP_EL3 to a pointer to a 'cpu_context' set for * the required security state ******************************************************************************/ void cm_set_next_eret_context(uint32_t security_state) { cpu_context *ctx; #if DEBUG uint64_t sp_mode; #endif ctx = cm_get_context(read_mpidr(), security_state); assert(ctx); #if DEBUG /* * Check that this function is called with SP_EL0 as the stack * pointer */ __asm__ volatile("mrs %0, SPSel\n" : "=r" (sp_mode)); assert(sp_mode == MODE_SP_EL0); #endif __asm__ volatile("msr spsel, #1\n" "mov sp, %0\n" "msr spsel, #0\n" : : "r" (ctx)); } /******************************************************************************* * This function is used to program exception stack in the 'cpu_context' * structure. This is the initial stack used for taking and handling exceptions * at EL3. This stack is expected to be initialized once by each security state ******************************************************************************/ void cm_init_exception_stack(uint64_t mpidr, uint32_t security_state) { cpu_context *ctx; el3_state *state; ctx = cm_get_context(mpidr, security_state); assert(ctx); /* Set exception stack in the context */ state = get_el3state_ctx(ctx); write_ctx_reg(state, CTX_EXCEPTION_SP, get_exception_stack(mpidr)); }
bsd-3-clause
SPlanzer/QGIS-AIMS-Plugin
doc/Aims-Plugin_Doc/qgis._gui.QgsExpressionHighlighter-class.html
15295
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>qgis._gui.QgsExpressionHighlighter</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> qgis :: _gui :: QgsExpressionHighlighter :: Class&nbsp;QgsExpressionHighlighter </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="qgis._gui.QgsExpressionHighlighter-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class QgsExpressionHighlighter</h1><p class="nomargin-top"></p> <pre class="base-tree"> object --+ | sip.simplewrapper --+ | sip.wrapper --+ | <a href="PyQt4.QtCore.QObject-class.html">PyQt4.QtCore.QObject</a> --+ | <a href="PyQt4.QtGui.QSyntaxHighlighter-class.html">PyQt4.QtGui.QSyntaxHighlighter</a> --+ | <strong class="uidshort">QgsExpressionHighlighter</strong> </pre> <hr /> <p>QgsExpressionHighlighter(QTextDocument parent=None)</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="addFields"></a><span class="summary-sig-name">addFields</span>(<span class="summary-sig-arg">...</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="qgis._gui.QgsExpressionHighlighter-class.html#highlightBlock" class="summary-sig-name">highlightBlock</a>(<span class="summary-sig-arg">...</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html">PyQt4.QtGui.QSyntaxHighlighter</a></code></b>: <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#currentBlock">currentBlock</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#currentBlockState">currentBlockState</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#currentBlockUserData">currentBlockUserData</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#document">document</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#format">format</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#previousBlockState">previousBlockState</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#rehighlight">rehighlight</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#rehighlightBlock">rehighlightBlock</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#setCurrentBlockState">setCurrentBlockState</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#setCurrentBlockUserData">setCurrentBlockUserData</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#setDocument">setDocument</a></code>, <code><a href="PyQt4.QtGui.QSyntaxHighlighter-class.html#setFormat">setFormat</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="PyQt4.QtCore.QObject-class.html">PyQt4.QtCore.QObject</a></code></b>: <code><a href="PyQt4.QtCore.QObject-class.html#__getattr__">__getattr__</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#blockSignals">blockSignals</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#childEvent">childEvent</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#children">children</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#connect">connect</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#connectNotify">connectNotify</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#customEvent">customEvent</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#deleteLater">deleteLater</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#destroyed">destroyed</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#disconnect">disconnect</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#disconnectNotify">disconnectNotify</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#dumpObjectInfo">dumpObjectInfo</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#dumpObjectTree">dumpObjectTree</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#dynamicPropertyNames">dynamicPropertyNames</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#emit">emit</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#event">event</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#eventFilter">eventFilter</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#findChild">findChild</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#findChildren">findChildren</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#inherits">inherits</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#installEventFilter">installEventFilter</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#isWidgetType">isWidgetType</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#killTimer">killTimer</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#metaObject">metaObject</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#moveToThread">moveToThread</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#objectName">objectName</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#parent">parent</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#property">property</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#pyqtConfigure">pyqtConfigure</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#receivers">receivers</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#removeEventFilter">removeEventFilter</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#sender">sender</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#senderSignalIndex">senderSignalIndex</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#setObjectName">setObjectName</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#setParent">setParent</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#setProperty">setProperty</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#signalsBlocked">signalsBlocked</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#startTimer">startTimer</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#thread">thread</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#timerEvent">timerEvent</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#tr">tr</a></code>, <code><a href="PyQt4.QtCore.QObject-class.html#trUtf8">trUtf8</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>sip.simplewrapper</code></b>: <code>__init__</code>, <code>__new__</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__hash__</code>, <code>__reduce__</code>, <code>__reduce_ex__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__str__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== CLASS VARIABLES ==================== --> <a name="section-ClassVariables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Class Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-ClassVariables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="PyQt4.QtCore.QObject-class.html">PyQt4.QtCore.QObject</a></code></b>: <code><a href="PyQt4.QtCore.QObject-class.html#staticMetaObject">staticMetaObject</a></code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="highlightBlock"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">highlightBlock</span>(<span class="sig-arg">...</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <dl class="fields"> <dt>Overrides: PyQt4.QtGui.QSyntaxHighlighter.highlightBlock </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="QGIS-AIMS-Plugin-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Jun 14 13:29:21 2016 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
bsd-3-clause
tianocore/edk
Sample/Platform/Generic/RuntimeDxe/FvbServices/Common/ia32/Ia32Fwh.c
1133
/*++ Copyright (c) 2004, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: Ia32Fwh.c Abstract: Revision History --*/ #include "FWBlockService.h" EFI_STATUS FvbSpecificInitialize ( IN ESAL_FWB_GLOBAL *mFvbModuleGlobal ) /*++ Routine Description: Additional initialize code for IA32 platform. Arguments: ESAL_FWB_GLOBAL - Global pointer that points to the instance data Returns: EFI_SUCCESS --*/ { return EFI_SUCCESS; }
bsd-3-clause
hadim/fiji_tools
src/main/resources/script_templates/Hadim_Scripts/ROI/Circle_ROI_Builder.py
587
# @Float(label="Diameter of the circle ROI (pixel)", value=7) circle_diam from ij.plugin.frame import RoiManager from ij.gui import OvalRoi rm = RoiManager.getInstance() new_rois = [] for roi in rm.getRoisAsArray(): assert roi.getTypeAsString() == 'Point', "ROI needs to be a point" x_center = roi.getContainedPoints()[0].x - (circle_diam / 2) + 0.5 y_center = roi.getContainedPoints()[0].y - (circle_diam / 2) + 0.5 new_roi = OvalRoi(x_center, y_center, circle_diam, circle_diam) new_rois.append(new_roi) rm.reset() for new_roi in new_rois: rm.addRoi(new_roi) print("Done")
bsd-3-clause
CBlasse/premosa
src/mylib/DOCUMENTS/HTML/Correlation.html
25433
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>mylib 1.0: Correlation and Regression Module Reference</title> <link href="mydoc.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"> <img src="images/qt-logo.png" align="left" border="0" /></a> </td> <td width="1">&nbsp;&nbsp;</td> <td class="postheader" valign="center"><a href="index.html"> <font color="#004faf">Home</font></a>&nbsp;&middot; <a href="AllPages.html"><font color="#004faf">Pages</font></a>&nbsp;&middot; <a href="AllFunctions.html"><font color="#004faf">Index</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a> </td> </tr> </table> <table align="center" width=810><tr><td> <h1 class="title">Correlation and Regression Module Reference</h1> <p> Functions for correlations and regressions over AForm objects. <a href="#details">More...</a> </p> <pre> #include &lt;correlate.h&gt; </pre> <hr /> <a name="Bundles"></a> <h2>Structures</h2> <table><tr><td width="100px">&nbsp;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Regression_Bundle"> Regression_Bundle </a></b> </td><td class="define" valign="baseline">: struct</td> </tr></table> <table><tr><td valign="top"> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#tss"> tss </a></b> </td><td class="define" valign="baseline">: double</td> </tr> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#mss"> mss </a></b> </td><td class="define" valign="baseline">: double</td> </tr> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#rss"> rss </a></b> </td><td class="define" valign="baseline">: double</td> </tr> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#ser"> ser </a></b> </td><td class="define" valign="baseline">: double</td> </tr> </table> </td><td> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="comment" valign="baseline">total sum of squares</td></tr> <tr><td class="comment" valign="baseline">model sum of squares</td></tr> <tr><td class="comment" valign="baseline">residual sum of squares</td></tr> <tr><td class="comment" valign="baseline">standard error of the estimate</td></tr> </table> </td></tr> <tr><td>&nbsp;</td></tr> <tr><td> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#R2"> R2 </a></b> </td><td class="define" valign="baseline">: double</td> </tr> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#aR2"> aR2 </a></b> </td><td class="define" valign="baseline">: double</td> </tr> </table> </td><td> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="comment" valign="baseline">R-squared, coefficient of determination</td></tr> <tr><td class="comment" valign="baseline">adjusted R-squared</td></tr> </table> </td></tr> <tr><td>&nbsp;</td></tr> <tr><td> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#std_err"> std_err </a></b> </td><td class="define" valign="baseline">: Double_Vector *</td> </tr> <tr><td class="field" valign="baseline">&bull;</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#t_stat"> t_stat </a></b> </td><td class="define" valign="baseline">: Double_Vector *</td> </tr> </table> </td><td> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="comment" valign="baseline">standard error of each parameter</td></tr> <tr><td class="comment" valign="baseline">t-statistic for each parameter</td></tr> </table> </td></tr> </table> <hr /> <a name="Routines"></a> <h2>Routines</h2> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="return" valign="baseline">double</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#A_Correlation">A_Correlation</a></b> (AForm *<I>a1</I>, AForm *<I>a2</I>)</td></tr> <tr><td class="return" valign="baseline">double</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#A_Covariance">A_Covariance</a></b> (AForm *<I>a1</I>, AForm *<I>a2</I>)</td></tr> <tr><td class="return" valign="baseline">double</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#A_Pearson_Correlation">A_Pearson_Correlation</a></b> (AForm *<I>a1</I>, AForm *<I>a2</I>)</td></tr> </table> <br> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="return" valign="baseline">Double_Matrix *</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Correlations">Correlations</a></b><sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, AForm *<I>a1</I>, ... AForm *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> <tr><td class="return" valign="baseline">Double_Matrix *</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Covariances">Covariances</a></b><sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, AForm *<I>a1</I>, ... AForm *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> <tr><td class="return" valign="baseline">Double_Matrix *</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Pearson_Correlations">Pearson_Correlations</a></b><sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, AForm *<I>a1</I>, ... AForm *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> </table> <br> <table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width=0> <tr><td class="return" valign="baseline">Double_Vector *</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Linear_Regression">Linear_Regression</a></b><sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, Regression_Bundle *<I>stats</I> <sup><b><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AForm *<I>obs</I>, AForm *<I>a1</I>, ... AForm *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> <tr><td class="return" valign="baseline">Double_Vector *</td> <td class="name" valign="baseline"> <b><a href="Correlation.html#Simple_Regression">Simple_Regression</a></b> (Array *<I>vector</I> <sup><b><font color="#00AA55" title="This argument is *R*eturned as the result">R</font><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, Regression_Bundle *<I>stats</I> <sup><b><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AForm *<I>obs</I>, AForm *<I>inp</I>)</td></tr> </table> <a name="details"></a> <hr /> <h2>Detailed Description</h2> <p> For all the routines in this module, the shape of the <a href="AForm.html">AForm</a>s passed to them is not important. Each <a href="AForm.html">AForm</a> is treated as a linear vector (linearized according to innermost-first order) whose length is equal to the number of elements in the array form. So for example, when computing <a href="Correlation.html#A_Correlation">A_Correlation</a> between two arrays <I>a1</I> and <I>a2</I>, <I>a1</I> and <I>a2</I> can have different shapes and types, but they must have the same number of elements. </p> <p> On can compute simple <B>correlation</B>, <B>covariance</B> (correlation with mean bias), and <B>normalized correlation</B>, or "Pearson correlation" (covariance normalized by the standard deviations of the series). For each of these three correlations, there is a routine that takes two <a href="AForm.html">AForm</a>s and returns the desired quantity as a <I>double</I> value (<a href="Correlation.html#A_Correlation">A_Correlation</a>, <a href="Correlation.html#A_Covariance">A_Covariance</a>, <a href="Correlation.html#A_Pearson_Correlation">A_Pearson_Correlation</a>). There is also a routine that takes any number, <I>n</I>, of <a href="AForm.html">AForm</a>s and computes all pairs of the given correlation between them, generating and returning an <I>n</I>x<I>n</I> <a href="Array.html#Double_Matrix">Double_Matrix</a> of all the pairwise entities (<a href="Correlation.html#Correlations">Correlations</a>, <a href="Correlation.html#Covariances">Covariances</a>, Pearson_Correlations'); </p> <p> <a href="Correlation.html#Linear_Regression">Linear_Regression</a> is a routine for performing a standard linear regression, i.e. finding the set of weights that gives the best least squares fit between a linear, weighted combination of any number of input vectors and an observation vector. The routine can optionally fill in a bundle of standard statistics about the nature of the fit (see <a href="Correlation.html#Regression_Bundle">Regression_Bundle</a> below). There is also a specialized routine, <a href="Correlation.html#Simple_Regression">Simple_Regression</a>, for the common case where an observation is to be explained as an affine function of a single input. </p> <hr /> <h2>Structure Documentation</h2> <h3 class="fn"> <table cellspacing="0" width=0> <a name="Regression_Bundle"></a> <tr><td class="name" valign="top">Regression_Bundle</td> <td class="define">: struct</td></tr></table> <table cellspacing="0" width=0> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>tss</i></td><td class="define">: double</td></tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>mss</i></td><td class="define">: double</td></tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>rss</i></td><td class="define">: double</td></tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>ser</i></td><td class="define">: double</td></tr> <td>&nbsp;</td><td>&nbsp;</td><tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>R2</i></td><td class="define">: double</td></tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>aR2</i></td><td class="define">: double</td></tr> <td>&nbsp;</td><td>&nbsp;</td><tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>std_err</i></td><td class="define">: <a href="Array.html#Double_Vector">Double_Vector</a> *</td></tr> <tr><td class="dot" valign="baseline">&bull;</td> <td class="name"><i>t_stat</i></td><td class="define">: <a href="Array.html#Double_Vector">Double_Vector</a> *</td></tr> </table> </h3> <p> A bundle of this kind, when passed to either <a href="Correlation.html#Linear_Regression">Linear_Regression</a> or <a href="Correlation.html#Simple_Regression">Simple_Regression</a>, is filled in with various statistics that provide information about the goodness of the fit of the regression. The deeper statistical meaning of each field is defered to a good text on statistics. Here a simple and hopefully operative description of each statistic is given. We assume that the observation vector is <I>obs</I>, the <I>n</I> input vectors are <I>a1</I>, <I>a2</I>, ... <I>an</I>, all the vectors have <I>N</I> elements, and that the computed linear regression variables are <I>c[0]</I>, <I>c[1]</I>, ... <I>c[n-1]</I>. The vector of predicted values will be donted by <I>est</I>, where <i>est[t] = c[0]*a1[t] + ... + c[n-1]*an[t]</i>. </p> <p> <font color="#008844"><B>tss</B></font>: stands for "total sum of squares" and is the variance in the observation vector <I>obs</I> about its mean, i.e. <I>tss</I> = <i><font size="+1">&Sigma;</font><sub>t</sub> (obs[t] - &mu;)<sup>2</sup></i>, where <i>&mu;</i> is the the mean of the elements in <I>obs</I>. </p> <p> <font color="#008844"><B>mss</B></font>: stands for "model sum of squares" and is the variance of the estimate of the observation, <I>est</I> about the mean of <I>obs</I>, i.e. <I>mss</I> = <i><font size="+1">&Sigma;</font><sub>t</sub> (est[t] - &mu;)<sup>2</sup></i>, where <i>&mu;</i> is the the mean of the elements in <I>obs</I>. </p> <p> <font color="#008844"><B>rss</B></font>: stands for "residual sum of squares" and is the covariance between observation vector <I>obs</I> and the predicted values <I>est</I>, i.e. <I>rss</I> = <i><font size="+1">&Sigma;</font><sub>t</sub> (obs[t] - est[t])<sup>2</sup></i>. It is this quantity that is minimized by the linear regression. </p> <p> <font color="#008844"><B>ser</B></font>: is the "standard error of the estimate" which is just the standard deviation of the distribution of <I>obs</I>-<I>est</I>, i.e. <I>ser</I> = <I>(rss/(N-n))<sup>.5</sup></I> </p> <p> <font color="#008844"><B>R2</B></font>: is "R-squared" or the "coefficient of determination". It ranges from 0 to 1 and indicates how well the observation is explained or predicted by a linear combination of the input factors, where 0 implies no predictive power, and 1 implies perfectly predictive. Mathematically, it is <I>1-rss/tss</I> where <I>rss</I> and <I>tss</I> are explained above. </p> <p> <font color="#008844"><B>aR2</B></font>: is the "adjusted R-squared" coefficient equal to <I>1 - (rss*(N-1)) / (tss*(N-n))</I> Note that <I>aR2</I> = <I>R2</I> when <I>n = 1</I> and <I>ar2</I> &lt; <I>R2</I> when <I>n &gt; 1</I>. The idea is that the number of degrees of freedom <I>n</I> compensates for the expected greater "predictive" power the more input vectors there are. </p> <p> <font color="#008844"><B>std_err</B></font>: is an <I>n</I>-element vector that gives the standard error for each coefficient <I>c[i]</I>. Under the assumption that <I>N</I> is "large enough", then by the central limit theorem the error in each coefficient approaches a normal distribution with 0 mean and a standard deviation of <font><i>std_err</i>[i] = <i>ser</i>*Q<sup>-1</sup><sub>ii</sub></font> where <I>Q</I> = <a href="Correlation.html#Correlations">Correlations</a>(n,a1,...,an). </p> <p> <font color="#008844"><B>t_stat</B></font>: is an <I>n</I>-element vector that gives the t-statistic for each coefficient <I>c[i]</I> under the assumption of asymptotically large <I>N</I>. This statistic, which is <I>t_stat[i]</I> = <I>c[i]/std_err[i]</I>, follows the Student t-distribution and can thus be used to compute the p-value that <I>c[i]</I> is non-zero. </p> <hr /> <h2>Routine Documentation</h2> <h3 class="fn"><table> <a name="A_Correlation"></a><tr><td valign="baseline">double</td> <td valign="baseline">A_Correlation (<a href="AForm.html">AForm</a> *<I>a1</I>, <a href="AForm.html">AForm</a> *<I>a2</I>)</td></tr> </table></h3> <p> Return the correlation, <i><font size="+1"\>&Sigma;</font><sub>t</sub> a1[t]a2[t]</i>, between <I>a1</I> and <I>a2</I>. The only constraint on <I>a1</I> and <I>a2</I> is that they have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="A_Covariance"></a><tr><td valign="baseline">double</td> <td valign="baseline">A_Covariance (<a href="AForm.html">AForm</a> *<I>a1</I>, <a href="AForm.html">AForm</a> *<I>a2</I>)</td></tr> </table></h3> <p> Return the covariance, <i><font size="+1">&Sigma;</font><sub>t</sub> (a1[t] - &mu;<sub>1</sub>)(a2[t] - </i> <i>&mu;<sub>2</sub>) / A</i>, between <I>a1</I> and <I>a2</I>, where <i>&mu;<sub>i</sub></i> is the mean of the elements of <I>ai</I>, and <I>A</I> is the number of elements in both <I>a1</I> and <I>a2</I>. The only constraint on <I>a1</I> and <I>a2</I> is that they have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="A_Pearson_Correlation"></a><tr><td valign="baseline">double</td> <td valign="baseline">A_Pearson_Correlation (<a href="AForm.html">AForm</a> *<I>a1</I>, <a href="AForm.html">AForm</a> *<I>a2</I>)</td></tr> </table></h3> <p> Returns the Pearson- or normalized-correlation, <i><font size="+1">&Sigma;</font><sub>t</sub></i> <i>(a1[t] - &mu;<sub>1</sub>)(a2[t] - &mu;<sub>2</sub>) / </i> <i>(&sigma;<sub>1</sub>&sigma;<sub>2</sub>A), </i> where <i>&mu;<sub>i</sub></i> is the mean of the elements of <I>ai</I>, <i>&sigma;<sub>i</sub></i> is the standard deviation of the elements in <I>ai</I>, and <I>A</I> is the number of elements in both <I>a1</I> and <I>a2</I>. The only constraint on <I>a1</I> and <I>a2</I> is that they have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="Correlations"></a><tr><td valign="baseline"><a href="Array.html#Double_Matrix">Double_Matrix</a> *</td> <td valign="baseline">Correlations<sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, <a href="AForm.html">AForm</a> *<I>a1</I>, ... <a href="AForm.html">AForm</a> *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> </table></h3> <p> Generates an <I>n</I> x <I>n</I> correlation matrix, <I>c</I>, where <I>c[i,j] = <a href="Correlation.html#A_Correlation">A_Correlation</a>(ai,aj)</I>. The only constraint on the <I>ai</I>'s is that they all have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="Covariances"></a><tr><td valign="baseline"><a href="Array.html#Double_Matrix">Double_Matrix</a> *</td> <td valign="baseline">Covariances<sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, <a href="AForm.html">AForm</a> *<I>a1</I>, ... <a href="AForm.html">AForm</a> *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> </table></h3> <p> Generates an <I>n</I> x <I>n</I> covariance matrix, <I>c</I>, where <I>c[i,j] = <a href="Correlation.html#A_Covariance">A_Covariance</a>(ai,aj)</I>. The only constraint on the <I>ai</I>'s is that they all have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="Pearson_Correlations"></a><tr><td valign="baseline"><a href="Array.html#Double_Matrix">Double_Matrix</a> *</td> <td valign="baseline">Pearson_Correlations<sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, <a href="AForm.html">AForm</a> *<I>a1</I>, ... <a href="AForm.html">AForm</a> *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> </table></h3> <p> Generates an <I>n</I> x <I>n</I> normalized correlation matrix, <I>c</I>, where <I>c[i,j] = <a href="Correlation.html#A_Pearson_Correlation">A_Pearson_Correlation</a>(ai,aj)</I>. The only constraint on the <I>ai</I>'s is that they all have the same number of elements (but not necessarily the same shape or type). </p> <h3 class="fn"><table> <a name="Linear_Regression"></a><tr><td valign="baseline"><a href="Array.html#Double_Vector">Double_Vector</a> *</td> <td valign="baseline">Linear_Regression<sup><b><font color="#00AA55" title="The function *G*enerates or creates the returned object">G</font></b></sup> (int <I>n</I>, <a href="Correlation.html#Regression_Bundle">Regression_Bundle</a> *<I>stats</I> <sup><b><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="AForm.html">AForm</a> *<I>obs</I>, <a href="AForm.html">AForm</a> *<I>a1</I>, ... <a href="AForm.html">AForm</a> *<I>an</I> <sup><b><font color="#00AA55" title="This argument is symbolic only, *x*'d out">X</font></b></sup>)</td></tr> </table></h3> <p> Linear regression generates an <I>n</I>-element vector of coefficients, <I>c</I>, such that the least squares distance between <I>obs</I> and the <I>c</I>-weighted sum of the <I>ai</I>'s is minimal, that is, </p> <p class="center"><i><font size="+1">&Sigma;</font><sub>t</sub></i> <i>(obs[t] - (c[0]*a1[t] + ... + c[n-1]*an[t]))<sup>2</sup></i> is minimized. </p> <p> The routine will return statistics for the regression in the <a href="Correlation.html#Regression_Bundle">Regression_Bundle</a> pointed at by <I>stats</I> if and only if it is not NULL. If the arrays pointed at by the fields <I>std_err</I> and/or <I>t_stat</I> within this bundle are NULL on entrance, then vectors of the appropriate size are created, otherwise the arrays they point to are converted to <I>n</I>-element <a href="Array.html#Double_Vector">Double_Vector</a>s if they are not already thus, and then filled in with the desired values. The caller is responsible for freeing or killing these arrays. </p> <h3 class="fn"><table> <a name="Simple_Regression"></a><tr><td valign="baseline"><a href="Array.html#Double_Vector">Double_Vector</a> *</td> <td valign="baseline">Simple_Regression (<a href="Array.html">Array</a> *<I>vector</I> <sup><b><font color="#00AA55" title="This argument is *R*eturned as the result">R</font><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, <a href="Correlation.html#Regression_Bundle">Regression_Bundle</a> *<I>stats</I> <sup><b><font color="#00AA55" title="This argument's value is set (*O*utput)">O</font></b></sup>, <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="AForm.html">AForm</a> *<I>obs</I>, <a href="AForm.html">AForm</a> *<I>inp</I>)</td></tr> </table></h3> <p> Simple_Regression returns a pointer to a 2-element <a href="Array.html#Double_Vector">Double_Vector</a>, <I>c</I>, that minimizes the sum: </p> <p class="center"><i><font size="+1">&Sigma;</font><sub>t</sub></i> <i>(obs[t] - (c[0] + c[1] * inp[t]))<sup>2</sup></i> </p> <p> If <I>vector</I> is NULL then a 2-element <a href="Array.html#Double_Vector">Double_Vector</a> is generated and returned as <I>c</I>, otherwise the vector is converted to a 2-element <a href="Array.html#Double_Vector">Double_Vector</a> if it is not already one and then returned as <I>c</I>. The point of passing <I>vector</I> rather than generating a <a href="Array.html#Double_Vector">Double_Vector</a> containing <I>c</I>, is that if one wants to solve, say thousands of such regressions, then one can generate a 2-element double vector at the start, and then reuse it for each call. This saves time in the regression routine as an <a href="Array.html">Array</a> object need neither be created or re-shaped and re-typed. </p> <p> The routine will return statistics for the regression in the <a href="Correlation.html#Regression_Bundle">Regression_Bundle</a> pointed at by <I>stats</I> if and only if it is not NULL. If the arrays pointed at by the fields <I>std_err</I> and/or <I>t_stat</I> within this bundle are NULL on entrance, then 2-element <a href="Array.html#Double_Vector">Double_Vector</a>s are generated, otherwise they are converted to 2-element <a href="Array.html#Double_Vector">Double_Vector</a>s if they are not already thus, and then filled in with the desired values. The caller is responsible for freeing or killing these arrays. </td></tr></table> </body> </html>
bsd-3-clause
cornernote/yii2
docs/guide-pt-BR/output-theming.md
4558
Temas ===== Tema é uma forma de substituir um conjunto de [views](structure-views.md) por outras, sem a necessidade de tocar no código de renderização de view original. Você pode usar tema para alterar sistematicamente a aparência de uma aplicação. Para usar tema, você deve configurar a propriedade [[yii\base\View::theme|theme]] da `view (visão)` da aplicação. A propriedade configura um objeto [[yii\base\Theme]] que rege a forma como os arquivos de views são substituídos. Você deve principalmente especificar as seguintes propriedades de [[yii\base\Theme]]: - [[yii\base\Theme::basePath]]: determina o diretório de base que contém os recursos temáticos (CSS, JS, images, etc.) - [[yii\base\Theme::baseUrl]]: determina a URL base dos recursos temáticos. - [[yii\base\Theme::pathMap]]: determina as regras de substituição dos arquivos de view. Mais detalhes serão dados nas subseções seguintes. Por exemplo, se você chama `$this->render('about')` no `SiteController`, você estará renderizando a view `@app/views/site/about.php`. Todavia, se você habilitar tema na seguinte configuração da aplicação, a view `@app/themes/basic/site/about.php` será renderizada, no lugar da primeira. ```php return [ 'components' => [ 'view' => [ 'theme' => [ 'basePath' => '@app/themes/basic' 'baseUrl' => '@web/themes/basic', 'pathMap' => [ '@app/views' => '@app/themes/basic', ], ], ], ], ]; ``` > Observação: aliases de caminhos são suportados por temas. Ao fazer substituição de view, aliases de caminho serão transformados nos caminhos ou URLs reais. Você pode acessar o objeto [[yii\base\Theme]] através da propriedade [[yii\base\View::theme]]. Por exemplo, na view, você pode escrever o seguinte código, pois `$this` refere-se ao objeto view: ```php $theme = $this->theme; // retorno: $theme->baseUrl . '/img/logo.gif' $url = $theme->getUrl('img/logo.gif'); // retorno: $theme->basePath . '/img/logo.gif' $file = $theme->getPath('img/logo.gif'); ``` A propriedade [[yii\base\Theme::pathMap]] rege como a view deve ser substituída. É preciso um array de pares de valores-chave, onde as chaves são os caminhos originais da view que serão substituídos e os valores são os caminhos dos temas correspondentes. A substituição é baseada na correspondência parcial: Se um caminho de view inicia com alguma chave no array [[yii\base\Theme::pathMap|pathMap]], a parte correspondente será substituída pelo valor do array. Usando o exemplo de configuração acima, `@app/views/site/about.php` corresponde parcialmente a chave `@app/views`, ele será substituído por `@app/themes/basic/site/about.php`. ## Tema de Módulos <span id="theming-modules"></span> A fim de configurar temas por módulos, [[yii\base\Theme::pathMap]] pode ser configurado da seguinte forma: ```php 'pathMap' => [ '@app/views' => '@app/themes/basic', '@app/modules' => '@app/themes/basic/modules', // <-- !!! ], ``` Isto lhe permitirá tematizar `@app/modules/blog/views/comment/index.php` com `@app/themes/basic/modules/blog/views/comment/index.php`. ## Tema de Widgets <span id="theming-widgets"></span> A fim de configurar temas por widgets, você pode configurar [[yii\base\Theme::pathMap]] da seguinte forma: ```php 'pathMap' => [ '@app/views' => '@app/themes/basic', '@app/widgets' => '@app/themes/basic/widgets', // <-- !!! ], ``` Isto lhe permitirá tematizar `@app/widgets/currency/views/index.php` com `@app/themes/basic/widgets/currency/index.php`. ## Herança de Tema <span id="theme-inheritance"></span> Algumas vezes você pode querer definir um tema que contém um visual básico da aplicação, e em seguida, com base em algum feriado, você pode querer variar o visual levemente. Você pode atingir este objetivo usando herança de tema que é feito através do mapeamento de um único caminho de view para múltiplos alvos. Por exemplo, ```php 'pathMap' => [ '@app/views' => [ '@app/themes/christmas', '@app/themes/basic', ], ] ``` Neste caso, a view `@app/views/site/index.php` seria tematizada tanto como `@app/themes/christmas/site/index.php` ou `@app/themes/basic/site/index.php`, dependendo de qual arquivo de tema existir. Se os dois arquivos existirem, o primeiro terá precedência. Na prática, você iria manter mais arquivos de temas em `@app/themes/basic` e personalizar alguns deles em `@app/themes/christmas`.
bsd-3-clause
oci-pronghorn/FogLight
apidemo/transducerdemo/src/test/java/com/ociweb/oe/foglight/api/AppTest.java
400
package com.ociweb.oe.foglight.api; import com.ociweb.iot.maker.FogRuntime; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * Unit test for simple App. */ public class AppTest { @Test @Ignore public void testApp() { boolean cleanExit = FogRuntime.testConcurrentUntilShutdownRequested(new TransducerDemo(), 1000); assertTrue(cleanExit); } }
bsd-3-clause
golang/snappy
golden_test.go
45089
// Copyright 2016 The Snappy-Go 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 snappy // extendMatchGoldenTestCases is the i and j arguments, and the returned value, // for every extendMatch call issued when encoding the // testdata/Isaac.Newton-Opticks.txt file. It is used to benchmark the // extendMatch implementation. // // It was generated manually by adding some print statements to the (pure Go) // encodeBlock implementation (in encode_other.go) to replace the inlined // version of extendMatch. // // s += 4 // s0 := s // for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { // } // println("{", candidate + 4, ",", s0, ",", s, "},") // // and running "go test -test.run=EncodeGoldenInput -tags=noasm". var extendMatchGoldenTestCases = []struct { i, j, want int }{ {571, 627, 627}, {220, 644, 645}, {99, 649, 649}, {536, 653, 656}, {643, 671, 673}, {676, 732, 733}, {732, 751, 752}, {67, 768, 772}, {93, 780, 780}, {199, 788, 788}, {487, 792, 796}, {699, 826, 826}, {698, 838, 838}, {697, 899, 901}, {847, 911, 912}, {37, 923, 923}, {833, 928, 928}, {69, 941, 943}, {323, 948, 948}, {671, 955, 957}, {920, 973, 974}, {935, 979, 983}, {750, 997, 999}, {841, 1014, 1014}, {928, 1053, 1053}, {854, 1057, 1060}, {755, 1072, 1072}, {838, 1094, 1097}, {1022, 1106, 1106}, {1085, 1114, 1114}, {955, 1128, 1130}, {814, 1134, 1135}, {1063, 1145, 1147}, {918, 1161, 1162}, {815, 1195, 1196}, {1128, 1207, 1209}, {1170, 1225, 1225}, {897, 1236, 1242}, {193, 1255, 1262}, {644, 1266, 1267}, {784, 1274, 1282}, {227, 1287, 1289}, {1161, 1294, 1295}, {923, 1299, 1299}, {1195, 1303, 1303}, {718, 1334, 1339}, {805, 1350, 1350}, {874, 1357, 1357}, {1318, 1362, 1362}, {994, 1372, 1373}, {90, 1387, 1387}, {1053, 1399, 1400}, {1094, 1417, 1417}, {1250, 1445, 1445}, {1285, 1449, 1453}, {806, 1457, 1461}, {895, 1472, 1472}, {1236, 1481, 1488}, {1266, 1495, 1496}, {921, 1508, 1509}, {940, 1522, 1522}, {1541, 1558, 1559}, {788, 1582, 1582}, {1298, 1590, 1590}, {1361, 1594, 1595}, {910, 1599, 1601}, {720, 1605, 1605}, {1399, 1615, 1616}, {736, 1629, 1629}, {1078, 1634, 1638}, {677, 1645, 1645}, {757, 1650, 1655}, {1294, 1659, 1663}, {1119, 1677, 1684}, {995, 1688, 1688}, {1357, 1695, 1696}, {1169, 1700, 1721}, {808, 1725, 1727}, {1390, 1732, 1732}, {1513, 1736, 1736}, {1315, 1740, 1740}, {685, 1748, 1750}, {899, 1754, 1760}, {1598, 1764, 1767}, {1386, 1782, 1783}, {1465, 1787, 1787}, {1014, 1791, 1791}, {1724, 1800, 1805}, {1166, 1811, 1811}, {1659, 1823, 1824}, {1218, 1829, 1843}, {695, 1847, 1850}, {1175, 1855, 1857}, {860, 1876, 1878}, {1799, 1892, 1892}, {1319, 1896, 1896}, {1691, 1900, 1900}, {1378, 1904, 1904}, {1495, 1912, 1912}, {1588, 1917, 1921}, {679, 1925, 1928}, {1398, 1935, 1936}, {1551, 1941, 1942}, {1612, 1946, 1950}, {1814, 1959, 1959}, {1853, 1965, 1966}, {1307, 1983, 1986}, {1695, 1990, 1991}, {905, 1995, 1995}, {1057, 1999, 2002}, {1431, 2006, 2007}, {848, 2018, 2018}, {1064, 2022, 2023}, {1151, 2027, 2027}, {1071, 2050, 2050}, {1478, 2057, 2057}, {1911, 2065, 2066}, {1306, 2070, 2074}, {2035, 2085, 2085}, {1188, 2100, 2100}, {11, 2117, 2118}, {1725, 2122, 2126}, {991, 2130, 2130}, {1786, 2139, 2141}, {737, 2153, 2154}, {1481, 2161, 2164}, {1990, 2173, 2173}, {2057, 2185, 2185}, {1881, 2200, 2200}, {2171, 2205, 2207}, {1412, 2215, 2216}, {2210, 2220, 2220}, {799, 2230, 2230}, {2103, 2234, 2234}, {2195, 2238, 2240}, {1935, 2244, 2245}, {2220, 2249, 2249}, {726, 2256, 2256}, {2188, 2262, 2266}, {2215, 2270, 2272}, {2122, 2276, 2278}, {1110, 2282, 2283}, {1369, 2287, 2287}, {724, 2294, 2294}, {1626, 2300, 2300}, {2138, 2306, 2309}, {709, 2313, 2316}, {1558, 2327, 2327}, {2109, 2333, 2333}, {2173, 2354, 2354}, {2152, 2362, 2367}, {2065, 2371, 2373}, {1692, 2377, 2380}, {819, 2384, 2386}, {2270, 2393, 2395}, {1787, 2399, 2400}, {1989, 2405, 2405}, {1225, 2414, 2414}, {2330, 2418, 2418}, {986, 2424, 2425}, {1899, 2429, 2431}, {1070, 2436, 2440}, {1038, 2450, 2450}, {1365, 2457, 2457}, {1983, 2461, 2462}, {1025, 2469, 2469}, {2354, 2476, 2476}, {2457, 2482, 2482}, {5, 2493, 2494}, {2234, 2498, 2498}, {2352, 2514, 2516}, {2353, 2539, 2540}, {1594, 2544, 2546}, {2113, 2550, 2551}, {2303, 2556, 2557}, {2429, 2561, 2563}, {2512, 2568, 2568}, {1739, 2572, 2572}, {1396, 2583, 2587}, {1854, 2593, 2593}, {2345, 2601, 2602}, {2536, 2606, 2612}, {2176, 2617, 2633}, {2421, 2637, 2637}, {1645, 2641, 2641}, {800, 2645, 2647}, {804, 2654, 2661}, {687, 2665, 2665}, {1668, 2669, 2669}, {1065, 2673, 2673}, {2027, 2677, 2677}, {2312, 2685, 2691}, {2371, 2695, 2697}, {2453, 2701, 2702}, {2479, 2711, 2711}, {2399, 2715, 2715}, {1018, 2720, 2723}, {1457, 2727, 2727}, {2376, 2732, 2732}, {1387, 2744, 2744}, {2641, 2748, 2748}, {2476, 2755, 2755}, {2460, 2761, 2765}, {2006, 2769, 2769}, {2773, 2774, 2809}, {2769, 2818, 2818}, {134, 2835, 2835}, {472, 2847, 2850}, {206, 2856, 2856}, {1072, 2860, 2863}, {801, 2867, 2868}, {787, 2875, 2883}, {2560, 2897, 2901}, {2744, 2909, 2913}, {2211, 2919, 2919}, {2150, 2927, 2927}, {2598, 2931, 2931}, {2761, 2936, 2938}, {1312, 2942, 2943}, {997, 2948, 2950}, {2637, 2957, 2961}, {2872, 2971, 2975}, {1687, 2983, 2984}, {2755, 2994, 2994}, {1644, 3000, 3001}, {1634, 3005, 3008}, {2555, 3012, 3014}, {2947, 3018, 3032}, {1649, 3036, 3051}, {691, 3055, 3055}, {2714, 3059, 3061}, {2498, 3069, 3069}, {3012, 3074, 3076}, {2543, 3087, 3089}, {2983, 3097, 3098}, {1011, 3111, 3111}, {1552, 3115, 3115}, {1427, 3124, 3124}, {1331, 3133, 3134}, {1012, 3138, 3140}, {2194, 3148, 3148}, {2561, 3152, 3155}, {3054, 3159, 3161}, {3065, 3169, 3173}, {2346, 3177, 3177}, {2606, 3181, 3185}, {2994, 3204, 3206}, {1329, 3210, 3211}, {1797, 3215, 3215}, {12, 3221, 3221}, {1013, 3227, 3228}, {3168, 3233, 3238}, {3194, 3247, 3247}, {3097, 3256, 3257}, {1219, 3265, 3271}, {1753, 3275, 3277}, {1550, 3282, 3292}, {1182, 3296, 3303}, {2818, 3307, 3307}, {2774, 3311, 3346}, {2812, 3350, 3356}, {2829, 3367, 3367}, {2835, 3373, 3387}, {2860, 3393, 3395}, {2971, 3405, 3409}, {1433, 3413, 3414}, {3405, 3424, 3428}, {2957, 3432, 3432}, {2889, 3455, 3460}, {1213, 3472, 3474}, {947, 3478, 3479}, {2747, 3490, 3491}, {3036, 3495, 3497}, {2873, 3501, 3504}, {2979, 3508, 3509}, {684, 3514, 3516}, {275, 3524, 3525}, {3221, 3529, 3529}, {2748, 3533, 3533}, {2708, 3546, 3546}, {1104, 3550, 3550}, {766, 3554, 3556}, {1672, 3560, 3561}, {1155, 3565, 3568}, {3417, 3572, 3572}, {2393, 3581, 3583}, {3533, 3587, 3587}, {762, 3591, 3591}, {820, 3604, 3605}, {3436, 3609, 3615}, {2497, 3624, 3625}, {3454, 3630, 3633}, {2276, 3642, 3644}, {823, 3649, 3649}, {648, 3660, 3662}, {2049, 3666, 3669}, {3111, 3680, 3680}, {2048, 3698, 3702}, {2313, 3706, 3708}, {2060, 3717, 3717}, {2695, 3722, 3724}, {1114, 3733, 3733}, {1385, 3738, 3738}, {3477, 3744, 3748}, {3512, 3753, 3753}, {2859, 3764, 3764}, {3210, 3773, 3774}, {1334, 3778, 3780}, {3103, 3785, 3785}, {3018, 3789, 3792}, {3432, 3802, 3802}, {3587, 3806, 3806}, {2148, 3819, 3819}, {1581, 3827, 3829}, {3485, 3833, 3838}, {2727, 3845, 3845}, {1303, 3849, 3849}, {2287, 3853, 3855}, {2133, 3859, 3862}, {3806, 3866, 3866}, {3827, 3878, 3880}, {3845, 3884, 3884}, {810, 3888, 3888}, {3866, 3892, 3892}, {3537, 3896, 3898}, {2905, 3903, 3907}, {3666, 3911, 3913}, {3455, 3920, 3924}, {3310, 3930, 3934}, {3311, 3939, 3942}, {3938, 3946, 3967}, {2340, 3977, 3977}, {3542, 3983, 3983}, {1629, 3992, 3992}, {3733, 3998, 3999}, {3816, 4003, 4007}, {2017, 4018, 4019}, {883, 4027, 4029}, {1178, 4033, 4033}, {3977, 4039, 4039}, {3069, 4044, 4045}, {3802, 4049, 4053}, {3875, 4061, 4066}, {1628, 4070, 4071}, {1113, 4075, 4076}, {1975, 4081, 4081}, {2414, 4087, 4087}, {4012, 4096, 4096}, {4017, 4102, 4104}, {2169, 4112, 4112}, {3998, 4123, 4124}, {2909, 4130, 4130}, {4032, 4136, 4136}, {4016, 4140, 4145}, {3565, 4154, 4157}, {3892, 4161, 4161}, {3878, 4168, 4169}, {3928, 4173, 4215}, {144, 4238, 4239}, {4243, 4244, 4244}, {3307, 4255, 4255}, {1971, 4261, 4268}, {3393, 4272, 4274}, {3591, 4278, 4278}, {1962, 4282, 4282}, {1688, 4286, 4286}, {3911, 4298, 4300}, {780, 4304, 4305}, {2842, 4309, 4309}, {4048, 4314, 4315}, {3770, 4321, 4321}, {2244, 4331, 4331}, {3148, 4336, 4336}, {1548, 4340, 4340}, {3209, 4345, 4351}, {768, 4355, 4355}, {1903, 4362, 4362}, {2212, 4366, 4366}, {1494, 4378, 4380}, {1183, 4385, 4391}, {3778, 4403, 4405}, {3642, 4409, 4411}, {2593, 4419, 4419}, {4160, 4430, 4431}, {3204, 4441, 4441}, {2875, 4450, 4451}, {1265, 4455, 4457}, {3927, 4466, 4466}, {416, 4479, 4480}, {4474, 4489, 4490}, {4135, 4502, 4504}, {4314, 4511, 4518}, {1870, 4529, 4529}, {3188, 4534, 4535}, {777, 4541, 4542}, {2370, 4549, 4552}, {1795, 4556, 4558}, {1529, 4577, 4577}, {4298, 4581, 4584}, {4336, 4596, 4596}, {1423, 4602, 4602}, {1004, 4608, 4608}, {4580, 4615, 4615}, {4003, 4619, 4623}, {4593, 4627, 4628}, {2680, 4644, 4644}, {2259, 4650, 4650}, {2544, 4654, 4655}, {4320, 4660, 4661}, {4511, 4672, 4673}, {4545, 4677, 4680}, {4570, 4689, 4696}, {2505, 4700, 4700}, {4605, 4706, 4712}, {3243, 4717, 4722}, {4581, 4726, 4734}, {3852, 4747, 4748}, {4653, 4756, 4758}, {4409, 4762, 4764}, {3165, 4774, 4774}, {2100, 4780, 4780}, {3722, 4784, 4786}, {4756, 4798, 4811}, {4422, 4815, 4815}, {3124, 4819, 4819}, {714, 4825, 4827}, {4699, 4832, 4832}, {4725, 4836, 4839}, {4588, 4844, 4845}, {1469, 4849, 4849}, {4743, 4853, 4863}, {4836, 4869, 4869}, {2682, 4873, 4873}, {4774, 4877, 4877}, {4738, 4881, 4882}, {4784, 4886, 4892}, {2759, 4896, 4896}, {4795, 4900, 4900}, {4378, 4905, 4905}, {1050, 4909, 4912}, {4634, 4917, 4918}, {4654, 4922, 4923}, {1542, 4930, 4930}, {4658, 4934, 4937}, {4762, 4941, 4943}, {4751, 4949, 4950}, {4286, 4961, 4961}, {1377, 4965, 4965}, {4587, 4971, 4973}, {2575, 4977, 4978}, {4922, 4982, 4983}, {4941, 4987, 4992}, {4790, 4996, 5000}, {4070, 5004, 5005}, {4538, 5009, 5012}, {4659, 5016, 5018}, {4926, 5024, 5034}, {3884, 5038, 5042}, {3853, 5046, 5048}, {4752, 5053, 5053}, {4954, 5057, 5057}, {4877, 5063, 5063}, {4977, 5067, 5067}, {2418, 5071, 5071}, {4968, 5075, 5075}, {681, 5079, 5080}, {5074, 5086, 5087}, {5016, 5091, 5092}, {2196, 5096, 5097}, {1782, 5107, 5108}, {5061, 5112, 5113}, {5096, 5117, 5118}, {1563, 5127, 5128}, {4872, 5134, 5135}, {1324, 5139, 5139}, {5111, 5144, 5148}, {4987, 5152, 5154}, {5075, 5158, 5175}, {4685, 5181, 5181}, {4961, 5185, 5185}, {1564, 5192, 5192}, {2982, 5198, 5199}, {917, 5203, 5203}, {4419, 5208, 5208}, {4507, 5213, 5213}, {5083, 5217, 5217}, {5091, 5221, 5222}, {3373, 5226, 5226}, {4475, 5231, 5231}, {4496, 5238, 5239}, {1255, 5243, 5244}, {3680, 5254, 5256}, {5157, 5260, 5261}, {4508, 5265, 5274}, {4946, 5279, 5279}, {1860, 5285, 5285}, {889, 5289, 5289}, {785, 5293, 5297}, {2290, 5303, 5303}, {2931, 5310, 5310}, {5021, 5316, 5316}, {2571, 5323, 5323}, {5071, 5327, 5327}, {5084, 5331, 5333}, {4614, 5342, 5343}, {4899, 5347, 5347}, {4441, 5351, 5351}, {5327, 5355, 5358}, {5063, 5362, 5362}, {3974, 5367, 5367}, {5316, 5382, 5382}, {2528, 5389, 5389}, {1391, 5393, 5393}, {2582, 5397, 5401}, {3074, 5405, 5407}, {4010, 5412, 5412}, {5382, 5420, 5420}, {5243, 5429, 5442}, {5265, 5447, 5447}, {5278, 5451, 5475}, {5319, 5479, 5483}, {1158, 5488, 5488}, {5423, 5494, 5496}, {5355, 5500, 5503}, {5283, 5507, 5509}, {5340, 5513, 5515}, {3841, 5530, 5530}, {1069, 5535, 5537}, {4970, 5541, 5544}, {5386, 5548, 5550}, {2916, 5556, 5563}, {4023, 5570, 5570}, {1215, 5576, 5576}, {4665, 5580, 5581}, {4402, 5585, 5586}, {5446, 5592, 5593}, {5330, 5597, 5597}, {5221, 5601, 5602}, {5300, 5606, 5608}, {4626, 5612, 5614}, {3660, 5618, 5618}, {2405, 5623, 5623}, {3486, 5628, 5633}, {3143, 5645, 5645}, {5606, 5650, 5650}, {5158, 5654, 5654}, {5378, 5658, 5658}, {4057, 5663, 5663}, {5107, 5670, 5670}, {4886, 5674, 5676}, {5654, 5680, 5680}, {5307, 5684, 5687}, {2449, 5691, 5691}, {5331, 5695, 5696}, {3215, 5700, 5700}, {5447, 5704, 5704}, {5650, 5708, 5708}, {4965, 5712, 5715}, {102, 5722, 5723}, {2753, 5733, 5735}, {5695, 5739, 5744}, {2182, 5748, 5748}, {4903, 5753, 5753}, {5507, 5757, 5759}, {5347, 5763, 5778}, {5548, 5782, 5784}, {5392, 5788, 5798}, {2304, 5803, 5803}, {4643, 5810, 5810}, {5703, 5815, 5817}, {4355, 5821, 5821}, {5429, 5825, 5826}, {3624, 5830, 5831}, {5711, 5836, 5836}, {5580, 5840, 5844}, {1909, 5848, 5848}, {4933, 5853, 5857}, {5100, 5863, 5870}, {4904, 5875, 5876}, {4529, 5883, 5883}, {3220, 5892, 5893}, {1533, 5897, 5897}, {4780, 5904, 5904}, {3101, 5908, 5909}, {5627, 5914, 5920}, {4166, 5926, 5929}, {5596, 5933, 5934}, {5680, 5938, 5938}, {4849, 5942, 5942}, {5739, 5948, 5949}, {5533, 5961, 5961}, {849, 5972, 5972}, {3752, 5989, 5990}, {2158, 5996, 5996}, {4982, 6000, 6001}, {5601, 6005, 6007}, {5101, 6014, 6021}, {4726, 6025, 6025}, {5720, 6036, 6039}, {4534, 6045, 6046}, {5763, 6050, 6050}, {5914, 6057, 6063}, {1492, 6067, 6067}, {2160, 6075, 6078}, {4619, 6083, 6083}, {893, 6092, 6093}, {5948, 6097, 6097}, {2556, 6105, 6106}, {1615, 6110, 6110}, {1156, 6114, 6120}, {5699, 6128, 6128}, {2710, 6132, 6133}, {4446, 6138, 6138}, {5815, 6143, 6148}, {1254, 6152, 6161}, {2357, 6167, 6168}, {2144, 6172, 6176}, {2159, 6184, 6184}, {5810, 6188, 6190}, {4011, 6195, 6195}, {6070, 6199, 6199}, {6005, 6203, 6206}, {4683, 6211, 6213}, {4466, 6221, 6222}, {5230, 6226, 6231}, {5238, 6235, 6239}, {5250, 6246, 6253}, {5704, 6257, 6257}, {5451, 6261, 6286}, {181, 6293, 6293}, {5314, 6297, 6305}, {5788, 6314, 6316}, {5938, 6320, 6320}, {4844, 6324, 6325}, {5782, 6329, 6332}, {5628, 6336, 6337}, {4873, 6341, 6342}, {6110, 6346, 6346}, {6328, 6350, 6354}, {1036, 6358, 6359}, {6128, 6364, 6364}, {4740, 6373, 6373}, {2282, 6377, 6377}, {5405, 6386, 6388}, {6257, 6392, 6392}, {4123, 6396, 6397}, {5487, 6401, 6410}, {6290, 6414, 6415}, {3844, 6423, 6424}, {3888, 6428, 6428}, {1086, 6432, 6432}, {5320, 6436, 6439}, {6310, 6443, 6444}, {6401, 6448, 6448}, {5124, 6452, 6452}, {5424, 6456, 6457}, {5851, 6472, 6478}, {6050, 6482, 6482}, {5499, 6486, 6490}, {4900, 6498, 6500}, {5674, 6510, 6512}, {871, 6518, 6520}, {5748, 6528, 6528}, {6447, 6533, 6534}, {5820, 6538, 6539}, {6448, 6543, 6543}, {6199, 6547, 6547}, {6320, 6551, 6551}, {1882, 6555, 6555}, {6368, 6561, 6566}, {6097, 6570, 6570}, {6495, 6576, 6579}, {5821, 6583, 6583}, {6507, 6587, 6587}, {4454, 6596, 6596}, {2324, 6601, 6601}, {6547, 6608, 6608}, {5712, 6612, 6612}, {5575, 6618, 6619}, {6414, 6623, 6624}, {6296, 6629, 6629}, {4134, 6633, 6634}, {6561, 6640, 6644}, {4555, 6649, 6652}, {4671, 6659, 6660}, {5592, 6664, 6666}, {5152, 6670, 6672}, {6599, 6676, 6676}, {5521, 6680, 6691}, {6432, 6695, 6695}, {6623, 6699, 6705}, {2601, 6712, 6712}, {5117, 6723, 6724}, {6524, 6730, 6733}, {5351, 6737, 6737}, {6573, 6741, 6741}, {6392, 6745, 6746}, {6592, 6750, 6751}, {4650, 6760, 6761}, {5302, 6765, 6765}, {6615, 6770, 6783}, {3732, 6787, 6789}, {6709, 6793, 6793}, {5306, 6797, 6797}, {6243, 6801, 6802}, {5226, 6808, 6816}, {4497, 6821, 6821}, {1436, 6825, 6825}, {1790, 6833, 6834}, {5525, 6838, 6843}, {5279, 6847, 6849}, {6828, 6855, 6857}, {5038, 6861, 6865}, {6741, 6869, 6869}, {4627, 6873, 6873}, {4037, 6878, 6880}, {10, 6885, 6887}, {6730, 6894, 6894}, {5528, 6898, 6898}, {6744, 6903, 6903}, {5839, 6907, 6907}, {2350, 6911, 6911}, {2269, 6915, 6918}, {6869, 6922, 6922}, {6035, 6929, 6930}, {1604, 6938, 6939}, {6922, 6943, 6943}, {6699, 6947, 6950}, {6737, 6954, 6954}, {1775, 6958, 6959}, {5309, 6963, 6964}, {6954, 6968, 6968}, {6369, 6972, 6976}, {3789, 6980, 6983}, {2327, 6990, 6990}, {6837, 6995, 7001}, {4485, 7006, 7013}, {6820, 7017, 7031}, {6291, 7036, 7036}, {5691, 7041, 7042}, {7034, 7047, 7047}, {5310, 7051, 7051}, {1502, 7056, 7056}, {4797, 7061, 7061}, {6855, 7066, 7068}, {6669, 7072, 7075}, {6943, 7079, 7079}, {6528, 7083, 7083}, {4036, 7087, 7090}, {6884, 7094, 7100}, {6946, 7104, 7108}, {6297, 7112, 7114}, {5684, 7118, 7121}, {6903, 7127, 7135}, {3580, 7141, 7147}, {6926, 7152, 7182}, {7117, 7186, 7190}, {6968, 7194, 7217}, {6838, 7222, 7227}, {7005, 7231, 7240}, {6235, 7244, 7245}, {6825, 7249, 7249}, {4594, 7254, 7254}, {6569, 7258, 7258}, {7222, 7262, 7267}, {7047, 7272, 7272}, {6801, 7276, 7276}, {7056, 7280, 7280}, {6583, 7284, 7284}, {5825, 7288, 7294}, {6787, 7298, 7300}, {7079, 7304, 7304}, {7253, 7308, 7313}, {6891, 7317, 7317}, {6829, 7321, 7322}, {7257, 7326, 7363}, {7231, 7367, 7377}, {2854, 7381, 7381}, {7249, 7385, 7385}, {6203, 7389, 7391}, {6363, 7395, 7397}, {6745, 7401, 7402}, {6695, 7406, 7406}, {5208, 7410, 7411}, {6679, 7415, 7416}, {7288, 7420, 7421}, {5248, 7425, 7425}, {6422, 7429, 7429}, {5206, 7434, 7436}, {2255, 7441, 7442}, {2145, 7452, 7452}, {7283, 7458, 7459}, {4830, 7469, 7472}, {6000, 7476, 7477}, {7395, 7481, 7492}, {2715, 7496, 7496}, {6542, 7500, 7502}, {7420, 7506, 7513}, {4981, 7517, 7517}, {2243, 7522, 7524}, {916, 7528, 7529}, {5207, 7533, 7534}, {1271, 7538, 7539}, {2654, 7544, 7544}, {7451, 7553, 7561}, {7464, 7569, 7571}, {3992, 7577, 7577}, {3114, 7581, 7581}, {7389, 7589, 7591}, {7433, 7595, 7598}, {7448, 7602, 7608}, {1772, 7612, 7612}, {4152, 7616, 7616}, {3247, 7621, 7624}, {963, 7629, 7630}, {4895, 7640, 7640}, {6164, 7646, 7646}, {4339, 7663, 7664}, {3244, 7668, 7672}, {7304, 7676, 7676}, {7401, 7680, 7681}, {6670, 7685, 7688}, {6195, 7692, 7693}, {7505, 7699, 7705}, {5252, 7709, 7710}, {6193, 7715, 7718}, {1916, 7724, 7724}, {4868, 7729, 7731}, {1176, 7736, 7736}, {5700, 7740, 7740}, {5757, 7744, 7746}, {6345, 7750, 7752}, {3132, 7756, 7759}, {4312, 7763, 7763}, {7685, 7767, 7769}, {6907, 7774, 7774}, {5584, 7779, 7780}, {6025, 7784, 7784}, {4435, 7791, 7798}, {6807, 7809, 7817}, {6234, 7823, 7825}, {7385, 7829, 7829}, {1286, 7833, 7836}, {7258, 7840, 7840}, {7602, 7844, 7850}, {7388, 7854, 7856}, {7528, 7860, 7866}, {640, 7874, 7875}, {7844, 7879, 7886}, {4700, 7890, 7890}, {7440, 7894, 7896}, {4831, 7900, 7902}, {4556, 7906, 7908}, {7547, 7914, 7924}, {7589, 7928, 7929}, {7914, 7935, 7945}, {7284, 7949, 7949}, {7538, 7953, 7957}, {4635, 7964, 7964}, {1994, 7968, 7970}, {7406, 7974, 7976}, {2409, 7983, 7983}, {7542, 7989, 7989}, {7112, 7993, 7993}, {5259, 7997, 7999}, {1287, 8004, 8006}, {7911, 8010, 8011}, {7449, 8015, 8021}, {7928, 8025, 8027}, {1476, 8042, 8044}, {7784, 8048, 8050}, {4434, 8054, 8062}, {7802, 8066, 8074}, {7367, 8087, 8088}, {4494, 8094, 8097}, {7829, 8101, 8101}, {7321, 8105, 8111}, {7035, 8115, 8121}, {7949, 8125, 8125}, {7506, 8129, 8130}, {5830, 8134, 8135}, {8047, 8144, 8144}, {5362, 8148, 8148}, {8125, 8152, 8152}, {7676, 8156, 8156}, {6324, 8160, 8161}, {6606, 8173, 8173}, {7064, 8177, 8182}, {6993, 8186, 8199}, {8092, 8203, 8204}, {7244, 8208, 8213}, {8105, 8217, 8218}, {8185, 8222, 8222}, {8115, 8226, 8232}, {4164, 8238, 8239}, {6608, 8244, 8244}, {8176, 8248, 8277}, {8208, 8281, 8282}, {7997, 8287, 8289}, {7118, 8293, 8303}, {7103, 8308, 8308}, {6436, 8312, 8315}, {3523, 8321, 8321}, {6442, 8327, 8329}, {3391, 8333, 8334}, {6986, 8339, 8344}, {7221, 8348, 8354}, {5989, 8358, 8360}, {4418, 8364, 8365}, {8307, 8369, 8370}, {7051, 8375, 8375}, {4027, 8379, 8380}, {8333, 8384, 8387}, {6873, 8391, 8392}, {4154, 8396, 8399}, {6878, 8403, 8428}, {8087, 8432, 8438}, {7017, 8442, 8443}, {8129, 8447, 8453}, {6486, 8457, 8461}, {8248, 8465, 8465}, {6349, 8473, 8478}, {5393, 8482, 8483}, {8465, 8487, 8487}, {30, 8495, 8495}, {4642, 8499, 8500}, {6768, 8505, 8505}, {7061, 8513, 8514}, {7151, 8518, 8528}, {6648, 8532, 8532}, {2093, 8539, 8539}, {3392, 8544, 8544}, {6980, 8548, 8551}, {8217, 8555, 8563}, {8375, 8567, 8567}, {7041, 8571, 8571}, {5008, 8576, 8576}, {4796, 8580, 8582}, {4271, 8586, 8586}, {7320, 8591, 8593}, {8222, 8597, 8597}, {7262, 8601, 8606}, {8432, 8610, 8615}, {8442, 8619, 8620}, {8101, 8624, 8624}, {7308, 8628, 8628}, {8597, 8632, 8641}, {8498, 8645, 8645}, {927, 8650, 8651}, {5979, 8661, 8661}, {5381, 8665, 8666}, {2184, 8675, 8675}, {5342, 8680, 8681}, {1527, 8686, 8687}, {4168, 8694, 8694}, {8332, 8698, 8702}, {8628, 8706, 8710}, {8447, 8714, 8720}, {8610, 8724, 8724}, {5530, 8730, 8730}, {6472, 8734, 8734}, {7476, 8738, 8739}, {7756, 8743, 8743}, {8570, 8749, 8753}, {2706, 8757, 8759}, {5875, 8763, 8764}, {8147, 8769, 8770}, {6526, 8775, 8776}, {8694, 8780, 8780}, {3431, 8784, 8785}, {7787, 8789, 8789}, {5526, 8794, 8796}, {6902, 8800, 8801}, {8756, 8811, 8818}, {7735, 8822, 8823}, {5523, 8827, 8828}, {5668, 8833, 8833}, {2237, 8839, 8839}, {8152, 8843, 8846}, {6633, 8852, 8853}, {6152, 8858, 8865}, {8762, 8869, 8870}, {6216, 8876, 8878}, {8632, 8882, 8892}, {2436, 8896, 8897}, {5541, 8901, 8904}, {8293, 8908, 8911}, {7194, 8915, 8915}, {5658, 8919, 8919}, {5045, 8923, 8927}, {7549, 8932, 8932}, {1623, 8936, 8941}, {6471, 8946, 8947}, {8487, 8951, 8951}, {8714, 8955, 8961}, {8574, 8965, 8965}, {2701, 8969, 8970}, {5500, 8974, 8977}, {8481, 8984, 8986}, {5416, 8991, 8991}, {8950, 8996, 8996}, {8706, 9001, 9005}, {8601, 9009, 9014}, {8882, 9018, 9018}, {8951, 9022, 9022}, {1521, 9026, 9026}, {8025, 9030, 9031}, {8645, 9035, 9035}, {8384, 9039, 9042}, {9001, 9046, 9050}, {3189, 9054, 9054}, {8955, 9058, 9065}, {1043, 9078, 9079}, {8974, 9083, 9095}, {6496, 9099, 9100}, {8995, 9104, 9105}, {9045, 9109, 9110}, {6395, 9114, 9116}, {9038, 9125, 9125}, {9029, 9135, 9138}, {1051, 9144, 9147}, {7833, 9151, 9155}, {9022, 9159, 9159}, {9046, 9163, 9163}, {2732, 9168, 9170}, {7750, 9174, 9180}, {8747, 9184, 9186}, {7663, 9192, 9193}, {9159, 9197, 9197}, {8730, 9207, 9209}, {4429, 9223, 9223}, {8536, 9227, 9227}, {1231, 9237, 9237}, {8965, 9244, 9244}, {5840, 9248, 9254}, {4058, 9263, 9270}, {3214, 9288, 9289}, {6346, 9293, 9293}, {6114, 9297, 9298}, {9104, 9302, 9302}, {4818, 9331, 9332}, {8513, 9336, 9337}, {6971, 9341, 9346}, {8779, 9357, 9357}, {8989, 9363, 9367}, {8843, 9371, 9373}, {9035, 9381, 9382}, {3648, 9386, 9386}, {6988, 9390, 9403}, {8869, 9407, 9407}, {7767, 9411, 9413}, {6341, 9417, 9417}, {2293, 9424, 9424}, {9360, 9428, 9428}, {8048, 9432, 9435}, {8981, 9439, 9439}, {6336, 9443, 9444}, {9431, 9449, 9453}, {8391, 9457, 9458}, {9380, 9463, 9464}, {6947, 9468, 9471}, {7993, 9475, 9475}, {7185, 9479, 9484}, {5848, 9488, 9488}, {9371, 9492, 9492}, {7628, 9498, 9500}, {8757, 9504, 9504}, {9410, 9508, 9508}, {9293, 9512, 9512}, {5138, 9516, 9516}, {9420, 9521, 9521}, {4416, 9525, 9528}, {4825, 9534, 9536}, {9057, 9540, 9540}, {7276, 9544, 9546}, {5491, 9550, 9550}, {9058, 9554, 9560}, {8321, 9569, 9569}, {6357, 9573, 9575}, {9385, 9579, 9579}, {6972, 9583, 9587}, {7996, 9591, 9594}, {8990, 9598, 9599}, {9442, 9603, 9605}, {9579, 9609, 9609}, {9389, 9613, 9628}, {8789, 9632, 9632}, {7152, 9636, 9646}, {9491, 9652, 9653}, {2493, 9658, 9659}, {2456, 9663, 9664}, {8509, 9672, 9675}, {6510, 9682, 9684}, {2533, 9688, 9688}, {6632, 9696, 9698}, {4460, 9709, 9711}, {9302, 9715, 9718}, {9609, 9722, 9722}, {4824, 9728, 9731}, {9553, 9735, 9735}, {9544, 9739, 9742}, {9492, 9746, 9746}, {9554, 9750, 9756}, {9525, 9761, 9764}, {7789, 9769, 9769}, {2136, 9773, 9777}, {3848, 9782, 9783}, {9432, 9787, 9790}, {8165, 9794, 9795}, {9590, 9799, 9803}, {8555, 9807, 9812}, {9009, 9816, 9822}, {9656, 9829, 9833}, {4101, 9841, 9841}, {6382, 9846, 9846}, {9721, 9850, 9850}, {9296, 9854, 9856}, {9573, 9860, 9866}, {9636, 9870, 9883}, {9722, 9887, 9887}, {9163, 9891, 9891}, {9799, 9895, 9895}, {9816, 9899, 9906}, {767, 9912, 9913}, {8287, 9918, 9923}, {6293, 9927, 9930}, {9726, 9934, 9934}, {6876, 9939, 9940}, {5847, 9945, 9946}, {9829, 9951, 9955}, {9125, 9962, 9962}, {8542, 9967, 9972}, {9767, 9978, 9978}, {4165, 9982, 9982}, {8243, 9986, 9987}, {9682, 9993, 9995}, {4916, 10006, 10010}, {9456, 10016, 10018}, {9761, 10024, 10029}, {9886, 10033, 10034}, {9468, 10038, 10044}, {3000, 10052, 10053}, {9807, 10057, 10062}, {8226, 10066, 10072}, {9650, 10077, 10080}, {9054, 10084, 10084}, {9891, 10088, 10089}, {6518, 10095, 10097}, {8238, 10101, 10117}, {7890, 10121, 10123}, {9894, 10128, 10138}, {3508, 10142, 10143}, {6377, 10147, 10147}, {3768, 10152, 10154}, {6764, 10158, 10160}, {8852, 10164, 10166}, {2867, 10172, 10174}, {4461, 10178, 10179}, {5889, 10184, 10185}, {9917, 10189, 10191}, {6797, 10195, 10195}, {8567, 10199, 10199}, {7125, 10203, 10206}, {9938, 10210, 10234}, {9967, 10240, 10246}, {8923, 10251, 10254}, {10157, 10258, 10258}, {8032, 10264, 10264}, {9887, 10268, 10276}, {9750, 10280, 10286}, {10258, 10290, 10290}, {10268, 10294, 10302}, {9899, 10306, 10311}, {9715, 10315, 10318}, {8539, 10322, 10322}, {10189, 10327, 10329}, {9135, 10333, 10335}, {8369, 10340, 10341}, {9119, 10347, 10347}, {10290, 10352, 10352}, {7900, 10357, 10359}, {3275, 10363, 10365}, {10294, 10369, 10369}, {5417, 10376, 10376}, {10120, 10381, 10381}, {9786, 10385, 10395}, {9826, 10399, 10399}, {8171, 10403, 10407}, {8402, 10421, 10425}, {9428, 10429, 10429}, {1863, 10434, 10435}, {3092, 10446, 10446}, {10000, 10450, 10450}, {9986, 10463, 10464}, {9632, 10468, 10484}, {10315, 10489, 10489}, {10332, 10493, 10493}, {8914, 10506, 10507}, {10369, 10511, 10512}, {1865, 10516, 10517}, {9204, 10521, 10526}, {9993, 10533, 10534}, {2568, 10539, 10539}, {10429, 10543, 10543}, {10489, 10549, 10549}, {10014, 10553, 10558}, {10024, 10563, 10573}, {9457, 10577, 10578}, {9591, 10582, 10585}, {8908, 10589, 10592}, {10203, 10596, 10598}, {10006, 10602, 10604}, {10209, 10613, 10613}, {4996, 10617, 10617}, {9846, 10621, 10622}, {6927, 10627, 10635}, {8664, 10639, 10639}, {8586, 10643, 10644}, {10576, 10648, 10650}, {10487, 10654, 10656}, {10553, 10660, 10664}, {10563, 10670, 10679}, {9000, 10683, 10688}, {10280, 10692, 10699}, {10582, 10703, 10706}, {9934, 10710, 10710}, {10547, 10714, 10716}, {7065, 10720, 10724}, {10691, 10730, 10738}, {872, 10742, 10744}, {10357, 10751, 10752}, {1323, 10756, 10756}, {10087, 10761, 10763}, {9381, 10769, 10769}, {9982, 10773, 10778}, {10533, 10784, 10785}, {9687, 10789, 10789}, {8324, 10799, 10799}, {8742, 10805, 10813}, {9039, 10817, 10824}, {5947, 10828, 10828}, {10306, 10832, 10837}, {10261, 10841, 10843}, {10350, 10847, 10850}, {7415, 10860, 10861}, {19, 10866, 10866}, {10188, 10872, 10875}, {10613, 10881, 10881}, {7869, 10886, 10886}, {3801, 10891, 10892}, {9099, 10896, 10897}, {8738, 10903, 10904}, {10322, 10908, 10908}, {6494, 10912, 10916}, {9772, 10921, 10921}, {8170, 10927, 10930}, {7456, 10940, 10943}, {10457, 10948, 10952}, {1405, 10959, 10959}, {6936, 10963, 10963}, {4549, 10970, 10975}, {4880, 10982, 10982}, {8763, 10986, 10987}, {4565, 10993, 10994}, {1310, 11000, 11000}, {4596, 11010, 11010}, {6427, 11015, 11016}, {7729, 11023, 11024}, {10978, 11029, 11030}, {10947, 11034, 11039}, {10577, 11043, 11043}, {10542, 11052, 11053}, {9443, 11057, 11058}, {10468, 11062, 11062}, {11028, 11066, 11068}, {10057, 11072, 11073}, {8881, 11077, 11078}, {8148, 11082, 11082}, {10816, 11089, 11093}, {11066, 11097, 11109}, {10511, 11113, 11113}, {9174, 11117, 11119}, {10345, 11125, 11125}, {4532, 11129, 11129}, {9918, 11133, 11134}, {8858, 11138, 11146}, {10703, 11150, 11153}, {9030, 11157, 11160}, {6481, 11165, 11166}, {10543, 11170, 11170}, {8580, 11177, 11178}, {10886, 11184, 11187}, {10210, 11191, 11197}, {2015, 11202, 11202}, {9312, 11211, 11218}, {9324, 11223, 11231}, {10884, 11235, 11235}, {8166, 11239, 11239}, {10502, 11243, 11250}, {11182, 11254, 11259}, {5366, 11263, 11264}, {3676, 11268, 11268}, {5649, 11273, 11274}, {11065, 11281, 11284}, {11034, 11288, 11293}, {7083, 11297, 11297}, {9550, 11302, 11302}, {9336, 11310, 11311}, {7071, 11316, 11316}, {11314, 11320, 11320}, {11113, 11324, 11324}, {11157, 11328, 11330}, {6482, 11334, 11334}, {7139, 11338, 11338}, {10152, 11345, 11345}, {3554, 11352, 11356}, {11190, 11364, 11364}, {11324, 11368, 11368}, {10710, 11372, 11372}, {8793, 11376, 11381}, {6358, 11385, 11386}, {11368, 11390, 11390}, {9704, 11394, 11396}, {7778, 11400, 11400}, {11149, 11404, 11408}, {10889, 11414, 11414}, {9781, 11421, 11422}, {10267, 11426, 11427}, {11328, 11431, 11433}, {5751, 11439, 11440}, {10817, 11444, 11447}, {10896, 11451, 11452}, {10751, 11456, 11457}, {10163, 11461, 11461}, {10504, 11466, 11473}, {8743, 11477, 11484}, {11150, 11488, 11491}, {10088, 11495, 11495}, {10828, 11499, 11509}, {11444, 11513, 11516}, {11495, 11520, 11520}, {11487, 11524, 11524}, {10692, 11528, 11535}, {9121, 11540, 11546}, {11389, 11558, 11564}, {10195, 11568, 11578}, {5004, 11582, 11583}, {5908, 11588, 11588}, {11170, 11592, 11592}, {11253, 11597, 11597}, {11372, 11601, 11601}, {3115, 11605, 11605}, {11390, 11609, 11609}, {10832, 11613, 11616}, {8800, 11620, 11621}, {11384, 11625, 11631}, {10171, 11635, 11637}, {11400, 11642, 11650}, {11451, 11654, 11655}, {11419, 11661, 11664}, {11608, 11668, 11669}, {11431, 11673, 11680}, {11550, 11688, 11690}, {11609, 11694, 11694}, {10588, 11702, 11708}, {6664, 11712, 11712}, {11461, 11719, 11753}, {11524, 11757, 11757}, {11613, 11761, 11764}, {10257, 11769, 11770}, {11694, 11774, 11774}, {11520, 11778, 11781}, {11138, 11785, 11793}, {11539, 11797, 11797}, {11512, 11802, 11802}, {10602, 11808, 11812}, {11773, 11816, 11824}, {11760, 11828, 11835}, {9083, 11839, 11850}, {11654, 11855, 11857}, {6612, 11861, 11862}, {11816, 11866, 11875}, {11528, 11879, 11897}, {10549, 11901, 11901}, {9108, 11905, 11907}, {11757, 11911, 11920}, {837, 11924, 11928}, {11855, 11932, 11934}, {8482, 11938, 11939}, {9439, 11943, 11943}, {1068, 11950, 11953}, {10789, 11958, 11958}, {4611, 11963, 11964}, {11861, 11968, 11992}, {11797, 11997, 12004}, {11719, 12009, 12009}, {11774, 12013, 12013}, {756, 12017, 12019}, {10178, 12023, 12024}, {9258, 12028, 12047}, {9534, 12060, 12063}, {12013, 12067, 12067}, {8160, 12071, 12072}, {10865, 12076, 12083}, {9311, 12091, 12099}, {11223, 12104, 12115}, {11932, 12119, 12120}, {2925, 12130, 12130}, {6906, 12135, 12136}, {8895, 12143, 12143}, {4684, 12147, 12148}, {11642, 12152, 12152}, {5573, 12160, 12164}, {10459, 12168, 12168}, {2108, 12172, 12172}, {187, 12179, 12180}, {2358, 12184, 12184}, {11796, 12188, 12188}, {1963, 12192, 12192}, {2538, 12199, 12200}, {6497, 12206, 12206}, {6723, 12210, 12211}, {7657, 12216, 12216}, {12204, 12224, 12231}, {1080, 12239, 12240}, {12224, 12244, 12246}, {11911, 12250, 12250}, {9912, 12266, 12268}, {7616, 12272, 12272}, {1956, 12279, 12279}, {1522, 12283, 12285}, {9504, 12289, 12290}, {11672, 12297, 12300}, {10621, 12304, 12304}, {11592, 12308, 12308}, {11385, 12312, 12313}, {3281, 12317, 12317}, {3487, 12321, 12321}, {9417, 12325, 12325}, {9613, 12335, 12337}, {10670, 12342, 12348}, {10589, 12352, 12357}, {10616, 12362, 12363}, {9326, 12369, 12375}, {5211, 12379, 12382}, {12304, 12386, 12395}, {1048, 12399, 12399}, {12335, 12403, 12405}, {12250, 12410, 12410}, {10084, 12414, 12414}, {11394, 12418, 12421}, {12126, 12425, 12429}, {9582, 12433, 12438}, {10784, 12445, 12447}, {9568, 12454, 12455}, {12308, 12459, 12459}, {9635, 12464, 12475}, {11513, 12479, 12482}, {12119, 12486, 12487}, {12066, 12494, 12495}, {12403, 12499, 12502}, {11687, 12506, 12513}, {12418, 12517, 12519}, {12352, 12523, 12528}, {11600, 12532, 12532}, {12450, 12539, 12539}, {12067, 12543, 12543}, {11477, 12547, 12565}, {11540, 12569, 12575}, {11202, 12580, 12581}, {10903, 12585, 12586}, {11601, 12590, 12590}, {12459, 12599, 12599}, {11839, 12603, 12605}, {11426, 12609, 12610}, {12486, 12614, 12616}, {9406, 12621, 12621}, {6897, 12625, 12628}, {12312, 12632, 12633}, {12445, 12638, 12640}, {1743, 12645, 12645}, {11551, 12649, 12650}, {12543, 12654, 12654}, {11635, 12658, 12660}, {12522, 12664, 12675}, {12539, 12683, 12712}, {11801, 12716, 12721}, {5803, 12725, 12725}, {716, 12730, 12732}, {8900, 12736, 12740}, {12076, 12744, 12746}, {5046, 12751, 12751}, {12735, 12755, 12755}, {11879, 12759, 12766}, {1609, 12770, 12770}, {10921, 12774, 12774}, {11420, 12778, 12778}, {12754, 12783, 12784}, {12177, 12788, 12788}, {12191, 12792, 12792}, {12139, 12798, 12802}, {11082, 12806, 12806}, {12152, 12810, 12810}, {10381, 12814, 12814}, {11239, 12820, 12821}, {2198, 12825, 12826}, {6123, 12832, 12832}, {10642, 12836, 12839}, {11117, 12843, 12844}, {12210, 12848, 12849}, {9688, 12853, 12853}, {12832, 12857, 12860}, {12147, 12864, 12870}, {12028, 12874, 12893}, {12052, 12898, 12898}, {8202, 12902, 12903}, {7243, 12907, 12909}, {8014, 12913, 12920}, {7680, 12924, 12931}, {11056, 12939, 12941}, {3817, 12946, 12949}, {9390, 12954, 12954}, {12249, 12958, 12960}, {12237, 12966, 12969}, {12638, 12973, 12975}, {12386, 12979, 12979}, {10626, 12984, 12997}, {6793, 13005, 13005}, {10625, 13009, 13025}, {12963, 13029, 13029}, {10038, 13033, 13036}, {12599, 13040, 13041}, {11568, 13046, 13050}, {13040, 13054, 13054}, {11238, 13058, 13060}, {5125, 13064, 13064}, {12425, 13068, 13080}, {9760, 13084, 13088}, {12729, 13092, 13093}, {9672, 13097, 13099}, {3675, 13104, 13104}, {6055, 13108, 13112}, {2681, 13119, 13120}, {12843, 13124, 13125}, {12952, 13129, 13132}, {13063, 13137, 13137}, {5861, 13141, 13141}, {10948, 13145, 13149}, {3080, 13153, 13153}, {12743, 13158, 13158}, {13123, 13163, 13166}, {11043, 13170, 13171}, {13136, 13175, 13176}, {12796, 13180, 13181}, {13107, 13185, 13185}, {13156, 13192, 13202}, {12954, 13207, 13208}, {8648, 13213, 13231}, {10403, 13235, 13235}, {12603, 13239, 13239}, {13029, 13243, 13243}, {6420, 13251, 13251}, {5801, 13261, 13265}, {8901, 13269, 13272}, {5139, 13276, 13278}, {8036, 13282, 13283}, {8041, 13288, 13288}, {10871, 13293, 13297}, {12923, 13301, 13303}, {10340, 13307, 13308}, {9926, 13312, 13316}, {9478, 13320, 13328}, {4571, 13334, 13339}, {8325, 13343, 13343}, {10933, 13349, 13349}, {9515, 13354, 13354}, {10979, 13358, 13358}, {7500, 13364, 13366}, {12820, 13371, 13375}, {13068, 13380, 13392}, {8724, 13397, 13397}, {8624, 13401, 13401}, {13206, 13405, 13406}, {12939, 13410, 13412}, {11015, 13417, 13418}, {12924, 13422, 13423}, {13103, 13427, 13431}, {13353, 13435, 13435}, {13415, 13440, 13443}, {10147, 13447, 13448}, {13180, 13452, 13457}, {12751, 13461, 13461}, {2291, 13465, 13465}, {12168, 13469, 13471}, {7744, 13475, 13477}, {6386, 13488, 13490}, {12755, 13494, 13494}, {13482, 13498, 13499}, {12410, 13503, 13503}, {13494, 13507, 13507}, {11376, 13511, 13516}, {13422, 13520, 13521}, {10742, 13525, 13527}, {1528, 13531, 13531}, {7517, 13537, 13537}, {4930, 13541, 13542}, {13507, 13546, 13546}, {13033, 13550, 13553}, {9475, 13557, 13568}, {12805, 13572, 13572}, {6188, 13576, 13578}, {12770, 13582, 13587}, {12648, 13593, 13594}, {13054, 13598, 13598}, {8856, 13603, 13613}, {1046, 13618, 13619}, {13348, 13623, 13624}, {13520, 13628, 13628}, {10142, 13632, 13633}, {13434, 13643, 13643}, {5488, 13648, 13648}, {649, 13652, 13652}, {11272, 13657, 13657}, {12873, 13663, 13663}, {4631, 13670, 13670}, {12578, 13674, 13677}, {12091, 13684, 13692}, {13581, 13699, 13699}, {13549, 13704, 13708}, {13598, 13712, 13712}, {13320, 13716, 13722}, {13712, 13726, 13726}, {13370, 13730, 13731}, {11352, 13735, 13737}, {13601, 13742, 13742}, {13497, 13746, 13769}, {12973, 13773, 13775}, {11235, 13784, 13784}, {10627, 13788, 13796}, {13152, 13800, 13800}, {12585, 13804, 13804}, {13730, 13809, 13810}, {13488, 13814, 13816}, {11815, 13821, 13821}, {11254, 13825, 13825}, {13788, 13829, 13838}, {13141, 13842, 13842}, {9658, 13846, 13848}, {11088, 13852, 13853}, {10239, 13860, 13866}, {13780, 13870, 13871}, {9981, 13877, 13883}, {11901, 13889, 13891}, {13405, 13895, 13897}, {12680, 13901, 13901}, {8363, 13905, 13910}, {13546, 13914, 13914}, {13498, 13918, 13927}, {13550, 13931, 13937}, {13628, 13941, 13941}, {13900, 13952, 13952}, {13841, 13957, 13957}, {3102, 13961, 13961}, {12835, 13966, 13970}, {12071, 13974, 13975}, {12810, 13979, 13980}, {11488, 13984, 13987}, {13809, 13991, 13992}, {13234, 13996, 13997}, {13886, 14001, 14002}, {11128, 14006, 14007}, {6013, 14012, 14013}, {8748, 14018, 14020}, {9678, 14024, 14024}, {12188, 14029, 14029}, {13914, 14033, 14033}, {11778, 14037, 14040}, {11828, 14044, 14051}, {12479, 14055, 14058}, {14037, 14062, 14066}, {12759, 14070, 14076}, {13889, 14080, 14081}, {13895, 14086, 14121}, {10199, 14125, 14131}, {13663, 14135, 14135}, {9261, 14139, 14155}, {12898, 14160, 14160}, {13667, 14164, 14167}, {12579, 14172, 14174}, {13681, 14178, 14189}, {13697, 14194, 14196}, {14033, 14200, 14200}, {13931, 14204, 14207}, {13726, 14211, 14211}, {9583, 14215, 14222}, {13243, 14226, 14226}, {13379, 14230, 14231}, {7481, 14237, 14239}, {10373, 14243, 14243}, {8644, 14248, 14249}, {1082, 14259, 14260}, {5814, 14265, 14265}, {10414, 14269, 14270}, {9512, 14274, 14274}, {9286, 14285, 14288}, {12593, 14295, 14295}, {13773, 14300, 14302}, {5874, 14308, 14308}, {13804, 14312, 14312}, {10412, 14317, 14320}, {12836, 14324, 14327}, {13974, 14331, 14337}, {14200, 14341, 14341}, {14086, 14345, 14347}, {4853, 14352, 14353}, {13961, 14357, 14357}, {14340, 14361, 14367}, {14005, 14374, 14374}, {13857, 14379, 14388}, {10532, 14397, 14399}, {14379, 14405, 14406}, {11957, 14411, 14413}, {10939, 14419, 14419}, {12547, 14423, 14429}, {13772, 14435, 14438}, {14341, 14442, 14447}, {14409, 14453, 14453}, {14442, 14457, 14457}, {13918, 14461, 14470}, {13511, 14474, 14483}, {14080, 14487, 14488}, {14344, 14492, 14495}, {13901, 14499, 14520}, {12609, 14524, 14525}, {14204, 14529, 14532}, {13557, 14536, 14536}, {6220, 14541, 14542}, {14139, 14546, 14562}, {14160, 14567, 14574}, {14172, 14579, 14596}, {14194, 14601, 14610}, {14125, 14614, 14614}, {14211, 14618, 14659}, {2011, 14663, 14663}, {14264, 14667, 14680}, {9951, 14687, 14691}, {12863, 14696, 14698}, {7980, 14702, 14703}, {14357, 14707, 14708}, {12266, 14714, 14715}, {10772, 14723, 14729}, {12806, 14733, 14733}, {2583, 14737, 14741}, {14006, 14745, 14745}, {12945, 14749, 14752}, {8679, 14756, 14758}, {12184, 14762, 14763}, {14423, 14767, 14773}, {14054, 14777, 14779}, {10411, 14785, 14789}, {11310, 14794, 14795}, {6455, 14799, 14800}, {5418, 14804, 14804}, {13821, 14808, 14808}, {11905, 14812, 14814}, {13502, 14818, 14819}, {11761, 14823, 14829}, {14745, 14833, 14833}, {14070, 14837, 14843}, {8173, 14850, 14850}, {2999, 14854, 14856}, {9201, 14860, 14867}, {14807, 14871, 14872}, {14812, 14878, 14881}, {13814, 14885, 14887}, {12644, 14891, 14892}, {14295, 14898, 14898}, {14457, 14902, 14902}, {14331, 14906, 14907}, {13170, 14911, 14911}, {14352, 14915, 14916}, {12649, 14920, 14921}, {12399, 14925, 14925}, {13349, 14929, 14929}, {13207, 14934, 14935}, {14372, 14939, 14941}, {14498, 14945, 14945}, {13860, 14949, 14955}, {14452, 14960, 14962}, {14792, 14970, 14970}, {14720, 14975, 14975}, {13858, 14984, 14984}, {5733, 14989, 14991}, {14982, 14995, 14995}, {14524, 14999, 15000}, {2347, 15004, 15004}, {4612, 15009, 15009}, {3225, 15013, 15013}, {12320, 15017, 15018}, {14975, 15022, 15022}, {13416, 15026, 15028}, {8140, 15034, 15034}, {15016, 15040, 15042}, {14299, 15046, 15051}, {14901, 15055, 15056}, {14933, 15060, 15061}, {14960, 15066, 15066}, {14999, 15070, 15071}, {14461, 15075, 15080}, {14666, 15084, 15084}, {14474, 15088, 15134}, {15055, 15138, 15138}, {13046, 15142, 15146}, {14536, 15150, 15176}, {14567, 15181, 15181}, {12725, 15185, 15185}, {13346, 15189, 15189}, {13268, 15193, 15197}, {5568, 15203, 15203}, {15192, 15207, 15207}, {15075, 15211, 15216}, {15207, 15220, 15220}, {13941, 15224, 15224}, {13091, 15228, 15230}, {13623, 15234, 15235}, {13362, 15239, 15243}, {10066, 15247, 15252}, {6452, 15257, 15257}, {14837, 15261, 15267}, {13576, 15271, 15281}, {12874, 15285, 15304}, {15181, 15309, 15309}, {14164, 15313, 15316}, {14579, 15321, 15326}, {12090, 15330, 15339}, {14601, 15344, 15346}, {15084, 15350, 15350}, {12523, 15354, 15357}, {14618, 15361, 15361}, {12788, 15365, 15365}, {6032, 15369, 15369}, {12127, 15373, 15378}, {4703, 15382, 15382}, {12140, 15386, 15387}, {4602, 15392, 15392}, {12856, 15396, 15398}, {13990, 15403, 15406}, {13213, 15412, 15416}, {13979, 15420, 15420}, {14300, 15424, 15426}, {10617, 15430, 15430}, {10094, 15435, 15435}, {12413, 15439, 15440}, {10900, 15447, 15450}, {10908, 15455, 15455}, {15220, 15459, 15459}, {14911, 15463, 15464}, {15026, 15468, 15470}, {14696, 15478, 15480}, {12414, 15484, 15484}, {14215, 15488, 15491}, {13009, 15496, 15508}, {15424, 15512, 15514}, {11334, 15518, 15519}, {11280, 15523, 15524}, {11345, 15528, 15529}, {15459, 15533, 15533}, {14243, 15537, 15539}, {14818, 15543, 15544}, {15533, 15548, 15548}, {14230, 15552, 15554}, {14832, 15561, 15562}, {9787, 15566, 15567}, {15443, 15573, 15575}, {13845, 15579, 15584}, {15430, 15588, 15588}, {15561, 15593, 15593}, {14453, 15601, 15608}, {14870, 15613, 15615}, {12275, 15619, 15619}, {14613, 15623, 15624}, {10596, 15628, 15630}, {1940, 15634, 15634}, {9773, 15638, 15638}, {2665, 15642, 15642}, {13638, 15646, 15646}, {6861, 15650, 15650}, {12781, 15654, 15657}, {15088, 15661, 15665}, {11712, 15669, 15669}, {5534, 15673, 15674}, {12864, 15678, 15684}, {15547, 15688, 15689}, {15365, 15693, 15693}, {7973, 15697, 15698}, {13144, 15702, 15710}, {15548, 15714, 15714}, {14906, 15718, 15719}, {15444, 15723, 15723}, {11456, 15727, 15729}, {12632, 15733, 15734}, {13602, 15738, 15738}, {8932, 15746, 15746}, {15598, 15752, 15753}, {14257, 15757, 15758}, {8379, 15762, 15763}, {10531, 15767, 15767}, {8403, 15771, 15775}, {10432, 15779, 15784}, {14285, 15791, 15794}, {3086, 15800, 15803}, {14925, 15807, 15807}, {14934, 15812, 15812}, {15065, 15816, 15817}, {15737, 15821, 15821}, {15210, 15825, 15831}, {15350, 15835, 15835}, {15661, 15839, 15843}, {15223, 15847, 15848}, {10450, 15855, 15855}, {10501, 15860, 15870}, {10515, 15879, 15879}, {12621, 15884, 15884}, {15593, 15890, 15890}, {15021, 15894, 15894}, {15512, 15898, 15900}, {14274, 15904, 15905}, {15566, 15909, 15909}, {3785, 15913, 15913}, {14995, 15917, 15917}, {15565, 15921, 15921}, {14762, 15925, 15926}, {14016, 15933, 15940}, {10264, 15948, 15948}, {15944, 15952, 15953}, {14847, 15962, 15966}, {15321, 15973, 15975}, {15917, 15979, 15980}, {8141, 15984, 15984}, {15714, 15988, 15988}, {15004, 15992, 16018}, {5180, 16023, 16024}, {15017, 16028, 16029}, {15046, 16033, 16036}, {14499, 16040, 16061}, {15987, 16065, 16066}, {15354, 16070, 16073}, {15628, 16077, 16081}, {13235, 16085, 16088}, {15835, 16093, 16093}, {13247, 16097, 16107}, {15929, 16112, 16112}, {7992, 16118, 16118}, {15988, 16122, 16122}, {15811, 16126, 16133}, {5185, 16137, 16137}, {6056, 16149, 16156}, {15723, 16160, 16160}, {13435, 16167, 16167}, {15692, 16173, 16175}, {1346, 16182, 16183}, {15641, 16187, 16187}, {13157, 16192, 16192}, {12813, 16197, 16197}, {5216, 16201, 16202}, {16170, 16206, 16206}, {15224, 16210, 16211}, {12979, 16215, 16215}, {13342, 16230, 16230}, {15070, 16236, 16237}, {16070, 16241, 16244}, {15361, 16248, 16248}, {15488, 16252, 16256}, {15184, 16265, 16273}, {10860, 16277, 16278}, {8780, 16286, 16287}, {15271, 16291, 16293}, {16206, 16297, 16297}, {14529, 16301, 16304}, {16248, 16308, 16308}, {13716, 16312, 16322}, {16252, 16326, 16330}, {13874, 16334, 16334}, {12773, 16338, 16349}, {14929, 16353, 16353}, {15697, 16361, 16362}, {13531, 16366, 16368}, {14833, 16373, 16373}, {15904, 16377, 16378}, {16173, 16386, 16388}, {13582, 16392, 16393}, {9488, 16399, 16399}, {15468, 16403, 16404}, {13905, 16409, 16411}, {3784, 16415, 16416}, {16297, 16420, 16420}, {16210, 16424, 16426}, {12936, 16430, 16430}, {8508, 16435, 16438}, {9602, 16443, 16446}, {1317, 16450, 16451}, {4739, 16456, 16461}, }
bsd-3-clause
Airblader/i3-original
travis/check-spelling.pl
1897
#!/usr/bin/env perl # vim:ts=4:sw=4:expandtab # # © 2016 Michael Stapelberg # # Checks for spelling errors in binaries and manpages (to be run by continuous # integration to point out spelling errors before accepting contributions). use strict; use warnings; use v5.10; use autodie; use lib 'testcases/lib'; use i3test::Util qw(slurp); use Lintian::Spelling qw(check_spelling); # Lintian complains if we don’t set a vendor. use Lintian::Data; use Lintian::Profile; my $profile = Lintian::Profile->new; $profile->load('debian', ['/usr/share/lintian']); Lintian::Data->set_vendor($profile); my $exitcode = 0; # Whitelist for spelling errors in manpages, in case the spell checker has # false-positives. my $binary_spelling_exceptions = { #'exmaple' => 1, # Example for how to add entries to this whitelist. 'betwen' => 1, # asan_flags.inc contains this spelling error. 'dissassemble' => 1, # https://reviews.llvm.org/D93902 }; my @binaries = qw( build/i3 build/i3-config-wizard build/i3-dump-log build/i3-input build/i3-msg build/i3-nagbar build/i3bar ); for my $binary (@binaries) { check_spelling(slurp($binary), $binary_spelling_exceptions, sub { my ($current, $fixed) = @_; say STDERR qq|Binary "$binary" contains a spelling error: "$current" should be "$fixed"|; $exitcode = 1; }); } # Whitelist for spelling errors in manpages, in case the spell checker has # false-positives. my $manpage_spelling_exceptions = { }; for my $name (glob('build/man/*.1')) { for my $line (split(/\n/, slurp($name))) { next if $line =~ /^\.\\\"/o; check_spelling($line, $manpage_spelling_exceptions, sub { my ($current, $fixed) = @_; say STDERR qq|Manpage "$name" contains a spelling error: "$current" should be "$fixed"|; $exitcode = 1; }); } } exit $exitcode;
bsd-3-clause
DavidGriffith/tme
machine/sun2/sun2-mmu.c
27548
/* $Id: sun2-mmu.c,v 1.14 2009/08/30 14:39:47 fredette Exp $ */ /* machine/sun2/sun2-mmu.c - implementation of Sun 2 MMU emulation: */ /* * Copyright (c) 2003 Matt Fredette * All rights reserved. * * 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. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Matt Fredette. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <tme/common.h> _TME_RCSID("$Id: sun2-mmu.c,v 1.14 2009/08/30 14:39:47 fredette Exp $"); /* includes: */ #include "sun2-impl.h" /* macros: */ /* real PTE entry bits: */ #define TME_SUN2_PTE_VALID 0x80000000 #define TME_SUN2_PTE_PROT 0x7C000000 #define TME_SUN2_PTE_FOD 0x02000000 #define TME_SUN2_PTE_PGTYPE 0x00C00000 #define TME_SUN2_PTE_PGTYPE_MASK 0x00000003 #define TME_SUN2_PTE_REF 0x00200000 #define TME_SUN2_PTE_MOD 0x00100000 #define TME_SUN2_PTE_PGFRAME 0x00000FFF /* real PTE page types: */ #define TME_SUN2_PGTYPE_OBMEM (0) #define TME_SUN2_PGTYPE_OBIO (1) #define TME_SUN2_PGTYPE_MBMEM (2) #define TME_SUN2_PGTYPE_VME0 (2) #define TME_SUN2_PGTYPE_MBIO (3) #define TME_SUN2_PGTYPE_VME8 (3) /* real bus error register bits: */ #define TME_SUN2_BUSERR_PARERR_L TME_BIT(0) /* parity error, lower byte */ #define TME_SUN2_BUSERR_PARERR_U TME_BIT(1) /* parity error, upper byte */ #define TME_SUN2_BUSERR_TIMEOUT TME_BIT(2) /* bus access timed out */ #define TME_SUN2_BUSERR_PROTERR TME_BIT(3) /* protection error */ #define TME_SUN2_BUSERR_VMEBUSERR TME_BIT(6) /* bus error signaled on VMEbus */ #define TME_SUN2_BUSERR_VALID TME_BIT(7) /* page map was valid */ /* real context count: */ #define TME_SUN2_CONTEXT_COUNT (8) /* this logs a bus error: */ #ifndef TME_NO_LOG static void _tme_sun2_bus_fault_log(struct tme_sun2 *sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle) { tme_bus_addr32_t virtual_address; struct tme_sun_mmu_pte pte; tme_uint32_t pte_sun2; const char *bus_name; tme_bus_addr32_t physical_address; int rc; /* this silences gcc -Wuninitialized: */ bus_name = NULL; /* recover the virtual address used: */ virtual_address = cycle->tme_bus_cycle_address - tlb->tme_bus_tlb_addr_offset; /* look up the PTE involved. since this is a real bus error, and not a protection violation or page not present bus error, we assume the system context: */ rc = tme_sun_mmu_pte_get(sun2->tme_sun2_mmu, sun2->tme_sun2_context_system, virtual_address, &pte); assert(rc == TME_OK); pte_sun2 = pte.tme_sun_mmu_pte_raw; /* form the physical address and get the bus name: */ physical_address = (((pte_sun2 & TME_SUN2_PTE_PGFRAME) << TME_SUN2_PAGE_SIZE_LOG2) | (virtual_address & (TME_SUN2_PAGE_SIZE - 1))); switch ((pte_sun2 & TME_SUN2_PTE_PGTYPE) / (TME_SUN2_PTE_PGTYPE / TME_SUN2_PTE_PGTYPE_MASK)) { case TME_SUN2_PGTYPE_OBMEM: bus_name = "obmem"; break; case TME_SUN2_PGTYPE_OBIO: bus_name = "obio"; break; case TME_SUN2_PGTYPE_MBMEM: if (sun2->tme_sun2_has_vme) { bus_name = "VME"; } else { bus_name = "mbmem"; } break; case TME_SUN2_PGTYPE_MBIO: if (sun2->tme_sun2_has_vme) { bus_name = "VME"; physical_address |= 0x800000; } else { bus_name = "mbio"; } break; } /* log this bus error: */ tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("%s bus error, physical 0x%08x, virtual 0x%08x, buserr = 0x%02x"), bus_name, physical_address, virtual_address, sun2->tme_sun2_buserr)); } #else /* TME_NO_LOG */ #define _tme_sun2_bus_fault_log(a, b, c) do { } while (/* CONSTCOND */ 0) #endif /* TME_NO_LOG */ /* our general bus fault handler: */ static int _tme_sun2_bus_fault_handler(struct tme_sun2 *sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle, int rc) { tme_uint16_t buserr; /* dispatch on our fault code: */ switch (rc) { /* bus address nonexistent: */ case ENOENT: buserr = TME_SUN2_BUSERR_VALID | TME_SUN2_BUSERR_TIMEOUT; break; /* anything else is just a fault: */ default: buserr = TME_SUN2_BUSERR_VALID; break; } /* set the bus error register: */ sun2->tme_sun2_buserr = buserr; /* log the fault: */ _tme_sun2_bus_fault_log(sun2, tlb, cycle); return (rc); } /* our obio bus fault handler: */ static int _tme_sun2_obio_fault_handler(void *_sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle, int rc) { tme_uint8_t all_bits_one[sizeof(tme_uint16_t)]; /* the sun2 obio bus doesn't generate bus errors, it just reads all-bits-one: */ memset(all_bits_one, 0xff, sizeof(all_bits_one)); tme_bus_cycle_xfer_memory(cycle, &all_bits_one[0] - cycle->tme_bus_cycle_address, cycle->tme_bus_cycle_address + sizeof(all_bits_one)); return (TME_OK); } /* our obmem bus fault handler: */ static int _tme_sun2_obmem_fault_handler(void *_sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle, int rc) { tme_uint8_t all_bits_one[sizeof(tme_uint16_t)]; /* the sun2 obmem bus apparently doesn't generate bus errors below 0x700000, and instead just reads all-bits-one: */ if (cycle->tme_bus_cycle_address < 0x700000) { memset(all_bits_one, 0xff, sizeof(all_bits_one)); tme_bus_cycle_xfer_memory(cycle, &all_bits_one[0] - cycle->tme_bus_cycle_address, cycle->tme_bus_cycle_address + sizeof(all_bits_one)); return (TME_OK); } /* call the common bus fault handler: */ return (_tme_sun2_bus_fault_handler((struct tme_sun2 *) _sun2, tlb, cycle, rc)); } /* our Multibus fault handler: */ static int _tme_sun2_multibus_fault_handler(void *_sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle, int rc) { /* call the common bus fault handler: */ return (_tme_sun2_bus_fault_handler((struct tme_sun2 *) _sun2, tlb, cycle, rc)); } /* our VMEbus fault handler: */ static int _tme_sun2_vmebus_fault_handler(void *_sun2, struct tme_bus_tlb *tlb, struct tme_bus_cycle *cycle, int rc) { struct tme_sun2 *sun2; /* recover our sun2: */ sun2 = (struct tme_sun2 *) _sun2; /* call the common bus fault handler: */ rc = _tme_sun2_bus_fault_handler((struct tme_sun2 *) _sun2, tlb, cycle, rc); /* this bus fault happened on the VMEbus: */ sun2->tme_sun2_buserr |= TME_SUN2_BUSERR_VMEBUSERR; /* return the fault: */ return (rc); } /* our page-invalid cycle handler: */ static int _tme_sun2_mmu_invalid(void *_sun2, struct tme_bus_cycle *cycle) { struct tme_sun2 *sun2; /* recover our sun2: */ sun2 = (struct tme_sun2 *) _sun2; /* log this bus error: */ tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("page invalid bus error"))); /* set the bus error register: */ sun2->tme_sun2_buserr = TME_SUN2_BUSERR_PROTERR; /* return the fault: */ return (EFAULT); } /* our protection error cycle handler: */ static int _tme_sun2_mmu_proterr(void *_sun2, struct tme_bus_cycle *cycle) { struct tme_sun2 *sun2; /* recover our sun2: */ sun2 = (struct tme_sun2 *) _sun2; /* log this bus error: */ tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("page protection bus error"))); /* set the bus error register: */ sun2->tme_sun2_buserr = TME_SUN2_BUSERR_VALID | TME_SUN2_BUSERR_PROTERR; /* return the fault: */ return (EFAULT); } /* our m68k TLB filler: */ int _tme_sun2_m68k_tlb_fill(struct tme_m68k_bus_connection *conn_m68k, struct tme_m68k_tlb *tlb_m68k, unsigned int function_code, tme_uint32_t address, unsigned int cycles) { struct tme_sun2 *sun2; struct tme_bus_tlb *tlb; unsigned int function_codes_mask; struct tme_bus_tlb tlb_mapping; tme_uint32_t context; tme_uint32_t access; unsigned short tlb_flags; /* recover our sun2: */ sun2 = (struct tme_sun2 *) conn_m68k->tme_m68k_bus_connection.tme_bus_connection.tme_connection_element->tme_element_private; /* get the generic bus TLB: */ tlb = &tlb_m68k->tme_m68k_tlb_bus_tlb; /* if this is function code three, we handle this ourselves: */ if (function_code == TME_M68K_FC_3) { /* initialize the TLB entry: */ tme_bus_tlb_initialize(tlb); /* we cover the entire address space: */ tlb->tme_bus_tlb_addr_first = 0; tlb->tme_bus_tlb_addr_last = 0 - (tme_bus_addr32_t) 1; /* we allow reading and writing: */ tlb->tme_bus_tlb_cycles_ok = TME_BUS_CYCLE_READ | TME_BUS_CYCLE_WRITE; /* our bus cycle handler: */ tlb->tme_bus_tlb_cycle_private = sun2; tlb->tme_bus_tlb_cycle = _tme_sun2_control_cycle_handler; /* this is good for function code three only: */ tlb_m68k->tme_m68k_tlb_function_codes_mask = TME_BIT(TME_M68K_FC_3); /* done: */ return (TME_OK); } /* this must be or a user or supervisor program or data function code: */ assert(function_code == TME_M68K_FC_UD || function_code == TME_M68K_FC_UP || function_code == TME_M68K_FC_SD || function_code == TME_M68K_FC_SP); /* assume that if this TLB entry ends up good for the supervisor, it's good for the supervisor program function code: */ function_codes_mask = TME_BIT(TME_M68K_FC_SP); /* if we're in the boot state: */ if (__tme_predict_false((sun2->tme_sun2_enable & TME_SUN2_ENA_NOTBOOT) == 0)) { /* if this is the supervisor program function code: */ if (function_code == TME_M68K_FC_SP) { /* fill this TLB entry directly from the obmem bus: */ (*sun2->tme_sun2_obmem->tme_bus_tlb_fill) (sun2->tme_sun2_obmem, tlb, TME_SUN2_PROM_BASE | (address & (TME_SUN2_PROM_SIZE - 1)), cycles); /* create the mapping TLB entry: */ tlb_mapping.tme_bus_tlb_addr_first = address & (((tme_bus_addr32_t) 0) - TME_SUN2_PROM_SIZE); tlb_mapping.tme_bus_tlb_addr_last = address | (TME_SUN2_PROM_SIZE - 1); tlb_mapping.tme_bus_tlb_cycles_ok = TME_BUS_CYCLE_READ; /* map the filled TLB entry: */ tme_bus_tlb_map(tlb, TME_SUN2_PROM_BASE | (address & (TME_SUN2_PROM_SIZE - 1)), &tlb_mapping, address); /* this is good for the supervisor program function code only: */ tlb_m68k->tme_m68k_tlb_function_codes_mask = TME_BIT(TME_M68K_FC_SP); /* done: */ return(TME_OK); } /* if this TLB entry ends up good for the supervisor, it's not good for the supervisor program function code: */ function_codes_mask = 0; } /* start the access: */ access = ((cycles & TME_BUS_CYCLE_WRITE) ? TME_SUN_MMU_PTE_PROT_RW : TME_SUN_MMU_PTE_PROT_RO); /* if this is a user program or data function code: */ if (function_code == TME_M68K_FC_UD || function_code == TME_M68K_FC_UP) { context = sun2->tme_sun2_context_user; access = TME_SUN_MMU_PTE_PROT_USER(access); function_codes_mask = (TME_BIT(TME_M68K_FC_UD) + TME_BIT(TME_M68K_FC_UP)); } /* otherwise, this is a supervisor program or data function code: */ else { context = sun2->tme_sun2_context_system; access = TME_SUN_MMU_PTE_PROT_SYSTEM(access); function_codes_mask += TME_BIT(TME_M68K_FC_SD); } /* fill this TLB entry from the MMU: */ tlb_flags = tme_sun_mmu_tlb_fill(sun2->tme_sun2_mmu, tlb, context, address, access); /* TLB entries are good only for the program and data function codes for the user or supervisor, but never both, because the two types of accesses go through different contexts: */ tlb_m68k->tme_m68k_tlb_function_codes_mask = function_codes_mask; return (TME_OK); } /* our bus TLB filler: */ int _tme_sun2_bus_tlb_fill(struct tme_bus_connection *conn_bus, struct tme_bus_tlb *tlb, tme_bus_addr_t address_wider, unsigned int cycles) { struct tme_sun2 *sun2; tme_bus_addr32_t address; struct tme_sun2_bus_connection *conn_sun2; tme_uint32_t base, size; struct tme_bus_tlb tlb_bus; /* recover our sun2: */ sun2 = (struct tme_sun2 *) conn_bus->tme_bus_connection.tme_connection_element->tme_element_private; /* get the normal-width address: */ address = address_wider; assert (address == address_wider); /* recover the sun2 internal mainbus connection: */ conn_sun2 = (struct tme_sun2_bus_connection *) conn_bus; /* turn the bus address into a DVMA address: */ switch (conn_sun2->tme_sun2_bus_connection_which) { /* obio devices can actually see the whole address space: */ case TME_SUN2_BUS_OBIO: base = 0x000000; size = 0x1000000; break; case TME_SUN2_BUS_MBMEM: base = 0xf00000; size = TME_SUN2_DVMA_SIZE_MBMEM; break; case TME_SUN2_BUS_VME: base = 0xf00000; size = TME_SUN2_DVMA_SIZE_VME; break; default: abort(); } assert (!(address & base) && (address < size)); /* fill this TLB entry from the MMU: */ tme_sun_mmu_tlb_fill(sun2->tme_sun2_mmu, tlb, sun2->tme_sun2_context_system, address | base, ((cycles & TME_BUS_CYCLE_WRITE) ? TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RW) : TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RO))); /* create the mapping TLB entry. we do this even if base == 0, because the TLB entry as currently filled may cover more address space than DVMA space on this machine is supposed to cover: */ tlb_bus.tme_bus_tlb_addr_first = 0; tlb_bus.tme_bus_tlb_addr_last = size - 1; tlb_bus.tme_bus_tlb_cycles_ok = (TME_BUS_CYCLE_READ | TME_BUS_CYCLE_WRITE); /* map the filled TLB entry: */ tme_bus_tlb_map(tlb, address | base, &tlb_bus, address); return (TME_OK); } /* our post-MMU TLB filler: */ static int _tme_sun2_tlb_fill_mmu(void *_sun2, struct tme_bus_tlb *tlb, struct tme_sun_mmu_pte *pte, tme_uint32_t *_address, unsigned int cycles) { struct tme_sun2 *sun2; tme_uint32_t address; unsigned int bus_type; struct tme_bus_connection *conn_bus; tme_bus_fault_handler bus_fault_handler; int rc; /* recover our sun2: */ sun2 = (struct tme_sun2 *) _sun2; /* get the physical page frame and bus type: */ address = ((pte->tme_sun_mmu_pte_raw & TME_SUN2_PTE_PGFRAME) << TME_SUN2_PAGE_SIZE_LOG2); bus_type = (pte->tme_sun_mmu_pte_raw & TME_SUN2_PTE_PGTYPE) / (TME_SUN2_PTE_PGTYPE / TME_SUN2_PTE_PGTYPE_MASK); /* any mapping of the *first* page of obio space means the PROM. the virtual page frame is actually used to form the physical address: */ if (address == 0 && bus_type == TME_SUN2_PGTYPE_OBIO) { address = TME_SUN2_PROM_BASE | (*_address & ((TME_SUN2_PROM_SIZE - 1) & ~(TME_SUN2_PAGE_SIZE - 1))); bus_type = TME_SUN2_PGTYPE_OBMEM; } /* add in the page offset to finish the address: */ address |= *_address & (TME_SUN2_PAGE_SIZE - 1); *_address = address; /* if this is obio: */ if (bus_type == TME_SUN2_PGTYPE_OBIO) { conn_bus = sun2->tme_sun2_obio; bus_fault_handler = _tme_sun2_obio_fault_handler; } /* if this is obmem: */ else if (bus_type == TME_SUN2_PGTYPE_OBMEM) { conn_bus = sun2->tme_sun2_obmem; bus_fault_handler = _tme_sun2_obmem_fault_handler; } /* if this is the VME bus: */ else if (sun2->tme_sun2_has_vme) { if (bus_type == TME_SUN2_PGTYPE_VME8) { address |= 0x800000; } else { assert(bus_type == TME_SUN2_PGTYPE_VME0); } bus_fault_handler = _tme_sun2_vmebus_fault_handler; /* TBD: */ abort(); } /* if this is mbmem: */ else if (bus_type == TME_SUN2_PGTYPE_MBMEM) { conn_bus = sun2->tme_sun2_mbmem; bus_fault_handler = _tme_sun2_multibus_fault_handler; } /* otherwise, this is mbio: */ else { assert(bus_type == TME_SUN2_PGTYPE_MBIO); conn_bus = sun2->tme_sun2_mbio; bus_fault_handler = _tme_sun2_multibus_fault_handler; } /* call the bus TLB filler: */ rc = ((*conn_bus->tme_bus_tlb_fill) (conn_bus, tlb, address, cycles)); /* if the bus TLB filler succeeded, add our bus fault handler: */ if (rc == TME_OK) { TME_BUS_TLB_FAULT_HANDLER(tlb, bus_fault_handler, sun2); } return (rc); } /* this gets a PTE from the MMU: */ int _tme_sun2_mmu_pte_get(struct tme_sun2 *sun2, tme_uint32_t address, tme_uint32_t *_pte_sun2) { struct tme_sun_mmu_pte pte; tme_uint32_t pte_sun2; unsigned int pte_flags; int rc; /* get the PTE from the MMU: */ rc = tme_sun_mmu_pte_get(sun2->tme_sun2_mmu, sun2->tme_sun2_context_user, address, &pte); assert(rc == TME_OK); /* form the Sun-2 PTE: */ pte_sun2 = pte.tme_sun_mmu_pte_raw; pte_flags = pte.tme_sun_mmu_pte_flags; if (pte_flags & TME_SUN_MMU_PTE_REF) { pte_sun2 |= TME_SUN2_PTE_REF; } if (pte_flags & TME_SUN_MMU_PTE_MOD) { pte_sun2 |= TME_SUN2_PTE_MOD; } /* done: */ *_pte_sun2 = pte_sun2; tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("pte_get: PGMAP[%d:0x%08x] -> 0x%08x"), sun2->tme_sun2_context_user, address, pte_sun2)); return (TME_OK); } /* this sets a PTE into the MMU: */ int _tme_sun2_mmu_pte_set(struct tme_sun2 *sun2, tme_uint32_t address, tme_uint32_t pte_sun2) { struct tme_sun_mmu_pte pte; unsigned int pte_flags; #ifndef TME_NO_LOG const char *bus_name; tme_bus_addr32_t physical_address; /* this silences gcc -Wuninitialized: */ bus_name = NULL; /* log this setting: */ physical_address = ((pte_sun2 & TME_SUN2_PTE_PGFRAME) << TME_SUN2_PAGE_SIZE_LOG2); switch ((pte_sun2 & TME_SUN2_PTE_PGTYPE) / (TME_SUN2_PTE_PGTYPE / TME_SUN2_PTE_PGTYPE_MASK)) { case TME_SUN2_PGTYPE_OBMEM: bus_name = "obmem"; break; case TME_SUN2_PGTYPE_OBIO: bus_name = "obio"; break; case TME_SUN2_PGTYPE_MBMEM: if (sun2->tme_sun2_has_vme) { bus_name = "VME"; } else { bus_name = "mbmem"; } break; case TME_SUN2_PGTYPE_MBIO: if (sun2->tme_sun2_has_vme) { bus_name = "VME"; physical_address |= 0x800000; } else { bus_name = "mbio"; } break; } tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("pte_set: PGMAP[%d:0x%08x] <- 0x%08x (%s 0x%08x)"), sun2->tme_sun2_context_user, address, pte_sun2, bus_name, physical_address)); #endif /* !TME_NO_LOG */ pte.tme_sun_mmu_pte_raw = pte_sun2; pte_flags = 0; if (pte_sun2 & TME_SUN2_PTE_MOD) { pte_flags |= TME_SUN_MMU_PTE_MOD; } if (pte_sun2 & TME_SUN2_PTE_REF) { pte_flags |= TME_SUN_MMU_PTE_REF; } switch (pte_sun2 & TME_SUN2_PTE_PROT) { /* with this protection, the system can read and write, and the user gets a protection error: */ case 0x70000000: case 0x74000000: case 0x60000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RW) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_ERROR)); break; /* with this protection, the system gets a protection error, and the user gets a protection error: */ case 0x30000000: case 0x20000000: case 0x10000000: case 0x00000000: case 0x04000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_ERROR) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_ERROR)); break; /* with this protection, the system can read and write, and the user can read and write: */ case 0x7C000000: case 0x6C000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RW) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RW)); break; /* with this protection, the system can read and write, and the user can read: */ case 0x78000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RW) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RO)); break; /* with this protection, the system can read, and the user can read: */ case 0x58000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RO) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RO)); break; /* with this protection, the system can read, and the user can read and write: */ case 0x5C000000: case 0x4C000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RO) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RW)); break; /* with this protection, the system can read, and the user gets a protection error: */ case 0x50000000: case 0x40000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_RO) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_ERROR)); break; /* with this protection, the system gets a protection error, and the user can read and write: */ case 0x3c000000: case 0x0c000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_ERROR) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RW)); break; /* with this protection, the system gets a protection error, and the user can read: */ case 0x08000000: pte_flags |= (TME_SUN_MMU_PTE_PROT_SYSTEM(TME_SUN_MMU_PTE_PROT_ERROR) | TME_SUN_MMU_PTE_PROT_USER(TME_SUN_MMU_PTE_PROT_RO)); break; default: abort(); } if (pte_sun2 & TME_SUN2_PTE_VALID) { pte_flags |= TME_SUN_MMU_PTE_VALID; } pte.tme_sun_mmu_pte_flags = pte_flags; return (tme_sun_mmu_pte_set(sun2->tme_sun2_mmu, sun2->tme_sun2_context_user, address, &pte)); } /* this is called when the system context register is set: */ void _tme_sun2_mmu_context_system_set(struct tme_sun2 *sun2) { /* system context register changes are assumed to be rare. if they were frequent, we'd have to allocate 64 TLB sets for each TLB user - one for each possible combination of user context and system context. instead, when the system context register changes, we simply invalidate all TLB entries everywhere: */ tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("system context now #%d"), sun2->tme_sun2_context_system)); tme_sun_mmu_tlbs_invalidate(sun2->tme_sun2_mmu); } /* this is called when the user context register is set: */ void _tme_sun2_mmu_context_user_set(struct tme_sun2 *sun2) { tme_bus_context_t context_base; /* NB that even though user and supervisor references use the two different context registers simultaneously, TLB entries for one are never usable by the other. because of this, and because we assume that the system context register rarely changes, we choose not to factor the system context into the context seen by the m68k: */ /* there are sixteen total contexts. contexts zero through seven are the not-boot (normal) contexts. contexts eight through fifteen are the same contexts, but in the boot state. in the boot state, TLB fills for supervisor program references bypass the MMU and are filled to reference the PROM, and data fills are filled as normal using the current context: */ /* in the not-boot (i.e., normal, state): */ if (__tme_predict_true(sun2->tme_sun2_enable & TME_SUN2_ENA_NOTBOOT)) { tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("user context now #%d"), sun2->tme_sun2_context_user)); /* the normal state contexts are numbered from zero: */ context_base = 0; } /* in the boot state: */ else { tme_log(TME_SUN2_LOG_HANDLE(sun2), 1000, TME_OK, (TME_SUN2_LOG_HANDLE(sun2), _("user context now #%d (boot state)"), sun2->tme_sun2_context_user)); /* the boot state contexts are numbered from eight: */ context_base = TME_SUN2_CONTEXT_COUNT; } /* update the m68k bus context register: */ *sun2->tme_sun2_m68k_bus_context = (context_base + sun2->tme_sun2_context_user); /* NB: unlike the sun3, sun2 DVMA TLBS are always filled using the system context, meaning they don't need to be invalidated when the user context changes, so we don't need to call tme_sun_mmu_context_switched() here: */ } /* this adds a new TLB set: */ int _tme_sun2_mmu_tlb_set_add(struct tme_bus_connection *conn_bus_asker, struct tme_bus_tlb_set_info *tlb_set_info) { struct tme_sun2 *sun2; int rc; /* recover our sun2: */ sun2 = (struct tme_sun2 *) conn_bus_asker->tme_bus_connection.tme_connection_element->tme_element_private; /* add the TLB set to the MMU: */ rc = tme_sun_mmu_tlb_set_add(sun2->tme_sun2_mmu, tlb_set_info); assert (rc == TME_OK); /* if this is the TLB set from the m68k: */ if (conn_bus_asker->tme_bus_connection.tme_connection_type == TME_CONNECTION_BUS_M68K) { /* the m68k must expose a bus context register: */ assert (tlb_set_info->tme_bus_tlb_set_info_bus_context != NULL); /* save the pointer to the m68k bus context register, and initialize it: */ sun2->tme_sun2_m68k_bus_context = tlb_set_info->tme_bus_tlb_set_info_bus_context; _tme_sun2_mmu_context_user_set(sun2); /* return the maximum context number. there are eight contexts in the not-boot (normal) state, and each of them has a boot state counterpart: */ tlb_set_info->tme_bus_tlb_set_info_bus_context_max = (TME_SUN2_CONTEXT_COUNT + TME_SUN2_CONTEXT_COUNT - 1); } return (rc); } /* this creates a Sun-2 MMU: */ void _tme_sun2_mmu_new(struct tme_sun2 *sun2) { struct tme_sun_mmu_info mmu_info; memset(&mmu_info, 0, sizeof(mmu_info)); mmu_info.tme_sun_mmu_info_element = sun2->tme_sun2_element; mmu_info.tme_sun_mmu_info_address_bits = 24; mmu_info.tme_sun_mmu_info_pgoffset_bits = TME_SUN2_PAGE_SIZE_LOG2; mmu_info.tme_sun_mmu_info_pteindex_bits = 4; mmu_info.tme_sun_mmu_info_contexts = TME_SUN2_CONTEXT_COUNT; mmu_info.tme_sun_mmu_info_pmegs = 256; mmu_info.tme_sun_mmu_info_tlb_fill_private = sun2; mmu_info.tme_sun_mmu_info_tlb_fill = _tme_sun2_tlb_fill_mmu; mmu_info.tme_sun_mmu_info_proterr_private = sun2; mmu_info.tme_sun_mmu_info_proterr = _tme_sun2_mmu_proterr; mmu_info.tme_sun_mmu_info_invalid_private = sun2; mmu_info.tme_sun_mmu_info_invalid = _tme_sun2_mmu_invalid; sun2->tme_sun2_mmu = tme_sun_mmu_new(&mmu_info); }
bsd-3-clause
bolav/pmd-src-4.2.6-perl
src/net/sourceforge/pmd/jaxen/MatchesFunction.java
1085
package net.sourceforge.pmd.jaxen; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.SimpleFunctionContext; import org.jaxen.XPathFunctionContext; import java.util.List; import java.util.regex.Pattern; import java.util.regex.Matcher; public class MatchesFunction implements Function { public static void registerSelfInSimpleContext() { // see http://jaxen.org/extensions.html ((SimpleFunctionContext) XPathFunctionContext.getInstance()).registerFunction(null, "matches", new MatchesFunction()); } public Object call(Context context, List args) throws FunctionCallException { if (args.isEmpty()) { return Boolean.FALSE; } List attributes = (List) args.get(0); Attribute attr = (Attribute) attributes.get(0); Pattern check = Pattern.compile((String) args.get(1)); Matcher matcher = check.matcher(attr.getValue()); if (matcher.find()) { return context.getNodeSet(); } return Boolean.FALSE; } }
bsd-3-clause
DougBurke/astropy
cextern/wcslib/C/prj.c
191340
/*============================================================================ WCSLIB 5.18 - an implementation of the FITS WCS standard. Copyright (C) 1995-2018, Mark Calabretta This file is part of WCSLIB. WCSLIB is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WCSLIB 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with WCSLIB. If not, see http://www.gnu.org/licenses. Direct correspondence concerning WCSLIB to [email protected] Author: Mark Calabretta, Australia Telescope National Facility, CSIRO. http://www.atnf.csiro.au/people/Mark.Calabretta $Id: prj.c,v 5.18 2018/01/10 08:32:14 mcalabre Exp $ *===========================================================================*/ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wcserr.h" #include "wcsmath.h" #include "wcsprintf.h" #include "wcstrig.h" #include "wcsutil.h" #include "prj.h" /* Projection categories. */ const int ZENITHAL = 1; const int CYLINDRICAL = 2; const int PSEUDOCYLINDRICAL = 3; const int CONVENTIONAL = 4; const int CONIC = 5; const int POLYCONIC = 6; const int QUADCUBE = 7; const int HEALPIX = 8; const char prj_categories[9][32] = {"undefined", "zenithal", "cylindrical", "pseudocylindrical", "conventional", "conic", "polyconic", "quadcube", "HEALPix"}; /* Projection codes. */ const int prj_ncode = 28; const char prj_codes[28][4] = {"AZP", "SZP", "TAN", "STG", "SIN", "ARC", "ZPN", "ZEA", "AIR", "CYP", "CEA", "CAR", "MER", "COP", "COE", "COD", "COO", "SFL", "PAR", "MOL", "AIT", "BON", "PCO", "TSC", "CSC", "QSC", "HPX", "XPH"}; const int AZP = 101; const int SZP = 102; const int TAN = 103; const int STG = 104; const int SIN = 105; const int ARC = 106; const int ZPN = 107; const int ZEA = 108; const int AIR = 109; const int CYP = 201; const int CEA = 202; const int CAR = 203; const int MER = 204; const int SFL = 301; const int PAR = 302; const int MOL = 303; const int AIT = 401; const int COP = 501; const int COE = 502; const int COD = 503; const int COO = 504; const int BON = 601; const int PCO = 602; const int TSC = 701; const int CSC = 702; const int QSC = 703; const int HPX = 801; const int XPH = 802; /* Map status return value to message. */ const char *prj_errmsg[] = { "Success", "Null prjprm pointer passed", "Invalid projection parameters", "One or more of the (x,y) coordinates were invalid", "One or more of the (phi,theta) coordinates were invalid"}; /* Convenience macros for generating common error messages. */ #define PRJERR_BAD_PARAM_SET(function) \ wcserr_set(&(prj->err), PRJERR_BAD_PARAM, function, __FILE__, __LINE__, \ "Invalid parameters for %s projection", prj->name); #define PRJERR_BAD_PIX_SET(function) \ wcserr_set(&(prj->err), PRJERR_BAD_PIX, function, __FILE__, __LINE__, \ "One or more of the (x, y) coordinates were invalid for %s projection", \ prj->name); #define PRJERR_BAD_WORLD_SET(function) \ wcserr_set(&(prj->err), PRJERR_BAD_WORLD, function, __FILE__, __LINE__, \ "One or more of the (lat, lng) coordinates were invalid for " \ "%s projection", prj->name); #define copysign(X, Y) ((Y) < 0.0 ? -fabs(X) : fabs(X)) /*============================================================================ * Generic routines: * * prjini initializes a prjprm struct to default values. * * prjfree frees any memory that may have been allocated to store an error * message in the prjprm struct. * * prjprt prints the contents of a prjprm struct. * * prjbchk performs bounds checking on the native coordinates returned by the * *x2s() routines. * * prjset invokes the specific initialization routine based on the projection * code in the prjprm struct. * * prjx2s invokes the specific deprojection routine based on the pointer-to- * function stored in the prjprm struct. * * prjs2x invokes the specific projection routine based on the pointer-to- * function stored in the prjprm struct. * *---------------------------------------------------------------------------*/ int prjini(prj) struct prjprm *prj; { register int k; if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = 0; strcpy(prj->code, " "); prj->pv[0] = 0.0; prj->pv[1] = UNDEFINED; prj->pv[2] = UNDEFINED; prj->pv[3] = UNDEFINED; for (k = 4; k < PVN; prj->pv[k++] = 0.0); prj->r0 = 0.0; prj->phi0 = UNDEFINED; prj->theta0 = UNDEFINED; prj->bounds = 7; strcpy(prj->name, "undefined"); for (k = 9; k < 40; prj->name[k++] = '\0'); prj->category = 0; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 0; prj->x0 = 0.0; prj->y0 = 0.0; prj->err = 0x0; prj->padding = 0x0; for (k = 0; k < 10; prj->w[k++] = 0.0); prj->m = 0; prj->n = 0; prj->prjx2s = 0x0; prj->prjs2x = 0x0; return 0; } /*--------------------------------------------------------------------------*/ int prjfree(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->err) { free(prj->err); prj->err = 0x0; } return 0; } /*--------------------------------------------------------------------------*/ int prjprt(prj) const struct prjprm *prj; { char hext[32]; int i, n; if (prj == 0x0) return PRJERR_NULL_POINTER; wcsprintf(" flag: %d\n", prj->flag); wcsprintf(" code: \"%s\"\n", prj->code); wcsprintf(" r0: %9f\n", prj->r0); wcsprintf(" pv:"); if (prj->pvrange) { n = (prj->pvrange)%100; if (prj->pvrange/100) { wcsprintf(" (0)"); } else { wcsprintf(" %#- 11.5g", prj->pv[0]); n--; } for (i = 1; i <= n; i++) { if (i%5 == 1) { wcsprintf("\n "); } if (undefined(prj->pv[i])) { wcsprintf(" UNDEFINED "); } else { wcsprintf(" %#- 11.5g", prj->pv[i]); } } wcsprintf("\n"); } else { wcsprintf(" (not used)\n"); } if (undefined(prj->phi0)) { wcsprintf(" phi0: UNDEFINED\n"); } else { wcsprintf(" phi0: %9f\n", prj->phi0); } if (undefined(prj->theta0)) { wcsprintf(" theta0: UNDEFINED\n"); } else { wcsprintf(" theta0: %9f\n", prj->theta0); } wcsprintf(" bounds: %d\n", prj->bounds); wcsprintf("\n"); wcsprintf(" name: \"%s\"\n", prj->name); wcsprintf(" category: %d (%s)\n", prj->category, prj_categories[prj->category]); wcsprintf(" pvrange: %d\n", prj->pvrange); wcsprintf(" simplezen: %d\n", prj->simplezen); wcsprintf(" equiareal: %d\n", prj->equiareal); wcsprintf(" conformal: %d\n", prj->conformal); wcsprintf(" global: %d\n", prj->global); wcsprintf(" divergent: %d\n", prj->divergent); wcsprintf(" x0: %f\n", prj->x0); wcsprintf(" y0: %f\n", prj->y0); WCSPRINTF_PTR(" err: ", prj->err, "\n"); if (prj->err) { wcserr_prt(prj->err, " "); } wcsprintf(" w[]:"); for (i = 0; i < 5; i++) { wcsprintf(" %#- 11.5g", prj->w[i]); } wcsprintf("\n "); for (i = 5; i < 10; i++) { wcsprintf(" %#- 11.5g", prj->w[i]); } wcsprintf("\n"); wcsprintf(" m: %d\n", prj->m); wcsprintf(" n: %d\n", prj->n); wcsprintf(" prjx2s: %s\n", wcsutil_fptr2str((int (*)(void))prj->prjx2s, hext)); wcsprintf(" prjs2x: %s\n", wcsutil_fptr2str((int (*)(void))prj->prjs2x, hext)); return 0; } /*--------------------------------------------------------------------------*/ int prjperr(const struct prjprm *prj, const char *prefix) { if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->err) { wcserr_prt(prj->err, prefix); } return 0; } /*--------------------------------------------------------------------------*/ int prjbchk(tol, nphi, ntheta, spt, phi, theta, stat) double tol; int nphi, ntheta, spt; double phi[], theta[]; int stat[]; { int status = 0; register int iphi, itheta, *statp; register double *phip, *thetap; phip = phi; thetap = theta; statp = stat; for (itheta = 0; itheta < ntheta; itheta++) { for (iphi = 0; iphi < nphi; iphi++, phip += spt, thetap += spt, statp++) { /* Skip values already marked as illegal. */ if (*statp == 0) { if (*phip < -180.0) { if (*phip < -180.0-tol) { *statp = 1; status = 1; } else { *phip = -180.0; } } else if (180.0 < *phip) { if (180.0+tol < *phip) { *statp = 1; status = 1; } else { *phip = 180.0; } } if (*thetap < -90.0) { if (*thetap < -90.0-tol) { *statp = 1; status = 1; } else { *thetap = -90.0; } } else if (90.0 < *thetap) { if (90.0+tol < *thetap) { *statp = 1; status = 1; } else { *thetap = 90.0; } } } } } return status; } /*--------------------------------------------------------------------------*/ int prjset(prj) struct prjprm *prj; { static const char *function = "prjset"; int status; struct wcserr **err; if (prj == 0x0) return PRJERR_NULL_POINTER; err = &(prj->err); /* Invoke the relevant initialization routine. */ prj->code[3] = '\0'; if (strcmp(prj->code, "AZP") == 0) { status = azpset(prj); } else if (strcmp(prj->code, "SZP") == 0) { status = szpset(prj); } else if (strcmp(prj->code, "TAN") == 0) { status = tanset(prj); } else if (strcmp(prj->code, "STG") == 0) { status = stgset(prj); } else if (strcmp(prj->code, "SIN") == 0) { status = sinset(prj); } else if (strcmp(prj->code, "ARC") == 0) { status = arcset(prj); } else if (strcmp(prj->code, "ZPN") == 0) { status = zpnset(prj); } else if (strcmp(prj->code, "ZEA") == 0) { status = zeaset(prj); } else if (strcmp(prj->code, "AIR") == 0) { status = airset(prj); } else if (strcmp(prj->code, "CYP") == 0) { status = cypset(prj); } else if (strcmp(prj->code, "CEA") == 0) { status = ceaset(prj); } else if (strcmp(prj->code, "CAR") == 0) { status = carset(prj); } else if (strcmp(prj->code, "MER") == 0) { status = merset(prj); } else if (strcmp(prj->code, "SFL") == 0) { status = sflset(prj); } else if (strcmp(prj->code, "PAR") == 0) { status = parset(prj); } else if (strcmp(prj->code, "MOL") == 0) { status = molset(prj); } else if (strcmp(prj->code, "AIT") == 0) { status = aitset(prj); } else if (strcmp(prj->code, "COP") == 0) { status = copset(prj); } else if (strcmp(prj->code, "COE") == 0) { status = coeset(prj); } else if (strcmp(prj->code, "COD") == 0) { status = codset(prj); } else if (strcmp(prj->code, "COO") == 0) { status = cooset(prj); } else if (strcmp(prj->code, "BON") == 0) { status = bonset(prj); } else if (strcmp(prj->code, "PCO") == 0) { status = pcoset(prj); } else if (strcmp(prj->code, "TSC") == 0) { status = tscset(prj); } else if (strcmp(prj->code, "CSC") == 0) { status = cscset(prj); } else if (strcmp(prj->code, "QSC") == 0) { status = qscset(prj); } else if (strcmp(prj->code, "HPX") == 0) { status = hpxset(prj); } else if (strcmp(prj->code, "XPH") == 0) { status = xphset(prj); } else { /* Unrecognized projection code. */ status = wcserr_set(WCSERR_SET(PRJERR_BAD_PARAM), "Unrecognized projection code '%s'", prj->code); } return status; } /*--------------------------------------------------------------------------*/ int prjx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int status; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag == 0) { if ((status = prjset(prj))) return status; } return prj->prjx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat); } /*--------------------------------------------------------------------------*/ int prjs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int status; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag == 0) { if ((status = prjset(prj))) return status; } return prj->prjs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat); } /*============================================================================ * Internal helper routine used by the *set() routines - not intended for * outside use. It forces (x,y) = (0,0) at (phi0,theta0). *---------------------------------------------------------------------------*/ int prjoff(prj, phi0, theta0) struct prjprm *prj; const double phi0, theta0; { int stat; double x0, y0; if (prj == 0x0) return PRJERR_NULL_POINTER; prj->x0 = 0.0; prj->y0 = 0.0; if (undefined(prj->phi0) || undefined(prj->theta0)) { /* Set both to the projection-specific default if either undefined. */ prj->phi0 = phi0; prj->theta0 = theta0; } else { if (prj->prjs2x(prj, 1, 1, 1, 1, &(prj->phi0), &(prj->theta0), &x0, &y0, &stat)) { return PRJERR_BAD_PARAM_SET("prjoff"); } prj->x0 = x0; prj->y0 = y0; } return 0; } /*============================================================================ * AZP: zenithal/azimuthal perspective projection. * * Given: * prj->pv[1] Distance parameter, mu in units of r0. * prj->pv[2] Tilt angle, gamma in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag AZP * prj->code "AZP" * prj->x0 Offset in x. * prj->y0 Offset in y. * prj->w[0] r0*(mu+1) * prj->w[1] tan(gamma) * prj->w[2] sec(gamma) * prj->w[3] cos(gamma) * prj->w[4] sin(gamma) * prj->w[5] asin(-1/mu) for |mu| >= 1, -90 otherwise * prj->w[6] mu*cos(gamma) * prj->w[7] 1 if |mu*cos(gamma)| < 1, 0 otherwise * prj->prjx2s Pointer to azpx2s(). * prj->prjs2x Pointer to azps2x(). *===========================================================================*/ int azpset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = AZP; strcpy(prj->code, "AZP"); if (undefined(prj->pv[1])) prj->pv[1] = 0.0; if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "zenithal/azimuthal perspective"); prj->category = ZENITHAL; prj->pvrange = 102; prj->simplezen = prj->pv[2] == 0.0; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = prj->pv[1] <= 1.0; prj->w[0] = prj->r0*(prj->pv[1] + 1.0); if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("azpset"); } prj->w[3] = cosd(prj->pv[2]); if (prj->w[3] == 0.0) { return PRJERR_BAD_PARAM_SET("azpset"); } prj->w[2] = 1.0/prj->w[3]; prj->w[4] = sind(prj->pv[2]); prj->w[1] = prj->w[4] / prj->w[3]; if (fabs(prj->pv[1]) > 1.0) { prj->w[5] = asind(-1.0/prj->pv[1]); } else { prj->w[5] = -90.0; } prj->w[6] = prj->pv[1] * prj->w[3]; prj->w[7] = (fabs(prj->w[6]) < 1.0) ? 1.0 : 0.0; prj->prjx2s = azpx2s; prj->prjs2x = azps2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int azpx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double a, b, q, r, s, t, xj, yj, yc, yc2; const double tol = 1.0e-13; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AZP) { if ((status = azpset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yc = yj*prj->w[3]; yc2 = yc*yc; q = prj->w[0] + yj*prj->w[4]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yc2); if (r == 0.0) { *phip = 0.0; *thetap = 90.0; *(statp++) = 0; } else { *phip = atan2d(xj, -yc); s = r / q; t = s*prj->pv[1]/sqrt(s*s + 1.0); s = atan2d(1.0, s); if (fabs(t) > 1.0) { if (fabs(t) > 1.0+tol) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("azpx2s"); continue; } t = copysign(90.0, t); } else { t = asind(t); } a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; *thetap = (a > b) ? a : b; *(statp++) = 0; } } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("azpx2s"); } return status; } /*--------------------------------------------------------------------------*/ int azps2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double a, b, cosphi, costhe, r, s, sinphi, sinthe, t; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AZP) { if ((status = azpset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { s = prj->w[1]*(*yp); t = (prj->pv[1] + sinthe) + costhe*s; if (t == 0.0) { *xp = 0.0; *yp = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_WORLD_SET("azps2x"); } else { r = prj->w[0]*costhe/t; /* Bounds checking. */ istat = 0; if (prj->bounds&1) { if (*thetap < prj->w[5]) { /* Overlap. */ istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("azps2x"); } else if (prj->w[7] > 0.0) { /* Divergence. */ t = prj->pv[1] / sqrt(1.0 + s*s); if (fabs(t) <= 1.0) { s = atand(-s); t = asind(t); a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; if (*thetap < ((a > b) ? a : b)) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("azps2x"); } } } } *xp = r*(*xp) - prj->x0; *yp = -r*(*yp)*prj->w[2] - prj->y0; *(statp++) = istat; } } } return status; } /*============================================================================ * SZP: slant zenithal perspective projection. * * Given: * prj->pv[1] Distance of the point of projection from the centre of the * generating sphere, mu in units of r0. * prj->pv[2] Native longitude, phi_c, and ... * prj->pv[3] Native latitude, theta_c, on the planewards side of the * intersection of the line through the point of projection * and the centre of the generating sphere, phi_c in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag SZP * prj->code "SZP" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 1/r0 * prj->w[1] xp = -mu*cos(theta_c)*sin(phi_c) * prj->w[2] yp = mu*cos(theta_c)*cos(phi_c) * prj->w[3] zp = mu*sin(theta_c) + 1 * prj->w[4] r0*xp * prj->w[5] r0*yp * prj->w[6] r0*zp * prj->w[7] (zp - 1)^2 * prj->w[8] asin(1-zp) if |1 - zp| < 1, -90 otherwise * prj->prjx2s Pointer to szpx2s(). * prj->prjs2x Pointer to szps2x(). *===========================================================================*/ int szpset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = SZP; strcpy(prj->code, "SZP"); if (undefined(prj->pv[1])) prj->pv[1] = 0.0; if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (undefined(prj->pv[3])) prj->pv[3] = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "slant zenithal perspective"); prj->category = ZENITHAL; prj->pvrange = 103; prj->simplezen = prj->pv[3] == 90.0; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = prj->pv[1] <= 1.0; prj->w[0] = 1.0/prj->r0; prj->w[3] = prj->pv[1] * sind(prj->pv[3]) + 1.0; if (prj->w[3] == 0.0) { return PRJERR_BAD_PARAM_SET("szpset"); } prj->w[1] = -prj->pv[1] * cosd(prj->pv[3]) * sind(prj->pv[2]); prj->w[2] = prj->pv[1] * cosd(prj->pv[3]) * cosd(prj->pv[2]); prj->w[4] = prj->r0 * prj->w[1]; prj->w[5] = prj->r0 * prj->w[2]; prj->w[6] = prj->r0 * prj->w[3]; prj->w[7] = (prj->w[3] - 1.0) * prj->w[3] - 1.0; if (fabs(prj->w[3] - 1.0) < 1.0) { prj->w[8] = asind(1.0 - prj->w[3]); } else { prj->w[8] = -90.0; } prj->prjx2s = szpx2s; prj->prjs2x = szps2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int szpx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double a, b, c, d, r2, sinth1, sinth2, sinthe, t, x1, xr, xy, y1, yr, z; const double tol = 1.0e-13; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SZP) { if ((status = szpset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xr = (*xp + prj->x0)*prj->w[0]; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xr; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yr = (*yp + prj->y0)*prj->w[0]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xr = *phip; r2 = xr*xr + yr*yr; x1 = (xr - prj->w[1])/prj->w[3]; y1 = (yr - prj->w[2])/prj->w[3]; xy = xr*x1 + yr*y1; if (r2 < 1.0e-10) { /* Use small angle formula. */ z = r2/2.0; *thetap = 90.0 - R2D*sqrt(r2/(1.0 + xy)); } else { t = x1*x1 + y1*y1; a = t + 1.0; b = xy - t; c = r2 - xy - xy + t - 1.0; d = b*b - a*c; /* Check for a solution. */ if (d < 0.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("szpx2s"); continue; } d = sqrt(d); /* Choose solution closest to pole. */ sinth1 = (-b + d)/a; sinth2 = (-b - d)/a; sinthe = (sinth1 > sinth2) ? sinth1 : sinth2; if (sinthe > 1.0) { if (sinthe-1.0 < tol) { sinthe = 1.0; } else { sinthe = (sinth1 < sinth2) ? sinth1 : sinth2; } } if (sinthe < -1.0) { if (sinthe+1.0 > -tol) { sinthe = -1.0; } } if (sinthe > 1.0 || sinthe < -1.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("szpx2s"); continue; } *thetap = asind(sinthe); z = 1.0 - sinthe; } *phip = atan2d(xr - x1*z, -(yr - y1*z)); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("szpx2s"); } return status; } /*--------------------------------------------------------------------------*/ int szps2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double a, b, cosphi, r, s, sinphi, t, u, v; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SZP) { if ((status = szpset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { s = 1.0 - sind(*thetap); t = prj->w[3] - s; if (t == 0.0) { for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = 0.0; *yp = 0.0; *(statp++) = 1; } if (!status) status = PRJERR_BAD_WORLD_SET("szps2x"); } else { r = prj->w[6]*cosd(*thetap)/t; u = prj->w[4]*s/t + prj->x0; v = prj->w[5]*s/t + prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { /* Bounds checking. */ istat = 0; if (prj->bounds&1) { if (*thetap < prj->w[8]) { /* Divergence. */ istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("szps2x"); } else if (fabs(prj->pv[1]) > 1.0) { /* Overlap. */ s = prj->w[1]*(*xp) - prj->w[2]*(*yp); t = 1.0/sqrt(prj->w[7] + s*s); if (fabs(t) <= 1.0) { s = atan2d(s, prj->w[3] - 1.0); t = asind(t); a = s - t; b = s + t + 180.0; if (a > 90.0) a -= 360.0; if (b > 90.0) b -= 360.0; if (*thetap < ((a > b) ? a : b)) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("szps2x"); } } } } *xp = r*(*xp) - u; *yp = -r*(*yp) - v; *(statp++) = istat; } } } return status; } /*============================================================================ * TAN: gnomonic projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag TAN * prj->code "TAN" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->prjx2s Pointer to tanx2s(). * prj->prjs2x Pointer to tans2x(). *===========================================================================*/ int tanset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = TAN; strcpy(prj->code, "TAN"); if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "gnomonic"); prj->category = ZENITHAL; prj->pvrange = 0; prj->simplezen = 1; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 1; prj->prjx2s = tanx2s; prj->prjs2x = tans2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int tanx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, xj, yj, yj2; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != TAN) { if ((status = tanset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2); if (r == 0.0) { *phip = 0.0; } else { *phip = atan2d(xj, -yj); } *thetap = atan2d(prj->r0, r); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("tanx2s"); } return status; } /*--------------------------------------------------------------------------*/ int tans2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, r, s, sinphi; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != TAN) { if ((status = tanset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { s = sind(*thetap); if (s == 0.0) { for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = 0.0; *yp = 0.0; *(statp++) = 1; } if (!status) status = PRJERR_BAD_WORLD_SET("tans2x"); } else { r = prj->r0*cosd(*thetap)/s; /* Bounds checking. */ istat = 0; if (prj->bounds&1) { if (s < 0.0) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("tans2x"); } } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = istat; } } } return status; } /*============================================================================ * STG: stereographic projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag STG * prj->code "STG" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 2*r0 * prj->w[1] 1/(2*r0) * prj->prjx2s Pointer to stgx2s(). * prj->prjs2x Pointer to stgs2x(). *===========================================================================*/ int stgset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = STG; strcpy(prj->code, "STG"); strcpy(prj->name, "stereographic"); prj->category = ZENITHAL; prj->pvrange = 0; prj->simplezen = 1; prj->equiareal = 0; prj->conformal = 1; prj->global = 0; prj->divergent = 1; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 360.0/PI; prj->w[1] = PI/360.0; } else { prj->w[0] = 2.0*prj->r0; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = stgx2s; prj->prjs2x = stgs2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int stgx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, xj, yj, yj2; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != STG) { if ((status = stgset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2); if (r == 0.0) { *phip = 0.0; } else { *phip = atan2d(xj, -yj); } *thetap = 90.0 - 2.0*atand(r*prj->w[1]); *(statp++) = 0; } } return 0; } /*--------------------------------------------------------------------------*/ int stgs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, r, s, sinphi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != STG) { if ((status = stgset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { s = 1.0 + sind(*thetap); if (s == 0.0) { for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = 0.0; *yp = 0.0; *(statp++) = 1; } if (!status) status = PRJERR_BAD_WORLD_SET("stgs2x"); } else { r = prj->w[0]*cosd(*thetap)/s; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = 0; } } } return status; } /*============================================================================ * SIN: orthographic/synthesis projection. * * Given: * prj->pv[1:2] Obliqueness parameters, xi and eta. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag SIN * prj->code "SIN" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 1/r0 * prj->w[1] xi**2 + eta**2 * prj->w[2] xi**2 + eta**2 + 1 * prj->w[3] xi**2 + eta**2 - 1 * prj->prjx2s Pointer to sinx2s(). * prj->prjs2x Pointer to sins2x(). *===========================================================================*/ int sinset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = SIN; strcpy(prj->code, "SIN"); if (undefined(prj->pv[1])) prj->pv[1] = 0.0; if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "orthographic/synthesis"); prj->category = ZENITHAL; prj->pvrange = 102; prj->simplezen = (prj->pv[1] == 0.0 && prj->pv[2] == 0.0); prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 0; prj->w[0] = 1.0/prj->r0; prj->w[1] = prj->pv[1]*prj->pv[1] + prj->pv[2]*prj->pv[2]; prj->w[2] = prj->w[1] + 1.0; prj->w[3] = prj->w[1] - 1.0; prj->prjx2s = sinx2s; prj->prjs2x = sins2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int sinx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; const double tol = 1.0e-13; double a, b, c, d, eta, r2, sinth1, sinth2, sinthe, x0, xi, x1, xy, y0, y02, y1, z; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SIN) { if ((status = sinset(prj))) return status; } xi = prj->pv[1]; eta = prj->pv[2]; if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { x0 = (*xp + prj->x0)*prj->w[0]; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = x0; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { y0 = (*yp + prj->y0)*prj->w[0]; y02 = y0*y0; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { /* Compute intermediaries. */ x0 = *phip; r2 = x0*x0 + y02; if (prj->w[1] == 0.0) { /* Orthographic projection. */ if (r2 != 0.0) { *phip = atan2d(x0, -y0); } else { *phip = 0.0; } if (r2 < 0.5) { *thetap = acosd(sqrt(r2)); } else if (r2 <= 1.0) { *thetap = asind(sqrt(1.0 - r2)); } else { *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("sinx2s") continue; } } else { /* "Synthesis" projection. */ xy = x0*xi + y0*eta; if (r2 < 1.0e-10) { /* Use small angle formula. */ z = r2/2.0; *thetap = 90.0 - R2D*sqrt(r2/(1.0 + xy)); } else { a = prj->w[2]; b = xy - prj->w[1]; c = r2 - xy - xy + prj->w[3]; d = b*b - a*c; /* Check for a solution. */ if (d < 0.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("sinx2s") continue; } d = sqrt(d); /* Choose solution closest to pole. */ sinth1 = (-b + d)/a; sinth2 = (-b - d)/a; sinthe = (sinth1 > sinth2) ? sinth1 : sinth2; if (sinthe > 1.0) { if (sinthe-1.0 < tol) { sinthe = 1.0; } else { sinthe = (sinth1 < sinth2) ? sinth1 : sinth2; } } if (sinthe < -1.0) { if (sinthe+1.0 > -tol) { sinthe = -1.0; } } if (sinthe > 1.0 || sinthe < -1.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("sinx2s") continue; } *thetap = asind(sinthe); z = 1.0 - sinthe; } x1 = -y0 + eta*z; y1 = x0 - xi*z; if (x1 == 0.0 && y1 == 0.0) { *phip = 0.0; } else { *phip = atan2d(y1,x1); } } *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("sinx2s"); } return status; } /*--------------------------------------------------------------------------*/ int sins2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, costhe, sinphi, r, t, z, z1, z2; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SIN) { if ((status = sinset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { t = (90.0 - fabs(*thetap))*D2R; if (t < 1.0e-5) { if (*thetap > 0.0) { z = t*t/2.0; } else { z = 2.0 - t*t/2.0; } costhe = t; } else { z = 1.0 - sind(*thetap); costhe = cosd(*thetap); } r = prj->r0*costhe; if (prj->w[1] == 0.0) { /* Orthographic projection. */ istat = 0; if (prj->bounds&1) { if (*thetap < 0.0) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("sins2x"); } } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = istat; } } else { /* "Synthesis" projection. */ z *= prj->r0; z1 = prj->pv[1]*z - prj->x0; z2 = prj->pv[2]*z - prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { istat = 0; if (prj->bounds&1) { t = -atand(prj->pv[1]*(*xp) - prj->pv[2]*(*yp)); if (*thetap < t) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("sins2x"); } } *xp = r*(*xp) + z1; *yp = -r*(*yp) + z2; *(statp++) = istat; } } } return status; } /*============================================================================ * ARC: zenithal/azimuthal equidistant projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag ARC * prj->code "ARC" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjx2s Pointer to arcx2s(). * prj->prjs2x Pointer to arcs2x(). *===========================================================================*/ int arcset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = ARC; strcpy(prj->code, "ARC"); strcpy(prj->name, "zenithal/azimuthal equidistant"); prj->category = ZENITHAL; prj->pvrange = 0; prj->simplezen = 1; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = arcx2s; prj->prjs2x = arcs2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int arcx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, xj, yj, yj2; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ARC) { if ((status = arcset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2); if (r == 0.0) { *phip = 0.0; *thetap = 90.0; } else { *phip = atan2d(xj, -yj); *thetap = 90.0 - r*prj->w[1]; } *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("arcx2s"); } return status; } /*--------------------------------------------------------------------------*/ int arcs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, r, sinphi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ARC) { if ((status = arcset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { r = prj->w[0]*(90.0 - *thetap); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = 0; } } return 0; } /*============================================================================ * ZPN: zenithal/azimuthal polynomial projection. * * Given: * prj->pv[] Polynomial coefficients. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag ZPN * prj->code "ZPN" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->n Degree of the polynomial, N. * prj->w[0] Co-latitude of the first point of inflection, radian. * prj->w[1] Radius of the first point of inflection (N > 1), radian. * prj->prjx2s Pointer to zpnx2s(). * prj->prjs2x Pointer to zpns2x(). *===========================================================================*/ int zpnset(prj) struct prjprm *prj; { int j, k, m; double d, d1, d2, r, zd, zd1, zd2; const double tol = 1.0e-13; if (prj == 0x0) return PRJERR_NULL_POINTER; strcpy(prj->code, "ZPN"); prj->flag = ZPN; if (undefined(prj->pv[1])) prj->pv[1] = 0.0; if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (undefined(prj->pv[3])) prj->pv[3] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "zenithal/azimuthal polynomial"); prj->category = ZENITHAL; prj->pvrange = 30; prj->simplezen = 1; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 0; /* Find the highest non-zero coefficient. */ for (k = PVN-1; k >= 0 && prj->pv[k] == 0.0; k--); if (k < 0) { return PRJERR_BAD_PARAM_SET("zpnset"); } prj->n = k; if (k < 2) { /* No point of inflection. */ prj->w[0] = PI; } else { /* Find the point of inflection closest to the pole. */ zd1 = 0.0; d1 = prj->pv[1]; if (d1 <= 0.0) { return PRJERR_BAD_PARAM_SET("zpnset"); } /* Find the point where the derivative first goes negative. */ for (j = 0; j < 180; j++) { zd2 = j*D2R; d2 = 0.0; for (m = k; m > 0; m--) { d2 = d2*zd2 + m*prj->pv[m]; } if (d2 <= 0.0) break; zd1 = zd2; d1 = d2; } if (j == 180) { /* No negative derivative -> no point of inflection. */ zd = PI; prj->global = 1; } else { /* Find where the derivative is zero. */ for (j = 1; j <= 10; j++) { zd = zd1 - d1*(zd2-zd1)/(d2-d1); d = 0.0; for (m = k; m > 0; m--) { d = d*zd + m*prj->pv[m]; } if (fabs(d) < tol) break; if (d < 0.0) { zd2 = zd; d2 = d; } else { zd1 = zd; d1 = d; } } } r = 0.0; for (m = k; m >= 0; m--) { r = r*zd + prj->pv[m]; } prj->w[0] = zd; prj->w[1] = r; } prj->prjx2s = zpnx2s; prj->prjs2x = zpns2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int zpnx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int j, k, m, mx, my, rowlen, rowoff, status; double a, b, c, d, lambda, r, r1, r2, rt, xj, yj, yj2, zd, zd1, zd2; const double tol = 1.0e-13; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ZPN) { if ((status = zpnset(prj))) return status; } k = prj->n; if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2)/prj->r0; if (r == 0.0) { *phip = 0.0; } else { *phip = atan2d(xj, -yj); } if (k < 1) { /* Constant - no solution. */ return PRJERR_BAD_PARAM_SET("zpnx2s"); } else if (k == 1) { /* Linear. */ zd = (r - prj->pv[0])/prj->pv[1]; } else if (k == 2) { /* Quadratic. */ a = prj->pv[2]; b = prj->pv[1]; c = prj->pv[0] - r; d = b*b - 4.0*a*c; if (d < 0.0) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); continue; } d = sqrt(d); /* Choose solution closest to pole. */ zd1 = (-b + d)/(2.0*a); zd2 = (-b - d)/(2.0*a); zd = (zd1<zd2) ? zd1 : zd2; if (zd < -tol) zd = (zd1>zd2) ? zd1 : zd2; if (zd < 0.0) { if (zd < -tol) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); continue; } zd = 0.0; } else if (zd > PI) { if (zd > PI+tol) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); continue; } zd = PI; } } else { /* Higher order - solve iteratively. */ zd1 = 0.0; r1 = prj->pv[0]; zd2 = prj->w[0]; r2 = prj->w[1]; if (r < r1) { if (r < r1-tol) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); continue; } zd = zd1; } else if (r > r2) { if (r > r2+tol) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); continue; } zd = zd2; } else { /* Dissect the interval. */ for (j = 0; j < 100; j++) { lambda = (r2 - r)/(r2 - r1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } zd = zd2 - lambda*(zd2 - zd1); rt = 0.0; for (m = k; m >= 0; m--) { rt = (rt * zd) + prj->pv[m]; } if (rt < r) { if (r-rt < tol) break; r1 = rt; zd1 = zd; } else { if (rt-r < tol) break; r2 = rt; zd2 = zd; } if (fabs(zd2-zd1) < tol) break; } } } *thetap = 90.0 - zd*R2D; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("zpnx2s"); } return status; } /*--------------------------------------------------------------------------*/ int zpns2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int m, mphi, mtheta, rowlen, rowoff, status; double cosphi, r, s, sinphi; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ZPN) { if ((status = zpnset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { s = (90.0 - *thetap)*D2R; r = 0.0; for (m = prj->n; m >= 0; m--) { r = r*s + prj->pv[m]; } r *= prj->r0; /* Bounds checking. */ istat = 0; if (prj->bounds&1) { if (s > prj->w[0]) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("zpns2x"); } } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = istat; } } return status; } /*============================================================================ * ZEA: zenithal/azimuthal equal area projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag ZEA * prj->code "ZEA" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 2*r0 * prj->w[1] 1/(2*r0) * prj->prjx2s Pointer to zeax2s(). * prj->prjs2x Pointer to zeas2x(). *===========================================================================*/ int zeaset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = ZEA; strcpy(prj->code, "ZEA"); strcpy(prj->name, "zenithal/azimuthal equal area"); prj->category = ZENITHAL; prj->pvrange = 0; prj->simplezen = 1; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 360.0/PI; prj->w[1] = PI/360.0; } else { prj->w[0] = 2.0*prj->r0; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = zeax2s; prj->prjs2x = zeas2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int zeax2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, s, xj, yj, yj2; const double tol = 1.0e-12; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ZEA) { if ((status = zeaset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2); if (r == 0.0) { *phip = 0.0; } else { *phip = atan2d(xj, -yj); } s = r*prj->w[1]; if (fabs(s) > 1.0) { if (fabs(r - prj->w[0]) < tol) { *thetap = -90.0; } else { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("zeax2s"); continue; } } else { *thetap = 90.0 - 2.0*asind(s); } *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("zeax2s"); } return status; } /*--------------------------------------------------------------------------*/ int zeas2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, r, sinphi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != ZEA) { if ((status = zeaset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { r = prj->w[0]*sind((90.0 - *thetap)/2.0); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = 0; } } return 0; } /*============================================================================ * AIR: Airy's projection. * * Given: * prj->pv[1] Latitude theta_b within which the error is minimized, in * degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 90.0 if undefined. * * Returned: * prj->flag AIR * prj->code "AIR" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 2*r0 * prj->w[1] ln(cos(xi_b))/tan(xi_b)**2, where xi_b = (90-theta_b)/2 * prj->w[2] 1/2 - prj->w[1] * prj->w[3] 2*r0*prj->w[2] * prj->w[4] tol, cutoff for using small angle approximation, in * radians. * prj->w[5] prj->w[2]*tol * prj->w[6] (180/pi)/prj->w[2] * prj->prjx2s Pointer to airx2s(). * prj->prjs2x Pointer to airs2x(). *===========================================================================*/ int airset(prj) struct prjprm *prj; { const double tol = 1.0e-4; double cosxi; if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = AIR; strcpy(prj->code, "AIR"); if (undefined(prj->pv[1])) prj->pv[1] = 90.0; if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "Airy's zenithal"); prj->category = ZENITHAL; prj->pvrange = 101; prj->simplezen = 1; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 1; prj->w[0] = 2.0*prj->r0; if (prj->pv[1] == 90.0) { prj->w[1] = -0.5; prj->w[2] = 1.0; } else if (prj->pv[1] > -90.0) { cosxi = cosd((90.0 - prj->pv[1])/2.0); prj->w[1] = log(cosxi)*(cosxi*cosxi)/(1.0-cosxi*cosxi); prj->w[2] = 0.5 - prj->w[1]; } else { return PRJERR_BAD_PARAM_SET("airset"); } prj->w[3] = prj->w[0] * prj->w[2]; prj->w[4] = tol; prj->w[5] = prj->w[2]*tol; prj->w[6] = R2D/prj->w[2]; prj->prjx2s = airx2s; prj->prjs2x = airs2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int airx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int k, mx, my, rowlen, rowoff, status; double cosxi, lambda, r, r1, r2, rt, tanxi, x1, x2, xi, xj, yj, yj2; const double tol = 1.0e-12; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AIR) { if ((status = airset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + yj2)/prj->w[0]; if (r == 0.0) { *phip = 0.0; } else { *phip = atan2d(xj, -yj); } if (r == 0.0) { xi = 0.0; } else if (r < prj->w[5]) { xi = r*prj->w[6]; } else { /* Find a solution interval. */ x1 = x2 = 1.0; r1 = r2 = 0.0; for (k = 0; k < 30; k++) { x2 = x1/2.0; tanxi = sqrt(1.0-x2*x2)/x2; r2 = -(log(x2)/tanxi + prj->w[1]*tanxi); if (r2 >= r) break; x1 = x2; r1 = r2; } if (k == 30) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("airx2s"); continue; } for (k = 0; k < 100; k++) { /* Weighted division of the interval. */ lambda = (r2-r)/(r2-r1); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } cosxi = x2 - lambda*(x2-x1); tanxi = sqrt(1.0-cosxi*cosxi)/cosxi; rt = -(log(cosxi)/tanxi + prj->w[1]*tanxi); if (rt < r) { if (r-rt < tol) break; r1 = rt; x1 = cosxi; } else { if (rt-r < tol) break; r2 = rt; x2 = cosxi; } } if (k == 100) { *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("airx2s"); continue; } xi = acosd(cosxi); } *thetap = 90.0 - 2.0*xi; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("airx2s"); } return status; } /*--------------------------------------------------------------------------*/ int airs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, cosxi, r, tanxi, xi, sinphi; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AIR) { if ((status = airset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { istat = 0; if (*thetap == 90.0) { r = 0.0; } else if (*thetap > -90.0) { xi = D2R*(90.0 - *thetap)/2.0; if (xi < prj->w[4]) { r = xi*prj->w[3]; } else { cosxi = cosd((90.0 - *thetap)/2.0); tanxi = sqrt(1.0 - cosxi*cosxi)/cosxi; r = -prj->w[0]*(log(cosxi)/tanxi + prj->w[1]*tanxi); } } else { r = 0.0; istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("airs2x"); } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - prj->y0; *(statp++) = istat; } } return status; } /*============================================================================ * CYP: cylindrical perspective projection. * * Given: * prj->pv[1] Distance of point of projection from the centre of the * generating sphere, mu, in units of r0. * prj->pv[2] Radius of the cylinder of projection, lambda, in units of * r0. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag CYP * prj->code "CYP" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*lambda*(pi/180) * prj->w[1] (180/pi)/(r0*lambda) * prj->w[2] r0*(mu + lambda) * prj->w[3] 1/(r0*(mu + lambda)) * prj->prjx2s Pointer to cypx2s(). * prj->prjs2x Pointer to cyps2x(). *===========================================================================*/ int cypset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = CYP; strcpy(prj->code, "CYP"); if (undefined(prj->pv[1])) prj->pv[1] = 1.0; if (undefined(prj->pv[2])) prj->pv[2] = 1.0; strcpy(prj->name, "cylindrical perspective"); prj->category = CYLINDRICAL; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = prj->pv[1] < -1.0 || 0.0 < prj->pv[1]; prj->divergent = !prj->global; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = prj->pv[2]; if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("cypset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = R2D*(prj->pv[1] + prj->pv[2]); if (prj->w[2] == 0.0) { return PRJERR_BAD_PARAM_SET("cypset"); } prj->w[3] = 1.0/prj->w[2]; } else { prj->w[0] = prj->r0*prj->pv[2]*D2R; if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("cypset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = prj->r0*(prj->pv[1] + prj->pv[2]); if (prj->w[2] == 0.0) { return PRJERR_BAD_PARAM_SET("cypset"); } prj->w[3] = 1.0/prj->w[2]; } prj->prjx2s = cypx2s; prj->prjs2x = cyps2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int cypx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double eta, s, t; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CYP) { if ((status = cypset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1]*(*xp + prj->x0); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; phip += rowlen; } } /* Do y dependence. */ yp = y; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { eta = prj->w[3]*(*yp + prj->y0); t = atan2d(eta,1.0) + asind(eta*prj->pv[1]/sqrt(eta*eta+1.0)); for (ix = 0; ix < mx; ix++, thetap += spt) { *thetap = t; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("cypx2s"); } return status; } /*--------------------------------------------------------------------------*/ int cyps2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, xi; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CYP) { if ((status = cypset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip) - prj->x0; xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { eta = prj->pv[1] + cosd(*thetap); istat = 0; if (eta == 0.0) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cyps2x"); } else { eta = prj->w[2]*sind(*thetap)/eta; } eta -= prj->y0; for (iphi = 0; iphi < mphi; iphi++, yp += sxy) { *yp = eta; *(statp++) = istat; } } return status; } /*============================================================================ * CEA: cylindrical equal area projection. * * Given: * prj->pv[1] Square of the cosine of the latitude at which the * projection is conformal, lambda. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag CEA * prj->code "CEA" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] r0/lambda * prj->w[3] lambda/r0 * prj->prjx2s Pointer to ceax2s(). * prj->prjs2x Pointer to ceas2x(). *===========================================================================*/ int ceaset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = CEA; strcpy(prj->code, "CEA"); if (undefined(prj->pv[1])) prj->pv[1] = 1.0; strcpy(prj->name, "cylindrical equal area"); prj->category = CYLINDRICAL; prj->pvrange = 101; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; if (prj->pv[1] <= 0.0 || prj->pv[1] > 1.0) { return PRJERR_BAD_PARAM_SET("ceaset"); } prj->w[2] = prj->r0/prj->pv[1]; prj->w[3] = prj->pv[1]/prj->r0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = R2D/prj->r0; if (prj->pv[1] <= 0.0 || prj->pv[1] > 1.0) { return PRJERR_BAD_PARAM_SET("ceaset"); } prj->w[2] = prj->r0/prj->pv[1]; prj->w[3] = prj->pv[1]/prj->r0; } prj->prjx2s = ceax2s; prj->prjs2x = ceas2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int ceax2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double s; const double tol = 1.0e-13; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CEA) { if ((status = ceaset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1]*(*xp + prj->x0); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; phip += rowlen; } } /* Do y dependence. */ yp = y; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { s = prj->w[3]*(*yp + prj->y0); istat = 0; if (fabs(s) > 1.0) { if (fabs(s) > 1.0+tol) { s = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("ceax2s"); } else { s = copysign(90.0, s); } } else { s = asind(s); } for (ix = 0; ix < mx; ix++, thetap += spt) { *thetap = s; *(statp++) = istat; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("ceax2s"); } return status; } /*--------------------------------------------------------------------------*/ int ceas2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CEA) { if ((status = ceaset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip) - prj->x0; xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { eta = prj->w[2]*sind(*thetap) - prj->y0; for (iphi = 0; iphi < mphi; iphi++, yp += sxy) { *yp = eta; *(statp++) = 0; } } return 0; } /*============================================================================ * CAR: Plate carree projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag CAR * prj->code "CAR" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjx2s Pointer to carx2s(). * prj->prjs2x Pointer to cars2x(). *===========================================================================*/ int carset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = CAR; strcpy(prj->code, "CAR"); strcpy(prj->name, "plate caree"); prj->category = CYLINDRICAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = carx2s; prj->prjs2x = cars2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int carx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double s, t; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CAR) { if ((status = carset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1]*(*xp + prj->x0); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; phip += rowlen; } } /* Do y dependence. */ yp = y; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { t = prj->w[1]*(*yp + prj->y0); for (ix = 0; ix < mx; ix++, thetap += spt) { *thetap = t; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("carx2s"); } return status; } /*--------------------------------------------------------------------------*/ int cars2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CAR) { if ((status = carset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip) - prj->x0; xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { eta = prj->w[0]*(*thetap) - prj->y0; for (iphi = 0; iphi < mphi; iphi++, yp += sxy) { *yp = eta; *(statp++) = 0; } } return 0; } /*============================================================================ * MER: Mercator's projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag MER * prj->code "MER" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjx2s Pointer to merx2s(). * prj->prjs2x Pointer to mers2x(). *===========================================================================*/ int merset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = MER; strcpy(prj->code, "MER"); strcpy(prj->name, "Mercator's"); prj->category = CYLINDRICAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 1; prj->global = 0; prj->divergent = 1; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = merx2s; prj->prjs2x = mers2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int merx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double s, t; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != MER) { if ((status = merset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1]*(*xp + prj->x0); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; phip += rowlen; } } /* Do y dependence. */ yp = y; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { t = 2.0*atand(exp((*yp + prj->y0)/prj->r0)) - 90.0; for (ix = 0; ix < mx; ix++, thetap += spt) { *thetap = t; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("merx2s"); } return status; } /*--------------------------------------------------------------------------*/ int mers2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, xi; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != MER) { if ((status = merset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip) - prj->x0; xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { istat = 0; if (*thetap <= -90.0 || *thetap >= 90.0) { eta = 0.0; istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("mers2x"); } else { eta = prj->r0*log(tand((*thetap+90.0)/2.0)) - prj->y0; } for (iphi = 0; iphi < mphi; iphi++, yp += sxy) { *yp = eta; *(statp++) = istat; } } return status; } /*============================================================================ * SFL: Sanson-Flamsteed ("global sinusoid") projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag SFL * prj->code "SFL" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->prjx2s Pointer to sflx2s(). * prj->prjs2x Pointer to sfls2x(). *===========================================================================*/ int sflset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = SFL; strcpy(prj->code, "SFL"); strcpy(prj->name, "Sanson-Flamsteed"); prj->category = PSEUDOCYLINDRICAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = sflx2s; prj->prjs2x = sfls2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int sflx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double s, t, yj; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SFL) { if ((status = sflset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1]*(*xp + prj->x0); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; s = cos(yj/prj->r0); istat = 0; if (s == 0.0) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("sflx2s"); } else { s = 1.0/s; } t = prj->w[1]*yj; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { *phip *= s; *thetap = t; *(statp++) = istat; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-12, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("sflx2s"); } return status; } /*--------------------------------------------------------------------------*/ int sfls2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != SFL) { if ((status = sflset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip); xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { xi = cosd(*thetap); eta = prj->w[0]*(*thetap) - prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = xi*(*xp) - prj->x0; *yp = eta; *(statp++) = 0; } } return 0; } /*============================================================================ * PAR: parabolic projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag PAR * prj->code "PAR" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] pi*r0 * prj->w[3] 1/(pi*r0) * prj->prjx2s Pointer to parx2s(). * prj->prjs2x Pointer to pars2x(). *===========================================================================*/ int parset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = PAR; strcpy(prj->code, "PAR"); strcpy(prj->name, "parabolic"); prj->category = PSEUDOCYLINDRICAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; prj->w[2] = 180.0; prj->w[3] = 1.0/prj->w[2]; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; prj->w[2] = PI*prj->r0; prj->w[3] = 1.0/prj->w[2]; } prj->prjx2s = parx2s; prj->prjs2x = pars2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int parx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, s, t, xj; const double tol = 1.0e-13; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != PAR) { if ((status = parset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; s = prj->w[1]*xj; t = fabs(xj) - tol; phip = phi + rowoff; thetap = theta + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; *thetap = t; phip += rowlen; thetap += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { r = prj->w[3]*(*yp + prj->y0); istat = 0; if (r > 1.0 || r < -1.0) { s = 0.0; t = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("parx2s"); } else { s = 1.0 - 4.0*r*r; if (s == 0.0) { /* Deferred test. */ istat = -1; } else { s = 1.0/s; } t = 3.0*asind(r); } for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { if (istat < 0) { if (*thetap < 0.0) { *(statp++) = 0; } else { *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("parx2s"); } } else { *(statp++) = istat; } *phip *= s; *thetap = t; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-12, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("parx2s"); } return status; } /*--------------------------------------------------------------------------*/ int pars2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double eta, s, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != PAR) { if ((status = parset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0]*(*phip); xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { s = sind((*thetap)/3.0); xi = (1.0 - 4.0*s*s); eta = prj->w[2]*s - prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = xi*(*xp) - prj->x0; *yp = eta; *(statp++) = 0; } } return 0; } /*============================================================================ * MOL: Mollweide's projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag MOL * prj->code "MOL" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] sqrt(2)*r0 * prj->w[1] sqrt(2)*r0/90 * prj->w[2] 1/(sqrt(2)*r0) * prj->w[3] 90/r0 * prj->prjx2s Pointer to molx2s(). * prj->prjs2x Pointer to mols2x(). *===========================================================================*/ int molset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = MOL; strcpy(prj->code, "MOL"); if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "Mollweide's"); prj->category = PSEUDOCYLINDRICAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; prj->w[0] = SQRT2*prj->r0; prj->w[1] = prj->w[0]/90.0; prj->w[2] = 1.0/prj->w[0]; prj->w[3] = 90.0/prj->r0; prj->w[4] = 2.0/PI; prj->prjx2s = molx2s; prj->prjs2x = mols2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int molx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double r, s, t, xj, y0, yj, z; const double tol = 1.0e-12; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != MOL) { if ((status = molset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; s = prj->w[3]*xj; t = fabs(xj) - tol; phip = phi + rowoff; thetap = theta + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; *thetap = t; phip += rowlen; thetap += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; y0 = yj/prj->r0; r = 2.0 - y0*y0; istat = 0; if (r <= tol) { if (r < -tol) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("molx2s"); } else { /* OK if fabs(x) < tol whence phi = 0.0. */ istat = -1; } r = 0.0; s = 0.0; } else { r = sqrt(r); s = 1.0/r; } z = yj*prj->w[2]; if (fabs(z) > 1.0) { if (fabs(z) > 1.0+tol) { z = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("molx2s"); } else { z = copysign(1.0, z) + y0*r/PI; } } else { z = asin(z)*prj->w[4] + y0*r/PI; } if (fabs(z) > 1.0) { if (fabs(z) > 1.0+tol) { z = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("molx2s"); } else { z = copysign(1.0, z); } } t = asind(z); for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { if (istat < 0) { if (*thetap < 0.0) { *(statp++) = 0; } else { *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("molx2s"); } } else { *(statp++) = istat; } *phip *= s; *thetap = t; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-11, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("molx2s"); } return status; } /*--------------------------------------------------------------------------*/ int mols2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int k, mphi, mtheta, rowlen, rowoff, status; double eta, gamma, resid, u, v, v0, v1, xi; const double tol = 1.0e-13; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != MOL) { if ((status = molset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[1]*(*phip); xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = xi; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { if (fabs(*thetap) == 90.0) { xi = 0.0; eta = copysign(prj->w[0], *thetap); } else if (*thetap == 0.0) { xi = 1.0; eta = 0.0; } else { u = PI*sind(*thetap); v0 = -PI; v1 = PI; v = u; for (k = 0; k < 100; k++) { resid = (v - u) + sin(v); if (resid < 0.0) { if (resid > -tol) break; v0 = v; } else { if (resid < tol) break; v1 = v; } v = (v0 + v1)/2.0; } gamma = v/2.0; xi = cos(gamma); eta = prj->w[0]*sin(gamma); } eta -= prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = xi*(*xp) - prj->x0; *yp = eta; *(statp++) = 0; } } return 0; } /*============================================================================ * AIT: Hammer-Aitoff projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag AIT * prj->code "AIT" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] 2*r0**2 * prj->w[1] 1/(2*r0)**2 * prj->w[2] 1/(4*r0)**2 * prj->w[3] 1/(2*r0) * prj->prjx2s Pointer to aitx2s(). * prj->prjs2x Pointer to aits2x(). *===========================================================================*/ int aitset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = AIT; strcpy(prj->code, "AIT"); if (prj->r0 == 0.0) prj->r0 = R2D; strcpy(prj->name, "Hammer-Aitoff"); prj->category = CONVENTIONAL; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; prj->w[0] = 2.0*prj->r0*prj->r0; prj->w[1] = 1.0/(2.0*prj->w[0]); prj->w[2] = prj->w[1]/4.0; prj->w[3] = 1.0/(2.0*prj->r0); prj->prjx2s = aitx2s; prj->prjs2x = aits2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int aitx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double s, t, x0, xj, y0, yj, yj2, z; const double tol = 1.0e-13; register int ix, iy, istat, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AIT) { if ((status = aitset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; s = 1.0 - xj*xj*prj->w[2]; t = xj*prj->w[3]; phip = phi + rowoff; thetap = theta + rowoff; for (iy = 0; iy < my; iy++) { *phip = s; *thetap = t; phip += rowlen; thetap += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; yj2 = yj*yj*prj->w[1]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { s = *phip - yj2; istat = 0; if (s < 0.5) { if (s < 0.5-tol) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("aitx2s"); } s = 0.5; } z = sqrt(s); x0 = 2.0*z*z - 1.0; y0 = z*(*thetap); if (x0 == 0.0 && y0 == 0.0) { *phip = 0.0; } else { *phip = 2.0*atan2d(y0, x0); } t = z*yj/prj->r0; if (fabs(t) > 1.0) { if (fabs(t) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("aitx2s"); } t = copysign(90.0, t); } else { t = asind(t); } *thetap = t; *(statp++) = istat; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("aitx2s"); } return status; } /*--------------------------------------------------------------------------*/ int aits2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cosphi, costhe, sinphi, sinthe, w; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != AIT) { if ((status = aitset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { w = (*phip)/2.0; sincosd(w, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinphi; *yp = cosphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { w = sqrt(prj->w[0]/(1.0 + costhe*(*yp))); *xp = 2.0*w*costhe*(*xp) - prj->x0; *yp = w*sinthe - prj->y0; *(statp++) = 0; } } return 0; } /*============================================================================ * COP: conic perspective projection. * * Given: * prj->pv[1] sigma = (theta2+theta1)/2 * prj->pv[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to sigma if undefined. * prj->theta0 Reset to sigma if undefined. * * Returned: * prj->flag COP * prj->code "COP" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] C = sin(sigma) * prj->w[1] 1/C * prj->w[2] Y0 = r0*cos(delta)*cot(sigma) * prj->w[3] r0*cos(delta) * prj->w[4] 1/(r0*cos(delta) * prj->w[5] cot(sigma) * prj->prjx2s Pointer to copx2s(). * prj->prjs2x Pointer to cops2x(). *===========================================================================*/ int copset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = COP; strcpy(prj->code, "COP"); strcpy(prj->name, "conic perspective"); if (undefined(prj->pv[1])) { return PRJERR_BAD_PARAM_SET("copset"); } if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->category = CONIC; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 0; prj->divergent = 1; prj->w[0] = sind(prj->pv[1]); if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("copset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0*cosd(prj->pv[2]); if (prj->w[3] == 0.0) { return PRJERR_BAD_PARAM_SET("copset"); } prj->w[4] = 1.0/prj->w[3]; prj->w[5] = 1.0/tand(prj->pv[1]); prj->w[2] = prj->w[3]*prj->w[5]; prj->prjx2s = copx2s; prj->prjs2x = cops2x; return prjoff(prj, 0.0, prj->pv[1]); } /*--------------------------------------------------------------------------*/ int copx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double alpha, dy, dy2, r, xj; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COP) { if ((status = copset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { dy = prj->w[2] - (*yp + prj->y0); dy2 = dy*dy; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + dy2); if (prj->pv[1] < 0.0) r = -r; if (r == 0.0) { alpha = 0.0; } else { alpha = atan2d(xj/r, dy/r); } *phip = alpha*prj->w[1]; *thetap = prj->pv[1] + atand(prj->w[5] - r*prj->w[4]); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("copx2s"); } return status; } /*--------------------------------------------------------------------------*/ int cops2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double alpha, cosalpha, r, s, t, sinalpha, y0; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COP) { if ((status = copset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { alpha = prj->w[0]*(*phip); sincosd(alpha, &sinalpha, &cosalpha); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinalpha; *yp = cosalpha; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; y0 = prj->y0 - prj->w[2]; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { t = *thetap - prj->pv[1]; s = cosd(t); istat = 0; if (s == 0.0) { /* Latitude of divergence. */ r = 0.0; istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cops2x"); } else if (fabs(*thetap) == 90.0) { /* Return an exact value at the poles. */ r = 0.0; /* Bounds checking. */ if (prj->bounds&1) { if ((*thetap < 0.0) != (prj->pv[1] < 0.0)) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cops2x"); } } } else { r = prj->w[2] - prj->w[3]*sind(t)/s; /* Bounds checking. */ if (prj->bounds&1) { if (r*prj->w[0] < 0.0) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cops2x"); } } } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - y0; *(statp++) = istat; } } return status; } /*============================================================================ * COE: conic equal area projection. * * Given: * prj->pv[1] sigma = (theta2+theta1)/2 * prj->pv[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to sigma if undefined. * prj->theta0 Reset to sigma if undefined. * * Returned: * prj->flag COE * prj->code "COE" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] C = (sin(theta1) + sin(theta2))/2 * prj->w[1] 1/C * prj->w[2] Y0 = chi*sqrt(psi - 2C*sind(sigma)) * prj->w[3] chi = r0/C * prj->w[4] psi = 1 + sin(theta1)*sin(theta2) * prj->w[5] 2C * prj->w[6] (1 + sin(theta1)*sin(theta2))*(r0/C)**2 * prj->w[7] C/(2*r0**2) * prj->w[8] chi*sqrt(psi + 2C) * prj->prjx2s Pointer to coex2s(). * prj->prjs2x Pointer to coes2x(). *===========================================================================*/ int coeset(prj) struct prjprm *prj; { double theta1, theta2; if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = COE; strcpy(prj->code, "COE"); strcpy(prj->name, "conic equal area"); if (undefined(prj->pv[1])) { return PRJERR_BAD_PARAM_SET("coeset"); } if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->category = CONIC; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; theta1 = prj->pv[1] - prj->pv[2]; theta2 = prj->pv[1] + prj->pv[2]; prj->w[0] = (sind(theta1) + sind(theta2))/2.0; if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("coeset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0/prj->w[0]; prj->w[4] = 1.0 + sind(theta1)*sind(theta2); prj->w[5] = 2.0*prj->w[0]; prj->w[6] = prj->w[3]*prj->w[3]*prj->w[4]; prj->w[7] = 1.0/(2.0*prj->r0*prj->w[3]); prj->w[8] = prj->w[3]*sqrt(prj->w[4] + prj->w[5]); prj->w[2] = prj->w[3]*sqrt(prj->w[4] - prj->w[5]*sind(prj->pv[1])); prj->prjx2s = coex2s; prj->prjs2x = coes2x; return prjoff(prj, 0.0, prj->pv[1]); } /*--------------------------------------------------------------------------*/ int coex2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double alpha, dy, dy2, r, t, w, xj; const double tol = 1.0e-12; register int ix, iy, istat, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COE) { if ((status = coeset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { dy = prj->w[2] - (*yp + prj->y0); dy2 = dy*dy; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + dy2); if (prj->pv[1] < 0.0) r = -r; if (r == 0.0) { alpha = 0.0; } else { alpha = atan2d(xj/r, dy/r); } istat = 0; if (fabs(r - prj->w[8]) < tol) { t = -90.0; } else { w = (prj->w[6] - r*r)*prj->w[7]; if (fabs(w) > 1.0) { if (fabs(w-1.0) < tol) { t = 90.0; } else if (fabs(w+1.0) < tol) { t = -90.0; } else { t = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("coex2s"); } } else { t = asind(w); } } *phip = alpha*prj->w[1]; *thetap = t; *(statp++) = istat; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("coex2s"); } return status; } /*--------------------------------------------------------------------------*/ int coes2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double alpha, cosalpha, r, sinalpha, y0; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COE) { if ((status = coeset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { alpha = prj->w[0]*(*phip); sincosd(alpha, &sinalpha, &cosalpha); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinalpha; *yp = cosalpha; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; y0 = prj->y0 - prj->w[2]; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { if (*thetap == -90.0) { r = prj->w[8]; } else { r = prj->w[3]*sqrt(prj->w[4] - prj->w[5]*sind(*thetap)); } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - y0; *(statp++) = 0; } } return 0; } /*============================================================================ * COD: conic equidistant projection. * * Given: * prj->pv[1] sigma = (theta2+theta1)/2 * prj->pv[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to sigma if undefined. * prj->theta0 Reset to sigma if undefined. * * Returned: * prj->flag COD * prj->code "COD" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] C = r0*sin(sigma)*sin(delta)/delta * prj->w[1] 1/C * prj->w[2] Y0 = delta*cot(delta)*cot(sigma) * prj->w[3] Y0 + sigma * prj->prjx2s Pointer to codx2s(). * prj->prjs2x Pointer to cods2x(). *===========================================================================*/ int codset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = COD; strcpy(prj->code, "COD"); strcpy(prj->name, "conic equidistant"); if (undefined(prj->pv[1])) { return PRJERR_BAD_PARAM_SET("codset"); } if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->category = CONIC; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->pv[2] == 0.0) { prj->w[0] = prj->r0*sind(prj->pv[1])*D2R; } else { prj->w[0] = prj->r0*sind(prj->pv[1])*sind(prj->pv[2])/prj->pv[2]; } if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("codset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[2] = prj->r0*cosd(prj->pv[2])*cosd(prj->pv[1])/prj->w[0]; prj->w[3] = prj->w[2] + prj->pv[1]; prj->prjx2s = codx2s; prj->prjs2x = cods2x; return prjoff(prj, 0.0, prj->pv[1]); } /*--------------------------------------------------------------------------*/ int codx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double alpha, dy, dy2, r, xj; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COD) { if ((status = codset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { dy = prj->w[2] - (*yp + prj->y0); dy2 = dy*dy; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + dy2); if (prj->pv[1] < 0.0) r = -r; if (r == 0.0) { alpha = 0.0; } else { alpha = atan2d(xj/r, dy/r); } *phip = alpha*prj->w[1]; *thetap = prj->w[3] - r; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("codx2s"); } return status; } /*--------------------------------------------------------------------------*/ int cods2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double alpha, cosalpha, r, sinalpha, y0; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COD) { if ((status = codset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { alpha = prj->w[0]*(*phip); sincosd(alpha, &sinalpha, &cosalpha); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinalpha; *yp = cosalpha; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; y0 = prj->y0 - prj->w[2]; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { r = prj->w[3] - *thetap; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - y0; *(statp++) = 0; } } return 0; } /*============================================================================ * COO: conic orthomorphic projection. * * Given: * prj->pv[1] sigma = (theta2+theta1)/2 * prj->pv[2] delta = (theta2-theta1)/2, where theta1 and theta2 are the * latitudes of the standard parallels, in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to sigma if undefined. * prj->theta0 Reset to sigma if undefined. * * Returned: * prj->flag COO * prj->code "COO" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] C = ln(cos(theta2)/cos(theta1))/ln(tan(tau2)/tan(tau1)) * where tau1 = (90 - theta1)/2 * tau2 = (90 - theta2)/2 * prj->w[1] 1/C * prj->w[2] Y0 = psi*tan((90-sigma)/2)**C * prj->w[3] psi = (r0*cos(theta1)/C)/tan(tau1)**C * prj->w[4] 1/psi * prj->prjx2s Pointer to coox2s(). * prj->prjs2x Pointer to coos2x(). *===========================================================================*/ int cooset(prj) struct prjprm *prj; { double cos1, cos2, tan1, tan2, theta1, theta2; if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = COO; strcpy(prj->code, "COO"); strcpy(prj->name, "conic orthomorphic"); if (undefined(prj->pv[1])) { return PRJERR_BAD_PARAM_SET("cooset"); } if (undefined(prj->pv[2])) prj->pv[2] = 0.0; if (prj->r0 == 0.0) prj->r0 = R2D; prj->category = CONIC; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 1; prj->global = 0; prj->divergent = 1; theta1 = prj->pv[1] - prj->pv[2]; theta2 = prj->pv[1] + prj->pv[2]; tan1 = tand((90.0 - theta1)/2.0); cos1 = cosd(theta1); if (theta1 == theta2) { prj->w[0] = sind(theta1); } else { tan2 = tand((90.0 - theta2)/2.0); cos2 = cosd(theta2); prj->w[0] = log(cos2/cos1)/log(tan2/tan1); } if (prj->w[0] == 0.0) { return PRJERR_BAD_PARAM_SET("cooset"); } prj->w[1] = 1.0/prj->w[0]; prj->w[3] = prj->r0*(cos1/prj->w[0])/pow(tan1,prj->w[0]); if (prj->w[3] == 0.0) { return PRJERR_BAD_PARAM_SET("cooset"); } prj->w[2] = prj->w[3]*pow(tand((90.0 - prj->pv[1])/2.0),prj->w[0]); prj->w[4] = 1.0/prj->w[3]; prj->prjx2s = coox2s; prj->prjs2x = coos2x; return prjoff(prj, 0.0, prj->pv[1]); } /*--------------------------------------------------------------------------*/ int coox2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double alpha, dy, dy2, r, t, xj; register int ix, iy, istat, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COO) { if ((status = cooset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { dy = prj->w[2] - (*yp + prj->y0); dy2 = dy*dy; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + dy2); if (prj->pv[1] < 0.0) r = -r; if (r == 0.0) { alpha = 0.0; } else { alpha = atan2d(xj/r, dy/r); } istat = 0; if (r == 0.0) { if (prj->w[0] < 0.0) { t = -90.0; } else { t = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("coox2s"); } } else { t = 90.0 - 2.0*atand(pow(r*prj->w[4],prj->w[1])); } *phip = alpha*prj->w[1]; *thetap = t; *(statp++) = istat; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("coox2s"); } return status; } /*--------------------------------------------------------------------------*/ int coos2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double alpha, cosalpha, r, sinalpha, y0; register int iphi, itheta, istat, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != COO) { if ((status = cooset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { alpha = prj->w[0]*(*phip); sincosd(alpha, &sinalpha, &cosalpha); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = sinalpha; *yp = cosalpha; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; y0 = prj->y0 - prj->w[2]; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { istat = 0; if (*thetap == -90.0) { r = 0.0; if (prj->w[0] >= 0.0) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("coos2x"); } } else { r = prj->w[3]*pow(tand((90.0 - *thetap)/2.0),prj->w[0]); } for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = r*(*xp) - prj->x0; *yp = -r*(*yp) - y0; *(statp++) = istat; } } return status; } /*============================================================================ * BON: Bonne's projection. * * Given: * prj->pv[1] Bonne conformal latitude, theta1, in degrees. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag BON * prj->code "BON" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[1] r0*pi/180 * prj->w[2] Y0 = r0*(cot(theta1) + theta1*pi/180) * prj->prjx2s Pointer to bonx2s(). * prj->prjs2x Pointer to bons2x(). *===========================================================================*/ int bonset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = BON; strcpy(prj->code, "BON"); strcpy(prj->name, "Bonne's"); if (undefined(prj->pv[1])) { return PRJERR_BAD_PARAM_SET("bonset"); } if (prj->pv[1] == 0.0) { /* Sanson-Flamsteed. */ return sflset(prj); } prj->category = POLYCONIC; prj->pvrange = 101; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[1] = 1.0; prj->w[2] = prj->r0*cosd(prj->pv[1])/sind(prj->pv[1]) + prj->pv[1]; } else { prj->w[1] = prj->r0*D2R; prj->w[2] = prj->r0*(cosd(prj->pv[1])/sind(prj->pv[1]) + prj->pv[1]*D2R); } prj->prjx2s = bonx2s; prj->prjs2x = bons2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int bonx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double alpha, dy, dy2, costhe, r, s, t, xj; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->pv[1] == 0.0) { /* Sanson-Flamsteed. */ return sflx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat); } if (prj->flag != BON) { if ((status = bonset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { dy = prj->w[2] - (*yp + prj->y0); dy2 = dy*dy; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; r = sqrt(xj*xj + dy2); if (prj->pv[1] < 0.0) r = -r; if (r == 0.0) { alpha = 0.0; } else { alpha = atan2d(xj/r, dy/r); } t = (prj->w[2] - r)/prj->w[1]; costhe = cosd(t); if (costhe == 0.0) { s = 0.0; } else { s = alpha*(r/prj->r0)/costhe; } *phip = s; *thetap = t; *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-11, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("bonx2s"); } return status; } /*--------------------------------------------------------------------------*/ int bons2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double alpha, cosalpha, r, s, sinalpha, y0; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->pv[1] == 0.0) { /* Sanson-Flamsteed. */ return sfls2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat); } if (prj->flag != BON) { if ((status = bonset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } y0 = prj->y0 - prj->w[2]; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { s = prj->r0*(*phip); xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = s; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { r = prj->w[2] - prj->w[1]*(*thetap); s = cosd(*thetap)/r; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { alpha = s*(*xp); sincosd(alpha, &sinalpha, &cosalpha); *xp = r*sinalpha - prj->x0; *yp = -r*cosalpha - y0; *(statp++) = 0; } } return 0; } /*============================================================================ * PCO: polyconic projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag PCO * prj->code "PCO" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] 2*r0 * prj->w[3] (pi/180)/(2*r0) * prj->prjx2s Pointer to pcox2s(). * prj->prjs2x Pointer to pcos2x(). *===========================================================================*/ int pcoset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = PCO; strcpy(prj->code, "PCO"); strcpy(prj->name, "polyconic"); prj->category = POLYCONIC; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; prj->w[2] = 360.0/PI; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = 1.0/prj->w[0]; prj->w[2] = 2.0*prj->r0; } prj->w[3] = D2R/prj->w[2]; prj->prjx2s = pcox2s; prj->prjs2x = pcos2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int pcox2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double f, fneg, fpos, lambda, tanthe, the, theneg, thepos, w, x1, xj, xx, yj, ymthe, y1; const double tol = 1.0e-12; register int ix, iy, k, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != PCO) { if ((status = pcoset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xj = *xp + prj->x0; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xj; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yj = *yp + prj->y0; w = fabs(yj*prj->w[1]); for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xj = *phip; if (w < tol) { *phip = xj*prj->w[1]; *thetap = 0.0; } else if (fabs(w-90.0) < tol) { *phip = 0.0; *thetap = copysign(90.0, yj); } else { if (w < 1.0e-4) { /* To avoid cot(theta) blowing up near theta == 0. */ the = yj / (prj->w[0] + prj->w[3]*xj*xj); ymthe = yj - prj->w[0]*the; tanthe = tand(the); } else { /* Iterative solution using weighted division of the interval. */ thepos = yj / prj->w[0]; theneg = 0.0; /* Setting fneg = -fpos halves the interval in the first iter. */ xx = xj*xj; fpos = xx; fneg = -xx; for (k = 0; k < 64; k++) { /* Weighted division of the interval. */ lambda = fpos/(fpos-fneg); if (lambda < 0.1) { lambda = 0.1; } else if (lambda > 0.9) { lambda = 0.9; } the = thepos - lambda*(thepos-theneg); /* Compute the residue. */ ymthe = yj - prj->w[0]*the; tanthe = tand(the); f = xx + ymthe*(ymthe - prj->w[2]/tanthe); /* Check for convergence. */ if (fabs(f) < tol) break; if (fabs(thepos-theneg) < tol) break; /* Redefine the interval. */ if (f > 0.0) { thepos = the; fpos = f; } else { theneg = the; fneg = f; } } } x1 = prj->r0 - ymthe*tanthe; y1 = xj*tanthe; if (x1 == 0.0 && y1 == 0.0) { *phip = 0.0; } else { *phip = atan2d(y1, x1)/sind(the); } *thetap = the; } *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-12, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("pcox2s"); } return status; } /*--------------------------------------------------------------------------*/ int pcos2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double cospsi, costhe, cotthe, sinpsi, sinthe, therad; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != PCO) { if ((status = pcoset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xp = x + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = *phip; xp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { if (*thetap == 0.0) { for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = prj->w[0]*(*xp) - prj->x0; *yp = -prj->y0; *(statp++) = 0; } } else if (fabs(*thetap) < 1.0e-4) { /* To avoid cot(theta) blowing up near theta == 0. */ for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *xp = prj->w[0]*(*xp)*cosd(*thetap) - prj->x0; *yp = (prj->w[0] + prj->w[3]*(*xp)*(*xp))*(*thetap) - prj->y0; *(statp++) = 0; } } else { therad = (*thetap)*D2R; sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { sincosd((*xp)*sinthe, &sinpsi, &cospsi); cotthe = costhe/sinthe; *xp = prj->r0*cotthe*sinpsi - prj->x0; *yp = prj->r0*(cotthe*(1.0 - cospsi) + therad) - prj->y0; *(statp++) = 0; } } } return 0; } /*============================================================================ * TSC: tangential spherical cube projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag TSC * prj->code "TSC" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjx2s Pointer to tscx2s(). * prj->prjs2x Pointer to tscs2x(). *===========================================================================*/ int tscset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = TSC; strcpy(prj->code, "TSC"); strcpy(prj->name, "tangential spherical cube"); prj->category = QUADCUBE; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = tscx2s; prj->prjs2x = tscs2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int tscx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double l, m, n, xf, yf; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != TSC) { if ((status = tscset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xf = (*xp + prj->x0)*prj->w[1]; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xf; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yf = (*yp + prj->y0)*prj->w[1]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xf = *phip; /* Bounds checking. */ if (fabs(xf) <= 1.0) { if (fabs(yf) > 3.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("tscx2s"); continue; } } else { if (fabs(xf) > 7.0 || fabs(yf) > 1.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("tscx2s"); continue; } } /* Map negative faces to the other side. */ if (xf < -1.0) xf += 8.0; /* Determine the face. */ if (xf > 5.0) { /* face = 4 */ xf = xf - 6.0; m = -1.0/sqrt(1.0 + xf*xf + yf*yf); l = -m*xf; n = -m*yf; } else if (xf > 3.0) { /* face = 3 */ xf = xf - 4.0; l = -1.0/sqrt(1.0 + xf*xf + yf*yf); m = l*xf; n = -l*yf; } else if (xf > 1.0) { /* face = 2 */ xf = xf - 2.0; m = 1.0/sqrt(1.0 + xf*xf + yf*yf); l = -m*xf; n = m*yf; } else if (yf > 1.0) { /* face = 0 */ yf = yf - 2.0; n = 1.0/sqrt(1.0 + xf*xf + yf*yf); l = -n*yf; m = n*xf; } else if (yf < -1.0) { /* face = 5 */ yf = yf + 2.0; n = -1.0/sqrt(1.0 + xf*xf + yf*yf); l = -n*yf; m = -n*xf; } else { /* face = 1 */ l = 1.0/sqrt(1.0 + xf*xf + yf*yf); m = l*xf; n = l*yf; } if (l == 0.0 && m == 0.0) { *phip = 0.0; } else { *phip = atan2d(m, l); } *thetap = asind(n); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("tscx2s"); } return status; } /*--------------------------------------------------------------------------*/ int tscs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int face, mphi, mtheta, rowlen, rowoff, status; double cosphi, costhe, l, m, n, sinphi, sinthe, x0, xf, y0, yf, zeta; const double tol = 1.0e-12; register int iphi, istat, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != TSC) { if ((status = tscset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = cosphi; *yp = sinphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { l = costhe*(*xp); m = costhe*(*yp); n = sinthe; face = 0; zeta = n; if (l > zeta) { face = 1; zeta = l; } if (m > zeta) { face = 2; zeta = m; } if (-l > zeta) { face = 3; zeta = -l; } if (-m > zeta) { face = 4; zeta = -m; } if (-n > zeta) { face = 5; zeta = -n; } switch (face) { case 1: xf = m/zeta; yf = n/zeta; x0 = 0.0; y0 = 0.0; break; case 2: xf = -l/zeta; yf = n/zeta; x0 = 2.0; y0 = 0.0; break; case 3: xf = -m/zeta; yf = n/zeta; x0 = 4.0; y0 = 0.0; break; case 4: xf = l/zeta; yf = n/zeta; x0 = 6.0; y0 = 0.0; break; case 5: xf = m/zeta; yf = l/zeta; x0 = 0.0; y0 = -2.0; break; default: /* face == 0 */ xf = m/zeta; yf = -l/zeta; x0 = 0.0; y0 = 2.0; break; } istat = 0; if (fabs(xf) > 1.0) { if (fabs(xf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("tscs2x"); } xf = copysign(1.0, xf); } if (fabs(yf) > 1.0) { if (fabs(yf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("tscs2x"); } yf = copysign(1.0, yf); } *xp = prj->w[0]*(xf + x0) - prj->x0; *yp = prj->w[0]*(yf + y0) - prj->y0; *(statp++) = istat; } } return status; } /*============================================================================ * CSC: COBE quadrilateralized spherical cube projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag CSC * prj->code "CSC" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjx2s Pointer to cscx2s(). * prj->prjs2x Pointer to cscs2x(). *===========================================================================*/ int cscset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = CSC; strcpy(prj->code, "CSC"); strcpy(prj->name, "COBE quadrilateralized spherical cube"); prj->category = QUADCUBE; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 0; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = cscx2s; prj->prjs2x = cscs2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int cscx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int face, mx, my, rowlen, rowoff, status; double l, m, n, t; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; float chi, psi, xf, xx, yf, yy, z0, z1, z2, z3, z4, z5, z6; const float p00 = -0.27292696f; const float p10 = -0.07629969f; const float p20 = -0.22797056f; const float p30 = 0.54852384f; const float p40 = -0.62930065f; const float p50 = 0.25795794f; const float p60 = 0.02584375f; const float p01 = -0.02819452f; const float p11 = -0.01471565f; const float p21 = 0.48051509f; const float p31 = -1.74114454f; const float p41 = 1.71547508f; const float p51 = -0.53022337f; const float p02 = 0.27058160f; const float p12 = -0.56800938f; const float p22 = 0.30803317f; const float p32 = 0.98938102f; const float p42 = -0.83180469f; const float p03 = -0.60441560f; const float p13 = 1.50880086f; const float p23 = -0.93678576f; const float p33 = 0.08693841f; const float p04 = 0.93412077f; const float p14 = -1.41601920f; const float p24 = 0.33887446f; const float p05 = -0.63915306f; const float p15 = 0.52032238f; const float p06 = 0.14381585f; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CSC) { if ((status = cscset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xf = (float)((*xp + prj->x0)*prj->w[1]); phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xf; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yf = (float)((*yp + prj->y0)*prj->w[1]); for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xf = (float)(*phip); /* Bounds checking. */ if (fabs((double)xf) <= 1.0) { if (fabs((double)yf) > 3.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("cscx2s"); continue; } } else { if (fabs((double)xf) > 7.0 || fabs((double)yf) > 1.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("cscx2s"); continue; } } /* Map negative faces to the other side. */ if (xf < -1.0f) xf += 8.0f; /* Determine the face. */ if (xf > 5.0f) { face = 4; xf = xf - 6.0f; } else if (xf > 3.0f) { face = 3; xf = xf - 4.0f; } else if (xf > 1.0f) { face = 2; xf = xf - 2.0f; } else if (yf > 1.0f) { face = 0; yf = yf - 2.0f; } else if (yf < -1.0f) { face = 5; yf = yf + 2.0f; } else { face = 1; } xx = xf*xf; yy = yf*yf; z0 = p00 + xx*(p10 + xx*(p20 + xx*(p30 + xx*(p40 + xx*(p50 + xx*(p60)))))); z1 = p01 + xx*(p11 + xx*(p21 + xx*(p31 + xx*(p41 + xx*(p51))))); z2 = p02 + xx*(p12 + xx*(p22 + xx*(p32 + xx*(p42)))); z3 = p03 + xx*(p13 + xx*(p23 + xx*(p33))); z4 = p04 + xx*(p14 + xx*(p24)); z5 = p05 + xx*(p15); z6 = p06; chi = z0 + yy*(z1 + yy*(z2 + yy*(z3 + yy*(z4 + yy*(z5 + yy*z6))))); chi = xf + xf*(1.0f - xx)*chi; z0 = p00 + yy*(p10 + yy*(p20 + yy*(p30 + yy*(p40 + yy*(p50 + yy*(p60)))))); z1 = p01 + yy*(p11 + yy*(p21 + yy*(p31 + yy*(p41 + yy*(p51))))); z2 = p02 + yy*(p12 + yy*(p22 + yy*(p32 + yy*(p42)))); z3 = p03 + yy*(p13 + yy*(p23 + yy*(p33))); z4 = p04 + yy*(p14 + yy*(p24)); z5 = p05 + yy*(p15); z6 = p06; psi = z0 + xx*(z1 + xx*(z2 + xx*(z3 + xx*(z4 + xx*(z5 + xx*z6))))); psi = yf + yf*(1.0f - yy)*psi; t = 1.0/sqrt((double)(chi*chi + psi*psi) + 1.0); switch (face) { case 1: l = t; m = chi*l; n = psi*l; break; case 2: m = t; l = -chi*m; n = psi*m; break; case 3: l = -t; m = chi*l; n = -psi*l; break; case 4: m = -t; l = -chi*m; n = -psi*m; break; case 5: n = -t; l = -psi*n; m = -chi*n; break; default: /* face == 0 */ n = t; l = -psi*n; m = chi*n; break; } if (l == 0.0 && m == 0.0) { *phip = 0.0; } else { *phip = atan2d(m, l); } *thetap = asind(n); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("cscx2s"); } return status; } /*--------------------------------------------------------------------------*/ int cscs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int face, mphi, mtheta, rowlen, rowoff, status; double cosphi, costhe, eta, l, m, n, sinphi, sinthe, xi, zeta; const float tol = 1.0e-7; register int iphi, istat, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; float chi, chi2, chi2psi2, chi4, chipsi, psi, psi2, psi4, chi2co, psi2co, x0, xf, y0, yf; const float gstar = 1.37484847732f; const float mm = 0.004869491981f; const float gamma = -0.13161671474f; const float omega1 = -0.159596235474f; const float d0 = 0.0759196200467f; const float d1 = -0.0217762490699f; const float c00 = 0.141189631152f; const float c10 = 0.0809701286525f; const float c01 = -0.281528535557f; const float c11 = 0.15384112876f; const float c20 = -0.178251207466f; const float c02 = 0.106959469314f; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != CSC) { if ((status = cscset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = cosphi; *yp = sinphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { l = costhe*(*xp); m = costhe*(*yp); n = sinthe; face = 0; zeta = n; if (l > zeta) { face = 1; zeta = l; } if (m > zeta) { face = 2; zeta = m; } if (-l > zeta) { face = 3; zeta = -l; } if (-m > zeta) { face = 4; zeta = -m; } if (-n > zeta) { face = 5; zeta = -n; } switch (face) { case 1: xi = m; eta = n; x0 = 0.0; y0 = 0.0; break; case 2: xi = -l; eta = n; x0 = 2.0; y0 = 0.0; break; case 3: xi = -m; eta = n; x0 = 4.0; y0 = 0.0; break; case 4: xi = l; eta = n; x0 = 6.0; y0 = 0.0; break; case 5: xi = m; eta = l; x0 = 0.0; y0 = -2.0; break; default: /* face == 0 */ xi = m; eta = -l; x0 = 0.0; y0 = 2.0; break; } chi = (float)( xi/zeta); psi = (float)(eta/zeta); chi2 = chi*chi; psi2 = psi*psi; chi2co = 1.0f - chi2; psi2co = 1.0f - psi2; /* Avoid floating underflows. */ chipsi = (float)fabs((double)(chi*psi)); chi4 = (chi2 > 1.0e-16f) ? chi2*chi2 : 0.0f; psi4 = (psi2 > 1.0e-16f) ? psi2*psi2 : 0.0f; chi2psi2 = (chipsi > 1.0e-16f) ? chi2*psi2 : 0.0f; xf = chi*(chi2 + chi2co*(gstar + psi2*(gamma*chi2co + mm*chi2 + psi2co*(c00 + c10*chi2 + c01*psi2 + c11*chi2psi2 + c20*chi4 + c02*psi4)) + chi2*(omega1 - chi2co*(d0 + d1*chi2)))); yf = psi*(psi2 + psi2co*(gstar + chi2*(gamma*psi2co + mm*psi2 + chi2co*(c00 + c10*psi2 + c01*chi2 + c11*chi2psi2 + c20*psi4 + c02*chi4)) + psi2*(omega1 - psi2co*(d0 + d1*psi2)))); istat = 0; if (fabs((double)xf) > 1.0) { if (fabs((double)xf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cscs2x"); } xf = (float)copysign(1.0, (double)xf); } if (fabs((double)yf) > 1.0) { if (fabs((double)yf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("cscs2x"); } yf = (float)copysign(1.0, (double)yf); } *xp = prj->w[0]*(xf + x0) - prj->x0; *yp = prj->w[0]*(yf + y0) - prj->y0; *(statp++) = istat; } } return status; } /*============================================================================ * QSC: quadrilaterilized spherical cube projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag QSC * prj->code "QSC" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/4) * prj->w[1] (4/pi)/r0 * prj->prjx2s Pointer to qscx2s(). * prj->prjs2x Pointer to qscs2x(). *===========================================================================*/ int qscset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = QSC; strcpy(prj->code, "QSC"); strcpy(prj->name, "quadrilateralized spherical cube"); prj->category = QUADCUBE; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 45.0; prj->w[1] = 1.0/45.0; } else { prj->w[0] = prj->r0*PI/4.0; prj->w[1] = 1.0/prj->w[0]; } prj->prjx2s = qscx2s; prj->prjs2x = qscs2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int qscx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int direct, face, mx, my, rowlen, rowoff, status; double cosw, l, m, n, omega, sinw, tau, xf, yf, w, zeco, zeta; const double tol = 1.0e-12; register int ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != QSC) { if ((status = qscset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xf = (*xp + prj->x0)*prj->w[1]; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xf; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yf = (*yp + prj->y0)*prj->w[1]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xf = *phip; /* Bounds checking. */ if (fabs(xf) <= 1.0) { if (fabs(yf) > 3.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("qscx2s"); continue; } } else { if (fabs(xf) > 7.0 || fabs(yf) > 1.0) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("qscx2s"); continue; } } /* Map negative faces to the other side. */ if (xf < -1.0) xf += 8.0; /* Determine the face. */ if (xf > 5.0) { face = 4; xf -= 6.0; } else if (xf > 3.0) { face = 3; xf -= 4.0; } else if (xf > 1.0) { face = 2; xf -= 2.0; } else if (yf > 1.0) { face = 0; yf -= 2.0; } else if (yf < -1.0) { face = 5; yf += 2.0; } else { face = 1; } direct = (fabs(xf) > fabs(yf)); if (direct) { if (xf == 0.0) { omega = 0.0; tau = 1.0; zeta = 1.0; zeco = 0.0; } else { w = 15.0*yf/xf; omega = sind(w)/(cosd(w) - SQRT2INV); tau = 1.0 + omega*omega; zeco = xf*xf*(1.0 - 1.0/sqrt(1.0 + tau)); zeta = 1.0 - zeco; } } else { if (yf == 0.0) { omega = 0.0; tau = 1.0; zeta = 1.0; zeco = 0.0; } else { w = 15.0*xf/yf; sincosd(w, &sinw, &cosw); omega = sinw/(cosw - SQRT2INV); tau = 1.0 + omega*omega; zeco = yf*yf*(1.0 - 1.0/sqrt(1.0 + tau)); zeta = 1.0 - zeco; } } if (zeta < -1.0) { if (zeta < -1.0-tol) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("qscx2s"); continue; } zeta = -1.0; zeco = 2.0; w = 0.0; } else { w = sqrt(zeco*(2.0-zeco)/tau); } switch (face) { case 1: l = zeta; if (direct) { m = w; if (xf < 0.0) m = -m; n = m*omega; } else { n = w; if (yf < 0.0) n = -n; m = n*omega; } break; case 2: m = zeta; if (direct) { l = w; if (xf > 0.0) l = -l; n = -l*omega; } else { n = w; if (yf < 0.0) n = -n; l = -n*omega; } break; case 3: l = -zeta; if (direct) { m = w; if (xf > 0.0) m = -m; n = -m*omega; } else { n = w; if (yf < 0.0) n = -n; m = -n*omega; } break; case 4: m = -zeta; if (direct) { l = w; if (xf < 0.0) l = -l; n = l*omega; } else { n = w; if (yf < 0.0) n = -n; l = n*omega; } break; case 5: n = -zeta; if (direct) { m = w; if (xf < 0.0) m = -m; l = m*omega; } else { l = w; if (yf < 0.0) l = -l; m = l*omega; } break; default: /* face == 0 */ n = zeta; if (direct) { m = w; if (xf < 0.0) m = -m; l = -m*omega; } else { l = w; if (yf > 0.0) l = -l; m = -l*omega; } break; } if (l == 0.0 && m == 0.0) { *phip = 0.0; } else { *phip = atan2d(m, l); } *thetap = asind(n); *(statp++) = 0; } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-13, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("qscx2s"); } return status; } /*--------------------------------------------------------------------------*/ int qscs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int face, mphi, mtheta, rowlen, rowoff, status; double cosphi, costhe, eta, l, m, n, omega, p, sinphi, sinthe, t, tau, x0, xf, xi, y0, yf, zeco, zeta; const double tol = 1.0e-12; register int iphi, istat, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != QSC) { if ((status = qscset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } status = 0; /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { sincosd(*phip, &sinphi, &cosphi); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { *xp = cosphi; *yp = sinphi; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sincosd(*thetap, &sinthe, &costhe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { if (fabs(*thetap) == 90.0) { *xp = -prj->x0; *yp = copysign(2.0*prj->w[0], *thetap) - prj->y0; *(statp++) = 0; continue; } l = costhe*(*xp); m = costhe*(*yp); n = sinthe; face = 0; zeta = n; if (l > zeta) { face = 1; zeta = l; } if (m > zeta) { face = 2; zeta = m; } if (-l > zeta) { face = 3; zeta = -l; } if (-m > zeta) { face = 4; zeta = -m; } if (-n > zeta) { face = 5; zeta = -n; } zeco = 1.0 - zeta; switch (face) { case 1: xi = m; eta = n; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (*thetap)*D2R; p = atan2(*yp, *xp); zeco = (p*p + t*t)/2.0; } x0 = 0.0; y0 = 0.0; break; case 2: xi = -l; eta = n; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (*thetap)*D2R; p = atan2(*yp, *xp) - PI/2.0; zeco = (p*p + t*t)/2.0; } x0 = 2.0; y0 = 0.0; break; case 3: xi = -m; eta = n; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (*thetap)*D2R; p = atan2(*yp, *xp); p -= copysign(PI, p); zeco = (p*p + t*t)/2.0; } x0 = 4.0; y0 = 0.0; break; case 4: xi = l; eta = n; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (*thetap)*D2R; p = atan2(*yp, *xp) + PI/2.0; zeco = (p*p + t*t)/2.0; } x0 = 6; y0 = 0.0; break; case 5: xi = m; eta = l; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (*thetap + 90.0)*D2R; zeco = t*t/2.0; } x0 = 0.0; y0 = -2; break; default: /* face == 0 */ xi = m; eta = -l; if (zeco < 1.0e-8) { /* Small angle formula. */ t = (90.0 - *thetap)*D2R; zeco = t*t/2.0; } x0 = 0.0; y0 = 2.0; break; } xf = 0.0; yf = 0.0; if (xi != 0.0 || eta != 0.0) { if (-xi > fabs(eta)) { omega = eta/xi; tau = 1.0 + omega*omega; xf = -sqrt(zeco/(1.0 - 1.0/sqrt(1.0+tau))); yf = (xf/15.0)*(atand(omega) - asind(omega/sqrt(tau+tau))); } else if (xi > fabs(eta)) { omega = eta/xi; tau = 1.0 + omega*omega; xf = sqrt(zeco/(1.0 - 1.0/sqrt(1.0+tau))); yf = (xf/15.0)*(atand(omega) - asind(omega/sqrt(tau+tau))); } else if (-eta >= fabs(xi)) { omega = xi/eta; tau = 1.0 + omega*omega; yf = -sqrt(zeco/(1.0 - 1.0/sqrt(1.0+tau))); xf = (yf/15.0)*(atand(omega) - asind(omega/sqrt(tau+tau))); } else if (eta >= fabs(xi)) { omega = xi/eta; tau = 1.0 + omega*omega; yf = sqrt(zeco/(1.0 - 1.0/sqrt(1.0+tau))); xf = (yf/15.0)*(atand(omega) - asind(omega/sqrt(tau+tau))); } } istat = 0; if (fabs(xf) > 1.0) { if (fabs(xf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("qscs2x"); } xf = copysign(1.0, xf); } if (fabs(yf) > 1.0) { if (fabs(yf) > 1.0+tol) { istat = 1; if (!status) status = PRJERR_BAD_WORLD_SET("qscs2x"); } yf = copysign(1.0, yf); } *xp = prj->w[0]*(xf + x0) - prj->x0; *yp = prj->w[0]*(yf + y0) - prj->y0; *(statp++) = istat; } } return status; } /*============================================================================ * HPX: HEALPix projection. * * Given: * prj->pv[1] H - the number of facets in longitude. * prj->pv[2] K - the number of facets in latitude * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag HPX * prj->code "HPX" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->m True if H is odd. * prj->n True if K is odd. * prj->w[0] r0*(pi/180) * prj->w[1] (180/pi)/r0 * prj->w[2] (K-1)/K * prj->w[3] 90*K/H * prj->w[4] (K+1)/2 * prj->w[5] 90*(K-1)/H * prj->w[6] 180/H * prj->w[7] H/360 * prj->w[8] r0*(pi/180)*(90*K/H) * prj->w[9] r0*(pi/180)*(180/H) * prj->prjx2s Pointer to hpxx2s(). * prj->prjs2x Pointer to hpxs2x(). *===========================================================================*/ int hpxset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = HPX; strcpy(prj->code, "HPX"); if (undefined(prj->pv[1])) prj->pv[1] = 4.0; if (undefined(prj->pv[2])) prj->pv[2] = 3.0; strcpy(prj->name, "HEALPix"); prj->category = HEALPIX; prj->pvrange = 102; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->pv[1] <= 0.0 || prj->pv[2] <= 0.0) { return PRJERR_BAD_PARAM_SET("hpxset"); } prj->m = ((int)(prj->pv[1]+0.5))%2; prj->n = ((int)(prj->pv[2]+0.5))%2; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = R2D/prj->r0; } prj->w[2] = (prj->pv[2] - 1.0) / prj->pv[2]; prj->w[3] = 90.0 * prj->pv[2] / prj->pv[1]; prj->w[4] = (prj->pv[2] + 1.0) / 2.0; prj->w[5] = 90.0 * (prj->pv[2] - 1.0) / prj->pv[1]; prj->w[6] = 180.0 / prj->pv[1]; prj->w[7] = prj->pv[1] / 360.0; prj->w[8] = prj->w[3] * prj->w[0]; prj->w[9] = prj->w[6] * prj->w[0]; prj->prjx2s = hpxx2s; prj->prjs2x = hpxs2x; return prjoff(prj, 0.0, 0.0); } /*--------------------------------------------------------------------------*/ int hpxx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int h, mx, my, offset, rowlen, rowoff, status; double absy, r, s, sigma, slim, t, ylim, yr; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != HPX) { if ((status = hpxset(prj))) return status; } slim = prj->w[6] + 1e-12; ylim = prj->w[9] * prj->w[4]; if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { s = prj->w[1] * (*xp + prj->x0); /* x_c for K odd or theta > 0. */ t = -180.0 + (2.0 * floor((*xp + 180.0) * prj->w[7]) + 1.0) * prj->w[6]; t = prj->w[1] * (*xp - t); phip = phi + rowoff; thetap = theta + rowoff; for (iy = 0; iy < my; iy++) { /* theta[] is used to hold (x - x_c). */ *phip = s; *thetap = t; phip += rowlen; thetap += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yr = prj->w[1]*(*yp + prj->y0); absy = fabs(yr); istat = 0; if (absy <= prj->w[5]) { /* Equatorial regime. */ t = asind(yr/prj->w[3]); for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { *thetap = t; *(statp++) = 0; } } else if (absy <= ylim) { /* Polar regime. */ offset = (prj->n || *yp > 0.0) ? 0 : 1; sigma = prj->w[4] - absy / prj->w[6]; if (sigma == 0.0) { s = 1e9; t = 90.0; } else { t = 1.0 - sigma*sigma/prj->pv[2]; if (t < -1.0) { s = 0.0; t = 0.0; istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("hpxx2s"); } else { s = 1.0/sigma; t = asind(t); } } if (*yp < 0.0) t = -t; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { if (offset) { /* Offset the southern polar half-facets for even K. */ h = (int)floor(*phip / prj->w[6]) + prj->m; if (h%2) { *thetap -= prj->w[6]; } else { *thetap += prj->w[6]; } } /* Recall that theta[] holds (x - x_c). */ r = s * *thetap; /* Bounds checking. */ if (prj->bounds&2) { if (slim <= fabs(r)) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("hpxx2s"); } } if (r != 0.0) r -= *thetap; *phip += r; *thetap = t; *(statp++) = istat; } } else { /* Beyond latitude range. */ for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { *phip = 0.0; *thetap = 0.0; *(statp++) = 1; } if (!status) status = PRJERR_BAD_PIX_SET("hpxx2s"); } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-12, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("hpxx2s"); } return status; } /*--------------------------------------------------------------------------*/ int hpxs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int h, mphi, mtheta, offset, rowlen, rowoff, status; double abssin, eta, sigma, sinthe, t, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != HPX) { if ((status = hpxset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { xi = prj->w[0] * (*phip) - prj->x0; /* phi_c for K odd or theta > 0. */ t = -180.0 + (2.0*floor((*phip+180.0) * prj->w[7]) + 1.0) * prj->w[6]; t = prj->w[0] * (*phip - t); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { /* y[] is used to hold (phi - phi_c). */ *xp = xi; *yp = t; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sinthe = sind(*thetap); abssin = fabs(sinthe); if (abssin <= prj->w[2]) { /* Equatorial regime. */ eta = prj->w[8] * sinthe - prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { *yp = eta; *(statp++) = 0; } } else { /* Polar regime. */ offset = (prj->n || *thetap > 0.0) ? 0 : 1; sigma = sqrt(prj->pv[2]*(1.0 - abssin)); xi = sigma - 1.0; eta = prj->w[9] * (prj->w[4] - sigma); if (*thetap < 0) eta = -eta; eta -= prj->y0; for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { if (offset) { /* Offset the southern polar half-facets for even K. */ h = (int)floor((*xp + prj->x0) / prj->w[9]) + prj->m; if (h%2) { *yp -= prj->w[9]; } else { *yp += prj->w[9]; } } /* Recall that y[] holds (phi - phi_c). */ *xp += *yp * xi; *yp = eta; *(statp++) = 0; /* Put the phi = 180 meridian in the expected place. */ if (180.0 < *xp) *xp = 360.0 - *xp; } } } return 0; } /*============================================================================ * XPH: HEALPix polar, aka "butterfly" projection. * * Given and/or returned: * prj->r0 Reset to 180/pi if 0. * prj->phi0 Reset to 0.0 if undefined. * prj->theta0 Reset to 0.0 if undefined. * * Returned: * prj->flag XPH * prj->code "XPH" * prj->x0 Fiducial offset in x. * prj->y0 Fiducial offset in y. * prj->w[0] r0*(pi/180)/sqrt(2) * prj->w[1] (180/pi)/r0/sqrt(2) * prj->w[2] 2/3 * prj->w[3] tol (= 1e-4) * prj->w[4] sqrt(2/3)*(180/pi) * prj->w[5] 90 - tol*sqrt(2/3)*(180/pi) * prj->w[6] sqrt(3/2)*(pi/180) * prj->prjx2s Pointer to xphx2s(). * prj->prjs2x Pointer to xphs2x(). *===========================================================================*/ int xphset(prj) struct prjprm *prj; { if (prj == 0x0) return PRJERR_NULL_POINTER; prj->flag = XPH; strcpy(prj->code, "XPH"); strcpy(prj->name, "butterfly"); prj->category = HEALPIX; prj->pvrange = 0; prj->simplezen = 0; prj->equiareal = 1; prj->conformal = 0; prj->global = 1; prj->divergent = 0; if (prj->r0 == 0.0) { prj->r0 = R2D; prj->w[0] = 1.0; prj->w[1] = 1.0; } else { prj->w[0] = prj->r0*D2R; prj->w[1] = R2D/prj->r0; } prj->w[0] /= sqrt(2.0); prj->w[1] /= sqrt(2.0); prj->w[2] = 2.0/3.0; prj->w[3] = 1e-4; prj->w[4] = sqrt(prj->w[2])*R2D; prj->w[5] = 90.0 - prj->w[3]*prj->w[4]; prj->w[6] = sqrt(1.5)*D2R; prj->prjx2s = xphx2s; prj->prjs2x = xphs2x; return prjoff(prj, 0.0, 90.0); } /*--------------------------------------------------------------------------*/ int xphx2s(prj, nx, ny, sxy, spt, x, y, phi, theta, stat) struct prjprm *prj; int nx, ny, sxy, spt; const double x[], y[]; double phi[], theta[]; int stat[]; { int mx, my, rowlen, rowoff, status; double abseta, eta, eta1, sigma, xi, xi1, xr, yr; const double tol = 1.0e-12; register int istat, ix, iy, *statp; register const double *xp, *yp; register double *phip, *thetap; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != XPH) { if ((status = xphset(prj))) return status; } if (ny > 0) { mx = nx; my = ny; } else { mx = 1; my = 1; ny = nx; } status = 0; /* Do x dependence. */ xp = x; rowoff = 0; rowlen = nx*spt; for (ix = 0; ix < nx; ix++, rowoff += spt, xp += sxy) { xr = (*xp + prj->x0)*prj->w[1]; phip = phi + rowoff; for (iy = 0; iy < my; iy++) { *phip = xr; phip += rowlen; } } /* Do y dependence. */ yp = y; phip = phi; thetap = theta; statp = stat; for (iy = 0; iy < ny; iy++, yp += sxy) { yr = (*yp + prj->y0)*prj->w[1]; for (ix = 0; ix < mx; ix++, phip += spt, thetap += spt) { xr = *phip; if (xr <= 0.0 && 0.0 < yr) { xi1 = -xr - yr; eta1 = xr - yr; *phip = -180.0; } else if (xr < 0.0 && yr <= 0.0) { xi1 = xr - yr; eta1 = xr + yr; *phip = -90.0; } else if (0.0 <= xr && yr < 0.0) { xi1 = xr + yr; eta1 = -xr + yr; *phip = 0.0; } else { xi1 = -xr + yr; eta1 = -xr - yr; *phip = 90.0; } xi = xi1 + 45.0; eta = eta1 + 90.0; abseta = fabs(eta); if (abseta <= 90.0) { if (abseta <= 45.0) { /* Equatorial regime. */ *phip += xi; *thetap = asind(eta/67.5); istat = 0; /* Bounds checking. */ if (prj->bounds&2) { if (45.0+tol < fabs(xi1)) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("xphx2s"); } } *(statp++) = istat; } else { /* Polar regime. */ sigma = (90.0 - abseta) / 45.0; /* Ensure an exact result for points on the boundary. */ if (xr == 0.0) { if (yr <= 0.0) { *phip = 0.0; } else { *phip = 180.0; } } else if (yr == 0.0) { if (xr < 0.0) { *phip = -90.0; } else { *phip = 90.0; } } else { *phip += 45.0 + xi1/sigma; } if (sigma < prj->w[3]) { *thetap = 90.0 - sigma*prj->w[4]; } else { *thetap = asind(1.0 - sigma*sigma/3.0); } if (eta < 0.0) *thetap = -(*thetap); /* Bounds checking. */ istat = 0; if (prj->bounds&2) { if (eta < -45.0 && eta+90.0+tol < fabs(xi1)) { istat = 1; if (!status) status = PRJERR_BAD_PIX_SET("xphx2s"); } } *(statp++) = istat; } } else { /* Beyond latitude range. */ *phip = 0.0; *thetap = 0.0; *(statp++) = 1; if (!status) status = PRJERR_BAD_PIX_SET("xphx2s"); } } } /* Do bounds checking on the native coordinates. */ if (prj->bounds&4 && prjbchk(1.0e-12, nx, my, spt, phi, theta, stat)) { if (!status) status = PRJERR_BAD_PIX_SET("xphx2s"); } return status; } /*--------------------------------------------------------------------------*/ int xphs2x(prj, nphi, ntheta, spt, sxy, phi, theta, x, y, stat) struct prjprm *prj; int nphi, ntheta, spt, sxy; const double phi[], theta[]; double x[], y[]; int stat[]; { int mphi, mtheta, rowlen, rowoff, status; double abssin, chi, eta, psi, sigma, sinthe, xi; register int iphi, itheta, *statp; register const double *phip, *thetap; register double *xp, *yp; /* Initialize. */ if (prj == 0x0) return PRJERR_NULL_POINTER; if (prj->flag != XPH) { if ((status = xphset(prj))) return status; } if (ntheta > 0) { mphi = nphi; mtheta = ntheta; } else { mphi = 1; mtheta = 1; ntheta = nphi; } /* Do phi dependence. */ phip = phi; rowoff = 0; rowlen = nphi*sxy; for (iphi = 0; iphi < nphi; iphi++, rowoff += sxy, phip += spt) { chi = *phip; if (180.0 <= fabs(chi)) { chi = fmod(chi, 360.0); if (chi < -180.0) { chi += 360.0; } else if (180.0 <= chi) { chi -= 360.0; } } /* phi is also recomputed from chi to avoid rounding problems. */ chi += 180.0; psi = fmod(chi, 90.0); xp = x + rowoff; yp = y + rowoff; for (itheta = 0; itheta < mtheta; itheta++) { /* y[] is used to hold phi (rounded). */ *xp = psi; *yp = chi - 180.0; xp += rowlen; yp += rowlen; } } /* Do theta dependence. */ thetap = theta; xp = x; yp = y; statp = stat; for (itheta = 0; itheta < ntheta; itheta++, thetap += spt) { sinthe = sind(*thetap); abssin = fabs(sinthe); for (iphi = 0; iphi < mphi; iphi++, xp += sxy, yp += sxy) { if (abssin <= prj->w[2]) { /* Equatorial regime. */ xi = *xp; eta = 67.5 * sinthe; } else { /* Polar regime. */ if (*thetap < prj->w[5]) { sigma = sqrt(3.0*(1.0 - abssin)); } else { sigma = (90.0 - *thetap)*prj->w[6]; } xi = 45.0 + (*xp - 45.0)*sigma; eta = 45.0 * (2.0 - sigma); if (*thetap < 0.0) eta = -eta; } xi -= 45.0; eta -= 90.0; /* Recall that y[] holds phi. */ if (*yp < -90.0) { *xp = prj->w[0]*(-xi + eta) - prj->x0; *yp = prj->w[0]*(-xi - eta) - prj->y0; } else if (*yp < 0.0) { *xp = prj->w[0]*(+xi + eta) - prj->x0; *yp = prj->w[0]*(-xi + eta) - prj->y0; } else if (*yp < 90.0) { *xp = prj->w[0]*( xi - eta) - prj->x0; *yp = prj->w[0]*( xi + eta) - prj->y0; } else { *xp = prj->w[0]*(-xi - eta) - prj->x0; *yp = prj->w[0]*( xi - eta) - prj->y0; } *(statp++) = 0; } } return 0; }
bsd-3-clause
mgrauer/midas3score
library/Zend/Service/DeveloperGarden/LocalSearch/SearchParameters.php
14725
<?php /** * 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://framework.zend.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 [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: SearchParameters.php 22662 2010-07-24 17:37:36Z mabe $ */ /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_LocalSearch_SearchParameters { /** * possible search parameters, incl. default values * * @var array */ private $_parameters = array( 'what' => null, 'dymwhat' => null, 'dymrelated' => null, 'hits' => null, 'collapse' => null, 'where' => null, 'dywhere' => null, 'radius' => null, 'lx' => null, 'ly' => null, 'rx' => null, 'ry' => null, 'transformgeocode' => null, 'sort' => null, 'spatial' => null, 'sepcomm' => null, 'filter' => null, // can be ONLINER or OFFLINER 'openingtime' => null, // can be now or HH::MM 'kategorie' => null, // @see http://www.suchen.de/kategorie-katalog 'site' => null, 'typ' => null, 'name' => null, 'page' => null, 'city' => null, 'plz' => null, 'strasse' => null, 'bundesland' => null, ); /** * possible collapse values * * @var array */ private $_possibleCollapseValues = array( true, false, 'ADDRESS_COMPANY', 'DOMAIN' ); /** * sets a new search word * alias for setWhat * * @param string $searchValue * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSearchValue($searchValue) { return $this->setWhat($searchValue); } /** * sets a new search word * * @param string $searchValue * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setWhat($searchValue) { $this->_parameters['what'] = $searchValue; return $this; } /** * enable the did you mean what feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanWhat() { $this->_parameters['dymwhat'] = 'true'; return $this; } /** * disable the did you mean what feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanWhat() { $this->_parameters['dymwhat'] = 'false'; return $this; } /** * enable the did you mean where feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanWhere() { $this->_parameters['dymwhere'] = 'true'; return $this; } /** * disable the did you mean where feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanWhere() { $this->_parameters['dymwhere'] = 'false'; return $this; } /** * enable did you mean related, if true Kihno will be corrected to Kino * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanRelated() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * diable did you mean related, if false Kihno will not be corrected to Kino * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanRelated() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * set the max result hits for this search * * @param integer $hits * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setHits($hits = 10) { // require_once 'Zend/Validate/Between.php'; $validator = new Zend_Validate_Between(0, 1000); if (!$validator->isValid($hits)) { $message = $validator->getMessages(); // require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['hits'] = $hits; return $this; } /** * If true, addresses will be collapsed for a single domain, common values * are: * ADDRESS_COMPANY – to collapse by address * DOMAIN – to collapse by domain (same like collapse=true) * false * * @param mixed $value * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setCollapse($value) { if (!in_array($value, $this->_possibleCollapseValues, true)) { // require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid value provided.'); } $this->_parameters['collapse'] = $value; return $this; } /** * set a specific search location * examples: * +47°54’53.10”, 11° 10’ 56.76” * 47°54’53.10;11°10’56.76” * 47.914750,11.182533 * +47.914750 ; +11.1824 * Darmstadt * Berlin * * @param string $where * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setWhere($where) { // require_once 'Zend/Validate/NotEmpty.php'; $validator = new Zend_Validate_NotEmpty(); if (!$validator->isValid($where)) { $message = $validator->getMessages(); // require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['where'] = $where; return $this; } /** * returns the defined search location (ie city, country) * * @return string */ public function getWhere() { return $this->_parameters['where']; } /** * enable the spatial search feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableSpatial() { $this->_parameters['spatial'] = 'true'; return $this; } /** * disable the spatial search feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableSpatial() { $this->_parameters['spatial'] = 'false'; return $this; } /** * sets spatial and the given radius for a circle search * * @param integer $radius * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setRadius($radius) { // require_once 'Zend/Validate/Int.php'; $validator = new Zend_Validate_Int(); if (!$validator->isValid($radius)) { $message = $validator->getMessages(); // require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['radius'] = $radius; $this->_parameters['transformgeocode'] = 'false'; return $this; } /** * sets the values for a rectangle search * lx = longitude left top * ly = latitude left top * rx = longitude right bottom * ry = latitude right bottom * * @param $lx * @param $ly * @param $rx * @param $ry * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setRectangle($lx, $ly, $rx, $ry) { $this->_parameters['lx'] = $lx; $this->_parameters['ly'] = $ly; $this->_parameters['rx'] = $rx; $this->_parameters['ry'] = $ry; return $this; } /** * if set, the service returns the zipcode for the result * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setTransformGeoCode() { $this->_parameters['transformgeocode'] = 'true'; $this->_parameters['radius'] = null; return $this; } /** * sets the sort value * possible values are: 'relevance' and 'distance' (only with spatial enabled) * * @param string $sort * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSort($sort) { if (!in_array($sort, array('relevance', 'distance'))) { // require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid sort value provided.'); } $this->_parameters['sort'] = $sort; return $this; } /** * enable the separation of phone numbers * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enablePhoneSeparation() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * disable the separation of phone numbers * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disablePhoneSeparation() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * if this filter is set, only results with a website are returned * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setFilterOnliner() { $this->_parameters['filter'] = 'ONLINER'; return $this; } /** * if this filter is set, only results without a website are returned * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setFilterOffliner() { $this->_parameters['filter'] = 'OFFLINER'; return $this; } /** * removes the filter value * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableFilter() { $this->_parameters['filter'] = null; return $this; } /** * set a filter to get just results who are open at the given time * possible values: * now = open right now * HH:MM = at the given time (ie 20:00) * * @param string $time * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setOpeningTime($time = null) { $this->_parameters['openingtime'] = $time; return $this; } /** * sets a category filter * * @see http://www.suchen.de/kategorie-katalog * @param $category * @return unknown_type */ public function setCategory($category = null) { $this->_parameters['kategorie'] = $category; return $this; } /** * sets the site filter * ie: www.developergarden.com * * @param string $site * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSite($site) { $this->_parameters['site'] = $site; return $this; } /** * sets a filter to the given document type * ie: pdf, html * * @param string $type * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setDocumentType($type) { $this->_parameters['typ'] = $type; return $this; } /** * sets a filter for the company name * ie: Deutsche Telekom * * @param string $name * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setName($name) { $this->_parameters['name'] = $name; return $this; } /** * sets a filter for the zip code * * @param string $zip * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setZipCode($zip) { $this->_parameters['plz'] = $zip; return $this; } /** * sets a filter for the street * * @param string $street * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setStreet($street) { $this->_parameters['strasse'] = $street; return $this; } /** * sets a filter for the county * * @param string $county * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setCounty($county) { $this->_parameters['bundesland'] = $county; return $this; } /** * sets a raw parameter with the value * * @param string $key * @param mixed $value * @return unknown_type */ public function setRawParameter($key, $value) { $this->_parameters[$key] = $value; return $this; } /** * returns the parameters as an array * * @return array */ public function getSearchParameters() { $retVal = array(); foreach ($this->_parameters as $key => $value) { if ($value === null) { continue; } $param = array( 'parameter' => $key, 'value' => $value ); $retVal[] = $param; } return $retVal; } }
bsd-3-clause
yelizariev/apivk
docs/com/serialization/json/package-detail.html
2976
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../../../style.css" type="text/css" media="screen"> <link rel="stylesheet" href="../../../print.css" type="text/css" media="print"> <title>com.serialization.json Summary</title> </head> <body> <script type="text/javascript" language="javascript" src="../../../asdoc.js"></script><script type="text/javascript" language="javascript" src="../../../cookies.js"></script><script type="text/javascript" language="javascript"> <!-- asdocTitle = 'com.serialization.json Package - Документация apivk'; var baseRef = '../../../'; window.onload = configPage; --></script> <table style="display:none" id="titleTable" cellspacing="0" cellpadding="0" class="titleTable"> <tr> <td align="left" class="titleTableTitle">apivk.googlecode.com</td><td align="right" class="titleTableTopNav"><a onclick="loadClassListFrame('../../../all-classes.html')" href="../../../package-summary.html">All&nbsp;Packages</a>&nbsp;|&nbsp;<a onclick="loadClassListFrame('../../../all-classes.html')" href="../../../class-summary.html">All&nbsp;Classes</a>&nbsp;|&nbsp;<a onclick="loadClassListFrame('../../../index-list.html')" href="../../../all-index-A.html">Index</a>&nbsp;|&nbsp;<a href="../../../index.html?com/serialization/json/package-detail.html&amp;com/serialization/json/class-list.html" id="framesLink1">Frames</a><a onclick="parent.location=document.location" href="" style="display:none" id="noFramesLink1">No&nbsp;Frames</a></td><td rowspan="3" align="right" class="titleTableLogo"><img alt="Adobe Logo" title="Adobe Logo" class="logoImage" src="../../../images/logo.jpg"></td> </tr> <tr class="titleTableRow2"> <td align="left" id="subTitle" class="titleTableSubTitle">Package&nbsp;com.serialization.json</td><td align="right" id="subNav" class="titleTableSubNav"><a href="package-detail.html#classSummary">Classes</a></td> </tr> <tr class="titleTableRow3"> <td colspan="2">&nbsp;</td> </tr> </table> <script type="text/javascript" language="javascript"> <!-- if (!isEclipse() || window.name != ECLIPSE_FRAME_NAME) {titleBar_setSubTitle("Package com.serialization.json"); titleBar_setSubNav(false,false,false,false,false,false,false,false,false,false,false,false,true,false);} --></script> <div class="MainContent"> <br> <br> <hr> <a name="classSummary"></a> <div class="summaryTableTitle">Classes</div> <table class="summaryTable" cellspacing="0" cellpadding="3"> <tr> <th>&nbsp;</th><th width="30%">Class</th><th width="70%">Description</th> </tr> <tr class="prow1"> <td class="summaryTablePaddingCol">&nbsp;</td><td class="summaryTableSecondCol"><a href="JSON.html">JSON</a></td><td class="summaryTableLastCol">&nbsp;</td> </tr> </table> <p></p> <div> <p></p> <center class="copyright">v. 2.0.8</center> </div> </div> </body> </html> <!--v. 2.0.8-->
bsd-3-clause
patrickm/chromium.src
content/browser/indexed_db/indexed_db_pending_connection.h
1195
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_INDEXED_DB_PENDING_CONNECTION_H_ #define CONTENT_BROWSER_INDEXED_DB_PENDING_CONNECTION_H_ #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "content/browser/indexed_db/indexed_db_callbacks.h" #include "content/browser/indexed_db/indexed_db_database_callbacks.h" #include "content/common/content_export.h" namespace content { class IndexedDBCallbacks; class IndexedDBDatabaseCallbacks; struct CONTENT_EXPORT IndexedDBPendingConnection { IndexedDBPendingConnection( scoped_refptr<IndexedDBCallbacks> callbacks_in, scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks_in, int child_process_id_in, int64 transaction_id_in, int64 version_in); ~IndexedDBPendingConnection(); scoped_refptr<IndexedDBCallbacks> callbacks; scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks; int child_process_id; int64 transaction_id; int64 version; }; } // namespace content #endif // CONTENT_BROWSER_INDEXED_DB_PENDING_CONNECTION_H_
bsd-3-clause
beiyuxinke/CONNECT
Product/Production/Adapters/General/CONNECTAdapterWeb/src/main/java/gov/hhs/fha/nhinc/adapter/deferred/queue/DeferredQueueTimerTask.java
4650
/* * Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services. * 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. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.adapter.deferred.queue; import gov.hhs.fha.nhinc.properties.PropertyAccessException; import gov.hhs.fha.nhinc.properties.PropertyAccessor; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.log4j.Logger; /** * This class is responsible for handling the work that is done each time the timer goes off; i.e. processing the * outstanding deferred queue request messages. * * @author richard.ettema */ public class DeferredQueueTimerTask { private static final Logger LOG = Logger.getLogger(DeferredQueueTimerTask.class); private static final String GATEWAY_PROPERTY_FILE = "gateway"; private static final String DEFERRED_QUEUE_SWITCH_PROPERTY = "DeferredQueueProcessActive"; protected void forceDeferredQueueProcess() { try { DeferredQueueManagerHelper helper = new DeferredQueueManagerHelper(); helper.forceProcess(); } catch (DeferredQueueException ex) { LOG.error("DeferredQueueTimerTask DeferredQueueException thrown.", ex); StringWriter stackTrace = new StringWriter(); ex.printStackTrace(new PrintWriter(stackTrace)); String sValue = stackTrace.toString(); if (sValue.indexOf("EJBClassLoader") >= 0) { DeferredQueueTimer timer = DeferredQueueTimer.getInstance(); timer.stopTimer(); } } } /** * This method is called each time the timer thread wakes up. */ public void run() { boolean bQueueActive = true; try { bQueueActive = PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, DEFERRED_QUEUE_SWITCH_PROPERTY); if (bQueueActive) { LOG.debug("Start: DeferredQueueTimerTask.run method - processing queue entries."); forceDeferredQueueProcess(); LOG.debug("Done: DeferredQueueTimerTask.run method - processing queue entries."); } else { LOG.debug("DeferredQueueTimerTask is disabled by the DeferredQueueRefreshActive property."); } } catch (PropertyAccessException ex) { LOG.error("DeferredQueueTimerTask.run method unable to read DeferredQueueRefreshActive property.", ex); } } /** * Main method used to test this class. This one really should not be run under unit test scenarios because it * requires access to the UDDI server. * * @param args */ public static void main(String[] args) { System.out.println("Starting test."); try { DeferredQueueTimerTask oTimerTask = new DeferredQueueTimerTask(); oTimerTask.run(); } catch (Exception e) { System.out.println("An unexpected exception occurred: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } System.out.println("End of test."); } }
bsd-3-clause
alunys/ApigilityAngularTest
vendor/zfcampus/zf-apigility-doctrine/test/src/Admin/Model/DoctrineMetadata1Test.php
4716
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZFTest\Apigility\Doctrine\Admin\Model; use ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceEntity; use ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceResource; use Doctrine\ORM\Tools\SchemaTool; use Zend\Http\Request; use Zend\Mvc\Router\RouteMatch; use Zend\Filter\FilterChain; class DoctrineMetadata1Test extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase { public function setUp() { $this->setApplicationConfig( include __DIR__ . '/../../../../../config/application.config.php' ); parent::setUp(); } public function tearDown() { # FIXME: Drop database from in-memory } /** * @see https://github.com/zfcampus/zf-apigility/issues/18 */ public function testDoctrineMetadataResource() { $serviceManager = $this->getApplication()->getServiceManager(); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $this->getRequest()->getHeaders()->addHeaders( array( 'Accept' => 'application/json', ) ); $this->dispatch( '/apigility/api/doctrine/doctrine.entitymanager.orm_default/metadata/Db%5CEntity%5CArtist', Request::METHOD_GET ); $body = json_decode($this->getResponse()->getBody(), true); $this->assertArrayHasKey('name', $body); $this->assertEquals('Db\Entity\Artist', $body['name']); $this->dispatch('/apigility/api/doctrine/doctrine.entitymanager.orm_default/metadata', Request::METHOD_GET); $body = json_decode($this->getResponse()->getBody(), true); $this->assertArrayHasKey('_embedded', $body); } public function testDoctrineService() { $serviceManager = $this->getApplication()->getServiceManager(); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $tool = new SchemaTool($em); $res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata()); // Create DB $resourceDefinition = array( "objectManager"=> "doctrine.entitymanager.orm_default", "serviceName" => "Artist", "entityClass" => "Db\\Entity\\Artist", "routeIdentifierName" => "artist_id", "entityIdentifierName" => "id", "routeMatch" => "/db-test/artist", ); $this->resource = $serviceManager->get('ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceResource'); $this->resource->setModuleName('DbApi'); $entity = $this->resource->create($resourceDefinition); $this->assertInstanceOf('ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceEntity', $entity); $controllerServiceName = $entity->controllerServiceName; $this->assertNotEmpty($controllerServiceName); $this->assertContains('DbApi\V1\Rest\Artist\Controller', $controllerServiceName); $filter = new FilterChain(); $filter->attachByName('WordCamelCaseToUnderscore') ->attachByName('StringToLower'); $em = $serviceManager->get('doctrine.entitymanager.orm_default'); $metadataFactory = $em->getMetadataFactory(); $entityMetadata = $metadataFactory->getMetadataFor("Db\\Entity\\Artist"); foreach ($entityMetadata->associationMappings as $mapping) { switch ($mapping['type']) { case 4: $rpcServiceResource = $serviceManager->get( 'ZF\Apigility\Doctrine\Admin\Model\DoctrineRpcServiceResource' ); $rpcServiceResource->setModuleName('DbApi'); $rpcServiceResource->create( array( 'service_name' => 'Artist' . $mapping['fieldName'], 'route' => '/db-test/artist[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]', 'http_methods' => array( 'GET', 'PUT', 'POST' ), 'options' => array( 'target_entity' => $mapping['targetEntity'], 'source_entity' => $mapping['sourceEntity'], 'field_name' => $mapping['fieldName'], ), 'selector' => 'custom selector', ) ); break; default: break; } } } }
bsd-3-clause
gx1997/chrome-loongson
third_party/webdriver/python/test/selenium/webdriver/common/correct_event_firing_tests.py
5540
#!/usr/bin/python # Copyright 2008-2010 WebDriver committers # Copyright 2008-2010 Google Inc. # # 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. import os import re import tempfile import time import shutil import unittest from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException def not_available_on_remote(func): def testMethod(self): print self.driver if type(self.driver) == 'remote': return lambda x: None else: return func(self) return testMethod class CorrectEventFiringTests(unittest.TestCase): def testShouldFireClickEventWhenClicking(self): self._loadPage("javascriptPage") self._clickOnElementWhichRecordsEvents() self._assertEventFired("click") def testShouldFireMouseDownEventWhenClicking(self): self._loadPage("javascriptPage") self._clickOnElementWhichRecordsEvents() self._assertEventFired("mousedown") def testShouldFireMouseUpEventWhenClicking(self): self._loadPage("javascriptPage") self._clickOnElementWhichRecordsEvents() self._assertEventFired("mouseup") def testShouldIssueMouseDownEvents(self): self._loadPage("javascriptPage") self.driver.find_element_by_id("mousedown").click() result = self.driver.find_element_by_id("result").text self.assertEqual(result, "mouse down") def testShouldIssueClickEvents(self): self._loadPage("javascriptPage") self.driver.find_element_by_id("mouseclick").click() result = self.driver.find_element_by_id("result").text self.assertEqual(result, "mouse click") def testShouldIssueMouseUpEvents(self): self._loadPage("javascriptPage") self.driver.find_element_by_id("mouseup").click() result = self.driver.find_element_by_id("result").text self.assertEqual(result, "mouse up") def testMouseEventsShouldBubbleUpToContainingElements(self): self._loadPage("javascriptPage") self.driver.find_element_by_id("child").click() result = self.driver.find_element_by_id("result").text self.assertEqual(result, "mouse down") def testShouldEmitOnChangeEventsWhenSelectingElements(self): self._loadPage("javascriptPage") # Intentionally not looking up the select tag. See selenium r7937 for details. allOptions = self.driver.find_elements_by_xpath("//select[@id='selector']//option") initialTextValue = self.driver.find_element_by_id("result").text foo = allOptions[0] bar = allOptions[1] foo.select() self.assertEqual(self.driver.find_element_by_id("result").text, initialTextValue) bar.select() self.assertEqual(self.driver.find_element_by_id("result").text, "bar") def testShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox(self): self._loadPage("javascriptPage") checkbox = self.driver.find_element_by_id("checkbox") checkbox.select() self.assertEqual(self.driver.find_element_by_id("result").text, "checkbox thing") def testShouldEmitClickEventWhenClickingOnATextInputElement(self): self._loadPage("javascriptPage") clicker = self.driver.find_element_by_id("clickField") clicker.click() self.assertEqual(clicker.value, "Clicked") def testClearingAnElementShouldCauseTheOnChangeHandlerToFire(self): self._loadPage("javascriptPage") element = self.driver.find_element_by_id("clearMe") element.clear() result = self.driver.find_element_by_id("result") self.assertEqual(result.text, "Cleared"); # TODO Currently Failing and needs fixing #def testSendingKeysToAnotherElementShouldCauseTheBlurEventToFire(self): # self._loadPage("javascriptPage") # element = self.driver.find_element_by_id("theworks") # element.send_keys("foo") # element2 = self.driver.find_element_by_id("changeable") # element2.send_keys("bar") # self._assertEventFired("blur") # TODO Currently Failing and needs fixing #def testSendingKeysToAnElementShouldCauseTheFocusEventToFire(self): # self._loadPage("javascriptPage") # element = self.driver.find_element_by_id("theworks") # element.send_keys("foo") # self._assertEventFired("focus") def _clickOnElementWhichRecordsEvents(self): self.driver.find_element_by_id("plainButton").click() def _assertEventFired(self, eventName): result = self.driver.find_element_by_id("result") text = result.text self.assertTrue(eventName in text, "No " + eventName + " fired: " + text) def _pageURL(self, name): return "http://localhost:%d/%s.html" % (self.webserver.port, name) def _loadSimplePage(self): self._loadPage("simpleTest") def _loadPage(self, name): self.driver.get(self._pageURL(name))
bsd-3-clause
endlessm/chromium-browser
chrome/browser/extensions/window_controller.cc
2365
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/window_controller.h" #include <stddef.h> #include <memory> #include "base/values.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/window_controller_list.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/windows.h" namespace extensions { /////////////////////////////////////////////////////////////////////////////// // WindowController // static WindowController::TypeFilter WindowController::GetAllWindowFilter() { // This needs to be updated if there is a change to // extensions::api::windows:WindowType. static_assert(api::windows::WINDOW_TYPE_LAST == 5, "Update extensions WindowController to match WindowType"); return ((1 << api::windows::WINDOW_TYPE_NORMAL) | (1 << api::windows::WINDOW_TYPE_PANEL) | (1 << api::windows::WINDOW_TYPE_POPUP) | (1 << api::windows::WINDOW_TYPE_APP) | (1 << api::windows::WINDOW_TYPE_DEVTOOLS)); } // static WindowController::TypeFilter WindowController::GetFilterFromWindowTypes( const std::vector<api::windows::WindowType>& types) { WindowController::TypeFilter filter = kNoWindowFilter; for (auto& window_type : types) filter |= 1 << window_type; return filter; } // static WindowController::TypeFilter WindowController::GetFilterFromWindowTypesValues( const base::ListValue* types) { WindowController::TypeFilter filter = WindowController::kNoWindowFilter; if (!types) return filter; for (size_t i = 0; i < types->GetSize(); i++) { std::string window_type; if (types->GetString(i, &window_type)) filter |= 1 << api::windows::ParseWindowType(window_type); } return filter; } WindowController::WindowController(ui::BaseWindow* window, Profile* profile) : window_(window), profile_(profile) { } WindowController::~WindowController() { } Browser* WindowController::GetBrowser() const { return NULL; } bool WindowController::MatchesFilter(TypeFilter filter) const { TypeFilter type = 1 << api::windows::ParseWindowType(GetWindowTypeText()); return (type & filter) != 0; } } // namespace extensions
bsd-3-clause
radiosity/reader
src/Pages.cpp
15805
/* Copyright (c) 2014, Richard Martin 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. * Neither the name of Richard Martin nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 RICHARD MARTIN 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 "Pages.hpp" #include <string> #include <list> #include <utility> #include <iostream> #include <pangomm/init.h> #include <boost/filesystem.hpp> #include <thread> #include <sqlite3.h> #include <cstdlib> #include "DrawingUtils.hpp" #include "Global.hpp" using namespace std; using namespace boost::filesystem; ///// PageContentItems first PageContentItem::PageContentItem(PageContentType _pct, ustring _content) : pct(_pct), content(_content) { } PageContentItem::PageContentItem(PageContentItem const & cpy) : pct(cpy.pct), content(cpy.content) { } PageContentItem::PageContentItem(PageContentItem && mv) : pct(move(mv.pct)), content(move(mv.content)) { } PageContentItem & PageContentItem::operator =(const PageContentItem & cpy) { pct = cpy.pct; content = cpy.content; return *this; } PageContentItem & PageContentItem::operator =(PageContentItem && mv) { pct = move(mv.pct); content = move(mv.content); return *this; } PageContentItem::~PageContentItem() { } // Page Descriptor next. PageDescriptor::PageDescriptor() : items() { } PageDescriptor::PageDescriptor::PageDescriptor(PageDescriptor const & cpy) : items(cpy.items) { } PageDescriptor::PageDescriptor(PageDescriptor && mv) : items(move(mv.items)) { } PageDescriptor & PageDescriptor::operator =(const PageDescriptor & cpy) { items = cpy.items; return *this; } PageDescriptor & PageDescriptor::operator =(PageDescriptor && mv) { items = move(mv.items); return *this; } PageDescriptor::~PageDescriptor() { } // Pages Pages::Pages() : mtx(), ready(), descriptors(), finished(false) { } Pages::~Pages() { } bool Pages::available(const unsigned int n) const { return n < descriptors.size(); } bool Pages::is_valid_index(const unsigned int n) { unique_lock<mutex> lck(mtx); if(finished) { return n < descriptors.size(); } else { return true; } } PageDescriptor Pages::get(const unsigned int n) { unique_lock<mutex> lck(mtx); if(available(n)) { //we have it return descriptors[n]; } else { //we don't have it while(!available(n)) { ready.wait(lck); } return descriptors[n]; } } void Pages::add(PageDescriptor p) { unique_lock<mutex> lck(mtx); descriptors.push_back(p); ready.notify_one(); } void Pages::set_finished_loading(bool val) { unique_lock<mutex> lck(mtx); finished = val; } bool Pages::finished_loading() { unique_lock<mutex> lck(mtx); return finished; } void Pages::clear() { unique_lock<mutex> lck(mtx); finished = false; descriptors.clear(); } // Now the Paginator iteself //anonymous namespace for epub loading and //sqlite loading helper functions namespace { void __load_epub(Pages & pages, path filename, path dbfilename) { unique_lock<mutex> import_lock(import_mtx); //Yield to the interface thread if this one is //executing first. std::this_thread::yield(); #ifdef DEBUG cout << "Loading Epub" << endl; #endif //So, first let's sort out the database sqlite3 * db; int rc; char * errmsg; rc = sqlite3_open(dbfilename.c_str(), &db); if( rc ) { //Failed to open } const string table_sql = "CREATE VIRTUAL TABLE book USING fts4(" \ "pagen INT NOT NULL," \ "descriptorid INT NOT NULL," \ "contenttype INT NOT NULL," \ "contentformatted TEXT NOT NULL," \ "contentstripped TEXT NOT NULL ) ;"; sqlite3_exec(db, table_sql.c_str(), NULL, NULL, &errmsg); //Table created. const string book_insert_sql = "INSERT INTO book (pagen, descriptorid, contenttype, contentformatted, contentstripped) VALUES (?, ?, ?, ?, ?);"; sqlite3_stmt * book_insert; rc = sqlite3_prepare_v2(db, book_insert_sql.c_str(), -1, &book_insert, 0); if(rc != SQLITE_OK && rc != SQLITE_DONE) { throw - 1; } //Do all the following inserts in an SQLite Transaction, because this speeds up the inserts like crazy. sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &errmsg); //Unpack the ebook Epub book(filename.c_str()); //Initialise Pango for the journey ahead. Pango::init(); unsigned int epub_content_index = 0; unsigned int epub_content_length = book.contents[0].items.size(); bool has_fragment = false; ustring fragment = ""; ustring fragment_stripped = ""; unsigned int pagenum = 0; unsigned int itemid = 0; for( ; epub_content_index < epub_content_length ; pagenum++) { //Create a new PageDescriptor to store the items we're going to create. PageDescriptor pd; #ifdef DEBUG cout << "Processing page " << pagenum << endl; #endif //reset the id counter itemid = 0; string filename = "pages/page"; filename += to_string(pagenum + 1); filename += ".png"; const int width = 600; const int height = 900; /* Cairo::RefPtr<Cairo::SvgSurface> surface = Cairo::SvgSurface::create(filename, width, height); Cairo::RefPtr<Cairo::Context> cr = Cairo::Context::create(surface); */ int stride; unsigned char * data; Cairo::RefPtr<Cairo::ImageSurface> surface; stride = Cairo::ImageSurface::format_stride_for_width (Cairo::Format::FORMAT_ARGB32, width); data = (unsigned char *) malloc (stride * height); surface = Cairo::ImageSurface::create (data, Cairo::Format::FORMAT_ARGB32, width, height, stride); Cairo::RefPtr<Cairo::Context> cr = Cairo::Context::create(surface); const int rectangle_width = width; const int rectangle_height = height; //cr->set_antialias(ANTIALIAS_BEST); cr->set_source_rgb(1.0, 1.0, 1.0); DrawingUtils::draw_rectangle(cr, rectangle_width, rectangle_height); auto it = book.opf_files[0].metadata.find(MetadataType::TITLE); const ustring title = it->second.contents; it = book.opf_files[0].metadata.find(MetadataType::CREATOR); const ustring author = it->second.contents; int start_pos = 0; cr->set_source_rgb(0.15, 0.15, 0.15); if(has_fragment) { sqlite3_bind_int(book_insert, 1, pagenum); sqlite3_bind_int(book_insert, 2, itemid); sqlite3_bind_int(book_insert, 3, PAGE_FRAGMENT); sqlite3_bind_text(book_insert, 4, fragment.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(book_insert, 5, fragment_stripped.c_str(), -1, SQLITE_STATIC); int result = sqlite3_step(book_insert); if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) { throw - 1; } sqlite3_reset(book_insert); pd.items.push_back(PageContentItem(PAGE_FRAGMENT, fragment)); has_fragment = false; start_pos += DrawingUtils::draw_fragment(cr, fragment, rectangle_width, rectangle_height, start_pos); fragment = ""; fragment_stripped = ""; itemid++; } while(epub_content_index < epub_content_length) { sqlite3_bind_int(book_insert, 1, pagenum); sqlite3_bind_int(book_insert, 2, itemid); const ContentItem c = book.contents[0].items[epub_content_index]; epub_content_index++; if(c.type == H1) { //There should be only one H1 on a page. To make sure //of this, we're going to push an H1 onto a new page the current //page contains any content, and then we're going to push a new page afterwards. if(pd.items.size() != 0) { epub_content_index--; break; } else { //I don't like people messing with formatting in headers. So here we're going to use //the stripped text for everything and remove the formatting sqlite3_bind_int(book_insert, 3, PAGE_H1); sqlite3_bind_text(book_insert, 4, c.stripped_content.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC); pd.items.push_back(PageContentItem(PAGE_H1, c.stripped_content)); start_pos += DrawingUtils::draw_h1(cr, c.stripped_content, rectangle_width, rectangle_height); //ensure that there's only one H1 on a page. break; } } else if (c.type == H2) { if(DrawingUtils::will_fit_h2(cr, c.content, rectangle_width, rectangle_height, start_pos)) { //I don't like people messing with formatting in headers. So here we're going to use //the stripped text for everything and remove the formatting sqlite3_bind_int(book_insert, 3, PAGE_H2); sqlite3_bind_text(book_insert, 4, c.stripped_content.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC); pd.items.push_back(PageContentItem(PAGE_H2, c.stripped_content)); // Only pack out the header when it's not the first thing in the page if (itemid != 0) { start_pos += 35; } start_pos += DrawingUtils::draw_h2(cr, c.stripped_content, rectangle_width, rectangle_height, start_pos); start_pos += 35; } else { epub_content_index--; break; } } else if (c.type == P) { //cout << c.content << endl; if(DrawingUtils::will_fit_text(cr, c.content, rectangle_width, rectangle_height, start_pos)) { sqlite3_bind_int(book_insert, 3, PAGE_PARAGRAPH); sqlite3_bind_text(book_insert, 4, c.content.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC); pd.items.push_back(PageContentItem(PAGE_PARAGRAPH, c.content)); start_pos += DrawingUtils::draw_text(cr, c.content, rectangle_width, rectangle_height, start_pos); } else { pair<ustring, ustring> packres = DrawingUtils::pack_text(cr, c.content, rectangle_width, rectangle_height, start_pos); fragment = packres.second; fragment_stripped = packres.second; // This doesn't work under all circumstances if(fragment.compare(c.content) == 0) { //can't pack the content. Go back one, and set a new page, so we do all this again. epub_content_index--; } else { has_fragment = true; pd.items.push_back(PageContentItem(PAGE_PARAGRAPH, packres.first)); sqlite3_bind_int(book_insert, 3, PAGE_PARAGRAPH); sqlite3_bind_text(book_insert, 4, packres.first.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(book_insert, 5, packres.first.c_str(), -1, SQLITE_STATIC); //We will need to break out of the loop under this condition, //but if we do then we haven't saved the info in the database. //So we have to go out of our way to save it here. int result = sqlite3_step(book_insert); if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) { throw - 1; } sqlite3_reset(book_insert); } break; } } else if (c.type == HR) { if(pd.items.size() == 0) { //If there's nothing on the page, then forcing a new page is unnecessary. //So we ignore it. continue; } else { break; } } int result = sqlite3_step(book_insert); if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) { throw - 1; } sqlite3_reset(book_insert); itemid++; } cr->set_source_rgb(0.5, 0.5, 0.5); DrawingUtils::draw_header(cr, rectangle_width, rectangle_height, title, pagenum); pages.add(pd); cr->show_page(); //surface->write_to_png(filename); free(data); } pages.set_finished_loading(true); const string book_optimise_sql = "INSERT INTO book(book) VALUES('optimize');"; sqlite3_stmt * book_optimise; rc = sqlite3_prepare_v2(db, book_optimise_sql.c_str(), -1, &book_optimise, 0); if(rc != SQLITE_OK && rc != SQLITE_DONE) { throw - 1; } rc = sqlite3_step(book_optimise); if(rc != SQLITE_OK && rc != SQLITE_DONE) { throw - 1; } sqlite3_finalize(book_optimise); sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &errmsg); sqlite3_finalize(book_insert); sqlite3_close(db); info_bar_hide_dispatcher.emit(); #ifdef DEBUG cout << "Done Loading Epub" << endl; #endif } void __load_sqlite(Pages & pages, path filename) { unique_lock<mutex> import_lck(import_mtx); //Yield to the interface thread if this one is //executing first. std::this_thread::yield(); #ifdef DEBUG cout << "Loading SQLite" << endl; #endif sqlite3 * db; int rc; rc = sqlite3_open(filename.c_str(), &db); if( rc ) { //Failed to open } const string book_select_sql = "SELECT * FROM book ORDER BY pagen, descriptorid"; sqlite3_stmt * book_select; rc = sqlite3_prepare_v2(db, book_select_sql.c_str(), -1, &book_select, 0); if(rc != SQLITE_OK && rc != SQLITE_DONE) { throw - 1; } rc = sqlite3_step(book_select); PageDescriptor pd; int currentpagen = 0; while ( rc == SQLITE_ROW ) { int pagen = sqlite3_column_int(book_select, 0); //int descriptorn = sqlite3_column_int(book_select, 1); int contenttype = sqlite3_column_int(book_select, 2); ustring content = ustring((char *)sqlite3_column_text(book_select, 3)); if(pagen != currentpagen) { //New page! wrap up the old page. currentpagen = pagen; pages.add(pd); pd = PageDescriptor(); } PageContentType pct = static_cast<PageContentType>(contenttype); pd.items.push_back(PageContentItem(pct, content)); //cout << content << endl; rc = sqlite3_step(book_select); } if ( rc == SQLITE_ERROR) { cout << "Database Error " << endl; } pages.add(pd); pages.set_finished_loading(true); sqlite3_finalize(book_select); sqlite3_close(db); #ifdef DEBUG cout << "Done Loading SQLite" << endl; #endif } } //end of anonymous namespace void Paginator::load(Pages & pages, string filename) { //OK, time for heavy lifting; path file = path(filename); if(!exists(file)) { //do something } path fn = file.filename(); path dbfn("."); dbfn += fn; dbfn += path(".db"); path databasefile = fn.parent_path(); databasefile /= dbfn; #ifdef DEBUG cout << databasefile << endl; #endif if(!exists(databasefile)) { //Urgh. we need to load the whole thing from the damn EPUB file. thread t(__load_epub, ref(pages), file, databasefile); t.detach(); } else { //Good, we can load from SQLite and we don't have to do any parsing. //thread t(__load_sqlite, ref(pages), databasefile); //t.detach(); __load_sqlite(pages, databasefile); } }
bsd-3-clause
cjh1/vtkmodular
Wrapping/Python/vtk/test/Testing.py
17259
""" This module attempts to make it easy to create VTK-Python unittests. The module uses unittest for the test interface. For more documentation on what unittests are and how to use them, please read these: http://www.python.org/doc/current/lib/module-unittest.html http://www.diveintopython.org/roman_divein.html This VTK-Python test module supports image based tests with multiple images per test suite and multiple images per individual test as well. It also prints information appropriate for Dart (http://public.kitware.com/Dart/). This module defines several useful classes and functions to make writing tests easy. The most important of these are: class vtkTest: Subclass this for your tests. It also has a few useful internal functions that can be used to do some simple blackbox testing. compareImage(renwin, img_fname, threshold=10): Compares renwin with image and generates image if it does not exist. The threshold determines how closely the images must match. The function also handles multiple images and finds the best matching image. compareImageWithSavedImage(src_img, img_fname, threshold=10): Compares given source image (in the form of a vtkImageData) with saved image and generates the image if it does not exist. The threshold determines how closely the images must match. The function also handles multiple images and finds the best matching image. getAbsImagePath(img_basename): Returns the full path to the image given the basic image name. main(cases): Does the testing given a list of tuples containing test classes and the starting string of the functions used for testing. interact(): Interacts with the user if necessary. The behavior of this is rather trivial and works best when using Tkinter. It does not do anything by default and stops to interact with the user when given the appropriate command line arguments. isInteractive(): If interact() is not good enough, use this to find if the mode is interactive or not and do whatever is necessary to generate an interactive view. Examples: The best way to learn on how to use this module is to look at a few examples. The end of this file contains a trivial example. Please also look at the following examples: Rendering/Testing/Python/TestTkRenderWidget.py, Rendering/Testing/Python/TestTkRenderWindowInteractor.py Created: September, 2002 Prabhu Ramachandran <[email protected]> """ import sys, os, time import os.path import unittest, getopt import vtk import BlackBox # location of the VTK data files. Set via command line args or # environment variable. VTK_DATA_ROOT = "" # location of the VTK baseline images. Set via command line args or # environment variable. VTK_BASELINE_ROOT = "" # location of the VTK difference images for failed tests. Set via # command line args or environment variable. VTK_TEMP_DIR = "" # Verbosity of the test messages (used by unittest) _VERBOSE = 0 # Determines if it is necessary to interact with the user. If zero # dont interact if 1 interact. Set via command line args _INTERACT = 0 # This will be set to 1 when the image test will not be performed. # This option is used internally by the script and set via command # line arguments. _NO_IMAGE = 0 class vtkTest(unittest.TestCase): """A simple default VTK test class that defines a few useful blackbox tests that can be readily used. Derive your test cases from this class and use the following if you'd like to. Note: Unittest instantiates this class (or your subclass) each time it tests a method. So if you do not want that to happen when generating VTK pipelines you should create the pipeline in the class definition as done below for _blackbox. """ _blackbox = BlackBox.Tester(debug=0) # Due to what seems to be a bug in python some objects leak. # Avoid the exit-with-error in vtkDebugLeaks. dl = vtk.vtkDebugLeaks() dl.SetExitError(0) dl = None def _testParse(self, obj): """Does a blackbox test by attempting to parse the class for its various methods using vtkMethodParser. This is a useful test because it gets all the methods of the vtkObject, parses them and sorts them into different classes of objects.""" self._blackbox.testParse(obj) def _testGetSet(self, obj, excluded_methods=[]): """Checks the Get/Set method pairs by setting the value using the current state and making sure that it equals the value it was originally. This effectively calls _testParse internally. """ self._blackbox.testGetSet(obj, excluded_methods) def _testBoolean(self, obj, excluded_methods=[]): """Checks the Boolean methods by setting the value on and off and making sure that the GetMethod returns the the set value. This effectively calls _testParse internally. """ self._blackbox.testBoolean(obj, excluded_methods) def interact(): """Interacts with the user if necessary. """ global _INTERACT if _INTERACT: raw_input("\nPress Enter/Return to continue with the testing. --> ") def isInteractive(): """Returns if the currently chosen mode is interactive or not based on command line options.""" return _INTERACT def getAbsImagePath(img_basename): """Returns the full path to the image given the basic image name.""" global VTK_BASELINE_ROOT return os.path.join(VTK_BASELINE_ROOT, img_basename) def _getTempImagePath(img_fname): x = os.path.join(VTK_TEMP_DIR, os.path.split(img_fname)[1]) return os.path.abspath(x) def compareImageWithSavedImage(src_img, img_fname, threshold=10): """Compares a source image (src_img, which is a vtkImageData) with the saved image file whose name is given in the second argument. If the image file does not exist the image is generated and stored. If not the source image is compared to that of the figure. This function also handles multiple images and finds the best matching image. """ global _NO_IMAGE if _NO_IMAGE: return f_base, f_ext = os.path.splitext(img_fname) if not os.path.isfile(img_fname): # generate the image pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(img_fname)) pngw.SetInputData(src_img) pngw.Write() return pngr = vtk.vtkPNGReader() pngr.SetFileName(img_fname) idiff = vtk.vtkImageDifference() idiff.SetInputData(src_img) idiff.SetImageConnection(pngr.GetOutputPort()) min_err = idiff.GetThresholdedError() img_err = min_err best_img = img_fname err_index = 0 count = 0 if min_err > threshold: count = 1 test_failed = 1 err_index = -1 while 1: # keep trying images till we get the best match. new_fname = f_base + "_%d.png"%count if not os.path.exists(new_fname): # no other image exists. break # since file exists check if it matches. pngr.SetFileName(new_fname) pngr.Update() idiff.Update() alt_err = idiff.GetThresholdedError() if alt_err < threshold: # matched, err_index = count test_failed = 0 min_err = alt_err img_err = alt_err best_img = new_fname break else: if alt_err < min_err: # image is a better match. err_index = count min_err = alt_err img_err = alt_err best_img = new_fname count = count + 1 # closes while loop. if test_failed: _handleFailedImage(idiff, pngr, best_img) # Print for Dart. _printDartImageError(img_err, err_index, f_base) msg = "Failed image test: %f\n"%idiff.GetThresholdedError() raise AssertionError, msg # output the image error even if a test passed _printDartImageSuccess(img_err, err_index) def compareImage(renwin, img_fname, threshold=10): """Compares renwin's (a vtkRenderWindow) contents with the image file whose name is given in the second argument. If the image file does not exist the image is generated and stored. If not the image in the render window is compared to that of the figure. This function also handles multiple images and finds the best matching image. """ global _NO_IMAGE if _NO_IMAGE: return w2if = vtk.vtkWindowToImageFilter() w2if.ReadFrontBufferOff() w2if.SetInput(renwin) return compareImageWithSavedImage(w2if.GetOutput(), img_fname, threshold) def _printDartImageError(img_err, err_index, img_base): """Prints the XML data necessary for Dart.""" img_base = _getTempImagePath(img_base) print "Failed image test with error: %f"%img_err print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">", print "%f </DartMeasurement>"%img_err if err_index <= 0: print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>", else: print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">", print "%d </DartMeasurement>"%err_index print "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.png') print "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.diff.png') print "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.valid.png') def _printDartImageSuccess(img_err, err_index): "Prints XML data for Dart when image test succeeded." print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">", print "%f </DartMeasurement>"%img_err if err_index <= 0: print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>", else: print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">", print "%d </DartMeasurement>"%err_index def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write the difference image gamma adjusted for the dashboard. gamma = vtk.vtkImageShiftScale() gamma.SetInputConnection(idiff.GetOutputPort()) gamma.SetShift(0) gamma.SetScale(10) pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInputConnection(gamma.GetOutputPort()) pngw.Write() # Write out the image that was generated. Write it out as full so that # it may be used as a baseline image if the tester deems it valid. pngw.SetInputConnection(idiff.GetInputConnection(0,0)) pngw.SetFileName(_getTempImagePath(f_base + ".png")) pngw.Write() # write out the valid image that matched. pngw.SetInputConnection(idiff.GetInputConnection(1,0)) pngw.SetFileName(_getTempImagePath(f_base + ".valid.png")) pngw.Write() def main(cases): """ Pass a list of tuples containing test classes and the starting string of the functions used for testing. Example: main ([(vtkTestClass, 'test'), (vtkTestClass1, 'test')]) """ processCmdLine() timer = vtk.vtkTimerLog() s_time = timer.GetCPUTime() s_wall_time = time.time() # run the tests result = test(cases) tot_time = timer.GetCPUTime() - s_time tot_wall_time = float(time.time() - s_wall_time) # output measurements for Dart print "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">", print " %f </DartMeasurement>"%tot_wall_time print "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">", print " %f </DartMeasurement>"%tot_time # Delete these to eliminate debug leaks warnings. del cases, timer if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) def test(cases): """ Pass a list of tuples containing test classes and the functions used for testing. It returns a unittest._TextTestResult object. Example: test = test_suite([(vtkTestClass, 'test'), (vtkTestClass1, 'test')]) """ # Make the test suites from the arguments. suites = [] for case in cases: suites.append(unittest.makeSuite(case[0], case[1])) test_suite = unittest.TestSuite(suites) # Now run the tests. runner = unittest.TextTestRunner(verbosity=_VERBOSE) result = runner.run(test_suite) return result def usage(): msg="""Usage:\nTestScript.py [options]\nWhere options are:\n -D /path/to/VTKData --data-dir /path/to/VTKData Directory containing VTK Data use for tests. If this option is not set via the command line the environment variable VTK_DATA_ROOT is used. If the environment variable is not set the value defaults to '../../../../VTKData'. -B /path/to/valid/image_dir/ --baseline-root /path/to/valid/image_dir/ This is a path to the directory containing the valid images for comparison. If this option is not set via the command line the environment variable VTK_BASELINE_ROOT is used. If the environment variable is not set the value defaults to the same value set for -D (--data-dir). -T /path/to/valid/temporary_dir/ --temp-dir /path/to/valid/temporary_dir/ This is a path to the directory where the image differences are written. If this option is not set via the command line the environment variable VTK_TEMP_DIR is used. If the environment variable is not set the value defaults to '../../../Testing/Temporary'. -v level --verbose level Sets the verbosity of the test runner. Valid values are 0, 1, and 2 in increasing order of verbosity. -I --interact Interacts with the user when chosen. If this is not chosen the test will run and exit as soon as it is finished. When enabled, the behavior of this is rather trivial and works best when the test uses Tkinter. -n --no-image Does not do any image comparisons. This is useful if you want to run the test and not worry about test images or image failures etc. -h --help Prints this message. """ return msg def parseCmdLine(): arguments = sys.argv[1:] options = "B:D:T:v:hnI" long_options = ['baseline-root=', 'data-dir=', 'temp-dir=', 'verbose=', 'help', 'no-image', 'interact'] try: opts, args = getopt.getopt(arguments, options, long_options) except getopt.error, msg: print usage() print '-'*70 print msg sys.exit (1) return opts, args def processCmdLine(): opts, args = parseCmdLine() global VTK_DATA_ROOT, VTK_BASELINE_ROOT, VTK_TEMP_DIR global _VERBOSE, _NO_IMAGE, _INTERACT # setup defaults try: VTK_DATA_ROOT = os.environ['VTK_DATA_ROOT'] except KeyError: VTK_DATA_ROOT = os.path.normpath("../../../../VTKData") try: VTK_BASELINE_ROOT = os.environ['VTK_BASELINE_ROOT'] except KeyError: pass try: VTK_TEMP_DIR = os.environ['VTK_TEMP_DIR'] except KeyError: VTK_TEMP_DIR = os.path.normpath("../../../Testing/Temporary") for o, a in opts: if o in ('-D', '--data-dir'): VTK_DATA_ROOT = os.path.abspath(a) if o in ('-B', '--baseline-root'): VTK_BASELINE_ROOT = os.path.abspath(a) if o in ('-T', '--temp-dir'): VTK_TEMP_DIR = os.path.abspath(a) if o in ('-n', '--no-image'): _NO_IMAGE = 1 if o in ('-I', '--interact'): _INTERACT = 1 if o in ('-v', '--verbose'): try: _VERBOSE = int(a) except: msg="Verbosity should be an integer. 0, 1, 2 are valid." print msg sys.exit(1) if o in ('-h', '--help'): print usage() sys.exit() if not VTK_BASELINE_ROOT: # default value. VTK_BASELINE_ROOT = VTK_DATA_ROOT if __name__ == "__main__": ###################################################################### # A Trivial test case to illustrate how this module works. class SampleTest(vtkTest): obj = vtk.vtkActor() def testParse(self): "Test if class is parseable" self._testParse(self.obj) def testGetSet(self): "Testing Get/Set methods" self._testGetSet(self.obj) def testBoolean(self): "Testing Boolean methods" self._testBoolean(self.obj) # Test with the above trivial sample test. main( [ (SampleTest, 'test') ] )
bsd-3-clause
busypeoples/reactcards.js
docs/WritingCards.md
2264
#Writing Cards #### Basic Example ```javascript import React from 'react' import cards from 'reactcards' import {Foo, Bar} from './components' const demo = cards('demo') demo.card( `## markdown doc you can use markdown for card documentation - foo - bar`, <Foo message="hello"/> ) demo.card(<Foo message="hello world"/>) demo.card(<Bar/>, {title: 'a bar card'}) ``` ![card](/assets/images/component.png) #### Creating a Stateful Component ```javascript import React from 'react' import cards from 'reactcards' import {StatefulCounter} from './components' const demo = cards('demo') demo.card( `## Counter This is a stateful counter. If you change the value prop in the source file it will not update because the new prop will be ignored and instead the component local state is rendered. Implement *componentWillReceiveProps* and override the component local state if you want this to work as expected.`, <StatefulCounter value={42}/> ) ``` ![card with stateful component](/assets/images/component_state.png) #### Displaying a Component With Undo/Redo ```javascript import React from 'react' import cards from 'reactcards' import {StatelessCounter} from './components' const demo = cards('demo') demo.card( `## Undo/Redo Same example as before but with undo/redo controls added by the card.`, (state) => <StatelessCounter value={state.get()} inc={() => state.update(x => x + 1)} dec={() => state.update(x => x - 1)}/>, { init: 1337, history:true, } ) ``` ![card with stateful component and undo/redo](/assets/images/component_state_undo_redo.png) ## Writing Tests ```javascript // your test file... import {assert} from 'chai' export function testAdd() { assert.equal(1 + 1, 2) } export function testFail() { assert.isTrue(false) } // your reactcards file import React from 'react' import cards from 'reactcards' import someTests from './testFile' const demo = cards('demo') demo.test(someTests, {title:'simple tests'}) ``` You can write tests in a separate folder or write them directly inside a card. The first enables us to reuse the test in a different setting. More information regarding testing very soon. ![test card](/assets/images/component_test.png)
bsd-3-clause
khajaamin/vishwashantiseva
backend/views/plans/_search.php
706
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\PlansSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="plans-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'id') ?> <?= $form->field($model, 'name') ?> <?= $form->field($model, 'price') ?> <?= $form->field($model, 'days') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
bsd-3-clause
oesteban/tract_querier
setup.py
1691
#!/usr/bin/env python from distutils.core import setup DISTNAME = 'tract_querier' DESCRIPTION = \ 'WMQL: Query language for automatic tract extraction from '\ 'full-brain tractographies with '\ 'a registered template on top of them' LONG_DESCRIPTION = open('README.md').read() MAINTAINER = 'Demian Wassermann' MAINTAINER_EMAIL = '[email protected]' URL = 'http://demianw.github.io/tract_querier' LICENSE = open('license.rst').read() DOWNLOAD_URL = 'https://github.com/demianw/tract_querier' VERSION = '0.1' def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(quiet=True) config.add_subpackage('tract_querier') return config if __name__ == "__main__": setup( name=DISTNAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, license=LICENSE, url=URL, version=VERSION, download_url=DOWNLOAD_URL, long_description=LONG_DESCRIPTION, requires=[ 'numpy(>=1.6)', 'nibabel(>=1.3)' ], classifiers=[ 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS' ], scripts=[ 'scripts/tract_querier', 'scripts/tract_math' ], **(configuration().todict()) )
bsd-3-clause
MakeNowJust/highlight.js
src/languages/brainfuck.js
792
/* Language: Brainfuck Author: Evgeny Stepanischev <[email protected]> Website: https://esolangs.org/wiki/Brainfuck */ function(hljs){ var LITERAL = { className: 'literal', begin: '[\\+\\-]', relevance: 0 }; return { aliases: ['bf'], contains: [ hljs.COMMENT( '[^\\[\\]\\.,\\+\\-<> \r\n]', '[\\[\\]\\.,\\+\\-<> \r\n]', { returnEnd: true, relevance: 0 } ), { className: 'title', begin: '[\\[\\]]', relevance: 0 }, { className: 'string', begin: '[\\.,]', relevance: 0 }, { // this mode works as the only relevance counter begin: /(?:\+\+|\-\-)/, contains: [LITERAL] }, LITERAL ] }; }
bsd-3-clause
Rathilesh/FMS_V1
protected/views/generic_Flex_Value/create.php
439
<?php /* @var $this Generic_Flex_ValueController */ /* @var $model Generic_Flex_Value */ $this->breadcrumbs=array( 'Generic Flex Values'=>array('index'), 'Create', ); $this->menu=array( array('label'=>'List Generic_Flex_Value', 'url'=>array('index')), array('label'=>'Manage Generic_Flex_Value', 'url'=>array('admin')), ); ?> <h1>Create Generic_Flex_Value</h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
bsd-3-clause
cboy868/lion
modules/shop/views/admin/mix-cate/update.php
374
<div class="page-content"> <!-- /section:settings.box --> <div class="page-content-area"> <div class="row"> <div class="col-xs-12 mix-cate-update"> <?= $this->render('_form', [ 'model' => $model, ]) ?> <div class="hr hr-18 dotted hr-double"></div> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.page-content-area --> </div>
bsd-3-clause
start-jsk/jsk_apc
demos/instance_occlsegm/tests/datasets_tests/apc_tests/arc2017_tests/jsk_tests/check_jsk_arc2017_v1_dataset.py
222
if __name__ == '__main__': import instance_occlsegm_lib dataset = instance_occlsegm_lib.datasets.apc.arc2017.JskARC2017DatasetV1( 'train') instance_occlsegm_lib.datasets.view_class_seg_dataset(dataset)
bsd-3-clause
CoherentLabs/depot_tools
tests/gclient_eval_unittest.py
35099
#!/usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import itertools import logging import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from third_party import schema import metrics_utils # We have to disable monitoring before importing gclient. metrics_utils.COLLECT_METRICS = False import gclient import gclient_eval import gclient_utils class GClientEvalTest(unittest.TestCase): def test_str(self): self.assertEqual('foo', gclient_eval._gclient_eval('"foo"')) def test_tuple(self): self.assertEqual(('a', 'b'), gclient_eval._gclient_eval('("a", "b")')) def test_list(self): self.assertEqual(['a', 'b'], gclient_eval._gclient_eval('["a", "b"]')) def test_dict(self): self.assertEqual({'a': 'b'}, gclient_eval._gclient_eval('{"a": "b"}')) def test_name_safe(self): self.assertEqual(True, gclient_eval._gclient_eval('True')) def test_name_unsafe(self): with self.assertRaises(ValueError) as cm: gclient_eval._gclient_eval('UnsafeName') self.assertIn('invalid name \'UnsafeName\'', str(cm.exception)) def test_invalid_call(self): with self.assertRaises(ValueError) as cm: gclient_eval._gclient_eval('Foo("bar")') self.assertIn('Str and Var are the only allowed functions', str(cm.exception)) def test_expands_vars(self): self.assertEqual( 'foo', gclient_eval._gclient_eval('Var("bar")', vars_dict={'bar': 'foo'})) self.assertEqual( 'baz', gclient_eval._gclient_eval( 'Var("bar")', vars_dict={'bar': gclient_eval.ConstantString('baz')})) def test_expands_vars_with_braces(self): self.assertEqual( 'foo', gclient_eval._gclient_eval('"{bar}"', vars_dict={'bar': 'foo'})) self.assertEqual( 'baz', gclient_eval._gclient_eval( '"{bar}"', vars_dict={'bar': gclient_eval.ConstantString('baz')})) def test_invalid_var(self): with self.assertRaises(KeyError) as cm: gclient_eval._gclient_eval('"{bar}"', vars_dict={}) self.assertIn('bar was used as a variable, but was not declared', str(cm.exception)) def test_plus(self): self.assertEqual('foo', gclient_eval._gclient_eval('"f" + "o" + "o"')) def test_format(self): self.assertEqual('foo', gclient_eval._gclient_eval('"%s" % "foo"')) def test_not_expression(self): with self.assertRaises(SyntaxError) as cm: gclient_eval._gclient_eval('def foo():\n pass') self.assertIn('invalid syntax', str(cm.exception)) def test_not_whitelisted(self): with self.assertRaises(ValueError) as cm: gclient_eval._gclient_eval('[x for x in [1, 2, 3]]') self.assertIn( 'unexpected AST node: <_ast.ListComp object', str(cm.exception)) def test_dict_ordered(self): for test_case in itertools.permutations(range(4)): input_data = ['{'] + ['"%s": "%s",' % (n, n) for n in test_case] + ['}'] expected = [(str(n), str(n)) for n in test_case] result = gclient_eval._gclient_eval(''.join(input_data)) self.assertEqual(expected, list(result.items())) class ExecTest(unittest.TestCase): def test_multiple_assignment(self): with self.assertRaises(ValueError) as cm: gclient_eval.Exec('a, b, c = "a", "b", "c"') self.assertIn( 'invalid assignment: target should be a name', str(cm.exception)) def test_override(self): with self.assertRaises(ValueError) as cm: gclient_eval.Exec('a = "a"\na = "x"') self.assertIn( 'invalid assignment: overrides var \'a\'', str(cm.exception)) def test_schema_wrong_type(self): with self.assertRaises(gclient_utils.Error): gclient_eval.Exec('include_rules = {}') def test_recursedeps_list(self): local_scope = gclient_eval.Exec( 'recursedeps = [["src/third_party/angle", "DEPS.chromium"]]') self.assertEqual( {'recursedeps': [['src/third_party/angle', 'DEPS.chromium']]}, local_scope) def test_var(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', ' "baz": Str("quux")', '}', 'deps = {', ' "a_dep": "a" + Var("foo") + "b" + Var("baz"),', '}', ])) Str = gclient_eval.ConstantString self.assertEqual({ 'vars': {'foo': 'bar', 'baz': Str('quux')}, 'deps': {'a_dep': 'abarbquux'}, }, local_scope) def test_braces_var(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', ' "baz": Str("quux")', '}', 'deps = {', ' "a_dep": "a{foo}b{baz}",', '}', ])) Str = gclient_eval.ConstantString self.assertEqual({ 'vars': {'foo': 'bar', 'baz': Str('quux')}, 'deps': {'a_dep': 'abarbquux'}, }, local_scope) def test_empty_deps(self): local_scope = gclient_eval.Exec('deps = {}') self.assertEqual({'deps': {}}, local_scope) def test_overrides_vars(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', ' "quux": Str("quuz")', '}', 'deps = {', ' "a_dep": "a{foo}b",', ' "b_dep": "c{quux}d",', '}', ]), vars_override={'foo': 'baz', 'quux': 'corge'}) Str = gclient_eval.ConstantString self.assertEqual({ 'vars': {'foo': 'bar', 'quux': Str('quuz')}, 'deps': {'a_dep': 'abazb', 'b_dep': 'ccorged'}, }, local_scope) def test_doesnt_override_undeclared_vars(self): with self.assertRaises(KeyError) as cm: gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', '}', 'deps = {', ' "a_dep": "a{baz}b",', '}', ]), vars_override={'baz': 'lalala'}) self.assertIn('baz was used as a variable, but was not declared', str(cm.exception)) def test_doesnt_allow_duplicate_deps(self): with self.assertRaises(ValueError) as cm: gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": {', ' "url": "a_url@a_rev",', ' "condition": "foo",', ' },', ' "a_dep": {', ' "url": "a_url@another_rev",', ' "condition": "not foo",', ' }', '}', ]), '<unknown>') self.assertIn('duplicate key in dictionary: a_dep', str(cm.exception)) class UpdateConditionTest(unittest.TestCase): def test_both_present(self): info = {'condition': 'foo'} gclient_eval.UpdateCondition(info, 'and', 'bar') self.assertEqual(info, {'condition': '(foo) and (bar)'}) info = {'condition': 'foo'} gclient_eval.UpdateCondition(info, 'or', 'bar') self.assertEqual(info, {'condition': '(foo) or (bar)'}) def test_one_present_and(self): # If one of info's condition or new_condition is present, and |op| == 'and' # then the the result must be the present condition. info = {'condition': 'foo'} gclient_eval.UpdateCondition(info, 'and', None) self.assertEqual(info, {'condition': 'foo'}) info = {} gclient_eval.UpdateCondition(info, 'and', 'bar') self.assertEqual(info, {'condition': 'bar'}) def test_both_absent_and(self): # Nothing happens info = {} gclient_eval.UpdateCondition(info, 'and', None) self.assertEqual(info, {}) def test_or(self): # If one of info's condition and new_condition is not present, then there # shouldn't be a condition. An absent value is treated as implicitly True. info = {'condition': 'foo'} gclient_eval.UpdateCondition(info, 'or', None) self.assertEqual(info, {}) info = {} gclient_eval.UpdateCondition(info, 'or', 'bar') self.assertEqual(info, {}) info = {} gclient_eval.UpdateCondition(info, 'or', None) self.assertEqual(info, {}) class EvaluateConditionTest(unittest.TestCase): def test_true(self): self.assertTrue(gclient_eval.EvaluateCondition('True', {})) def test_variable(self): self.assertFalse(gclient_eval.EvaluateCondition('foo', {'foo': 'False'})) def test_variable_cyclic_reference(self): with self.assertRaises(ValueError) as cm: self.assertTrue(gclient_eval.EvaluateCondition('bar', {'bar': 'bar'})) self.assertIn( 'invalid cyclic reference to \'bar\' (inside \'bar\')', str(cm.exception)) def test_operators(self): self.assertFalse(gclient_eval.EvaluateCondition( 'a and not (b or c)', {'a': 'True', 'b': 'False', 'c': 'True'})) def test_expansion(self): self.assertTrue(gclient_eval.EvaluateCondition( 'a or b', {'a': 'b and c', 'b': 'not c', 'c': 'False'})) def test_string_equality(self): self.assertTrue(gclient_eval.EvaluateCondition( 'foo == "baz"', {'foo': '"baz"'})) self.assertFalse(gclient_eval.EvaluateCondition( 'foo == "bar"', {'foo': '"baz"'})) def test_string_inequality(self): self.assertTrue(gclient_eval.EvaluateCondition( 'foo != "bar"', {'foo': '"baz"'})) self.assertFalse(gclient_eval.EvaluateCondition( 'foo != "baz"', {'foo': '"baz"'})) def test_triple_or(self): self.assertTrue(gclient_eval.EvaluateCondition( 'a or b or c', {'a': 'False', 'b': 'False', 'c': 'True'})) self.assertFalse(gclient_eval.EvaluateCondition( 'a or b or c', {'a': 'False', 'b': 'False', 'c': 'False'})) def test_triple_and(self): self.assertTrue(gclient_eval.EvaluateCondition( 'a and b and c', {'a': 'True', 'b': 'True', 'c': 'True'})) self.assertFalse(gclient_eval.EvaluateCondition( 'a and b and c', {'a': 'True', 'b': 'True', 'c': 'False'})) def test_triple_and_and_or(self): self.assertTrue(gclient_eval.EvaluateCondition( 'a and b and c or d or e', {'a': 'False', 'b': 'False', 'c': 'False', 'd': 'False', 'e': 'True'})) self.assertFalse(gclient_eval.EvaluateCondition( 'a and b and c or d or e', {'a': 'True', 'b': 'True', 'c': 'False', 'd': 'False', 'e': 'False'})) def test_string_bool(self): self.assertFalse(gclient_eval.EvaluateCondition( 'false_str_var and true_var', {'false_str_var': 'False', 'true_var': True})) def test_string_bool_typo(self): with self.assertRaises(ValueError) as cm: gclient_eval.EvaluateCondition( 'false_var_str and true_var', {'false_str_var': 'False', 'true_var': True}) self.assertIn( 'invalid "and" operand \'false_var_str\' ' '(inside \'false_var_str and true_var\')', str(cm.exception)) def test_non_bool_in_or(self): with self.assertRaises(ValueError) as cm: gclient_eval.EvaluateCondition( 'string_var or true_var', {'string_var': 'Kittens', 'true_var': True}) self.assertIn( 'invalid "or" operand \'Kittens\' ' '(inside \'string_var or true_var\')', str(cm.exception)) def test_non_bool_in_and(self): with self.assertRaises(ValueError) as cm: gclient_eval.EvaluateCondition( 'string_var and true_var', {'string_var': 'Kittens', 'true_var': True}) self.assertIn( 'invalid "and" operand \'Kittens\' ' '(inside \'string_var and true_var\')', str(cm.exception)) def test_tuple_presence(self): self.assertTrue(gclient_eval.EvaluateCondition( 'foo in ("bar", "baz")', {'foo': 'bar'})) self.assertFalse(gclient_eval.EvaluateCondition( 'foo in ("bar", "baz")', {'foo': 'not_bar'})) def test_unsupported_tuple_operation(self): with self.assertRaises(ValueError) as cm: gclient_eval.EvaluateCondition('foo == ("bar", "baz")', {'foo': 'bar'}) self.assertIn('unexpected AST node', str(cm.exception)) with self.assertRaises(ValueError) as cm: gclient_eval.EvaluateCondition('(foo,) == "bar"', {'foo': 'bar'}) self.assertIn('unexpected AST node', str(cm.exception)) def test_str_in_condition(self): Str = gclient_eval.ConstantString self.assertTrue(gclient_eval.EvaluateCondition( 's_var == "foo"', {'s_var': Str("foo")})) self.assertFalse(gclient_eval.EvaluateCondition( 's_var in ("baz", "quux")', {'s_var': Str("foo")})) class VarTest(unittest.TestCase): def assert_adds_var(self, before, after): local_scope = gclient_eval.Exec('\n'.join(before)) gclient_eval.AddVar(local_scope, 'baz', 'lemur') results = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(results, '\n'.join(after)) def test_adds_var(self): before = [ 'vars = {', ' "foo": "bar",', '}', ] after = [ 'vars = {', ' "baz": "lemur",', ' "foo": "bar",', '}', ] self.assert_adds_var(before, after) def test_adds_var_twice(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', '}', ])) gclient_eval.AddVar(local_scope, 'baz', 'lemur') gclient_eval.AddVar(local_scope, 'v8_revision', 'deadbeef') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'vars = {', ' "v8_revision": "deadbeef",', ' "baz": "lemur",', ' "foo": "bar",', '}', ])) def test_gets_and_sets_var(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": "bar",', ' "quux": Str("quuz")', '}', ])) self.assertEqual(gclient_eval.GetVar(local_scope, 'foo'), "bar") self.assertEqual(gclient_eval.GetVar(local_scope, 'quux'), "quuz") gclient_eval.SetVar(local_scope, 'foo', 'baz') gclient_eval.SetVar(local_scope, 'quux', 'corge') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'vars = {', ' "foo": "baz",', ' "quux": Str("corge")', '}', ])) def test_gets_and_sets_var_non_string(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "foo": True,', '}', ])) result = gclient_eval.GetVar(local_scope, 'foo') self.assertEqual(result, True) gclient_eval.SetVar(local_scope, 'foo', 'False') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'vars = {', ' "foo": False,', '}', ])) def test_add_preserves_formatting(self): before = [ '# Copyright stuff', '# some initial comments', '', 'vars = { ', ' # Some comments.', ' "foo": "bar",', '', ' # More comments.', ' # Even more comments.', ' "v8_revision": ', ' "deadbeef",', ' # Someone formatted this wrong', '}', ] after = [ '# Copyright stuff', '# some initial comments', '', 'vars = { ', ' "baz": "lemur",', ' # Some comments.', ' "foo": "bar",', '', ' # More comments.', ' # Even more comments.', ' "v8_revision": ', ' "deadbeef",', ' # Someone formatted this wrong', '}', ] self.assert_adds_var(before, after) def test_set_preserves_formatting(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' # Comment with trailing space ', ' "foo": \'bar\',', '}', ])) gclient_eval.SetVar(local_scope, 'foo', 'baz') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'vars = {', ' # Comment with trailing space ', ' "foo": \'baz\',', '}', ])) class CipdTest(unittest.TestCase): def test_gets_and_sets_cipd(self): local_scope = gclient_eval.Exec('\n'.join([ 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "some/cipd/package",', ' "version": "deadbeef",', ' },', ' {', ' "package": "another/cipd/package",', ' "version": "version:5678",', ' },', ' ],', ' "condition": "checkout_android",', ' "dep_type": "cipd",', ' },', '}', ])) self.assertEqual( gclient_eval.GetCIPD( local_scope, 'src/cipd/package', 'some/cipd/package'), 'deadbeef') self.assertEqual( gclient_eval.GetCIPD( local_scope, 'src/cipd/package', 'another/cipd/package'), 'version:5678') gclient_eval.SetCIPD( local_scope, 'src/cipd/package', 'another/cipd/package', 'version:6789') gclient_eval.SetCIPD( local_scope, 'src/cipd/package', 'some/cipd/package', 'foobar') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "some/cipd/package",', ' "version": "foobar",', ' },', ' {', ' "package": "another/cipd/package",', ' "version": "version:6789",', ' },', ' ],', ' "condition": "checkout_android",', ' "dep_type": "cipd",', ' },', '}', ])) def test_gets_and_sets_cipd_vars(self): local_scope = gclient_eval.Exec('\n'.join([ 'vars = {', ' "cipd-rev": "git_revision:deadbeef",', ' "another-cipd-rev": "version:1.0.3",', '}', 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "some/cipd/package",', ' "version": Var("cipd-rev"),', ' },', ' {', ' "package": "another/cipd/package",', ' "version": "{another-cipd-rev}",', ' },', ' ],', ' "condition": "checkout_android",', ' "dep_type": "cipd",', ' },', '}', ])) self.assertEqual( gclient_eval.GetCIPD( local_scope, 'src/cipd/package', 'some/cipd/package'), 'git_revision:deadbeef') self.assertEqual( gclient_eval.GetCIPD( local_scope, 'src/cipd/package', 'another/cipd/package'), 'version:1.0.3') gclient_eval.SetCIPD( local_scope, 'src/cipd/package', 'another/cipd/package', 'version:1.1.0') gclient_eval.SetCIPD( local_scope, 'src/cipd/package', 'some/cipd/package', 'git_revision:foobar') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'vars = {', ' "cipd-rev": "git_revision:foobar",', ' "another-cipd-rev": "version:1.1.0",', '}', 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "some/cipd/package",', ' "version": Var("cipd-rev"),', ' },', ' {', ' "package": "another/cipd/package",', ' "version": "{another-cipd-rev}",', ' },', ' ],', ' "condition": "checkout_android",', ' "dep_type": "cipd",', ' },', '}', ])) def test_preserves_escaped_vars(self): local_scope = gclient_eval.Exec('\n'.join([ 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "package/${{platform}}",', ' "version": "version:abcd",', ' },', ' ],', ' "dep_type": "cipd",', ' },', '}', ])) gclient_eval.SetCIPD( local_scope, 'src/cipd/package', 'package/${platform}', 'version:dcba') result = gclient_eval.RenderDEPSFile(local_scope) self.assertEqual(result, '\n'.join([ 'deps = {', ' "src/cipd/package": {', ' "packages": [', ' {', ' "package": "package/${{platform}}",', ' "version": "version:dcba",', ' },', ' ],', ' "dep_type": "cipd",', ' },', '}', ])) class RevisionTest(unittest.TestCase): def assert_gets_and_sets_revision(self, before, after, rev_before='deadbeef'): local_scope = gclient_eval.Exec('\n'.join(before)) result = gclient_eval.GetRevision(local_scope, 'src/dep') self.assertEqual(result, rev_before) gclient_eval.SetRevision(local_scope, 'src/dep', 'deadfeed') self.assertEqual('\n'.join(after), gclient_eval.RenderDEPSFile(local_scope)) def test_revision(self): before = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@deadbeef",', '}', ] after = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@deadfeed",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_revision_new_line(self): before = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@"', ' + "deadbeef",', '}', ] after = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@"', ' + "deadfeed",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_revision_windows_local_path(self): before = [ 'deps = {', ' "src/dep": "file:///C:\\\\path.git@deadbeef",', '}', ] after = [ 'deps = {', ' "src/dep": "file:///C:\\\\path.git@deadfeed",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_revision_multiline_strings(self): deps = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@"', ' "deadbeef",', '}', ] with self.assertRaises(ValueError) as e: local_scope = gclient_eval.Exec('\n'.join(deps)) gclient_eval.SetRevision(local_scope, 'src/dep', 'deadfeed') self.assertEqual( 'Can\'t update value for src/dep. Multiline strings and implicitly ' 'concatenated strings are not supported.\n' 'Consider reformatting the DEPS file.', str(e.exception)) def test_revision_implicitly_concatenated_strings(self): deps = [ 'deps = {', ' "src/dep": "https://example.com" + "/dep.git@" "deadbeef",', '}', ] with self.assertRaises(ValueError) as e: local_scope = gclient_eval.Exec('\n'.join(deps)) gclient_eval.SetRevision(local_scope, 'src/dep', 'deadfeed') self.assertEqual( 'Can\'t update value for src/dep. Multiline strings and implicitly ' 'concatenated strings are not supported.\n' 'Consider reformatting the DEPS file.', str(e.exception)) def test_revision_inside_dict(self): before = [ 'deps = {', ' "src/dep": {', ' "url": "https://example.com/dep.git@deadbeef",', ' "condition": "some_condition",', ' },', '}', ] after = [ 'deps = {', ' "src/dep": {', ' "url": "https://example.com/dep.git@deadfeed",', ' "condition": "some_condition",', ' },', '}', ] self.assert_gets_and_sets_revision(before, after) def test_follows_var_braces(self): before = [ 'vars = {', ' "dep_revision": "deadbeef",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git@{dep_revision}",', '}', ] after = [ 'vars = {', ' "dep_revision": "deadfeed",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git@{dep_revision}",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_follows_var_braces_newline(self): before = [ 'vars = {', ' "dep_revision": "deadbeef",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git"', ' + "@{dep_revision}",', '}', ] after = [ 'vars = {', ' "dep_revision": "deadfeed",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git"', ' + "@{dep_revision}",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_follows_var_function(self): before = [ 'vars = {', ' "dep_revision": "deadbeef",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git@" + Var("dep_revision"),', '}', ] after = [ 'vars = {', ' "dep_revision": "deadfeed",', '}', 'deps = {', ' "src/dep": "https://example.com/dep.git@" + Var("dep_revision"),', '}', ] self.assert_gets_and_sets_revision(before, after) def test_pins_revision(self): before = [ 'deps = {', ' "src/dep": "https://example.com/dep.git",', '}', ] after = [ 'deps = {', ' "src/dep": "https://example.com/dep.git@deadfeed",', '}', ] self.assert_gets_and_sets_revision(before, after, rev_before=None) def test_preserves_variables(self): before = [ 'vars = {', ' "src_root": "src"', '}', 'deps = {', ' "{src_root}/dep": "https://example.com/dep.git@deadbeef",', '}', ] after = [ 'vars = {', ' "src_root": "src"', '}', 'deps = {', ' "{src_root}/dep": "https://example.com/dep.git@deadfeed",', '}', ] self.assert_gets_and_sets_revision(before, after) def test_preserves_formatting(self): before = [ 'vars = {', ' # Some comment on deadbeef ', ' "dep_revision": "deadbeef",', '}', 'deps = {', ' "src/dep": {', ' "url": "https://example.com/dep.git@" + Var("dep_revision"),', '', ' "condition": "some_condition",', ' },', '}', ] after = [ 'vars = {', ' # Some comment on deadbeef ', ' "dep_revision": "deadfeed",', '}', 'deps = {', ' "src/dep": {', ' "url": "https://example.com/dep.git@" + Var("dep_revision"),', '', ' "condition": "some_condition",', ' },', '}', ] self.assert_gets_and_sets_revision(before, after) class ParseTest(unittest.TestCase): def callParse(self, vars_override=None): return gclient_eval.Parse('\n'.join([ 'vars = {', ' "foo": "bar",', '}', 'deps = {', ' "a_dep": "a{foo}b",', '}', ]), '<unknown>', vars_override) def test_supports_vars_inside_vars(self): deps_file = '\n'.join([ 'vars = {', ' "foo": "bar",', ' "baz": "\\"{foo}\\" == \\"bar\\"",', '}', 'deps = {', ' "src/baz": {', ' "url": "baz_url",', ' "condition": "baz",', ' },', '}', ]) local_scope = gclient_eval.Parse(deps_file, '<unknown>', None) self.assertEqual({ 'vars': {'foo': 'bar', 'baz': '"bar" == "bar"'}, 'deps': {'src/baz': {'url': 'baz_url', 'dep_type': 'git', 'condition': 'baz'}}, }, local_scope) def test_has_builtin_vars(self): builtin_vars = {'builtin_var': 'foo'} deps_file = '\n'.join([ 'deps = {', ' "a_dep": "a{builtin_var}b",', '}', ]) local_scope = gclient_eval.Parse(deps_file, '<unknown>', None, builtin_vars) self.assertEqual({ 'deps': {'a_dep': {'url': 'afoob', 'dep_type': 'git'}}, }, local_scope) def test_declaring_builtin_var_has_no_effect(self): builtin_vars = {'builtin_var': 'foo'} deps_file = '\n'.join([ 'vars = {', ' "builtin_var": "bar",', '}', 'deps = {', ' "a_dep": "a{builtin_var}b",', '}', ]) local_scope = gclient_eval.Parse(deps_file, '<unknown>', None, builtin_vars) self.assertEqual({ 'vars': {'builtin_var': 'bar'}, 'deps': {'a_dep': {'url': 'afoob', 'dep_type': 'git'}}, }, local_scope) def test_override_builtin_var(self): builtin_vars = {'builtin_var': 'foo'} vars_override = {'builtin_var': 'override'} deps_file = '\n'.join([ 'deps = {', ' "a_dep": "a{builtin_var}b",', '}', ]) local_scope = gclient_eval.Parse( deps_file, '<unknown>', vars_override, builtin_vars) self.assertEqual({ 'deps': {'a_dep': {'url': 'aoverrideb', 'dep_type': 'git'}}, }, local_scope, str(local_scope)) def test_expands_vars(self): local_scope = self.callParse() self.assertEqual({ 'vars': {'foo': 'bar'}, 'deps': {'a_dep': {'url': 'abarb', 'dep_type': 'git'}}, }, local_scope) def test_overrides_vars(self): local_scope = self.callParse(vars_override={'foo': 'baz'}) self.assertEqual({ 'vars': {'foo': 'bar'}, 'deps': {'a_dep': {'url': 'abazb', 'dep_type': 'git'}}, }, local_scope) def test_no_extra_vars(self): deps_file = '\n'.join([ 'vars = {', ' "foo": "bar",', '}', 'deps = {', ' "a_dep": "a{baz}b",', '}', ]) with self.assertRaises(KeyError) as cm: gclient_eval.Parse(deps_file, '<unknown>', {'baz': 'lalala'}) self.assertIn('baz was used as a variable, but was not declared', str(cm.exception)) def test_standardizes_deps_string_dep(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": "a_url@a_rev",', '}', ]), '<unknown>') self.assertEqual({ 'deps': {'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git'}}, }, local_scope) def test_standardizes_deps_dict_dep(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": {', ' "url": "a_url@a_rev",', ' "condition": "checkout_android",', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': {'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git', 'condition': 'checkout_android'}}, }, local_scope) def test_ignores_none_in_deps_os(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": "a_url@a_rev",', '}', 'deps_os = {', ' "mac": {', ' "a_dep": None,', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': {'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git'}}, }, local_scope) def test_merges_deps_os_extra_dep(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": "a_url@a_rev",', '}', 'deps_os = {', ' "mac": {', ' "b_dep": "b_url@b_rev"', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': {'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git'}, 'b_dep': {'url': 'b_url@b_rev', 'dep_type': 'git', 'condition': 'checkout_mac'}}, }, local_scope) def test_merges_deps_os_existing_dep_with_no_condition(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": "a_url@a_rev",', '}', 'deps_os = {', ' "mac": {', ' "a_dep": "a_url@a_rev"', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': {'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git'}}, }, local_scope) def test_merges_deps_os_existing_dep_with_condition(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": {', ' "url": "a_url@a_rev",', ' "condition": "some_condition",', ' },', '}', 'deps_os = {', ' "mac": {', ' "a_dep": "a_url@a_rev"', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': { 'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git', 'condition': '(checkout_mac) or (some_condition)'}, }, }, local_scope) def test_merges_deps_os_multiple_os(self): local_scope = gclient_eval.Parse('\n'.join([ 'deps_os = {', ' "win": {' ' "a_dep": "a_url@a_rev"', ' },', ' "mac": {', ' "a_dep": "a_url@a_rev"', ' },', '}', ]), '<unknown>') self.assertEqual({ 'deps': { 'a_dep': {'url': 'a_url@a_rev', 'dep_type': 'git', 'condition': '(checkout_mac) or (checkout_win)'}, }, }, local_scope) def test_fails_to_merge_same_dep_with_different_revisions(self): with self.assertRaises(gclient_eval.gclient_utils.Error) as cm: gclient_eval.Parse('\n'.join([ 'deps = {', ' "a_dep": {', ' "url": "a_url@a_rev",', ' "condition": "some_condition",', ' },', '}', 'deps_os = {', ' "mac": {', ' "a_dep": "a_url@b_rev"', ' },', '}', ]), '<unknown>') self.assertIn('conflicts with existing deps', str(cm.exception)) def test_merges_hooks_os(self): local_scope = gclient_eval.Parse('\n'.join([ 'hooks = [', ' {', ' "action": ["a", "action"],', ' },', ']', 'hooks_os = {', ' "mac": [', ' {', ' "action": ["b", "action"]', ' },', ' ]', '}', ]), '<unknown>') self.assertEqual({ "hooks": [{"action": ["a", "action"]}, {"action": ["b", "action"], "condition": "checkout_mac"}], }, local_scope) if __name__ == '__main__': level = logging.DEBUG if '-v' in sys.argv else logging.FATAL logging.basicConfig( level=level, format='%(asctime).19s %(levelname)s %(filename)s:' '%(lineno)s %(message)s') unittest.main()
bsd-3-clause
hugozap/polymer-practice
dist/elements/interact-wrapper.html
98
<script type="text/javascript" src='../bower_components/interact/dist/interact.min.js'></script>
bsd-3-clause
CBIIT/caaers
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/AutocompleterField.java
962
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.web.rule; /** * @author Rhett Sutphin */ public class AutocompleterField extends AbstractInputField { public AutocompleterField() { } public AutocompleterField(String propertyName, String displayName, boolean required) { super(propertyName, displayName, required); } public String getTextfieldId() { return getPropertyName() + "-input"; } public String getChoicesId() { return getPropertyName() + "-choices"; } @Override public Category getCategory() { return Category.AUTOCOMPLETER; } }
bsd-3-clause
BogusCurry/halcyon
OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs
24358
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.IO; using System.Web; using System.Xml; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Communications.Capabilities.Caps; using OSDArray = OpenMetaverse.StructuredData.OSDArray; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.CoreModules.World.Media.Moap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MoapModule")] public class MoapModule : INonSharedRegionModule, IMoapModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "MoapModule"; } } public Type ReplaceableInterface { get { return null; } } /// <summary> /// Is this module enabled? /// </summary> protected bool m_isEnabled; /// <summary> /// The scene to which this module is attached /// </summary> protected Scene m_scene; /// <summary> /// Track the ObjectMedia capabilities given to users keyed by path /// </summary> protected Dictionary<string, UUID> m_omCapUsers = new Dictionary<string, UUID>(); /// <summary> /// Track the ObjectMedia capabilities given to users keyed by agent. Lock m_omCapUsers to manipulate. /// </summary> protected Dictionary<UUID, string> m_omCapUrls = new Dictionary<UUID, string>(); /// <summary> /// Track the ObjectMediaUpdate capabilities given to users keyed by path /// </summary> protected Dictionary<string, UUID> m_omuCapUsers = new Dictionary<string, UUID>(); /// <summary> /// Track the ObjectMediaUpdate capabilities given to users keyed by agent. Lock m_omuCapUsers to manipulate /// </summary> protected Dictionary<UUID, string> m_omuCapUrls = new Dictionary<UUID, string>(); public void Initialise(IConfigSource configSource) { m_isEnabled = true; IConfig config = configSource.Configs["MediaOnAPrim"]; if (config != null) m_isEnabled = config.GetBoolean("Enabled", m_isEnabled); } public void AddRegion(Scene scene) { if (!m_isEnabled) return; m_scene = scene; m_scene.RegisterModuleInterface<IMoapModule>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { if (!m_isEnabled) return; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnDeregisterCaps += OnDeregisterCaps; m_scene.EventManager.OnSceneObjectPartCopy += OnSceneObjectPartCopy; } public void Close() { if (!m_isEnabled) return; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps; m_scene.EventManager.OnSceneObjectPartCopy -= OnSceneObjectPartCopy; } public void OnRegisterCaps(UUID agentID, Caps caps) { // m_log.DebugFormat( // "[MOAP]: Registering ObjectMedia and ObjectMediaNavigate capabilities for agent {0}", agentID); string omCapUrl = "/CAPS/" + UUID.Random(); lock (m_omCapUsers) { m_omCapUsers[omCapUrl] = agentID; m_omCapUrls[agentID] = omCapUrl; // Even though we're registering for POST we're going to get GETS and UPDATES too IRequestHandler handler = new RestStreamHandler("POST", omCapUrl, HandleObjectMediaMessage); caps.RegisterHandler("ObjectMedia", handler); } string omuCapUrl = "/CAPS/" + UUID.Random(); lock (m_omuCapUsers) { m_omuCapUsers[omuCapUrl] = agentID; m_omuCapUrls[agentID] = omuCapUrl; // Even though we're registering for POST we're going to get GETS and UPDATES too IRequestHandler handler = new RestStreamHandler("POST", omuCapUrl, HandleObjectMediaNavigateMessage); caps.RegisterHandler("ObjectMediaNavigate", handler); } } public void OnDeregisterCaps(UUID agentID, Caps caps) { lock (m_omCapUsers) { string path = m_omCapUrls[agentID]; m_omCapUrls.Remove(agentID); m_omCapUsers.Remove(path); } lock (m_omuCapUsers) { string path = m_omuCapUrls[agentID]; m_omuCapUrls.Remove(agentID); m_omuCapUsers.Remove(path); } } protected void OnSceneObjectPartCopy(SceneObjectPart copy, SceneObjectPart original, bool userExposed) { if (original.Shape.Media == null) { copy.Shape.Media = null; } else { copy.Shape.Media = new PrimitiveBaseShape.PrimMedia(original.Shape.Media); } } public MediaEntry GetMediaEntry(SceneObjectPart part, int face) { MediaEntry me = null; if (!CheckFaceParam(part, face)) return null; if (part.Shape.Media == null) return null; // no media entries if (face >= part.Shape.Media.Count) return null; // out of range me = part.Shape.Media[face]; if (me == null) // no media entry for that face return null; // TODO: Really need a proper copy constructor down in libopenmetaverse me = MediaEntry.FromOSD(me.GetOSD()); // m_log.DebugFormat("[MOAP]: GetMediaEntry for {0} face {1} found {2}", part.Name, face, me); return me; } /// <summary> /// Set the media entry on the face of the given part. /// </summary> /// <param name="part">/param> /// <param name="face"></param> /// <param name="me">If null, then the media entry is cleared.</param> public void SetMediaEntry(SceneObjectPart part, int face, MediaEntry me) { // m_log.DebugFormat("[MOAP]: SetMediaEntry for {0}, face {1}", part.Name, face); int numFaces = part.GetNumberOfSides(); if (part.Shape.Media == null) part.Shape.Media = new PrimitiveBaseShape.PrimMedia(numFaces); else part.Shape.Media.Resize(numFaces); if (!CheckFaceParam(part, face)) return; // ClearMediaEntry passes null for me so it must not be ignored! lock (part.Shape.Media) part.Shape.Media[face] = me; UpdateMediaUrl(part, UUID.Zero); SetPartMediaFlags(part, face, me != null); part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); } /// <summary> /// Clear the media entry from the face of the given part. /// </summary> /// <param name="part"></param> /// <param name="face"></param> public void ClearMediaEntry(SceneObjectPart part, int face) { SetMediaEntry(part, face, null); } /// <summary> /// Set the media flags on the texture face of the given part. /// </summary> /// <remarks> /// The fact that we need a separate function to do what should be a simple one line operation is BUTT UGLY. /// </remarks> /// <param name="part"></param> /// <param name="face"></param> /// <param name="flag"></param> protected void SetPartMediaFlags(SceneObjectPart part, int face, bool flag) { Primitive.TextureEntry te = part.Shape.Textures; Primitive.TextureEntryFace teFace = te.CreateFace((uint)face); teFace.MediaFlags = flag; part.Shape.Textures = te; } /// <summary> /// Sets or gets per face media textures. /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <returns></returns> protected string HandleObjectMediaMessage( string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { // m_log.DebugFormat("[MOAP]: Got ObjectMedia path [{0}], raw request [{1}]", path, request); OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request); ObjectMediaMessage omm = new ObjectMediaMessage(); omm.Deserialize(osd); if (omm.Request is ObjectMediaRequest) return HandleObjectMediaRequest(omm.Request as ObjectMediaRequest); else if (omm.Request is ObjectMediaUpdate) return HandleObjectMediaUpdate(path, omm.Request as ObjectMediaUpdate); throw new Exception( string.Format( "[MOAP]: ObjectMediaMessage has unrecognized ObjectMediaBlock of {0}", omm.Request.GetType())); } /// <summary> /// Handle a fetch request for media textures /// </summary> /// <param name="omr"></param> /// <returns></returns> protected string HandleObjectMediaRequest(ObjectMediaRequest omr) { UUID primId = omr.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received a GET ObjectMediaRequest for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } if (null == part.Shape.Media) return string.Empty; ObjectMediaResponse resp = new ObjectMediaResponse(); resp.PrimID = primId; lock (part.Shape.Media) resp.FaceMedia = part.Shape.Media.CopyArray(); resp.Version = part.MediaUrl; string rawResp = OSDParser.SerializeLLSDXmlString(resp.Serialize()); // m_log.DebugFormat("[MOAP]: Got HandleObjectMediaRequestGet raw response is [{0}]", rawResp); return rawResp; } /// <summary> /// Handle an update of media textures. /// </summary> /// <param name="path">Path on which this request was made</param> /// <param name="omu">/param> /// <returns></returns> protected string HandleObjectMediaUpdate(string path, ObjectMediaUpdate omu) { UUID primId = omu.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received an UPDATE ObjectMediaRequest for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } // m_log.DebugFormat("[MOAP]: Received {0} media entries for prim {1}", omu.FaceMedia.Length, primId); // // for (int i = 0; i < omu.FaceMedia.Length; i++) // { // MediaEntry me = omu.FaceMedia[i]; // string v = (null == me ? "null": OSDParser.SerializeLLSDXmlString(me.GetOSD())); // m_log.DebugFormat("[MOAP]: Face {0} [{1}]", i, v); // } if (omu.FaceMedia.Length > part.GetNumberOfSides()) { m_log.WarnFormat( "[MOAP]: Received {0} media entries from client for prim {1} {2} but this prim has only {3} faces. Dropping request.", omu.FaceMedia.Length, part.Name, part.UUID, part.GetNumberOfSides()); return string.Empty; } UUID agentId = default(UUID); lock (m_omCapUsers) agentId = m_omCapUsers[path]; if (null == part.Shape.Media) { // m_log.DebugFormat("[MOAP]: Setting all new media list for {0}", part.Name); part.Shape.Media = new PrimitiveBaseShape.PrimMedia(omu.FaceMedia); for (int i = 0; i < omu.FaceMedia.Length; i++) { if (omu.FaceMedia[i] != null) { // FIXME: Race condition here since some other texture entry manipulator may overwrite/get // overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry // directly. SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", // i, part.Shape.Textures.FaceTextures[i].MediaFlags); } } } else { // m_log.DebugFormat("[MOAP]: Setting existing media list for {0}", part.Name); // We need to go through the media textures one at a time to make sure that we have permission // to change them // FIXME: Race condition here since some other texture entry manipulator may overwrite/get // overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry // directly. Primitive.TextureEntry te = part.Shape.Textures; lock (part.Shape.Media) { for (int i = 0; i < part.Shape.Media.Count; i++) { if (m_scene.Permissions.CanControlPrimMedia(agentId, part.UUID, i)) { part.Shape.Media[i] = omu.FaceMedia[i]; // When a face is cleared this is done by setting the MediaFlags in the TextureEntry via a normal // texture update, so we don't need to worry about clearing MediaFlags here. if (null == part.Shape.Media[i]) continue; SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", // i, face.MediaFlags); // m_log.DebugFormat("[MOAP]: Set media entry for face {0} on {1}", i, part.Name); } } } part.Shape.Textures = te; // for (int i2 = 0; i2 < part.Shape.Textures.FaceTextures.Length; i2++) // m_log.DebugFormat("[MOAP]: FaceTexture[{0}] is {1}", i2, part.Shape.Textures.FaceTextures[i2]); } UpdateMediaUrl(part, agentId); // Arguably, we could avoid sending a full update to the avatar that just changed the texture. part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); return string.Empty; } /// <summary> /// Received from the viewer if a user has changed the url of a media texture. /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="httpRequest">/param> /// <param name="httpResponse">/param> /// <returns></returns> protected string HandleObjectMediaNavigateMessage( string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { // m_log.DebugFormat("[MOAP]: Got ObjectMediaNavigate request [{0}]", request); OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request); ObjectMediaNavigateMessage omn = new ObjectMediaNavigateMessage(); omn.Deserialize(osd); UUID primId = omn.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received an ObjectMediaNavigateMessage for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } UUID agentId = default(UUID); lock (m_omuCapUsers) agentId = m_omuCapUsers[path]; if (!m_scene.Permissions.CanInteractWithPrimMedia(agentId, part.UUID, omn.Face)) return string.Empty; // m_log.DebugFormat( // "[MOAP]: Received request to update media entry for face {0} on prim {1} {2} to {3}", // omn.Face, part.Name, part.UUID, omn.URL); // If media has never been set for this prim, then just return. if (null == part.Shape.Media) return string.Empty; MediaEntry me = null; lock (part.Shape.Media) me = part.Shape.Media[omn.Face]; // Do the same if media has not been set up for a specific face if (null == me) return string.Empty; if (me.EnableWhiteList) { if (!CheckUrlAgainstWhitelist(omn.URL, me.WhiteList)) { // m_log.DebugFormat( // "[MOAP]: Blocking change of face {0} on prim {1} {2} to {3} since it's not on the enabled whitelist", // omn.Face, part.Name, part.UUID, omn.URL); return string.Empty; } } me.CurrentURL = omn.URL; UpdateMediaUrl(part, agentId); part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); return OSDParser.SerializeLLSDXmlString(new OSD()); } /// <summary> /// Check that the face number is valid for the given prim. /// </summary> /// <param name="part"></param> /// <param name="face"></param> protected bool CheckFaceParam(SceneObjectPart part, int face) { if (face < 0) return false; return (face < part.GetNumberOfSides()); } /// <summary> /// Update the media url of the given part /// </summary> /// <param name="part"></param> /// <param name="updateId"> /// The id to attach to this update. Normally, this is the user that changed the /// texture /// </param> protected void UpdateMediaUrl(SceneObjectPart part, UUID updateId) { if (null == part.MediaUrl) { // TODO: We can't set the last changer until we start tracking which cap we give to which agent id part.MediaUrl = "x-mv:0000000000/" + updateId; } else { string rawVersion = part.MediaUrl.Substring(5, 10); int version = int.Parse(rawVersion); part.MediaUrl = string.Format("x-mv:{0:D10}/{1}", ++version, updateId); } // m_log.DebugFormat("[MOAP]: Storing media url [{0}] in prim {1} {2}", part.MediaUrl, part.Name, part.UUID); } /// <summary> /// Check the given url against the given whitelist. /// </summary> /// <param name="rawUrl"></param> /// <param name="whitelist"></param> /// <returns>true if the url matches an entry on the whitelist, false otherwise</returns> protected bool CheckUrlAgainstWhitelist(string rawUrl, string[] whitelist) { Uri url = new Uri(rawUrl); foreach (string origWlUrl in whitelist) { string wlUrl = origWlUrl; // Deal with a line-ending wildcard if (wlUrl.EndsWith("*")) wlUrl = wlUrl.Remove(wlUrl.Length - 1); // m_log.DebugFormat("[MOAP]: Checking whitelist URL pattern {0}", origWlUrl); // Handle a line starting wildcard slightly differently since this can only match the domain, not the path if (wlUrl.StartsWith("*")) { wlUrl = wlUrl.Substring(1); if (url.Host.Contains(wlUrl)) { // m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl); return true; } } else { string urlToMatch = url.Authority + url.AbsolutePath; if (urlToMatch.StartsWith(wlUrl)) { // m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl); return true; } } } return false; } } }
bsd-3-clause
tangentforks/vanar
src/asmcache/bs.asm
107
section .text global _start _start: call rax call r8 call r9 call r10 call r11 call r12 call r13 call r14
bsd-3-clause
piwik/piwik-sdk-android
tracker/src/test/java/testhelpers/JUnitTree.java
1081
package testhelpers; import androidx.annotation.NonNull; import android.util.Log; import timber.log.Timber; public class JUnitTree extends Timber.DebugTree { private final int minlogLevel; public JUnitTree() { minlogLevel = Log.VERBOSE; } public JUnitTree(int minlogLevel) { this.minlogLevel = minlogLevel; } private static String priorityToString(int priority) { switch (priority) { case Log.ERROR: return "E"; case Log.WARN: return "W"; case Log.INFO: return "I"; case Log.DEBUG: return "D"; case Log.VERBOSE: return "V"; default: return String.valueOf(priority); } } @Override protected void log(int priority, String tag, @NonNull String message, Throwable t) { if (priority < minlogLevel) return; System.out.println(System.currentTimeMillis() + " " + priorityToString(priority) + "/" + tag + ": " + message); } }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE197_Numeric_Truncation_Error/s02/CWE197_Numeric_Truncation_Error__short_fgets_09.c
3534
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE197_Numeric_Truncation_Error__short_fgets_09.c Label Definition File: CWE197_Numeric_Truncation_Error__short.label.xml Template File: sources-sink-09.tmpl.c */ /* * @description * CWE: 197 Numeric Truncation Error * BadSource: fgets Read data from the console using fgets() * GoodSource: Less than CHAR_MAX * Sink: * BadSink : Convert data to a char * Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE) * * */ #include "std_testcase.h" /* Must be at least 8 for atoi() to work properly */ #define CHAR_ARRAY_SIZE 8 #ifndef OMITBAD void CWE197_Numeric_Truncation_Error__short_fgets_09_bad() { short data; /* Initialize data */ data = -1; if(GLOBAL_CONST_TRUE) { { char inputBuffer[CHAR_ARRAY_SIZE] = ""; /* FLAW: Use a number input from the console using fgets() */ if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) { /* Convert to short */ data = (short)atoi(inputBuffer); } else { printLine("fgets() failed."); } } } { /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ char charData = (char)data; printHexCharLine(charData); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */ static void goodG2B1() { short data; /* Initialize data */ data = -1; if(GLOBAL_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a positive integer less than CHAR_MAX*/ data = CHAR_MAX-5; } { /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ char charData = (char)data; printHexCharLine(charData); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { short data; /* Initialize data */ data = -1; if(GLOBAL_CONST_TRUE) { /* FIX: Use a positive integer less than CHAR_MAX*/ data = CHAR_MAX-5; } { /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ char charData = (char)data; printHexCharLine(charData); } } void CWE197_Numeric_Truncation_Error__short_fgets_09_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE197_Numeric_Truncation_Error__short_fgets_09_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE197_Numeric_Truncation_Error__short_fgets_09_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
supertanglang/i2pd
Destination.h
7466
#ifndef DESTINATION_H__ #define DESTINATION_H__ #include <thread> #include <mutex> #include <memory> #include <map> #include <set> #include <string> #include <functional> #include <boost/asio.hpp> #include "Identity.h" #include "tunnel/TunnelPool.h" #include "crypto/CryptoConst.h" #include "LeaseSet.h" #include "Garlic.h" #include "NetDb.h" #include "Streaming.h" #include "Datagram.h" namespace i2p { namespace client { const uint8_t PROTOCOL_TYPE_STREAMING = 6; const uint8_t PROTOCOL_TYPE_DATAGRAM = 17; const uint8_t PROTOCOL_TYPE_RAW = 18; const int PUBLISH_CONFIRMATION_TIMEOUT = 5; // in seconds const int LEASESET_REQUEST_TIMEOUT = 5; // in seconds const int MAX_LEASESET_REQUEST_TIMEOUT = 40; // in seconds const int MAX_NUM_FLOODFILLS_PER_REQUEST = 7; const int DESTINATION_CLEANUP_TIMEOUT = 20; // in minutes // I2CP const char I2CP_PARAM_INBOUND_TUNNEL_LENGTH[] = "inbound.length"; const int DEFAULT_INBOUND_TUNNEL_LENGTH = 3; const char I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH[] = "outbound.length"; const int DEFAULT_OUTBOUND_TUNNEL_LENGTH = 3; const char I2CP_PARAM_INBOUND_TUNNELS_QUANTITY[] = "inbound.quantity"; const int DEFAULT_INBOUND_TUNNELS_QUANTITY = 5; const char I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY[] = "outbound.quantity"; const int DEFAULT_OUTBOUND_TUNNELS_QUANTITY = 5; const char I2CP_PARAM_EXPLICIT_PEERS[] = "explicitPeers"; const int STREAM_REQUEST_TIMEOUT = 60; //in seconds typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete; class ClientDestination: public i2p::garlic::GarlicDestination { typedef std::function<void (std::shared_ptr<i2p::data::LeaseSet> leaseSet)> RequestComplete; // leaseSet = nullptr means not found struct LeaseSetRequest { LeaseSetRequest (boost::asio::io_service& service): requestTime (0), requestTimeoutTimer (service) {}; std::set<i2p::data::IdentHash> excluded; uint64_t requestTime; boost::asio::deadline_timer requestTimeoutTimer; RequestComplete requestComplete; }; public: ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params = nullptr); ~ClientDestination (); virtual void Start (); virtual void Stop (); bool IsRunning () const { return m_IsRunning; }; boost::asio::io_service& GetService () { return m_Service; }; std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () { return m_Pool; }; bool IsReady () const { return m_LeaseSet && m_LeaseSet->HasNonExpiredLeases () && m_Pool->GetOutboundTunnels ().size () > 0; }; std::shared_ptr<const i2p::data::LeaseSet> FindLeaseSet (const i2p::data::IdentHash& ident); bool RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete = nullptr); // streaming std::shared_ptr<i2p::stream::StreamingDestination> CreateStreamingDestination (int port); // additional std::shared_ptr<i2p::stream::StreamingDestination> GetStreamingDestination (int port = 0) const; // following methods operate with default streaming destination void CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port = 0); std::shared_ptr<i2p::stream::Stream> CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port = 0); void AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor); void StopAcceptingStreams (); bool IsAcceptingStreams () const; // datagram i2p::datagram::DatagramDestination * GetDatagramDestination () const { return m_DatagramDestination; }; i2p::datagram::DatagramDestination * CreateDatagramDestination (); // implements LocalDestination const i2p::data::PrivateKeys& GetPrivateKeys () const { return m_Keys; }; const uint8_t * GetEncryptionPrivateKey () const { return m_EncryptionPrivateKey; }; const uint8_t * GetEncryptionPublicKey () const { return m_EncryptionPublicKey; }; // implements GarlicDestination std::shared_ptr<const i2p::data::LeaseSet> GetLeaseSet (); std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () const { return m_Pool; } void HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from); // override GarlicDestination bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag); void ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg); void ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg); void SetLeaseSetUpdated (); // I2CP void HandleDataMessage (const uint8_t * buf, size_t len); private: void Run (); void UpdateLeaseSet (); void Publish (); void HandlePublishConfirmationTimer (const boost::system::error_code& ecode); void HandleDatabaseStoreMessage (const uint8_t * buf, size_t len); void HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len); void HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg); void RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete); bool SendLeaseSetRequest (const i2p::data::IdentHash& dest, std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, LeaseSetRequest * request); void HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest); void HandleCleanupTimer (const boost::system::error_code& ecode); void CleanupRemoteLeaseSets (); private: volatile bool m_IsRunning; std::thread * m_Thread; boost::asio::io_service m_Service; boost::asio::io_service::work m_Work; i2p::data::PrivateKeys m_Keys; uint8_t m_EncryptionPublicKey[256], m_EncryptionPrivateKey[256]; std::map<i2p::data::IdentHash, std::shared_ptr<i2p::data::LeaseSet> > m_RemoteLeaseSets; std::map<i2p::data::IdentHash, LeaseSetRequest *> m_LeaseSetRequests; std::shared_ptr<i2p::tunnel::TunnelPool> m_Pool; std::shared_ptr<i2p::data::LeaseSet> m_LeaseSet; bool m_IsPublic; uint32_t m_PublishReplyToken; std::set<i2p::data::IdentHash> m_ExcludedFloodfills; // for publishing std::shared_ptr<i2p::stream::StreamingDestination> m_StreamingDestination; // default std::map<uint16_t, std::shared_ptr<i2p::stream::StreamingDestination> > m_StreamingDestinationsByPorts; i2p::datagram::DatagramDestination * m_DatagramDestination; boost::asio::deadline_timer m_PublishConfirmationTimer, m_CleanupTimer; public: // for HTTP only int GetNumRemoteLeaseSets () const { return m_RemoteLeaseSets.size (); }; }; } } #endif
bsd-3-clause
eriser/JamomaCore
Foundation/extensions/DataspaceLib/tests/ColorDataspace.test.cpp
7913
/** @file * * @ingroup foundationDataspaceLib * * @brief Unit tests for the #ColorDataspace. * * @authors Trond Lossius, Tim Place, Nils Peters, ... * * @copyright Copyright © 2011 Trond Lossius @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ // Dataspaces and Units employ C++ double-inheritance and are thus unsuitable for direct use // through the usual TTObject API #define TT_NO_DEPRECATION_WARNINGS #include "ColorDataspace.h" TTErr ColorDataspace::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // Create dataspace object and set to color try { TTObject myDataspace("dataspace"); myDataspace.set(TT("dataspace"), TT("color")); TTValue v; TTValue expected; /************************************************/ /* */ /* Test conversions to neutral unit */ /* */ /************************************************/ // rgb => rgb myDataspace.set(TT("inputUnit"), TT("rgb")); myDataspace.set(TT("outputUnit"), TT("rgb")); v.resize(3); v[0] = TTFloat64(124.2); v[1] = TTFloat64(162.9); v[2] = TTFloat64(13.163); expected.resize(3); expected[0] = TTFloat64(124.2); expected[1] = TTFloat64(162.9); expected[2] = TTFloat64(13.163); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb to rgb", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // cmy => rgb myDataspace.set(TT("inputUnit"), TT("cmy")); myDataspace.set(TT("outputUnit"), TT("rgb")); v.resize(3); v[0] = TTFloat64(255.); v[1] = TTFloat64(127.5); v[2] = TTFloat64(0.); expected.resize(3); expected[0] = TTFloat64(0.); expected[1] = TTFloat64(0.5); expected[2] = TTFloat64(1.0); myDataspace.send(TT("convert"), v, v); TTTestAssertion("cmy to rgb", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // hsl => rgb myDataspace.set(TT("inputUnit"), TT("hsl")); myDataspace.set(TT("outputUnit"), TT("rgb")); v.resize(3); v[0] = TTFloat64(120.); v[1] = TTFloat64(100.); v[2] = TTFloat64(50.); expected.resize(3); expected[0] = TTFloat64(0.); expected[1] = TTFloat64(1.0); expected[2] = TTFloat64(0.); myDataspace.send(TT("convert"), v, v); TTTestAssertion("hsl to rgb", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // rgb8 => rgb myDataspace.set(TT("inputUnit"), TT("rgb8")); myDataspace.set(TT("outputUnit"), TT("rgb")); v.resize(3); v[0] = TTFloat64(255.); v[1] = TTFloat64(127.5); v[2] = TTFloat64(0.); expected.resize(3); expected[0] = TTFloat64(1.); expected[1] = TTFloat64(0.5); expected[2] = TTFloat64(0.0); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb8 to rgb", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // hsv => rgb myDataspace.set(TT("inputUnit"), TT("hsv")); myDataspace.set(TT("outputUnit"), TT("rgb")); v.resize(3); v[0] = TTFloat64(120.); v[1] =TTFloat64(100.); v[2] = TTFloat64(100.); expected.resize(3); expected[0] = TTFloat64(0.); expected[1] = TTFloat64(1.0); expected[2] = TTFloat64(0.); myDataspace.send(TT("convert"), v, v); TTTestAssertion("hsv to rgb", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); /************************************************/ /* */ /* Test conversions from neutral unit */ /* */ /************************************************/ // rgb => cmy myDataspace.set(TT("inputUnit"), TT("rgb")); myDataspace.set(TT("outputUnit"), TT("cmy")); v.resize(3); v[0] = TTFloat64(0.); v[1] = TTFloat64(0.5); v[2] = TTFloat64(1.); expected.resize(3); expected[0] = TTFloat64(255.); expected[1] = TTFloat64(127.5); expected[2] = TTFloat64(0.0); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb to cmy", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // rgb => hsl myDataspace.set(TT("inputUnit"), TT("rgb")); myDataspace.set(TT("outputUnit"), TT("hsl")); v.resize(3); v[0] = TTFloat64(0.); v[1] = TTFloat64(1.); v[2] = TTFloat64(0.); expected.resize(3); expected[0] = TTFloat64(120.); expected[1] = TTFloat64(100.0); expected[2] = TTFloat64(50.); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb to hsl", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // rgb => rgb8 myDataspace.set(TT("inputUnit"), TT("rgb")); myDataspace.set(TT("outputUnit"), TT("rgb8")); v.resize(3); v[0] = TTFloat64(1.); v[1] = TTFloat64(0.5); v[2] = TTFloat64(0.); expected.resize(3); expected[0] = TTFloat64(255.); expected[1] = TTFloat64(127.5); expected[2] = TTFloat64(0.0); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb to rgb8", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); // rgb => hsv myDataspace.set(TT("inputUnit"), TT("rgb")); myDataspace.set(TT("outputUnit"), TT("hsv")); v.resize(3); v[0] = TTFloat64(0.); v[1] = TTFloat64(1.); v[2] = TTFloat64(0.); expected.resize(3); expected[0] = TTFloat64(120.); expected[1] = TTFloat64(100.0); expected[2] = TTFloat64(100.); myDataspace.send(TT("convert"), v, v); TTTestAssertion("rgb to hsv", TTTestFloat64ArrayEquivalence(v, expected), testAssertionCount, errorCount); } catch (...) { TTLogMessage("ColorDataspace::test TOTAL FAILURE"); errorCount = 1; testAssertionCount = 1; } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
bsd-3-clause
beiyuxinke/CONNECT
Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/service/jaxws/DeletePolicyGroups.java
4197
/* * Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services. * 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. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 UNITED STATES GOVERNMENT 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. */ /* Copyright (c) 2010, NHIN Direct Project All rights reserved. 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. 3. Neither the name of the The NHIN Direct Project (nhindirect.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 gov.hhs.fha.nhinc.directconfig.service.jaxws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "deletePolicyGroups", namespace = "http://nhind.org/config") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "deletePolicyGroups", namespace = "http://nhind.org/config") public class DeletePolicyGroups { @XmlElement(name = "policyGroupIds", namespace = "", nillable = true) private long[] policyGroupIds; /** * * @return * returns long[] */ public long[] getPolicyGroupIds() { return this.policyGroupIds; } /** * * @param policyGroupIds * the value for the policyGroupIds property */ public void setPolicyGroupIds(long[] policyGroupIds) { this.policyGroupIds = policyGroupIds; } }
bsd-3-clause
escherba/lsh-hdc
lsh_hdc/ranking.py
19946
""" Problem Statement ----------------- Assume that there is a large data set of mostly unique samples where a hidden binary variable is dependent on the number of similar samples that exist in the set (i.e. a sample is called positive if it has many neighbors) and that our goal is to label all samples in this set. It is easy to see that, given sparse enough data, if a clustering method relies on the same sample property on which the ground truth similarity space is defined, it will naturally separate the samples into two groups -- those found in clusters and containing mostly positives, and those found outside clusters and containing mostly negatives. There would exist only one possible perfect clustering -- the one with a single, entirely homogeneous cluster C that covers all positives present in the data set. If one were to obtain such clustering, one could correctly label all positive samples in one step with the simple rule, *all positive samples belong to cluster C*. Under an imperfect clustering, on the other hand, the presence of the given sample in a cluster of size two or more implies the sample is only likely to be positive, with the confidence of the positive call monotonously increasing with the size of the cluster. In other words, our expectation from a good clustering is that it will help us minimize the amount of work labeling samples. The application that inspired the design of this metric was mining for positive spam examples in large data sets of short user-generated content. Given large enough data sets, spam content naturally forms clusters either because creative rewriting of every single individual spam message is too expensive for spammers to employ, or because, even if human or algorithmic rewriting is applied, one can still find features that link individual spam messages to their creator or to the product or service being promoted in the spam campaign. The finding was consistent with what is reported in literature [104]_. Algorithm --------- Given a clustering, we order the clusters from the largest one to the smallest one. We then plot a cumulative step function where the width of the bin under a given "step" is proportional to cluster size, and the height of the bin is proportional to the expected number of positive samples seen so far [103]_. If a sample is in a cluster of size one, we assume it is likely to be negative and is therefore checked on an individual basis (the specific setting of cluster size at which the expectation changes is our 'threshold' parameter. The result of this assumption is that the expected contribution from unclustered samples is equal to their actual contribution (we assume individual checking always gives a correct answer). After two-way normalization, a perfect clustering (i.e. where a single perfectly homogeneous cluster covers the entire set of positives) will have the AUL score of 1.0. A failure to will result in the AUL of 0.5. A perverse clustering, i.e. one where many negative samples fall into clusters whose size is above our threshold, or where many positive samples remain unclustered (fall into clusters of size below the threshold one) the AUL somewhere between 0.0 and 0.5. A special treatment is necessary for cases where clusters are tied by size. If one were to treat tied clusters as a single group, one would obtain AUL of 1.0 when no clusters at all are present, which is against our desiderata. On the other hand, if one were to treat tied clusters entirely separately, one would obtain different results depending on the properties of the sorting algorithm, also an undesirable situation. Always placing "heavy" clusters (i.e. those containing more positives) towards the beginning or towards the end of the tied group will result in, respectively, overestimating or underestimating the true AUL. The solution here is to average the positive counts among all clusters in a tied group, and then walk through them one by one, with the stepwise cumulative function asymptotically approaching a diagonal from the group's bottom left corner to the top right one. This way, a complete absence of clustering (i.e. all clusters are of size one) will always result in AUL of 0.5. The resulting AUL measure has some similarity with the Gini coefficient of inequality [105]_ except we plot the corresponding curve in the opposite direction (from "richest" to "poorest"), and do not subtract 0.5 from the resulting score. .. [103] We take the expected number of positives and not the actual number seen so far as the vertical scale in order to penalize non-homogeneous clusters. Otherwise the y=1.0 ceiling would be reached early in the process even in very bad cases, for example when there is only one giant non-homogeneous cluster. References ---------- .. [104] `Whissell, J. S., & Clarke, C. L. (2011, September). Clustering for semi-supervised spam filtering. In Proceedings of the 8th Annual Collaboration, Electronic messaging, Anti-Abuse and Spam Conference (pp. 125-134). ACM. <https://doi.org/10.1145/2030376.2030391>`_ .. [105] `Wikipedia entry for Gini coefficient of inequality <https://en.wikipedia.org/wiki/Gini_coefficient>`_ """ import warnings import numpy as np from itertools import izip, chain from operator import itemgetter from sklearn.metrics.ranking import auc, roc_curve from pymaptools.iter import aggregate_tuples from pymaptools.containers import labels_to_clusters def num2bool(num): """True if zero or positive real, False otherwise When binarizing class labels, this lets us be consistent with Scikit-Learn where binary labels can be {0, 1} with 0 being negative or {-1, 1} with -1 being negative. """ return num > 0 class LiftCurve(object): """Lift Curve for cluster-size correlated classification """ def __init__(self, score_groups): self._score_groups = list(score_groups) @classmethod def from_counts(cls, counts_true, counts_pred): """Instantiates class from arrays of true and predicted counts Parameters ---------- counts_true : array, shape = [n_clusters] Count of positives in cluster counts_pred : array, shape = [n_clusters] Predicted number of positives in each cluster """ # convert input to a series of tuples count_groups = izip(counts_pred, counts_true) # sort tuples by predicted count in descending order count_groups = sorted(count_groups, key=itemgetter(0), reverse=True) # group tuples by predicted count so as to handle ties correctly return cls(aggregate_tuples(count_groups)) @classmethod def from_clusters(cls, clusters, is_class_pos=num2bool): """Instantiates class from clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of lists of class labels is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ # take all non-empty clusters, score them by size and by number of # ground truth positives data = ((len(cluster), sum(is_class_pos(class_label) for class_label in cluster)) for cluster in clusters if cluster) scores_pred, scores_true = zip(*data) or ([], []) return cls.from_counts(scores_true, scores_pred) @classmethod def from_labels(cls, labels_true, labels_pred, is_class_pos=num2bool): """Instantiates class from arrays of classes and cluster sizes Parameters ---------- labels_true : array, shape = [n_samples] Class labels. If binary, 'is_class_pos' is optional labels_pred : array, shape = [n_samples] Cluster labels to evaluate is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ clusters = labels_to_clusters(labels_true, labels_pred) return cls.from_clusters(clusters, is_class_pos=is_class_pos) def aul_score(self, threshold=1, plot=False): """Calculate AUL score Parameters ---------- threshold : int, optional (default=1) only predicted scores above this number considered accurate plot : bool, optional (default=False) whether to return X and Y data series for plotting """ total_any = 0 total_true = 0 assumed_vertical = 0 aul = 0.0 if plot: xs, ys = [], [] bin_height = 0.0 bin_right_edge = 0.0 # second pass: iterate over each group of predicted scores of the same # size and calculate the AUL metric for pred_score, true_scores in self._score_groups: # number of clusters num_true_scores = len(true_scores) # sum total of positives in all clusters of given size group_height = sum(true_scores) total_true += group_height # cluster size x number of clusters of given size group_width = pred_score * num_true_scores total_any += group_width if pred_score > threshold: # penalize non-homogeneous clusters simply by assuming that they # are homogeneous, in which case their expected vertical # contribution should be equal to their horizontal contribution. height_incr = group_width else: # clusters of size one are by definition homogeneous so their # expected vertical contribution equals sum total of any # remaining true positives. height_incr = group_height assumed_vertical += height_incr if plot: avg_true_score = group_height / float(num_true_scores) for _ in true_scores: bin_height += avg_true_score aul += bin_height * pred_score if plot: xs.append(bin_right_edge) bin_right_edge += pred_score xs.append(bin_right_edge) ys.append(bin_height) ys.append(bin_height) else: # if not tasked with generating plots, use a geometric method # instead of looping aul += (total_true * group_width - ((num_true_scores - 1) * pred_score * group_height) / 2.0) if total_true > total_any: warnings.warn( "Number of positives found (%d) exceeds total count of %d" % (total_true, total_any) ) rect_area = assumed_vertical * total_any # special case: since normalizing the AUL defines it as always smaller # than the bounding rectangle, when denominator in the expression below # is zero, the AUL score is also equal to zero. aul = 0.0 if rect_area == 0 else aul / rect_area if plot: xs = np.array(xs, dtype=float) / total_any ys = np.array(ys, dtype=float) / assumed_vertical return aul, xs, ys else: return aul def plot(self, threshold=1, fill=True, marker=None, save_to=None): # pragma: no cover """Create a graphical representation of Lift Curve Requires Matplotlib Parameters ---------- threshold : int, optional (default=1) only predicted scores above this number considered accurate marker : str, optional (default=None) Whether to draw marker at each bend save_to : str, optional (default=None) If specified, save the plot to path instead of displaying """ from matplotlib import pyplot as plt score, xs, ys = self.aul_score(threshold=threshold, plot=True) fig, ax = plt.subplots() ax.plot(xs, ys, marker=marker, linestyle='-') if fill: ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2) ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey') ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.set_xlim(xmin=0.0, xmax=1.03) ax.set_ylim(ymin=0.0, ymax=1.04) ax.set_xlabel("portion total") ax.set_ylabel("portion expected positive") ax.set_title("Lift Curve (AUL=%.3f)" % score) if save_to is None: fig.show() else: fig.savefig(save_to) plt.close(fig) def aul_score_from_clusters(clusters): """Calculate AUL score given clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of clusters where each point is binary-coded according to true class. Returns ------- aul : float """ return LiftCurve.from_clusters(clusters).aul_score() def aul_score_from_labels(y_true, labels_pred): """AUL score given array of classes and array of cluster sizes Parameters ---------- y_true : array, shape = [n_samples] True binary labels in range {0, 1} labels_pred : array, shape = [n_samples] Cluster labels to evaluate Returns ------- aul : float """ return LiftCurve.from_labels(y_true, labels_pred).aul_score() class RocCurve(object): """Receiver Operating Characteristic (ROC) :: >>> c = RocCurve.from_labels([0, 0, 1, 1], ... [0.1, 0.4, 0.35, 0.8]) >>> c.auc_score() 0.75 >>> c.max_informedness() 0.5 """ def __init__(self, fprs, tprs, thresholds=None, pos_label=None, sample_weight=None): self.fprs = fprs self.tprs = tprs self.thresholds = thresholds self.pos_label = pos_label self.sample_weight = sample_weight def plot(self, fill=True, marker=None, save_to=None): # pragma: no cover """Plot the ROC curve """ from matplotlib import pyplot as plt score = self.auc_score() xs, ys = self.fprs, self.tprs fig, ax = plt.subplots() ax.plot(xs, ys, marker=marker, linestyle='-') if fill: ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2) ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey') ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey') ax.set_xlim(xmin=0.0, xmax=1.03) ax.set_ylim(ymin=0.0, ymax=1.04) ax.set_ylabel('TPR') ax.set_xlabel('FPR') ax.set_title("ROC Curve (AUC=%.3f)" % score) if save_to is None: fig.show() else: fig.savefig(save_to) plt.close(fig) @classmethod def from_scores(cls, scores_neg, scores_pos): """Instantiate given scores of two ground truth classes The score arrays don't have to be the same length. """ scores_pos = ((1, x) for x in scores_pos if not np.isnan(x)) scores_neg = ((0, x) for x in scores_neg if not np.isnan(x)) all_scores = zip(*chain(scores_neg, scores_pos)) or ([], []) return cls.from_labels(*all_scores) @classmethod def from_labels(cls, labels_true, y_score, is_class_pos=num2bool): """Instantiate assuming binary labeling of {0, 1} labels_true : array, shape = [n_samples] Class labels. If binary, 'is_class_pos' is optional y_score : array, shape = [n_samples] Predicted scores is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ # num2bool Y labels y_true = map(is_class_pos, labels_true) # calculate axes fprs, tprs, thresholds = roc_curve( y_true, y_score, pos_label=True) return cls(fprs, tprs, thresholds=thresholds) @classmethod def from_clusters(cls, clusters, is_class_pos=num2bool): """Instantiates class from clusters of class-coded points Parameters ---------- clusters : collections.Iterable List of lists of class labels is_class_pos: label_true -> Bool Boolean predicate used to binarize true (class) labels """ y_true = [] y_score = [] for cluster in clusters: pred_cluster = len(cluster) for point in cluster: true_cluster = is_class_pos(point) y_true.append(true_cluster) y_score.append(pred_cluster) return cls.from_labels(y_true, y_score) def auc_score(self): """Replacement for Scikit-Learn's method If number of Y classes is other than two, a warning will be triggered but no exception thrown (the return value will be a NaN). Also, we don't reorder arrays during ROC calculation since they are assumed to be in order. """ return auc(self.fprs, self.tprs, reorder=False) def optimal_cutoff(self, scoring_method): """Optimal cutoff point on ROC curve under scoring method The scoring method must take two arguments: fpr and tpr. """ max_index = np.NINF opt_pair = (np.nan, np.nan) for pair in izip(self.fprs, self.tprs): index = scoring_method(*pair) if index > max_index: opt_pair = pair max_index = index return opt_pair, max_index @staticmethod def _informedness(fpr, tpr): return tpr - fpr def max_informedness(self): """Maximum value of Informedness (TPR minus FPR) on a ROC curve A diagram of what this measure looks like is shown in [101]_. Note a correspondence between the definitions of this measure and that of Kolmogorov-Smirnov's supremum statistic. References ---------- .. [101] `Wikipedia entry for Youden's J statistic <https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_ """ return self.optimal_cutoff(self._informedness)[1] def roc_auc_score(y_true, y_score, sample_weight=None): """AUC score for a ROC curve Replaces Scikit Learn implementation (given binary ``y_true``). """ return RocCurve.from_labels(y_true, y_score).auc_score() def dist_auc(scores0, scores1): """AUC score for two distributions, with NaN correction Note: arithmetic mean appears to be appropriate here, as other means don't result in total of 1.0 when sides are switched. """ scores0_len = len(scores0) scores1_len = len(scores1) scores0p = [x for x in scores0 if not np.isnan(x)] scores1p = [x for x in scores1 if not np.isnan(x)] scores0n_len = scores0_len - len(scores0p) scores1n_len = scores1_len - len(scores1p) # ``nan_pairs`` are pairs for which it is impossible to define order, due # to at least one of the members of each being a NaN. ``def_pairs`` are # pairs for which order can be established. all_pairs = 2 * scores0_len * scores1_len nan_pairs = scores0n_len * scores1_len + scores1n_len * scores0_len def_pairs = all_pairs - nan_pairs # the final score is the average of the score for the defined portion and # of random-chance AUC (0.5), weighted according to the number of pairs in # each group. auc_score = RocCurve.from_scores(scores0p, scores1p).auc_score() return np.average([auc_score, 0.5], weights=[def_pairs, nan_pairs])
bsd-3-clause
Workday/OpenFrame
third_party/WebKit/ManualTests/webaudio/audiobuffersource-looping.html
2933
<!doctype html> <html> <head> <title>AudioBufferSource with Looping Enabled then Disabled</title> <script> var context = new AudioContext(); // Launch countdown example var url = "http://www.nasa.gov/mp3/590318main_ringtone_135_launch.mp3"; function enableButtons() { document.getElementById("Original").disabled = false; document.getElementById("Test").disabled = false; } function disableButtons() { document.getElementById("Original").disabled = true; document.getElementById("Test").disabled = true; } function playClip(loopEndTime) { disableButtons(); var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; request.onload = function () { context.decodeAudioData( request.response, function (buffer) { var source = context.createBufferSource(); source.buffer = buffer; source.connect(context.destination); source.onended = enableButtons; source.start(); // If a loopEndTime is given, enable looping and stop looping after loopEndTime ms. if (loopEndTime) { // These limits were selected to cause the word "eight" to be repeated in the given // URL. If the URL is updated these values probably need to be changed. source.loopStart = 2.2; source.loopEnd = 3; source.loop = true; setTimeout(function () { source.loop = false; }, loopEndTime); } }, function () { alert("Could not get audio clip"); }); }; request.send(); } </script> </head> <body> <h1>AudioBufferSource with looping enabled then disabled</h1> <p> This tests an AudioBufferSource node is not prematurely stopped if looping is enabled for the buffer and then disabled. This can't be tested in an offline context until suspend/resume support is added for an offline context. </p> <p>Press "Original" to play the clip in its entirety (15 sec).</p> <p> Press "Test" to run the test. A part of the clip will be looped for a while and then looping will be turned off. (You should hear "eight" repeated about four times.) The rest of the clip should be heard in its entirety. The onended event should also be fired, enabling the buttons again. If the buttons are not enabled, the test has failed. File a new bug at <a href="http://crbug.com/new">crbug.com/new</a>. </p> <button id="Original" onclick="playClip()">Original</button> <button id="Test" onclick="playClip(5000)">Test</button> </body> </html>
bsd-3-clause
serge-sans-paille/pythran
pythran/tests/cases/empirical.py
678
#from https://github.com/serge-sans-paille/pythran/issues/1229 #runas import numpy as np; x = np.arange(3., 10.); empirical(x, 3., .5) import numpy as np #pythran export empirical(float[:], float, float) def empirical(ds, alpha, x): sds = np.sort(ds) ds_to_the_alpha = sds**alpha fractions = ds_to_the_alpha #/ sum (ds_to_the_alpha) thresholds = np.cumsum(fractions) thresholds /= thresholds[-1] i = find_first (thresholds, lambda u: x < u) return i #pthran export find_first(float[:], bool (float)) def find_first (seq, pred): for i,x in enumerate (seq): print(i, x, pred(x)) if pred(x): return i return None
bsd-3-clause
NimbRo/nimbro-op-ros
src/nimbro/behaviour/soccer_behaviour/src/control_layer/control_head.cpp
1704
// Behaviour Control Framework - Head control behaviour // Author: Philipp Allgeuer <[email protected]> // Includes #include <soccer_behaviour/control_layer/control_head.h> #include <soccer_behaviour/control_layer/control_layer.h> #include <head_control/LookAtTarget.h> // Namespaces using namespace std; using namespace soccerbehaviour; // // Constructors // // Constructor ControlHead::ControlHead(ControlLayer* L) : Behaviour(L, "ControlHead"), L(L), M(L->M), SM(L->SM), AM(L->AM) { } // // Function overrides // // Initialisation function ret_t ControlHead::init() { // Return that initialisation was successful return RET_OK; } // Update function void ControlHead::update() { } // Compute activation level function level_t ControlHead::computeActivationLevel() { // Head control is active by default return true; // Control head is active whenever Search For Ball (inhibits this) is being inhibited by a higher behaviour } // Execute function void ControlHead::execute() { if(wasJustActivated()) ROS_WARN(" CONTROL HEAD just activated!"); geometry_msgs::PointStampedConstPtr focalVec = SM->ballFocalPosition.read(); if(!focalVec) return; // no data yet head_control::LookAtTarget target; target.is_angular_data = true; target.is_relative = true; target.vec.z = atan2(-focalVec->point.x, focalVec->point.z); target.vec.y = atan2(focalVec->point.y, focalVec->point.z); AM->headControlTarget.write(target, this); } // Inhibited function void ControlHead::inhibited() { if(wasJustDeactivated()) ROS_WARN(" CONTROL HEAD just deactivated! XXXXXXXXXXXXXXXXXXXXXXXXXX"); } // // Extra stuff // /* TODO: Define other functions that you need here */ // EOF
bsd-3-clause
fmilano/mitk
Modules/CppMicroServices/core/src/module/usModuleResourceContainer.cpp
6232
/*============================================================================ Library: CppMicroServices Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. 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. ============================================================================*/ #include "usModuleResourceContainer_p.h" #include "usModuleInfo.h" #include "usModuleUtils_p.h" #include "usModuleResource.h" #include "usLog_p.h" #include "miniz.h" #include <set> #include <cstring> #include <climits> #include <cassert> US_BEGIN_NAMESPACE struct ModuleResourceContainerPrivate { ModuleResourceContainerPrivate(const ModuleInfo* moduleInfo) : m_ModuleInfo(moduleInfo) , m_IsValid(false) , m_ZipArchive() {} typedef std::pair<std::string, int> NameIndexPair; struct PairComp { bool operator()(const NameIndexPair& p1, const NameIndexPair& p2) const { return p1.first < p2.first; } }; typedef std::set<NameIndexPair, PairComp> SetType; void InitSortedEntries() { if (m_SortedEntries.empty()) { mz_uint numFiles = mz_zip_reader_get_num_files(&m_ZipArchive); for (mz_uint fileIndex = 0; fileIndex < numFiles; ++fileIndex) { char fileName[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; mz_zip_reader_get_filename(&m_ZipArchive, fileIndex, fileName, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE); m_SortedEntries.insert(std::make_pair(std::string(fileName), fileIndex)); } } } const ModuleInfo* m_ModuleInfo; bool m_IsValid; mz_zip_archive m_ZipArchive; std::set<NameIndexPair, PairComp> m_SortedEntries; }; ModuleResourceContainer::ModuleResourceContainer(const ModuleInfo* moduleInfo) : d(new ModuleResourceContainerPrivate(moduleInfo)) { if (mz_zip_reader_init_file(&d->m_ZipArchive, moduleInfo->location.c_str(), 0)) { d->m_IsValid = true; } else { US_DEBUG << "Could not init zip archive for module " << moduleInfo->name; } } ModuleResourceContainer::~ModuleResourceContainer() { if (IsValid()) { mz_zip_reader_end(&d->m_ZipArchive); } delete d; } bool ModuleResourceContainer::IsValid() const { return d->m_IsValid; } bool ModuleResourceContainer::GetStat(ModuleResourceContainer::Stat& stat) const { if (IsValid()) { int fileIndex = mz_zip_reader_locate_file(&d->m_ZipArchive, stat.filePath.c_str(), nullptr, 0); if (fileIndex >= 0) { return GetStat(fileIndex, stat); } } return false; } bool ModuleResourceContainer::GetStat(int index, ModuleResourceContainer::Stat& stat) const { if (IsValid()) { if (index >= 0) { mz_zip_archive_file_stat zipStat; if (!mz_zip_reader_file_stat(&d->m_ZipArchive, index, &zipStat)) { return false; } stat.index = index; stat.filePath = zipStat.m_filename; stat.isDir = mz_zip_reader_is_file_a_directory(&d->m_ZipArchive, index) ? true : false; stat.modifiedTime = zipStat.m_time; // This will limit the size info from uint64 to uint32 on 32-bit // architectures. We don't care because we assume resources > 2GB // don't make sense to be embedded in a module anyway. assert(zipStat.m_comp_size < INT_MAX); assert(zipStat.m_uncomp_size < INT_MAX); stat.uncompressedSize = static_cast<int>(zipStat.m_uncomp_size); return true; } } return false; } void* ModuleResourceContainer::GetData(int index) const { return mz_zip_reader_extract_to_heap(&d->m_ZipArchive, index, nullptr, 0); } const ModuleInfo*ModuleResourceContainer::GetModuleInfo() const { return d->m_ModuleInfo; } void ModuleResourceContainer::GetChildren(const std::string& resourcePath, bool relativePaths, std::vector<std::string>& names, std::vector<uint32_t>& indices) const { d->InitSortedEntries(); ModuleResourceContainerPrivate::SetType::const_iterator iter = d->m_SortedEntries.find(std::make_pair(resourcePath, 0)); if (iter == d->m_SortedEntries.end()) { return; } for (++iter; iter != d->m_SortedEntries.end(); ++iter) { if (resourcePath.size() > iter->first.size()) break; if (iter->first.compare(0, resourcePath.size(), resourcePath) == 0) { std::size_t pos = iter->first.find_first_of('/', resourcePath.size()); if (pos == std::string::npos || pos == iter->first.size()-1) { if (relativePaths) { names.push_back(iter->first.substr(resourcePath.size())); } else { names.push_back(iter->first); } indices.push_back(iter->second); } } } } void ModuleResourceContainer::FindNodes(const std::string& path, const std::string& filePattern, bool recurse, std::vector<ModuleResource>& resources) const { std::vector<std::string> names; std::vector<uint32_t> indices; this->GetChildren(path, true, names, indices); for(std::size_t i = 0, s = names.size(); i < s; ++i) { if (*names[i].rbegin() == '/' && recurse) { this->FindNodes(path + names[i], filePattern, recurse, resources); } if (this->Matches(names[i], filePattern)) { resources.push_back(ModuleResource(indices[i], *this)); } } } bool ModuleResourceContainer::Matches(const std::string& name, const std::string& filePattern) const { // short-cut if (filePattern == "*") return true; std::stringstream ss(filePattern); std::string tok; std::size_t pos = 0; while(std::getline(ss, tok, '*')) { std::size_t index = name.find(tok, pos); if (index == std::string::npos) return false; pos = index + tok.size(); } return true; } US_END_NAMESPACE
bsd-3-clause
wadejong/avogadrolibs
avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.h
2687
/****************************************************************************** This source file is part of the Avogadro project. Copyright 2010 Eric C. Brown This source code is released under the New BSD License, (the "License"). 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. ******************************************************************************/ #ifndef QTAIMCRITICALPOINTLOCATOR_H #define QTAIMCRITICALPOINTLOCATOR_H #include <QDebug> #include <QList> #include <QVector3D> #include <QPair> #include "qtaimwavefunction.h" #include "qtaimwavefunctionevaluator.h" #include "qtaimmathutilities.h" namespace Avogadro { namespace QtPlugins { class QTAIMCriticalPointLocator { public: explicit QTAIMCriticalPointLocator(QTAIMWavefunction &wfn); void locateNuclearCriticalPoints(); void locateBondCriticalPoints(); void locateElectronDensitySources(); void locateElectronDensitySinks(); QList<QVector3D> nuclearCriticalPoints() const { return m_nuclearCriticalPoints; } QList<QVector3D> bondCriticalPoints() const { return m_bondCriticalPoints; } QList<QVector3D> ringCriticalPoints() const { return m_ringCriticalPoints; } QList<QVector3D> cageCriticalPoints() const { return m_cageCriticalPoints; } QList<qreal> laplacianAtBondCriticalPoints() const { return m_laplacianAtBondCriticalPoints; } QList<qreal> ellipticityAtBondCriticalPoints() const { return m_ellipticityAtBondCriticalPoints; } QList<QList<QVector3D> > bondPaths() {return m_bondPaths; } QList<QPair<qint64,qint64> > bondedAtoms() {return m_bondedAtoms; } QList<QVector3D> electronDensitySources() const { return m_electronDensitySources; } QList<QVector3D> electronDensitySinks() const { return m_electronDensitySinks; } private: QTAIMWavefunction *m_wfn; QList<QVector3D> m_nuclearCriticalPoints; QList<QVector3D> m_bondCriticalPoints; QList<QVector3D> m_ringCriticalPoints; QList<QVector3D> m_cageCriticalPoints; QList<qreal> m_laplacianAtBondCriticalPoints; QList<qreal> m_ellipticityAtBondCriticalPoints; QList<QPair<qint64, qint64> > m_bondedAtoms; QList<QList<QVector3D> > m_bondPaths; QList<QVector3D> m_electronDensitySources; QList<QVector3D> m_electronDensitySinks; QString temporaryFileName(); }; } // namespace QtPlugins } // namespace Avogadro #endif // QTAIMCRITICALPOINTLOCATOR_H
bsd-3-clause
tenbits/highlight.js
test/special/languageAlias.js
557
'use strict'; var _ = require('lodash'); var utility = require('../utility'); describe('language alias', function() { before(function() { var testHTML = document.querySelectorAll('#language-alias .hljs'); this.blocks = _.map(testHTML, 'innerHTML'); }); it('should highlight as aliased language', function() { var filename = utility.buildPath('fixtures', 'expect', 'languagealias.txt'), actual = this.blocks[0]; return utility.expectedFile(filename, 'utf-8', actual); }); });
bsd-3-clause
magicDGS/gatk
src/test/java/org/broadinstitute/hellbender/tools/spark/sv/integration/CpxVariantReInterpreterSparkIntegrationTest.java
8322
package org.broadinstitute.hellbender.tools.spark.sv.integration; import htsjdk.samtools.util.CloseableIterator; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFFileReader; import org.apache.hadoop.fs.Path; import org.broadinstitute.hellbender.CommandLineProgramTest; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.utils.Utils; import org.broadinstitute.hellbender.testutils.ArgumentsBuilder; import org.broadinstitute.hellbender.testutils.MiniClusterUtils; import org.broadinstitute.hellbender.testutils.VariantContextTestUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CpxVariantReInterpreterSparkIntegrationTest extends CommandLineProgramTest { private static final String THIS_TEST_FOLDER = getTestDataDir() + "/spark/sv/integration/inputs/"; private static final String complexVCF = THIS_TEST_FOLDER + "CpxVariantReInterpreterSparkIntegrationTest_complex.vcf"; private static final String assemblyAlignmentsAccompanyingComplexVCF = largeFileTestDir + "/sv/CpxVariantReInterpreterSparkIntegrationTest_complex_assembly.bam"; private static final File fastaReference = new File(b38_reference_20_21); private static final String nonCanonicalChromosomeNamesFile = THIS_TEST_FOLDER + "Homo_sapiens_assembly38.kill.alts"; private static final String outPrefix = "cpx_reinterpreted_simple"; private static final String expectedOneSegmentVCF = getTestDataDir() + "/spark/sv/integration/outputs/cpx_reinterpreted_simple_1_seg.vcf"; private static final String expectedMultiSegmentVCF = getTestDataDir() + "/spark/sv/integration/outputs/cpx_reinterpreted_simple_multi_seg.vcf"; private static final List<String> annotationsToIgnoreWhenComparingVariants = Collections.emptyList(); private static final class CpxVariantReInterpreterSparkIntegrationTestArgs { final String outputDir; CpxVariantReInterpreterSparkIntegrationTestArgs(final String outputDir) { this.outputDir = outputDir; } String getCommandLine() { return " -R " + fastaReference + " -I " + assemblyAlignmentsAccompanyingComplexVCF + " --non-canonical-contig-names-file " + nonCanonicalChromosomeNamesFile + " --cpx-vcf " + complexVCF + " --prefix-out-vcf " + outputDir + "/" + outPrefix; } } @DataProvider(name = "forCpxVariantReInterpreterSparkIntegrationTest") private Object[][] createData() { List<Object[]> data = new ArrayList<>(); final File cpxVariantReInterpreterSparkIntegrationTest = createTempDir("CpxVariantReInterpreterSparkIntegrationTest"); data.add(new Object[]{new CpxVariantReInterpreterSparkIntegrationTestArgs(cpxVariantReInterpreterSparkIntegrationTest.getAbsolutePath())}); return data.toArray(new Object[data.size()][]); } @Test(groups = "sv", dataProvider = "forCpxVariantReInterpreterSparkIntegrationTest") public void testRunLocal(final CpxVariantReInterpreterSparkIntegrationTestArgs params) throws Exception { final List<String> args = Arrays.asList( new ArgumentsBuilder().add(params.getCommandLine()).getArgsArray() ); runCommandLine(args); final String actualVCFForOneSegmentCalls = params.outputDir + "/" + outPrefix + "_1_seg.vcf"; vcfEquivalenceTest(actualVCFForOneSegmentCalls, expectedOneSegmentVCF, annotationsToIgnoreWhenComparingVariants, false); final String actualVCFForMultiSegmentCalls = params.outputDir + "/" + outPrefix + "_multi_seg.vcf"; vcfEquivalenceTest(actualVCFForMultiSegmentCalls, expectedMultiSegmentVCF, annotationsToIgnoreWhenComparingVariants, false); } @Test(groups = "sv", dataProvider = "forCpxVariantReInterpreterSparkIntegrationTest") public void testRunHDFS(final CpxVariantReInterpreterSparkIntegrationTestArgs params) throws Exception { MiniClusterUtils.runOnIsolatedMiniCluster(cluster -> { final List<String> argsToBeModified = Arrays.asList( new ArgumentsBuilder().add(params.getCommandLine()).getArgsArray() ); final Path workingDirectory = MiniClusterUtils.getWorkingDir(cluster); int idx = 0; // copy inputs idx = argsToBeModified.indexOf("-I"); Path path = new Path(workingDirectory, "hdfs.bam"); File file = new File(argsToBeModified.get(idx+1)); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); argsToBeModified.set(idx+1, path.toUri().toString()); path = new Path(workingDirectory, "hdfs.bam.bai"); // .bai file = new File(file.getAbsolutePath() + ".bai"); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); idx = argsToBeModified.indexOf("-R"); path = new Path(workingDirectory, "reference.fasta"); file = new File(argsToBeModified.get(idx+1)); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); argsToBeModified.set(idx+1, path.toUri().toString()); path = new Path(workingDirectory, "reference.fasta.fai"); // .fasta.fai for fasta file = new File(file.getAbsolutePath() + ".fai"); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); path = new Path(workingDirectory, "reference.dict"); // .dict for fasta file = new File(file.getAbsolutePath().replace(".fasta.fai", ".dict")); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); idx = argsToBeModified.indexOf("--non-canonical-contig-names-file"); path = new Path(workingDirectory, "Homo_sapiens_assembly38.kill.alts"); file = new File(argsToBeModified.get(idx+1)); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); argsToBeModified.set(idx+1, path.toUri().toString()); idx = argsToBeModified.indexOf("--cpx-vcf"); path = new Path(workingDirectory, "CpxVariantReInterpreterSparkIntegrationTest_complex.vcf"); file = new File(argsToBeModified.get(idx+1)); cluster.getFileSystem().copyFromLocalFile(new Path(file.toURI()), path); argsToBeModified.set(idx+1, path.toUri().toString()); // outputs, prefix with hdfs address idx = argsToBeModified.indexOf("--prefix-out-vcf"); path = new Path(workingDirectory, "test"); argsToBeModified.set(idx+1, path.toUri().toString()); runCommandLine(argsToBeModified); final String actualVCFForOneSegmentCallsOnHDFS = path.toUri().toString() + "_1_seg.vcf"; final String actualVCFForMultiSegmentCallsOnHDFS = path.toUri().toString() + "_multi_seg.vcf"; vcfEquivalenceTest(actualVCFForOneSegmentCallsOnHDFS, expectedOneSegmentVCF, annotationsToIgnoreWhenComparingVariants, true); vcfEquivalenceTest(actualVCFForMultiSegmentCallsOnHDFS, expectedMultiSegmentVCF, annotationsToIgnoreWhenComparingVariants, true); }); } private static void vcfEquivalenceTest(final String generatedVCFPath, final String expectedVCFPath, final List<String> attributesToIgnore, final boolean onHDFS) throws Exception { List<VariantContext> expectedVcs; try (final VCFFileReader fileReader = new VCFFileReader(new File(expectedVCFPath), false) ) { try (final CloseableIterator<VariantContext> iterator = fileReader.iterator()) { expectedVcs = Utils.stream(iterator).collect(Collectors.toList()); } } final List<VariantContext> actualVcs = StructuralVariationDiscoveryPipelineSparkIntegrationTest .extractActualVCs(generatedVCFPath, onHDFS); GATKBaseTest.assertCondition(actualVcs, expectedVcs, (a, e) -> VariantContextTestUtils.assertVariantContextsAreEqual(a, e, attributesToIgnore)); } }
bsd-3-clause
google/skia
include/core/SkCustomMesh.h
8753
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkCustomMesh_DEFINED #define SkCustomMesh_DEFINED #include "include/core/SkTypes.h" #ifdef SK_ENABLE_SKSL #include "include/core/SkColorSpace.h" #include "include/core/SkImageInfo.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkSpan.h" #include "include/core/SkString.h" #include <vector> namespace SkSL { struct Program; } /** * A specification for custom meshes. Specifies the vertex buffer attributes and stride, the * vertex program that produces a user-defined set of varyings, a fragment program that ingests * the interpolated varyings and produces local coordinates and optionally a color. * * The signature of the vertex program must be: * float2 main(Attributes, out Varyings) * where the return value is a local position that will be transformed by SkCanvas's matrix. * * The signature of the fragment program must be either: * (float2|void) main(Varyings) * or * (float2|void) main(Varyings, out (half4|float4) color) * * where the return value is the local coordinates that will be used to access SkShader. If the * return type is void then the interpolated position from vertex shader return is used as the local * coordinate. If the color variant is used it will be blended with SkShader (or SkPaint color in * absence of a shader) using the SkBlender provided to the SkCanvas draw call. */ class SkCustomMeshSpecification : public SkNVRefCnt<SkCustomMeshSpecification> { public: /** These values are enforced when creating a specification. */ static constexpr size_t kMaxStride = 1024; static constexpr size_t kMaxAttributes = 8; static constexpr size_t kStrideAlignment = 4; static constexpr size_t kOffsetAlignment = 4; static constexpr size_t kMaxVaryings = 6; struct Attribute { enum class Type : uint32_t { // CPU representation Shader Type kFloat, // float float kFloat2, // two floats float2 kFloat3, // three floats float3 kFloat4, // four floats float4 kUByte4_unorm, // four bytes half4 kLast = kUByte4_unorm }; Type type; size_t offset; SkString name; }; struct Varying { enum class Type : uint32_t { kFloat, // "float" kFloat2, // "float2" kFloat3, // "float3" kFloat4, // "float4" kHalf, // "half" kHalf2, // "half2" kHalf3, // "half3" kHalf4, // "half4" kLast = kHalf4 }; Type type; SkString name; }; ~SkCustomMeshSpecification(); struct Result { sk_sp<SkCustomMeshSpecification> specification; SkString error; }; /** * If successful the return is a specification and an empty error string. Otherwise, it is a * null specification a non-empty error string. * * @param attributes The vertex attributes that will be consumed by 'vs'. Attributes need * not be tightly packed but attribute offsets must be aligned to * kOffsetAlignment and offset + size may not be greater than * 'vertexStride'. At least one attribute is required. * @param vertexStride The offset between successive attribute values. This must be aligned to * kStrideAlignment. * @param varyings The varyings that will be written by 'vs' and read by 'fs'. This may * be empty. * @param vs The vertex shader code that computes a vertex position and the varyings * from the attributes. * @param fs The fragment code that computes a local coordinate and optionally a * color from the varyings. The local coordinate is used to sample * SkShader. * @param cs The colorspace of the color produced by 'fs'. Ignored if 'fs's main() * function does not have a color out param. * @param at The alpha type of the color produced by 'fs'. Ignored if 'fs's main() * function does not have a color out param. Cannot be kUnknown. */ static Result Make(SkSpan<const Attribute> attributes, size_t vertexStride, SkSpan<const Varying> varyings, const SkString& vs, const SkString& fs, sk_sp<SkColorSpace> cs = SkColorSpace::MakeSRGB(), SkAlphaType at = kPremul_SkAlphaType); SkSpan<const Attribute> attributes() const { return SkMakeSpan(fAttributes); } size_t stride() const { return fStride; } private: friend struct SkCustomMeshSpecificationPriv; enum class ColorType { kNone, kHalf4, kFloat4, }; static Result MakeFromSourceWithStructs(SkSpan<const Attribute> attributes, size_t stride, SkSpan<const Varying> varyings, const SkString& vs, const SkString& fs, sk_sp<SkColorSpace> cs, SkAlphaType at); SkCustomMeshSpecification(SkSpan<const Attribute>, size_t, SkSpan<const Varying>, std::unique_ptr<SkSL::Program>, std::unique_ptr<SkSL::Program>, ColorType, bool hasLocalCoords, sk_sp<SkColorSpace>, SkAlphaType); SkCustomMeshSpecification(const SkCustomMeshSpecification&) = delete; SkCustomMeshSpecification(SkCustomMeshSpecification&&) = delete; SkCustomMeshSpecification& operator=(const SkCustomMeshSpecification&) = delete; SkCustomMeshSpecification& operator=(SkCustomMeshSpecification&&) = delete; const std::vector<Attribute> fAttributes; const std::vector<Varying> fVaryings; std::unique_ptr<SkSL::Program> fVS; std::unique_ptr<SkSL::Program> fFS; size_t fStride; uint32_t fHash; ColorType fColorType; bool fHasLocalCoords; sk_sp<SkColorSpace> fColorSpace; SkAlphaType fAlphaType; }; /** * This is a placeholder object. We will want something that allows the client to incrementally * update the mesh that can be synchronized with the GPU backend without requiring extra copies. * * A buffer of vertices, a topology, optionally indices, and a compatible SkCustomMeshSpecification. * The data in 'vb' is expected to contain the attributes described in 'spec' for 'vcount' vertices. * The size of the buffer must be at least spec->stride()*vcount (even if vertex attributes contains * pad at the end of the stride). If 'bounds' does not contain all points output by 'spec''s vertex * program when applied to the vertices in 'vb' a draw of the custom mesh produces undefined * results. * * If indices is null then then 'icount' must be <= 0. 'vcount' vertices will be selected from 'vb' * to create the topology indicated by 'mode'. * * If indices is not null then icount must be >= 3. 'vb' will be indexed by 'icount' successive * values in 'indices' to create the topology indicated by 'mode'. The values in 'indices' must be * less than 'vcount' */ struct SkCustomMesh { enum class Mode { kTriangles, kTriangleStrip }; sk_sp<SkCustomMeshSpecification> spec; Mode mode = Mode::kTriangles; SkRect bounds = SkRect::MakeEmpty(); const void* vb = nullptr; int vcount = 0; const uint16_t* indices = nullptr; int icount = 0; }; #endif // SK_ENABLE_SKSL #endif
bsd-3-clause
EmergentOrder/clmagma
testing/testing_spotrf_mgpu.cpp
9790
/* * -- clMAGMA (version 1.1.0) -- * Univ. of Tennessee, Knoxville * Univ. of California, Berkeley * Univ. of Colorado, Denver * @date January 2014 * * @generated from testing_zpotrf_mgpu.cpp normal z -> s, Fri Jan 10 15:51:19 2014 * **/ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // includes, project #include "flops.h" #include "magma.h" #include "magma_lapack.h" #include "testings.h" #define PRECISION_s // Flops formula #if defined(PRECISION_z) || defined(PRECISION_c) #define FLOPS(n) ( 6. * FMULS_POTRF(n) + 2. * FADDS_POTRF(n) ) #else #define FLOPS(n) ( FMULS_POTRF(n) + FADDS_POTRF(n) ) #endif /* //////////////////////////////////////////////////////////////////////////// -- Testing spotrf_mgpu */ #define h_A(i,j) h_A[ i + j*lda ] int main( int argc, char** argv) { real_Double_t gflops, gpu_perf, cpu_perf, gpu_time, cpu_time; float *h_A, *h_R; magmaFloat_ptr d_lA[MagmaMaxGPUs]; magma_int_t N = 0, n2, lda, ldda; magma_int_t size[10] = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 }; magma_int_t i, j, k, info; float mz_one = MAGMA_S_NEG_ONE; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; float work[1], matnorm, diffnorm; magma_int_t num_gpus0 = 1, num_gpus, flag = 0; int nb, mb, n_local, nk; magma_uplo_t uplo = MagmaLower; if (argc != 1){ for(i = 1; i<argc; i++){ if (strcmp("-N", argv[i])==0){ N = atoi(argv[++i]); if (N>0) { size[0] = size[9] = N; flag = 1; }else exit(1); } if(strcmp("-NGPU", argv[i])==0) num_gpus0 = atoi(argv[++i]); if(strcmp("-UPLO", argv[i])==0){ if(strcmp("L", argv[++i])==0){ uplo = MagmaLower; }else{ uplo = MagmaUpper; } } } } else { printf("\nUsage: \n"); printf(" testing_spotrf_mgpu -N %d -NGPU %d -UPLO -L\n\n", 1024, num_gpus0); } /* looking for max. ldda */ ldda = 0; n2 = 0; for(i=0;i<10;i++){ N = size[i]; nb = magma_get_spotrf_nb(N); mb = nb; if(num_gpus0 > N/nb){ num_gpus = N/nb; if(N%nb != 0) num_gpus ++; }else{ num_gpus = num_gpus0; } n_local = nb*(1+N/(nb*num_gpus))*mb*((N+mb-1)/mb); if(n_local > ldda) ldda = n_local; if(n2 < N*N) n2 = N*N; if(flag != 0) break; } /* Allocate host memory for the matrix */ TESTING_MALLOC_PIN( h_A, float, n2 ); TESTING_MALLOC_PIN( h_R, float, n2 ); /* Initialize */ magma_queue_t queues[MagmaMaxGPUs * 2]; //magma_queue_t queues[MagmaMaxGPUs]; magma_device_t devices[ MagmaMaxGPUs ]; int num = 0; magma_err_t err; magma_init(); err = magma_get_devices( devices, MagmaMaxGPUs, &num ); if ( err != 0 || num < 1 ) { fprintf( stderr, "magma_get_devices failed: %d\n", err ); exit(-1); } for(i=0;i<num_gpus;i++){ err = magma_queue_create( devices[i], &queues[2*i] ); if ( err != 0 ) { fprintf( stderr, "magma_queue_create failed: %d\n", err ); exit(-1); } err = magma_queue_create( devices[i], &queues[2*i+1] ); if ( err != 0 ) { fprintf( stderr, "magma_queue_create failed: %d\n", err ); exit(-1); } } printf("each buffer size: %d\n", ldda); /* allocate local matrix on Buffers */ for(i=0; i<num_gpus0; i++){ TESTING_MALLOC_DEV( d_lA[i], float, ldda ); } printf("\n\n"); printf("Using GPUs: %d\n", num_gpus0); if(uplo == MagmaUpper){ printf("\n testing_spotrf_mgpu -N %d -NGPU %d -UPLO U\n\n", N, num_gpus0); }else{ printf("\n testing_spotrf_mgpu -N %d -NGPU %d -UPLO L\n\n", N, num_gpus0); } printf(" N CPU GFlop/s (sec) GPU GFlop/s (sec) ||R_magma-R_lapack||_F / ||R_lapack||_F\n"); printf("========================================================================================\n"); for(i=0; i<10; i++){ N = size[i]; lda = N; n2 = lda*N; ldda = ((N+31)/32)*32; gflops = FLOPS( (float)N ) * 1e-9; /* Initialize the matrix */ lapackf77_slarnv( &ione, ISEED, &n2, h_A ); /* Symmetrize and increase the diagonal */ for( int i = 0; i < N; ++i ) { MAGMA_S_SET2REAL( h_A(i,i), MAGMA_S_REAL(h_A(i,i)) + N ); for( int j = 0; j < i; ++j ) { h_A(i, j) = MAGMA_S_CNJG( h_A(j,i) ); } } lapackf77_slacpy( MagmaFullStr, &N, &N, h_A, &lda, h_R, &lda ); /* Warm up to measure the performance */ nb = magma_get_spotrf_nb(N); if(num_gpus0 > N/nb){ num_gpus = N/nb; if(N%nb != 0) num_gpus ++; printf("too many GPUs for the matrix size, using %d GPUs\n", (int)num_gpus); }else{ num_gpus = num_gpus0; } /* distribute matrix to gpus */ if(uplo == MagmaUpper){ // Upper ldda = ((N+mb-1)/mb)*mb; for(j=0;j<N;j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_ssetmatrix(N, nk, &h_A[j*lda], 0, lda, d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda, queues[2*k]); } }else{ // Lower ldda = (1+N/(nb*num_gpus))*nb; for(j=0;j<N;j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_ssetmatrix(nk, N, &h_A[j], 0, lda, d_lA[k], (j/(nb*num_gpus)*nb), ldda, queues[2*k]); } } magma_spotrf_mgpu( num_gpus, uplo, N, d_lA, 0, ldda, &info, queues ); /* ==================================================================== Performs operation using MAGMA =================================================================== */ /* distribute matrix to gpus */ if(uplo == MagmaUpper){ // Upper ldda = ((N+mb-1)/mb)*mb; for(j=0;j<N;j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_ssetmatrix(N, nk, &h_A[j*lda], 0, lda, d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda, queues[2*k]); } }else{ // Lower ldda = (1+N/(nb*num_gpus))*nb; for(j=0;j<N;j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_ssetmatrix(nk, N, &h_A[j], 0, lda, d_lA[k], (j/(nb*num_gpus)*nb), ldda, queues[2*k]); } } gpu_time = magma_wtime(); magma_spotrf_mgpu( num_gpus, uplo, N, d_lA, 0, ldda, &info, queues ); gpu_time = magma_wtime() - gpu_time; if (info != 0) printf( "magma_spotrf had error %d.\n", info ); gpu_perf = gflops / gpu_time; /* gather matrix from gpus */ if(uplo==MagmaUpper){ // Upper for(j=0;j<N;j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_sgetmatrix(N, nk, d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda, &h_R[j*lda], 0, lda, queues[2*k]); } }else{ // Lower for(j=0; j<N; j+=nb){ k = (j/nb)%num_gpus; nk = min(nb, N-j); magma_sgetmatrix( nk, N, d_lA[k], (j/(nb*num_gpus)*nb), ldda, &h_R[j], 0, lda, queues[2*k] ); } } /* ===================================================================== Performs operation using LAPACK =================================================================== */ cpu_time = magma_wtime(); if(uplo == MagmaLower){ lapackf77_spotrf( MagmaLowerStr, &N, h_A, &lda, &info ); }else{ lapackf77_spotrf( MagmaUpperStr, &N, h_A, &lda, &info ); } cpu_time = magma_wtime() - cpu_time; if (info != 0) printf( "lapackf77_spotrf had error %d.\n", info ); cpu_perf = gflops / cpu_time; /* ===================================================================== Check the result compared to LAPACK |R_magma - R_lapack| / |R_lapack| =================================================================== */ matnorm = lapackf77_slange("f", &N, &N, h_A, &lda, work); blasf77_saxpy(&n2, &mz_one, h_A, &ione, h_R, &ione); diffnorm = lapackf77_slange("f", &N, &N, h_R, &lda, work); printf( "%5d %6.2f (%6.2f) %6.2f (%6.2f) %e\n", N, cpu_perf, cpu_time, gpu_perf, gpu_time, diffnorm / matnorm ); if (flag != 0) break; } /* clean up */ TESTING_FREE_PIN( h_A ); TESTING_FREE_PIN( h_R ); for(i=0;i<num_gpus;i++){ TESTING_FREE_DEV( d_lA[i] ); magma_queue_destroy( queues[2*i] ); magma_queue_destroy( queues[2*i+1] ); } magma_finalize(); }
bsd-3-clause
SvenBunge/tracee
binding/jaxws/src/main/java/io/tracee/binding/jaxws/TraceeClientHandlerResolver.java
677
package io.tracee.binding.jaxws; import io.tracee.TraceeBackend; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.HandlerResolver; import javax.xml.ws.handler.PortInfo; import java.util.ArrayList; import java.util.List; public class TraceeClientHandlerResolver implements HandlerResolver { private final List<Handler> handlerList = new ArrayList<>(); public TraceeClientHandlerResolver() { handlerList.add(new TraceeClientHandler()); } TraceeClientHandlerResolver(TraceeBackend backend) { handlerList.add(new TraceeClientHandler(backend)); } @Override public final List<Handler> getHandlerChain(PortInfo portInfo) { return handlerList; } }
bsd-3-clause
chintak/scikit-image
skimage/filter/tests/test_ctmf.py
3895
import numpy as np from nose.tools import raises from skimage.filter import median_filter def test_00_00_zeros(): '''The median filter on an array of all zeros should be zero''' result = median_filter(np.zeros((10, 10)), 3, np.ones((10, 10), bool)) assert np.all(result == 0) def test_00_01_all_masked(): '''Test a completely masked image Regression test of IMG-1029''' result = median_filter(np.zeros((10, 10)), 3, np.zeros((10, 10), bool)) assert (np.all(result == 0)) def test_00_02_all_but_one_masked(): mask = np.zeros((10, 10), bool) mask[5, 5] = True median_filter(np.zeros((10, 10)), 3, mask) def test_01_01_mask(): '''The median filter, masking a single value''' img = np.zeros((10, 10)) img[5, 5] = 1 mask = np.ones((10, 10), bool) mask[5, 5] = False result = median_filter(img, 3, mask) assert (np.all(result[mask] == 0)) np.testing.assert_equal(result[5, 5], 1) def test_02_01_median(): '''A median filter larger than the image = median of image''' np.random.seed(0) img = np.random.uniform(size=(9, 9)) result = median_filter(img, 20, np.ones((9, 9), bool)) np.testing.assert_equal(result[0, 0], np.median(img)) assert (np.all(result == np.median(img))) def test_02_02_median_bigger(): '''Use an image of more than 255 values to test approximation''' np.random.seed(0) img = np.random.uniform(size=(20, 20)) result = median_filter(img, 40, np.ones((20, 20), bool)) sorted = np.ravel(img) sorted.sort() min_acceptable = sorted[198] max_acceptable = sorted[202] assert (np.all(result >= min_acceptable)) assert (np.all(result <= max_acceptable)) def test_03_01_shape(): '''Make sure the median filter is the expected octagonal shape''' radius = 5 a_2 = int(radius / 2.414213) i, j = np.mgrid[-10:11, -10:11] octagon = np.ones((21, 21), bool) # # constrain the octagon mask to be the points that are on # the correct side of the 8 edges # octagon[i < -radius] = False octagon[i > radius] = False octagon[j < -radius] = False octagon[j > radius] = False octagon[i + j < -radius - a_2] = False octagon[j - i > radius + a_2] = False octagon[i + j > radius + a_2] = False octagon[i - j > radius + a_2] = False np.random.seed(0) img = np.random.uniform(size=(21, 21)) result = median_filter(img, radius, np.ones((21, 21), bool)) sorted = img[octagon] sorted.sort() min_acceptable = sorted[len(sorted) / 2 - 1] max_acceptable = sorted[len(sorted) / 2 + 1] assert (result[10, 10] >= min_acceptable) assert (result[10, 10] <= max_acceptable) def test_04_01_half_masked(): '''Make sure that the median filter can handle large masked areas.''' img = np.ones((20, 20)) mask = np.ones((20, 20), bool) mask[10:, :] = False img[~ mask] = 2 img[1, 1] = 0 # to prevent short circuit for uniform data. result = median_filter(img, 5, mask) # in partial coverage areas, the result should be only # from the masked pixels assert (np.all(result[:14, :] == 1)) # in zero coverage areas, the result should be the lowest # value in the valid area assert (np.all(result[15:, :] == np.min(img[mask]))) def test_default_values(): img = (np.random.random((20, 20)) * 255).astype(np.uint8) mask = np.ones((20, 20), dtype=np.uint8) result1 = median_filter(img, radius=2, mask=mask, percent=50) result2 = median_filter(img) np.testing.assert_array_equal(result1, result2) @raises(ValueError) def test_insufficient_size(): img = (np.random.random((20, 20)) * 255).astype(np.uint8) median_filter(img, radius=1) @raises(TypeError) def test_wrong_shape(): img = np.empty((10, 10, 3)) median_filter(img) if __name__ == "__main__": np.testing.run_module_suite()
bsd-3-clause
Erin-Mounts/mPowerSDK
mPowerSDK/TasksAndSteps/MoodSurvey/CustomView/APHCustomTextView.h
1836
// // APHCustomTextView.h // mPowerSDK // // Copyright (c) 2015, 2016, Sage Bionetworks. All rights reserved. // // 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. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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. // #import <UIKit/UIKit.h> @interface APHCustomTextView : UITextView @end
bsd-3-clause
patrickianwilson/vijava-contrib
src/main/java/com/vmware/vim25/HostCapabilityFtUnsupportedReason.java
2147
/*================================================================================ Copyright (c) 2013 Steve Jin. 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. * Neither the names of copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 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. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ public enum HostCapabilityFtUnsupportedReason { vMotionNotLicensed ("vMotionNotLicensed"), missingVMotionNic ("missingVMotionNic"), missingFTLoggingNic ("missingFTLoggingNic"), ftNotLicensed ("ftNotLicensed"), haAgentIssue ("haAgentIssue"); @SuppressWarnings("unused") private final String val; private HostCapabilityFtUnsupportedReason(String val) { this.val = val; } }
bsd-3-clause
antsmc2/mics
survey/migrations/0119_auto__add_field_batchlocationstatus_non_response.py
36447
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'BatchLocationStatus.non_response' db.add_column(u'survey_batchlocationstatus', 'non_response', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'BatchLocationStatus.non_response' db.delete_column(u'survey_batchlocationstatus', 'non_response') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'locations.location': { 'Meta': {'object_name': 'Location'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'parent_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'parent_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'point': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Point']", 'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['locations.Location']"}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations'", 'null': 'True', 'to': u"orm['locations.LocationType']"}) }, u'locations.locationtype': { 'Meta': {'object_name': 'LocationType'}, 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'primary_key': 'True'}) }, u'locations.point': { 'Meta': {'object_name': 'Point'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'}), 'longitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'}) }, 'survey.answerrule': { 'Meta': {'object_name': 'AnswerRule'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_rule'", 'null': 'True', 'to': "orm['survey.Batch']"}), 'condition': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'next_question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'parent_question_rules'", 'null': 'True', 'to': "orm['survey.Question']"}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'rule'", 'null': 'True', 'to': "orm['survey.Question']"}), 'validate_with_max_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}), 'validate_with_min_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}), 'validate_with_option': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answer_rule'", 'null': 'True', 'to': "orm['survey.QuestionOption']"}), 'validate_with_question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}), 'validate_with_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}) }, 'survey.backend': { 'Meta': {'object_name': 'Backend'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}) }, 'survey.batch': { 'Meta': {'unique_together': "(('survey', 'name'),)", 'object_name': 'Batch'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch'", 'null': 'True', 'to': "orm['survey.Survey']"}) }, 'survey.batchlocationstatus': { 'Meta': {'object_name': 'BatchLocationStatus'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'open_locations'", 'null': 'True', 'to': "orm['survey.Batch']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'open_batches'", 'null': 'True', 'to': u"orm['locations.Location']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'non_response': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'survey.batchquestionorder': { 'Meta': {'object_name': 'BatchQuestionOrder'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_question_order'", 'to': "orm['survey.Batch']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'question_batch_order'", 'to': "orm['survey.Question']"}) }, 'survey.formula': { 'Meta': {'object_name': 'Formula'}, 'count': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_count'", 'null': 'True', 'to': "orm['survey.Question']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'denominator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_denominator'", 'null': 'True', 'to': "orm['survey.Question']"}), 'denominator_options': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'denominator_options'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['survey.QuestionOption']"}), 'groups': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_group'", 'null': 'True', 'to': "orm['survey.HouseholdMemberGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'formula'", 'null': 'True', 'to': "orm['survey.Indicator']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'numerator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'as_numerator'", 'null': 'True', 'to': "orm['survey.Question']"}), 'numerator_options': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'numerator_options'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['survey.QuestionOption']"}) }, 'survey.groupcondition': { 'Meta': {'unique_together': "(('value', 'attribute', 'condition'),)", 'object_name': 'GroupCondition'}, 'attribute': ('django.db.models.fields.CharField', [], {'default': "'AGE'", 'max_length': '20'}), 'condition': ('django.db.models.fields.CharField', [], {'default': "'EQUALS'", 'max_length': '20'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'conditions'", 'symmetrical': 'False', 'to': "orm['survey.HouseholdMemberGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'survey.household': { 'Meta': {'object_name': 'Household'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'households'", 'null': 'True', 'to': "orm['survey.Investigator']"}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'random_sample_number': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'survey_household'", 'null': 'True', 'to': "orm['survey.Survey']"}), 'uid': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}) }, 'survey.householdbatchcompletion': { 'Meta': {'object_name': 'HouseholdBatchCompletion'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_completion_households'", 'null': 'True', 'to': "orm['survey.Batch']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_completion_batches'", 'null': 'True', 'to': "orm['survey.Household']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Investigator']", 'null': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}) }, 'survey.householdhead': { 'Meta': {'object_name': 'HouseholdHead', '_ormbases': ['survey.HouseholdMember']}, u'householdmember_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['survey.HouseholdMember']", 'unique': 'True', 'primary_key': 'True'}), 'level_of_education': ('django.db.models.fields.CharField', [], {'default': "'Primary'", 'max_length': '100', 'null': 'True'}), 'occupation': ('django.db.models.fields.CharField', [], {'default': "'16'", 'max_length': '100'}), 'resident_since_month': ('django.db.models.fields.PositiveIntegerField', [], {'default': '5'}), 'resident_since_year': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1984'}) }, 'survey.householdmember': { 'Meta': {'object_name': 'HouseholdMember'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'household_member'", 'to': "orm['survey.Household']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'male': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'surname': ('django.db.models.fields.CharField', [], {'max_length': '25'}) }, 'survey.householdmemberbatchcompletion': { 'Meta': {'object_name': 'HouseholdMemberBatchCompletion'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_households'", 'null': 'True', 'to': "orm['survey.Batch']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_batches'", 'null': 'True', 'to': "orm['survey.Household']"}), 'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_member_batches'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_batches'", 'null': 'True', 'to': "orm['survey.Investigator']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}) }, 'survey.householdmembergroup': { 'Meta': {'object_name': 'HouseholdMemberGroup'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'unique': 'True', 'max_length': '5'}) }, 'survey.indicator': { 'Meta': {'object_name': 'Indicator'}, 'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'measure': ('django.db.models.fields.CharField', [], {'default': "'Percentage'", 'max_length': '255'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'indicator'", 'to': "orm['survey.QuestionModule']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'survey.investigator': { 'Meta': {'object_name': 'Investigator'}, 'age': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'backend': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Backend']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_blocked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'English'", 'max_length': '100', 'null': 'True'}), 'level_of_education': ('django.db.models.fields.CharField', [], {'default': "'Primary'", 'max_length': '100', 'null': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}), 'male': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'mobile_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'weights': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, 'survey.locationautocomplete': { 'Meta': {'object_name': 'LocationAutoComplete'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '500'}) }, 'survey.locationcode': { 'Meta': {'object_name': 'LocationCode'}, 'code': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '10'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'code'", 'to': u"orm['locations.Location']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}) }, 'survey.locationtypedetails': { 'Meta': {'object_name': 'LocationTypeDetails'}, 'country': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'details'", 'null': 'True', 'to': u"orm['locations.Location']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'has_code': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'length_of_code': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'location_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'details'", 'to': u"orm['locations.LocationType']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'unique': 'True', 'null': 'True', 'blank': 'True'}), 'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'survey.locationweight': { 'Meta': {'object_name': 'LocationWeight'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'weight'", 'to': u"orm['locations.Location']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'selection_probability': ('django.db.models.fields.FloatField', [], {'default': '1.0'}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'location_weight'", 'to': "orm['survey.Survey']"}) }, 'survey.multichoiceanswer': { 'Meta': {'object_name': 'MultiChoiceAnswer'}, 'answer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.QuestionOption']", 'null': 'True'}), 'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.Household']"}), 'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}), 'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}), 'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'}) }, 'survey.numericalanswer': { 'Meta': {'object_name': 'NumericalAnswer'}, 'answer': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '5', 'null': 'True'}), 'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.Household']"}), 'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}), 'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}), 'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'}) }, 'survey.question': { 'Meta': {'object_name': 'Question'}, 'answer_type': ('django.db.models.fields.CharField', [], {'max_length': '15'}), 'batches': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'questions'", 'null': 'True', 'to': "orm['survey.Batch']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'question_group'", 'null': 'True', 'to': "orm['survey.HouseholdMemberGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'module_question'", 'null': 'True', 'to': "orm['survey.QuestionModule']"}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'null': 'True', 'to': "orm['survey.Question']"}), 'subquestion': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '150'}) }, 'survey.questionmodule': { 'Meta': {'object_name': 'QuestionModule'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'survey.questionoption': { 'Meta': {'object_name': 'QuestionOption'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'null': 'True', 'to': "orm['survey.Question']"}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '150'}) }, 'survey.randomhouseholdselection': { 'Meta': {'object_name': 'RandomHouseHoldSelection'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mobile_number': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'no_of_households': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}), 'selected_households': ('django.db.models.fields.CharField', [], {'max_length': '510'}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'random_household'", 'null': 'True', 'to': "orm['survey.Survey']"}) }, 'survey.survey': { 'Meta': {'object_name': 'Survey'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'has_sampling': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}), 'sample_size': ('django.db.models.fields.PositiveIntegerField', [], {'default': '10', 'max_length': '2'}), 'type': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'survey.textanswer': { 'Meta': {'object_name': 'TextAnswer'}, 'answer': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.Household']"}), 'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}), 'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}), 'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'}) }, 'survey.unknowndobattribute': { 'Meta': {'object_name': 'UnknownDOBAttribute'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'household_member': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'unknown_dob_attribute'", 'to': "orm['survey.HouseholdMember']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '15'}) }, 'survey.uploaderrorlog': { 'Meta': {'object_name': 'UploadErrorLog'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'error': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}), 'filename': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'row_number': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'survey.userprofile': { 'Meta': {'object_name': 'UserProfile'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mobile_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'userprofile'", 'unique': 'True', 'to': u"orm['auth.User']"}) } } complete_apps = ['survey']
bsd-3-clause
KarlTDebiec/myplotspec_sim
moldynplot/StateProbFigureManager.py
7284
#!/usr/bin/python # -*- coding: utf-8 -*- # moldynplot.StateProbFigureManager.py # # Copyright (C) 2015-2017 Karl T Debiec # All rights reserved. # # This software may be modified and distributed under the terms of the # BSD license. See the LICENSE file for details. """ Generates one or more state probability figures to specifications in a YAML file. """ ################################### MODULES ################################### from __future__ import (absolute_import, division, print_function, unicode_literals) if __name__ == "__main__": __package__ = str("moldynplot") import moldynplot from .myplotspec.FigureManager import FigureManager from .myplotspec.manage_defaults_presets import manage_defaults_presets from .myplotspec.manage_kwargs import manage_kwargs ################################### CLASSES ################################### class StateProbFigureManager(FigureManager): """ Class to manage the generation of probability distribution figures """ defaults = """ draw_figure: subplot_kw: autoscale_on: False axisbg: none multi_tick_params: bottom: off left: on right: off top: off shared_legend: True shared_legend_kw: spines: False handle_kw: ls: none marker: s mec: black legend_kw: borderaxespad: 0.0 frameon: False handletextpad: 0.0 loc: 9 numpoints: 1 draw_subplot: tick_params: bottom: off direction: out left: on right: off top: off title_kw: verticalalignment: bottom grid: True grid_kw: axis: y b: True color: [0.7,0.7,0.7] linestyle: '-' xticklabels: [] yticks: [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] draw_dataset: bar_kw: align: center width: 0.6 ecolor: black zorder: 3 error_kw: zorder: 4 handle_kw: ls: none marker: s mec: black """ available_presets = """ pbound: help: Probability of bound state draw_subplot: ylabel: $P_{bound}$ yticklabels: [0.0,"",0.2,"",0.4,"",0.6,"",0.8,"",1.0] presentation_wide: class: target inherits: presentation_wide draw_figure: bottom: 1.70 left: 4.60 right: 4.60 sub_width: 3.20 sub_height: 3.20 top: 1.00 wspace: 0.20 shared_legend: True shared_legend_kw: left: 4.60 sub_width: 10.00 sub_height: 1.50 bottom: 0.00 legend_kw: columnspacing: 1 labelspacing: 0.8 legend_fp: 20r loc: 9 ncol: 4 draw_dataset: bar_kw: error_kw: capsize: 4 capthick: 2 elinewidth: 2 linewidth: 2 edgecolor: [0,0,0] handle_kw: ms: 20 mew: 2.0 manuscript: class: target inherits: manuscript draw_figure: left: 0.40 sub_width: 1.50 wspace: 0.10 right: 0.10 top: 0.35 sub_height: 1.50 bottom: 0.45 shared_legend: True shared_legend_kw: left: 0.40 sub_width: 1.50 sub_height: 0.40 bottom: 0.00 handle_kw: mew: 0.5 ms: 5 legend_kw: columnspacing: 0.5 labelspacing: 0.5 ncol: 4 draw_dataset: bar_kw: error_kw: capsize: 2 capthick: 0.5 elinewidth: 0.5 linewidth: 0.5 edgecolor: [0,0,0] handle_kw: markeredgewidth: 0.5 markersize: 5 """ @manage_defaults_presets() @manage_kwargs() def draw_dataset(self, subplot, experiment=None, x=None, label="", handles=None, draw_bar=True, draw_plot=False, verbose=1, debug=0, **kwargs): """ Draws a dataset. Arguments: subplot (Axes): Axes on which to draw x (float): X coordinate of bar label (str, optional): Dataset label color (str, list, ndarray, float, optional): Dataset color bar_kw (dict, optional): Additional keyword arguments passed to subplot.plot() handles (OrderedDict, optional): Nascent OrderedDict of [labels]: handles on subplot kwargs (dict): Additional keyword arguments """ from .myplotspec import get_colors, multi_get_copy from .dataset import H5Dataset # Handle missing input gracefully handle_kw = multi_get_copy("handle_kw", kwargs, {}) if experiment is not None: subplot.axhspan(experiment[0], experiment[1], lw=2, color=[0.6, 0.6, 0.6]) if kwargs.get("draw_experiment_handle", True): handles["Experiment"] = \ subplot.plot([-10, -10], [-10, -10], mfc=[0.6, 0.6, 0.6], **handle_kw)[0] return if "infile" not in kwargs: if "P unbound" in kwargs and "P unbound se" in kwargs: y = 1.0 - kwargs.pop("P unbound") yerr = kwargs.pop("P unbound se") * 1.96 elif "y" in kwargs and "y se" in kwargs: y = kwargs.pop("y") yerr = kwargs.pop("y se") * 1.96 elif "P unbound" in kwargs and not draw_bar and draw_plot: y = 1.0 - kwargs.pop("P unbound") else: return else: dataset = H5Dataset(default_address="assign/stateprobs", default_key="pbound", **kwargs) y = 1.0 - dataset.datasets["pbound"]["P unbound"][0] yerr = dataset.datasets["pbound"]["P unbound se"][0] * 1.96 # Configure plot settings # Plot if draw_bar: bar_kw = multi_get_copy("bar_kw", kwargs, {}) get_colors(bar_kw, kwargs) barplot = subplot.bar(x, y, yerr=yerr, **bar_kw) handle_kw = multi_get_copy("handle_kw", kwargs, {}) handle_kw["mfc"] = barplot.patches[0].get_facecolor() handle = subplot.plot([-10, -10], [-10, -10], **handle_kw)[0] if draw_plot: plot_kw = multi_get_copy("plot_kw", kwargs, {}) get_colors(plot_kw) subplot.plot(x, y, **plot_kw) if handles is not None and label is not None: handles[label] = handle #################################### MAIN ##################################### if __name__ == "__main__": StateProbFigureManager().main()
bsd-3-clause
chromium2014/src
extensions/common/features/feature.h
5772
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EXTENSIONS_COMMON_FEATURES_FEATURE_H_ #define EXTENSIONS_COMMON_FEATURES_FEATURE_H_ #include <set> #include <string> #include "base/values.h" #include "extensions/common/manifest.h" class GURL; namespace extensions { class Extension; // Represents a single feature accessible to an extension developer, such as a // top-level manifest key, a permission, or a programmatic API. A feature can // express requirements for where it can be accessed, and supports testing // support for those requirements. If platforms are not specified, then feature // is available on all platforms. class Feature { public: // The JavaScript contexts the feature is supported in. enum Context { UNSPECIFIED_CONTEXT, // A context in a privileged extension process. BLESSED_EXTENSION_CONTEXT, // A context in an unprivileged extension process. UNBLESSED_EXTENSION_CONTEXT, // A context from a content script. CONTENT_SCRIPT_CONTEXT, // A normal web page. This should have an associated URL matching pattern. WEB_PAGE_CONTEXT, // A web page context which has been blessed by the user. Typically this // will be via the installation of a hosted app, so this may host an // extension. This is not affected by the URL matching pattern. BLESSED_WEB_PAGE_CONTEXT, }; // The platforms the feature is supported in. enum Platform { UNSPECIFIED_PLATFORM, CHROMEOS_PLATFORM, LINUX_PLATFORM, MACOSX_PLATFORM, WIN_PLATFORM }; // Whether a feature is available in a given situation or not, and if not, // why not. enum AvailabilityResult { IS_AVAILABLE, NOT_FOUND_IN_WHITELIST, INVALID_URL, INVALID_TYPE, INVALID_CONTEXT, INVALID_LOCATION, INVALID_PLATFORM, INVALID_MIN_MANIFEST_VERSION, INVALID_MAX_MANIFEST_VERSION, NOT_PRESENT, UNSUPPORTED_CHANNEL, FOUND_IN_BLACKLIST, }; // Container for AvailabiltyResult that also exposes a user-visible error // message in cases where the feature is not available. class Availability { public: AvailabilityResult result() const { return result_; } bool is_available() const { return result_ == IS_AVAILABLE; } const std::string& message() const { return message_; } private: friend class SimpleFeature; friend class Feature; // Instances should be created via Feature::CreateAvailability. Availability(AvailabilityResult result, const std::string& message) : result_(result), message_(message) { } const AvailabilityResult result_; const std::string message_; }; Feature(); virtual ~Feature(); // Used by ChromeV8Context until the feature system is fully functional. // TODO(kalman): This is no longer used by ChromeV8Context, so what is the // comment trying to say? static Availability CreateAvailability(AvailabilityResult result, const std::string& message); const std::string& name() const { return name_; } void set_name(const std::string& name) { name_ = name; } bool no_parent() const { return no_parent_; } // Gets the platform the code is currently running on. static Platform GetCurrentPlatform(); // Tests whether this is an internal API or not. virtual bool IsInternal() const = 0; // Returns True for features excluded from service worker backed contexts. virtual bool IsBlockedInServiceWorker() const = 0; // Returns true if the feature is available to be parsed into a new extension // manifest. Availability IsAvailableToManifest(const std::string& extension_id, Manifest::Type type, Manifest::Location location, int manifest_version) const { return IsAvailableToManifest(extension_id, type, location, manifest_version, GetCurrentPlatform()); } virtual Availability IsAvailableToManifest(const std::string& extension_id, Manifest::Type type, Manifest::Location location, int manifest_version, Platform platform) const = 0; // Returns true if the feature is available to |extension|. Availability IsAvailableToExtension(const Extension* extension); // Returns true if the feature is available to be used in the specified // extension and context. Availability IsAvailableToContext(const Extension* extension, Context context, const GURL& url) const { return IsAvailableToContext(extension, context, url, GetCurrentPlatform()); } virtual Availability IsAvailableToContext(const Extension* extension, Context context, const GURL& url, Platform platform) const = 0; virtual std::string GetAvailabilityMessage(AvailabilityResult result, Manifest::Type type, const GURL& url, Context context) const = 0; virtual bool IsIdInBlacklist(const std::string& extension_id) const = 0; virtual bool IsIdInWhitelist(const std::string& extension_id) const = 0; protected: std::string name_; bool no_parent_; }; } // namespace extensions #endif // EXTENSIONS_COMMON_FEATURES_FEATURE_H_
bsd-3-clause
theosyspe/levent_01
vendor/ZF2/bin/test/n/e/i.php
37
<?php namespace test\n\e; class i { }
bsd-3-clause
LWJGL-CI/lwjgl3
modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkDebugReportCallbackEXTI.java
5004
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import org.lwjgl.system.*; import org.lwjgl.system.libffi.*; import static org.lwjgl.system.APIUtil.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.libffi.LibFFI.*; /** * Application-defined debug report callback function. * * <h5>C Specification</h5> * * <p>The prototype for the {@link VkDebugReportCallbackCreateInfoEXT}{@code ::pfnCallback} function implemented by the application is:</p> * * <pre><code> * typedef VkBool32 (VKAPI_PTR *PFN_vkDebugReportCallbackEXT)( * VkDebugReportFlagsEXT flags, * VkDebugReportObjectTypeEXT objectType, * uint64_t object, * size_t location, * int32_t messageCode, * const char* pLayerPrefix, * const char* pMessage, * void* pUserData);</code></pre> * * <h5>Description</h5> * * <p>The callback <b>must</b> not call {@code vkDestroyDebugReportCallbackEXT}.</p> * * <p>The callback returns a {@code VkBool32}, which is interpreted in a layer-specified manner. The application <b>should</b> always return {@link VK10#VK_FALSE FALSE}. The {@link VK10#VK_TRUE TRUE} value is reserved for use in layer development.</p> * * <p>{@code object} <b>must</b> be a Vulkan object or {@link VK10#VK_NULL_HANDLE NULL_HANDLE}. If {@code objectType} is not {@link EXTDebugReport#VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT} and {@code object} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code object} <b>must</b> be a Vulkan object of the corresponding type associated with {@code objectType} as defined in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#debug-report-object-types">{@code VkDebugReportObjectTypeEXT} and Vulkan Handle Relationship</a>.</p> * * <h5>See Also</h5> * * <p>{@link VkDebugReportCallbackCreateInfoEXT}</p> */ @FunctionalInterface @NativeType("PFN_vkDebugReportCallbackEXT") public interface VkDebugReportCallbackEXTI extends CallbackI { FFICIF CIF = apiCreateCIF( apiStdcall(), ffi_type_uint32, ffi_type_uint32, ffi_type_uint32, ffi_type_uint64, ffi_type_pointer, ffi_type_sint32, ffi_type_pointer, ffi_type_pointer, ffi_type_pointer ); @Override default FFICIF getCallInterface() { return CIF; } @Override default void callback(long ret, long args) { int __result = invoke( memGetInt(memGetAddress(args)), memGetInt(memGetAddress(args + POINTER_SIZE)), memGetLong(memGetAddress(args + 2 * POINTER_SIZE)), memGetAddress(memGetAddress(args + 3 * POINTER_SIZE)), memGetInt(memGetAddress(args + 4 * POINTER_SIZE)), memGetAddress(memGetAddress(args + 5 * POINTER_SIZE)), memGetAddress(memGetAddress(args + 6 * POINTER_SIZE)), memGetAddress(memGetAddress(args + 7 * POINTER_SIZE)) ); apiClosureRet(ret, __result); } /** * Application-defined debug report callback function. * * @param flags specifies the {@code VkDebugReportFlagBitsEXT} that triggered this callback. * @param objectType a {@code VkDebugReportObjectTypeEXT} value specifying the type of object being used or created at the time the event was triggered. * @param object the object where the issue was detected. If {@code objectType} is {@link EXTDebugReport#VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT}, {@code object} is undefined. * @param location a component (layer, driver, loader) defined value specifying the <em>location</em> of the trigger. This is an <b>optional</b> value. * @param messageCode a layer-defined value indicating what test triggered this callback. * @param pLayerPrefix a null-terminated string that is an abbreviation of the name of the component making the callback. {@code pLayerPrefix} is only valid for the duration of the callback. * @param pMessage a null-terminated string detailing the trigger conditions. {@code pMessage} is only valid for the duration of the callback. * @param pUserData the user data given when the {@code VkDebugReportCallbackEXT} was created. */ @NativeType("VkBool32") int invoke(@NativeType("VkDebugReportFlagsEXT") int flags, @NativeType("VkDebugReportObjectTypeEXT") int objectType, @NativeType("uint64_t") long object, @NativeType("size_t") long location, @NativeType("int32_t") int messageCode, @NativeType("char const *") long pLayerPrefix, @NativeType("char const *") long pMessage, @NativeType("void *") long pUserData); }
bsd-3-clause
jamoma/JamomaCore
DSP/extensions/FilterLib/tests/TTAllpass2a.test.cpp
665
/** @file * * @ingroup dspFilterLib * * @brief Unit test for the FilterLib #TTAllpass2a class. * * @details Currently this test is just a stub * * @authors Trond Lossius, Tim Place * * @copyright Copyright © 2012 by Trond Lossius & Timothy Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTAllpass2a.h" TTErr TTAllpass2a::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
bsd-3-clause
halfflat/nestmc-proto
python/test/unit/test_catalogues.py
2948
from .. import fixtures import unittest import arbor as arb """ tests for (dynamically loaded) catalogues """ class recipe(arb.recipe): def __init__(self): arb.recipe.__init__(self) self.tree = arb.segment_tree() self.tree.append(arb.mnpos, (0, 0, 0, 10), (1, 0, 0, 10), 1) self.props = arb.neuron_cable_properties() try: self.cat = arb.default_catalogue() self.props.register(self.cat) except: print("Catalogue not found. Are you running from build directory?") raise d = arb.decor() d.paint('(all)', arb.density('pas')) d.set_property(Vm=0.0) self.cell = arb.cable_cell(self.tree, arb.label_dict(), d) def global_properties(self, _): return self.props def num_cells(self): return 1 def cell_kind(self, gid): return arb.cell_kind.cable def cell_description(self, gid): return self.cell class TestCatalogues(unittest.TestCase): def test_nonexistent(self): with self.assertRaises(FileNotFoundError): arb.load_catalogue("_NO_EXIST_.so") @fixtures.dummy_catalogue def test_shared_catalogue(self, dummy_catalogue): cat = dummy_catalogue nms = [m for m in cat] self.assertEqual(nms, ['dummy'], "Expected equal names.") for nm in nms: prm = list(cat[nm].parameters.keys()) self.assertEqual(prm, ['gImbar'], "Expected equal parameters on mechanism '{}'.".format(nm)) def test_simulation(self): rcp = recipe() ctx = arb.context() dom = arb.partition_load_balance(rcp, ctx) sim = arb.simulation(rcp, dom, ctx) sim.run(tfinal=30) def test_empty(self): def len(cat): return sum(1 for _ in cat) def hash_(cat): return hash(" ".join(sorted(cat))) cat = arb.catalogue() ref = arb.default_catalogue() other = arb.default_catalogue() # Test empty constructor self.assertEqual(0, len(cat), "Expected no mechanisms in `arbor.catalogue()`.") # Test empty extend other.extend(cat, "") self.assertEqual(hash_(ref), hash_(other), "Extending cat with empty should not change cat.") self.assertEqual(0, len(cat), "Extending cat with empty should not change empty.") other.extend(cat, "prefix/") self.assertEqual(hash_(ref), hash_(other), "Extending cat with prefixed empty should not change cat.") self.assertEqual(0, len(cat), "Extending cat with prefixed empty should not change empty.") cat.extend(other, "") self.assertEqual(hash_(other), hash_(cat), "Extending empty with cat should turn empty into cat.") cat = arb.catalogue() cat.extend(other, "prefix/") self.assertNotEqual(hash_(other), hash_(cat), "Extending empty with prefixed cat should not yield cat")
bsd-3-clause
handloomweaver/mongrel2
src/io.c
13792
#define _XOPEN_SOURCE 500 #define _FILE_OFFSET_BITS 64 #include "io.h" #include "register.h" #include "mem/halloc.h" #include "dbg.h" #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <polarssl/havege.h> #include <polarssl/ssl.h> #include <task/task.h> static ssize_t null_send(IOBuf *iob, char *buffer, int len) { return len; } static ssize_t null_recv(IOBuf *iob, char *buffer, int len) { return len; } static ssize_t null_stream_file(IOBuf *iob, int fd, off_t len) { return len; } static ssize_t plaintext_send(IOBuf *iob, char *buffer, int len) { return fdsend(iob->fd, buffer, len); } static ssize_t plaintext_recv(IOBuf *iob, char *buffer, int len) { return fdrecv(iob->fd, buffer, len); } static ssize_t file_send(IOBuf *iob, char *buffer, int len) { return fdwrite(iob->fd, buffer, len); } static ssize_t file_recv(IOBuf *iob, char *buffer, int len) { return fdread(iob->fd, buffer, len); } static ssize_t plain_stream_file(IOBuf *iob, int fd, off_t len) { off_t sent = 0; off_t total = 0; off_t offset = 0; off_t block_size = MAX_SEND_BUFFER; int conn_fd = IOBuf_fd(iob); for(total = 0; fdwait(conn_fd, 'w') == 0 && total < len; total += sent) { block_size = (len - total) > block_size ? block_size : (len - total); sent = IOBuf_sendfile(conn_fd, fd, &offset, block_size); check(Register_write(iob->fd, sent) != -1, "Socket seems to be closed."); check_debug(sent > 0, "Client closed probably during sendfile on socket: %d from " "file %d", conn_fd, fd); } check(total <= len, "Wrote way too much, wrote %d but size was %zd", (int)total, len); check(total == len, "Sent other than expected, sent: %d, but expected: %zd", (int)total, len); return total; error: return -1; } static int ssl_fdsend_wrapper(void *p_iob, unsigned char *ubuffer, int len) { IOBuf *iob = (IOBuf *) p_iob; return fdsend(iob->fd, (char *) ubuffer, len); } static int ssl_fdrecv_wrapper(void *p_iob, unsigned char *ubuffer, int len) { IOBuf *iob = (IOBuf *) p_iob; return fdrecv1(iob->fd, (char *) ubuffer, len); } static int ssl_do_handshake(IOBuf *iob) { int rcode; check(!iob->handshake_performed, "ssl_do_handshake called unnecessarily"); while((rcode = ssl_handshake(&iob->ssl)) != 0) { check(rcode == POLARSSL_ERR_NET_TRY_AGAIN, "handshake failed with error code %d", rcode); } iob->handshake_performed = 1; return 0; error: return -1; } static ssize_t ssl_send(IOBuf *iob, char *buffer, int len) { check(iob->use_ssl, "IOBuf not set up to use ssl"); if(!iob->handshake_performed) { int rcode = ssl_do_handshake(iob); check(rcode == 0, "handshake failed"); } return ssl_write(&iob->ssl, (const unsigned char*) buffer, len); error: return -1; } static ssize_t ssl_recv(IOBuf *iob, char *buffer, int len) { check(iob->use_ssl, "IOBuf not set up to use ssl"); if(!iob->handshake_performed) { int rcode = ssl_do_handshake(iob); check(rcode == 0, "handshake failed"); } return ssl_read(&iob->ssl, (unsigned char*) buffer, len); error: return -1; } static ssize_t ssl_stream_file(IOBuf *iob, int fd, off_t len) { ssize_t sent = 0; off_t total = 0; ssize_t amt = 0; ssize_t tosend = 0; int conn_fd = IOBuf_fd(iob); char buff[1024]; for(total = 0; fdwait(conn_fd, 'w') == 0 && total < len; total += tosend) { tosend = pread(fd, buff, sizeof(buff), total); check_debug(tosend > 0, "Came up short in reading file %d\n", fd); // We do this in case the file somehow lengthened on us. In general, // it shouldn't happen. if(tosend + total > len) tosend = len - total; sent = 0; while(sent < tosend) { amt = ssl_send(iob, buff, tosend); check_debug(amt > 0, "ssl_send failed in ssl_stream_file with " "return code %zd", amt); sent += amt; } check(Register_write(iob->fd, sent) != -1, "Failed to record write, must have died."); } check(total <= len, "Wrote way too much, wrote %d but size was %zd", (int)total, len); check(total == len, "Sent other than expected, sent: %d, but expected: %zd", (int)total, len); return total; error: return -1; } void ssl_debug(void *p, int level, const char *msg) { if(level < 2) { debug("polarssl: %s", msg); } } IOBuf *IOBuf_create(size_t len, int fd, IOBufType type) { IOBuf *buf = h_calloc(sizeof(IOBuf), 1); check_mem(buf); buf->fd = fd; buf->len = len; buf->buf = h_malloc(len + 1); check_mem(buf->buf); hattach(buf->buf, buf); buf->type = type; if(type == IOBUF_SSL) { buf->use_ssl = 1; buf->handshake_performed = 0; ssl_init(&buf->ssl); ssl_set_endpoint(&buf->ssl, SSL_IS_SERVER); ssl_set_authmode(&buf->ssl, SSL_VERIFY_NONE); havege_init(&buf->hs); ssl_set_rng(&buf->ssl, havege_rand, &buf->hs); ssl_set_dbg(&buf->ssl, ssl_debug, NULL); ssl_set_bio(&buf->ssl, ssl_fdrecv_wrapper, buf, ssl_fdsend_wrapper, buf); ssl_set_session(&buf->ssl, 1, 0, &buf->ssn); memset(&buf->ssn, 0, sizeof(buf->ssn)); buf->send = ssl_send; buf->recv = ssl_recv; buf->stream_file = ssl_stream_file; } else if(type == IOBUF_NULL) { buf->send = null_send; buf->recv = null_recv; buf->stream_file = null_stream_file; } else if(type == IOBUF_FILE) { buf->send = file_send; buf->recv = file_recv; buf->stream_file = plain_stream_file; } else if(type == IOBUF_SOCKET) { buf->send = plaintext_send; buf->recv = plaintext_recv; buf->stream_file = plain_stream_file; } else { sentinel("Invalid IOBufType given: %d", type); } return buf; error: if(buf) h_free(buf); return NULL; } void IOBuf_destroy(IOBuf *buf) { if(buf) { if(buf->use_ssl) { ssl_close_notify(&buf->ssl); ssl_free(&buf->ssl); } fdclose(buf->fd); h_free(buf); } } void IOBuf_resize(IOBuf *buf, size_t new_size) { buf->buf = h_realloc(buf->buf, new_size); buf->len = new_size; } static inline void IOBuf_compact(IOBuf *buf) { memmove(buf->buf, IOBuf_start(buf), buf->avail); buf->cur = 0; } /** * Does a non-blocking read and either reads in the amount you requested * with "need" or less so you can try again. It sets out_len to what is * available (<= need) so you can decide after that. You can keep attempting * to read more and more (up to buf->len) and you'll get the same start point * each time. * * Once you're done with the data you've been trying to read, you use IOBuf_read_commit * to commit the "need" amount and then start doing new reads. * * Internally this works like a "half open ring buffer" and it tries to greedily * read as much as possible without blocking or copying. * * To just get as much as possible, use the IOBuf_read_some macro. */ char *IOBuf_read(IOBuf *buf, int need, int *out_len) { int rc = 0; assert(buf->cur + buf->avail <= buf->len && "Buffer math off, cur+avail can't be more than > len."); assert(buf->cur >= 0 && "Buffer cur can't be < 0"); assert(buf->avail >= 0 && "Buffer avail can't be < 0"); assert(need <= buf->len && "Request for more than possible in the buffer."); if(IOBuf_closed(buf)) { if(buf->avail > 0) { *out_len = buf->avail; } else { *out_len = 0; return NULL; } } else if(buf->avail < need) { if(buf->cur > 0 && IOBuf_compact_needed(buf, need)) { IOBuf_compact(buf); } rc = buf->recv(buf, IOBuf_read_point(buf), IOBuf_remaining(buf)); if(rc <= 0) { debug("Socket was closed, will return only what's available: %d", buf->avail); buf->closed = 1; } else { buf->avail = buf->avail + rc; } if(buf->avail < need) { // less than expected *out_len = buf->avail; } else { // more than expected *out_len = need; } } else if(buf->avail >= need) { *out_len = need; } else { sentinel("Invalid branch processing buffer, Tell Zed."); } return IOBuf_start(buf); error: return NULL; } /** * Commits the amount given by need to the buffer, moving the internal * counters around so that the next read starts after the need point. * You use this after you're done working with the data and want to * do the next read. */ int IOBuf_read_commit(IOBuf *buf, int need) { buf->avail -= need; assert(buf->avail >= 0 && "Buffer commit reduced avail to < 0."); check(Register_read(buf->fd, need) != -1, "Failed to record read, must have died."); buf->mark = 0; if(buf->avail == 0) { // if there's nothing available then just start at the beginning buf->cur = 0; } else { buf->cur += need; } return 0; error: return -1; } /** * Wraps the usual send, so not much to it other than it'll avoid doing * any calls if the socket is already closed. */ int IOBuf_send(IOBuf *buf, char *data, int len) { int rc = 0; rc = buf->send(buf, data, len); if(rc >= 0) { check(Register_write(buf->fd, rc) != -1, "Failed to record write, must have died."); } else { buf->closed = 1; } return rc; error: return -1; } /** * Reads the entire amount requested into the IOBuf (as long as there's * space to hold it) and then commits that read in one shot. */ char *IOBuf_read_all(IOBuf *buf, int len, int retries) { int nread = 0; int attempts = 0; check_debug(!IOBuf_closed(buf), "Closed when attempting to read from buffer."); if(len > buf->len) { // temporarily grow the buffer IOBuf_resize(buf, len); } char *data = IOBuf_read(buf, len, &nread); debug("INITIAL READ: len: %d, nread: %d", len, nread); for(attempts = 0; nread < len; attempts++) { data = IOBuf_read(buf, len, &nread); check_debug(data, "Read error from socket."); assert(nread <= len && "Invalid nread size (too much) on IOBuf read."); if(nread == len) { break; } else { fdwait(buf->fd, 'r'); } } debug("ATTEMPTS: %d, RETRIES: %d", attempts, retries); if(attempts > retries) { log_err("Read of %d length attempted %d times which is over %d retry limit..", len, attempts, retries); } check(IOBuf_read_commit(buf, len) != -1, "Final commit failed of read_all."); return data; error: buf->closed = 1; return NULL; } /** * Streams data out of the from IOBuf and into the to IOBuf * until it's moved total bytes between them. */ int IOBuf_stream(IOBuf *from, IOBuf *to, int total) { int need = 0; int remain = total; int avail = 0; int rc = 0; char *data = NULL; if(from->len > to->len) IOBuf_resize(to, from->len); while(remain > 0) { need = remain <= from->len ? remain : from->len; data = IOBuf_read(from, need, &avail); check_debug(avail > 0, "Nothing in read buffer."); rc = IOBuf_send_all(to, IOBuf_start(from), avail); check_debug(rc == avail, "Failed to send all of the data: %d of %d", rc, avail) // commit whatever we just did check(IOBuf_read_commit(from, rc) != -1, "Final commit failed during streaming."); // reduce it by the given amount remain -= rc; } assert(remain == 0 && "Buffer math is wrong."); return total - remain; error: return -1; } int IOBuf_send_all(IOBuf *buf, char *data, int len) { int rc = 0; int total = len; do { rc = IOBuf_send(buf, data, total); check(rc > 0, "Write error when sending all."); total -= rc; } while(total > 0); assert(total == 0 && "Math error sending all from buffer."); return len; error: return -1; } int IOBuf_stream_file(IOBuf *buf, int fd, off_t len) { int rc = 0; // We depend on the stream_file callback to call Register_write. // Doing it here would make the connection look inactive for long periods // if we are streaming a large file. rc = buf->stream_file(buf, fd, len); if(rc < 0) buf->closed = 1; return rc; } void debug_dump(void *addr, int len) { #ifdef NDEBUG return; #endif char tohex[] = "0123456789ABCDEF"; int i = 0; unsigned char *pc = addr; char buf0[32] = {0}; // offset char buf1[64] = {0}; // hex char buf2[64] = {0}; // literal char *pc1 = NULL; char *pc2 = NULL; while(--len >= 0) { if(i % 16 == 0) { sprintf(buf0, "%08x", i); buf1[0] = 0; buf2[0] = 0; pc1 = buf1; pc2 = buf2; } *pc1++ = tohex[*pc >> 4]; *pc1++ = tohex[*pc & 15]; *pc1++ = ' '; if(*pc >= 32 && *pc < 127) { *pc2++ = *pc; } else { *pc2++ = '.'; } i++; pc++; if(i % 16 == 0) { *pc1 = 0; *pc2 = 0; debug("%s: %s %s", buf0, buf1, buf2); } } if(i % 16 != 0) { while(i % 16 != 0) { *pc1++ = ' '; *pc1++ = ' '; *pc1++ = ' '; *pc2++ = ' '; i++; } *pc1 = 0; *pc2 = 0; debug("%s: %s %s", buf0, buf1, buf2); } }
bsd-3-clause
alepharchives/quickfast
src/Codecs/DataDestination_fwd.h
604
// Copyright (c) 2009, Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #ifdef _MSC_VER # pragma once #endif #ifndef DATADESTINATION_FWD_H #define DATADESTINATION_FWD_H namespace QuickFAST{ namespace Codecs{ class DestinationBuffer; /// @brief A smart pointer to a DestinationBuffer. typedef boost::shared_ptr<DestinationBuffer> DestinationBufferPtr; class DataDestination; /// @brief A smart pointer to a DataDestination. typedef boost::shared_ptr<DataDestination> DataDestinationPtr; } } #endif // DATADESTINATION_FWD_H
bsd-3-clause
nebulab/spree_line_item_discount
spec/spec_helper.rb
2752
# Run Coverage report require 'simplecov' SimpleCov.start do add_filter 'spec/dummy' add_group 'Controllers', 'app/controllers' add_group 'Helpers', 'app/helpers' add_group 'Mailers', 'app/mailers' add_group 'Models', 'app/models' add_group 'Views', 'app/views' add_group 'Libraries', 'lib' end # Configure Rails Environment ENV['RAILS_ENV'] = 'test' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' require 'database_cleaner' require 'ffaker' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f } # Requires factories and other useful helpers defined in spree_core. require 'spree/testing_support/authorization_helpers' require 'spree/testing_support/capybara_ext' require 'spree/testing_support/controller_requests' require 'spree/testing_support/factories' require 'spree/testing_support/url_helpers' # Requires factories defined in lib/spree_line_item_discount/factories.rb require 'spree_line_item_discount/factories' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods # == URL Helpers # # Allows access to Spree's routes in specs: # # visit spree.admin_path # current_path.should eql(spree.products_path) config.include Spree::TestingSupport::UrlHelpers # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr config.mock_with :rspec config.color = true # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner # to cleanup after each test instead. Without transactional fixtures set to false the records created # to setup a test will be unavailable to the browser, which runs under a separate server instance. config.use_transactional_fixtures = false # Ensure Suite is set to use transactions for speed. config.before :suite do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with :truncation end # Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary. config.before :each do DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction DatabaseCleaner.start end # After each spec clean the database. config.after :each do DatabaseCleaner.clean end config.fail_fast = ENV['FAIL_FAST'] || false config.order = "random" end
bsd-3-clause
ckingclub/jinliApi
vendor/qcloud/weapp-sdk/tests/test-suite/Tunnel/TunnelServiceTest.php
13797
<?php use \QCloud_WeApp_SDK\Conf; use \QCloud_WeApp_SDK\Helper\Util; use \QCloud_WeApp_SDK\Auth\Constants; use \QCloud_WeApp_SDK\Tunnel\TunnelService; /** * @runTestsInSeparateProcesses */ class TunnelServiceTest extends PHPUnit_Framework_TestCase { private $mockedTunnelHandler; public static function setUpBeforeClass() { Conf::setup(array( 'ServerHost' => SERVER_HOST, 'AuthServerUrl' => AUTH_SERVER_URL, 'TunnelServerUrl' => TUNNEL_SERVER_URL, 'TunnelSignatureKey' => TUNNEL_SIGNATURE_KEY, 'TunnelCheckSignature' => FALSE, )); } public function setUp() { $this->setOutputCallback(function () {}); $this->mockedTunnelHandler = $this->getMock('\QCloud_WeApp_SDK\Tunnel\ITunnelHandler'); } public function testHandleNeitherGetNorPostRequest() { $_SERVER['REQUEST_METHOD'] = 'PUT'; TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(501, $body['code']); } public function testHandleGetWithNoCheckLogin() { $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/tunnel'; $this->mockedTunnelHandler ->expects($this->once()) ->method('onRequest') ->with($this->isType('string'), $this->isNull()); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertInternalType('string', $body['url']); } public function testHandleGetWithCheckLogin() { $this->setHttpHeader(Constants::WX_HEADER_ID, 'valid-id'); $this->setHttpHeader(Constants::WX_HEADER_SKEY, 'valid-skey'); $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/tunnel'; $this->mockedTunnelHandler ->expects($this->once()) ->method('onRequest') ->with($this->isType('string'), $this->isType('array')); TunnelService::handle($this->mockedTunnelHandler, array( 'checkLogin' => TRUE )); $body = json_decode($this->getActualOutput(), TRUE); $this->assertInternalType('string', $body['url']); } public function testHandleGetWithCheckLoginAndNoSessionInfo() { $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/tunnel'; $this->mockedTunnelHandler ->expects($this->never()) ->method('onRequest'); TunnelService::handle($this->mockedTunnelHandler, array( 'checkLogin' => TRUE )); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(1, $body[Constants::WX_SESSION_MAGIC_ID]); $this->assertArrayHasKey('error', $body); } public function testHandleGetWithCheckLoginAndInvalidSessionInfo() { $this->setHttpHeader(Constants::WX_HEADER_ID, 'invalid-id'); $this->setHttpHeader(Constants::WX_HEADER_SKEY, 'valid-skey'); $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/tunnel'; $this->mockedTunnelHandler ->expects($this->never()) ->method('onRequest'); TunnelService::handle($this->mockedTunnelHandler, array( 'checkLogin' => TRUE )); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(1, $body[Constants::WX_SESSION_MAGIC_ID]); $this->assertArrayHasKey('error', $body); } public function testHandleGetWhenTunnelServerRespondWithInvalidSignature() { Conf::setTunnelCheckSignature(TRUE); $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/tunnel'; TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertArrayHasKey('error', $body); } public function testHandlePostWithoutPayload() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(9001, $body['code']); } public function testHandlePostWithEmptyObject() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload('{}'); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(9002, $body['code']); } public function testHandlePostWithInvalidSignature() { Conf::setTunnelCheckSignature(TRUE); $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => '{}', 'signature' => 'invalid-signature', ))); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(9003, $body['code']); } public function testHandlePostWithNonObjectData() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => 'this is an object', 'signature' => 'valid-signature', ))); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(9004, $body['code']); } public function testHandlePostWithValidPayload() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => '{}', 'signature' => 'valid-signature', ))); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testHandlePostShouldCallOnConnect() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => '{"tunnelId":"tunnel1","type":"connect"}', 'signature' => 'valid-signature', ))); $this->mockedTunnelHandler ->expects($this->once()) ->method('onConnect') ->with($this->identicalTo('tunnel1')); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testHandlePostShouldCallOnMessage() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => json_encode(array( 'tunnelId' => 'tunnel1', 'type' => 'message', 'content' => json_encode(array( 'type' => 'hi', 'content' => 'hello, everyone.', )), )), 'signature' => 'valid-signature', ))); $this->mockedTunnelHandler ->expects($this->once()) ->method('onMessage') ->with( $this->identicalTo('tunnel1'), $this->identicalTo('hi'), $this->identicalTo('hello, everyone.') ); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testHandlePostShouldCallOnMessageEvenWithoutContent() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => json_encode(array( 'tunnelId' => 'tunnel1', 'type' => 'message', )), 'signature' => 'valid-signature', ))); $this->mockedTunnelHandler ->expects($this->once()) ->method('onMessage') ->with( $this->identicalTo('tunnel1'), $this->identicalTo('UnknownRaw'), $this->identicalTo(NULL) ); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testHandlePostShouldCallOnMessageEvenWithUnknownContent() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => json_encode(array( 'tunnelId' => 'tunnel1', 'type' => 'message', 'content' => 'hi, there', )), 'signature' => 'valid-signature', ))); $this->mockedTunnelHandler ->expects($this->once()) ->method('onMessage') ->with( $this->identicalTo('tunnel1'), $this->identicalTo('UnknownRaw'), $this->identicalTo('hi, there') ); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testHandlePostShouldCallOnClose() { $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['REQUEST_URI'] = '/tunnel'; Util::setPostPayload(json_encode(array( 'data' => '{"tunnelId":"tunnel1","type":"close"}', 'signature' => 'valid-signature', ))); $this->mockedTunnelHandler ->expects($this->once()) ->method('onClose') ->with($this->identicalTo('tunnel1')); TunnelService::handle($this->mockedTunnelHandler); $body = json_decode($this->getActualOutput(), TRUE); $this->assertSame(0, $body['code']); } public function testBroadcastUseCase() { $tunnelIds = array('tunnel1', 'tunnel2'); $messageType = 'hi'; $messageContent = 'hello, everybody!'; $result = TunnelService::broadcast($tunnelIds, $messageType, $messageContent); $this->assertSame(0, $result['code']); } public function testBroadcastExpect500() { $tunnelIds = array('expect-500', 'tunnel2'); $messageType = 'hi'; $messageContent = 'hello, everybody!'; $result = TunnelService::broadcast($tunnelIds, $messageType, $messageContent); $this->assertNotEquals(0, $result['code']); } public function testBroadcastExpectInvalidJson() { $tunnelIds = array('expect-invalid-json', 'tunnel2'); $messageType = 'hi'; $messageContent = 'hello, everybody!'; $result = TunnelService::broadcast($tunnelIds, $messageType, $messageContent); $this->assertNotEquals(0, $result['code']); } public function testBroadcastExpectFailedResult() { $tunnelIds = array('expect-failed-result', 'tunnel2'); $messageType = 'hi'; $messageContent = 'hello, everybody!'; $result = TunnelService::broadcast($tunnelIds, $messageType, $messageContent); $this->assertNotEquals(0, $result['code']); } public function testEmitUseCase() { $tunnelId = 'tunnel1'; $messageType = 'hi'; $messageContent = 'hello, how are you!'; $result = TunnelService::emit($tunnelId, $messageType, $messageContent); $this->assertSame(0, $result['code']); } public function testEmitExpect500() { $tunnelId = 'expect-500'; $messageType = 'hi'; $messageContent = 'hello, how are you!'; $result = TunnelService::emit($tunnelId, $messageType, $messageContent); $this->assertNotEquals(0, $result['code']); } public function testEmitExpectInvalidJson() { $tunnelId = 'expect-invalid-json'; $messageType = 'hi'; $messageContent = 'hello, how are you!'; $result = TunnelService::emit($tunnelId, $messageType, $messageContent); var_export($result); $this->assertNotEquals(0, $result['code']); } public function testEmitExpectFailedResult() { $tunnelId = 'expect-failed-result'; $messageType = 'hi'; $messageContent = 'hello, how are you!'; $result = TunnelService::emit($tunnelId, $messageType, $messageContent); $this->assertNotEquals(0, $result['code']); } public function testCloseTunnelUseCase() { $tunnelId = 'tunnel1'; $result = TunnelService::closeTunnel($tunnelId); $this->assertSame(0, $result['code']); } public function testCloseTunnelExpect500() { $tunnelId = 'expect-500'; $result = TunnelService::closeTunnel($tunnelId); $this->assertNotEquals(0, $result['code']); } public function testCloseTunnelExpectInvalidJson() { $tunnelId = 'expect-invalid-json'; $result = TunnelService::closeTunnel($tunnelId); $this->assertNotEquals(0, $result['code']); } public function testCloseTunnelExpectFailedResult() { $tunnelId = 'expect-failed-result'; $result = TunnelService::closeTunnel($tunnelId); $this->assertNotEquals(0, $result['code']); } private function setHttpHeader($headerKey, $headerVal) { $headerKey = strtoupper($headerKey); $headerKey = str_replace('-', '_', $headerKey); $headerKey = 'HTTP_' . $headerKey; $_SERVER[$headerKey] = $headerVal; } }
bsd-3-clause
blezek/Notion
Readme.md
3209
Notion PACS =========== Notion is a stand-alone [PACS](http://en.wikipedia.org/wiki/Picture_archiving_and_communication_system) designed to be used by radiology researchers for storage and anonymization of research images. ### Why use Notion? If you have a need to: - store DICOM images, but do not want/have a dedicated research PACS - anonymize DICOM images - map Names, IDs and Accession numbers during anonymization - maintain separation of image data across projects - scale to 100's of independant research projects ### Why *not* use Notion? If you: - already have a research PACS - do not need to anonymize data - do not care about isolation between research projects - are happy using manual anonymization tools There are other Open Source / free PACS systems available including - [Conquest](http://ingenium.home.xs4all.nl/dicom.html) - [orthanc](http://code.google.com/p/orthanc/) - [OsiriX](http://www.osirix-viewer.com/) - [DCM4CHE](http://www.dcm4che.org/) (Notion is based on dcm4che) - [ClearCanvas](http://www.clearcanvas.ca/) Depending on needs, one of the other systems may be a better fit. #### Installation [Download and unzip the Notion-X.X.X.zip package.](https://github.com/blezek/Notion/releases) Inside you'll find several interesting files, including ```Notion.jar``` and the [documentation](Documentation/html). Installation is complete at this point. Notion is released through [NITRC](http://www.nitrc.org/), future and older releases can be found on the [Notion downloads page](https://www.nitrc.org/frs/?group_id=793). #### Getting started ###### TL;DR version ```bash java -jar Notion.jar server notion.yml ``` Point a browser at [http://localhost:8080](http://localhost:8080). ###### Command line options Notion supports setting several command line parameters: ```bash # java -jar Notion.jar --help usage: Notion [options] [directory] options: -d,--db <arg> Start the embedded DB Web server on the given port (normally 8082), will not start without this option -h,--help Print help and exit -m,--memoryDB Start services in memory (DB only) -p,--port <arg> Port to listen for DICOM traffic, default is 11117 -r,--rest <arg> Port to listen for REST traffic, default is 11118 Start the Notion PACS system using [directory] for data storage. If not specified defaults to the current working directory. By default the REST api is started on port 11118, with the web app being served at http://localhost:11118 The DICOM listener starts on port 11117 (can be changed with a --port) and provides C-ECHO, C-MOVE, C-STORE and C-FIND services. Notion serves as a full DICOM query / retrive SCP. Database administration can be handled via the bundled web interface. By default, http://localhost:8082, if the --db option is given. It will not start up otherwise. The JDBC connection URL is given in the log message of the server. ``` Of particular interest is the `--db` argument which specifies a port for the server to listen on for web access to the embedded database. Performance tuning, db maintance, etc can be performed through the web interface ([http://localhost:8082](http://localhost:8082) by default).
bsd-3-clause
frankpaul142/aurasur
vendor/kartik-v/yii2-grid/messages/config.php
2763
<?php return [ // string, required, root directory of all source files 'sourcePath' => __DIR__ . DIRECTORY_SEPARATOR . '..', // string, required, root directory containing message translations. 'messagePath' => __DIR__, // array, required, list of language codes that the extracted messages // should be translated to. For example, ['zh-CN', 'de']. 'languages' => ['cz', 'da', 'de', 'el-GR', 'en', 'es', 'fa-IR', 'fr', 'hu', 'it', 'lt', 'nl', 'pl', 'pt', 'ru', 'vi', 'zh'], // string, the name of the function for translating messages. // Defaults to 'Yii::t'. This is used as a mark to find the messages to be // translated. You may use a string for single function name or an array for // multiple function names. 'translator' => 'Yii::t', // boolean, whether to sort messages by keys when merging new messages // with the existing ones. Defaults to false, which means the new (untranslated) // messages will be separated from the old (translated) ones. 'sort' => false, // boolean, whether the message file should be overwritten with the merged messages 'overwrite' => true, // boolean, whether to remove messages that no longer appear in the source code. // Defaults to false, which means each of these messages will be enclosed with a pair of '' marks. 'removeUnused' => false, // array, list of patterns that specify which files/directories should NOT be processed. // If empty or not set, all files/directories will be processed. // A path matches a pattern if it contains the pattern string at its end. For example, // '/a/b' will match all files and directories ending with '/a/b'; // the '*.svn' will match all files and directories whose name ends with '.svn'. // and the '.svn' will match all files and directories named exactly '.svn'. // Note, the '/' characters in a pattern matches both '/' and '\'. // See helpers/FileHelper::findFiles() description for more details on pattern matching rules. 'only' => ['*.php'], // array, list of patterns that specify which files (not directories) should be processed. // If empty or not set, all files will be processed. // Please refer to "except" for details about the patterns. // If a file/directory matches both a pattern in "only" and "except", it will NOT be processed. 'except' => [ '.svn', '.git', '.gitignore', '.gitkeep', '.hgignore', '.hgkeep', '/messages', ], // Generated file format. Can be either "php", "po" or "db". 'format' => 'php', // When format is "db", you may specify the following two options //'db' => 'db', //'sourceMessageTable' => '{{%source_message}}', ];
bsd-3-clause
cetin01/callbutler-in-vs2008
CallButler Manager/Forms/EditionChooserForm.Designer.cs
11454
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // 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. // /////////////////////////////////////////////////////////////////////////////////////////////// namespace CallButler.Manager.Forms { partial class EditionChooserForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditionChooserForm)); this.btnOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.btnChooseEdition = new global::Controls.LinkButton(); this.lbEditions = new global::Controls.ListBoxEx(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(280, 279); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 0; this.btnOK.Text = "&OK"; this.btnOK.UseVisualStyleBackColor = true; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(243, 37); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(156, 13); this.label1.TabIndex = 1; this.label1.Text = "Choose a CallButler Edition"; // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(48, 82); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(359, 48); this.label2.TabIndex = 2; this.label2.Text = "Please choose an Edition of CallButler to setup. You are only required to do this" + " once, but you may change the edition later if you choose to upgrade."; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(48, 244); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(168, 13); this.label3.TabIndex = 3; this.label3.Text = "Not sure which edition to choose?"; // // btnChooseEdition // this.btnChooseEdition.AntiAliasText = false; this.btnChooseEdition.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.btnChooseEdition.Cursor = System.Windows.Forms.Cursors.Hand; this.btnChooseEdition.Font = new System.Drawing.Font("Tahoma", 8.25F); this.btnChooseEdition.ForeColor = System.Drawing.Color.RoyalBlue; this.btnChooseEdition.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnChooseEdition.Location = new System.Drawing.Point(212, 241); this.btnChooseEdition.Name = "btnChooseEdition"; this.btnChooseEdition.Size = new System.Drawing.Size(144, 19); this.btnChooseEdition.TabIndex = 24; this.btnChooseEdition.Text = "Click here to learn more."; this.btnChooseEdition.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnChooseEdition.UnderlineOnHover = true; this.btnChooseEdition.Click += new System.EventHandler(this.btnChooseEdition_Click); // // lbEditions // this.lbEditions.AntiAliasText = false; this.lbEditions.BackColor = System.Drawing.Color.WhiteSmoke; this.lbEditions.BorderColor = System.Drawing.Color.Gray; this.lbEditions.CaptionColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.lbEditions.CaptionFont = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbEditions.DisplayMember = "Name"; this.lbEditions.DrawBorder = false; this.lbEditions.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.lbEditions.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbEditions.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.lbEditions.FormattingEnabled = true; this.lbEditions.ItemMargin = 5; this.lbEditions.Location = new System.Drawing.Point(51, 127); this.lbEditions.Name = "lbEditions"; this.lbEditions.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(225)))), ((int)(((byte)(244))))); this.lbEditions.Size = new System.Drawing.Size(356, 113); this.lbEditions.TabIndex = 25; this.lbEditions.ValueMember = "CategoryID"; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button1.Location = new System.Drawing.Point(361, 279); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 26; this.button1.Text = "&Cancel"; this.button1.UseVisualStyleBackColor = true; // // EditionChooserForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.BackgroundImage = global::CallButler.Manager.Properties.Resources.cb_header_small; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.ClientSize = new System.Drawing.Size(448, 314); this.Controls.Add(this.button1); this.Controls.Add(this.lbEditions); this.Controls.Add(this.btnChooseEdition); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.btnOK); this.Font = new System.Drawing.Font("Tahoma", 8.25F); this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "EditionChooserForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Choose CallButler Edition"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private global::Controls.LinkButton btnChooseEdition; private global::Controls.ListBoxEx lbEditions; private System.Windows.Forms.Button button1; } }
bsd-3-clause
exponent/exponent
packages/expo-status-bar/src/useColorScheme.ts
566
import { useColorScheme as maybeUseColorScheme } from 'react-native'; // TODO(brentvatne): add this warning back after releasing SDK 38. // // if (!maybeUseColorScheme) { // console.warn( // 'expo-status-bar is only supported on Expo SDK >= 38 and React Native >= 0.62. You are seeing this message because useColorScheme from react-native is not available. Some features may not work as expected.' // ); // } const fallbackUseColorScheme = () => 'light'; const useColorScheme = maybeUseColorScheme ?? fallbackUseColorScheme; export default useColorScheme;
bsd-3-clause
witcxc/scipy
scipy/signal/signaltools.py
81684
# Author: Travis Oliphant # 1999 -- 2002 from __future__ import division, print_function, absolute_import import warnings import threading from . import sigtools from scipy._lib.six import callable from scipy._lib._version import NumpyVersion from scipy import linalg from scipy.fftpack import (fft, ifft, ifftshift, fft2, ifft2, fftn, ifftn, fftfreq) from numpy.fft import rfftn, irfftn from numpy import (allclose, angle, arange, argsort, array, asarray, atleast_1d, atleast_2d, cast, dot, exp, expand_dims, iscomplexobj, isscalar, mean, ndarray, newaxis, ones, pi, poly, polyadd, polyder, polydiv, polymul, polysub, polyval, prod, product, r_, ravel, real_if_close, reshape, roots, sort, sum, take, transpose, unique, where, zeros, zeros_like) import numpy as np from scipy.special import factorial from .windows import get_window from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext __all__ = ['correlate', 'fftconvolve', 'convolve', 'convolve2d', 'correlate2d', 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter', 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', 'cmplx_sort', 'unique_roots', 'invres', 'invresz', 'residue', 'residuez', 'resample', 'detrend', 'lfilter_zi', 'sosfilt_zi', 'filtfilt', 'decimate', 'vectorstrength'] _modedict = {'valid': 0, 'same': 1, 'full': 2} _boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1, 'symmetric': 1, 'reflect': 4} _rfft_mt_safe = (NumpyVersion(np.__version__) >= '1.9.0.dev-e24486e') _rfft_lock = threading.Lock() def _valfrommode(mode): try: val = _modedict[mode] except KeyError: if mode not in [0, 1, 2]: raise ValueError("Acceptable mode flags are 'valid' (0)," " 'same' (1), or 'full' (2).") val = mode return val def _bvalfromboundary(boundary): try: val = _boundarydict[boundary] << 2 except KeyError: if val not in [0, 1, 2]: raise ValueError("Acceptable boundary flags are 'fill', 'wrap'" " (or 'circular'), \n and 'symm'" " (or 'symmetric').") val = boundary << 2 return val def _check_valid_mode_shapes(shape1, shape2): for d1, d2 in zip(shape1, shape2): if not d1 >= d2: raise ValueError( "in1 should have at least as many items as in2 in " "every dimension for 'valid' mode.") def correlate(in1, in2, mode='full'): """ Cross-correlate two N-dimensional arrays. Cross-correlate `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`; if sizes of `in1` and `in2` are not equal then `in1` has to be the larger array. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. Returns ------- correlate : array An N-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. Notes ----- The correlation z of two d-dimensional arrays x and y is defined as: z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l + k,...]) Examples -------- Implement a matched filter using cross-correlation, to recover a signal that has passed through a noisy channel. >>> from scipy import signal >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128) >>> sig_noise = sig + np.random.randn(len(sig)) >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128 >>> import matplotlib.pyplot as plt >>> clock = np.arange(64, len(sig), 128) >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True) >>> ax_orig.plot(sig) >>> ax_orig.plot(clock, sig[clock], 'ro') >>> ax_orig.set_title('Original signal') >>> ax_noise.plot(sig_noise) >>> ax_noise.set_title('Signal with noise') >>> ax_corr.plot(corr) >>> ax_corr.plot(clock, corr[clock], 'ro') >>> ax_corr.axhline(0.5, ls=':') >>> ax_corr.set_title('Cross-correlated with rectangular pulse') >>> ax_orig.margins(0, 0.1) >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) # Don't use _valfrommode, since correlate should not accept numeric modes try: val = _modedict[mode] except KeyError: raise ValueError("Acceptable mode flags are 'valid'," " 'same', or 'full'.") if in1.ndim == in2.ndim == 0: return in1 * in2 elif not in1.ndim == in2.ndim: raise ValueError("in1 and in2 should have the same dimensionality") if mode == 'valid': _check_valid_mode_shapes(in1.shape, in2.shape) ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)] out = np.empty(ps, in1.dtype) z = sigtools._correlateND(in1, in2, out, val) else: # _correlateND is far slower when in2.size > in1.size, so swap them # and then undo the effect afterward swapped_inputs = (mode == 'full') and (in2.size > in1.size) if swapped_inputs: in1, in2 = in2, in1 ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)] # zero pad input in1zpadded = np.zeros(ps, in1.dtype) sc = [slice(0, i) for i in in1.shape] in1zpadded[sc] = in1.copy() if mode == 'full': out = np.empty(ps, in1.dtype) elif mode == 'same': out = np.empty(in1.shape, in1.dtype) z = sigtools._correlateND(in1zpadded, in2, out, val) # Reverse and conjugate to undo the effect of swapping inputs if swapped_inputs: slice_obj = [slice(None, None, -1)] * len(z.shape) z = z[slice_obj].conj() return z def _centered(arr, newsize): # Return the center newsize portion of the array. newsize = asarray(newsize) currsize = array(arr.shape) startind = (currsize - newsize) // 2 endind = startind + newsize myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] return arr[tuple(myslice)] def _next_regular(target): """ Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to FFTPACK. Target must be a positive integer. """ if target <= 6: return target # Quickly check if it's already a power of 2 if not (target & (target-1)): return target match = float('inf') # Anything found will be smaller p5 = 1 while p5 < target: p35 = p5 while p35 < target: # Ceiling integer division, avoiding conversion to float # (quotient = ceil(target / p35)) quotient = -(-target // p35) # Quickly find next power of 2 >= quotient try: p2 = 2**((quotient - 1).bit_length()) except AttributeError: # Fallback for Python <2.7 p2 = 2**(len(bin(quotient - 1)) - 2) N = p2 * p35 if N == target: return N elif N < match: match = N p35 *= 3 if p35 == target: return p35 if p35 < match: match = p35 p5 *= 5 if p5 == target: return p5 if p5 < match: match = p5 return match def fftconvolve(in1, in2, mode="full"): """Convolve two N-dimensional arrays using FFT. Convolve `in1` and `in2` using the fast Fourier transform method, with the output size determined by the `mode` argument. This is generally much faster than `convolve` for large arrays (n > ~500), but can be slower when only a few output values are needed, and can only output float arrays (int or object array inputs will be cast to float). Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`; if sizes of `in1` and `in2` are not equal then `in1` has to be the larger array. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear convolution of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. Returns ------- out : array An N-dimensional array containing a subset of the discrete linear convolution of `in1` with `in2`. Examples -------- Autocorrelation of white noise is an impulse. (This is at least 100 times as fast as `convolve`.) >>> from scipy import signal >>> sig = np.random.randn(1000) >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full') >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1) >>> ax_orig.plot(sig) >>> ax_orig.set_title('White noise') >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr) >>> ax_mag.set_title('Autocorrelation') >>> fig.show() Gaussian blur implemented using FFT convolution. Notice the dark borders around the image, due to the zero-padding beyond its boundaries. The `convolve2d` function allows for other types of image boundaries, but is far slower. >>> from scipy import misc >>> lena = misc.lena() >>> kernel = np.outer(signal.gaussian(70, 8), signal.gaussian(70, 8)) >>> blurred = signal.fftconvolve(lena, kernel, mode='same') >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(1, 3) >>> ax_orig.imshow(lena, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_kernel.imshow(kernel, cmap='gray') >>> ax_kernel.set_title('Gaussian kernel') >>> ax_kernel.set_axis_off() >>> ax_blurred.imshow(blurred, cmap='gray') >>> ax_blurred.set_title('Blurred') >>> ax_blurred.set_axis_off() >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if in1.ndim == in2.ndim == 0: # scalar inputs return in1 * in2 elif not in1.ndim == in2.ndim: raise ValueError("in1 and in2 should have the same dimensionality") elif in1.size == 0 or in2.size == 0: # empty arrays return array([]) s1 = array(in1.shape) s2 = array(in2.shape) complex_result = (np.issubdtype(in1.dtype, np.complex) or np.issubdtype(in2.dtype, np.complex)) shape = s1 + s2 - 1 if mode == "valid": _check_valid_mode_shapes(s1, s2) # Speed up FFT by padding to optimal size for FFTPACK fshape = [_next_regular(int(d)) for d in shape] fslice = tuple([slice(0, int(sz)) for sz in shape]) # Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make # sure we only call rfftn/irfftn from one thread at a time. if not complex_result and (_rfft_mt_safe or _rfft_lock.acquire(False)): try: ret = irfftn(rfftn(in1, fshape) * rfftn(in2, fshape), fshape)[fslice].copy() finally: if not _rfft_mt_safe: _rfft_lock.release() else: # If we're here, it's either because we need a complex result, or we # failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and # is already in use by another thread). In either case, use the # (threadsafe but slower) SciPy complex-FFT routines instead. ret = ifftn(fftn(in1, fshape) * fftn(in2, fshape))[fslice].copy() if not complex_result: ret = ret.real if mode == "full": return ret elif mode == "same": return _centered(ret, s1) elif mode == "valid": return _centered(ret, s1 - s2 + 1) else: raise ValueError("Acceptable mode flags are 'valid'," " 'same', or 'full'.") def convolve(in1, in2, mode='full'): """ Convolve two N-dimensional arrays. Convolve `in1` and `in2`, with the output size determined by the `mode` argument. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`; if sizes of `in1` and `in2` are not equal then `in1` has to be the larger array. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear convolution of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. Returns ------- convolve : array An N-dimensional array containing a subset of the discrete linear convolution of `in1` with `in2`. See also -------- numpy.polymul : performs polynomial multiplication (same operation, but also accepts poly1d objects) """ volume = asarray(in1) kernel = asarray(in2) if volume.ndim == kernel.ndim == 0: return volume * kernel slice_obj = [slice(None, None, -1)] * len(kernel.shape) if np.iscomplexobj(kernel): return correlate(volume, kernel[slice_obj].conj(), mode) else: return correlate(volume, kernel[slice_obj], mode) def order_filter(a, domain, rank): """ Perform an order filter on an N-dimensional array. Perform an order filter on the array in. The domain argument acts as a mask centered over each pixel. The non-zero elements of domain are used to select elements surrounding each input pixel which are placed in a list. The list is sorted, and the output for that pixel is the element corresponding to rank in the sorted list. Parameters ---------- a : ndarray The N-dimensional input array. domain : array_like A mask array with the same number of dimensions as `in`. Each dimension should have an odd number of elements. rank : int A non-negative integer which selects the element from the sorted list (0 corresponds to the smallest element, 1 is the next smallest element, etc.). Returns ------- out : ndarray The results of the order filter in an array with the same shape as `in`. Examples -------- >>> from scipy import signal >>> x = np.arange(25).reshape(5, 5) >>> domain = np.identity(3) >>> x array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) >>> signal.order_filter(x, domain, 0) array([[ 0., 0., 0., 0., 0.], [ 0., 0., 1., 2., 0.], [ 0., 5., 6., 7., 0.], [ 0., 10., 11., 12., 0.], [ 0., 0., 0., 0., 0.]]) >>> signal.order_filter(x, domain, 2) array([[ 6., 7., 8., 9., 4.], [ 11., 12., 13., 14., 9.], [ 16., 17., 18., 19., 14.], [ 21., 22., 23., 24., 19.], [ 20., 21., 22., 23., 24.]]) """ domain = asarray(domain) size = domain.shape for k in range(len(size)): if (size[k] % 2) != 1: raise ValueError("Each dimension of domain argument " " should have an odd number of elements.") return sigtools._order_filterND(a, domain, rank) def medfilt(volume, kernel_size=None): """ Perform a median filter on an N-dimensional array. Apply a median filter to the input array using a local window-size given by `kernel_size`. Parameters ---------- volume : array_like An N-dimensional input array. kernel_size : array_like, optional A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of `kernel_size` should be odd. If `kernel_size` is a scalar, then this scalar is used as the size in each dimension. Default size is 3 for each dimension. Returns ------- out : ndarray An array the same size as input containing the median filtered result. """ volume = atleast_1d(volume) if kernel_size is None: kernel_size = [3] * len(volume.shape) kernel_size = asarray(kernel_size) if kernel_size.shape == (): kernel_size = np.repeat(kernel_size.item(), volume.ndim) for k in range(len(volume.shape)): if (kernel_size[k] % 2) != 1: raise ValueError("Each element of kernel_size should be odd.") domain = ones(kernel_size) numels = product(kernel_size, axis=0) order = numels // 2 return sigtools._order_filterND(volume, domain, order) def wiener(im, mysize=None, noise=None): """ Perform a Wiener filter on an N-dimensional array. Apply a Wiener filter to the N-dimensional array `im`. Parameters ---------- im : ndarray An N-dimensional array. mysize : int or arraylike, optional A scalar or an N-length list giving the size of the Wiener filter window in each dimension. Elements of mysize should be odd. If mysize is a scalar, then this scalar is used as the size in each dimension. noise : float, optional The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Returns ------- out : ndarray Wiener filtered result with the same shape as `im`. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize) if mysize.shape == (): mysize = np.repeat(mysize.item(), im.ndim) # Estimate the local mean lMean = correlate(im, ones(mysize), 'same') / product(mysize, axis=0) # Estimate the local variance lVar = (correlate(im ** 2, ones(mysize), 'same') / product(mysize, axis=0) - lMean ** 2) # Estimate the noise power if needed. if noise is None: noise = mean(ravel(lVar), axis=0) res = (im - lMean) res *= (1 - noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0): """ Convolve two 2-dimensional arrays. Convolve `in1` and `in2` with output size determined by `mode`, and boundary conditions determined by `boundary` and `fillvalue`. Parameters ---------- in1, in2 : array_like Two-dimensional input arrays to be convolved. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear convolution of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. boundary : str {'fill', 'wrap', 'symm'}, optional A flag indicating how to handle boundaries: ``fill`` pad input arrays with fillvalue. (default) ``wrap`` circular boundary conditions. ``symm`` symmetrical boundary conditions. fillvalue : scalar, optional Value to fill pad input arrays with. Default is 0. Returns ------- out : ndarray A 2-dimensional array containing a subset of the discrete linear convolution of `in1` with `in2`. Examples -------- Compute the gradient of an image by 2D convolution with a complex Scharr operator. (Horizontal operator is real, vertical is imaginary.) Use symmetric boundary condition to avoid creating edges at the image boundaries. >>> from scipy import signal >>> from scipy import misc >>> lena = misc.lena() >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j], ... [-10+0j, 0+ 0j, +10 +0j], ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy >>> grad = signal.convolve2d(lena, scharr, boundary='symm', mode='same') >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(1, 3) >>> ax_orig.imshow(lena, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_mag.imshow(np.absolute(grad), cmap='gray') >>> ax_mag.set_title('Gradient magnitude') >>> ax_mag.set_axis_off() >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles >>> ax_ang.set_title('Gradient orientation') >>> ax_ang.set_axis_off() >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if mode == 'valid': _check_valid_mode_shapes(in1.shape, in2.shape) val = _valfrommode(mode) bval = _bvalfromboundary(boundary) with warnings.catch_warnings(): warnings.simplefilter('ignore', np.ComplexWarning) # FIXME: some cast generates a warning here out = sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue) return out def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0): """ Cross-correlate two 2-dimensional arrays. Cross correlate `in1` and `in2` with output size determined by `mode`, and boundary conditions determined by `boundary` and `fillvalue`. Parameters ---------- in1, in2 : array_like Two-dimensional input arrays to be convolved. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear cross-correlation of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. boundary : str {'fill', 'wrap', 'symm'}, optional A flag indicating how to handle boundaries: ``fill`` pad input arrays with fillvalue. (default) ``wrap`` circular boundary conditions. ``symm`` symmetrical boundary conditions. fillvalue : scalar, optional Value to fill pad input arrays with. Default is 0. Returns ------- correlate2d : ndarray A 2-dimensional array containing a subset of the discrete linear cross-correlation of `in1` with `in2`. Examples -------- Use 2D cross-correlation to find the location of a template in a noisy image: >>> from scipy import signal >>> from scipy import misc >>> lena = misc.lena() - misc.lena().mean() >>> template = np.copy(lena[235:295, 310:370]) # right eye >>> template -= template.mean() >>> lena = lena + np.random.randn(*lena.shape) * 50 # add noise >>> corr = signal.correlate2d(lena, template, boundary='symm', mode='same') >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(1, 3) >>> ax_orig.imshow(lena, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_template.imshow(template, cmap='gray') >>> ax_template.set_title('Template') >>> ax_template.set_axis_off() >>> ax_corr.imshow(corr, cmap='gray') >>> ax_corr.set_title('Cross-correlation') >>> ax_corr.set_axis_off() >>> ax_orig.plot(x, y, 'ro') >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if mode == 'valid': _check_valid_mode_shapes(in1.shape, in2.shape) val = _valfrommode(mode) bval = _bvalfromboundary(boundary) with warnings.catch_warnings(): warnings.simplefilter('ignore', np.ComplexWarning) # FIXME: some cast generates a warning here out = sigtools._convolve2d(in1, in2, 0, val, bval, fillvalue) return out def medfilt2d(input, kernel_size=3): """ Median filter a 2-dimensional array. Apply a median filter to the `input` array using a local window-size given by `kernel_size` (must be odd). Parameters ---------- input : array_like A 2-dimensional input array. kernel_size : array_like, optional A scalar or a list of length 2, giving the size of the median filter window in each dimension. Elements of `kernel_size` should be odd. If `kernel_size` is a scalar, then this scalar is used as the size in each dimension. Default is a kernel of size (3, 3). Returns ------- out : ndarray An array the same size as input containing the median filtered result. """ image = asarray(input) if kernel_size is None: kernel_size = [3] * 2 kernel_size = asarray(kernel_size) if kernel_size.shape == (): kernel_size = np.repeat(kernel_size.item(), 2) for size in kernel_size: if (size % 2) != 1: raise ValueError("Each element of kernel_size should be odd.") return sigtools._medfilt2d(image, kernel_size) def lfilter(b, a, x, axis=-1, zi=None): """ Filter data along one-dimension with an IIR or FIR filter. Filter a data sequence, `x`, using a digital filter. This works for many fundamental data types (including Object type). The filter is a direct form II transposed implementation of the standard difference equation (see Notes). Parameters ---------- b : array_like The numerator coefficient vector in a 1-D sequence. a : array_like The denominator coefficient vector in a 1-D sequence. If ``a[0]`` is not 1, then both `a` and `b` are normalized by ``a[0]``. x : array_like An N-dimensional input array. axis : int The axis of the input data array along which to apply the linear filter. The filter is applied to each subarray along this axis. Default is -1. zi : array_like, optional Initial conditions for the filter delays. It is a vector (or array of vectors for an N-dimensional input) of length ``max(len(a),len(b))-1``. If `zi` is None or is not given then initial rest is assumed. See `lfiltic` for more information. Returns ------- y : array The output of the digital filter. zf : array, optional If `zi` is None, this is not returned, otherwise, `zf` holds the final filter delay values. Notes ----- The filter function is implemented as a direct II transposed structure. This means that the filter implements:: a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[nb]*x[n-nb] - a[1]*y[n-1] - ... - a[na]*y[n-na] using the following difference equations:: y[m] = b[0]*x[m] + z[0,m-1] z[0,m] = b[1]*x[m] + z[1,m-1] - a[1]*y[m] ... z[n-3,m] = b[n-2]*x[m] + z[n-2,m-1] - a[n-2]*y[m] z[n-2,m] = b[n-1]*x[m] - a[n-1]*y[m] where m is the output sample number and n=max(len(a),len(b)) is the model order. The rational transfer function describing this filter in the z-transform domain is:: -1 -nb b[0] + b[1]z + ... + b[nb] z Y(z) = ---------------------------------- X(z) -1 -na a[0] + a[1]z + ... + a[na] z """ if isscalar(a): a = [a] if zi is None: return sigtools._linear_filter(b, a, x, axis) else: return sigtools._linear_filter(b, a, x, axis, zi) def lfiltic(b, a, y, x=None): """ Construct initial conditions for lfilter. Given a linear filter (b, a) and initial conditions on the output `y` and the input `x`, return the initial conditions on the state vector zi which is used by `lfilter` to generate the output given the input. Parameters ---------- b : array_like Linear filter term. a : array_like Linear filter term. y : array_like Initial conditions. If ``N=len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``. If `y` is too short, it is padded with zeros. x : array_like, optional Initial conditions. If ``M=len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``. If `x` is not given, its initial conditions are assumed zero. If `x` is too short, it is padded with zeros. Returns ------- zi : ndarray The state vector ``zi``. ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``, where ``K = max(M,N)``. See Also -------- lfilter """ N = np.size(a) - 1 M = np.size(b) - 1 K = max(M, N) y = asarray(y) if y.dtype.kind in 'bui': # ensure calculations are floating point y = y.astype(np.float64) zi = zeros(K, y.dtype) if x is None: x = zeros(M, y.dtype) else: x = asarray(x) L = np.size(x) if L < M: x = r_[x, zeros(M - L)] L = np.size(y) if L < N: y = r_[y, zeros(N - L)] for m in range(M): zi[m] = sum(b[m + 1:] * x[:M - m], axis=0) for m in range(N): zi[m] -= sum(a[m + 1:] * y[:N - m], axis=0) return zi def deconvolve(signal, divisor): """Deconvolves ``divisor`` out of ``signal``. Returns the quotient and remainder such that ``signal = convolve(divisor, quotient) + remainder`` Parameters ---------- signal : array_like Signal data, typically a recorded signal divisor : array_like Divisor data, typically an impulse response or filter that was applied to the original signal Returns ------- quotient : ndarray Quotient, typically the recovered original signal remainder : ndarray Remainder Examples -------- Deconvolve a signal that's been filtered: >>> from scipy import signal >>> original = [0, 1, 0, 0, 1, 1, 0, 0] >>> impulse_response = [2, 1] >>> recorded = signal.convolve(impulse_response, original) >>> recorded array([0, 2, 1, 0, 2, 3, 1, 0, 0]) >>> recovered, remainder = signal.deconvolve(recorded, impulse_response) >>> recovered array([ 0., 1., 0., 0., 1., 1., 0., 0.]) See also -------- numpy.polydiv : performs polynomial division (same operation, but also accepts poly1d objects) """ num = atleast_1d(signal) den = atleast_1d(divisor) N = len(num) D = len(den) if D > N: quot = [] rem = num else: input = ones(N - D + 1, float) input[1:] = 0 quot = lfilter(num, den, input) rem = num - convolve(den, quot, mode='full') return quot, rem def hilbert(x, N=None, axis=-1): """ Compute the analytic signal, using the Hilbert transform. The transformation is done along the last axis by default. Parameters ---------- x : array_like Signal data. Must be real. N : int, optional Number of Fourier components. Default: ``x.shape[axis]`` axis : int, optional Axis along which to do the transformation. Default: -1. Returns ------- xa : ndarray Analytic signal of `x`, of each 1-D array along `axis` Notes ----- The analytic signal ``x_a(t)`` of signal ``x(t)`` is: .. math:: x_a = F^{-1}(F(x) 2U) = x + i y where `F` is the Fourier transform, `U` the unit step function, and `y` the Hilbert transform of `x`. [1]_ In other words, the negative half of the frequency spectrum is zeroed out, turning the real-valued signal into a complex signal. The Hilbert transformed signal can be obtained from ``np.imag(hilbert(x))``, and the original signal from ``np.real(hilbert(x))``. References ---------- .. [1] Wikipedia, "Analytic signal". http://en.wikipedia.org/wiki/Analytic_signal """ x = asarray(x) if iscomplexobj(x): raise ValueError("x must be real.") if N is None: N = x.shape[axis] if N <= 0: raise ValueError("N must be positive.") Xf = fft(x, N, axis=axis) h = zeros(N) if N % 2 == 0: h[0] = h[N // 2] = 1 h[1:N // 2] = 2 else: h[0] = 1 h[1:(N + 1) // 2] = 2 if len(x.shape) > 1: ind = [newaxis] * x.ndim ind[axis] = slice(None) h = h[ind] x = ifft(Xf * h, axis=axis) return x def hilbert2(x, N=None): """ Compute the '2-D' analytic signal of `x` Parameters ---------- x : array_like 2-D signal data. N : int or tuple of two ints, optional Number of Fourier components. Default is ``x.shape`` Returns ------- xa : ndarray Analytic signal of `x` taken along axes (0,1). References ---------- .. [1] Wikipedia, "Analytic signal", http://en.wikipedia.org/wiki/Analytic_signal """ x = atleast_2d(x) if len(x.shape) > 2: raise ValueError("x must be 2-D.") if iscomplexobj(x): raise ValueError("x must be real.") if N is None: N = x.shape elif isinstance(N, int): if N <= 0: raise ValueError("N must be positive.") N = (N, N) elif len(N) != 2 or np.any(np.asarray(N) <= 0): raise ValueError("When given as a tuple, N must hold exactly " "two positive integers") Xf = fft2(x, N, axes=(0, 1)) h1 = zeros(N[0], 'd') h2 = zeros(N[1], 'd') for p in range(2): h = eval("h%d" % (p + 1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1 // 2] = 1 h[1:N1 // 2] = 2 else: h[0] = 1 h[1:(N1 + 1) // 2] = 2 exec("h%d = h" % (p + 1), globals(), locals()) h = h1[:, newaxis] * h2[newaxis, :] k = len(x.shape) while k > 2: h = h[:, newaxis] k -= 1 x = ifft2(Xf * h, axes=(0, 1)) return x def cmplx_sort(p): """Sort roots based on magnitude. Parameters ---------- p : array_like The roots to sort, as a 1-D array. Returns ------- p_sorted : ndarray Sorted roots. indx : ndarray Array of indices needed to sort the input `p`. """ p = asarray(p) if iscomplexobj(p): indx = argsort(abs(p)) else: indx = argsort(p) return take(p, indx, 0), indx def unique_roots(p, tol=1e-3, rtype='min'): """ Determine unique roots and their multiplicities from a list of roots. Parameters ---------- p : array_like The list of roots. tol : float, optional The tolerance for two roots to be considered equal. Default is 1e-3. rtype : {'max', 'min, 'avg'}, optional How to determine the returned root if multiple roots are within `tol` of each other. - 'max': pick the maximum of those roots. - 'min': pick the minimum of those roots. - 'avg': take the average of those roots. Returns ------- pout : ndarray The list of unique roots, sorted from low to high. mult : ndarray The multiplicity of each root. Notes ----- This utility function is not specific to roots but can be used for any sequence of values for which uniqueness and multiplicity has to be determined. For a more general routine, see `numpy.unique`. Examples -------- >>> from scipy import signal >>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3] >>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg') Check which roots have multiplicity larger than 1: >>> uniq[mult > 1] array([ 1.305]) """ if rtype in ['max', 'maximum']: comproot = np.max elif rtype in ['min', 'minimum']: comproot = np.min elif rtype in ['avg', 'mean']: comproot = np.mean else: raise ValueError("`rtype` must be one of " "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}") p = asarray(p) * 1.0 tol = abs(tol) p, indx = cmplx_sort(p) pout = [] mult = [] indx = -1 curp = p[0] + 5 * tol sameroots = [] for k in range(len(p)): tr = p[k] if abs(tr - curp) < tol: sameroots.append(tr) curp = comproot(sameroots) pout[indx] = curp mult[indx] += 1 else: pout.append(tr) curp = tr sameroots = [tr] indx += 1 mult.append(1) return array(pout), array(mult) def invres(r, p, k, tol=1e-3, rtype='avg'): """ Compute b(s) and a(s) from partial fraction expansion. If ``M = len(b)`` and ``N = len(a)``:: b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like:: r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n Parameters ---------- r : ndarray Residues. p : ndarray Poles. k : ndarray Coefficients of the direct polynomial term. tol : float, optional The tolerance for two roots to be considered equal. Default is 1e-3. rtype : {'max', 'min, 'avg'}, optional How to determine the returned root if multiple roots are within `tol` of each other. 'max': pick the maximum of those roots. 'min': pick the minimum of those roots. 'avg': take the average of those roots. See Also -------- residue, unique_roots """ extra = k p, indx = cmplx_sort(p) r = take(r, indx, 0) pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]] * mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra, a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]] * mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]] * (mult[k] - m - 1)) b = polyadd(b, r[indx] * poly(t2)) indx += 1 b = real_if_close(b) while allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a def residue(b, a, tol=1e-3, rtype='avg'): """ Compute partial-fraction expansion of b(s) / a(s). If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction expansion H(s) is defined as:: b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer together than `tol`), then H(s) has terms like:: r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n Returns ------- r : ndarray Residues. p : ndarray Poles. k : ndarray Coefficients of the direct polynomial term. See Also -------- invres, numpy.poly, unique_roots """ b, a = map(asarray, (b, a)) rscale = a[0] k, b = polydiv(b, a) p = roots(a) r = p * 0.0 pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]] * mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]] * mult[l]) an = atleast_1d(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig, 0, -1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn, 1), an) term2 = polymul(bn, polyder(an, 1)) bn = polysub(term1, term2) an = polymul(an, an) r[indx + m - 1] = (polyval(bn, pout[n]) / polyval(an, pout[n]) / factorial(sig - m)) indx += sig return r / rscale, p, k def residuez(b, a, tol=1e-3, rtype='avg'): """ Compute partial-fraction expansion of b(z) / a(z). If ``M = len(b)`` and ``N = len(a)``:: b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like:: r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also -------- invresz, unique_roots """ b, a = map(asarray, (b, a)) gain = a[0] brev, arev = b[::-1], a[::-1] krev, brev = polydiv(brev, arev) if krev == []: k = [] else: k = krev[::-1] b = brev[::-1] p = roots(a) r = p * 0.0 pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]] * mult[n]) p = asarray(p) # Compute the residue from the general formula (for discrete-time) # the polynomial is in z**(-1) and the multiplication is by terms # like this (1-p[i] z**(-1))**mult[i]. After differentiation, # we must divide by (-p[i])**(m-k) as well as (m-k)! indx = 0 for n in range(len(pout)): bn = brev.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]] * mult[l]) an = atleast_1d(poly(pn))[::-1] # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is # multiplicity of pole at po[n] and b(z) and a(z) are polynomials. sig = mult[n] for m in range(sig, 0, -1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn, 1), an) term2 = polymul(bn, polyder(an, 1)) bn = polysub(term1, term2) an = polymul(an, an) r[indx + m - 1] = (polyval(bn, 1.0 / pout[n]) / polyval(an, 1.0 / pout[n]) / factorial(sig - m) / (-pout[n]) ** (sig - m)) indx += sig return r / gain, p, k def invresz(r, p, k, tol=1e-3, rtype='avg'): """ Compute b(z) and a(z) from partial fraction expansion. If ``M = len(b)`` and ``N = len(a)``:: b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1)... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like:: r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See Also -------- residuez, unique_roots, invres """ extra = asarray(k) p, indx = cmplx_sort(p) r = take(r, indx, 0) pout, mult = unique_roots(p, tol=tol, rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]] * mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra, a) else: b = [0] indx = 0 brev = asarray(b)[::-1] for k in range(len(pout)): temp = [] # Construct polynomial which does not include any of this root for l in range(len(pout)): if l != k: temp.extend([pout[l]] * mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]] * (mult[k] - m - 1)) brev = polyadd(brev, (r[indx] * poly(t2))[::-1]) indx += 1 b = real_if_close(brev[::-1]) return b, a def resample(x, num, t=None, axis=0, window=None): """ Resample `x` to `num` samples using Fourier method along the given axis. The resampled signal starts at the same value as `x` but is sampled with a spacing of ``len(x) / num * (spacing of x)``. Because a Fourier method is used, the signal is assumed to be periodic. Parameters ---------- x : array_like The data to be resampled. num : int The number of samples in the resampled signal. t : array_like, optional If `t` is given, it is assumed to be the sample positions associated with the signal data in `x`. axis : int, optional The axis of `x` that is resampled. Default is 0. window : array_like, callable, string, float, or tuple, optional Specifies the window applied to the signal in the Fourier domain. See below for details. Returns ------- resampled_x or (resampled_x, resampled_t) Either the resampled array, or, if `t` was given, a tuple containing the resampled array and the corresponding resampled positions. Notes ----- The argument `window` controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to alleviate ringing in the resampled values for sampled signals you didn't intend to be interpreted as band-limited. If `window` is a function, then it is called with a vector of inputs indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ). If `window` is an array of the same length as `x.shape[axis]` it is assumed to be the window to be applied directly in the Fourier domain (with dc and low-frequency first). For any other type of `window`, the function `scipy.signal.get_window` is called to generate the window. The first sample of the returned vector is the same as the first sample of the input vector. The spacing between samples is changed from ``dx`` to ``dx * len(x) / num``. If `t` is not None, then it represents the old sample positions, and the new sample positions will be returned as well as the new samples. As noted, `resample` uses FFT transformations, which can be very slow if the number of input samples is large and prime, see `scipy.fftpack.fft`. """ x = asarray(x) X = fft(x, axis=axis) Nx = x.shape[axis] if window is not None: if callable(window): W = window(fftfreq(Nx)) elif isinstance(window, ndarray) and window.shape == (Nx,): W = window else: W = ifftshift(get_window(window, Nx)) newshape = [1] * x.ndim newshape[axis] = len(W) W.shape = newshape X = X * W sl = [slice(None)] * len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(np.minimum(num, Nx)) Y = zeros(newshape, 'D') sl[axis] = slice(0, (N + 1) // 2) Y[sl] = X[sl] sl[axis] = slice(-(N - 1) // 2, None) Y[sl] = X[sl] y = ifft(Y, axis=axis) * (float(num) / float(Nx)) if x.dtype.char not in ['F', 'D']: y = y.real if t is None: return y else: new_t = arange(0, num) * (t[1] - t[0]) * Nx / float(num) + t[0] return y, new_t def vectorstrength(events, period): ''' Determine the vector strength of the events corresponding to the given period. The vector strength is a measure of phase synchrony, how well the timing of the events is synchronized to a single period of a periodic signal. If multiple periods are used, calculate the vector strength of each. This is called the "resonating vector strength". Parameters ---------- events : 1D array_like An array of time points containing the timing of the events. period : float or array_like The period of the signal that the events should synchronize to. The period is in the same units as `events`. It can also be an array of periods, in which case the outputs are arrays of the same length. Returns ------- strength : float or 1D array The strength of the synchronization. 1.0 is perfect synchronization and 0.0 is no synchronization. If `period` is an array, this is also an array with each element containing the vector strength at the corresponding period. phase : float or array The phase that the events are most strongly synchronized to in radians. If `period` is an array, this is also an array with each element containing the phase for the corresponding period. References ---------- van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector strength: Auditory system, electric fish, and noise. Chaos 21, 047508 (2011); doi: 10.1063/1.3670512 van Hemmen, JL. Vector strength after Goldberg, Brown, and von Mises: biological and mathematical perspectives. Biol Cybern. 2013 Aug;107(4):385-96. doi: 10.1007/s00422-013-0561-7. van Hemmen, JL and Vollmayr, AN. Resonating vector strength: what happens when we vary the "probing" frequency while keeping the spike times fixed. Biol Cybern. 2013 Aug;107(4):491-94. doi: 10.1007/s00422-013-0560-8 ''' events = asarray(events) period = asarray(period) if events.ndim > 1: raise ValueError('events cannot have dimensions more than 1') if period.ndim > 1: raise ValueError('period cannot have dimensions more than 1') # we need to know later if period was originally a scalar scalarperiod = not period.ndim events = atleast_2d(events) period = atleast_2d(period) if (period <= 0).any(): raise ValueError('periods must be positive') # this converts the times to vectors vectors = exp(dot(2j*pi/period.T, events)) # the vector strength is just the magnitude of the mean of the vectors # the vector phase is the angle of the mean of the vectors vectormean = mean(vectors, axis=1) strength = abs(vectormean) phase = angle(vectormean) # if the original period was a scalar, return scalars if scalarperiod: strength = strength[0] phase = phase[0] return strength, phase def detrend(data, axis=-1, type='linear', bp=0): """ Remove linear trend along axis from data. Parameters ---------- data : array_like The input data. axis : int, optional The axis along which to detrend the data. By default this is the last axis (-1). type : {'linear', 'constant'}, optional The type of detrending. If ``type == 'linear'`` (default), the result of a linear least-squares fit to `data` is subtracted from `data`. If ``type == 'constant'``, only the mean of `data` is subtracted. bp : array_like of ints, optional A sequence of break points. If given, an individual linear fit is performed for each part of `data` between two break points. Break points are specified as indices into `data`. Returns ------- ret : ndarray The detrended input data. Examples -------- >>> from scipy import signal >>> randgen = np.random.RandomState(9) >>> npoints = 1e3 >>> noise = randgen.randn(npoints) >>> x = 3 + 2*np.linspace(0, 1, npoints) + noise >>> (signal.detrend(x) - noise).max() < 0.01 True """ if type not in ['linear', 'l', 'constant', 'c']: raise ValueError("Trend type must be 'linear' or 'constant'.") data = asarray(data) dtype = data.dtype.char if dtype not in 'dfDF': dtype = 'd' if type in ['constant', 'c']: ret = data - expand_dims(mean(data, axis), axis) return ret else: dshape = data.shape N = dshape[axis] bp = sort(unique(r_[0, bp, N])) if np.any(bp > N): raise ValueError("Breakpoints must be less than length " "of data along given axis.") Nreg = len(bp) - 1 # Restructure data so that axis is along first dimension and # all other dimensions are collapsed into second dimension rnk = len(dshape) if axis < 0: axis = axis + rnk newdims = r_[axis, 0:axis, axis + 1:rnk] newdata = reshape(transpose(data, tuple(newdims)), (N, prod(dshape, axis=0) // N)) newdata = newdata.copy() # make sure we have a copy if newdata.dtype.char not in 'dfDF': newdata = newdata.astype(dtype) # Find leastsq fit and remove it for each piece for m in range(Nreg): Npts = bp[m + 1] - bp[m] A = ones((Npts, 2), dtype) A[:, 0] = cast[dtype](arange(1, Npts + 1) * 1.0 / Npts) sl = slice(bp[m], bp[m + 1]) coef, resids, rank, s = linalg.lstsq(A, newdata[sl]) newdata[sl] = newdata[sl] - dot(A, coef) # Put data back in original shape. tdshape = take(dshape, newdims, 0) ret = reshape(newdata, tuple(tdshape)) vals = list(range(1, rnk)) olddims = vals[:axis] + [0] + vals[axis:] ret = transpose(ret, tuple(olddims)) return ret def lfilter_zi(b, a): """ Compute an initial state `zi` for the lfilter function that corresponds to the steady state of the step response. A typical use of this function is to set the initial state so that the output of the filter starts at the same value as the first element of the signal to be filtered. Parameters ---------- b, a : array_like (1-D) The IIR filter coefficients. See `lfilter` for more information. Returns ------- zi : 1-D ndarray The initial state for the filter. Notes ----- A linear filter with order m has a state space representation (A, B, C, D), for which the output y of the filter can be expressed as:: z(n+1) = A*z(n) + B*x(n) y(n) = C*z(n) + D*x(n) where z(n) is a vector of length m, A has shape (m, m), B has shape (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is a scalar). lfilter_zi solves:: zi = A*zi + B In other words, it finds the initial condition for which the response to an input of all ones is a constant. Given the filter coefficients `a` and `b`, the state space matrices for the transposed direct form II implementation of the linear filter, which is the implementation used by scipy.signal.lfilter, are:: A = scipy.linalg.companion(a).T B = b[1:] - a[1:]*b[0] assuming `a[0]` is 1.0; if `a[0]` is not 1, `a` and `b` are first divided by a[0]. Examples -------- The following code creates a lowpass Butterworth filter. Then it applies that filter to an array whose values are all 1.0; the output is also all 1.0, as expected for a lowpass filter. If the `zi` argument of `lfilter` had not been given, the output would have shown the transient signal. >>> from numpy import array, ones >>> from scipy.signal import lfilter, lfilter_zi, butter >>> b, a = butter(5, 0.25) >>> zi = lfilter_zi(b, a) >>> y, zo = lfilter(b, a, ones(10), zi=zi) >>> y array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) Another example: >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]) >>> y, zf = lfilter(b, a, x, zi=zi*x[0]) >>> y array([ 0.5 , 0.5 , 0.5 , 0.49836039, 0.48610528, 0.44399389, 0.35505241]) Note that the `zi` argument to `lfilter` was computed using `lfilter_zi` and scaled by `x[0]`. Then the output `y` has no transient until the input drops from 0.5 to 0.0. """ # FIXME: Can this function be replaced with an appropriate # use of lfiltic? For example, when b,a = butter(N,Wn), # lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)). # # We could use scipy.signal.normalize, but it uses warnings in # cases where a ValueError is more appropriate, and it allows # b to be 2D. b = np.atleast_1d(b) if b.ndim != 1: raise ValueError("Numerator b must be 1-D.") a = np.atleast_1d(a) if a.ndim != 1: raise ValueError("Denominator a must be 1-D.") while len(a) > 1 and a[0] == 0.0: a = a[1:] if a.size < 1: raise ValueError("There must be at least one nonzero `a` coefficient.") if a[0] != 1.0: # Normalize the coefficients so a[0] == 1. b = b / a[0] a = a / a[0] n = max(len(a), len(b)) # Pad a or b with zeros so they are the same length. if len(a) < n: a = np.r_[a, np.zeros(n - len(a))] elif len(b) < n: b = np.r_[b, np.zeros(n - len(b))] IminusA = np.eye(n - 1) - linalg.companion(a).T B = b[1:] - a[1:] * b[0] # Solve zi = A*zi + B zi = np.linalg.solve(IminusA, B) # For future reference: we could also use the following # explicit formulas to solve the linear system: # # zi = np.zeros(n - 1) # zi[0] = B.sum() / IminusA[:,0].sum() # asum = 1.0 # csum = 0.0 # for k in range(1,n-1): # asum += a[k] # csum += b[k] - a[k]*b[0] # zi[k] = asum*zi[0] - csum return zi def sosfilt_zi(sos): """ Compute an initial state `zi` for the sosfilt function that corresponds to the steady state of the step response. A typical use of this function is to set the initial state so that the output of the filter starts at the same value as the first element of the signal to be filtered. Parameters ---------- sos : array_like Array of second-order filter coefficients, must have shape ``(n_sections, 6)``. See `sosfilt` for the SOS filter format specification. Returns ------- zi : ndarray Initial conditions suitable for use with ``sosfilt``, shape ``(n_sections, 2)``. See Also -------- sosfilt, zpk2sos Notes ----- .. versionadded:: 0.16.0 Examples -------- Filter a rectangular pulse that begins at time 0, with and without the use of the `zi` argument of `scipy.signal.sosfilt`. >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> sos = signal.butter(9, 0.125, output='sos') >>> zi = signal.sosfilt_zi(sos) >>> x = (np.arange(250) < 100).astype(int) >>> f1 = signal.sosfilt(sos, x) >>> f2, zo = signal.sosfilt(sos, x, zi=zi) >>> plt.plot(x, 'k--', label='x') >>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered') >>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi') >>> plt.legend(loc='best') >>> plt.show() """ sos = np.asarray(sos) if sos.ndim != 2 or sos.shape[1] != 6: raise ValueError('sos must be shape (n_sections, 6)') n_sections = sos.shape[0] zi = np.empty((n_sections, 2)) scale = 1.0 for section in range(n_sections): b = sos[section, :3] a = sos[section, 3:] zi[section] = scale * lfilter_zi(b, a) # If H(z) = B(z)/A(z) is this section's transfer function, then # b.sum()/a.sum() is H(1), the gain at omega=0. That's the steady # state value of this section's step response. scale *= b.sum() / a.sum() return zi def _filtfilt_gust(b, a, x, axis=-1, irlen=None): """Forward-backward IIR filter that uses Gustafsson's method. Apply the IIR filter defined by `(b,a)` to `x` twice, first forward then backward, using Gustafsson's initial conditions [1]_. Let ``y_fb`` be the result of filtering first forward and then backward, and let ``y_bf`` be the result of filtering first backward then forward. Gustafsson's method is to compute initial conditions for the forward pass and the backward pass such that ``y_fb == y_bf``. Parameters ---------- b : scalar or 1-D ndarray Numerator coefficients of the filter. a : scalar or 1-D ndarray Denominator coefficients of the filter. x : ndarray Data to be filtered. axis : int, optional Axis of `x` to be filtered. Default is -1. irlen : int or None, optional The length of the nonnegligible part of the impulse response. If `irlen` is None, or if the length of the signal is less than ``2 * irlen``, then no part of the impulse response is ignored. Returns ------- y : ndarray The filtered data. x0 : ndarray Initial condition for the forward filter. x1 : ndarray Initial condition for the backward filter. Notes ----- Typically the return values `x0` and `x1` are not needed by the caller. The intended use of these return values is in unit tests. References ---------- .. [1] F. Gustaffson. Determining the initial states in forward-backward filtering. Transactions on Signal Processing, 46(4):988-992, 1996. """ # In the comments, "Gustafsson's paper" and [1] refer to the # paper referenced in the docstring. b = np.atleast_1d(b) a = np.atleast_1d(a) order = max(len(b), len(a)) - 1 if order == 0: # The filter is just scalar multiplication, with no state. scale = (b[0] / a[0])**2 y = scale * x return y, np.array([]), np.array([]) if axis != -1 or axis != x.ndim - 1: # Move the axis containing the data to the end. x = np.swapaxes(x, axis, x.ndim - 1) # n is the number of samples in the data to be filtered. n = x.shape[-1] if irlen is None or n <= 2*irlen: m = n else: m = irlen # Create Obs, the observability matrix (called O in the paper). # This matrix can be interpreted as the operator that propagates # an arbitrary initial state to the output, assuming the input is # zero. # In Gustafsson's paper, the forward and backward filters are not # necessarily the same, so he has both O_f and O_b. We use the same # filter in both directions, so we only need O. The same comment # applies to S below. Obs = np.zeros((m, order)) zi = np.zeros(order) zi[0] = 1 Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0] for k in range(1, order): Obs[k:, k] = Obs[:-k, 0] # Obsr is O^R (Gustafsson's notation for row-reversed O) Obsr = Obs[::-1] # Create S. S is the matrix that applies the filter to the reversed # propagated initial conditions. That is, # out = S.dot(zi) # is the same as # tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs. # out = lfilter(b, a, tmp[::-1]) # Reverse and filter. # Equations (5) & (6) of [1] S = lfilter(b, a, Obs[::-1], axis=0) # Sr is S^R (row-reversed S) Sr = S[::-1] # M is [(S^R - O), (O^R - S)] if m == n: M = np.hstack((Sr - Obs, Obsr - S)) else: # Matrix described in section IV of [1]. M = np.zeros((2*m, 2*order)) M[:m, :order] = Sr - Obs M[m:, order:] = Obsr - S # Naive forward-backward and backward-forward filters. # These have large transients because the filters use zero initial # conditions. y_f = lfilter(b, a, x) y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1] y_b = lfilter(b, a, x[..., ::-1])[..., ::-1] y_bf = lfilter(b, a, y_b) delta_y_bf_fb = y_bf - y_fb if m == n: delta = delta_y_bf_fb else: start_m = delta_y_bf_fb[..., :m] end_m = delta_y_bf_fb[..., -m:] delta = np.concatenate((start_m, end_m), axis=-1) # ic_opt holds the "optimal" initial conditions. # The following code computes the result shown in the formula # of the paper between equations (6) and (7). if delta.ndim == 1: ic_opt = linalg.lstsq(M, delta)[0] else: # Reshape delta so it can be used as an array of multiple # right-hand-sides in linalg.lstsq. delta2d = delta.reshape(-1, delta.shape[-1]).T ic_opt0 = linalg.lstsq(M, delta2d)[0].T ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],)) # Now compute the filtered signal using equation (7) of [1]. # First, form [S^R, O^R] and call it W. if m == n: W = np.hstack((Sr, Obsr)) else: W = np.zeros((2*m, 2*order)) W[:m, :order] = Sr W[m:, order:] = Obsr # Equation (7) of [1] says # Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt] # `wic` is (almost) the product on the right. # W has shape (m, 2*order), and ic_opt has shape (..., 2*order), # so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T, # so wic has shape (..., m). wic = ic_opt.dot(W.T) # `wic` is "almost" the product of W and the optimal ICs in equation # (7)--if we're using a truncated impulse response (m < n), `wic` # contains only the adjustments required for the ends of the signal. # Here we form y_opt, taking this into account if necessary. y_opt = y_fb if m == n: y_opt += wic else: y_opt[..., :m] += wic[..., :m] y_opt[..., -m:] += wic[..., -m:] x0 = ic_opt[..., :order] x1 = ic_opt[..., -order:] if axis != -1 or axis != x.ndim - 1: # Restore the data axis to its original position. x0 = np.swapaxes(x0, axis, x.ndim - 1) x1 = np.swapaxes(x1, axis, x.ndim - 1) y_opt = np.swapaxes(y_opt, axis, x.ndim - 1) return y_opt, x0, x1 def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', irlen=None): """ A forward-backward filter. This function applies a linear filter twice, once forward and once backwards. The combined filter has linear phase. The function provides options for handling the edges of the signal. When `method` is "pad", the function pads the data along the given axis in one of three ways: odd, even or constant. The odd and even extensions have the corresponding symmetry about the end point of the data. The constant extension extends the data with the values at the end points. On both the forward and backward passes, the initial condition of the filter is found by using `lfilter_zi` and scaling it by the end point of the extended data. When `method` is "gust", Gustafsson's method [1]_ is used. Initial conditions are chosen for the forward and backward passes so that the forward-backward filter gives the same result as the backward-forward filter. Parameters ---------- b : (N,) array_like The numerator coefficient vector of the filter. a : (N,) array_like The denominator coefficient vector of the filter. If ``a[0]`` is not 1, then both `a` and `b` are normalized by ``a[0]``. x : array_like The array of data to be filtered. axis : int, optional The axis of `x` to which the filter is applied. Default is -1. padtype : str or None, optional Must be 'odd', 'even', 'constant', or None. This determines the type of extension to use for the padded signal to which the filter is applied. If `padtype` is None, no padding is used. The default is 'odd'. padlen : int or None, optional The number of elements by which to extend `x` at both ends of `axis` before applying the filter. This value must be less than ``x.shape[axis] - 1``. ``padlen=0`` implies no padding. The default value is ``3 * max(len(a), len(b))``. method : str, optional Determines the method for handling the edges of the signal, either "pad" or "gust". When `method` is "pad", the signal is padded; the type of padding is determined by `padtype` and `padlen`, and `irlen` is ignored. When `method` is "gust", Gustafsson's method is used, and `padtype` and `padlen` are ignored. irlen : int or None, optional When `method` is "gust", `irlen` specifies the length of the impulse response of the filter. If `irlen` is None, no part of the impulse response is ignored. For a long signal, specifying `irlen` can significantly improve the performance of the filter. Returns ------- y : ndarray The filtered output, an array of type numpy.float64 with the same shape as `x`. See Also -------- lfilter_zi, lfilter Notes ----- The option to use Gustaffson's method was added in scipy version 0.16.0. References ---------- .. [1] F. Gustaffson, "Determining the initial states in forward-backward filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992, 1996. Examples -------- The examples will use several functions from `scipy.signal`. >>> from scipy import signal >>> import matplotlib.pyplot as plt First we create a one second signal that is the sum of two pure sine waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz. >>> t = np.linspace(0, 1.0, 2001) >>> xlow = np.sin(2 * np.pi * 5 * t) >>> xhigh = np.sin(2 * np.pi * 250 * t) >>> x = xlow + xhigh Now create a lowpass Butterworth filter with a cutoff of 0.125 times the Nyquist rate, or 125 Hz, and apply it to ``x`` with `filtfilt`. The result should be approximately ``xlow``, with no phase shift. >>> b, a = signal.butter(8, 0.125) >>> y = signal.filtfilt(b, a, x, padlen=150) >>> np.abs(y - xlow).max() 9.1086182074789912e-06 We get a fairly clean result for this artificial example because the odd extension is exact, and with the moderately long padding, the filter's transients have dissipated by the time the actual data is reached. In general, transient effects at the edges are unavoidable. The following example demonstrates the option ``method="gust"``. First, create a filter. >>> b, a = signal.ellip(4, 0.01, 120, 0.125) # Filter to be applied. >>> np.random.seed(123456) `sig` is a random input signal to be filtered. >>> n = 60 >>> sig = np.random.randn(n)**3 + 3*np.random.randn(n).cumsum() Apply `filtfilt` to `sig`, once using the Gustafsson method, and once using padding, and plot the results for comparison. >>> fgust = signal.filtfilt(b, a, sig, method="gust") >>> fpad = signal.filtfilt(b, a, sig, padlen=50) >>> plt.plot(sig, 'k-', label='input') >>> plt.plot(fgust, 'b-', linewidth=4, label='gust') >>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad') >>> plt.legend(loc='best') >>> plt.show() The `irlen` argument can be used to improve the performance of Gustafsson's method. Estimate the impulse response length of the filter. >>> z, p, k = signal.tf2zpk(b, a) >>> eps = 1e-9 >>> r = np.max(np.abs(p)) >>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) >>> approx_impulse_len 137 Apply the filter to a longer signal, with and without the `irlen` argument. The difference between `y1` and `y2` is small. For long signals, using `irlen` gives a significant performance improvement. >>> x = np.random.randn(5000) >>> y1 = signal.filtfilt(b, a, x, method='gust') >>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len) >>> print(np.max(np.abs(y1 - y2))) 1.80056858312e-10 """ b = np.atleast_1d(b) a = np.atleast_1d(a) x = np.asarray(x) if method not in ["pad", "gust"]: raise ValueError("method must be 'pad' or 'gust'.") if method == "gust": y, z1, z2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) return y # `method` is "pad"... ntaps = max(len(a), len(b)) if padtype not in ['even', 'odd', 'constant', None]: raise ValueError(("Unknown value '%s' given to padtype. padtype " "must be 'even', 'odd', 'constant', or None.") % padtype) if padtype is None: padlen = 0 if padlen is None: # Original padding; preserved for backwards compatibility. edge = ntaps * 3 else: edge = padlen # x's 'axis' dimension must be bigger than edge. if x.shape[axis] <= edge: raise ValueError("The length of the input vector x must be at least " "padlen, which is %d." % edge) if padtype is not None and edge > 0: # Make an extension of length `edge` at each # end of the input array. if padtype == 'even': ext = even_ext(x, edge, axis=axis) elif padtype == 'odd': ext = odd_ext(x, edge, axis=axis) else: ext = const_ext(x, edge, axis=axis) else: ext = x # Get the steady state of the filter's step response. zi = lfilter_zi(b, a) # Reshape zi and create x0 so that zi*x0 broadcasts # to the correct value for the 'zi' keyword argument # to lfilter. zi_shape = [1] * x.ndim zi_shape[axis] = zi.size zi = np.reshape(zi, zi_shape) x0 = axis_slice(ext, stop=1, axis=axis) # Forward filter. (y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0) # Backward filter. # Create y0 so zi*y0 broadcasts appropriately. y0 = axis_slice(y, start=-1, axis=axis) (y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0) # Reverse y. y = axis_reverse(y, axis=axis) if edge > 0: # Slice the actual signal from the extended signal. y = axis_slice(y, start=edge, stop=-edge, axis=axis) return y def sosfilt(sos, x, axis=-1, zi=None): """ Filter data along one dimension using cascaded second-order sections Filter a data sequence, `x`, using a digital IIR filter defined by `sos`. This is implemented by performing `lfilter` for each second-order section. See `lfilter` for details. Parameters ---------- sos : array_like Array of second-order filter coefficients, must have shape ``(n_sections, 6)``. Each row corresponds to a second-order section, with the first three columns providing the numerator coefficients and the last three providing the denominator coefficients. x : array_like An N-dimensional input array. axis : int The axis of the input data array along which to apply the linear filter. The filter is applied to each subarray along this axis. Default is -1. zi : array_like, optional Initial conditions for the cascaded filter delays. It is a (at least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]`` replaced by 2. If `zi` is None or is not given then initial rest (i.e. all zeros) is assumed. Note that these initial conditions are *not* the same as the initial conditions given by `lfiltic` or `lfilter_zi`. Returns ------- y : ndarray The output of the digital filter. zf : ndarray, optional If `zi` is None, this is not returned, otherwise, `zf` holds the final filter delay values. See Also -------- zpk2sos, sos2zpk, sosfilt_zi Notes ----- The filter function is implemented as a series of second-order filters with direct-form II transposed structure. It is designed to minimize numerical precision errors for high-order filters. .. versionadded:: 0.16.0 Examples -------- Plot a 13th-order filter's impulse response using both `lfilter` and `sosfilt`, showing the instability that results from trying to do a 13th-order filter in a single stage (the numerical error pushes some poles outside of the unit circle): >>> import matplotlib.pyplot as plt >>> from scipy import signal >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba') >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos') >>> x = np.zeros(700) >>> x[0] = 1. >>> y_tf = signal.lfilter(b, a, x) >>> y_sos = signal.sosfilt(sos, x) >>> plt.plot(y_tf, 'r', label='TF') >>> plt.plot(y_sos, 'k', label='SOS') >>> plt.legend(loc='best') >>> plt.show() """ x = np.asarray(x) sos = atleast_2d(sos) if sos.ndim != 2: raise ValueError('sos array must be 2D') n_sections, m = sos.shape if m != 6: raise ValueError('sos array must be shape (n_sections, 6)') use_zi = zi is not None if use_zi: zi = np.asarray(zi) x_zi_shape = list(x.shape) x_zi_shape[axis] = 2 x_zi_shape = tuple([n_sections] + x_zi_shape) if zi.shape != x_zi_shape: raise ValueError('Invalid zi shape. With axis=%r, an input with ' 'shape %r, and an sos array with %d sections, zi ' 'must have shape %r.' % (axis, x.shape, n_sections, x_zi_shape)) zf = zeros_like(zi) for section in range(n_sections): if use_zi: x, zf[section] = lfilter(sos[section, :3], sos[section, 3:], x, axis, zi=zi[section]) else: x = lfilter(sos[section, :3], sos[section, 3:], x, axis) out = (x, zf) if use_zi else x return out from scipy.signal.filter_design import cheby1 from scipy.signal.fir_filter_design import firwin def decimate(x, q, n=None, ftype='iir', axis=-1): """ Downsample the signal by using a filter. By default, an order 8 Chebyshev type I filter is used. A 30 point FIR filter with hamming window is used if `ftype` is 'fir'. Parameters ---------- x : ndarray The signal to be downsampled, as an N-dimensional array. q : int The downsampling factor. n : int, optional The order of the filter (1 less than the length for 'fir'). ftype : str {'iir', 'fir'}, optional The type of the lowpass filter. axis : int, optional The axis along which to decimate. Returns ------- y : ndarray The down-sampled signal. See also -------- resample """ if not isinstance(q, int): raise TypeError("q must be an integer") if n is None: if ftype == 'fir': n = 30 else: n = 8 if ftype == 'fir': b = firwin(n + 1, 1. / q, window='hamming') a = 1. else: b, a = cheby1(n, 0.05, 0.8 / q) y = lfilter(b, a, x, axis=axis) sl = [slice(None)] * y.ndim sl[axis] = slice(None, None, q) return y[sl]
bsd-3-clause
OBHITA/Consent2Share
DS4P/acs-showcase/c32-parser/src/main/java/gov/samhsa/consent2share/c32/dto/Qualifier.java
5997
/******************************************************************************* * Open Behavioral Health Information Technology Architecture (OBHITA.org) * * 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. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 <COPYRIGHT HOLDER> 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. ******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.10.18 at 11:05:26 AM EDT // package gov.samhsa.consent2share.c32.dto; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; // TODO: Auto-generated Javadoc /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{urn:hl7-org:v3}cd"> * &lt;sequence> * &lt;element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="value"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{urn:hl7-org:v3}cd"> * &lt;sequence> * &lt;element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "value" }) @XmlRootElement(name = "qualifier") public class Qualifier { /** The name. */ @XmlElement(required = true) protected Name name; /** The value. */ @XmlElement(required = true) protected Qualifier.Value value; /** * Gets the value of the name property. * * @return the name * possible object is * {@link Name } */ public Name getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link Name } * */ public void setName(Name value) { this.name = value; } /** * Gets the value of the value property. * * @return the value * possible object is * {@link Qualifier.Value } */ public Qualifier.Value getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link Qualifier.Value } * */ public void setValue(Qualifier.Value value) { this.value = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{urn:hl7-org:v3}cd"> * &lt;sequence> * &lt;element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Value extends Cd { } }
bsd-3-clause
mdcconcepts/opinion_desk_CAP
protected/models/menu/views/item/_form.php
4676
<div class="form"> <?php $form = $this->beginWidget('CActiveForm', array( 'id' => 'menu-item-form', 'enableAjaxValidation' => false, 'enableClientValidation' => true, )); echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model, 'name'); ?> <?php echo $form->textField($model, 'name', array('size' => 60, 'maxlength' => 128)); ?> <?php echo $form->error($model, 'name'); ?> </div><!-- row --> <div class="row"> <?php echo CHtml::radioButton('MenuItem[type]', $model->type == 'module', array('value' => 'module', 'id' => 'radio_module')); ?> <?php echo Yii::t('app', 'Module') . ' '; ?> <?php echo Chtml::dropDownList('MenuItem[module]', $model->link, Awecms::getModulesWithPath(), array('onfocus' => 'js:$("#radio_module").attr("checked", "checked");'));?> <br/> <?php // echo CHtml::radioButton('MenuItem[type]', $model->type == 'action', array('value' => 'action')); ?> <?php // echo Yii::t('app', 'Action'); // print_r(Awecms::getAllActions()); ?> <!--<br/>--> <?php if (Yii::app()->hasModule('page')) { echo CHtml::radioButton('MenuItem[type]', $model->type == 'content', array('value' => 'content', 'id' => 'radio_content')); echo Yii::t('app', 'Content') . ' '; echo CHtml::dropDownList('MenuItem[content]', $model->link, CHtml::listData(Page::model()->findAll(), 'path', 'title'), array('onfocus' => 'js:$("#radio_content").attr("checked", "checked");')); } ?> <br/> <?php echo CHtml::radioButton('MenuItem[type]', $model->type == 'url', array('value' => 'url', 'id' => 'radio_url')); ?> <?php echo Yii::t('app', 'Link') . ' '; ?> <?php echo Chtml::textField('MenuItem[url]', $model->link, array('size' => 60, 'onfocus' => 'js:$("#radio_url").attr("checked", "checked");')); ?> <?php echo $form->error($model, 'link'); ?> <br/> <p class="hint"> /item points to base_url/item, //item points to root_of_server/item, item creates link relative to dynamic user location, URLs rendered as is. </p> </div><!-- row --> <div class="row"> <?php echo $form->labelEx($model, 'description'); ?> <?php echo $form->textArea($model, 'description', array('rows' => 6, 'cols' => 50)); ?> <?php echo $form->error($model, 'description'); ?> </div><!-- row --> <div class="row"> <?php echo $form->labelEx($model, 'enabled'); ?> <?php echo $form->checkBox($model, 'enabled'); ?> <?php echo $form->error($model, 'enabled'); ?> </div><!-- row --> <div class="row"> <?php echo $form->labelEx($model, 'role'); ?> <?php echo CHtml::checkBoxList(get_class($model) . '[role]', explode(',', $model->role), $model->roles, array('selected' => 'all')); ?> <?php echo $form->error($model, 'role'); ?> </div><!-- row --> <div class="row"> <?php echo $form->labelEx($model, 'Open in new tab?'); ?> <?php echo CHtml::checkBox('MenuItem[target]', $model->target == '_blank', array('value' => '_blank')); ?> <?php echo $form->error($model, 'target'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'parent_id'); ?> <?php //show all menu items but current one $allModels = MenuItem::model()->findAll(); foreach ($allModels as $key => $aModel) { if ($aModel->id == $model->id) unset($allModels[$key]); } echo $form->dropDownList($model, 'parent', CHtml::listData($allModels, 'id', 'name'), array('prompt' => 'None')); ?> <?php echo $form->error($model, 'parent_id'); ?> </div><!-- row --> <?php //menu selection available only for edit if (isset($menuId)) echo $form->hiddenField($model, 'menu', array('value' => $menuId)); else { ?> <div class="row"> <?php echo $form->labelEx($model, 'menu_id'); ?> <?php echo $form->dropDownList($model, 'menu', CHtml::listData(Menu::model()->findAll(), 'id', 'name')); ?> <?php echo $form->error($model, 'menu_id'); ?> </div> <?php } ?> <div class="row buttons"> <?php echo CHtml::submitButton(Yii::t('app', 'Save')); echo CHtml::Button(Yii::t('app', 'Cancel'), array( 'submit' => 'javascript:history.go(-1)')); ?> </div> <?php $this->endWidget(); ?> </div>
bsd-3-clause
rsmmr/hilti
tests/hilti/c-api/c-interface-noyield-host.c
572
// @TEST-IGNORE #include <stdio.h> #include <libhilti.h> #include "c-interface-noyield.hlt.h" int main() { hlt_init(); hlt_execution_context* ctx = hlt_global_execution_context(); hlt_exception* excpt = 0; int i; foo_foo1(21, 1, &excpt, ctx); int32_t n = foo_foo2(21, &excpt, ctx); printf("C: %d\n", n); hlt_string t = hlt_string_from_asciiz("Foo", &excpt, ctx); hlt_string s = foo_foo3(t, &excpt, ctx); printf("C: "); for ( i = 0; i < s->len; i++ ) printf("%c", s->bytes[i]); printf("\n"); return 0; }
bsd-3-clause