code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* Public domain */ #ifndef _AGAR_CORE_NET_SERVER_H_ #define _AGAR_CORE_NET_SERVER_H_ #include <agar/core/begin.h> #define NS_HOSTNAME_MAX 256 struct ns_server; struct ns_client; struct ns_cmd; enum ns_log_lvl { NS_DEBUG, NS_INFO, NS_NOTICE, NS_WARNING, NS_ERR, NS_CRIT, NS_ALERT, NS_EMERG }; typedef int (*NS_LoginFn)(struct ns_server *, void *); typedef void (*NS_LogoutFn)(struct ns_server *, void *); typedef void (*NS_SigCheckFn)(struct ns_server *); typedef int (*NS_ErrorFn)(struct ns_server *); typedef int (*NS_AuthFn)(struct ns_server *, void *); typedef int (*NS_CommandFn)(struct ns_server *, NS_Command *, void *); typedef struct ns_cmd { const char *name; NS_CommandFn fn; void *arg; } NS_Cmd; typedef struct ns_auth { const char *name; NS_AuthFn fn; void *arg; } NS_Auth; typedef struct ns_server { struct ag_object obj; Uint flags; const char *protoName; /* Daemon name / protocol signature */ const char *protoVer; /* Protocol version string */ const char *host; /* Hostname for bind(), or NULL */ const char *port; /* Port number or name */ pid_t listenProc; /* PID of listening process */ NS_Cmd *cmds; /* Implemented commands */ Uint ncmds; NS_Auth *authModes; /* Authentication methods */ Uint nAuthModes; NS_ErrorFn errorFn; /* Call when any command fails, instead of returning error to client. */ NS_SigCheckFn sigCheckFn; /* Call upon signal interruptions */ NS_LoginFn loginFn; /* Call after basic auth */ NS_LogoutFn logoutFn; /* Call on disconnection */ void **listItems; /* For list functions */ size_t *listItemSize; Uint listItemCount; AG_TAILQ_HEAD_(ns_client) clients; /* Connected clients */ } NS_Server; typedef struct ns_client { struct ag_object obj; char host[NS_HOSTNAME_MAX]; /* Remote host */ } NS_Client; __BEGIN_DECLS extern AG_ObjectClass nsServerClass; extern AG_ObjectClass nsClientClass; void NS_InitSubsystem(Uint); NS_Server *NS_ServerNew(void *, Uint, const char *, const char *, const char *, const char *); void NS_ServerSetProtocol(NS_Server *, const char *, const char *); void NS_ServerBind(NS_Server *, const char *, const char *); void NS_Log(enum ns_log_lvl, const char *, ...); void NS_RegErrorFn(NS_Server *, NS_ErrorFn); void NS_RegSigCheckFn(NS_Server *, NS_SigCheckFn); void NS_RegCmd(NS_Server *, const char *, NS_CommandFn, void *); void NS_RegAuthMode(NS_Server *, const char *, NS_AuthFn, void *); void NS_RegLoginFn(NS_Server *, NS_LoginFn); void NS_RegLogoutFn(NS_Server *, NS_LogoutFn); int NS_ServerLoop(NS_Server *); void NS_Logout(NS_Server *, int, const char *, ...); void NS_Message(NS_Server *, int, const char *, ...); void NS_BeginData(NS_Server *, size_t); size_t NS_Data(NS_Server *, char *, size_t); void NS_EndData(NS_Server *); void NS_BeginList(NS_Server *); void NS_EndList(NS_Server *); void NS_ListItem(NS_Server *, void *, size_t); void NS_ListString(NS_Server *, const char *, ...); int NS_Write(NS_Server *, int, const void *, size_t); int NS_Read(NS_Server *, int, void *, size_t); __END_DECLS #include <agar/core/close.h> #endif /* _AGAR_CORE_NET_SERVER_H_ */
adsr/agar
core/net_server.h
C
bsd-2-clause
3,159
-- load_cfg.lua - internal file local ffi = require('ffi') ffi.cdef([[ void check_cfg(); void load_cfg(); void box_set_wal_mode(const char *mode); void box_set_listen(const char *uri); void box_set_replication_source(const char *source); void box_set_log_level(int level); void box_set_readahead(int readahead); void box_set_io_collect_interval(double interval); void box_set_too_long_threshold(double threshold); void box_set_snap_io_rate_limit(double limit); void box_set_panic_on_wal_error(int); ]]) local log = require('log') -- see default_cfg below local default_sophia_cfg = { memory_limit = 0, threads = 5, node_size = 134217728, page_size = 131072, compression = "none" } -- all available options local default_cfg = { listen = nil, slab_alloc_arena = 1.0, slab_alloc_minimal = 16, slab_alloc_maximal = 1024 * 1024, slab_alloc_factor = 1.1, work_dir = nil, snap_dir = ".", wal_dir = ".", sophia_dir = '.', sophia = default_sophia_cfg, logger = nil, logger_nonblock = true, log_level = 5, io_collect_interval = nil, readahead = 16320, snap_io_rate_limit = nil, -- no limit too_long_threshold = 0.5, wal_mode = "write", rows_per_wal = 500000, wal_dir_rescan_delay= 2, panic_on_snap_error = true, panic_on_wal_error = true, replication_source = nil, custom_proc_title = nil, pid_file = nil, background = false, username = nil , coredump = false, -- snapshot_daemon snapshot_period = 0, -- 0 = disabled snapshot_count = 6, } -- see template_cfg below local sophia_template_cfg = { memory_limit = 'number', threads = 'number', node_size = 'number', page_size = 'number', compression = 'string' } -- types of available options -- could be comma separated lua types or 'any' if any type is allowed local template_cfg = { listen = 'string, number', slab_alloc_arena = 'number', slab_alloc_minimal = 'number', slab_alloc_maximal = 'number', slab_alloc_factor = 'number', work_dir = 'string', snap_dir = 'string', wal_dir = 'string', sophia_dir = 'string', sophia = sophia_template_cfg, logger = 'string', logger_nonblock = 'boolean', log_level = 'number', io_collect_interval = 'number', readahead = 'number', snap_io_rate_limit = 'number', too_long_threshold = 'number', wal_mode = 'string', rows_per_wal = 'number', wal_dir_rescan_delay= 'number', panic_on_snap_error = 'boolean', panic_on_wal_error = 'boolean', replication_source = 'string, number', custom_proc_title = 'string', pid_file = 'string', background = 'boolean', username = 'string', coredump = 'boolean', snapshot_period = 'number', snapshot_count = 'number', } local function normalize_uri(port) if port == nil or type(port) == 'table' then return port end return tostring(port); end -- options that require special handling local modify_cfg = { listen = normalize_uri, replication_source = normalize_uri, } -- dynamically settable options local dynamic_cfg = { wal_mode = ffi.C.box_set_wal_mode, listen = ffi.C.box_set_listen, replication_source = ffi.C.box_set_replication_source, log_level = ffi.C.box_set_log_level, io_collect_interval = ffi.C.box_set_io_collect_interval, readahead = ffi.C.box_set_readahead, too_long_threshold = ffi.C.box_set_too_long_threshold, snap_io_rate_limit = ffi.C.box_set_snap_io_rate_limit, panic_on_wal_error = ffi.C.box_set_panic_on_wal_error, -- snapshot_daemon snapshot_period = box.internal.snapshot_daemon.set_snapshot_period, snapshot_count = box.internal.snapshot_daemon.set_snapshot_count, -- do nothing, affects new replicas, which query this value on start wal_dir_rescan_delay = function() end } local dynamic_cfg_skip_at_load = { wal_mode = true, listen = true, replication_source = true, wal_dir_rescan_delay = true, panic_on_wal_error = true, } local function prepare_cfg(cfg, default_cfg, template_cfg, modify_cfg, prefix) if cfg == nil then return {} end if type(cfg) ~= 'table' then error("Error: cfg should be a table") end -- just pass {.. dont_check = true, ..} to disable check below if cfg.dont_check then return end local readable_prefix = '' if prefix ~= nil and prefix ~= '' then readable_prefix = prefix .. '.' end local new_cfg = {} for k,v in pairs(cfg) do local readable_name = readable_prefix .. k; if template_cfg[k] == nil then error("Error: cfg parameter '" .. readable_name .. "' is unexpected") elseif v == "" or v == nil then -- "" and NULL = ffi.cast('void *', 0) set option to default value v = default_cfg[k] elseif template_cfg[k] == 'any' then -- any type is ok elseif type(template_cfg[k]) == 'table' then if type(v) ~= 'table' then error("Error: cfg parameter '" .. readable_name .. "' should be a table") end v = prepare_cfg(v, default_cfg[k], template_cfg[k], modify_cfg[k], readable_name) elseif (string.find(template_cfg[k], ',') == nil) then -- one type if type(v) ~= template_cfg[k] then error("Error: cfg parameter '" .. readable_name .. "' should be of type " .. template_cfg[k]) end else local good_types = string.gsub(template_cfg[k], ' ', ''); if (string.find(',' .. good_types .. ',', ',' .. type(v) .. ',') == nil) then good_types = string.gsub(good_types, ',', ', '); error("Error: cfg parameter '" .. readable_name .. "' should be one of types: " .. template_cfg[k]) end end if modify_cfg ~= nil and type(modify_cfg[k]) == 'function' then v = modify_cfg[k](v) end new_cfg[k] = v end return new_cfg end local function apply_default_cfg(cfg, default_cfg) for k,v in pairs(default_cfg) do if cfg[k] == nil then cfg[k] = v elseif type(v) == 'table' then apply_default_cfg(cfg[k], v) end end end local function reload_cfg(oldcfg, cfg) local newcfg = prepare_cfg(cfg, default_cfg, template_cfg, modify_cfg) -- iterate over original table because prepare_cfg() may store NILs for key in pairs(cfg) do if dynamic_cfg[key] == nil then box.error(box.error.RELOAD_CFG, key); end end for key in pairs(cfg) do local val = newcfg[key] if oldcfg[key] ~= val then dynamic_cfg[key](val) rawset(oldcfg, key, val) log.info("set '%s' configuration option to '%s'", key, val) end end if type(box.on_reload_configuration) == 'function' then box.on_reload_configuration() end end local box = require('box') -- Move all box members except 'error' to box_configured local box_configured = {} for k, v in pairs(box) do box_configured[k] = v -- box.net.box uses box.error and box.internal if k ~= 'error' and k ~= 'internal' and k ~= 'index' then box[k] = nil end end setmetatable(box, { __index = function(table, index) error(debug.traceback("Please call box.cfg{} first")) error("Please call box.cfg{} first") end }) local function load_cfg(cfg) cfg = prepare_cfg(cfg, default_cfg, template_cfg, modify_cfg) apply_default_cfg(cfg, default_cfg); -- Save new box.cfg box.cfg = cfg if not pcall(ffi.C.check_cfg) then box.cfg = load_cfg -- restore original box.cfg return box.error() -- re-throw exception from check_cfg() end -- Restore box members after initial configuration for k, v in pairs(box_configured) do box[k] = v end setmetatable(box, nil) box_configured = nil box.cfg = setmetatable(cfg, { __newindex = function(table, index) error('Attempt to modify a read-only table') end, __call = reload_cfg, }) ffi.C.load_cfg() for key, fun in pairs(dynamic_cfg) do local val = cfg[key] if val ~= nil and not dynamic_cfg_skip_at_load[key] then fun(cfg[key]) if val ~= default_cfg[key] then log.info("set '%s' configuration option to '%s'", key, val) end end end end box.cfg = load_cfg jit.off(load_cfg) jit.off(reload_cfg) jit.off(box.cfg)
dkorolev/tarantool
src/box/lua/load_cfg.lua
Lua
bsd-2-clause
9,216
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2014-2014. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_DETAIL_CONSTRUCT_IN_PLACE_HPP #define BOOST_CONTAINER_DETAIL_CONSTRUCT_IN_PLACE_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/container/allocator_traits.hpp> #include <boost/container/detail/iterators.hpp> #include <boost/container/detail/value_init.hpp> namespace lslboost { namespace container { //In place construction template<class Allocator, class T, class InpIt> BOOST_CONTAINER_FORCEINLINE void construct_in_place(Allocator &a, T* dest, InpIt source) { lslboost::container::allocator_traits<Allocator>::construct(a, dest, *source); } template<class Allocator, class T, class U, class D> BOOST_CONTAINER_FORCEINLINE void construct_in_place(Allocator &a, T *dest, value_init_construct_iterator<U, D>) { lslboost::container::allocator_traits<Allocator>::construct(a, dest); } template <class T, class Difference> class default_init_construct_iterator; template<class Allocator, class T, class U, class D> BOOST_CONTAINER_FORCEINLINE void construct_in_place(Allocator &a, T *dest, default_init_construct_iterator<U, D>) { lslboost::container::allocator_traits<Allocator>::construct(a, dest, default_init); } template <class T, class EmplaceFunctor, class Difference> class emplace_iterator; template<class Allocator, class T, class U, class EF, class D> BOOST_CONTAINER_FORCEINLINE void construct_in_place(Allocator &a, T *dest, emplace_iterator<U, EF, D> ei) { ei.construct_in_place(a, dest); } //Assignment template<class DstIt, class InpIt> BOOST_CONTAINER_FORCEINLINE void assign_in_place(DstIt dest, InpIt source) { *dest = *source; } template<class DstIt, class U, class D> BOOST_CONTAINER_FORCEINLINE void assign_in_place(DstIt dest, value_init_construct_iterator<U, D>) { dtl::value_init<U> val; *dest = lslboost::move(val.get()); } template <class DstIt, class Difference> class default_init_construct_iterator; template<class DstIt, class U, class D> BOOST_CONTAINER_FORCEINLINE void assign_in_place(DstIt dest, default_init_construct_iterator<U, D>) { U u; *dest = lslboost::move(u); } template <class T, class EmplaceFunctor, class Difference> class emplace_iterator; template<class DstIt, class U, class EF, class D> BOOST_CONTAINER_FORCEINLINE void assign_in_place(DstIt dest, emplace_iterator<U, EF, D> ei) { ei.assign_in_place(dest); } } //namespace container { } //namespace lslboost { #endif //#ifndef BOOST_CONTAINER_DETAIL_CONSTRUCT_IN_PLACE_HPP
nihospr01/OpenSpeechPlatform-UCSD
Sources/liblsl/lslboost/boost/container/detail/construct_in_place.hpp
C++
bsd-2-clause
2,973
var searchData= [ ['time',['time',['../group__lib__time.html',1,'']]], ['thread',['thread',['../group__thread.html',1,'']]] ];
alexeyk13/mkernel
doc/html/search/groups_74.js
JavaScript
bsd-2-clause
131
#include "e.h" static void *_create_data(E_Config_Dialog *cfd); static void _free_data(E_Config_Dialog *cfd, E_Config_Dialog_Data *cfdata); static int _basic_apply_data(E_Config_Dialog *cfd, E_Config_Dialog_Data *cfdata); static Evas_Object *_basic_create_widgets(E_Config_Dialog *cfd, Evas *evas, E_Config_Dialog_Data *cfdata); struct _E_Config_Dialog_Data { E_Config_Dialog *cfd; Evas_Object *o_frame; Evas_Object *o_fm; Evas_Object *o_up_button; Evas_Object *o_preview; Evas_Object *o_personal; Evas_Object *o_system; int fmdir; int show_splash; char *splash; }; E_Config_Dialog * e_int_config_startup(E_Container *con, const char *params __UNUSED__) { E_Config_Dialog *cfd; E_Config_Dialog_View *v; if (e_config_dialog_find("E", "appearance/startup")) return NULL; v = E_NEW(E_Config_Dialog_View, 1); v->create_cfdata = _create_data; v->free_cfdata = _free_data; v->basic.apply_cfdata = _basic_apply_data; v->basic.create_widgets = _basic_create_widgets; cfd = e_config_dialog_new(con, _("Startup Settings"), "E", "appearance/startup", "preferences-startup", 0, v, NULL); return cfd; } static void _cb_button_up(void *data1, void *data2 __UNUSED__) { E_Config_Dialog_Data *cfdata; cfdata = data1; if (cfdata->o_fm) e_fm2_parent_go(cfdata->o_fm); if (cfdata->o_frame) e_widget_scrollframe_child_pos_set(cfdata->o_frame, 0, 0); } static void _cb_files_changed(void *data, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { E_Config_Dialog_Data *cfdata; cfdata = data; if (!cfdata->o_fm) return; if (!e_fm2_has_parent_get(cfdata->o_fm)) { if (cfdata->o_up_button) e_widget_disabled_set(cfdata->o_up_button, 1); } else { if (cfdata->o_up_button) e_widget_disabled_set(cfdata->o_up_button, 0); } if (cfdata->o_frame) e_widget_scrollframe_child_pos_set(cfdata->o_frame, 0, 0); } static void _cb_files_selection_change(void *data, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { E_Config_Dialog_Data *cfdata; Eina_List *selected; E_Fm2_Icon_Info *ici; const char *real_path; char buf[4096]; cfdata = data; if (!cfdata->o_fm) return; selected = e_fm2_selected_list_get(cfdata->o_fm); if (!selected) return; ici = selected->data; real_path = e_fm2_real_path_get(cfdata->o_fm); if (!strcmp(real_path, "/")) snprintf(buf, sizeof(buf), "/%s", ici->file); else snprintf(buf, sizeof(buf), "%s/%s", real_path, ici->file); eina_list_free(selected); if (ecore_file_is_dir(buf)) return; E_FREE(cfdata->splash); cfdata->splash = strdup(buf); if (cfdata->o_preview) e_widget_preview_edje_set(cfdata->o_preview, buf, "e/init/splash"); if (cfdata->o_frame) e_widget_change(cfdata->o_frame); } static void _cb_files_files_changed(void *data, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { E_Config_Dialog_Data *cfdata; char buf[4096]; const char *p; size_t len; cfdata = data; if (!cfdata->splash) return; if (!cfdata->o_fm) return; p = e_fm2_real_path_get(cfdata->o_fm); if (p) { if (strncmp(p, cfdata->splash, strlen(p))) return; } len = e_user_dir_concat_static(buf, "themes"); if (!p) return; if (!strncmp(cfdata->splash, buf, len)) p = cfdata->splash + len + 1; else { len = e_prefix_data_concat_static(buf, "data/themes"); if (!strncmp(cfdata->splash, buf, len)) p = cfdata->splash + len + 1; else p = cfdata->splash; } e_fm2_select_set(cfdata->o_fm, p, 1); e_fm2_file_show(cfdata->o_fm, p); } static void _cb_dir(void *data, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { E_Config_Dialog_Data *cfdata; char path[4096]; cfdata = data; if (cfdata->fmdir == 1) { e_prefix_data_concat_static(path, "data/themes"); } else { e_user_dir_concat_static(path, "themes"); } e_fm2_path_set(cfdata->o_fm, path, "/"); } static void _fill_data(E_Config_Dialog_Data *cfdata) { char path[4096]; size_t len; cfdata->show_splash = e_config->show_splash; cfdata->splash = NULL; if (e_config->init_default_theme) cfdata->splash = strdup(e_config->init_default_theme); else { e_prefix_data_concat_static(path, "data/themes/default.edj"); cfdata->splash = strdup(path); } if (cfdata->splash[0] != '/') { e_user_dir_snprintf(path, sizeof(path), "themes/%s", cfdata->splash); if (ecore_file_exists(path)) { E_FREE(cfdata->splash); cfdata->splash = strdup(path); } else { e_prefix_data_snprintf(path, sizeof(path), "data/themes/%s", cfdata->splash); if (ecore_file_exists(path)) { E_FREE(cfdata->splash); cfdata->splash = strdup(path); } } } len = e_prefix_data_concat_static(path, "data/themes"); if (!strncmp(cfdata->splash, path, len)) cfdata->fmdir = 1; } static void * _create_data(E_Config_Dialog *cfd) { E_Config_Dialog_Data *cfdata; cfdata = E_NEW(E_Config_Dialog_Data, 1); _fill_data(cfdata); cfd->cfdata = cfdata; cfdata->cfd = cfd; return cfdata; } static void _free_data(E_Config_Dialog *cfd __UNUSED__, E_Config_Dialog_Data *cfdata) { E_FREE(cfdata->splash); E_FREE(cfdata); } static int _basic_apply_data(E_Config_Dialog *cfd __UNUSED__, E_Config_Dialog_Data *cfdata) { e_config->show_splash = cfdata->show_splash; if (e_config->init_default_theme) eina_stringshare_del(e_config->init_default_theme); e_config->init_default_theme = NULL; if (cfdata->splash) { if (cfdata->splash[0]) { const char *f; f = ecore_file_file_get(cfdata->splash); e_config->init_default_theme = eina_stringshare_add(f); } } e_config_save_queue(); return 1; } static Evas_Object * _basic_create_widgets(E_Config_Dialog *cfd, Evas *evas, E_Config_Dialog_Data *cfdata) { Evas_Object *o, *ot, *of, *il, *ol; char path[4096]; E_Fm2_Config fmc; E_Zone *z; E_Radio_Group *rg; z = e_zone_current_get(cfd->con); ot = e_widget_table_add(evas, 0); ol = e_widget_table_add(evas, 0); il = e_widget_table_add(evas, 1); rg = e_widget_radio_group_new(&(cfdata->fmdir)); o = e_widget_radio_add(evas, _("Personal"), 0, rg); cfdata->o_personal = o; evas_object_smart_callback_add(o, "changed", _cb_dir, cfdata); e_widget_table_object_append(il, o, 0, 0, 1, 1, 1, 1, 0, 0); o = e_widget_radio_add(evas, _("System"), 1, rg); cfdata->o_system = o; evas_object_smart_callback_add(o, "changed", _cb_dir, cfdata); e_widget_table_object_append(il, o, 1, 0, 1, 1, 1, 1, 0, 0); e_widget_table_object_append(ol, il, 0, 0, 1, 1, 0, 0, 0, 0); o = e_widget_button_add(evas, _("Go up a Directory"), "go-up", _cb_button_up, cfdata, NULL); cfdata->o_up_button = o; e_widget_table_object_append(ol, o, 0, 1, 1, 1, 0, 0, 0, 0); if (cfdata->fmdir == 1) e_prefix_data_concat_static(path, "data/themes"); else e_user_dir_concat_static(path, "themes"); o = e_fm2_add(evas); cfdata->o_fm = o; memset(&fmc, 0, sizeof(E_Fm2_Config)); fmc.view.mode = E_FM2_VIEW_MODE_LIST; fmc.view.open_dirs_in_place = 1; fmc.view.selector = 1; fmc.view.single_click = 0; fmc.view.no_subdir_jump = 0; fmc.icon.list.w = 48; fmc.icon.list.h = 48; fmc.icon.fixed.w = 1; fmc.icon.fixed.h = 1; fmc.icon.extension.show = 0; fmc.icon.key_hint = "e/init/splash"; fmc.list.sort.no_case = 1; fmc.list.sort.dirs.first = 0; fmc.list.sort.dirs.last = 1; fmc.selection.single = 1; fmc.selection.windows_modifiers = 0; e_fm2_config_set(o, &fmc); e_fm2_icon_menu_flags_set(o, E_FM2_MENU_NO_SHOW_HIDDEN); evas_object_smart_callback_add(o, "dir_changed", _cb_files_changed, cfdata); evas_object_smart_callback_add(o, "selection_change", _cb_files_selection_change, cfdata); evas_object_smart_callback_add(o, "changed", _cb_files_files_changed, cfdata); e_fm2_path_set(o, path, "/"); of = e_widget_scrollframe_pan_add(evas, o, e_fm2_pan_set, e_fm2_pan_get, e_fm2_pan_max_get, e_fm2_pan_child_size_get); cfdata->o_frame = of; e_widget_size_min_set(of, 160, 160); e_widget_table_object_append(ol, of, 0, 2, 1, 1, 1, 1, 1, 1); e_widget_table_object_append(ot, ol, 0, 0, 1, 1, 1, 1, 1, 1); of = e_widget_list_add(evas, 0, 0); o = e_widget_check_add(evas, _("Show Splash Screen on Login"), &(cfdata->show_splash)); e_widget_list_object_append(of, o, 1, 0, 0.0); o = e_widget_preview_add(evas, 320, (320 * z->h) / z->w); cfdata->o_preview = o; if (cfdata->splash) e_widget_preview_edje_set(o, cfdata->splash, "e/init/splash"); e_widget_list_object_append(of, o, 0, 0, 0.5); e_widget_table_object_append(ot, of, 1, 0, 1, 1, 0, 0, 0, 0); return ot; }
jordemort/e17
src/modules/conf_theme/e_int_config_startup.c
C
bsd-2-clause
9,644
package org.fxmisc.richtext.model; import static org.fxmisc.richtext.model.TwoDimensional.Bias.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.reactfx.EventSource; import org.reactfx.EventStream; import org.reactfx.Subscription; import org.reactfx.SuspendableNo; import org.reactfx.collection.LiveList; import org.reactfx.collection.LiveListBase; import org.reactfx.collection.MaterializedListModification; import org.reactfx.collection.QuasiListModification; import org.reactfx.collection.UnmodifiableByDefaultLiveList; import org.reactfx.util.BiIndex; import org.reactfx.util.Lists; import org.reactfx.value.Val; /** * Provides an implementation of {@link EditableStyledDocument} */ class GenericEditableStyledDocumentBase<PS, SEG, S> implements EditableStyledDocument<PS, SEG, S> { private class ParagraphList extends LiveListBase<Paragraph<PS, SEG, S>> implements UnmodifiableByDefaultLiveList<Paragraph<PS, SEG, S>> { @Override public Paragraph<PS, SEG, S> get(int index) { return doc.getParagraph(index); } @Override public int size() { return doc.getParagraphCount(); } @Override protected Subscription observeInputs() { return parChanges.subscribe(mod -> { mod = mod.trim(); QuasiListModification<Paragraph<PS, SEG, S>> qmod = QuasiListModification.create(mod.getFrom(), mod.getRemoved(), mod.getAddedSize()); notifyObservers(qmod.asListChange()); }); } } private ReadOnlyStyledDocument<PS, SEG, S> doc; private final EventSource<RichTextChange<PS, SEG, S>> richChanges = new EventSource<>(); @Override public EventStream<RichTextChange<PS, SEG, S>> richChanges() { return richChanges; } private final Val<String> text = Val.create(() -> doc.getText(), richChanges); @Override public String getText() { return text.getValue(); } @Override public Val<String> textProperty() { return text; } private final Val<Integer> length = Val.create(() -> doc.length(), richChanges); @Override public int getLength() { return length.getValue(); } @Override public Val<Integer> lengthProperty() { return length; } @Override public int length() { return length.getValue(); } private final EventSource<MaterializedListModification<Paragraph<PS, SEG, S>>> parChanges = new EventSource<>(); private final LiveList<Paragraph<PS, SEG, S>> paragraphs = new ParagraphList(); @Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return paragraphs; } @Override public ReadOnlyStyledDocument<PS, SEG, S> snapshot() { return doc; } private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; } @Override public final boolean isBeingUpdated() { return beingUpdated.get(); } GenericEditableStyledDocumentBase(Paragraph<PS, SEG, S> initialParagraph/*, SegmentOps<SEG, S> segmentOps*/) { this.doc = new ReadOnlyStyledDocument<>(Collections.singletonList(initialParagraph)); } /** * Creates an empty {@link EditableStyledDocument} */ public GenericEditableStyledDocumentBase(PS initialParagraphStyle, S initialStyle, TextOps<SEG, S> segmentOps) { this(new Paragraph<>(initialParagraphStyle, segmentOps, segmentOps.create("", initialStyle))); } @Override public Position position(int major, int minor) { return doc.position(major, minor); } @Override public Position offsetToPosition(int offset, Bias bias) { return doc.offsetToPosition(offset, bias); } @Override public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) { ensureValidRange(start, end); doc.replace(start, end, ReadOnlyStyledDocument.from(replacement)).exec(this::update); } @Override public void setStyle(int from, int to, S style) { ensureValidRange(from, to); doc.replace(from, to, removed -> removed.mapParagraphs(par -> par.restyle(style))).exec(this::update); } @Override public void setStyle(int paragraph, S style) { ensureValidParagraphIndex(paragraph); doc.replaceParagraph(paragraph, p -> p.restyle(style)).exec(this::update); } @Override public void setStyle(int paragraph, int fromCol, int toCol, S style) { ensureValidParagraphRange(paragraph, fromCol, toCol); doc.replace( new BiIndex(paragraph, fromCol), new BiIndex(paragraph, toCol), d -> d.mapParagraphs(p -> p.restyle(style)) ).exec(this::update); } @Override public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { int len = styleSpans.length(); ensureValidRange(from, from + len); doc.replace(from, from + len, d -> { Position i = styleSpans.position(0, 0); List<Paragraph<PS, SEG, S>> pars = new ArrayList<>(d.getParagraphs().size()); for(Paragraph<PS, SEG, S> p: d.getParagraphs()) { Position j = i.offsetBy(p.length(), Backward); StyleSpans<? extends S> spans = styleSpans.subView(i, j); pars.add(p.restyle(0, spans)); i = j.offsetBy(1, Forward); // skip the newline } return new ReadOnlyStyledDocument<>(pars); }).exec(this::update); } @Override public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { setStyleSpans(doc.position(paragraph, from).toOffset(), styleSpans); } @Override public void setParagraphStyle(int parIdx, PS style) { ensureValidParagraphIndex(parIdx); doc.replaceParagraph(parIdx, p -> p.setParagraphStyle(style)).exec(this::update); } @Override public StyledDocument<PS, SEG, S> concat(StyledDocument<PS, SEG, S> that) { return doc.concat(that); } @Override public StyledDocument<PS, SEG, S> subSequence(int start, int end) { return doc.subSequence(start, end); } /* ********************************************************************** * * * * Private and package private methods * * * * ********************************************************************** */ private void ensureValidParagraphIndex(int parIdx) { Lists.checkIndex(parIdx, doc.getParagraphCount()); } private void ensureValidRange(int start, int end) { Lists.checkRange(start, end, length()); } private void ensureValidParagraphRange(int par, int start, int end) { ensureValidParagraphIndex(par); Lists.checkRange(start, end, fullLength(par)); } private int fullLength(int par) { int n = doc.getParagraphCount(); return doc.getParagraph(par).length() + (par == n-1 ? 0 : 1); } private void update( ReadOnlyStyledDocument<PS, SEG, S> newValue, RichTextChange<PS, SEG, S> change, MaterializedListModification<Paragraph<PS, SEG, S>> parChange) { this.doc = newValue; beingUpdated.suspendWhile(() -> { richChanges.push(change); parChanges.push(parChange); }); } }
cemartins/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/model/GenericEditableStyledDocumentBase.java
Java
bsd-2-clause
7,622
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020-2021 Inviwo Foundation * 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. * * 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. * *********************************************************************************/ #include <modules/glfw/glfwuserdata.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> namespace inviwo { GLFWUserData::GLFWUserData(GLFWwindow* win) { glfwSetWindowUserPointer(win, this); } GLFWUserData* GLFWUserData::self(GLFWwindow* win) { return static_cast<GLFWUserData*>(glfwGetWindowUserPointer(win)); } } // namespace inviwo
inviwo/inviwo
modules/glfw/src/glfwuserdata.cpp
C++
bsd-2-clause
1,930
<?php require_once('BaseController.class.php'); require_once('plugins/LdapAuthAdapter.php'); require_once('plugins/OrgAuthAdapter.php'); // 認証画面 class AuthController extends BaseController { public function init() { // ここにコントローラの初期化処理を記述する } // 認証フォーム public function indexAction() { } // 外部ログイン画面 public function loginAction() { } public function createLog($user, $message) { $message = '[' . $_SERVER["REMOTE_ADDR"] . '][' . $user . '] : ' . $message; BaseController::loginLogWrite($message); } // ロールが未設定(空)の場合 public function errorAction() { $info = Zend_Auth::getInstance()->getIdentity(); Zend_Auth::getInstance()->clearIdentity(); // 認証情報破棄 $errorMessage = 'このIDでのログインは許可されていません'; if(empty($info->type) || $info->type === 'ldap') { $this->createLog((!empty($info->id) ? $info->id : ''), 'LDAP login error : No Rolls'); $this->view->assign('error', $errorMessage); $this->_forward('index', 'auth'); } else { $this->createLog((!empty($info->id) ? $info->id : ''), 'Authentication error : No Rolls'); $this->view->assign('error', $errorMessage); $this->_forward('login', 'auth'); } } // 認証プロセス public function processAction() { Zend_Auth::getInstance()->clearIdentity(); // 認証情報破棄 $err = $this->getRequest()->error; $errorMessage = 'IDもしくはパスワードに誤りがあります'; // Zend_Authオブジェクトのインスタンス取得 $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { // 認証済み(プラグイン(plugins/AuthPlugin)でチェック済みなので auth/process が直接呼び出された場合のみ) $this->_redirect('/'); } else { // 未認証 // フォームからのリクエスト取得 $req = $this->getRequest(); $account = $req->getPost('account'); $password = $req->getPost('password'); // LDAP認証を行う // if (APPLICATION_TYPE == '0') if (APPLICATION_TYPE == 'kwl') { // LDAP認証追加 ここから $adapter = new LdapAuthAdapter($account, $password); $options = array ( 'server1' => array( 'host' => 'xxxx.xxxxx.xx.jp', 'port' => xxx, 'baseDn' => 'dc=xxxxxxxx,dc=xx,dc=xx', 'username' => 'cn=xxxxx,ou=xxxxx,dc=xxxx,dc=xx,dc=jp', 'password' => 'xxxxxxxx', 'bindRequiresDn' => true ) ); $adapter1 = new Zend_Auth_Adapter_Ldap($options,$account,$password); // 認証 $result = $auth->authenticate($adapter1); // LDAP認証追加 ここまで if ($result->isValid()) { $adapter->authenticate(); $stdObj = $adapter->getMemberInfo(); $auth->getStorage()->write($stdObj); // ユーザ情報をセッションへ保存 // セッションに保存済みのリクエストを取得 $sess = new Zend_Session_Namespace('cScQlPsMuqoKayhj'); $action = $sess->currentAction; $controller = $sess->currentController; $module = $sess->currentModule; // 保存済みのURLを取得し、リダイレクトする $url = $sess->currentURL; // 保存済みリクエスト削除 $sess->currentAction = NULL; $sess->currentController = NULL; $sess->currentModule = NULL; $this->createLog($account, 'LDAP login succeeded'); if($action === 'index') { // 権限を判断してリダイレクト $this->redirectRoles($stdObj->roles); } else { // 元のリクエスト先にリダイレクト $this->_redirect($url); } } else { $this->createLog($account, 'LDAP login failed : Incorrect ID or Password'); $this->view->assign('error', $errorMessage); $this->_forward('index', 'auth'); } return; } // 認証 if (empty($account) || empty($password)) { $this->view->assign('error', $errorMessage); $this->_forward('index', 'auth'); } else { $adapter = new OrgAuthAdapter($account, $password); //$result = $auth->authenticate($a_db); $result = $adapter->authenticate(); if ($result->isValid()) { // 成功 // パスワード以外のユーザ情報をセッションへ保存 $stdObj = $adapter->getMemberInfo(); $auth->getStorage()->write($stdObj); // ユーザ情報をセッションへ保存 // セッションに保存済みのリクエストを取得 $sess = new Zend_Session_Namespace('cScQlPsMuqoKayhj'); $action = $sess->currentAction; $controller = $sess->currentController; $module = $sess->currentModule; // 保存済みのURLを取得し、リダイレクトする $url = $sess->currentURL; // 保存済みリクエスト削除 $sess->currentAction = NULL; $sess->currentController = NULL; $sess->currentModule = NULL; $sess->currentURL = NULL; if($action === 'index') { // 権限を判断してリダイレクト $this->redirectRoles($stdObj->roles); } else { // 元のリクエスト先にリダイレクト $this->_redirect($url); } } else { // 失敗 $this->view->assign('error', $errorMessage); $this->_forward('index', 'auth'); } } } } public function orgprocessAction() { Zend_Auth::getInstance()->clearIdentity(); // 認証情報破棄 $errorMessage = 'IDもしくはパスワードに誤りがあります'; // Zend_Authオブジェクトのインスタンス取得 $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { // 認証済み(プラグイン(plugins/AuthPlugin)でチェック済みなので auth/process が直接呼び出された場合のみ) $this->_redirect('/'); } else { // 未認証 // フォームからのリクエスト取得 $req = $this->getRequest(); $account = $req->getPost('account'); $password = $req->getPost('password'); // 認証 if (empty($account) || empty($password)) { $this->createLog((!empty($account) ? $account : ''), 'Authentication failed : Incorrect ID or Password'); $this->view->assign('error', $errorMessage); $this->_forward('login', 'auth'); } else { $adapter = new OrgAuthAdapter($account, $password); //$result = $auth->authenticate($a_db); $result = $adapter->authenticate(); if ($result->isValid()) { // 成功 // パスワード以外のユーザ情報をセッションへ保存 $stdObj = $adapter->getMemberInfo(); $auth->getStorage()->write($stdObj); // ユーザ情報をセッションへ保存 // セッションに保存済みのリクエストを取得 $sess = new Zend_Session_Namespace('cScQlPsMuqoKayhj'); $action = $sess->currentAction; $controller = $sess->currentController; $module = $sess->currentModule; // 保存済みのURLを取得し、リダイレクトする $url = $sess->currentURL; // 保存済みリクエスト削除 $sess->currentAction = NULL; $sess->currentController = NULL; $sess->currentModule = NULL; $sess->currentURL = NULL; $this->createLog($account, 'Authentication succeeded'); if($action === 'index' || $action !== 'error') { // 権限を判断してリダイレクト $this->redirectRoles($stdObj->roles); } else { // 元のリクエスト先にリダイレクト $this->_redirect($url); } } else { // 失敗 $this->createLog($account, 'Authentication failed : Incorrect ID or Password'); $this->view->assign('error', $errorMessage); $this->_forward('login', 'auth'); } } } } // ログアウト public function logoutAction() { // ログアウト後のリダイレクト先を分岐する $type = Zend_Auth::getInstance()->getIdentity()->type; Zend_Auth::getInstance()->clearIdentity(); // 認証情報破棄 Zend_Session::destroy(); // セッション情報削除 if($type === 'org') $this->_redirect('auth/login'); else $this->_redirect('/'); // トップページへリダイレクト(結果、ログイン画面へ戻る) } // 権限を判断してリダイレクト(2014/04/18 S.Satake) public function redirectRoles($roles) { $role = explode(',', $roles); if (count($role) > 1) { // 複数のロール $this->_redirect('seltop/index'); } else { // 単一ロール if (strstr($roles, 'Student')) $this->_redirect('labo/index'); elseif (strstr($roles, 'Staff')) $this->_redirect('staff/index'); elseif (strstr($roles, 'Administrator')) $this->_redirect('admin/index'); elseif (strstr($roles, 'Professor')) $this->_redirect('tecfolio/professor/file'); else { $this->_redirect('auth/error'); } } } }
tec-admin/tecsystem
tecfolio/application/controllers/AuthController.php
PHP
bsd-2-clause
9,053
UserSettings = new Mongo.Collection( 'user-settings' ); UserSettings.allow({ insert: function () { return true }, update: function () { // TODO move this server side. Only allow the owner to edit return true } });
MantarayAR/pingr-io
src/both/collections/user-settings.js
JavaScript
bsd-2-clause
234
class Antibody < Formula desc "The fastest shell plugin manager" homepage "https://getantibody.github.io/" url "https://github.com/getantibody/antibody/archive/v6.1.0.tar.gz" sha256 "b2cf67af801ebf10c0d52b1767cbdb5e3ab5a1713e6c3d28616a109e1d7906a7" license "MIT" bottle do cellar :any_skip_relocation sha256 "34220ece903751e682659e9f76f069ec28cd6369373d0391d4298805a6f64a3b" => :catalina sha256 "3044c7a8f003006ef6f0b05ba590c4b41f578e377c02e5e9cb36ff7e18bad269" => :mojave sha256 "a0fc8f0db6b35280d073f046d83d00142e0104d5e7857ff04acdbcbe25eeeb40" => :high_sierra end depends_on "go" => :build def install system "go", "build", "-ldflags", "-s -w -X main.version=#{version}", "-trimpath", "-o", bin/"antibody" end test do # See if antibody can install a bundle correctly system "#{bin}/antibody", "bundle", "rupa/z" assert_match("rupa/z", shell_output("#{bin}/antibody list")) end end
lembacon/homebrew-core
Formula/antibody.rb
Ruby
bsd-2-clause
944
=begin #MINDBODY Public API #No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.6 =end require 'spec_helper' require 'json' require 'date' # Unit tests for SwaggerClient::ContactLogType # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'ContactLogType' do before do # run before each test @instance = SwaggerClient::ContactLogType.new end after do # run after each test end describe 'test an instance of ContactLogType' do it 'should create an instance of ContactLogType' do expect(@instance).to be_instance_of(SwaggerClient::ContactLogType) end end describe 'test attribute "id"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "sub_types"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
mindbody/API-Examples
SDKs/Ruby/spec/models/contact_log_type_spec.rb
Ruby
bsd-2-clause
1,217
// Generated by gtkmmproc -- DO NOT MODIFY! #include <glibmm.h> #include <pangomm/fontmetrics.h> #include <pangomm/private/fontmetrics_p.h> // -*- c++ -*- /* $Id: fontmetrics.ccg,v 1.1 2003/01/21 13:41:04 murrayc Exp $ */ /* * * Copyright 1998-1999 The Gtk-- Development Team * Copyright 2001 Free Software Foundation * * This library 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 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ namespace { } // anonymous namespace namespace Glib { Pango::FontMetrics wrap(PangoFontMetrics* object, bool take_copy) { return Pango::FontMetrics(object, take_copy); } } // namespace Glib namespace Pango { // static GType FontMetrics::get_type() { return pango_font_metrics_get_type(); } FontMetrics::FontMetrics() : gobject_ (0) // Allows creation of invalid wrapper, e.g. for output arguments to methods. {} FontMetrics::FontMetrics(const FontMetrics& other) : gobject_ ((other.gobject_) ? pango_font_metrics_ref(other.gobject_) : 0) {} FontMetrics::FontMetrics(PangoFontMetrics* gobject, bool make_a_copy) : // For BoxedType wrappers, make_a_copy is true by default. The static // BoxedType wrappers must always take a copy, thus make_a_copy = true // ensures identical behaviour if the default argument is used. gobject_ ((make_a_copy && gobject) ? pango_font_metrics_ref(gobject) : gobject) {} FontMetrics& FontMetrics::operator=(const FontMetrics& other) { FontMetrics temp (other); swap(temp); return *this; } FontMetrics::~FontMetrics() { if(gobject_) pango_font_metrics_unref(gobject_); } void FontMetrics::swap(FontMetrics& other) { PangoFontMetrics *const temp = gobject_; gobject_ = other.gobject_; other.gobject_ = temp; } PangoFontMetrics* FontMetrics::gobj_copy() const { return pango_font_metrics_ref(gobject_); } int FontMetrics::get_ascent() const { return pango_font_metrics_get_ascent(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_descent() const { return pango_font_metrics_get_descent(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_approximate_char_width() const { return pango_font_metrics_get_approximate_char_width(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_approximate_digit_width() const { return pango_font_metrics_get_approximate_digit_width(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_underline_position() const { return pango_font_metrics_get_underline_position(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_underline_thickness() const { return pango_font_metrics_get_underline_thickness(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_strikethrough_position() const { return pango_font_metrics_get_strikethrough_position(const_cast<PangoFontMetrics*>(gobj())); } int FontMetrics::get_strikethrough_thickness() const { return pango_font_metrics_get_strikethrough_thickness(const_cast<PangoFontMetrics*>(gobj())); } } // namespace Pango
yleydier/gtkmm2_msvc14
pangomm/pango/pangomm/fontmetrics.cc
C++
bsd-2-clause
3,614
# The set of languages for which implicit dependencies are needed: SET(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: SET(CMAKE_DEPENDS_CHECK_CXX "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/color.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/color.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/filter.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/filter.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/gradient.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/gradient.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/image.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/image.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/morph.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/morph.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/nms.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/nms.cpp.o" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/lib/imgproc/resample.cpp" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/resample.cpp.o" ) SET(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. SET(CMAKE_TARGET_DEFINITIONS "LBFGS_FLOAT=32" ) # Targets to which this target links. SET(CMAKE_TARGET_LINKED_INFO_FILES "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/lib/util/CMakeFiles/util.dir/DependInfo.cmake" "/home/zimo/Documents/dense_functional_map_matching/external/gop_1.3/build/external/liblbfgs-1.10/CMakeFiles/lbfgs.dir/DependInfo.cmake" ) # The include file search paths: SET(CMAKE_C_TARGET_INCLUDE_PATH "../external/eigen" "../external" "../external/CImg" "../external/rapidxml-1.13" "../external/libsvm-3.17" "../external/liblbfgs-1.10/include" "../external/maxflow-v3.03.src" "../external/ibfs" "../external/quadprog" "../lib" "/usr/local/include" ) SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH}) SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH}) SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
LiZimo/FuncFlow
external/gop_1.3/build/lib/imgproc/CMakeFiles/imgproc.dir/DependInfo.cmake
CMake
bsd-2-clause
2,743
var Jsonix = require('../jsonix').Jsonix; module.exports = { "Type": function(test) { test.equal(true, Jsonix.Util.Type.isString('abc')); test.equal(false, Jsonix.Util.Type.isString(1)); test.equal(false, Jsonix.Util.Type.isString(null)); test.equal(false, Jsonix.Util.Type.isString(undefined)); // test.equal(true, Jsonix.Util.Type.isBoolean(true)); test.equal(true, Jsonix.Util.Type.isBoolean(true)); test.equal(false, Jsonix.Util.Type.isBoolean('true')); // test.equal(true, Jsonix.Util.Type.isNumber(0)); test.equal(true, Jsonix.Util.Type.isNumber(1.2)); test.equal(false, Jsonix.Util.Type.isNumber(Number('1..2'))); test.equal(false, Jsonix.Util.Type.isNumber('1.2')); test.equal(true, Jsonix.Util.Type.isArray([])); test.equal(true, Jsonix.Util.Type.isArray([0])); test.equal(false, Jsonix.Util.Type.isArray(0)); test.equal(true, Jsonix.Util.Type.isNumberOrNaN(Number.NaN)); test.equal(true, Jsonix.Util.Type.isNaN(Number.NaN)); test.equal(false, Jsonix.Util.Type.isNumber(Number.NaN)); test.equal("undefined", typeof Jsonix.Util.Type.defaultValue()); test.equal(1, Jsonix.Util.Type.defaultValue(1)); test.equal(1, Jsonix.Util.Type.defaultValue(1, undefined, 2)); test.equal(2, Jsonix.Util.Type.defaultValue(undefined, 2, 3)); test.equal(3, Jsonix.Util.Type.defaultValue("1", {t:2}, 3)); test.equal(false, Jsonix.Util.Type.defaultValue(false, undefined, true)); test.equal(false, Jsonix.Util.Type.defaultValue("true", false, true)); test.equal(false, Jsonix.Util.Type.defaultValue("true", null, false)); test.done(); }, "StringUtils" : function(test) { test.equal('a b c', Jsonix.Util.StringUtils.trim(' a b c ')); test.equal(true, Jsonix.Util.StringUtils.isEmpty(' ')); test.done(); } };
wmakeev/jsonix
nodejs/scripts/tests/util.js
JavaScript
bsd-2-clause
1,785
/* * Copyright 2014 Nutiteq Llc. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://www.nutiteq.com/license/ */ #ifndef _NUTI_TORQUETILEDECODER_H_ #define _NUTI_TORQUETILEDECODER_H_ #include "VectorTileDecoder.h" #include "MapnikVT/Value.h" #include <memory> #include <mutex> #include <map> #include <string> #include <cglib/mat.h> namespace Nuti { namespace MapnikVT { class TorqueMap; class SymbolizerContext; } class CartoCSSStyleSet; /** * A decoder for Torque layer that accepts json-based Torque tiles. */ class TorqueTileDecoder : public VectorTileDecoder { public: /** * Constructs a new TorqueTileDecoder given style. * @param styleSet The style set used by decoder. */ TorqueTileDecoder(const std::shared_ptr<CartoCSSStyleSet>& styleSet); virtual ~TorqueTileDecoder(); /** * Returns the frame count defined in the Torque style. * @return The frame count in the animation. */ int getFrameCount() const; /** * Returns the current style set used by the decoder. * @return The current style set. */ const std::shared_ptr<CartoCSSStyleSet>& getStyleSet() const; /** * Sets the current style set used by the decoder. * @param styleSet The new style set to use. */ void setStyleSet(const std::shared_ptr<CartoCSSStyleSet>& styleSet); /** * Returns the tile resolution, in pixels. Default is 256. * @return The tile resolution in pixels. */ int getResolution() const; /** * Sets the tile resolution in pixels. Default is 256. * @param resolution The new resolution value. */ void setResolution(int resolution); virtual Color getBackgroundColor() const; virtual std::shared_ptr<const VT::BitmapPattern> getBackgroundPattern() const; virtual int getMinZoom() const; virtual int getMaxZoom() const; virtual std::shared_ptr<TileMap> decodeTile(const VT::TileId& tile, const VT::TileId& targetTile, const std::shared_ptr<TileData>& data) const; protected: static const int DEFAULT_TILE_SIZE; static const int GLYPHMAP_SIZE; int _resolution; std::shared_ptr<MapnikVT::TorqueMap> _map; std::shared_ptr<MapnikVT::SymbolizerContext> _symbolizerContext; std::shared_ptr<CartoCSSStyleSet> _styleSet; mutable std::mutex _mutex; }; } #endif
nutiteq/hellomap3d-ios
hellomap3/Nuti.framework/Versions/A/Headers/vectortiles/TorqueTileDecoder.h
C
bsd-2-clause
2,640
from __future__ import unicode_literals class MorfessorException(Exception): """Base class for exceptions in this module.""" pass class ArgumentException(Exception): """Exception in command line argument parsing.""" pass class InvalidCategoryError(MorfessorException): """Attempt to load data using a different categorization scheme.""" def __init__(self, category): super(InvalidCategoryError, self).__init__( self, 'This model does not recognize the category {}'.format( category)) class InvalidOperationError(MorfessorException): def __init__(self, operation, function_name): super(InvalidOperationError, self).__init__( self, ('This model does not have a method {}, and therefore cannot' ' perform operation "{}"').format(function_name, operation)) class UnsupportedConfigurationError(MorfessorException): def __init__(self, reason): super(UnsupportedConfigurationError, self).__init__( self, ('This operation is not supported in this program ' + 'configuration. Reason: {}.').format(reason))
aalto-speech/flatcat
flatcat/exception.py
Python
bsd-2-clause
1,153
// Copyright 2015, David Howden // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "tchaik.com/index" "tchaik.com/index/checklist" "tchaik.com/index/cursor" "tchaik.com/index/favourite" "tchaik.com/index/history" "tchaik.com/index/playlist" ) // Meta is a container for extra metadata which wraps the central media library. // TODO: Refactor meta to be user-specific. type Meta struct { history history.Store favourites favourite.Store checklist checklist.Store playlists playlist.Store cursors cursor.Store } func loadLocalMeta() (*Meta, error) { fmt.Printf("Loading play history...") playHistoryStore, err := history.NewStore(playHistoryPath) if err != nil { return nil, fmt.Errorf("error loading play history: %v", err) } fmt.Println("done.") fmt.Printf("Loading favourites...") favouriteStore, err := favourite.NewStore(favouritesPath) if err != nil { return nil, fmt.Errorf("\nerror loading favourites: %v", err) } fmt.Println("done.") fmt.Printf("Loading checklist...") checklistStore, err := checklist.NewStore(checklistPath) if err != nil { return nil, fmt.Errorf("\nerror loading checklist: %v", err) } fmt.Println("done.") fmt.Printf("Loading playlists...") playlistStore, err := playlist.NewStore(playlistPath) if err != nil { return nil, fmt.Errorf("\nerror loading playlists: %v", err) } // TODO(dhowden): remove this once we can better intialise the "Default" playlist if p := playlistStore.Get("Default"); p == nil { playlistStore.Set("Default", &playlist.Playlist{}) } fmt.Println("done") fmt.Printf("Loading cursors...") cursorStore, err := cursor.NewStore(cursorPath) if err != nil { return nil, fmt.Errorf("\nerror loading cursor: %v", err) } fmt.Println("done") return &Meta{ history: playHistoryStore, favourites: favouriteStore, checklist: checklistStore, playlists: playlistStore, cursors: cursorStore, }, nil } type metaFieldGrp struct { index.Group field string value interface{} } func (mfg metaFieldGrp) Field(f string) interface{} { if f == mfg.field { return mfg.value } return mfg.Group.Field(f) } type metaFieldCol struct { index.Collection field string value interface{} } func (mfc metaFieldCol) Field(f string) interface{} { if f == mfc.field { return mfc.value } return mfc.Collection.Field(f) } func newMetaField(g index.Group, field string, value bool) index.Group { if !value { return g } if c, ok := g.(index.Collection); ok { // TODO(dhowden): currently need to maintain the underlying interface type // so that it can be correctly transmitted, need a better way of doing this. return metaFieldCol{ Collection: c, field: field, value: value, } } return metaFieldGrp{ Group: g, field: field, value: value, } } // Annotate adds any meta information to the Group (identified by Path). func (m *Meta) Annotate(p index.Path, g index.Group) index.Group { g = newMetaField(g, "Favourite", m.favourites.Get(p)) return newMetaField(g, "Checklist", m.checklist.Get(p)) }
tchaik/tchaik
cmd/tchaik/meta.go
GO
bsd-2-clause
3,139
{-# LANGUAGE TypeFamilies, OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Xournal.Map -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- module Data.Xournal.Map where import Data.IntMap import Data.Xournal.Simple import Data.Xournal.Generic import Data.Xournal.BBox type TPageMap = GPage Background IntMap TLayerSimple type TXournalMap = GXournal [] TPageMap type TPageBBoxMap = GPage Background IntMap TLayerBBox type TXournalBBoxMap = GXournal IntMap TPageBBoxMap type TPageBBoxMapBkg b = GPage b IntMap TLayerBBox type TXournalBBoxMapBkg b = GXournal IntMap (TPageBBoxMapBkg b) emptyGXournalMap :: GXournal IntMap a emptyGXournalMap = GXournal "" empty
wavewave/xournal-types
src/Data/Xournal/Map.hs
Haskell
bsd-2-clause
875
/* Generated By:JJTree: Do not edit this line. ASTId.java */ public class ASTId extends SimpleNode { public ASTId(int id) { super(id); } public ASTId(SPLParser p, int id) { super(p, id); } }
aijunbai/skipoominijool
doc/javacc/javacc-examples/Interpreter/ASTId.java
Java
bsd-2-clause
210
#!/bin/sh . tests/shlib/common.sh . tests/shlib/vterm.sh enter_suite tmux vterm_setup ln -s "$(which env)" "$TEST_ROOT/path" ln -s "$(which cut)" "$TEST_ROOT/path" ln -s "$ROOT/scripts/powerline-render" "$TEST_ROOT/path" ln -s "$ROOT/scripts/powerline-config" "$TEST_ROOT/path" test_tmux() { if test "$PYTHON_IMPLEMENTATION" = PyPy; then # FIXME PyPy3 segfaults for some reason, PyPy does it as well, but # occasionally. return 0 fi if ! which "${POWERLINE_TMUX_EXE}" ; then return 0 fi ln -sf "$(which "${POWERLINE_TMUX_EXE}")" "$TEST_ROOT/path/tmux" f="$ROOT/tests/test_in_vterm/test_tmux.py" if ! "${PYTHON}" "$f" ; then local test_name="$("$POWERLINE_TMUX_EXE" -V 2>&1 | cut -d' ' -f2)" fail "$test_name" F "Failed vterm test $f" fi } if test -z "$POWERLINE_TMUX_EXE" && test -d "$ROOT/tests/bot-ci/deps/tmux" then for tmux in "$ROOT"/tests/bot-ci/deps/tmux/tmux-*/tmux ; do export POWERLINE_TMUX_EXE="$tmux" test_tmux || true done else export POWERLINE_TMUX_EXE="${POWERLINE_TMUX_EXE:-tmux}" test_tmux || true fi vterm_shutdown exit_suite
codeprimate/arid
powerline/tests/test_in_vterm/test_tmux.sh
Shell
bsd-2-clause
1,080
# -*- 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): # Changing field 'Feed.title' db.alter_column('feedmanager_feed', 'title', self.gf('django.db.models.fields.TextField')()) def backwards(self, orm): # Changing field 'Feed.title' db.alter_column('feedmanager_feed', 'title', self.gf('django.db.models.fields.CharField')(max_length=70)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, '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': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, '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': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), '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': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, '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'}), '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'}) }, 'feedmanager.feed': { 'Meta': {'object_name': 'Feed'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'hash': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_checked': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.TextField', [], {}), 'url': ('django.db.models.fields.TextField', [], {}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'symmetrical': 'False'}) }, 'feedmanager.item': { 'Meta': {'object_name': 'Item'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['feedmanager.Feed']"}), 'guid': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'link': ('django.db.models.fields.TextField', [], {}), 'pubdate': ('django.db.models.fields.DateTimeField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '70'}) } } complete_apps = ['feedmanager']
jacobjbollinger/sorbet
sorbet/feedmanager/migrations/0006_chg_field_feed_title.py
Python
bsd-2-clause
5,274
# General utility functions can go here. import os import random import string from django.utils import functional from django.utils.http import urlencode def rand_string(numOfChars): """ Generates a string of lowercase letters and numbers. That makes 36^10 = 3 x 10^15 possibilities. If we generate filenames randomly, it's harder for people to guess filenames and type in their URLs directly to bypass permissions. """ return ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(numOfChars)) def generate_random_filename(directory, originalFilename, numOfChars): """ Generate a random filename for a file upload. The filename will have numOfChars random characters. Also prepends the directory argument to get a filepath which is only missing the MEDIA_ROOT part at the beginning. The return value can be used as an upload_to argument for a FileField ImageField, ThumbnailerImageField, etc. An upload_to argument is automatically prepended with MEDIA_ROOT to get the upload filepath. """ # TODO: Use the directory argument to check for filename collisions with existing files. # To unit test this, use a Mocker or similar on the filename randomizer # to make filename collisions far more likely. extension = os.path.splitext(originalFilename)[1] filenameBase = rand_string(numOfChars) return os.path.join(directory, filenameBase + extension) def url_with_querystring(path, **kwargs): """ Takes a base URL (path) and GET query arguments (kwargs). Returns the complete GET URL. NOTE: Any kwargs with special characters like '/' and ' ' will be escaped with %2f, %20, etc. Source: http://stackoverflow.com/a/5341769/859858 """ return path + '?' + urlencode(kwargs) def is_django_str(s): """ Checks that the argument is either: (a) an instance of basestring, or (b) a Django lazy-translation string. :param s: Object to check the type of. :return: True if s is a Django string, False otherwise. """ if isinstance(s, basestring): return True elif isinstance(s, functional.Promise): return True else: return False
DevangS/CoralNet
utils.py
Python
bsd-2-clause
2,240
class AddArchivedToCodes < ActiveRecord::Migration def change add_column :codes, :archived, :boolean end end
joequant/scms
NScrypt/db/migrate/20150509101930_add_archived_to_codes.rb
Ruby
bsd-2-clause
117
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <script src="geEngine.js"></script> <style type=text/css> body { background-color: #CCCCCC; font-family: sans-serif; text-align: center; color: #666666; } div.centered { margin-left: auto; margin-right: auto; width: 640px; } h1#title { padding-bottom: 40px; position: relative; top: 30px; } h2#info { padding-top: 20px; } a#engine { text-decoration: none; color: #666666; border-bottom-style: solid; border-bottom-width: 3px; } a#engine:hover { color: #666666; } canvas { -webkit-box-shadow: 0px 0px 125px #000; display: inline-block; margin-bottom: 15px; } ul { list-style-type: none; } li { padding-top: 10px; display: inline; } select { margin-left: 10px; } </style> </head> <body id="main-body" onload="geInitialize(); document.forms[0].reset();"> <div class="centered"> <p><h1 id="title">HTML5 Path Tracing</h1></p> <form> <ul> <li><input type="checkbox" name="tracer_mode" value="1" checked onclick="geToggleTraceMode();"/> Global Illumination</li> <li><input type="checkbox" name="refl_surf" value="1" disabled checked "/> Reflective Surfaces</li> <!-- It would have been great to use the new range control here, but Firefox does not support it yet. --> <li><select size="1" value="2" onchange="geSetMipLevel(this.value);"> <option value="1">Highest Quality</option> <option value="2" selected>Medium High Quality</option> <option value="4">Medium Low Quality</option> <option value="8">Lowest Quality</option> </select></li> </ul> </form> <!-- Our Engine.js examines the element specifiers to determine the framebuffer dimensions --> <canvas width="640" height="480" id="gameWindow"><h2 id="info">Sorry! Your browser does not support the canvas tag!</h2><h3>Currently supporting: Chrome, Safari, Firefox, IE.</h3><br /></canvas> <p><span id="debugWindow"></span></p> <p><h2 id="info">Learn more about this tracer <a id="engine" href="http://bertolami.com/index.php?engine=portfolio&content=graphics&detail=html5-path-tracer">here</a>.</h2></p> <p><h5 id="copyright">&copy; 2011 Bertolami.com</h5></p> </div> </body> </html>
ramenhut/js-path-tracer
index.html
HTML
bsd-2-clause
2,716
/* * Part of DNS zone file validator `validns`. * * Copyright 2011-2014 Anton Berezin <tobez@tobez.org> * Modified BSD license. * (See LICENSE file in the distribution.) * */ #include <sys/types.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include "common.h" #include "textparse.h" #include "mempool.h" #include "carp.h" #include "rr.h" static struct rr* sshfp_parse(char *name, long ttl, int type, char *s) { struct rr_sshfp *rr = getmem(sizeof(*rr)); int algorithm, fp_type; algorithm = extract_integer(&s, "algorithm"); if (algorithm < 0) return NULL; if (algorithm != 1 && algorithm != 2 && algorithm != 3 && algorithm != 4) return bitch("unsupported algorithm"); rr->algorithm = algorithm; fp_type = extract_integer(&s, "fp type"); if (fp_type < 0) return NULL; if (fp_type != 1 && fp_type != 2) return bitch("unsupported fp_type"); rr->fp_type = fp_type; rr->fingerprint = extract_hex_binary_data(&s, "fingerprint", EXTRACT_EAT_WHITESPACE); if (rr->fingerprint.length < 0) return NULL; if (rr->fp_type == 1 && rr->fingerprint.length != SHA1_BYTES) { return bitch("wrong SHA-1 fingerprint length: %d bytes found, %d bytes expected", rr->fingerprint.length, SHA1_BYTES); } if (rr->fp_type == 2 && rr->fingerprint.length != SHA256_BYTES) { return bitch("wrong SHA-256 fingerprint length: %d bytes found, %d bytes expected", rr->fingerprint.length, SHA256_BYTES); } if (*s) { return bitch("garbage after valid SSHFP data"); } return store_record(type, name, ttl, rr); } static char* sshfp_human(struct rr *rrv) { RRCAST(sshfp); char ss[4096]; char *s = ss; int l; int i; l = snprintf(s, 4096, "%u %u ", rr->algorithm, rr->fp_type); s += l; for (i = 0; i < rr->fingerprint.length; i++) { l = snprintf(s, 4096-(s-ss), "%02X", (unsigned char)rr->fingerprint.data[i]); s += l; } return quickstrdup_temp(ss); } static struct binary_data sshfp_wirerdata(struct rr *rrv) { RRCAST(sshfp); return compose_binary_data("11d", 1, rr->algorithm, rr->fp_type, rr->fingerprint); } struct rr_methods sshfp_methods = { sshfp_parse, sshfp_human, sshfp_wirerdata, NULL, NULL };
MikeAT/validns
sshfp.c
C
bsd-2-clause
2,176
import django from django.db import router from django.db.models import signals try: from django.db.models.fields.related import ReverseManyRelatedObjectsDescriptor except ImportError: from django.db.models.fields.related import ManyToManyDescriptor as ReverseManyRelatedObjectsDescriptor from ..utils import cached_property class SortableReverseManyRelatedObjectsDescriptor(ReverseManyRelatedObjectsDescriptor): @cached_property def related_manager_cls(self): ManyRelatedManagerBase = super( SortableReverseManyRelatedObjectsDescriptor, self).related_manager_cls class ManyRelatedManager(ManyRelatedManagerBase): def _add_items(self, source_field_name, target_field_name, *objs): """ By default, auto_created through objects from form instances are saved using Manager.bulk_create(). Manager.bulk_create() is passed a list containing instances of the through model with the target and source foreign keys defined. In order to set the position field we need to tweak this logic (the modified lines are marked out with comments below). This method is added to ManyRelatedManager below in SortableDescriptorMixin.related_manager_cls """ # source_field_name: the PK fieldname in join table for the source object # target_field_name: the PK fieldname in join table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. # If there aren't any objects, there is nothing to do. from django.db.models import Model if objs: new_ids = set() for obj in objs: if isinstance(obj, self.model): if not router.allow_relation(obj, self.instance): raise ValueError('Cannot add "%r": instance is on database "%s", value is on database "%s"' % (obj, self.instance._state.db, obj._state.db)) # _get_fk_val wasn't introduced until django 1.4.2 if hasattr(self, '_get_fk_val'): fk_val = self._get_fk_val(obj, target_field_name) else: fk_val = obj.pk if fk_val is None: raise ValueError('Cannot add "%r": the value for field "%s" is None' % (obj, target_field_name)) new_ids.add(fk_val) elif isinstance(obj, Model): raise TypeError("'%s' instance expected, got %r" % (self.model._meta.object_name, obj)) else: new_ids.add(obj) db = router.db_for_write(self.through, instance=self.instance) vals = self.through._default_manager.using(db).values_list(target_field_name, flat=True) vals = vals.filter(**{ source_field_name: getattr(self, '_pk_val', getattr(self, '_fk_val', self.instance.pk)), '%s__in' % target_field_name: new_ids, }) new_ids = new_ids - set(vals) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action='pre_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) ###################################################################### # This is where we modify the default logic for _add_items(). # We use get_or_create for ALL objects. Typically it calls bulk_create # ONLY on ids which have not yet been created. ###################################################################### # sort_field = self.field.sort_field sort_field_attname = self.field.sort_field.attname for obj in objs: sort_position = getattr(obj, sort_field_attname) new_obj, created = self.through._default_manager.using(db).get_or_create(**{ sort_field_attname: sort_position, '%s_id' % source_field_name: getattr(self, '_pk_val', getattr(self, '_fk_val', self.instance.pk)), '%s_id' % target_field_name: obj.pk, }) if getattr(new_obj, sort_field_attname) is not sort_position: setattr(new_obj, sort_field_attname, sort_position) new_obj.save() ###################################################################### # End custom logic ###################################################################### if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=self.through, action='post_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids, using=db) def get_queryset(self): """ Adds ordering to ManyRelatedManager.get_queryset(). This is necessary in order for form widgets to display authors ordered by position. """ try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): if django.VERSION < (1, 7): qset = super(ManyRelatedManager, self).get_query_set() else: qset = super(ManyRelatedManager, self).get_queryset() opts = self.through._meta # If the through table has Meta.ordering defined, order the objects # returned by the ManyRelatedManager by those fields. if self.field.sort_field_name: object_name = opts.object_name.lower() order_by = ['%s__%s' % (object_name, self.field.sort_field_name)] if self.model._meta.ordering != order_by: return qset.order_by(*order_by) return qset if django.VERSION < (1, 7): get_query_set = get_queryset def get_prefetch_queryset(self, instances, *args): if django.VERSION < (1, 7): rel_qs, rel_obj_attr, instance_attr, single, cache_name = \ super(ManyRelatedManager, self).get_prefetch_query_set(instances, *args) else: rel_qs, rel_obj_attr, instance_attr, single, cache_name = \ super(ManyRelatedManager, self).get_prefetch_queryset(instances, *args) opts = self.through._meta # If the through table has Meta.ordering defined, order the objects # returned by the ManyRelatedManager by those fields. if self.field.sort_field_name: object_name = opts.object_name.lower() order_by = ['%s__%s' % (object_name, self.field.sort_field_name)] if self.model._meta.ordering != order_by: rel_qs = rel_qs.order_by(*order_by) return (rel_qs, rel_obj_attr, instance_attr, single, cache_name) if django.VERSION < (1, 7): get_prefetch_query_set = get_prefetch_queryset ManyRelatedManager.field = self.field return ManyRelatedManager
SpectralAngel/django-select2-forms
select2/models/descriptors.py
Python
bsd-2-clause
8,496
using UnityEngine; using System.Collections; public class ParticleAutodestruct : MonoBehaviour { void Start () { if(!particleSystem.loop) { Destroy(gameObject, particleSystem.duration); } } public void DestroyGracefully() { DestroyGracefully(gameObject); } static public void DestroyGracefully(GameObject go) { go.transform.parent = null; go.particleSystem.loop = false; go.particleSystem.enableEmission = false; Destroy(go, go.particleSystem.duration); } }
tutsplus/battle-circle-ai
src/Assets/Scripts/ParticleAutodestruct.cs
C#
bsd-2-clause
491
#include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "CLLogger.h" #define LOG_FILE_NAME "logger" #define MAX_SIZE 265 #define BUFFER_SIZE_LOG_FILE 4096 CLLogger* CLLogger::m_pLog = 0; pthread_mutex_t CLLogger::m_Mutex = PTHREAD_MUTEX_INITIALIZER; CLLogger::CLLogger() { m_Fd = open(LOG_FILE_NAME, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); if(m_Fd == -1) throw "In CLLogger::CLLogger(), open error"; m_pLogBuffer = new char[BUFFER_SIZE_LOG_FILE]; m_nUsedBytesForBuffer = 0; } CLLogger::~CLLogger() { delete [] m_pLogBuffer; close(m_Fd); } CLStatus CLLogger::WriteLogMsg(const char *pstrMsg, long lErrorCode) { CLLogger *pLog = CLLogger::GetInstance(); if(pLog == 0) return CLStatus(-1, 0); CLStatus s = pLog->WriteLog(pstrMsg, lErrorCode); if(s.IsSuccess()) return CLStatus(0, 0); else return CLStatus(-1, 0); } CLStatus CLLogger::Flush() { int r = pthread_mutex_lock(&m_Mutex); if(r != 0) return CLStatus(-1, r); try { if(m_pLog == 0) throw CLStatus(-1, 0); if(m_nUsedBytesForBuffer == 0) throw CLStatus(0, 0); if(write(m_Fd, m_pLogBuffer, m_nUsedBytesForBuffer) == -1) throw CLStatus(-1, errno); m_nUsedBytesForBuffer = 0; throw CLStatus(0, 0); } catch(CLStatus &s) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return s; } catch(...) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return CLStatus(-1, 0); } } CLStatus CLLogger::WriteMsgAndErrcodeToFile(const char *pstrMsg, const char *pstrErrcode) { if(write(m_Fd, pstrMsg, strlen(pstrMsg)) == -1) return CLStatus(-1, errno); if(write(m_Fd, pstrErrcode, strlen(pstrErrcode)) == -1) return CLStatus(-1, errno); return CLStatus(0, 0); } CLStatus CLLogger::WriteLog(const char *pstrMsg, long lErrorCode) { if(pstrMsg == 0) return CLStatus(-1, 0); if(strlen(pstrMsg) == 0) return CLStatus(-1, 0); char buf[MAX_SIZE]; snprintf(buf, MAX_SIZE, " Error code: %ld\r\n", lErrorCode); int len_strmsg = strlen(pstrMsg); int len_code = strlen(buf); unsigned int total_len = len_strmsg + len_code; int r = pthread_mutex_lock(&m_Mutex); if(r != 0) return CLStatus(-1, r); try { if(m_pLog == 0) throw CLStatus(-1, 0); if(total_len > BUFFER_SIZE_LOG_FILE) throw WriteMsgAndErrcodeToFile(pstrMsg, buf); unsigned int nleftroom = BUFFER_SIZE_LOG_FILE - m_nUsedBytesForBuffer; if(total_len > nleftroom) { if(write(m_Fd, m_pLogBuffer, m_nUsedBytesForBuffer) == -1) throw CLStatus(-1, errno); m_nUsedBytesForBuffer = 0; } memcpy(m_pLogBuffer + m_nUsedBytesForBuffer, pstrMsg, len_strmsg); m_nUsedBytesForBuffer += len_strmsg; memcpy(m_pLogBuffer + m_nUsedBytesForBuffer, buf, len_code); m_nUsedBytesForBuffer += len_code; throw CLStatus(0, 0); } catch (CLStatus& s) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return s; } catch(...) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return CLStatus(-1, 0); } } CLLogger* CLLogger::GetInstance() { return m_pLog; } CLStatus CLLogger::Create() { //CLLibExecutiveInitializerµÄInitialize·½·¨£¬ //ÓÉÓÚ²»ÊÇÿ¸ö¶ÔÏó³õʼ»¯¹¤×÷¶¼³É¹¦£¬ //Òò´Ë¿ÉÄܶà´Îµ÷ÓÃÇ°ÃæÒѾ­³É¹¦Á˵ĶÔÏóµÄCreate·½·¨ if(m_pLog != 0) return CLStatus(0, 0); m_pLog = new CLLogger(); return CLStatus(0, 0); } CLStatus CLLogger::Destroy() { if(m_pLog == 0) return CLStatus(0, 0); int r = pthread_mutex_lock(&m_Mutex); if(r != 0) return CLStatus(-1, r); try { if(m_pLog->m_nUsedBytesForBuffer != 0) { if(write(m_pLog->m_Fd, m_pLog->m_pLogBuffer, m_pLog->m_nUsedBytesForBuffer) == -1) throw CLStatus(-1, errno); } delete m_pLog; m_pLog = 0; throw CLStatus(0, 0); } catch(CLStatus& s) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return s; } catch(...) { r = pthread_mutex_unlock(&m_Mutex); if(r != 0) return CLStatus(-1, r); return CLStatus(-1, 0); } }
unix1986/universe
book/bookcode/4/4.14/CLLogger.cpp
C++
bsd-2-clause
4,303
using Newtonsoft.Json; using System; namespace Wilson.Accounting.Core.Entities.ValueObjects { [JsonObject] public class BillItem : ValueObject<BillItem> { protected BillItem() { } [JsonProperty] public int Quantity { get; private set; } [JsonProperty] public decimal Price { get; private set; } [JsonProperty] public string StorehouseItemId { get; private set; } public virtual StorehouseItem StorehouseItem { get; private set; } public static BillItem Create(int quantity, decimal price, string storehouseItemId, int storehouseItemQuantity) { if (quantity > storehouseItemQuantity || quantity < 0) { throw new ArgumentOutOfRangeException("quantity", "Quantity can't be more then the available quantity and less then zero."); } if (price <= 0) { throw new ArgumentOutOfRangeException("price", "Price can't be negative number or zero."); } return new BillItem() { Quantity = quantity, StorehouseItemId = storehouseItemId }; } public void AddQuantity(int quantity) { this.Quantity += quantity; } protected override bool EqualsCore(BillItem other) { if (other == null) { return false; } return this.StorehouseItemId == other.StorehouseItemId; } protected override int GetHashCodeCore() { unchecked { int hashCode = StorehouseItemId.GetHashCode(); hashCode = (hashCode * 397) ^ Quantity; hashCode = (hashCode * 397) ^ Price.GetHashCode(); return hashCode; } } } }
KostaVlev/Wilson
Accounting/Wilson.Accounting.Core/Entities/ValueObjects/BillItem.cs
C#
bsd-2-clause
1,868
/** * Module : neoui-pagination * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-03 08:45:49 */ import {BaseComponent} from 'tinper-sparrow/js/BaseComponent'; import {extend} from 'tinper-sparrow/js/extend'; import {addClass,wrap,css,hasClass,removeClass,closest} from 'tinper-sparrow/js/dom'; import {each} from 'tinper-sparrow/js/util'; import {on} from 'tinper-sparrow/js/event'; import {compMgr} from 'tinper-sparrow/js/compMgr'; import {trans} from 'tinper-sparrow/js/util/i18n' var pagination = BaseComponent.extend({ }); var PageProxy = function(options, page) { this.isCurrent = function() { return page == options.currentPage; } this.isFirst = function() { return page == 1; } this.isLast = function() { return page == options.totalPages; } this.isPrev = function() { return page == (options.currentPage - 1); } this.isNext = function() { return page == (options.currentPage + 1); } this.isLeftOuter = function() { return page <= options.outerWindow; } this.isRightOuter = function() { return(options.totalPages - page) < options.outerWindow; } this.isInsideWindow = function() { if(options.currentPage < options.innerWindow + 1) { return page <= ((options.innerWindow * 2) + 1); } else if(options.currentPage > (options.totalPages - options.innerWindow)) { return(options.totalPages - page) <= (options.innerWindow * 2); } else { return Math.abs(options.currentPage - page) <= options.innerWindow; } } this.number = function() { return page; } this.pageSize = function() { return options.pageSize; } } var View = { firstPage: function(pagin, options, currentPageProxy) { return '<li role="first"' + (currentPageProxy.isFirst() ? 'class="disabled"' : '') + '><a >' + options.first + '</a></li>'; }, prevPage: function(pagin, options, currentPageProxy) { return '<li role="prev"' + (currentPageProxy.isFirst() ? 'class="disabled"' : '') + '><a rel="prev">' + options.prev + '</a></li>'; }, nextPage: function(pagin, options, currentPageProxy) { return '<li role="next"' + (currentPageProxy.isLast() ? 'class="disabled"' : '') + '><a rel="next">' + options.next + '</a></li>'; }, lastPage: function(pagin, options, currentPageProxy) { return '<li role="last"' + (currentPageProxy.isLast() ? 'class="disabled"' : '') + '><a >' + options.last + '</a></li>'; }, gap: function(pagin, options) { return '<li role="gap" class="disabled"><a >' + options.gap + '</a></li>'; }, page: function(pagin, options, pageProxy) { return '<li role="page"' + (pageProxy.isCurrent() ? 'class="active"' : '') + '><a ' + (pageProxy.isNext() ? ' rel="next"' : '') + (pageProxy.isPrev() ? 'rel="prev"' : '') + '>' + pageProxy.number() + '</a></li>'; } } //pagination.prototype.compType = 'pagination'; pagination.prototype.init = function(element, options) { var self = this; var element = this.element; this.$element = element; this.options = extend({}, this.DEFAULTS, this.options); this.$ul = this.$element; //.find("ul"); this.render(); } pagination.prototype.DEFAULTS = { currentPage: 1, totalPages: 1, pageSize: 10, pageList: [5, 10, 20, 50, 100], innerWindow: 2, outerWindow: 0, first: '&laquo;', prev: '<i class="uf uf-anglepointingtoleft"></i>', next: '<i class="uf uf-anglearrowpointingtoright"></i>', last: '&raquo;', gap: '···', //totalText: '合计:', totalText: trans('pagination.totalText','共'), listText:trans('pagination.listText','条'), showText:trans('pagination.showText','显示'), pageText:trans('pagination.pageText','页'), toText:trans('pagination.toText','到'), okText: trans('public.ok','确定'), truncate: false, showState: true, showTotal: true,//初始默认显示总条数 “共xxx条” showColumn: true,//初始默认显示每页条数 “显示xx条” showJump: true,//初始默认显示跳转信息 “到xx页 确定” page: function(page) { return true; } } pagination.prototype.update = function(options) { this.$ul.innerHTML = ""; this.options = extend({}, this.options, options); this.render(); } pagination.prototype.render = function() { var a = (new Date()).valueOf(); var options = this.options; if(!options.totalPages) { this.$element.style.display = "none"; return; } else { this.$element.style.display = "block"; } var htmlArr = []; var currentPageProxy = new PageProxy(options, options.currentPage); //update pagination by pengyic@yonyou.com //预设显示页码数 var windows = 2; var total = options.totalPages - 0; var current = options.currentPage - 0; //预设显示页码数截断修正 var fix = 0; var pageProxy; if(current - 2 <= windows + 1) { for(var i = 1; i <= current; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } fix = windows - (current - 1) < 0 ? 0 : windows - (current - 1); if(total - current - fix <= windows + 1) { for(var i = current + 1; i <= total; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } } else { for(var i = current + 1; i <= current + windows + fix; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } //添加分割'...' htmlArr.push(View.gap(this, options)); pageProxy = new PageProxy(options, total); htmlArr.push(View.page(this, options, pageProxy)); } } else { if(total - current <= windows + 1) { fix = windows - (total - current) < 0 ? 0 : windows - (total - current); for(var i = current - windows - fix; i <= total; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } if(i >= 2) { //添加分割'...' htmlArr.unshift(View.gap(this, options)); pageProxy = new PageProxy(options, 1); htmlArr.unshift(View.page(this, options, pageProxy)); } } else { for(var i = current - windows; i <= current + windows; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } //添加分割'...' htmlArr.push(View.gap(this, options)); pageProxy = new PageProxy(options, total); htmlArr.push(View.page(this, options, pageProxy)); //添加分割'...' htmlArr.unshift(View.gap(this, options)); pageProxy = new PageProxy(options, 1); htmlArr.unshift(View.page(this, options, pageProxy)); } } htmlArr.unshift(View.prevPage(this, options, currentPageProxy)); htmlArr.push(View.nextPage(this, options, currentPageProxy)); if(options.totalCount === undefined || options.totalCount <= 0) { options.totalCount = 0; } if(options.showState) { // 处理pageOption字符串 var pageOption = ''; options.pageList.forEach(function(item) { if(options.pageSize - 0 == item) { pageOption += '<option selected>' + item + '</option>' } else { pageOption += '<option>' + item + '</option>' } }); var htmlTmp = ''; //分别得到分页条后“共xxx条”、“显示xx条”、“到xx页 确定”三个html片段 if(options.showTotal){ htmlTmp += '<div class="pagination-state">' + options.totalText + '&nbsp;' + options.totalCount + '&nbsp;'+options.listText +'</div>'; } if(options.showColumn){ if( hasClass(this.$ul, 'pagination-sm') ){ htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z page_z_sm">' + pageOption + '</select>'+options.listText +'</div>'; }else if( hasClass(this.$ul, 'pagination-lg')){ htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z page_z_lg">' + pageOption + '</select>'+options.listText +'</div>'; }else{ htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z">' + pageOption + '</select>'+options.listText +'</div>'; } } if(options.showJump){ if( hasClass(this.$ul, 'pagination-sm')){ htmlTmp += '<div class="pagination-state">' + options.toText + '<input class="page_j text-center page_j_sm padding-left-0" value=' + options.currentPage + '>' + options.pageText + '<input class="pagination-jump pagination-jump-sm" type="button" value="'+ options.okText +'"/></div>'; }else if( hasClass(this.$ul, 'pagination-lg')){ htmlTmp += '<div class="pagination-state">' + options.toText + '<input class="page_j text-center page_j_lg padding-left-0" value=' + options.currentPage + '>' + options.pageText + '<input class="pagination-jump pagination-jump-lg" type="button" value="'+ options.okText +'"/></div>'; }else{ htmlTmp += '<div class="pagination-state">' + options.toText + '<input class="page_j text-center padding-left-0" value=' + options.currentPage + '>' + options.pageText + '<input class="pagination-jump" type="button" value="'+ options.okText +'"/></div>'; } } htmlArr.push(htmlTmp); } //在将htmlArr插入到页面之前,对htmlArr进行处理 this.$ul.innerHTML = ""; this.$ul.insertAdjacentHTML('beforeEnd', htmlArr.join('')); var me = this; on(this.$ul.querySelector(".pagination-jump"), "click", function() { var jp, pz; jp = me.$ul.querySelector(".page_j").value || options.currentPage; pz = me.$ul.querySelector(".page_z").value || options.pageSize; if(isNaN(jp))return; //if (pz != options.pageSize){ // me.$element.trigger('sizeChange', [pz, jp - 1]) //}else{ // me.$element.trigger('pageChange', jp - 1) //} me.page(jp, options.totalPages, pz); //me.$element.trigger('pageChange', jp - 1) //me.$element.trigger('sizeChange', pz) return false; }) on(this.$ul.querySelector('[role="first"] a'), 'click', function() { if(options.currentPage <= 1) return; me.firstPage(); //me.$element.trigger('pageChange', 0) return false; }) on(this.$ul.querySelector('[role="prev"] a'), 'click', function() { if(options.currentPage <= 1) return; me.prevPage(); //me.$element.trigger('pageChange', options.currentPage - 1) return false; }) on(this.$ul.querySelector('[role="next"] a'), 'click', function() { if(parseInt(options.currentPage) + 1 > options.totalPages) return; me.nextPage(); //me.$element.trigger('pageChange', parseInt(options.currentPage) + 1) return false; }) on(this.$ul.querySelector('[role="last"] a'), 'click', function() { if(options.currentPage == options.totalPages) return; me.lastPage(); //me.$element.trigger('pageChange', options.totalPages - 1) return false; }) each(this.$ul.querySelectorAll('[role="page"] a'), function(i, node) { on(node, 'click', function() { var pz = (me.$element.querySelector(".page_z") && $(this).val()) || options.pageSize; me.page(parseInt(this.innerHTML), options.totalPages, pz); //me.$element.trigger('pageChange', parseInt($(this).html()) - 1) return false; }) }) on(this.$ul.querySelector('.page_z'), 'change', function() { var pz = (me.$element.querySelector(".page_z") && $(this).val()) || options.pageSize; me.trigger('sizeChange', pz) }) } pagination.prototype.page = function(pageIndex, totalPages, pageSize) { var options = this.options; if(totalPages === undefined) { totalPages = options.totalPages; } if(pageSize === undefined) { pageSize = options.pageSize; } var oldPageSize = options.pageSize; // if (pageIndex > 0 && pageIndex <= totalPages) { // if (options.page(pageIndex)) { // this.$ul.innerHTML=""; // options.pageSize = pageSize; // options.currentPage = pageIndex; // options.totalPages = totalPages; // this.render(); // } // }else{ // return false; // } if(options.page(pageIndex)) { if(pageIndex <= 0) { pageIndex = 1; } if(pageIndex > totalPages) { pageIndex = totalPages; } this.$ul.innerHTML = ""; options.pageSize = pageSize; options.currentPage = pageIndex; options.totalPages = totalPages; this.render(); } var temppageIndex = (pageIndex - 1)<0?0:(pageIndex - 1); if(pageSize != oldPageSize) { this.trigger('sizeChange', [pageSize, temppageIndex]) } else { this.trigger('pageChange', temppageIndex) } //this.$element.trigger('pageChange', pageIndex) return false; } pagination.prototype.firstPage = function() { return this.page(1); } pagination.prototype.lastPage = function() { return this.page(this.options.totalPages); } pagination.prototype.nextPage = function() { return this.page(parseInt(this.options.currentPage) + 1); } pagination.prototype.prevPage = function() { return this.page(this.options.currentPage - 1); } pagination.prototype.disableChangeSize = function() { this.$element.querySelector('.page_z').setAttribute('readonly', true); } pagination.prototype.enableChangeSize = function() { this.$element.querySelector('.page_z').removeAttribute('readonly'); } function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('u.pagination') var options = typeof option == 'object' && option if(!data) $this.data('u.pagination', (data = new Pagination(this, options))) else data.update(options); }) } // var old = $.fn.pagination; // $.fn.pagination = Plugin // $.fn.pagination.Constructor = Pagination if(compMgr) compMgr.regComp({ comp: pagination, compAsString: 'u.pagination', css: 'u-pagination' }); if(document.readyState && document.readyState === 'complete') { compMgr.updateComp(); } else { on(window, 'load', function() { //扫描并生成控件 compMgr.updateComp(); }); } export {pagination};
iuap-design/iuap-design
js/neoui-pagination.js
JavaScript
bsd-2-clause
13,439
package in.twizmwaz.openuhc.game; import in.twizmwaz.openuhc.OpenUHC; import in.twizmwaz.openuhc.event.game.GameEndEvent; import in.twizmwaz.openuhc.event.game.GameScatterEvent; import in.twizmwaz.openuhc.event.game.GameStartEvent; import in.twizmwaz.openuhc.game.exception.BusyGameStateException; import in.twizmwaz.openuhc.game.exception.InvalidGameStateException; import in.twizmwaz.openuhc.module.ModuleHandler; import in.twizmwaz.openuhc.module.ModuleRegistry; import in.twizmwaz.openuhc.team.Team; import in.twizmwaz.openuhc.util.Numbers; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import lombok.AccessLevel; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; @Getter public class Game { private World world; private final ModuleHandler moduleHandler = new ModuleHandler(); private final List<UUID> players = new ArrayList<>(); private final List<Team> teams = new ArrayList<>(); private GameState state = GameState.NEW; private boolean busy = false; @Getter(AccessLevel.NONE) private int chunkX; @Getter(AccessLevel.NONE) private int chunkY; private int worldRadius = 100; // TODO: configuration /** * Initializes the game object. */ public void initialize() { ModuleRegistry.getGameModules().forEach(moduleData -> { if (moduleData.isEnabledOnStart()) { moduleHandler.enableModule(moduleData.getClazz()); } }); } /** * De-initializes the game object. */ public void terminate() { moduleHandler.disableAllModules(); } /** * Generates the chunks in the game world with a given radius. */ public void generate() throws BusyGameStateException, InvalidGameStateException { if (busy) { throw new BusyGameStateException(); } else if (state != GameState.NEW) { throw new InvalidGameStateException(state, GameState.NEW); } busy = true; world = Bukkit.createWorld(new WorldCreator( OpenUHC.WORLD_DIR_PREFIX + String.valueOf(System.currentTimeMillis()))); world.setGameRuleValue("naturalRegeneration", "false"); final int chunkRadius = (worldRadius / 16) + 4; chunkX = -1 * chunkRadius; chunkY = -1 * chunkRadius; final CompletableFuture<BukkitTask> task = new CompletableFuture<>(); task.complete(Bukkit.getScheduler().runTaskTimer(OpenUHC.getInstance(), () -> { for (int i = 0; i < 25; ++i) { world.loadChunk(chunkX, chunkY); if (chunkX == chunkRadius && chunkY == chunkRadius) { try { // Task completed! busy = false; state = GameState.GENERATED; OpenUHC.getPluginLogger().info("World generation compete!"); task.get().cancel(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } else if (chunkX == chunkRadius) { chunkX = -1 * chunkRadius; ++chunkY; OpenUHC.getPluginLogger().info(chunkY + chunkRadius + "/" + chunkRadius * 2); } else { ++chunkX; } } }, 0, 1)); } /** * Scatters players before the start of the game. */ public void scatter() { if (busy) { throw new BusyGameStateException(); } else if (state != GameState.GENERATED) { throw new InvalidGameStateException(state, GameState.GENERATED); } finalizeTeams(); OpenUHC.getPluginLogger().info("Teams: " + teams.size()); busy = true; GameScatterEvent event = new GameScatterEvent(this); Bukkit.getPluginManager().callEvent(event); // Bad random scatter. Should be more equal in the future final Queue<Location> locs = new PriorityQueue<>(); for (int i = 0; i < teams.size(); ++i) { Location loc = new Location( world, Numbers.random(-1 * worldRadius, worldRadius), 0, Numbers.random(-1 * worldRadius, worldRadius)); loc.setY(world.getHighestBlockYAt(loc)); locs.add(loc); } // Teleport players over an interval. We'll want to handle offline players too TODO int delay = 10; for (Team team : teams) { Bukkit.getScheduler().runTaskLater(OpenUHC.getInstance(), () -> { Location loc = locs.remove(); boolean last = locs.isEmpty(); for (Player player : team.getOnlinePlayers()) { player.teleport(loc); } if (last) { busy = false; state = GameState.SCATTERED; } }, delay); delay += 10; } } /** * Starts the game. */ public void start() { if (busy) { throw new BusyGameStateException(); } else if (state != GameState.SCATTERED) { throw new InvalidGameStateException(state, GameState.GENERATED); } GameStartEvent event = new GameStartEvent(this); Bukkit.getServer().getPluginManager().callEvent(event); state = GameState.PLAYING; } /** * Ends the game. */ public void end() { if (state != GameState.PLAYING) { throw new InvalidGameStateException(state, GameState.PLAYING); } GameEndEvent event = new GameEndEvent(this); Bukkit.getServer().getPluginManager().callEvent(event); state = GameState.COMPLETED; } private void finalizeTeams() { // TODO handle spectators for (Player player : Bukkit.getOnlinePlayers()) { if (getTeam(player) == null) { Team team = new Team(player); } } for (Team team : teams) { players.addAll(team.getPlayers()); } } /** * Gets the team of a player, null if the player is not on a team. * * @param player The player * @return The team that has the player on it */ public Team getTeam(Player player) { for (Team team : teams) { if (team.hasPlayer(player)) { return team; } } return null; } /** * Gets the team of a player, null if the player is not on a team. * * @param player The player * @return The team that has the player on it */ public Team getTeam(UUID player) { for (Team team : teams) { if (team.hasPlayer(player)) { return team; } } return null; } }
twizmwazin/OpenUHC
OpenUHC/src/main/java/in/twizmwaz/openuhc/game/Game.java
Java
bsd-2-clause
6,433
/* * main.cpp * * Created on: 03/01/2011 * Author: adam */ // --------------------------------------------------------------- // Shock Includes #include "Shock/Memory/ObjectPool.h" // System Includes #include <cstdio> #include <iostream> // --------------------------------------------------------------- class TestObject { public: TestObject() { std::cout << "SUCCESS: object constructor called" << std::endl << std::flush; }; ~TestObject() { std::cout << "SUCCESS: object destructor called" << std::endl << std::flush; }; }; // --------------------------------------------------------------- int main( int argc, char* argv[] ) { std::cout << "Unit Test: Shock::Memory" << std::endl << std::flush; // Object Pool { Shock::Memory::ObjectPool< TestObject > kPool( 5, 1 ); // get our memory allocation void* raw = kPool.allocate(); // manually invoke the constructor using the memory w'eve been given TestObject* pObject = new(raw) TestObject(); // invoke the destructor manually pObject->~TestObject(); // release the object kPool.release( pObject ); } // new / delete operators // messy syntax { Shock::Memory::ObjectPool< TestObject > kPool( 5, 1 ); // call new on the pool TestObject *pObject = new( kPool ) TestObject(); // delete the object operator delete( pObject, kPool ); } // Complete std::cout << "Press enter to continue..." << std::endl << std::flush; getchar(); return 0; } // ---------------------------------------------------------------
adamlwgriffiths/Shock
Shock/UnitTest_Memory/src/main.cpp
C++
bsd-2-clause
1,660
// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #ifndef CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_STORAGE_HPP #define CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_STORAGE_HPP #include "crunch/base/align.hpp" #include <emmintrin.h> namespace Crunch { namespace Concurrency { namespace Platform { template<typename T> struct AtomicStorage; template<> struct AtomicStorage<char> { char bits; }; template<> struct CRUNCH_ALIGN_PREFIX(2) AtomicStorage<short> { short bits; } CRUNCH_ALIGN_POSTFIX(2); template<> struct CRUNCH_ALIGN_PREFIX(4) AtomicStorage<long> { long bits; } CRUNCH_ALIGN_POSTFIX(4); template<> struct CRUNCH_ALIGN_PREFIX(8) AtomicStorage<__int64> { __int64 bits; } CRUNCH_ALIGN_POSTFIX(8); template<> struct CRUNCH_ALIGN_PREFIX(16) AtomicStorage<__m128i> { __m128i bits; } CRUNCH_ALIGN_POSTFIX(16); static_assert(sizeof(AtomicStorage<char>) == 1, "Unexpected AtomicStorage size"); static_assert(sizeof(AtomicStorage<short>) == 2, "Unexpected AtomicStorage size"); static_assert(sizeof(AtomicStorage<long>) == 4, "Unexpected AtomicStorage size"); static_assert(sizeof(AtomicStorage<__int64>) == 8, "Unexpected AtomicStorage size"); static_assert(sizeof(AtomicStorage<__m128i>) == 16, "Unexpected AtomicStorage size"); }}} #endif
ancapdev/crunch.concurrency
include/crunch/concurrency/platform/win32/atomic_storage.hpp
C++
bsd-2-clause
1,319
<?php /** * Copyright (c) 2012-2019, Mollie B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * @category Mollie * @package Mollie_Mpm * @author Mollie B.V. (info@mollie.nl) * @copyright Copyright (c) 2012-2019 Mollie B.V. (https://www.mollie.nl) * @license http://www.opensource.org/licenses/bsd-license.php BSD-License 2 */ class Mollie_Mpm_Model_Adminhtml_System_Config_Source_IssuerListType extends Mollie_Mpm_Model_Adminhtml_System_Config_Source_SourceAbstract { /** * @return array */ public function toOptionArray() { if (!$this->options) { $this->options = array( array( 'value' => 'dropdown', 'label' => $this->mollieHelper->__('Dropdown') ), array( 'value' => 'radio', 'label' => $this->mollieHelper->__('List with images') ), array( 'value' => '', 'label' => $this->mollieHelper->__('Don\'t show issuer list') ) ); } return $this->options; } }
mollie/Magento
app/code/community/Mollie/Mpm/Model/Adminhtml/System/Config/Source/IssuerListType.php
PHP
bsd-2-clause
2,436
cask v1: 'airfile' do version '2.8.2' sha256 'ab8792e538462b8f8fc6b44af28dd2fe9d16af3f955cd2cfcc7ed6f88fb87e9a' # amazonaws.com is the official download host per the vendor homepage url "https://s3.amazonaws.com/airfile-static/__apps__/airfile/AirFile-#{version}.zip" name 'AirFile' appcast 'https://s3.amazonaws.com/airfile-static/__apps__/airfile/appcast.xml', sha256: '8593304382bcd34bfbf85efe09f2cc7f00bac0955258decdf46edd4f57a0db38' homepage 'http://airfileapp.tumblr.com/' license :commercial app 'AirFile.app' end
askl56/homebrew-cask
Casks/airfile.rb
Ruby
bsd-2-clause
551
#include "ifcconvector.h" #include "IFCEngine/engine.h" #include "Stream/UGFile.h" #include "OGDC/OgdcDataSource.h" #include "OGDC/OgdcProviderManager.h" #include <QMessageBox> #include <QProgressDialog> #include "Base3D/UGReindexer.h" #include "Base3D/UGModelEM.h" #include "Base3D/UGModelNodeShells.h" #include "Base3D/UGModelNode.h" #include "Base3D/UGVector3d.h" #include "Geometry3D/UGGeoModelPro.h" static int_t flagbit0 = 1; // 2^^0 0000.0000..0000.0001 static int_t flagbit1 = 2; // 2^^1 0000.0000..0000.0010 static int_t flagbit2 = 4; // 2^^2 0000.0000..0000.0100 static int_t flagbit3 = 8; // 2^^3 0000.0000..0000.1000 static int_t flagbit4 = 16; // 2^^4 0000.0000..0001.0000 static int_t flagbit5 = 32; // 2^^5 0000.0000..0010.0000 static int_t flagbit6 = 64; // 2^^6 0000.0000..0100.0000 static int_t flagbit7 = 128; // 2^^7 0000.0000..1000.0000 static int_t flagbit8 = 256; // 2^^8 0000.0001..0000.0000 static int_t flagbit9 = 512; // 2^^9 0000.0010..0000.0000 static int_t flagbit10 = 1024; // 2^^10 0000.0100..0000.0000 static int_t flagbit11 = 2048; // 2^^11 0000.1000..0000.0000 static int_t flagbit12 = 4096; // 2^^12 0001.0000..0000.0000 static int_t flagbit13 = 8192; // 2^^13 0010.0000..0000.0000 static int_t flagbit14 = 16384; // 2^^14 0100.0000..0000.0000 static int_t flagbit15 = 32768; // 2^^15 1000.0000..0000.0000 static bool contains(wchar_t * txtI, wchar_t * txtII) { int_t i = 0; while (txtI[i] && txtII[i]) { if (txtI[i] != txtII[i]) { return false; } i++; } if (txtII[i]) { return false; } else { return true; } } static bool __equals( wchar_t * txtI, wchar_t * txtII ) { int_t i = 0; if (txtI && txtII) { while (txtI[i]) { if (txtI[i] != txtII[i]) { return false; } i++; } if (txtII[i]) { return false; } } else if (txtI || txtII) { return false; } return true; } static bool equalStr(wchar_t * txtI, wchar_t * txtII) { int_t i = 0; if (txtI && txtII) { while (txtI[i]) { if (txtI[i] != txtII[i]) { return false; } i++; } if (txtII[i]) { return false; } } else if (txtI || txtII) { return false; } return true; } static wchar_t * copyStr(wchar_t * txt) { if (txt) { int_t i = 0; while (txt[i]) { i++; } wchar_t * rValue = new wchar_t[i + 1]; i = 0; while (txt[i]) { rValue[i] = txt[i]; i++; } rValue[i] = 0; return rValue; } else { return 0; } } IFCConvector::IFCConvector(QObject *parent) : QObject(parent) { m_ifcSchemaName_IFC2x3 = NULL; m_ifcSchemaName_IFC4 = NULL; m_ifcSchemaName_IFC4x1 = NULL; m_ifcObjects = NULL; m_firstFreeIfcObject = &m_ifcObjects; m_ifcModel = NULL; m_defaultMaterial = NULL; m_firstMaterial = NULL; m_lastMaterial = NULL; m_units = NULL; m_bIsPlaceSphere = true; Init(); } IFCConvector::~IFCConvector() { Clear(); } void IFCConvector::Init() { // ÔØÈëÅäÖÃÎļþ UGString cfilePath = UGFile::GetAppPath() + _U("config/"); wchar_t* configFilePath = (wchar_t*) cfilePath.Cstr(); int_t i = wcslen(configFilePath); m_ifcSchemaName_IFC2x3 = new wchar_t[i + wcslen(L"IFC2X3_TC1.exp") + 1]; memcpy(&m_ifcSchemaName_IFC2x3[0], configFilePath, i * sizeof(wchar_t)); memcpy(&m_ifcSchemaName_IFC2x3[i], L"IFC2X3_TC1.exp", (wcslen(L"IFC2X3_TC1.exp") + 1) * sizeof(wchar_t)); m_ifcSchemaName_IFC4 = new wchar_t[i + wcslen(L"IFC4_ADD2.exp") + 1]; memcpy(&m_ifcSchemaName_IFC4[0], configFilePath, i * sizeof(wchar_t)); memcpy(&m_ifcSchemaName_IFC4[i], L"IFC4_ADD2.exp", (wcslen(L"IFC4_ADD2.exp") + 1) * sizeof(wchar_t)); m_ifcSchemaName_IFC4x1 = new wchar_t[i + wcslen(L"IFC4X1.exp") + 1]; memcpy(&m_ifcSchemaName_IFC4x1[0], configFilePath, i * sizeof(wchar_t)); memcpy(&m_ifcSchemaName_IFC4x1[i], L"IFC4X1.exp", (wcslen(L"IFC4X1.exp") + 1) * sizeof(wchar_t)); } void IFCConvector::Clear() { delete[] m_ifcSchemaName_IFC2x3; delete[] m_ifcSchemaName_IFC4; delete[] m_ifcSchemaName_IFC4x1; ClearUpIfcModel(); m_ifcSchemaName_IFC2x3 = NULL; m_ifcSchemaName_IFC4 = NULL; m_ifcSchemaName_IFC4x1 = NULL; m_ifcObjects = NULL; m_firstFreeIfcObject = &m_ifcObjects; //m_ifcPropertySet = NULL; m_ifcModel = NULL; m_defaultMaterial = NULL; m_firstMaterial = NULL; m_lastMaterial = NULL; m_units = NULL; } //------------------------------------------------------------------------------------------------------- void IFCConvector::ClearUnits() { while (m_units) { IFC__SIUNIT * unitToRemove = m_units; m_units = m_units->next; delete unitToRemove; } m_units = NULL; } void IFCConvector::GetUnits(int_t ifcModel) { int_t ifcRelAggregates_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCRELAGGREGATES"); int_t ifcRelContainedInSpatialStructure_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCRELCONTAINEDINSPATIALSTRUCTURE"); int_t* ifcProjectInstances = sdaiGetEntityExtentBN(ifcModel, (char*)L"IFCPROJECT"); int_t noIfcProjectInstances = sdaiGetMemberCount(ifcProjectInstances); for (int_t i = 0; i < noIfcProjectInstances; ++i) { int_t ifcProjectInstance = 0; engiGetAggrElement(ifcProjectInstances, i, sdaiINSTANCE, &ifcProjectInstance); m_units = GetUnits(ifcModel, ifcProjectInstance); } } IFC__SIUNIT* IFCConvector::GetUnits(int_t ifcModel, int_t ifcProjectInstance) { IFC__SIUNIT * firstUnit = 0; int_t ifcUnitAssignmentInstance = 0; sdaiGetAttrBN(ifcProjectInstance, (char*)L"UnitsInContext", sdaiINSTANCE, &ifcUnitAssignmentInstance); int_t ifcConversianBasedUnit_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCCONVERSIONBASEDUNIT"), ifcSIUnit_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCSIUNIT"); int_t * unit_set = 0, unit_cnt, i = 0; sdaiGetAttrBN(ifcUnitAssignmentInstance, (char*)L"Units", sdaiAGGR, &unit_set); unit_cnt = sdaiGetMemberCount(unit_set); for (i = 0; i < unit_cnt; ++i) { int_t ifcUnitInstance = 0; engiGetAggrElement(unit_set, i, sdaiINSTANCE, &ifcUnitInstance); if (sdaiGetInstanceType(ifcUnitInstance) == ifcConversianBasedUnit_TYPE) { IFC__SIUNIT * unit = new IFC__SIUNIT(); unit->unitType = 0; unit->prefix = 0; unit->name = 0; unit->next = firstUnit; firstUnit = unit; int_t ifcMeasureWithUnitInstance = 0; sdaiGetAttrBN(ifcUnitInstance, (char*)L"ConversionFactor", sdaiINSTANCE, &ifcMeasureWithUnitInstance); if (ifcMeasureWithUnitInstance) { int_t ifcSIUnitInstance = 0; int_t * adb = 0; sdaiGetAttrBN(ifcMeasureWithUnitInstance, (char*)L"UnitComponent", sdaiINSTANCE, &ifcSIUnitInstance); sdaiGetAttrBN(ifcMeasureWithUnitInstance, (char*)L"ValueComponent", sdaiADB, &adb); double value = 0; sdaiGetADBValue(adb, sdaiREAL, &value); if (sdaiGetInstanceType(ifcSIUnitInstance) == ifcSIUnit_TYPE) { wchar_t * unitType = 0, *prefix = 0, *name = 0; sdaiGetAttrBN(ifcSIUnitInstance, (char*)L"UnitType", sdaiUNICODE, &unitType); sdaiGetAttrBN(ifcSIUnitInstance, (char*)L"Prefix", sdaiUNICODE, &prefix); sdaiGetAttrBN(ifcSIUnitInstance, (char*)L"Name", sdaiUNICODE, &name); UnitAddUnitType(unit, unitType); UnitAddPrefix(unit, prefix); UnitAddName(unit, name); } else { //ASSERT(false); } } else { //ASSERT(false); } } else if (sdaiGetInstanceType(ifcUnitInstance) == ifcSIUnit_TYPE) { IFC__SIUNIT * unit = new IFC__SIUNIT(); unit->unitType = 0; unit->prefix = 0; unit->name = 0; unit->next = firstUnit; firstUnit = unit; wchar_t * unitType = 0, *prefix = 0, *name = 0; sdaiGetAttrBN(ifcUnitInstance, (char*)L"UnitType", sdaiUNICODE, &unitType); sdaiGetAttrBN(ifcUnitInstance, (char*)L"Prefix", sdaiUNICODE, &prefix); sdaiGetAttrBN(ifcUnitInstance, (char*)L"Name", sdaiUNICODE, &name); UnitAddUnitType(unit, unitType); UnitAddPrefix(unit, prefix); UnitAddName(unit, name); } else { /////////////////// ASSERT(false); } } return firstUnit; } wchar_t * IFCConvector::GetUnit(IFC__SIUNIT * units, wchar_t * unitType) { IFC__SIUNIT * unit = units; while (unit) { if (equalStr(unit->unitType, unitType)) { int_t i = 0, j = 0; if (unit->prefix) { while (unit->prefix[i]) { i++; } i++; } if (unit->name) { while (unit->name[j]) { j++; } } wchar_t * rValue = new wchar_t[i + j + 1]; i = 0; if (unit->prefix) { while (unit->prefix[i]) { rValue[i++] = unit->prefix[i]; } rValue[i++] = ' '; } j = 0; if (unit->name) { while (unit->name[j]) { rValue[i + j++] = unit->name[j]; } rValue[i + j] = 0; } return rValue; } unit = unit->next; } return 0; } void IFCConvector::UnitAddUnitType(IFC__SIUNIT * unit, wchar_t * unitType) { // // unitType // if (equalStr(unitType, L".ABSORBEDDOSEUNIT.")) { unit->type = ABSORBEDDOSEUNIT; unit->unitType = L"ABSORBEDDOSEUNIT"; } else if (equalStr(unitType, L".AREAUNIT.")) { unit->type = AREAUNIT; unit->unitType = L"AREAUNIT"; } else if (equalStr(unitType, L".DOSEEQUIVALENTUNIT.")) { unit->type = DOSEEQUIVALENTUNIT; unit->unitType = L"DOSEEQUIVALENTUNIT"; } else if (equalStr(unitType, L".ELECTRICCAPACITANCEUNIT.")) { unit->type = ELECTRICCAPACITANCEUNIT; unit->unitType = L"ELECTRICCAPACITANCEUNIT"; } else if (equalStr(unitType, L".ELECTRICCHARGEUNIT.")) { unit->type = ELECTRICCHARGEUNIT; unit->unitType = L"ELECTRICCHARGEUNIT"; } else if (equalStr(unitType, L".ELECTRICCONDUCTANCEUNIT.")) { unit->type = ELECTRICCONDUCTANCEUNIT; unit->unitType = L"ELECTRICCONDUCTANCEUNIT"; } else if (equalStr(unitType, L".ELECTRICCURRENTUNIT.")) { unit->type = ELECTRICCURRENTUNIT; unit->unitType = L"ELECTRICCURRENTUNIT"; } else if (equalStr(unitType, L".ELECTRICRESISTANCEUNIT.")) { unit->type = ELECTRICRESISTANCEUNIT; unit->unitType = L"ELECTRICRESISTANCEUNIT"; } else if (equalStr(unitType, L".ELECTRICVOLTAGEUNIT.")) { unit->type = ELECTRICVOLTAGEUNIT; unit->unitType = L"ELECTRICVOLTAGEUNIT"; } else if (equalStr(unitType, L".ENERGYUNIT.")) { unit->type = ENERGYUNIT; unit->unitType = L"ENERGYUNIT"; } else if (equalStr(unitType, L".FORCEUNIT.")) { unit->type = FORCEUNIT; unit->unitType = L"FORCEUNIT"; } else if (equalStr(unitType, L".FREQUENCYUNIT.")) { unit->type = FREQUENCYUNIT; unit->unitType = L"FREQUENCYUNIT"; } else if (equalStr(unitType, L".ILLUMINANCEUNIT.")) { unit->type = ILLUMINANCEUNIT; unit->unitType = L"ILLUMINANCEUNIT"; } else if (equalStr(unitType, L".INDUCTANCEUNIT.")) { unit->type = INDUCTANCEUNIT; unit->unitType = L"INDUCTANCEUNIT"; } else if (equalStr(unitType, L".LENGTHUNIT.")) { unit->type = LENGTHUNIT; unit->unitType = L"LENGTHUNIT"; } else if (equalStr(unitType, L".LUMINOUSFLUXUNIT.")) { unit->type = LUMINOUSFLUXUNIT; unit->unitType = L"LUMINOUSFLUXUNIT"; } else if (equalStr(unitType, L".LUMINOUSINTENSITYUNIT.")) { unit->type = LUMINOUSINTENSITYUNIT; unit->unitType = L"LUMINOUSINTENSITYUNIT"; } else if (equalStr(unitType, L".MAGNETICFLUXDENSITYUNIT.")) { unit->type = MAGNETICFLUXDENSITYUNIT; unit->unitType = L"MAGNETICFLUXDENSITYUNIT"; } else if (equalStr(unitType, L".MAGNETICFLUXUNIT.")) { unit->type = MAGNETICFLUXUNIT; unit->unitType = L"MAGNETICFLUXUNIT"; } else if (equalStr(unitType, L".MASSUNIT.")) { unit->type = MASSUNIT; unit->unitType = L"MASSUNIT"; } else if (equalStr(unitType, L".PLANEANGLEUNIT.")) { unit->type = PLANEANGLEUNIT; unit->unitType = L"PLANEANGLEUNIT"; } else if (equalStr(unitType, L".POWERUNIT.")) { unit->type = POWERUNIT; unit->unitType = L"POWERUNIT"; } else if (equalStr(unitType, L".PRESSUREUNIT.")) { unit->type = PRESSUREUNIT; unit->unitType = L"PRESSUREUNIT"; } else if (equalStr(unitType, L".RADIOACTIVITYUNIT.")) { unit->type = RADIOACTIVITYUNIT; unit->unitType = L"RADIOACTIVITYUNIT"; } else if (equalStr(unitType, L".SOLIDANGLEUNIT.")) { unit->type = SOLIDANGLEUNIT; unit->unitType = L"SOLIDANGLEUNIT"; } else if (equalStr(unitType, L".THERMODYNAMICTEMPERATUREUNIT.")) { unit->type = THERMODYNAMICTEMPERATUREUNIT; unit->unitType = L"THERMODYNAMICTEMPERATUREUNIT"; } else if (equalStr(unitType, L".TIMEUNIT.")) { unit->type = TIMEUNIT; unit->unitType = L"TIMEUNIT"; } else if (equalStr(unitType, L".VOLUMEUNIT.")) { unit->type = VOLUMEUNIT; unit->unitType = L"VOLUMEUNIT"; } else if (equalStr(unitType, L".USERDEFINED.")) { unit->type = USERDEFINED; unit->unitType = L"USERDEFINED"; } else { //ASSERT(false); } } void IFCConvector::UnitAddPrefix(IFC__SIUNIT * unit, wchar_t * prefix) { // // prefix // if (equalStr(prefix, L".EXA.")) { unit->prefix = L"Exa"; } else if (equalStr(prefix, L".PETA.")) { unit->prefix = L"Peta"; } else if (equalStr(prefix, L".TERA.")) { unit->prefix = L"Tera"; } else if (equalStr(prefix, L".GIGA.")) { unit->prefix = L"Giga"; } else if (equalStr(prefix, L".MEGA.")) { unit->prefix = L"Mega"; } else if (equalStr(prefix, L".KILO.")) { unit->prefix = L"Kilo"; } else if (equalStr(prefix, L".HECTO.")) { unit->prefix = L"Hecto"; } else if (equalStr(prefix, L".DECA.")) { unit->prefix = L"Deca"; } else if (equalStr(prefix, L".DECI.")) { unit->prefix = L"Deci"; } else if (equalStr(prefix, L".CENTI.")) { unit->prefix = L"Centi"; } else if (equalStr(prefix, L".MILLI.")) { unit->prefix = L"Milli"; } else if (equalStr(prefix, L".MICRO.")) { unit->prefix = L"Micro"; } else if (equalStr(prefix, L".NANO.")) { unit->prefix = L"Nano"; } else if (equalStr(prefix, L".PICO.")) { unit->prefix = L"Pico"; } else if (equalStr(prefix, L".FEMTO.")) { unit->prefix = L"Femto"; } else if (equalStr(prefix, L".ATTO.")) { unit->prefix = L"Atto"; } else { //ASSERT(prefix == 0); } } void IFCConvector::UnitAddName(IFC__SIUNIT * unit, wchar_t * name) { // // name // if (equalStr(name, L".AMPERE.")) { unit->name = L"Ampere"; } else if (equalStr(name, L".BECQUEREL.")) { unit->name = L"Becquerel"; } else if (equalStr(name, L".CANDELA.")) { unit->name = L"Candela"; } else if (equalStr(name, L".COULOMB.")) { unit->name = L"Coulomb"; } else if (equalStr(name, L".CUBIC_METRE.")) { unit->name = L"Cubic Metre"; } else if (equalStr(name, L".DEGREE_CELSIUS.")) { unit->name = L"Degree Celcius"; } else if (equalStr(name, L".FARAD.")) { unit->name = L"Farad"; } else if (equalStr(name, L".GRAM.")) { unit->name = L"Gram"; } else if (equalStr(name, L".GRAY.")) { unit->name = L"Gray"; } else if (equalStr(name, L".HENRY.")) { unit->name = L"Henry"; } else if (equalStr(name, L".HERTZ.")) { unit->name = L"Hertz"; } else if (equalStr(name, L".JOULE.")) { unit->name = L"Joule"; } else if (equalStr(name, L".KELVIN.")) { unit->name = L"Kelvin"; } else if (equalStr(name, L".LUMEN.")) { unit->name = L"Lumen"; } else if (equalStr(name, L".LUX.")) { unit->name = L"Lux"; } else if (equalStr(name, L".METRE.")) { unit->name = L"Metre"; } else if (equalStr(name, L".MOLE.")) { unit->name = L"Mole"; } else if (equalStr(name, L".NEWTON.")) { unit->name = L"Newton"; } else if (equalStr(name, L".OHM.")) { unit->name = L"Ohm"; } else if (equalStr(name, L".PASCAL.")) { unit->name = L"Pascal"; } else if (equalStr(name, L".RADIAN.")) { unit->name = L"Radian"; } else if (equalStr(name, L".SECOND.")) { unit->name = L"Second"; } else if (equalStr(name, L".SIEMENS.")) { unit->name = L"Siemens"; } else if (equalStr(name, L".SIEVERT.")) { unit->name = L"Sievert"; } else if (equalStr(name, L".SQUARE_METRE.")) { unit->name = L"Square Metre"; } else if (equalStr(name, L".STERADIAN.")) { unit->name = L"Steradian"; } else if (equalStr(name, L".TESLA.")) { unit->name = L"Tesla"; } else if (equalStr(name, L".VOLT.")) { unit->name = L"Volt"; } else if (equalStr(name, L".WATT.")) { unit->name = L"Watt"; } else if (equalStr(name, L".WEBER.")) { unit->name = L"Weber"; } else { //ASSERT(false); } } //------------------------------------------------------------------------------------ UGbool IFCConvector::ParseFile(std::wstring filename) { // ¼ÓÔØIFCÎļþ ClearUpIfcModel(); m_firstItemWithGeometryPassed = false; setStringUnicode(1); m_ifcModel = sdaiOpenModelBNUnicode(0, (char*)filename.c_str(), 0); if (m_ifcModel) { wchar_t * fileSchema = 0; GetSPFFHeaderItem(m_ifcModel, 9, 0, sdaiUNICODE, (char**)&fileSchema); if (fileSchema == 0 || contains(fileSchema, L"IFC2x3") || contains(fileSchema, L"IFC2X3") || contains(fileSchema, L"IFC2x2") || contains(fileSchema, L"IFC2X2") || contains(fileSchema, L"IFC2x_") || contains(fileSchema, L"IFC2X_") || contains(fileSchema, L"IFC20")) { sdaiCloseModel(m_ifcModel); m_ifcModel = sdaiOpenModelBNUnicode(0, (char*)filename.c_str(), (char*)m_ifcSchemaName_IFC2x3); } else { if (contains(fileSchema, L"IFC4x") || contains(fileSchema, L"IFC4X")) { sdaiCloseModel(m_ifcModel); m_ifcModel = sdaiOpenModelBNUnicode(0, (char*)filename.c_str(), (char*)m_ifcSchemaName_IFC4x1); } else { if (contains(fileSchema, L"IFC4") || contains(fileSchema, L"IFC2x4") || contains(fileSchema, L"IFC2X4")) { sdaiCloseModel(m_ifcModel); m_ifcModel = sdaiOpenModelBNUnicode(0, (char*)filename.c_str(), (char*)m_ifcSchemaName_IFC4); } else { sdaiCloseModel(m_ifcModel); return FALSE; } } } // -------------------------------------------------- if (!m_ifcModel) { return FALSE; } //--------------------------------------------------- m_ifcSpace_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCSPACE"); m_ifcDistributionElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCDISTRIBUTIONELEMENT"); m_ifcElectricalElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCELECTRICALELEMENT"); m_ifcElementAssembly_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCELEMENTASSEMBLY"); m_ifcElementComponent_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCELEMENTCOMPONENT"); m_ifcEquipmentElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCEQUIPMENTELEMENT"); m_ifcFeatureElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCFEATUREELEMENT"); m_ifcFeatureElementSubtraction_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCFEATUREELEMENTSUBTRACTION"); m_ifcFurnishingElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCFURNISHINGELEMENT"); m_ifcReinforcingElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCREINFORCINGELEMENT"); m_ifcTransportElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCTRANSPORTELEMENT"); m_ifcVirtualElement_TYPE = sdaiGetEntity(m_ifcModel, (char*)L"IFCVIRTUALELEMENT"); QProgressDialog dialog; dialog.setModal(true); //dialog.setLabelText(QString("Progressing using %1 thread(s)...").arg(QThread::idealThreadCount())); dialog.setWindowTitle(QString::fromLocal8Bit("ÔØÈëIFCÎļþ...")); dialog.setLabelText(QString::fromLocal8Bit("ÔØÈë....")); dialog.setMaximum(100); dialog.setMinimum(0); dialog.setValue(0); bool hide = false; int segmentationParts = 36; dialog.show(); m_firstFreeIfcObject = GetChildrenRecursively( m_ifcModel, sdaiGetEntity(m_ifcModel, (char*)L"IFCPRODUCT"), m_firstFreeIfcObject, segmentationParts, hide ); for (int i=0; i<=25; i++) { dialog.setValue(i); } m_firstFreeIfcObject = QueryIfcObjects(m_ifcModel, m_firstFreeIfcObject, L"IFCRELSPACEBOUNDARY", segmentationParts, hide); if (m_ifcObjects) { dialog.setLabelText(QString::fromLocal8Bit("ÔØÈë²ÄÖÊ....")); InitMaterials(m_ifcModel); for (int i = 26; i <= 50; i++) { dialog.setValue(i); } // »ñÈ¡Geometry dialog.setLabelText(QString::fromLocal8Bit("ÔØÈ뼸ºÎÊý¾Ý....")); GenerateGeometryNestedCall(m_ifcModel); for (int i = 51; i <= 75; i++) { dialog.setValue(i); } // »ñÈ¡Units dialog.setLabelText(QString::fromLocal8Bit("ÔØÈ뵥λÐÅÏ¢....")); GetUnits(m_ifcModel); for (int i = 76; i <= 99; i++) { dialog.setValue(i); } dialog.setLabelText(QString::fromLocal8Bit("¹¹½¨ÊôÐÔ±í....")); dialog.setMaximum(m_instanceIFCObject.size()); dialog.setValue(0); // ¹¹½¨ÊôÐÔ±í std::map<int_t, IFC__OBJECT*>::iterator it= m_instanceIFCObject.begin(); int_t i = 0; while (it != m_instanceIFCObject.end()) { if (dialog.wasCanceled()) { break; } dialog.setValue(i); IFC__OBJECT* pIFCObj = it->second; if (pIFCObj && !pIFCObj->hide) { IFC__PROPERTY__SET* ifcPropSet = NULL; CreateIfcInstanceProperties(m_ifcModel, &ifcPropSet, it->first,m_units); m_ifcProperty[it->first] = ifcPropSet; //int_t entity = sdaiGetInstanceType(it->first); //int_t index = 0; //CreateObjProList(it->first,entity, index); } it++; i++; } dialog.hide(); return TRUE; } else { dialog.hide(); return FALSE; } } else { return FALSE; } } UGbool IFCConvector::ExportUDB(UGString filename, UGString datasetName) { datasetName.Replace(_U("-"), _U("_")); // Á´½ÓÊý¾Ý¼¯ OgdcDataSource* pUDBDataSource = OgdcProviderManager::CreateOgdcDataSource(OGDC::oeFile); pUDBDataSource->m_nEngineClass = 2; pUDBDataSource->m_connection.m_strServer = filename;//_U("E:/Data/workspace.udb"); if (!((OgdcDataSource*)pUDBDataSource)->Open()) { QMessageBox::warning(NULL, QString::fromLocal8Bit("¾¯¸æ"), QString::fromLocal8Bit("´ò¿ªÊý¾ÝԴʧ°Ü£¡")); delete pUDBDataSource; pUDBDataSource = NULL; return FALSE; } // ´´½¨Ä£ÐÍÊý¾Ý¼¯ OgdcDatasetVectorInfo tempDatasetVectorInfo; tempDatasetVectorInfo.m_strName = datasetName; tempDatasetVectorInfo.m_nType = OgdcDataset::Model; OgdcDataset* pModelDataSet = pUDBDataSource->GetDataset(datasetName); if (pModelDataSet != NULL) { pUDBDataSource->DeleteDataset(datasetName); pModelDataSet = NULL; } OgdcDatasetVector* pModelDataVector = pUDBDataSource->CreateDatasetVector(tempDatasetVectorInfo); if (pModelDataVector == NULL) { QMessageBox::warning(NULL, QString::fromLocal8Bit("¾¯¸æ"), QString::fromLocal8Bit("´´½¨Êý¾Ý¼¯Ê§°Ü£¡")); delete pUDBDataSource; pUDBDataSource = NULL; return FALSE; } if (m_bIsPlaceSphere) { OgdcCoordSys prjCoordSys;// ĬÈÏΪ¾­Î³¶È×ø±ê pModelDataVector->SetCoordSys(prjCoordSys); } // ´´½¨ÊôÐÔ×Ö¶Î UGFieldInfos fieldInfos; std::set<UGString>::iterator it;// = m_objPropList.begin(); // while (it != m_objPropList.end()) // { // UGFieldInfo fieldInfo; // fieldInfo.m_strName = *it; // fieldInfo.m_nType = UGFieldInfo::Text; // fieldInfo.m_nSize = 256; // fieldInfos.Add(fieldInfo); // // it++; // } it = m_propList.begin(); UGuint i = 1; while (it != m_propList.end()) { UGString strPropName =*it; UGuint nLength = strPropName.GetLength(); UGFieldInfo fieldInfo; fieldInfo.m_nType = UGFieldInfo::Text; fieldInfo.m_nSize = 256; if (nLength > 20) { fieldInfo.m_strName = _U("Property_") + UGString::From(i); fieldInfo.m_strForeignName = *it; m_propForeign[fieldInfo.m_strForeignName] = fieldInfo.m_strName; } else { fieldInfo.m_strName = *it; } fieldInfos.Add(fieldInfo); if (nLength > 20) { fieldInfo.m_strName = _U("Property_") + UGString::From(i) + _U("_Unit"); fieldInfo.m_strForeignName = *it + _U("_Unit"); } else { fieldInfo.m_strName = *it + _U("_Unit"); } fieldInfos.Add(fieldInfo); i++; it++; } pModelDataVector->CreateFields(fieldInfos); OgdcQueryDef def; def.m_nCursorType = OgdcQueryDef::OpenDynamic; def.m_nOptions = OgdcQueryDef::Both; OgdcRecordset* pModelRecordSet = pModelDataVector->Query(def); IFCObjToGeoModel(pModelRecordSet); if (pModelRecordSet) { pModelDataVector->ReleaseRecordset(pModelRecordSet); pModelRecordSet = NULL; } if (pUDBDataSource) { delete pUDBDataSource; pUDBDataSource = NULL; pModelDataVector = NULL; } return TRUE; } void IFCConvector::setPosition(UGPoint3D & point) { m_Pos = point; } void IFCConvector::setIsPlaceSphere(UGbool bPlaceSphere) { m_bIsPlaceSphere = bPlaceSphere; } //----------------------------------------------------------------------------------------------- void IFCConvector::DeleteIfcObject(IFC__OBJECT* ifcObject) { if (ifcObject->vertices) { delete[] ifcObject->vertices; } if (ifcObject->indicesForPoints) { delete[] ifcObject->indicesForPoints; } if (ifcObject->indicesForLines) { delete[] ifcObject->indicesForLines; } if (ifcObject->indicesForFaces) { delete[] ifcObject->indicesForFaces; } if (ifcObject->indicesForLinesWireFrame) { delete[] ifcObject->indicesForLinesWireFrame; } // STRUCT_MATERIALS * materials = ifcObject->materials; // while (materials) { // STRUCT_MATERIALS * materialToRemove = materials; // materials = materials->next; // // delete materialToRemove; // } delete ifcObject; } void IFCConvector::ClearUpIfcModel() { if (m_ifcObjects) { IFC__OBJECT * ifcObject = m_ifcObjects; while (ifcObject) { IFC__OBJECT * ifcObjectToRemove = ifcObject; ifcObject = ifcObject->next; DeleteIfcObject(ifcObjectToRemove); } m_ifcObjects = NULL; m_firstFreeIfcObject = &m_ifcObjects; } m_instanceIFCObject.clear(); ClearUnits(); ClearMaterials(); ClearPropertys(); } void IFCConvector::IFCObjToGeoModel(OgdcRecordset* pRecordset) { UGuint nCount = m_instanceIFCObject.size(); if (nCount == 0) { return; } IFC__SIUNIT* pUnits = m_units; // »ñÈ¡µ¥Î» wchar_t* strUnit = GetUnit(m_units, L"LENGTHUNIT"); double unit = 1.0; if (equalStr(strUnit, L"Milli Metre")) { unit = 1000.0; } else if(equalStr(strUnit,L"Centi Metre")) { unit = 100.0; } else if (equalStr(strUnit, L"Deci Metre")) { unit = 10.0; } QProgressDialog dialog; dialog.setModal(true); dialog.setWindowTitle(QString::fromLocal8Bit("µ¼³öÊý¾Ý¼¯...")); dialog.setLabelText(QString::fromLocal8Bit("µ¼³ö......")); dialog.setMaximum(m_instanceIFCObject.size()-1); dialog.setMinimum(0); dialog.show(); std::map<int_t, IFC__OBJECT*>::iterator it = m_instanceIFCObject.begin(); UGuint i = 0; while (it != m_instanceIFCObject.end()) { if (dialog.wasCanceled()) { break; } dialog.setValue(i); IFC__OBJECT* pIFCObj = it->second; if (pIFCObj) { if (pIFCObj->hide) { it++; i++; continue; } if (pIFCObj->noPrimitivesForFaces > 0) { // ¶¥µã int_t nVerCount = pIFCObj->noVertices; float* pVertices = pIFCObj->vertices; // Ë÷Òý UGuint nIndicesCount = pIFCObj->noPrimitivesForFaces * 3; int32_t* pIndices = pIFCObj->indicesForFaces; std::vector<UGuint> ids; // È¥³ýÈßÓàµã UGReindexer3d reindexer; for (UGuint j = 0; j < nIndicesCount; j++) { UGuint index = pIndices[j]; float x = pVertices[6 * index]; float y = pVertices[6 * index + 1]; float z = pVertices[6 * index + 2]; const UGVector3d v(x , y , z); UGuint id = reindexer.Lookup(v); ids.push_back(id); } // ÐµĶ¥µãºÍË÷Òý const UGVector3d* pVert = reindexer.GetArray(); nVerCount = reindexer.GetSize(); nIndicesCount = ids.size(); // ¹Ç¼Ü¶¥µã°ü UGVertexDataPackageExact* pVertexPackExat = new UGVertexDataPackageExact; UGuint nVertexDim = pVertexPackExat->m_nVertexDimension; pVertexPackExat->SetVertexNum(nVerCount); //pVertexPackExat->SetNormalNum(nVerCount); //pVertexPackExat->SetColorNum(nVerCount); for (int_t i = 0; i < nVerCount; i++) { // ¶¥µã pVertexPackExat->m_pVertices[nVertexDim*i + 0] = pVert[i].x / unit; pVertexPackExat->m_pVertices[nVertexDim*i + 1] = pVert[i].y / unit; pVertexPackExat->m_pVertices[nVertexDim*i + 2] = pVert[i].z / unit; // ·¨Ïß //pVertexPackExat->m_pNormals[nVertexDim * i + 0] = (UGdouble)pVertices[6 * i + 3]; //pVertexPackExat->m_pNormals[nVertexDim * i + 1] = (UGdouble)pVertices[6 * i + 4]; //pVertexPackExat->m_pNormals[nVertexDim * i + 2] = (UGdouble)pVertices[6 * i + 5]; // ¶¥µãÑÕÉ« //UGColorValue3D value; //value.SetValue(255, 0, 0, 255); //pVertexPackExat->m_pVertexColor[i] = value.GetAsLongARGB(); } //---------------------------- // ¹Ç¼ÜË÷Òý UGIndexPackage* pIndexPackage = new UGIndexPackage; //pIndexPackage->m_strPassName.Add(UG_MATERTIALNAME_DEFAULT); if (nIndicesCount > 65536) { pIndexPackage->m_enIndexType = IT_32BIT; } else { pIndexPackage->m_enIndexType = IT_16BIT; } pIndexPackage->SetIndexNum(nIndicesCount); for (UGuint i=0; i<nIndicesCount; i++) { if (pIndexPackage->m_enIndexType == IT_16BIT) { pIndexPackage->m_pIndexes[i] = ids[i]; } else { UGuint* pUintIndex = (UGuint*)pIndexPackage->m_pIndexes; pUintIndex[i] = ids[i]; } } UGString strName, strMateriaName; strName.Format(_U("%d"), it->first); strMateriaName.Format(_U("%d_Material"), it->first); UGModelMaterial* pModelMaterial = IFCMaterialToUGMaterial(strMateriaName, pIFCObj->materials); pIndexPackage->m_strPassName.Add(pModelMaterial->m_strName); UGModelSkeleton* pModelSkeleton = new UGModelSkeleton; pModelSkeleton->m_strName = strName; pModelSkeleton->m_strMaterialName = pModelMaterial->m_strName; pModelSkeleton->SetExactDataTag(true); pModelSkeleton->SetExactDataPackRef(pVertexPackExat, pIndexPackage); UGModelEMapPack mapPack; mapPack.AddSkeleton(pModelSkeleton); mapPack.AddMaterial(pModelMaterial); UGModelGeode* pGeode = new UGModelGeode(); pGeode->MakeFrom(mapPack); UGModelNode* pModelNode = new UGModelNode; pModelNode->AddGeode(pGeode , pModelNode->GetDataPatcheCount() - 1); UGGeoModelPro* pModelPro = new UGGeoModelPro; pModelPro->SetModelNode(pModelNode); pModelPro->SetSpherePlaced(m_bIsPlaceSphere); pModelPro->SetPosition(m_Pos); pRecordset->AddNew(pModelPro); int_t entity = sdaiGetInstanceType(it->first); int_t index = 0; //CreateObjProList(it->first,entity, index,pRecordset); IFCPropToFiled(pRecordset, m_ifcProperty[it->first]); pRecordset->Update(); delete pModelNode; pModelNode = NULL; delete pModelPro; } } it++; i++; } dialog.hide(); } IFC__OBJECT** IFCConvector::GetChildrenRecursively(int_t ifcModel,int_t ifcParentEntity,IFC__OBJECT** firstFreeIfcObject, int_t segmentationParts,bool hide) { int_t * ifcEntityExtend = sdaiGetEntityExtent(ifcModel, ifcParentEntity), cnt = sdaiGetMemberCount(ifcEntityExtend); if ((ifcParentEntity == m_ifcSpace_TYPE) || (ifcParentEntity == m_ifcFeatureElementSubtraction_TYPE)) { hide = true; } if ((ifcParentEntity == m_ifcDistributionElement_TYPE) || (ifcParentEntity == m_ifcElectricalElement_TYPE) || (ifcParentEntity == m_ifcElementAssembly_TYPE) || (ifcParentEntity == m_ifcElementComponent_TYPE) || (ifcParentEntity == m_ifcEquipmentElement_TYPE) || (ifcParentEntity == m_ifcFeatureElement_TYPE) || (ifcParentEntity == m_ifcFurnishingElement_TYPE) || (ifcParentEntity == m_ifcTransportElement_TYPE) || (ifcParentEntity == m_ifcVirtualElement_TYPE)) { segmentationParts = 12; } if (ifcParentEntity == m_ifcReinforcingElement_TYPE) { segmentationParts = 6;// 12; } if (cnt) { wchar_t * ifcParentEntityName = nullptr; engiGetEntityName(ifcParentEntity, sdaiUNICODE, (char**)&ifcParentEntityName); firstFreeIfcObject = QueryIfcObjects(ifcModel, firstFreeIfcObject, ifcParentEntityName ,segmentationParts,hide); } cnt = engiGetEntityCount(ifcModel); for (int_t i = 0; i < cnt; i++) { int_t ifcEntity = engiGetEntityElement(ifcModel, i); if (engiGetEntityParent(ifcEntity) == ifcParentEntity) { firstFreeIfcObject = GetChildrenRecursively(ifcModel, ifcEntity, firstFreeIfcObject, segmentationParts,hide); } } return firstFreeIfcObject; } IFC__OBJECT** IFCConvector::QueryIfcObjects(int_t ifcModel,IFC__OBJECT** firstFreeIfcObject, wchar_t* entityName,int_t segmentationParts,bool hide) { int_t i, *ifcObjectInstances, noIfcObjectInstances; ifcObjectInstances = sdaiGetEntityExtentBN(ifcModel, (char*)entityName); noIfcObjectInstances = sdaiGetMemberCount(ifcObjectInstances); if (noIfcObjectInstances) { int_t ifcEntity = sdaiGetEntity(ifcModel, (char*)entityName); for (i = 0; i < noIfcObjectInstances; ++i) { int_t ifcObjectInstance = 0; engiGetAggrElement(ifcObjectInstances, i, sdaiINSTANCE, &ifcObjectInstance); IFC__OBJECT * ifcObject = CreateIfcObject(ifcEntity, ifcObjectInstance, entityName, segmentationParts,hide); (*firstFreeIfcObject) = ifcObject; firstFreeIfcObject = &ifcObject->next; //allIFCObject[ifcObjectInstance] = ifcObject; } } return firstFreeIfcObject; } IFC__OBJECT* IFCConvector::CreateIfcObject(int_t ifcEntity,int_t ifcInstance, wchar_t* entityName, int_t segmentationParts,bool hide) { IFC__OBJECT * ifcObject = new IFC__OBJECT; // if (hide) { // ifcObject->selectState = TI_UNCHECKED; // } // else { // ifcObject->selectState = TI_CHECKED; // } ifcObject->noVertices = 0; ifcObject->vertices = 0; ifcObject->next = nullptr; ifcObject->entityName = entityName; ifcObject->hide = hide; ifcObject->segmentationParts = segmentationParts; ifcObject->materials = 0; //ifcObject->vecMin.x = 0; //ifcObject->vecMin.y = 0; //ifcObject->vecMin.z = 0; //ifcObject->vecMax.x = 0; //ifcObject->vecMax.y = 0; //ifcObject->vecMax.z = 0; ifcObject->ifcInstance = ifcInstance; ifcObject->ifcEntity = ifcEntity; // if (hide) { // ifcObject->ifcItemCheckedAtStartup = false; // } else { // ifcObject->ifcItemCheckedAtStartup = true; // } // ifcObject->treeItemGeometry = 0; // ifcObject->treeItemProperties = 0; ifcObject->noVertices = 0; ifcObject->vertices = 0; ifcObject->vertexOffset = 0; ifcObject->noPrimitivesForPoints = 0; ifcObject->indicesForPoints = 0; ifcObject->indexOffsetForPoints = 0; ifcObject->noPrimitivesForLines = 0; ifcObject->indicesForLines = 0; ifcObject->indexOffsetForLines = 0; ifcObject->noPrimitivesForFaces = 0; ifcObject->indicesForFaces = 0; ifcObject->indexOffsetForFaces = 0; ifcObject->noPrimitivesForWireFrame = 0; ifcObject->indicesForLinesWireFrame = 0; ifcObject->indexOffsetForWireFrame = 0; return ifcObject; } void IFCConvector::GenerateGeometryNestedCall(int_t ifcModel) { //int objectCnt = 0; IFC__OBJECT * ifcObject = m_ifcObjects; // while (ifcObject) { // objectCnt++; // ifcObject = ifcObject->next; // } // // ifcObject = * while (ifcObject) { // // Get Geometry // int_t setting = 0, mask = 0; mask += flagbit2; // PRECISION (32/64 bit) mask += flagbit3; // INDEX ARRAY (32/64 bit) mask += flagbit5; // NORMALS mask += flagbit8; // TRIANGLES mask += flagbit9; // LINES mask += flagbit10; // POINTS mask += flagbit12; // WIREFRAME setting += 0; // SINGLE PRECISION (float) setting += 0; // 32 BIT INDEX ARRAY (Int32) setting += flagbit5; // NORMALS ON setting += flagbit8; // TRIANGLES ON setting += flagbit9; // LINES ON setting += flagbit10; // POINTS ON setting += flagbit12; // WIREFRAME ON setFormat(ifcModel, setting, mask); setFilter(ifcModel, flagbit1, flagbit1); /**/ circleSegments(ifcObject->segmentationParts, 5); GenerateWireFrameGeometry(ifcModel, ifcObject); cleanMemory(ifcModel, 0); ifcObject = ifcObject->next; } } void IFCConvector::GenerateWireFrameGeometry(int_t ifcModel, IFC__OBJECT* ifcObject) { if (ifcObject && ifcObject->ifcInstance) { int64_t noVertices = 0, noIndices = 0; CalculateInstance((int_t)ifcObject->ifcInstance, &noVertices, &noIndices, nullptr); int64_t owlModel = 0, owlInstance = 0; if (noVertices && noIndices) { owlGetModel( ifcModel, &owlModel ); owlGetInstance( ifcModel, ifcObject->ifcInstance, &owlInstance ); } if (noVertices && noIndices) { ifcObject->noVertices = (int_t)noVertices; ifcObject->vertices = new float[(int)noVertices * 6]; int32_t * indices = new int32_t[(int)noIndices]; UpdateInstanceVertexBuffer(owlInstance, ifcObject->vertices); UpdateInstanceIndexBuffer(owlInstance, indices); // int64_t owlModel = 0, owlInstance = 0; if (m_firstItemWithGeometryPassed == false) { // owlGetModel(ifcModel, &owlModel); // owlGetInstance(ifcModel, ifcObject->ifcInstance, &owlInstance); // ASSERT(owlModel && owlInstance); double transformationMatrix[12], minVector[3], maxVector[3]; SetBoundingBoxReference(owlInstance, transformationMatrix, minVector, maxVector); if ((-1000000 > transformationMatrix[9] || transformationMatrix[9] > 1000000) || (-1000000 > transformationMatrix[10] || transformationMatrix[10] > 1000000) || (-1000000 > transformationMatrix[11] || transformationMatrix[11] > 1000000)) { SetVertexBufferOffset(ifcModel, -transformationMatrix[9], -transformationMatrix[10], -transformationMatrix[11]); ClearedInstanceExternalBuffers(owlInstance); UpdateInstanceVertexBuffer((__int64)ifcObject->ifcInstance, ifcObject->vertices); UpdateInstanceIndexBuffer((__int64)ifcObject->ifcInstance, indices); } } m_firstItemWithGeometryPassed = true; ifcObject->noPrimitivesForWireFrame = 0; //ASSERT(ifcObject->indicesForLinesWireFrame == 0); int32_t * indicesForLinesWireFrame = new int32_t[2 * (int)noIndices]; ifcObject->noVertices = (int_t)noVertices; //ASSERT(ifcObject->indicesForFaces == 0); int32_t * indicesForFaces = new int32_t[(int)noIndices]; int32_t * indicesForLines = new int32_t[(int)noIndices]; int32_t * indicesForPoints = new int32_t[(int)noIndices]; int_t faceCnt = getConceptualFaceCnt(ifcObject->ifcInstance); int_t * maxIndex = new int_t[faceCnt], *primitivesForFaces = new int_t[faceCnt]; for (int_t j = 0; j < faceCnt; j++) { int_t startIndexTriangles = 0, noIndicesTrangles = 0, startIndexLines = 0, noIndicesLines = 0, startIndexPoints = 0, noIndicesPoints = 0, startIndexFacesPolygons = 0, noIndicesFacesPolygons = 0; getConceptualFaceEx( ifcObject->ifcInstance, j, &startIndexTriangles, &noIndicesTrangles, &startIndexLines, &noIndicesLines, &startIndexPoints, &noIndicesPoints, &startIndexFacesPolygons, &noIndicesFacesPolygons, 0, 0 ); if (j) { maxIndex[j] = maxIndex[j - 1]; } else { maxIndex[j] = 0; } if (noIndicesTrangles && maxIndex[j] < startIndexTriangles + noIndicesTrangles) { maxIndex[j] = startIndexTriangles + noIndicesTrangles; } if (noIndicesLines && maxIndex[j] < startIndexLines + noIndicesLines) { maxIndex[j] = startIndexLines + noIndicesLines; } if (noIndicesPoints && maxIndex[j] < startIndexPoints + noIndicesPoints) { maxIndex[j] = startIndexPoints + noIndicesPoints; } if (noIndicesFacesPolygons && maxIndex[j] < startIndexFacesPolygons + noIndicesFacesPolygons) { maxIndex[j] = startIndexFacesPolygons + noIndicesFacesPolygons; } int_t i = 0; while (i < noIndicesTrangles) { indicesForFaces[ifcObject->noPrimitivesForFaces * 3 + i] = indices[startIndexTriangles + i]; i++; } ifcObject->noPrimitivesForFaces += noIndicesTrangles / 3; primitivesForFaces[j] = noIndicesTrangles / 3; i = 0; while (i < noIndicesLines) { indicesForLines[ifcObject->noPrimitivesForLines * 2 + i] = indices[startIndexLines + i]; i++; } ifcObject->noPrimitivesForLines += noIndicesLines / 2; i = 0; while (i < noIndicesPoints) { indicesForPoints[ifcObject->noPrimitivesForPoints * 1 + i] = indices[startIndexPoints + i]; i++; } ifcObject->noPrimitivesForPoints += noIndicesPoints / 1; i = 0; int32_t lastItem = -1; while (i < noIndicesFacesPolygons) { if (lastItem >= 0 && indices[startIndexFacesPolygons + i] >= 0) { indicesForLinesWireFrame[2 * ifcObject->noPrimitivesForWireFrame + 0] = lastItem; indicesForLinesWireFrame[2 * ifcObject->noPrimitivesForWireFrame + 1] = indices[startIndexFacesPolygons + i]; ifcObject->noPrimitivesForWireFrame++; } lastItem = indices[startIndexFacesPolygons + i]; i++; } } ifcObject->indicesForPoints = new int32_t[3 * ifcObject->noPrimitivesForPoints]; ifcObject->indicesForLines = new int32_t[3 * ifcObject->noPrimitivesForLines]; ifcObject->indicesForFaces = new int32_t[3 * ifcObject->noPrimitivesForFaces]; ifcObject->indicesForLinesWireFrame = new int32_t[2 * ifcObject->noPrimitivesForWireFrame]; memcpy(ifcObject->indicesForPoints, indicesForPoints, 1 * ifcObject->noPrimitivesForPoints * sizeof(int32_t)); memcpy(ifcObject->indicesForLines, indicesForLines, 2 * ifcObject->noPrimitivesForLines * sizeof(int32_t)); memcpy(ifcObject->indicesForFaces, indicesForFaces, 3 * ifcObject->noPrimitivesForFaces * sizeof(int32_t)); memcpy(ifcObject->indicesForLinesWireFrame, indicesForLinesWireFrame, 2 * ifcObject->noPrimitivesForWireFrame * sizeof(int32_t)); delete[] indicesForLinesWireFrame; delete[] indicesForFaces; delete[] indicesForLines; delete[] indicesForPoints; delete[] indices; ifcObject->materials = IFCObjectMaterial(ifcModel, ifcObject->ifcInstance); if (ifcObject->materials) { IFC_MATERIALS * materials = ifcObject->materials; if (materials->next) { __int64 indexBufferSize = 0, indexArrayOffset = 0, j = 0; while (materials) { //ASSERT(materials->__indexBufferSize >= 0); //ASSERT(materials->__noPrimitivesForFaces == 0); indexBufferSize += materials->__indexBufferSize; materials->__indexArrayOffset = indexArrayOffset; while (j < faceCnt && maxIndex[j] <= indexBufferSize) { materials->__noPrimitivesForFaces += primitivesForFaces[j]; indexArrayOffset += 3 * primitivesForFaces[j]; j++; } materials = materials->next; } //ASSERT(j == faceCnt && indexBufferSize == noIndices); } else { //ASSERT(materials->__indexBufferSize == -1); materials->__indexArrayOffset = 0; materials->__noPrimitivesForFaces = ifcObject->noPrimitivesForFaces; } } else { //ASSERT(false); } delete[] primitivesForFaces; delete[] maxIndex; m_instanceIFCObject[ifcObject->ifcInstance] = ifcObject; } else { //ASSERT(ifcObject->noVertices == 0 && ifcObject->noPrimitivesForPoints == 0 && ifcObject->noPrimitivesForLines == 0 && ifcObject->noPrimitivesForFaces == 0 && ifcObject->noPrimitivesForWireFrame == 0); //ifcObject->selectState = TI_NONE; //ASSERT(ifcObject->treeItemModel == nullptr); //ASSERT(ifcObject->treeItemSpaceBoundary == nullptr); } } } //--------------------------------------------------------------------------------------- IFC_MATERIALS* IFCConvector::IFCObjectMaterial(int_t ifcModel, int_t ifcInstance) { IFC_MATERIAL_META_INFO * materialMetaInfo = nullptr, ** ppMaterialMetaInfo = &materialMetaInfo; IFC_MATERIAL * returnedMaterial = nullptr; int_t ifcProductRepresentationInstance = 0; sdaiGetAttrBN(ifcInstance, (char*)L"Representation", sdaiINSTANCE, &ifcProductRepresentationInstance); if (ifcProductRepresentationInstance != 0) { GetRGB_productDefinitionShape(ifcModel, ifcProductRepresentationInstance, ppMaterialMetaInfo); } bool noMaterialFound = false; if (materialMetaInfo && (*ppMaterialMetaInfo)->next == 0 && (*ppMaterialMetaInfo)->child == 0) { //ASSERT((*ppMaterialMetaInfo) == materialMetaInfo); if ((materialMetaInfo->material->ambient.A == -1) && (materialMetaInfo->material->diffuse.A == -1) && (materialMetaInfo->material->emissive.A == -1) && (materialMetaInfo->material->specular.A == -1)) { noMaterialFound = true; } } if (noMaterialFound) { // // Look for material associations // int_t ifcRelAssociatesMaterialEntity = sdaiGetEntity(ifcModel, (char*)L"IFCRELASSOCIATESMATERIAL"), *ifcRelAssociatesAggr = nullptr, ifcRelAssociatesAggrCnt, i = 0; sdaiGetAttrBN(ifcInstance, (char*)L"HasAssociations", sdaiAGGR, &ifcRelAssociatesAggr); ifcRelAssociatesAggrCnt = sdaiGetMemberCount(ifcRelAssociatesAggr); while (i < ifcRelAssociatesAggrCnt) { int_t ifcRelAssociatesInstance = 0; engiGetAggrElement(ifcRelAssociatesAggr, i, sdaiINSTANCE, &ifcRelAssociatesInstance); if (sdaiGetInstanceType(ifcRelAssociatesInstance) == ifcRelAssociatesMaterialEntity) { GetRGB_relAssociatesMaterial(ifcModel, ifcRelAssociatesInstance, materialMetaInfo->material); } i++; } } if (materialMetaInfo) { bool unique = true, defaultColorIsUsed = false; IFC_MATERIAL * material = nullptr; //DEBUG__localObjectColor = materialMetaInfo; MinimizeMaterialItems(materialMetaInfo, &material, &unique, &defaultColorIsUsed); if (unique) { returnedMaterial = material; } else { returnedMaterial = 0; } if (defaultColorIsUsed) { // // Color not found, check if we can find colors via propertySets // /* STRUCT__PROPERTY__SET * propertySet = ifcItem->propertySets; while (propertySet) { if (equals(propertySet->name, L"Pset_Draughting")) { STRUCT__PROPERTY * _property = propertySet->properties; while (_property) { if (equals(_property->name, L"Red")) { int_t value = _wtoi(_property->nominalValue); } if (equals(_property->name, L"Green")) { int_t value = _wtoi(_property->nominalValue); } if (equals(_property->name, L"Blue")) { int_t value = _wtoi(_property->nominalValue); } _property = _property->next; } } propertySet = propertySet->next; } // */ } } if (returnedMaterial) { DeleteMaterialMetaInfo(materialMetaInfo); return CreateMaterials(returnedMaterial, ifcModel, ifcInstance); } else { IFC_MATERIALS * materials = 0, ** materialsRef = &materials; if (materialMetaInfo) { WalkThroughGeometry__transformation((int64_t)ifcModel, (int64_t)ifcInstance, &materialsRef, &materialMetaInfo); } DeleteMaterialMetaInfo(materialMetaInfo); if (materials) { return materials; } else { return CreateMaterials(m_firstMaterial, ifcModel, ifcInstance); } } } UGModelMaterial* IFCConvector::IFCMaterialToUGMaterial(UGString strMaterilName,IFC_MATERIALS * pIFCMaterials) { UGModelMaterial* pModelMaterial = new UGModelMaterial; if (pIFCMaterials == NULL || pIFCMaterials->material == NULL) { pModelMaterial->MakeDefault(); return pModelMaterial; } pModelMaterial->m_strName = strMaterilName; IFC_MATERIAL* pIFCMaterial = pIFCMaterials->material; IFC_MATERIAL* temp = pIFCMaterial->next; // while (temp) // { // pIFCMaterial = temp; // temp = pIFCMaterial->next; // } UGTechnique *t = new UGTechnique(); pModelMaterial->mTechniques.push_back(t); UGPass* pass = t->createPass(); pass->m_strName = strMaterilName; if (pIFCMaterial->ambient.R != -1) { pass->m_Ambient.r = pIFCMaterial->ambient.R; pass->m_Ambient.g = pIFCMaterial->ambient.G; pass->m_Ambient.b = pIFCMaterial->ambient.B; pass->m_Ambient.a = pIFCMaterial->transparency; } if (pIFCMaterial->diffuse.R != -1) { pass->m_Diffuse.r = pIFCMaterial->diffuse.R; pass->m_Diffuse.g = pIFCMaterial->diffuse.G; pass->m_Diffuse.b = pIFCMaterial->diffuse.B; pass->m_Diffuse.a = pIFCMaterial->transparency; } if (pIFCMaterial->specular.R != -1) { pass->m_Specular.r = pIFCMaterial->specular.R; pass->m_Specular.g = pIFCMaterial->specular.G; pass->m_Specular.b = pIFCMaterial->specular.B; pass->m_Specular.a = pIFCMaterial->transparency; } if (pIFCMaterial->emissive.R != -1) { pass->m_SelfIllumination.r = pIFCMaterial->emissive.R; pass->m_SelfIllumination.g = pIFCMaterial->emissive.G; pass->m_SelfIllumination.b = pIFCMaterial->emissive.B; pass->m_SelfIllumination.a = pIFCMaterial->transparency; } //pass->m_Specular.r = pIFCMaterial->specular.R; //pass->m_Specular.g = pIFCMaterial->specular.G; //pass->m_Specular.b = pIFCMaterial->specular.B; //pass->m_Specular.a = pIFCMaterial->transparency; //pass->m_SelfIllumination.r = pIFCMaterial->emissive.R; //pass->m_SelfIllumination.g = pIFCMaterial->emissive.G; //pass->m_SelfIllumination.b = pIFCMaterial->emissive.B; //pass->m_SelfIllumination.a = pIFCMaterial->transparency; pass->m_Shininess = pIFCMaterial->shininess; return pModelMaterial; } void IFCConvector::InitMaterials(int_t ifcObject) { m_firstMaterial = NULL; m_lastMaterial = NULL; m_defaultMaterial = CreateMaterial(); m_defaultMaterial->ambient.R = -1; m_defaultMaterial->ambient.G = -1; m_defaultMaterial->ambient.B = -1; m_defaultMaterial->ambient.A = -1; m_defaultMaterial->diffuse.R = -1; m_defaultMaterial->diffuse.G = -1; m_defaultMaterial->diffuse.B = -1; m_defaultMaterial->diffuse.A = -1; m_defaultMaterial->specular.R = -1; m_defaultMaterial->specular.G = -1; m_defaultMaterial->specular.B = -1; m_defaultMaterial->specular.A = -1; m_defaultMaterial->emissive.R = -1; m_defaultMaterial->emissive.G = -1; m_defaultMaterial->emissive.B = -1; m_defaultMaterial->emissive.A = -1; m_defaultMaterial->transparency = 1; m_defaultMaterial->shininess = 1; m_defaultMaterial->active = true; m_rdfClassTransformation = GetClassByName((int64_t)ifcObject, "Transformation"); m_rdfClassCollection = GetClassByName((int64_t)ifcObject, "Collection"); m_owlDataTypePropertyExpressID = GetPropertyByName((int64_t)ifcObject, "expressID"); m_owlObjectTypePropertyMatrix = GetPropertyByName((int64_t)ifcObject, "matrix"); m_owlObjectTypePropertyObject = GetPropertyByName((int64_t)ifcObject, "object"); m_owlObjectTypePropertyObjects = GetPropertyByName((int64_t)ifcObject, "objects"); } IFC_MATERIAL* IFCConvector::CreateMaterial() { IFC_MATERIAL* material = new IFC_MATERIAL; material->ambient.R = -1; material->ambient.G = -1; material->ambient.B = -1; material->ambient.A = -1; material->diffuse.R = -1; material->diffuse.G = -1; material->diffuse.B = -1; material->diffuse.A = -1; material->specular.R = -1; material->specular.G = -1; material->specular.B = -1; material->specular.A = -1; material->emissive.R = -1; material->emissive.G = -1; material->emissive.B = -1; material->emissive.A = -1; material->transparency = -1; material->shininess = -1; material->next = 0; material->prev = m_lastMaterial; if (m_firstMaterial == 0) { //ASSERT(lastMaterial == 0); m_firstMaterial = material; } m_lastMaterial = material; if (m_lastMaterial->prev) { m_lastMaterial->prev->next = m_lastMaterial; } //material->MTRL = nullptr; material->active = false; return material; } IFC_MATERIALS* IFCConvector::CreateMaterials(IFC_MATERIAL * material) { IFC_MATERIALS * materials = new IFC_MATERIALS; materials->material = material; materials->next = nullptr; materials->__indexOffsetForFaces = 0; materials->__indexArrayOffset = 0; materials->__noPrimitivesForFaces = 0; materials->__indexBufferSize = 0; return materials; } IFC_MATERIALS* IFCConvector::CreateMaterials(IFC_MATERIAL * material,int_t ifcModel,int_t ifcInstance) { IFC_MATERIALS * materials = CreateMaterials(material); materials->__noPrimitivesForFaces = 0; materials->__indexBufferSize = -1; return materials; } IFC_MATERIAL_META_INFO* IFCConvector::CreateMaterialMetaInfo(int_t ifcInstance) { IFC_MATERIAL_META_INFO * materialMetaInfo = new IFC_MATERIAL_META_INFO; //new_matMI++; if (ifcInstance) { materialMetaInfo->expressID = internalGetP21Line(ifcInstance); } else { materialMetaInfo->expressID = -1; } materialMetaInfo->isPoint = false; materialMetaInfo->isEdge = false; materialMetaInfo->isShell = false; materialMetaInfo->material = CreateMaterial(); materialMetaInfo->child = 0; materialMetaInfo->next = 0; return materialMetaInfo; } void IFCConvector::ClearMaterials() { IFC_MATERIAL * currentMaterial = m_firstMaterial; while (currentMaterial) { IFC_MATERIAL * materialToDelete = NULL; if (currentMaterial != m_defaultMaterial) { materialToDelete = currentMaterial; } currentMaterial = currentMaterial->next; if (materialToDelete) { delete materialToDelete; materialToDelete = NULL; } } if (m_defaultMaterial) { delete m_defaultMaterial; } m_firstMaterial = NULL; m_lastMaterial = NULL; m_defaultMaterial = NULL; } void IFCConvector::DeleteMaterial(IFC_MATERIAL * material) { if (material) { //totalAllocatedMaterial--; //ASSERT(material->active == false); //ASSERT(DEBUG_colorLoopConsistanceCheck()); IFC_MATERIAL * prev = material->prev, *next = material->next; if (prev == 0) { //ASSERT(firstMaterial == next->prev); } if (next == 0) { //ASSERT(lastMaterial == prev->next); } if (prev) { //ASSERT(prev->next == material); prev->next = next; } else { //ASSERT(firstMaterial == material); m_firstMaterial = next; next->prev = 0; } if (next) { //ASSERT(next->prev == material); next->prev = prev; } else { //ASSERT(lastMaterial == material); m_lastMaterial = prev; //ASSERT(prev->next == 0); } material->active = false; delete material; } } void IFCConvector::DeleteMaterialMetaInfo(IFC_MATERIAL_META_INFO * materialMetaInfo) { while (materialMetaInfo) { DeleteMaterialMetaInfo(materialMetaInfo->child); IFC_MATERIAL_META_INFO * materialMetaInfoToDelete = materialMetaInfo; materialMetaInfo = materialMetaInfo->next; //del_matMI++; delete materialMetaInfoToDelete; } } void IFCConvector::MinimizeMaterialItems(IFC_MATERIAL_META_INFO * materialMetaInfo, IFC_MATERIAL ** ppMaterial, bool * pUnique, bool * pDefaultColorIsUsed) { while (materialMetaInfo) { // // Check nested child object (i.e. Mapped Items) // if (materialMetaInfo->child) { //ASSERT(materialMetaInfo->material->ambient.R == -1); //ASSERT(materialMetaInfo->material->active == false); DeleteMaterial(materialMetaInfo->material); materialMetaInfo->material = 0; MinimizeMaterialItems(materialMetaInfo->child, ppMaterial, pUnique, pDefaultColorIsUsed); } // // Complete Color // IFC_MATERIAL * material = materialMetaInfo->material; if (material) { if (material->ambient.R == -1) { materialMetaInfo->material = m_defaultMaterial; DeleteMaterial(material); } else { if (material->diffuse.R == -1) { material->diffuse.R = material->ambient.R; material->diffuse.G = material->ambient.G; material->diffuse.B = material->ambient.B; material->diffuse.A = material->ambient.A; } if (material->specular.R == -1) { material->specular.R = material->ambient.R; material->specular.G = material->ambient.G; material->specular.B = material->ambient.B; material->specular.A = material->ambient.A; } } } else { //ASSERT(materialMetaInfo->child); } //ASSERT(DEBUG_colorLoopConsistanceCheck()); // // Merge the same colors // material = materialMetaInfo->material; if (material && material != m_defaultMaterial) { bool adjusted = false; //ASSERT(material->active == false); IFC_MATERIAL * materialLoop = m_firstMaterial->next; //ASSERT(firstMaterial == defaultMaterial); while (materialLoop) { if ((materialLoop->active) && (material->transparency == materialLoop->transparency) && (material->ambient.R == materialLoop->ambient.R) && (material->ambient.G == materialLoop->ambient.G) && (material->ambient.B == materialLoop->ambient.B) && (material->ambient.A == materialLoop->ambient.A) && (material->diffuse.R == materialLoop->diffuse.R) && (material->diffuse.G == materialLoop->diffuse.G) && (material->diffuse.B == materialLoop->diffuse.B) && (material->diffuse.A == materialLoop->diffuse.A) && (material->specular.R == materialLoop->specular.R) && (material->specular.G == materialLoop->specular.G) && (material->specular.B == materialLoop->specular.B) && (material->specular.A == materialLoop->specular.A)) { materialMetaInfo->material = materialLoop; DeleteMaterial(material); materialLoop = 0; adjusted = true; } else { if (materialLoop->active == false) { while (materialLoop) { //ASSERT(materialLoop->active == false); materialLoop = materialLoop->next; } materialLoop = 0; } else { materialLoop = materialLoop->next; } } } if (adjusted) { //ASSERT(materialMetaInfo->material->active); } else { //ASSERT(materialMetaInfo->material->active == false); materialMetaInfo->material->active = true; } //ASSERT(materialLoop == 0 || (materialLoop == defaultMaterial && materialLoop->next == 0)); } // // Assign default color in case of no color and no children // if (materialMetaInfo->material == 0 && materialMetaInfo->child == 0) { materialMetaInfo->material = m_defaultMaterial; } // // Check if unique // material = materialMetaInfo->material; if ((*ppMaterial)) { if ((*ppMaterial) != material) { if (material == 0 && materialMetaInfo->child) { } else { (*pUnique) = false; } } } else { //ASSERT((*pUnique) == true); (*ppMaterial) = material; } if (material == m_defaultMaterial) { (*pDefaultColorIsUsed) = true; } materialMetaInfo = materialMetaInfo->next; } } void IFCConvector::GetRGB_productDefinitionShape(int_t model, int_t ifcObjectInstance, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo) { int_t * representations_set = nullptr, representations_cnt, i = 0; sdaiGetAttrBN(ifcObjectInstance, (char*)L"Representations", sdaiAGGR, &representations_set); representations_cnt = sdaiGetMemberCount(representations_set); while (i < representations_cnt) { int_t ifcShapeRepresentation = 0; engiGetAggrElement(representations_set, i, sdaiINSTANCE, &ifcShapeRepresentation); if (ifcShapeRepresentation != 0) { GetRGB_shapeRepresentation( model, ifcShapeRepresentation, ppMaterialMetaInfo ); } i++; } } void IFCConvector::GetRGB_shapeRepresentation(int_t model, int_t ifcShapeRepresentationInstance, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo) { wchar_t * pRepresentationIdentifier = nullptr, *RepresentationType = nullptr; sdaiGetAttrBN(ifcShapeRepresentationInstance, (char*)L"RepresentationIdentifier", sdaiUNICODE, &pRepresentationIdentifier); sdaiGetAttrBN(ifcShapeRepresentationInstance, (char*)L"RepresentationType", sdaiUNICODE, &RepresentationType); if ((__equals(pRepresentationIdentifier, L"Body") || __equals(pRepresentationIdentifier, L"Mesh") || __equals(pRepresentationIdentifier, L"Facetation")) && !__equals(RepresentationType, L"BoundingBox")) { int_t * geometry_set = nullptr, geometry_cnt, i = 0; sdaiGetAttrBN(ifcShapeRepresentationInstance, (char*)L"Items", sdaiAGGR, &geometry_set); geometry_cnt = sdaiGetMemberCount(geometry_set); i = 0; while (i < geometry_cnt) { int_t geometryInstance = 0, styledItemInstance = 0; engiGetAggrElement(geometry_set, i, sdaiINSTANCE, &geometryInstance); //ASSERT((*ppMaterialMetaInfo) == 0); (*ppMaterialMetaInfo) = CreateMaterialMetaInfo(geometryInstance); sdaiGetAttrBN(geometryInstance, (char*)L"StyledByItem", sdaiINSTANCE, &styledItemInstance); if (styledItemInstance != 0) { GetRGB_styledItem( #ifdef _DEBUG model, #endif styledItemInstance, (*ppMaterialMetaInfo)->material ); } else { SearchDeeper(model, geometryInstance, ppMaterialMetaInfo, (*ppMaterialMetaInfo)->material); } ppMaterialMetaInfo = &(*ppMaterialMetaInfo)->next; i++; } } } void IFCConvector::GetRGB_styledItem( #ifdef _DEBUG int_t model, #endif int_t ifcStyledItemInstance, IFC_MATERIAL * material ) { int_t * styles_set = nullptr, styles_cnt, i = 0; sdaiGetAttrBN(ifcStyledItemInstance, (char*)L"Styles", sdaiAGGR, &styles_set); styles_cnt = sdaiGetMemberCount(styles_set); while (i < styles_cnt) { int_t presentationStyleAssignmentInstance = 0; engiGetAggrElement(styles_set, i, sdaiINSTANCE, &presentationStyleAssignmentInstance); if (presentationStyleAssignmentInstance != 0) { GetRGB_presentationStyleAssignment( #ifdef _DEBUG model, #endif presentationStyleAssignmentInstance, material ); } i++; } } void IFCConvector::GetRGB_presentationStyleAssignment( #ifdef _DEBUG int_t model, #endif int_t presentationStyleAssignmentInstance, IFC_MATERIAL * material ) { int_t * styles_set = nullptr, styles_cnt, i = 0; sdaiGetAttrBN(presentationStyleAssignmentInstance, (char*)L"Styles", sdaiAGGR, &styles_set); styles_cnt = sdaiGetMemberCount(styles_set); while (i < styles_cnt) { int_t surfaceStyleInstance = 0; engiGetAggrElement(styles_set, i, sdaiINSTANCE, &surfaceStyleInstance); if (surfaceStyleInstance != 0) { GetRGB_surfaceStyle( #ifdef _DEBUG model, #endif surfaceStyleInstance, material ); } i++; } } void IFCConvector::GetRGB_surfaceStyle( #ifdef _DEBUG int_t model, #endif int_t surfaceStyleInstance, IFC_MATERIAL * material ) { int_t * styles_set = nullptr, styles_cnt; sdaiGetAttrBN(surfaceStyleInstance, (char*)L"Styles", sdaiAGGR, &styles_set); styles_cnt = sdaiGetMemberCount(styles_set); for (int_t i = 0; i < styles_cnt; i++) { int_t surfaceStyleRenderingInstance = 0, SurfaceColourInstance = 0, SpecularColourInstance = 0, DiffuseColourInstance = 0; engiGetAggrElement(styles_set, i, sdaiINSTANCE, &surfaceStyleRenderingInstance); #ifdef _DEBUG int_t surfaceStyleRenderingEntity = sdaiGetEntity(model, (char*)L"IFCSURFACESTYLERENDERING"); #endif //ASSERT(sdaiGetInstanceType(surfaceStyleRenderingInstance) == surfaceStyleRenderingEntity); double transparency = 0; sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"Transparency", sdaiREAL, &transparency); material->transparency = 1 - (float)transparency; sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"SurfaceColour", sdaiINSTANCE, &SurfaceColourInstance); if (SurfaceColourInstance != 0) { GetRGB_colourRGB(SurfaceColourInstance, &material->ambient); } else { //ASSERT(false); } sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"DiffuseColour", sdaiINSTANCE, &DiffuseColourInstance); if (DiffuseColourInstance != 0) { GetRGB_colourRGB(DiffuseColourInstance, &material->diffuse); } else { int_t ADB = 0; sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"DiffuseColour", sdaiADB, &ADB); if (ADB) { double value = 0; sdaiGetADBValue((void *)ADB, sdaiREAL, &value); material->diffuse.R = (float)value * material->ambient.R; material->diffuse.G = (float)value * material->ambient.G; material->diffuse.B = (float)value * material->ambient.B; } } sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"SpecularColour", sdaiINSTANCE, &SpecularColourInstance); if (SpecularColourInstance != 0) { GetRGB_colourRGB(SpecularColourInstance, &material->specular); } else { int_t ADB = 0; sdaiGetAttrBN(surfaceStyleRenderingInstance, (char*)L"SpecularColour", sdaiADB, &ADB); if (ADB) { double value = 0; sdaiGetADBValue((void *)ADB, sdaiREAL, &value); material->specular.R = (float)value * material->ambient.R; material->specular.G = (float)value * material->ambient.G; material->specular.B = (float)value * material->ambient.B; } } } } void IFCConvector::GetRGB_colourRGB(int_t SurfaceColourInstance, IFC_COLOR * color) { double red = 0, green = 0, blue = 0; sdaiGetAttrBN(SurfaceColourInstance, (char*)L"Red", sdaiREAL, &red); sdaiGetAttrBN(SurfaceColourInstance, (char*)L"Green", sdaiREAL, &green); sdaiGetAttrBN(SurfaceColourInstance, (char*)L"Blue", sdaiREAL, &blue); color->R = (float)red; color->G = (float)green; color->B = (float)blue; } void IFCConvector::GetRGB_relAssociatesMaterial(int_t model, int_t ifcRelAssociatesMaterialInstance, IFC_MATERIAL * material) { int_t ifcMaterialEntity = sdaiGetEntity(model, (char*)L"IFCMATERIAL"), ifcMaterialLayerSetUsageEntity = sdaiGetEntity(model, (char*)L"IFCMATERIALLAYERSETUSAGE"), ifcMaterialLayerSetEntity = sdaiGetEntity(model, (char*)L"IFCMATERIALLAYERSET"), ifcMaterialLayerEntity = sdaiGetEntity(model, (char*)L"IFCMATERIALLAYER"), ifcMaterialSelectInstance = 0; sdaiGetAttrBN(ifcRelAssociatesMaterialInstance, (char*)L"RelatingMaterial", sdaiINSTANCE, &ifcMaterialSelectInstance); if (sdaiGetInstanceType(ifcMaterialSelectInstance) == ifcMaterialEntity) { GetRGB_ifcMaterial(model, ifcMaterialSelectInstance, material); } else if (sdaiGetInstanceType(ifcMaterialSelectInstance) == ifcMaterialLayerSetUsageEntity) { GetRGB_ifcMaterialLayerSetUsage(model, ifcMaterialSelectInstance, material); } else if (sdaiGetInstanceType(ifcMaterialSelectInstance) == ifcMaterialLayerSetEntity) { GetRGB_ifcMaterialLayerSet(model, ifcMaterialSelectInstance, material); } else if (sdaiGetInstanceType(ifcMaterialSelectInstance) == ifcMaterialLayerEntity) { GetRGB_ifcMaterialLayer(model, ifcMaterialSelectInstance, material); } } void IFCConvector::GetRGB_ifcMaterial(int_t model, int_t ifcMaterialInstance, IFC_MATERIAL * material) { int_t * ifcMaterialDefinitionRepresentationAggr = nullptr, ifcMaterialDefinitionRepresentationAggrCnt = 0, i = 0; sdaiGetAttrBN(ifcMaterialInstance, (char*)L"HasRepresentation", sdaiAGGR, &ifcMaterialDefinitionRepresentationAggr); ifcMaterialDefinitionRepresentationAggrCnt = sdaiGetMemberCount(ifcMaterialDefinitionRepresentationAggr); while (i < ifcMaterialDefinitionRepresentationAggrCnt) { int_t ifcMaterialDefinitionRepresentationInstance = 0; engiGetAggrElement(ifcMaterialDefinitionRepresentationAggr, i, sdaiINSTANCE, &ifcMaterialDefinitionRepresentationInstance); if (sdaiGetInstanceType(ifcMaterialDefinitionRepresentationInstance) == sdaiGetEntity(model, (char*)L"IFCMATERIALDEFINITIONREPRESENTATION")) { GetRGB_ifcMaterialDefinitionRepresentation(model, ifcMaterialDefinitionRepresentationInstance, material); } else { //ASSERT(false); } i++; } } void IFCConvector::GetRGB_ifcMaterialDefinitionRepresentation(int_t model, int_t ifcMaterialDefinitionRepresentationInstance, IFC_MATERIAL * material) { int_t * ifcRepresentationAggr = nullptr, ifcRepresentationAggrCnt = 0, i = 0; sdaiGetAttrBN(ifcMaterialDefinitionRepresentationInstance, (char*)L"Representations", sdaiAGGR, &ifcRepresentationAggr); ifcRepresentationAggrCnt = sdaiGetMemberCount(ifcRepresentationAggr); while (i < ifcRepresentationAggrCnt) { int_t ifcRepresentationInstance = 0; engiGetAggrElement(ifcRepresentationAggr, i, sdaiINSTANCE, &ifcRepresentationInstance); if (sdaiGetInstanceType(ifcRepresentationInstance) == sdaiGetEntity(model, (char*)L"IFCSTYLEDREPRESENTATION")) { GetRGB_ifcStyledRepresentation(model, ifcRepresentationInstance, material); } i++; } } void IFCConvector::GetRGB_ifcStyledRepresentation(int_t model, int_t ifcStyledRepresentationInstance, IFC_MATERIAL * material) { int_t * ifcRepresentationItemAggr = nullptr, ifcRepresentationItemAggrCnt = 0, i = 0; sdaiGetAttrBN(ifcStyledRepresentationInstance, (char*)L"Items", sdaiAGGR, &ifcRepresentationItemAggr); ifcRepresentationItemAggrCnt = sdaiGetMemberCount(ifcRepresentationItemAggr); while (i < ifcRepresentationItemAggrCnt) { int_t ifcRepresentationItemInstance = 0; engiGetAggrElement(ifcRepresentationItemAggr, i, sdaiINSTANCE, &ifcRepresentationItemInstance); if (sdaiGetInstanceType(ifcRepresentationItemInstance) == sdaiGetEntity(model, (char*)L"IFCSTYLEDITEM")) { GetRGB_styledItem( #ifdef _DEBUG model, #endif ifcRepresentationItemInstance, material ); } i++; } } void IFCConvector::GetRGB_ifcMaterialLayerSetUsage(int_t model, int_t ifcMaterialLayerSetUsage, IFC_MATERIAL * material) { int_t ifcMaterialLayerSetInstance = 0; sdaiGetAttrBN(ifcMaterialLayerSetUsage, (char*)L"ForLayerSet", sdaiINSTANCE, &ifcMaterialLayerSetInstance); //ASSERT(sdaiGetInstanceType(ifcMaterialLayerSetInstance) == sdaiGetEntity(model, (char*)L"IFCMATERIALLAYERSET")); GetRGB_ifcMaterialLayerSet(model, ifcMaterialLayerSetInstance, material); } void IFCConvector::GetRGB_ifcMaterialLayerSet(int_t model, int_t ifcMaterialLayerSet, IFC_MATERIAL * material) { int_t * ifcMaterialLayerAggr = nullptr, ifcMaterialLayerAggrCnt = 0; sdaiGetAttrBN(ifcMaterialLayerSet, (char*)L"MaterialLayers", sdaiAGGR, &ifcMaterialLayerAggr); ifcMaterialLayerAggrCnt = sdaiGetMemberCount(ifcMaterialLayerAggr); if (ifcMaterialLayerAggrCnt) { int_t ifcMaterialLayer = 0; engiGetAggrElement(ifcMaterialLayerAggr, 0, sdaiINSTANCE, &ifcMaterialLayer); if (sdaiGetInstanceType(ifcMaterialLayer) == sdaiGetEntity(model, (char*)L"IFCMATERIALLAYER")) { GetRGB_ifcMaterialLayer(model, ifcMaterialLayer, material); } else { //ASSERT(false); } } } void IFCConvector::GetRGB_ifcMaterialLayer(int_t model, int_t ifcMaterialLayer, IFC_MATERIAL * material) { int_t ifcMaterialInstance = 0; sdaiGetAttrBN(ifcMaterialLayer, (char*)L"Material", sdaiINSTANCE, &ifcMaterialInstance); //ASSERT(sdaiGetInstanceType(ifcMaterialInstance) == sdaiGetEntity(model, (char*)L"IFCMATERIAL")); GetRGB_ifcMaterial(model, ifcMaterialInstance, material); } void IFCConvector::WalkThroughGeometry__transformation(int64_t owlModel, int64_t owlInstance, IFC_MATERIALS *** ppMaterials, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo) { //ASSERT(GetInstanceClass(owlInstance) == rdfClassTransformation); int64_t * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); if (objectCard == 1) { WalkThroughGeometry__collection(owlModel, owlInstanceObject[0], ppMaterials, ppMaterialMetaInfo); } else { //ASSERT(false); } } void IFCConvector::WalkThroughGeometry__collection(int64_t owlModel, int64_t owlInstance, IFC_MATERIALS *** ppMaterials, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo) { if (GetInstanceClass(owlInstance) == m_rdfClassCollection) { int64_t * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); for (int_t i = 0; i < objectsCard; i++) { WalkThroughGeometry__object(owlModel, owlInstanceObjects[i], ppMaterials, ppMaterialMetaInfo); } } else { WalkThroughGeometry__object(owlModel, owlInstance, ppMaterials, ppMaterialMetaInfo); } } void IFCConvector::WalkThroughGeometry__object(int64_t owlModel, int64_t owlInstance, IFC_MATERIALS *** ppMaterials, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo) { int64_t * owlInstanceExpressID = 0, expressIDCard = 0; GetDataTypeProperty(owlInstance, m_owlDataTypePropertyExpressID, (void **)&owlInstanceExpressID, &expressIDCard); if (expressIDCard == 1) { int64_t expressID = owlInstanceExpressID[0]; while ((*ppMaterialMetaInfo) && (*ppMaterialMetaInfo)->expressID != expressID) { ppMaterialMetaInfo = &(*ppMaterialMetaInfo)->next; } if ((*ppMaterialMetaInfo)) { //ASSERT((*ppMaterialMetaInfo)->expressID == expressID); if ((*ppMaterialMetaInfo)->child) { IFC_MATERIAL_META_INFO ** ppMaterialMetaInfoChild = &(*ppMaterialMetaInfo)->child; if (GetInstanceClass(owlInstance) == m_rdfClassTransformation) { int64_t * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); if (objectCard == 1) { WalkThroughGeometry__object(owlModel, owlInstanceObject[0], ppMaterials, ppMaterialMetaInfoChild); } else { //ASSERT(false); } } else if (GetInstanceClass(owlInstance) == m_rdfClassCollection) { int64_t * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); for (int_t i = 0; i < objectsCard; i++) { WalkThroughGeometry__object(owlModel, owlInstanceObjects[i], ppMaterials, ppMaterialMetaInfoChild); } } else { //ASSERT(false); } } else { // // Now recreate the geometry for this object // int64_t vertexBufferSize = 0, indexBufferSize = 0; CalculateInstance(owlInstance, &vertexBufferSize, &indexBufferSize, 0); if ((**ppMaterials)) { (*ppMaterials) = &(**ppMaterials)->next; } (**ppMaterials) = CreateMaterials((*ppMaterialMetaInfo)->material); (**ppMaterials)->__indexBufferSize = indexBufferSize; } ppMaterialMetaInfo = &(*ppMaterialMetaInfo)->next; } else { //ASSERT(false); } } else { if (GetInstanceClass(owlInstance) == m_rdfClassTransformation) { int64_t * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); if (objectCard == 1) { WalkThroughGeometry__object(owlModel, owlInstanceObject[0], ppMaterials, ppMaterialMetaInfo); } else { //ASSERT(false); } } else if (GetInstanceClass(owlInstance) == m_rdfClassCollection) { int64_t * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, m_owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); int_t i = 0; while (i < objectsCard) { WalkThroughGeometry__object(owlModel, owlInstanceObjects[i], ppMaterials, ppMaterialMetaInfo); i++; } } else { //ASSERT(false); } } } void IFCConvector::SearchDeeper(int_t model, int_t geometryInstance, IFC_MATERIAL_META_INFO ** ppMaterialMetaInfo, IFC_MATERIAL * material) { int_t styledItemInstance = 0; sdaiGetAttrBN(geometryInstance, (char*)L"StyledByItem", sdaiINSTANCE, &styledItemInstance); if (styledItemInstance != 0) { GetRGB_styledItem( #ifdef _DEBUG model, #endif styledItemInstance, material ); if (material->ambient.R >= 0) { return; } } int_t booleanClippingResultEntity = sdaiGetEntity(model, (char*)L"IFCBOOLEANCLIPPINGRESULT"), booleanResultEntity = sdaiGetEntity(model, (char*)L"IFCBOOLEANRESULT"), mappedItemEntity = sdaiGetEntity(model, (char*)L"IFCMAPPEDITEM"), shellBasedSurfaceModelEntity = sdaiGetEntity(model, (char*)L"IFCSHELLBASEDSURFACEMODEL"); if (sdaiGetInstanceType(geometryInstance) == booleanResultEntity || sdaiGetInstanceType(geometryInstance) == booleanClippingResultEntity) { int_t geometryChildInstance = 0; sdaiGetAttrBN(geometryInstance, (char*)L"FirstOperand", sdaiINSTANCE, &geometryChildInstance); if (geometryChildInstance) { SearchDeeper(model, geometryChildInstance, ppMaterialMetaInfo, material); } } else if (sdaiGetInstanceType(geometryInstance) == mappedItemEntity) { int_t representationMapInstance = 0; sdaiGetAttrBN(geometryInstance, (char*)L"MappingSource", sdaiINSTANCE, &representationMapInstance); int_t shapeRepresentationInstance = 0; sdaiGetAttrBN(representationMapInstance, (char*)L"MappedRepresentation", sdaiINSTANCE, &shapeRepresentationInstance); if (shapeRepresentationInstance) { //ASSERT((*ppMaterialMetaInfo)->child == 0); GetRGB_shapeRepresentation(model, shapeRepresentationInstance, &(*ppMaterialMetaInfo)->child); } } else if (sdaiGetInstanceType(geometryInstance) == shellBasedSurfaceModelEntity) { int_t * geometryChildAggr = nullptr; sdaiGetAttrBN(geometryInstance, (char*)L"SbsmBoundary", sdaiAGGR, &geometryChildAggr); IFC_MATERIAL_META_INFO ** ppSubMaterialMetaInfo = &(*ppMaterialMetaInfo)->child; int_t cnt = sdaiGetMemberCount(geometryChildAggr), i = 0; while (i < cnt) { int_t geometryChildInstance = 0; engiGetAggrElement(geometryChildAggr, i, sdaiINSTANCE, &geometryChildInstance); if (geometryChildInstance) { //ASSERT((*ppSubMaterialMetaInfo) == 0); (*ppSubMaterialMetaInfo) = CreateMaterialMetaInfo(geometryChildInstance); SearchDeeper(model, geometryChildInstance, ppSubMaterialMetaInfo, (*ppSubMaterialMetaInfo)->material); ppSubMaterialMetaInfo = &(*ppSubMaterialMetaInfo)->next; } i++; } } } //--------------------------------------------------------------------------------------------- // brief ÊôÐÔ void IFCConvector::IFCPropToFiled(OgdcRecordset* pRecordset, IFC__PROPERTY__SET* pIFCPropSet) { IFC__PROPERTY__SET* pIFCPropSetNext = pIFCPropSet; while (pIFCPropSetNext) { IFC__PROPERTY* pProperty = pIFCPropSetNext->properties; while (pProperty) { wchar_t* name = pProperty->name; UGString strName = UGString(pIFCPropSetNext->name) + _U("_") + UGString(name); UGuint nLength = strName.GetLength(); UGString strPropName = strName; if (nLength > 20) { strPropName = m_propForeign[strName]; } std::set<UGString>::iterator it = m_propList.find(strName); if (it != m_propList.end()) { if (pProperty->nominalValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->nominalValue)); } else if (pProperty->volumeValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->nominalValue)); } else if (pProperty->timeValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->timeValue)); } else if (pProperty->lengthValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->lengthValue)); } else if (pProperty->countValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->countValue)); } else if (pProperty->areaValue) { pRecordset->SetFieldValue(strPropName, UGVariant(pProperty->areaValue)); } if (pProperty->unit) { UGString strUnit = strPropName + _U("_Unit"); pRecordset->SetFieldValue(strUnit, UGVariant(pProperty->unit)); } } pProperty = pProperty->next; } pIFCPropSetNext = pIFCPropSetNext->next; } } void IFCConvector::ClearPropertys() { std::map<int_t, IFC__PROPERTY__SET*>::iterator it = m_ifcProperty.begin(); while (it!= m_ifcProperty.end()) { DeletePropertySet(it->second); it++; } m_ifcProperty.clear(); m_propList.clear(); } void IFCConvector::DeletePropertySet(IFC__PROPERTY__SET* ifcPorpSet) { while (ifcPorpSet) { IFC__PROPERTY__SET * pSetToRemove = ifcPorpSet; IFC__PROPERTY * properties = ifcPorpSet->properties; while (properties) { IFC__PROPERTY * pToRemove = properties; properties = properties->next; if (pToRemove->name) { delete pToRemove->name; } if (pToRemove->description) { delete pToRemove->description; } if (pToRemove->nominalValue) { delete pToRemove->nominalValue; } if (pToRemove->lengthValue) { delete pToRemove->lengthValue; } if (pToRemove->areaValue) { delete pToRemove->areaValue; } if (pToRemove->countValue) { delete pToRemove->countValue; } if (pToRemove->timeValue) { delete pToRemove->timeValue; } if (pToRemove->volumeValue) { delete pToRemove->volumeValue; } if (pToRemove->weigthValue) { delete pToRemove->weigthValue; } // delete pToRemove->nameBuffer; delete pToRemove; } ifcPorpSet = ifcPorpSet->next; if (pSetToRemove->name) { delete[] pSetToRemove->name; } if (pSetToRemove->description) { delete[] pSetToRemove->description; } delete pSetToRemove; } } void IFCConvector::CreateObjProList(int_t ifcInstance, int_t entity , int_t & index, OgdcRecordset* pRecordset /*= NULL*/) { if (entity) { CreateObjProList(ifcInstance, engiGetEntityParent(entity), index, pRecordset); wchar_t * entityName = nullptr; engiGetEntityName(entity, sdaiUNICODE, (char**)&entityName); int_t argCnt = engiGetEntityNoArguments(entity); while (index < argCnt) { wchar_t * propertyName = nullptr; engiGetEntityArgumentName(entity, index, sdaiUNICODE, (char**)&propertyName); int_t propertyType = 0; engiGetEntityArgumentType(entity, index, &propertyType); UGString strName = UGString(propertyName); if (pRecordset == NULL) { m_objPropList.insert(strName); } else { UGString value = NestedPropertyValue(ifcInstance, propertyName, propertyType, 0); //QMessageBox::warning(NULL, "", QString::fromWCharArray(value)); pRecordset->SetFieldValue(UGString(strName), value); } index++; } entity = engiGetEntityParent(entity); } } void IFCConvector::CreateIfcInstanceProperties(int_t ifcModel, IFC__PROPERTY__SET ** propertySets, int_t ifcObjectInstance, IFC__SIUNIT * units) { int_t * isDefinedByInstances = 0, ifcRelDefinesByType_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCRELDEFINESBYTYPE"), ifcRelDefinesByProperties_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCRELDEFINESBYPROPERTIES"); sdaiGetAttrBN(ifcObjectInstance, (char*)L"IsDefinedBy", sdaiAGGR, &isDefinedByInstances); if (isDefinedByInstances) { int_t isDefinedByInstancesCnt = sdaiGetMemberCount(isDefinedByInstances); for (int_t i = 0; i < isDefinedByInstancesCnt; ++i) { int_t isDefinedByInstance = 0; engiGetAggrElement(isDefinedByInstances, i, sdaiINSTANCE, &isDefinedByInstance); if (sdaiGetInstanceType(isDefinedByInstance) == ifcRelDefinesByType_TYPE) { int_t typeObjectInstance = 0; sdaiGetAttrBN(isDefinedByInstance, (char*)L"RelatingType", sdaiINSTANCE, &typeObjectInstance); CreateTypeObjectInstance(ifcModel, propertySets, typeObjectInstance, units); } else if (sdaiGetInstanceType(isDefinedByInstance) == ifcRelDefinesByProperties_TYPE) { CreateRelDefinesByProperties(ifcModel, propertySets, isDefinedByInstance, units); } else { //ASSERT(false); } } } } void IFCConvector::CreateRelDefinesByProperties(int_t ifcModel, IFC__PROPERTY__SET ** propertySets, int_t ifcRelDefinesByProperties, IFC__SIUNIT * units) { if (ifcRelDefinesByProperties) { int_t ifcPropertySetInstance = 0, ifcElementQuantity_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCELEMENTQUANTITY"), ifcPropertySet_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCPROPERTYSET"); sdaiGetAttrBN(ifcRelDefinesByProperties, (char*)L"RelatingPropertyDefinition", sdaiINSTANCE, &ifcPropertySetInstance); if (sdaiGetInstanceType(ifcPropertySetInstance) == ifcElementQuantity_TYPE) { CreateIfcElementQuantity(ifcModel, propertySets, ifcPropertySetInstance, units); } else if (sdaiGetInstanceType(ifcPropertySetInstance) == ifcPropertySet_TYPE) { CreateIfcPropertySet(ifcModel, propertySets, ifcPropertySetInstance, units); } else { //ASSERT(false); } } else { //ASSERT(false); } } void IFCConvector::CreateTypeObjectInstance(int_t ifcModel, IFC__PROPERTY__SET ** propertySets, int_t ifcTypeObjectInstance, IFC__SIUNIT * units) { if (ifcTypeObjectInstance) { int_t * hasPropertySets = 0, hasPropertySetsCnt, ifcElementQuantity_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCELEMENTQUANTITY"), ifcPropertySet_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCPROPERTYSET"); sdaiGetAttrBN(ifcTypeObjectInstance, (char*)L"HasPropertySets", sdaiAGGR, &hasPropertySets); hasPropertySetsCnt = sdaiGetMemberCount(hasPropertySets); for (int_t i = 0; i < hasPropertySetsCnt; ++i) { int_t hasPropertySetInstance = 0; engiGetAggrElement(hasPropertySets, i, sdaiINSTANCE, &hasPropertySetInstance); if (sdaiGetInstanceType(hasPropertySetInstance) == ifcElementQuantity_TYPE) { CreateIfcElementQuantity(ifcModel, propertySets, hasPropertySetInstance, units); } else if (sdaiGetInstanceType(hasPropertySetInstance) == ifcPropertySet_TYPE) { CreateIfcPropertySet(ifcModel, propertySets, hasPropertySetInstance, units); } else { //ASSERT(false); } } } } void IFCConvector::CreateIfcElementQuantity(int_t ifcModel, IFC__PROPERTY__SET ** propertySets, int_t ifcPropertySetInstance, IFC__SIUNIT * units) { IFC__PROPERTY__SET ** ppPropertySet = propertySets;//&ifcObject->propertySets; while ((*ppPropertySet)) { ppPropertySet = &(*ppPropertySet)->next; } wchar_t * name = 0, *description = 0; sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"Name", sdaiUNICODE, &name); sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"Description", sdaiUNICODE, &description); //ASSERT((*ppPropertySet) == 0); (*ppPropertySet) = CreateIfcPropertySet(ifcPropertySetInstance, name, description); IFC__PROPERTY ** ppProperty = &(*ppPropertySet)->properties; int_t * ifcQuantityInstances = 0; #ifdef _DEBUG // int_t ifcRelDefinesByType_TYPE = sdaiGetEntity(ifcModel, (char*) L"IFCRELDEFINESBYTYPE"), // ifcRelDefinesByProperties_TYPE = sdaiGetEntity(ifcModel, (char*) L"IFCRELDEFINESBYPROPERTIES"); #endif sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"Quantities", sdaiAGGR, &ifcQuantityInstances); if (ifcQuantityInstances) { int_t ifcQuantityInstancesCnt = sdaiGetMemberCount(ifcQuantityInstances); for (int_t i = 0; i < ifcQuantityInstancesCnt; ++i) { int_t ifcQuantityInstance = 0, ifcQuantityLength_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYLENGTH"), ifcQuantityArea_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYAREA"), ifcQuantityVolume_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYVOLUME"), ifcQuantityCount_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYCOUNT"), ifcQuantityWeigth_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYWEIGHT"), ifcQuantityTime_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCQUANTITYTIME"); engiGetAggrElement(ifcQuantityInstances, i, sdaiINSTANCE, &ifcQuantityInstance); wchar_t * quantityName = 0, *quantityDescription = 0; sdaiGetAttrBN(ifcQuantityInstance, (char*)L"Name", sdaiUNICODE, &quantityName); sdaiGetAttrBN(ifcQuantityInstance, (char*)L"Description", sdaiUNICODE, &quantityDescription); //ASSERT((*ppProperty) == 0); (*ppProperty) = CreateIfcProperty(ifcQuantityInstance, quantityName, quantityDescription); // Ìí¼Óµ½ÊôÐÔÁбí UGString propName = UGString(name) + _U("_") +UGString(quantityName); m_propList.insert(propName); if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityLength_TYPE) { CreateIfcQuantityLength(ifcQuantityInstance, (*ppProperty), units); } else if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityArea_TYPE) { CreateIfcQuantityArea(ifcQuantityInstance, (*ppProperty), units); } else if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityVolume_TYPE) { CreateIfcQuantityVolume(ifcQuantityInstance, (*ppProperty), units); } else if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityCount_TYPE) { CreateIfcQuantityCount(ifcQuantityInstance, (*ppProperty));//, units); } else if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityWeigth_TYPE) { CreateIfcQuantityWeigth(ifcQuantityInstance, (*ppProperty), units); } else if (sdaiGetInstanceType(ifcQuantityInstance) == ifcQuantityTime_TYPE) { CreateIfcQuantityTime(ifcQuantityInstance, (*ppProperty), units); } else { //ASSERT(false); } ppProperty = &(*ppProperty)->next; } } } IFC__PROPERTY__SET * IFCConvector::CreateIfcPropertySet(int_t ifcInstance, wchar_t * name, wchar_t * description) { IFC__PROPERTY__SET * ifcPropertySet = new IFC__PROPERTY__SET; ifcPropertySet->structType = STRUCT_TYPE_PROPERTY_SET; ifcPropertySet->ifcInstance = ifcInstance; ifcPropertySet->name = copyStr(name); ifcPropertySet->description = copyStr(description); ifcPropertySet->nameBuffer = new wchar_t[512]; ifcPropertySet->properties = NULL; ifcPropertySet->next = NULL; return ifcPropertySet; } void IFCConvector::CreateIfcPropertySet(int_t ifcModel, IFC__PROPERTY__SET ** propertySets, int_t ifcPropertySetInstance, IFC__SIUNIT * units) { IFC__PROPERTY__SET ** ppPropertySet = propertySets;//&ifcObject->propertySets; while ((*ppPropertySet)) { ppPropertySet = &(*ppPropertySet)->next; } wchar_t * name = 0, *description = 0; sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"Name", sdaiUNICODE, &name); sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"Description", sdaiUNICODE, &description); //ASSERT((*ppPropertySet) == 0); (*ppPropertySet) = CreateIfcPropertySet(ifcPropertySetInstance, name, description); IFC__PROPERTY ** ppProperty = &(*ppPropertySet)->properties; int_t * ifcPropertyInstances = 0; #ifdef _DEBUG // int_t ifcRelDefinesByType_TYPE = sdaiGetEntity(ifcModel, (char*) L"IFCRELDEFINESBYTYPE"), // ifcRelDefinesByProperties_TYPE = sdaiGetEntity(ifcModel, (char*) L"IFCRELDEFINESBYPROPERTIES"); #endif sdaiGetAttrBN(ifcPropertySetInstance, (char*)L"HasProperties", sdaiAGGR, &ifcPropertyInstances); if (ifcPropertyInstances) { int_t ifcPropertyInstancesCnt = sdaiGetMemberCount(ifcPropertyInstances); for (int_t i = 0; i < ifcPropertyInstancesCnt; ++i) { int_t ifcPropertyInstance = 0, ifcPropertySingleValue_TYPE = sdaiGetEntity(ifcModel, (char*)L"IFCPROPERTYSINGLEVALUE"); engiGetAggrElement(ifcPropertyInstances, i, sdaiINSTANCE, &ifcPropertyInstance); wchar_t * propertyName = 0, *propertyDescription = 0; sdaiGetAttrBN(ifcPropertyInstance, (char*)L"Name", sdaiUNICODE, &propertyName); sdaiGetAttrBN(ifcPropertyInstance, (char*)L"Description", sdaiUNICODE, &propertyDescription); //ASSERT((*ppProperty) == 0); (*ppProperty) = CreateIfcProperty(ifcPropertyInstance, propertyName, propertyDescription); // Ìí¼Óµ½ÊôÐÔÁбí UGString propName = UGString(name) + _U("_") + UGString(propertyName); m_propList.insert(propName); if (sdaiGetInstanceType(ifcPropertyInstance) == ifcPropertySingleValue_TYPE) { CreateIfcPropertySingleValue(ifcPropertyInstance, (*ppProperty), units); } else { // ASSERT(false); } ppProperty = &(*ppProperty)->next; } } } void IFCConvector::CreateIfcPropertySingleValue(int_t ifcPropertySingleValue, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * nominalValue = 0, *unit = 0, *typePath = 0; int_t * nominalValueADB = 0; sdaiGetAttrBN(ifcPropertySingleValue, (char*)L"NominalValue", sdaiUNICODE, &nominalValue); if (nominalValue) { sdaiGetAttrBN(ifcPropertySingleValue, (char*)L"NominalValue", sdaiADB, &nominalValueADB); typePath = (wchar_t*)sdaiGetADBTypePath(nominalValueADB, 0); sdaiGetAttrBN(ifcPropertySingleValue, (char*)L"Unit", sdaiUNICODE, &unit); if (unit == 0) { if (equalStr(typePath, L"IFCBOOLEAN")) { } else if (equalStr(typePath, L"IFCIDENTIFIER")) { } else if (equalStr(typePath, L"IFCINTEGER")) { } else if (equalStr(typePath, L"IFCLABEL")) { } else if (equalStr(typePath, L"IFCLOGICAL")) { } else if (equalStr(typePath, L"IFCTEXT")) { } else if (equalStr(typePath, L"IFCREAL")) { } else if (equalStr(typePath, L"IFCCOUNTMEASURE")) { } else if (equalStr(typePath, L"IFCPOSITIVERATIOMEASURE")) { } else if (equalStr(typePath, L"IFCVOLUMETRICFLOWRATEMEASURE")) { } else if (equalStr(typePath, L"IFCABSORBEDDOSEMEASURE")) { unit = GetUnit(units, L"ABSORBEDDOSEUNIT"); } else if (equalStr(typePath, L"IFCAMOUNTOFSUBSTANCEMEASURE")) { unit = GetUnit(units, L"AMOUNTOFSUBSTANCEUNIT"); } else if (equalStr(typePath, L"IFCAREAMEASURE")) { unit = GetUnit(units, L"AREAUNIT"); } else if (equalStr(typePath, L"IFCDOSEEQUIVALENTMEASURE")) { unit = GetUnit(units, L"DOSEEQUIVALENTUNIT"); } else if (equalStr(typePath, L"IFCELECTRICCAPACITANCEMEASURE")) { unit = GetUnit(units, L"ELECTRICCAPACITANCEUNIT"); } else if (equalStr(typePath, L"IFCELECTRICCHARGEMEASURE")) { unit = GetUnit(units, L"ELECTRICCHARGEUNIT"); } else if (equalStr(typePath, L"IFCELECTRICCONDUCTANCEMEASURE")) { unit = GetUnit(units, L"ELECTRICCONDUCTANCEUNIT"); } else if (equalStr(typePath, L"IFCELECTRICCURRENTMEASURE")) { unit = GetUnit(units, L"ELECTRICCURRENTUNIT"); } else if (equalStr(typePath, L"IFCELECTRICRESISTANCEMEASURE")) { unit = GetUnit(units, L"ELECTRICRESISTANCEUNIT"); } else if (equalStr(typePath, L"IFCELECTRICVOLTAGEMEASURE")) { unit = GetUnit(units, L"ELECTRICVOLTAGEUNIT"); } else if (equalStr(typePath, L"IFCENERGYMEASURE")) { unit = GetUnit(units, L"ENERGYUNIT"); } else if (equalStr(typePath, L"IFCFORCEMEASURE")) { unit = GetUnit(units, L"FORCEUNIT"); } else if (equalStr(typePath, L"IFCFREQUENCYMEASURE")) { unit = GetUnit(units, L"FREQUENCYUNIT"); } else if (equalStr(typePath, L"IFCILLUMINANCEMEASURE")) { unit = GetUnit(units, L"ILLUMINANCEUNIT"); } else if (equalStr(typePath, L"IFCINDUCTANCEMEASURE")) { unit = GetUnit(units, L"INDUCTANCEUNIT"); } else if (equalStr(typePath, L"IFCLENGTHMEASURE") || equalStr(typePath, L"IFCPOSITIVELENGTHMEASURE")) { unit = GetUnit(units, L"LENGTHUNIT"); } else if (equalStr(typePath, L"IFCLUMINOUSFLUXMEASURE")) { unit = GetUnit(units, L"LUMINOUSFLUXUNIT"); } else if (equalStr(typePath, L"IFCLUMINOUSINTENSITYMEASURE")) { unit = GetUnit(units, L"LUMINOUSINTENSITYUNIT"); } else if (equalStr(typePath, L"IFCMAGNETICFLUXDENSITYMEASURE")) { unit = GetUnit(units, L"MAGNETICFLUXDENSITYUNIT"); } else if (equalStr(typePath, L"IFCMAGNETICFLUXMEASURE")) { unit = GetUnit(units, L"MAGNETICFLUXUNIT"); } else if (equalStr(typePath, L"IFCMASSMEASURE")) { unit = GetUnit(units, L"MASSUNIT"); } else if (equalStr(typePath, L"IFCPLANEANGLEMEASURE")) { unit = GetUnit(units, L"PLANEANGLEUNIT"); } else if (equalStr(typePath, L"IFPOWERCMEASURE")) { unit = GetUnit(units, L"POWERUNIT"); } else if (equalStr(typePath, L"IFCPRESSUREMEASURE")) { unit = GetUnit(units, L"PRESSUREUNIT"); } else if (equalStr(typePath, L"IFCRADIOACTIVITYMEASURE")) { unit = GetUnit(units, L"RADIOACTIVITYUNIT"); } else if (equalStr(typePath, L"IFCSOLIDANGLEMEASURE")) { unit = GetUnit(units, L"SOLIDANGLEUNIT"); } else if (equalStr(typePath, L"IFCTHERMODYNAMICTEMPERATUREMEASURE")) { unit = GetUnit(units, L"THERMODYNAMICTEMPERATUREUNIT"); } else if (equalStr(typePath, L"IFCTIMEMEASURE")) { unit = GetUnit(units, L"TIMEUNIT"); } else if (equalStr(typePath, L"IFCVOLUMEMEASURE")) { unit = GetUnit(units, L"VOLUMEUNIT"); } else if (equalStr(typePath, L"IFCUSERDEFINEDMEASURE")) { unit = GetUnit(units, L"USERDEFINED"); } else if (equalStr(typePath, L"IFCTHERMALTRANSMITTANCEMEASURE")) { unit = GetUnit(units, L"???"); } else { //ASSERT(false); } } else { //ASSERT(false); } ifcProperty->nominalValue = copyStr(nominalValue); ifcProperty->unit = copyStr(unit); } else { ifcProperty->nominalValue = 0; ifcProperty->unit = 0; } } IFC__PROPERTY * IFCConvector::CreateIfcProperty(int_t ifcInstance, wchar_t * name, wchar_t * description) { IFC__PROPERTY * ifcProperty = new IFC__PROPERTY; ifcProperty->structType = STRUCT_TYPE_PROPERTY; ifcProperty->ifcInstance = ifcInstance; ifcProperty->name = copyStr(name); ifcProperty->description = copyStr(description); ifcProperty->nominalValue = NULL; ifcProperty->lengthValue = NULL; ifcProperty->areaValue = NULL; ifcProperty->volumeValue = NULL; ifcProperty->countValue = NULL; ifcProperty->weigthValue = NULL; ifcProperty->timeValue = NULL; ifcProperty->unit = NULL; //ifcProperty->hTreeItem = 0; ifcProperty->nameBuffer = new wchar_t[512 + 1]; ifcProperty->next = NULL; return ifcProperty; } void IFCConvector::CreateIfcQuantityLength(int_t ifcQuantityLength, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * lengthValue = NULL; wchar_t * unit = NULL; int_t ifcUnitInstance = NULL; sdaiGetAttrBN(ifcQuantityLength, (char*)L"LengthValue", sdaiUNICODE, &lengthValue); sdaiGetAttrBN(ifcQuantityLength, (char*)L"Unit", sdaiUNICODE, &unit); sdaiGetAttrBN(ifcQuantityLength, (char*)L"Unit", sdaiINSTANCE, &ifcUnitInstance); //ASSERT(ifcUnitInstance == 0); ifcProperty->lengthValue = copyStr(lengthValue); ifcProperty->unit = copyStr(unit); if (unit == NULL || unit[0] == NULL) { while (units) { if (units->type == LENGTHUNIT) { ifcProperty->unit = units->name; } units = units->next; } } } void IFCConvector::CreateIfcQuantityArea(int_t ifcQuantityArea, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * areaValue = NULL; wchar_t * unit = NULL; sdaiGetAttrBN(ifcQuantityArea, (char*)L"AreaValue", sdaiUNICODE, &areaValue); sdaiGetAttrBN(ifcQuantityArea, (char*)L"Unit", sdaiUNICODE, &unit); ifcProperty->areaValue = copyStr(areaValue); ifcProperty->unit = copyStr(unit); if (unit == NULL || unit[0] == NULL) { while (units) { if (units->type == AREAUNIT) { ifcProperty->unit = units->name; } units = units->next; } } } void IFCConvector::CreateIfcQuantityVolume(int_t ifcQuantityVolume, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * volumeValue = NULL; wchar_t * unit = NULL; sdaiGetAttrBN(ifcQuantityVolume, (char*)L"VolumeValue", sdaiUNICODE, &volumeValue); sdaiGetAttrBN(ifcQuantityVolume, (char*)L"Unit", sdaiUNICODE, &unit); ifcProperty->volumeValue = copyStr(volumeValue); ifcProperty->unit = copyStr(unit); if (unit == NULL || unit[0] == NULL) { while (units) { if (units->type == VOLUMEUNIT) { ifcProperty->unit = units->name; } units = units->next; } } } void IFCConvector::CreateIfcQuantityCount(int_t ifcQuantityCount, IFC__PROPERTY * ifcProperty) { wchar_t * countValue = NULL; wchar_t * unit = NULL; sdaiGetAttrBN(ifcQuantityCount, (char*)L"CountValue", sdaiUNICODE, &countValue); sdaiGetAttrBN(ifcQuantityCount, (char*)L"Unit", sdaiUNICODE, &unit); ifcProperty->countValue = copyStr(countValue); ifcProperty->unit = copyStr(unit); } void IFCConvector::CreateIfcQuantityWeigth(int_t ifcQuantityWeigth, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * weigthValue = NULL; wchar_t * unit = NULL; sdaiGetAttrBN(ifcQuantityWeigth, (char*)L"WeigthValue", sdaiUNICODE, &weigthValue); sdaiGetAttrBN(ifcQuantityWeigth, (char*)L"Unit", sdaiUNICODE, &unit); ifcProperty->weigthValue = copyStr(weigthValue); ifcProperty->unit = copyStr(unit); if (unit == NULL || unit[0] == NULL) { while (units) { if (units->type == MASSUNIT) { ifcProperty->unit = units->name; } units = units->next; } } } void IFCConvector::CreateIfcQuantityTime(int_t ifcQuantityTime, IFC__PROPERTY * ifcProperty, IFC__SIUNIT * units) { wchar_t * timeValue = NULL; wchar_t * unit = NULL; sdaiGetAttrBN(ifcQuantityTime, (char*)L"TimeValue", sdaiUNICODE, &timeValue); sdaiGetAttrBN(ifcQuantityTime, (char*)L"Unit", sdaiUNICODE, &unit); ifcProperty->timeValue = copyStr(timeValue); ifcProperty->unit = copyStr(unit); if (unit == NULL || unit[0] == NULL) { while (units) { if (units->type == TIMEUNIT) { ifcProperty->unit = units->name; } units = units->next; } } } OGDC::OgdcString IFCConvector::NestedPropertyValue(int_t ifcEntityInstance, wchar_t * propertyName, int_t propertyType, int_t * ifcAggregate) { UGString rvalue = _U(""); if (ifcAggregate) { engiGetAggrType(ifcAggregate, &propertyType); } else { if (ifcEntityInstance == 0 || propertyName == NULL || propertyType == 0) { return rvalue; } } wchar_t * buffer = nullptr, buff[512]; int_t ifcInstance, lineNo, *ifcInstanceAggr, ifcInstanceAggrCnt, integer; wchar_t * nominalValue = nullptr, *typePath = nullptr; int_t * nominalValueADB = nullptr; switch (propertyType) { case sdaiADB: sdaiGetAttrBN(ifcEntityInstance, (char*)propertyName, sdaiUNICODE, &nominalValue); if (nominalValue) { sdaiGetAttrBN(ifcEntityInstance, (char*)propertyName, sdaiADB, &nominalValueADB); typePath = (wchar_t*)sdaiGetADBTypePath(nominalValueADB, sdaiUNICODE); UGString value(typePath); rvalue += value; } break; case sdaiAGGR: ifcInstanceAggr = 0; if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char *)propertyName, sdaiAGGR, &ifcInstanceAggr); } else { engiGetAggrElement(ifcAggregate, 0, sdaiAGGR, &ifcInstanceAggr); } if (ifcInstanceAggr) { ifcInstanceAggrCnt = sdaiGetMemberCount(ifcInstanceAggr); if (ifcInstanceAggrCnt > 0) { //rValue += NestedPropertyValue(0, 0, 0, ifcInstanceAggr); rvalue += NestedPropertyValue(0, 0, 0, ifcInstanceAggr); if (ifcInstanceAggrCnt > 1) { //rValue += ", ..."; } } else { //ASSERT(ifcInstanceAggrCnt == 0); //rValue += " ?"; } } else { //rValue += "???"; } //rValue += ")"; break; case sdaiBINARY: case sdaiBOOLEAN: case sdaiENUM: if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char*)propertyName, sdaiUNICODE, &buffer); } else { engiGetAggrElement(ifcAggregate, 0, sdaiUNICODE, &buffer); } if (buffer && buffer[0]) { //rValue += buffer; rvalue += UGString(buffer); } else { //rValue += "?"; } break; case sdaiINSTANCE: if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char *)propertyName, sdaiINSTANCE, &ifcInstance); } else { engiGetAggrElement(ifcAggregate, 0, sdaiINSTANCE, &ifcInstance); } if (ifcInstance) { lineNo = internalGetP21Line(ifcInstance); rvalue += _U("#"); #ifdef WIN64 _i64tow_s(lineNo, buff, 500, 10); #else _itow_s(lineNo, buff, 10); #endif rvalue += UGString(buff); } else { //rValue += "?"; } break; case sdaiINTEGER: integer = 0; if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char *)propertyName, sdaiINTEGER, &integer); } else { engiGetAggrElement(ifcAggregate, 0, sdaiINTEGER, &integer); } #ifdef WIN64 _i64tow_s(integer, buff, 500, 10); #else _itow_s(integer, buff, 10); #endif rvalue += UGString(buff); break; case sdaiLOGICAL: case sdaiREAL: if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char*)propertyName, sdaiUNICODE, &buffer); } else { engiGetAggrElement(ifcAggregate, 0, sdaiUNICODE, &buffer); } if (buffer && buffer[0]) { rvalue += UGString(buff); } else { //rValue += "?"; } break; case sdaiSTRING: if (ifcEntityInstance) { sdaiGetAttrBN(ifcEntityInstance, (char*)propertyName, sdaiUNICODE, &buffer); } else { engiGetAggrElement(ifcAggregate, 0, sdaiUNICODE, &buffer); } rvalue += UGString(buffer); //rValue += '\''; //rValue += buffer; //rValue += '\''; break; default: //rValue += "<NOT IMPLEMENTED>"; break; } return rvalue; }
SuperMap/OGDC
Samples/IFCTools/ifcconvector.cpp
C++
bsd-2-clause
102,226
/* * THE CHRONOTEXT-PLAYGROUND: https://github.com/arielm/chronotext-playground * COPYRIGHT (C) 2014-2015, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE SIMPLIFIED BSD LICENSE: * https://github.com/arielm/chronotext-playground/blob/master/LICENSE */ /* * SEE COMMENTS IN TestingMemory1::setup() * * MORE CONTEXT: * - https://github.com/arielm/new-chronotext-toolkit/blob/develop/src/chronotext/cocoa/system/MemoryManager.mm * - https://github.com/arielm/new-chronotext-toolkit/blob/develop/src/chronotext/android/system/MemoryManager.cpp */ #pragma once #include "Testing/TestingBase.h" #include "chronotext/system/MemoryInfo.h" class Unit { public: Unit(size_t size); ~Unit(); size_t size() const; uint8_t* data() const; const std::string write() const; protected: size_t _size; uint8_t *_data; }; class Measure { public: chr::MemoryInfo before; chr::MemoryInfo after; int64_t balance = -1; void begin(); void end(); const std::string write() const; protected: bool began = false; }; class TestingMemory1 : public TestingBase { public: void setup() final; void shutdown() final; /* * PASSING VIA update() IS (CURRENTLY) NECESSARY, IN ORDER TO BE PROPERLY NOTIFIED UPON "MEMORY WARNING" */ void update() final; protected: std::vector<std::shared_ptr<Unit>> units; bool adding; bool removing; bool done; size_t unitDataSize; size_t unitCount; };
arielm/chronotext-playground
Sketches/TestBed1/src/TestingMemory1.h
C
bsd-2-clause
1,562
## EqualAssay The `EqualAssay` class defines an assertion for equality based on the `==` method. assert EqualAssay.pass?(1, 1) assert EqualAssay.pass?(1, 1.0) refute EqualAssay.pass?(1, 2) refute EqualAssay.pass?(1, 'foo') And conversely, assert EqualAssay.fail?(1, 2) assert EqualAssay.fail?(1, 'foo') refute EqualAssay.fail?(1, 1) refute EqualAssay.fail?(1, 1.0)
rubyworks/assay
demo/01_assay_classes/05_equal_assay.md
Markdown
bsd-2-clause
405
//MIT, 2014-present, WinterDev using System; using System.Collections.Generic; using PixelFarm.Drawing; using PixelFarm.DrawingGL; namespace Mini { public delegate void GLSwapBufferDelegate(); public delegate IntPtr GetGLControlDisplay(); public delegate IntPtr GetGLSurface(); public abstract class DemoBase { public DemoBase() { this.Width = 900; this.Height = 700; } //when we use with opengl GLSwapBufferDelegate _swapBufferDelegate; GetGLControlDisplay _getGLControlDisplay; GetGLSurface _getGLSurface; public event EventHandler RequestGraphicRefresh; public void InvalidateGraphics() { RequestGraphicRefresh?.Invoke(this, EventArgs.Empty); } public virtual void Draw(Painter p) { OnGLRender(this, EventArgs.Empty); } public void CloseDemo() { DemoClosing(); } public virtual void Init() { } public virtual void KeyDown(int keycode) { } public virtual void MouseDrag(int x, int y) { } public virtual void MouseDown(int x, int y, bool isRightButton) { } public virtual void MouseUp(int x, int y) { } public virtual int Width { get; set; } public virtual int Height { get; set; } protected virtual void DemoClosing() { } protected virtual void OnTimerTick(object sender, EventArgs e) { } protected virtual bool EnableAnimationTimer { get => false; set { } } public static void InvokeGLPainterReady(DemoBase demo, GLPainterCore pcx, GLPainter painter) { demo.OnGLPainterReady(painter); demo.OnReadyForInitGLShaderProgram(); } public static void InvokePainterReady(DemoBase demo, Painter painter) { demo.OnPainterReady(painter); } protected virtual void OnGLPainterReady(GLPainter painter) { } protected virtual void OnPainterReady(Painter painter) { } protected virtual void OnReadyForInitGLShaderProgram() { //this method is called when the demo is ready for create GLES shader program } protected virtual void OnGLRender(object sender, EventArgs args) { } public void InvokeGLPaint() { OnGLRender(this, EventArgs.Empty); } protected void SwapBuffers() { //manual swap buffer _swapBufferDelegate?.Invoke(); } public void SetEssentialGLHandlers( GLSwapBufferDelegate swapBufferDelegate, GetGLControlDisplay getGLControlDisplay, GetGLSurface getGLSurface) { _swapBufferDelegate = swapBufferDelegate; _getGLControlDisplay = getGLControlDisplay; _getGLSurface = getGLSurface; } protected IntPtr getGLControlDisplay() { return _getGLControlDisplay(); } protected IntPtr getGLSurface() { return _getGLSurface(); } } [Flags] public enum DemoBackend { All, } [AttributeUsage(AttributeTargets.Class)] public class DemoConfigGroupAttribute : Attribute { public string Name { get; set; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class InfoAttribute : Attribute { public InfoAttribute() { } public InfoAttribute(DemoCategory catg) { this.Category = catg; } public InfoAttribute(string desc) { this.Description = desc; } public InfoAttribute(DemoCategory catg, string desc) { this.Category = catg; this.Description = desc; } public string Description { get; } public DemoCategory Category { get; } public string OrderCode { get; set; } public AvailableOn AvailableOn { get; set; } } public enum DemoCategory { Vector, Bitmap } [Flags] public enum AvailableOn { Empty = 0, GdiPlus = 1 << 1, //software Agg = 1 << 2, //software GLES = 1 << 3, //hardware BothHardwareAndSoftware = GdiPlus | Agg | GLES } public static class RootDemoPath { public static string Path = ""; } public enum DemoConfigPresentaionHint { TextBox, CheckBox, OptionBoxes, SlideBarDiscrete, SlideBarContinuous_R4, SlideBarContinuous_R8, ConfigGroup, } public class DemoConfigAttribute : Attribute { public DemoConfigAttribute() { } public DemoConfigAttribute(string name) { this.Name = name; } public string Name { get; set; } public int MinValue { get; set; } public int MaxValue { get; set; } } public class DemoActionAttribute : Attribute { public DemoActionAttribute() { } public DemoActionAttribute(string name) { this.Name = name; } public string Name { get; set; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class NoteAttribute : Attribute { public NoteAttribute(string desc) { this.Desc = desc; } public string Desc { get; set; } } public class ExampleAction { public ExampleAction(DemoActionAttribute config, System.Reflection.MethodInfo method) { Method = method; if (!string.IsNullOrEmpty(config.Name)) { this.Name = config.Name; } else { this.Name = method.Name; } } public System.Reflection.MethodInfo Method { get; } public string Name { get; } public void InvokeMethod(object target) { Method.Invoke(target, null); } } public class ExampleGroupConfigDesc { public List<ExampleConfigDesc> _configList = new List<ExampleConfigDesc>(); public List<ExampleAction> _configActionList = new List<ExampleAction>(); public ExampleGroupConfigDesc(DemoConfigGroupAttribute config, Type configClassOrStruct) { ConfigClassOrStruct = configClassOrStruct; OriginalGroupConfifAttribute = config; Name = config.Name; } public System.Reflection.PropertyInfo OwnerProperty { get; internal set; } public string Name { get; } public DemoConfigGroupAttribute OriginalGroupConfifAttribute { get; } public Type ConfigClassOrStruct { get; } } public class ExampleConfigDesc { readonly System.Reflection.PropertyInfo _property; readonly List<ExampleConfigValue> _optionFields; public ExampleConfigDesc(DemoConfigAttribute config, System.Reflection.PropertyInfo property) { _property = property; this.OriginalConfigAttribute = config; if (!string.IsNullOrEmpty(config.Name)) { this.Name = config.Name; } else { this.Name = property.Name; } Type propType = property.PropertyType; if (propType == typeof(bool)) { this.PresentaionHint = DemoConfigPresentaionHint.CheckBox; } else if (propType.IsEnum) { this.PresentaionHint = Mini.DemoConfigPresentaionHint.OptionBoxes; //find option var enumFields = propType.GetFields(); int j = enumFields.Length; _optionFields = new List<ExampleConfigValue>(j); for (int i = 0; i < j; ++i) { var enumField = enumFields[i]; if (enumField.IsStatic) { //use field name or note that assoc with its field name string fieldNameOrNote = enumField.Name; var foundNotAttr = enumField.GetCustomAttributes(typeof(NoteAttribute), false); if (foundNotAttr.Length > 0) { fieldNameOrNote = ((NoteAttribute)foundNotAttr[0]).Desc; } _optionFields.Add(new ExampleConfigValue(property, enumField, fieldNameOrNote)); } } } else if (propType == typeof(Int32)) { this.PresentaionHint = DemoConfigPresentaionHint.SlideBarDiscrete; } else if (propType == typeof(double)) { this.PresentaionHint = DemoConfigPresentaionHint.SlideBarContinuous_R8; } else if (propType == typeof(float)) { this.PresentaionHint = DemoConfigPresentaionHint.SlideBarContinuous_R4; } else { //config with custom attribute group var foundAttrs = propType.GetCustomAttributes(typeof(DemoConfigGroupAttribute), false); if (foundAttrs.Length == 1) { this.PresentaionHint = DemoConfigPresentaionHint.ConfigGroup; } else { this.PresentaionHint = DemoConfigPresentaionHint.TextBox; } } } public string Name { get; } public DemoConfigAttribute OriginalConfigAttribute { get; } public DemoConfigPresentaionHint PresentaionHint { get; } public Type DataType => _property.PropertyType; public void InvokeSet(object target, object value) { _property.GetSetMethod().Invoke(target, new object[] { value }); } public object InvokeGet(object target) { return _property.GetGetMethod().Invoke(target, null); } public List<ExampleConfigValue> GetOptionFields() => _optionFields; EventHandler _updatePresentationValueHandler; public void SetUpdatePresentationValueHandler(EventHandler updatePresentationValue) { _updatePresentationValueHandler = updatePresentationValue; } public void InvokeUpdatePresentationValue() { _updatePresentationValueHandler?.Invoke(this, EventArgs.Empty); } } public class ExampleAndDesc { readonly static Type s_demoConfigAttrType = typeof(DemoConfigAttribute); readonly static Type s_infoAttrType = typeof(InfoAttribute); readonly static Type s_demoAction = typeof(DemoActionAttribute); readonly List<ExampleConfigDesc> _configList = new List<ExampleConfigDesc>(); readonly List<ExampleAction> _actionList = new List<ExampleAction>(); readonly List<ExampleGroupConfigDesc> _groupConfigs = new List<ExampleGroupConfigDesc>(); public ExampleAndDesc(Type t, string name) { this.Type = t; this.Name = name; this.OrderCode = ""; //var p1 = t.GetProperties(); InfoAttribute[] exInfoList = t.GetCustomAttributes(s_infoAttrType, false) as InfoAttribute[]; int m = exInfoList.Length; if (m > 0) { for (int n = 0; n < m; ++n) { InfoAttribute info = exInfoList[n]; if (!string.IsNullOrEmpty(info.OrderCode)) { this.OrderCode = info.OrderCode; } if (!string.IsNullOrEmpty(info.Description)) { this.Description += " " + info.Description; } AvailableOn |= info.AvailableOn; } } if (AvailableOn == AvailableOn.Empty) { //if user dose not specific then //assume available on All AvailableOn |= AvailableOn.Agg | AvailableOn.GLES | AvailableOn.GdiPlus; } if (string.IsNullOrEmpty(this.Description)) { this.Description = this.Name; } foreach (var property in t.GetProperties()) { //1. var foundAttrs = property.GetCustomAttributes(s_demoConfigAttrType, true); if (foundAttrs.Length > 0) { //this is configurable attrs Type propertyType = property.PropertyType; if (propertyType.IsClass && CreateExampleConfigGroup((DemoConfigAttribute)foundAttrs[0], property)) { //check if config group or not //if yes=> the the config group is created with CreateExampleConfigGroup() //nothing to do more here //else => go the another else block } else { _configList.Add(new ExampleConfigDesc((DemoConfigAttribute)foundAttrs[0], property)); } } } foreach (var met in t.GetMethods()) { //only public and instance method if (met.IsStatic) continue; if (met.DeclaringType == t) { if (met.GetParameters().Length == 0) { var foundAttrs = met.GetCustomAttributes(s_demoAction, false); if (foundAttrs.Length > 0) { //this is configurable attrs _actionList.Add(new ExampleAction((DemoActionAttribute)foundAttrs[0], met)); } } } } //------ //some config is group config //... so extract more from that //------ } bool CreateExampleConfigGroup(DemoConfigAttribute configAttr, System.Reflection.PropertyInfo prop) { Type configGroup = prop.PropertyType; var configGroupAttrs = configGroup.GetCustomAttributes(typeof(DemoConfigGroupAttribute), false); if (configGroupAttrs.Length > 0) { //reflection this type ExampleGroupConfigDesc groupConfigDesc = new ExampleGroupConfigDesc((DemoConfigGroupAttribute)configGroupAttrs[0], configGroup); groupConfigDesc.OwnerProperty = prop; List<ExampleConfigDesc> configList = groupConfigDesc._configList; List<ExampleAction> exActionList = groupConfigDesc._configActionList; // foreach (var property in configGroup.GetProperties()) { //1. var foundAttrs = property.GetCustomAttributes(s_demoConfigAttrType, true); if (foundAttrs.Length > 0) { //in this version: no further subgroup configList.Add(new ExampleConfigDesc((DemoConfigAttribute)foundAttrs[0], property)); } } foreach (var met in configGroup.GetMethods()) { //only public and instance method if (met.IsStatic) continue; if (met.DeclaringType == configGroup) { if (met.GetParameters().Length == 0) { var foundAttrs = met.GetCustomAttributes(s_demoAction, false); if (foundAttrs.Length > 0) { //this is configurable attrs exActionList.Add(new ExampleAction((DemoActionAttribute)foundAttrs[0], met)); } } } } //------------ _groupConfigs.Add(groupConfigDesc); return true; } return false; } public AvailableOn AvailableOn { get; } public Type Type { get; } public string Name { get; } public override string ToString() { return this.OrderCode + " : " + this.Name; } public List<ExampleConfigDesc> GetConfigList() => _configList; public List<ExampleAction> GetActionList() => _actionList; public List<ExampleGroupConfigDesc> GetGroupConfigList() => _groupConfigs; public string Description { get; } public string OrderCode { get; } public bool IsAvailableOn(AvailableOn availablePlatform) { return ((int)AvailableOn & (int)availablePlatform) != 0; } } public class ExampleConfigValue { readonly System.Reflection.FieldInfo _fieldInfo; readonly System.Reflection.PropertyInfo _property; public ExampleConfigValue(System.Reflection.PropertyInfo property, System.Reflection.FieldInfo fieldInfo, string name) { _property = property; _fieldInfo = fieldInfo; this.Name = name; this.ValueAsInt32 = (int)fieldInfo.GetValue(null); } public string Name { get; } public int ValueAsInt32 { get; } public void InvokeSet(object target) { _property.GetSetMethod().Invoke(target, new object[] { ValueAsInt32 }); } } }
LayoutFarm/PixelFarm
src/Tests/TestSamples_Painting_Focus/00_DemoBase/DemoBase1.cs
C#
bsd-2-clause
18,127
/* * Copyright 2008-2017 Katherine Flavel * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <limits.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <re/re.h> static int re_fprint(FILE *f, enum re_dialect dialect, const char *s) { char start, end; assert(f != NULL); assert(s != NULL); if (dialect & RE_GROUP) { start = '['; end = ']'; } else { dialect &= ~RE_GROUP; switch (dialect) { case RE_LITERAL: start = '\''; end = start; break; case RE_GLOB: start = '\"'; end = start; break; default: start = '/'; end = start; break; } } /* TODO: escape per surrounding delim */ return fprintf(f, "%c%s%c", start, s, end); } void re_ferror(FILE *f, enum re_dialect dialect, const struct re_err *err, const char *file, const char *s) { assert(f != NULL); assert(err != NULL); if (file != NULL) { fprintf(f, "%s", file); } if (s != NULL) { if (file != NULL) { fprintf(f, ": "); } re_fprint(f, dialect, s); } if (err->e & RE_MARK) { assert(err->end.byte >= err->start.byte); if (file != NULL || s != NULL) { fprintf(f, ":"); } if (err->end.byte == err->start.byte) { fprintf(f, "%u", err->start.byte + 1); } else { fprintf(f, "%u-%u", err->start.byte + 1, err->end.byte + 1); } } switch (err->e) { case RE_EHEXRANGE: fprintf(f, ": Hex escape %s out of range", err->esc); break; case RE_EOCTRANGE: fprintf(f, ": Octal escape %s out of range", err->esc); break; case RE_ECOUNTRANGE: fprintf(f, ": Count %s out of range", err->esc); break; default: fprintf(f, ": %s", re_strerror(err->e)); break; } switch (err->e) { case RE_EHEXRANGE: fprintf(f, ": expected \\0..\\x%X inclusive", UCHAR_MAX); break; case RE_EOCTRANGE: fprintf(f, ": expected \\0..\\%o inclusive", UCHAR_MAX); break; case RE_ECOUNTRANGE: fprintf(f, ": expected 1..%u inclusive", UINT_MAX); break; case RE_EXESC: fprintf(f, " \\0..\\x%X inclusive", UCHAR_MAX); break; case RE_EXCOUNT: fprintf(f, " 1..%u inclusive", UINT_MAX); break; case RE_ENEGCOUNT: fprintf(f, " {%u,%u}", err->m, err->n); break; case RE_EBADCP: fprintf(f, ": U+%06lX", err->cp); break; default: ; } /* TODO: escape */ switch (err->e) { case RE_ENEGRANGE: fprintf(f, " [%s]", err->set); break; default: ; } fprintf(f, "\n"); } void re_perror(enum re_dialect dialect, const struct re_err *err, const char *file, const char *s) { re_ferror(stderr, dialect, err, file, s); }
katef/libfsm
src/libre/perror.c
C
bsd-2-clause
2,599
package com.joshng.util.concurrent; import java.util.concurrent.Future; /** * Created by: josh 10/22/13 2:04 PM */ public interface Cancellable { static Cancellable extendFuture(final Future future) { if (future instanceof Cancellable) return (Cancellable) future; return future::cancel; } boolean cancel(boolean mayInterruptIfRunning); }
joshng/papaya
papaya/src/main/java/com/joshng/util/concurrent/Cancellable.java
Java
bsd-2-clause
358
#include <cprocessing/cprocessing.hpp> using namespace cprocessing; #include "VariableScope.hpp" /** * Variable Scope. * * Variables have a global or local "scope". * For example, variables declared within either the * setup() or draw() functions may be only used in these * functions. Global variables, variables declared outside * of setup() and draw(), may be used anywhere within the program. * If a local variable is declared with the same name as a * global variable, the program will use the local variable to make * its calculations within the current scope. Variables are localized * within each block, the space between a { and }. */ int a = 80; // Create a global variable "a" void setup() { size(640, 360); background(0); stroke(255); noLoop(); } void draw() { // Draw a line using the global variable "a" line(a, 0, a, height); // Create a new variable "a" local to the for() statement for (int a = 120; a < 200; a += 2) { line(a, 0, a, height); } // Create a new variable "a" local to the draw() function int a = 300; // Draw a line using the new local variable "a" line(a, 0, a, height); // Make a call to the custom function drawAnotherLine() drawAnotherLine(); // Make a call to the custom function setYetAnotherLine() drawYetAnotherLine(); } void drawAnotherLine() { // Create a new variable "a" local to this method int a = 320; // Draw a line using the local variable "a" line(a, 0, a, height); } void drawYetAnotherLine() { // Because no new local variable "a" is set, // this lines draws using the original global // variable "a" which is set to the value 20. line(a+2, 0, a+2, height); }
whackashoe/cprocessing
examples/Basics/Data/VariableScope/VariableScope.cpp
C++
bsd-2-clause
1,707
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-prop-obj-init.case // - src/dstr-binding/default/cls-decl-meth-dflt.template /*--- description: Object binding pattern with "nested" object binding pattern using initializer (class expression method (default parameter)) esid: sec-runtime-semantics-bindingclassdeclarationevaluation es6id: 14.5.15 features: [destructuring-binding, default-parameters] flags: [generated] info: | ClassDeclaration : class BindingIdentifier ClassTail 1. Let className be StringValue of BindingIdentifier. 2. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] 14.3.8 Runtime Semantics: DefineMethod MethodDefinition : PropertyName ( StrictFormalParameters ) { FunctionBody } [...] 6. Let closure be FunctionCreate(kind, StrictFormalParameters, FunctionBody, scope, strict). If functionPrototype was passed as a parameter then pass its value as the functionPrototype optional argument of FunctionCreate. [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization [...] 3. If Initializer is present and v is undefined, then a. Let defaultValue be the result of evaluating Initializer. b. Let v be GetValue(defaultValue). c. ReturnIfAbrupt(v). 4. Return the result of performing BindingInitialization for BindingPattern passing v and environment as arguments. ---*/ var callCount = 0; class C { method({ w: { x, y, z } = { x: 4, y: 5, z: 6 } } = { w: undefined }) { assert.sameValue(x, 4); assert.sameValue(y, 5); assert.sameValue(z, 6); assert.throws(ReferenceError, function() { w; }); callCount = callCount + 1; } }; new C().method(); assert.sameValue(callCount, 1, 'method invoked exactly once');
sebastienros/jint
Jint.Tests.Test262/test/language/statements/class/dstr-meth-dflt-obj-ptrn-prop-obj-init.js
JavaScript
bsd-2-clause
2,859
// // audio-sender.h // ndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #ifndef __ndnrtc__audio_thread__ #define __ndnrtc__audio_thread__ #include <boost/thread.hpp> #include <ndn-cpp/data.hpp> #include "params.hpp" #include "ndnrtc-object.hpp" #include "audio-capturer.hpp" #include "frame-data.hpp" #include "estimators.hpp" namespace ndnrtc { struct Mutable; template <typename T> class AudioBundlePacketT; class AudioThread; class IAudioThreadCallback { public: /** * This is called when audio bundle consisting of RTP/RTCP packets * is ready. * @param threadName Name of the audio media thread * @param bundleNo Sequential bundle number * @param packet Shared pointer for bundle packet * @note This is called on audio system thread * @see AudioController */ virtual void onSampleBundle(std::string threadName, uint64_t bundleNo, boost::shared_ptr<AudioBundlePacketT<Mutable>> packet) = 0; }; class AudioThread : public NdnRtcComponent, public IAudioSampleConsumer { public: AudioThread(const AudioThreadParams &params, const AudioCaptureParams &captureParams, IAudioThreadCallback *callback, size_t bundleWireLength = 1000); ~AudioThread(); void start(); void stop(); std::string getName() const { return threadName_; } bool isRunning() const { return isRunning_; } std::string getCodec() const { return codec_; } double getRate() const; uint64_t getBundleNo() const { return bundleNo_; } void setLogger(boost::shared_ptr<ndnlog::new_api::Logger> logger); private: AudioThread(const AudioThread &) = delete; uint64_t bundleNo_; estimators::FreqMeter rateMeter_; std::string threadName_, codec_; IAudioThreadCallback *callback_; boost::shared_ptr<AudioBundlePacketT<Mutable>> bundle_; AudioCapturer capturer_; boost::atomic<bool> isRunning_; void onDeliverRtpFrame(unsigned int len, uint8_t *data); void onDeliverRtcpFrame(unsigned int len, uint8_t *data); void deliver(const AudioBundlePacketT<Mutable>::AudioSampleBlob &blob); }; } #endif /* defined(__ndnrtc__audio_thread__) */
remap/ndnrtc
cpp/src/audio-thread.hpp
C++
bsd-2-clause
2,351
class Texlive < Formula include Language::Python::Shebang include Language::Python::Virtualenv desc "Free software distribution for the TeX typesetting system" homepage "https://www.tug.org/texlive/" url "https://github.com/TeX-Live/texlive-source/archive/refs/tags/svn58837.tar.gz" sha256 "0afa6919e44675b7afe0fa45344747afef07b6ee98eeb14ff6a2ef78f458fc12" license :public_domain head "https://github.com/TeX-Live/texlive-source.git", branch: "trunk" livecheck do url :stable regex(%r{href=["']?[^"' >]*?/tag/\D+(\d+(?:\.\d+)*)["' >]}i) strategy :github_latest end bottle do sha256 arm64_big_sur: "f0038b8dcf103be8c0a244fe468b19453b7d87d114a407d4491d68cb0a43fd40" sha256 big_sur: "499d3a4288ce44171bd03c8302cfed3c82a9c8068b9bc906a561f1ceef09de6c" sha256 catalina: "ff3e7293bdf2febf0320060541a9320ca31ec61dd434eeb2f537a84e4cda0f5b" sha256 mojave: "7c27168b1a8592bc78b82ec0d92a87595bce2a77f7b96d9eb69af49af5c4d9e6" sha256 x86_64_linux: "9100a01d16c8e182e31c78d531ca806419e70beab6c08e10d80e778231b12743" end depends_on "cairo" depends_on "clisp" depends_on "fontconfig" depends_on "freetype" depends_on "gd" depends_on "ghostscript" depends_on "gmp" depends_on "graphite2" depends_on "harfbuzz" depends_on "libpng" depends_on "libxft" depends_on "lua" depends_on "luajit-openresty" depends_on "mpfr" depends_on "openjdk" depends_on "openssl@1.1" depends_on "perl" depends_on "pixman" depends_on "potrace" depends_on "pstoedit" depends_on "python@3.9" uses_from_macos "icu4c" uses_from_macos "ncurses" uses_from_macos "ruby" uses_from_macos "tcl-tk" uses_from_macos "zlib" on_linux do depends_on "pkg-config" => :build depends_on "gcc" depends_on "libice" depends_on "libsm" depends_on "libx11" depends_on "libxaw" depends_on "libxext" depends_on "libxmu" depends_on "libxpm" depends_on "libxt" depends_on "mesa" end fails_with gcc: "5" resource "texlive-extra" do url "https://ftp.math.utah.edu/pub/tex/historic/systems/texlive/2021/texlive-20210325-extra.tar.xz" sha256 "46a3f385d0b30893eec6b39352135d2929ee19a0a81df2441bfcaa9f6c78339c" end resource "install-tl" do url "https://ftp.math.utah.edu/pub/tex/historic/systems/texlive/2021/install-tl-unx.tar.gz" sha256 "74eac0855e1e40c8db4f28b24ef354bd7263c1f76031bdc02b52156b572b7a1d" end resource "texlive-texmf" do url "https://ftp.math.utah.edu/pub/tex/historic/systems/texlive/2021/texlive-20210325-texmf.tar.xz" sha256 "ff12d436c23e99fb30aad55924266104356847eb0238c193e839c150d9670f1c" end resource "Module::Build" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Module-Build-0.4231.tar.gz" sha256 "7e0f4c692c1740c1ac84ea14d7ea3d8bc798b2fb26c09877229e04f430b2b717" end resource "ExtUtils::Config" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Config-0.008.tar.gz" sha256 "ae5104f634650dce8a79b7ed13fb59d67a39c213a6776cfdaa3ee749e62f1a8c" end resource "ExtUtils::Helpers" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-Helpers-0.026.tar.gz" sha256 "de901b6790a4557cf4ec908149e035783b125bf115eb9640feb1bc1c24c33416" end resource "ExtUtils::InstallPaths" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/ExtUtils-InstallPaths-0.012.tar.gz" sha256 "84735e3037bab1fdffa3c2508567ad412a785c91599db3c12593a50a1dd434ed" end resource "Module::Build::Tiny" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/Module-Build-Tiny-0.039.tar.gz" sha256 "7d580ff6ace0cbe555bf36b86dc8ea232581530cbeaaea09bccb57b55797f11c" end resource "Digest::SHA1" do url "https://cpan.metacpan.org/authors/id/G/GA/GAAS/Digest-SHA1-2.13.tar.gz" sha256 "68c1dac2187421f0eb7abf71452a06f190181b8fc4b28ededf5b90296fb943cc" end resource "Try::Tiny" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/Try-Tiny-0.30.tar.gz" sha256 "da5bd0d5c903519bbf10bb9ba0cb7bcac0563882bcfe4503aee3fb143eddef6b" end resource "Path::Tiny" do url "https://cpan.metacpan.org/authors/id/D/DA/DAGOLDEN/Path-Tiny-0.118.tar.gz" sha256 "32138d8d0f4c9c1a84d2a8f91bc5e913d37d8a7edefbb15a10961bfed560b0fd" end resource "File::Copy::Recursive" do url "https://cpan.metacpan.org/authors/id/D/DM/DMUEY/File-Copy-Recursive-0.45.tar.gz" sha256 "d3971cf78a8345e38042b208bb7b39cb695080386af629f4a04ffd6549df1157" end resource "File::Which" do url "https://cpan.metacpan.org/authors/id/P/PL/PLICEASE/File-Which-1.27.tar.gz" sha256 "3201f1a60e3f16484082e6045c896842261fc345de9fb2e620fd2a2c7af3a93a" end resource "IPC::System::Simple" do url "https://cpan.metacpan.org/authors/id/J/JK/JKEENAN/IPC-System-Simple-1.30.tar.gz" sha256 "22e6f5222b505ee513058fdca35ab7a1eab80539b98e5ca4a923a70a8ae9ba9e" end resource "URI" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/URI-5.09.tar.gz" sha256 "03e63ada499d2645c435a57551f041f3943970492baa3b3338246dab6f1fae0a" end resource "TimeDate" do url "https://cpan.metacpan.org/authors/id/A/AT/ATOOMIC/TimeDate-2.33.tar.gz" sha256 "c0b69c4b039de6f501b0d9f13ec58c86b040c1f7e9b27ef249651c143d605eb2" end resource "Crypt::RC4" do url "https://cpan.metacpan.org/authors/id/S/SI/SIFUKURT/Crypt-RC4-2.02.tar.gz" sha256 "5ec4425c6bc22207889630be7350d99686e62a44c6136960110203cd594ae0ea" end resource "Digest::Perl::MD5" do url "https://cpan.metacpan.org/authors/id/D/DE/DELTA/Digest-Perl-MD5-1.9.tar.gz" sha256 "7100cba1710f45fb0e907d8b1a7bd8caef35c64acd31d7f225aff5affeecd9b1" end resource "IO::Scalar" do url "https://cpan.metacpan.org/authors/id/C/CA/CAPOEIRAB/IO-Stringy-2.113.tar.gz" sha256 "51220fcaf9f66a639b69d251d7b0757bf4202f4f9debd45bdd341a6aca62fe4e" end resource "OLE::Storage_Lite" do url "https://cpan.metacpan.org/authors/id/J/JM/JMCNAMARA/OLE-Storage_Lite-0.20.tar.gz" sha256 "ab18a6171c0e08ea934eea14a0ab4f3a8909975dda9da42124922eb41e84f8ba" end resource "Spreadsheet::ParseExcel" do url "https://cpan.metacpan.org/authors/id/D/DO/DOUGW/Spreadsheet-ParseExcel-0.65.tar.gz" sha256 "6ec4cb429bd58d81640fe12116f435c46f51ff1040c68f09cc8b7681c1675bec" end resource "Encode::Locale" do url "https://cpan.metacpan.org/authors/id/G/GA/GAAS/Encode-Locale-1.05.tar.gz" sha256 "176fa02771f542a4efb1dbc2a4c928e8f4391bf4078473bd6040d8f11adb0ec1" end resource "HTTP::Date" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTTP-Date-6.05.tar.gz" sha256 "365d6294dfbd37ebc51def8b65b81eb79b3934ecbc95a2ec2d4d827efe6a922b" end resource "LWP::Mediatypes" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/LWP-MediaTypes-6.04.tar.gz" sha256 "8f1bca12dab16a1c2a7c03a49c5e58cce41a6fec9519f0aadfba8dad997919d9" end resource "IO::HTML" do url "https://cpan.metacpan.org/authors/id/C/CJ/CJM/IO-HTML-1.004.tar.gz" sha256 "c87b2df59463bbf2c39596773dfb5c03bde0f7e1051af339f963f58c1cbd8bf5" end resource "HTTP::Request::Common" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTTP-Message-6.33.tar.gz" sha256 "23b967f71b852cb209ec92a1af6bac89a141dff1650d69824d29a345c1eceef7" end resource "HTML::Tagset" do url "https://cpan.metacpan.org/authors/id/P/PE/PETDANCE/HTML-Tagset-3.20.tar.gz" sha256 "adb17dac9e36cd011f5243881c9739417fd102fce760f8de4e9be4c7131108e2" end resource "HTML::Parser" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTML-Parser-3.76.tar.gz" sha256 "64d9e2eb2b420f1492da01ec0e6976363245b4be9290f03f10b7d2cb63fa2f61" end resource "HTML::TreeBuilder" do url "https://cpan.metacpan.org/authors/id/K/KE/KENTNL/HTML-Tree-5.07.tar.gz" sha256 "f0374db84731c204b86c1d5b90975fef0d30a86bd9def919343e554e31a9dbbf" end resource "File::Slurper" do url "https://cpan.metacpan.org/authors/id/L/LE/LEONT/File-Slurper-0.012.tar.gz" sha256 "4efb2ea416b110a1bda6f8133549cc6ea3676402e3caf7529fce0313250aa578" end resource "Font::Metrics" do url "https://cpan.metacpan.org/authors/id/G/GA/GAAS/Font-AFM-1.20.tar.gz" sha256 "32671166da32596a0f6baacd0c1233825a60acaf25805d79c81a3f18d6088bc1" end resource "HTML::FormatText" do url "https://cpan.metacpan.org/authors/id/N/NI/NIGELM/HTML-Formatter-2.16.tar.gz" sha256 "cb0a0dd8aa5e8ba9ca214ce451bf4df33aa09c13e907e8d3082ddafeb30151cc" end resource "File::Listing" do url "https://cpan.metacpan.org/authors/id/P/PL/PLICEASE/File-Listing-6.14.tar.gz" sha256 "15b3a4871e23164a36f226381b74d450af41f12cc94985f592a669fcac7b48ff" end resource "HTTP::Cookies" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTTP-Cookies-6.10.tar.gz" sha256 "e36f36633c5ce6b5e4b876ffcf74787cc5efe0736dd7f487bdd73c14f0bd7007" end resource "HTTP::Daemon" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTTP-Daemon-6.12.tar.gz" sha256 "df47bed10c38670c780fd0116867d5fd4693604acde31ba63380dce04c4e1fa6" end resource "HTTP::Negotiate" do url "https://cpan.metacpan.org/authors/id/G/GA/GAAS/HTTP-Negotiate-6.01.tar.gz" sha256 "1c729c1ea63100e878405cda7d66f9adfd3ed4f1d6cacaca0ee9152df728e016" end resource "Net::HTTP" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/Net-HTTP-6.21.tar.gz" sha256 "375aa35b76be99f06464089174d66ac76f78ce83a5c92a907bbfab18b099eec4" end resource "WWW::RobotRules" do url "https://cpan.metacpan.org/authors/id/G/GA/GAAS/WWW-RobotRules-6.02.tar.gz" sha256 "46b502e7a288d559429891eeb5d979461dd3ecc6a5c491ead85d165b6e03a51e" end resource "LWP" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/libwww-perl-6.57.tar.gz" sha256 "30c242359cb808f3fe2b115fb90712410557f0786ad74844f9801fd719bc42f8" end resource "CGI" do url "https://cpan.metacpan.org/authors/id/L/LE/LEEJO/CGI-4.53.tar.gz" sha256 "c67e732f3c96bcb505405fd944f131fe5c57b46e5d02885c00714c452bf14e60" end resource "HTML::Form" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/HTML-Form-6.07.tar.gz" sha256 "7daa8c7eaff4005501c3431c8bf478d58bbee7b836f863581aa14afe1b4b6227" end resource "HTML::Server::Simple" do url "https://cpan.metacpan.org/authors/id/B/BP/BPS/HTTP-Server-Simple-0.52.tar.gz" sha256 "d8939fa4f12bd6b8c043537fd0bf96b055ac3686b9cdd9fa773dca6ae679cb4c" end resource "WWW::Mechanize" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/WWW-Mechanize-2.05.tar.gz" sha256 "0c77284103e93d098fa8b277802b589cfd1df8c11a8968e5ecd377f863c21dd9" end resource "Mozilla::CA" do url "https://cpan.metacpan.org/authors/id/A/AB/ABH/Mozilla-CA-20200520.tar.gz" sha256 "b3ca0002310bf24a16c0d5920bdea97a2f46e77e7be3e7377e850d033387c726" end resource "Net::SSLeay" do url "https://cpan.metacpan.org/authors/id/C/CH/CHRISN/Net-SSLeay-1.90.tar.gz" sha256 "f8696cfaca98234679efeedc288a9398fcf77176f1f515dbc589ada7c650dc93" end resource "IO::Socket::SSL" do url "https://cpan.metacpan.org/authors/id/S/SU/SULLR/IO-Socket-SSL-2.072.tar.gz" sha256 "b5bee81db3905a9069340a450a48e1e1b32dec4ede0064f5703bafb9a707b89d" end resource "LWP::Protocol::https" do url "https://cpan.metacpan.org/authors/id/O/OA/OALDERS/LWP-Protocol-https-6.10.tar.gz" sha256 "cecfc31fe2d4fc854cac47fce13d3a502e8fdfe60c5bc1c09535743185f2a86c" end resource "Tk" do url "https://cpan.metacpan.org/authors/id/S/SR/SREZIC/Tk-804.036.tar.gz" sha256 "32aa7271a6bdfedc3330119b3825daddd0aa4b5c936f84ad74eabb932a200a5e" end resource "Pygments" do url "https://files.pythonhosted.org/packages/b7/b3/5cba26637fe43500d4568d0ee7b7362de1fb29c0e158d50b4b69e9a40422/Pygments-2.10.0.tar.gz" sha256 "f398865f7eb6874156579fdf36bc840a03cab64d1cde9e93d68f46a425ec52c6" end def install # Install Perl resources ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" ENV["PERL_MM_USE_DEFAULT"] = "1" ENV["OPENSSL_PREFIX"] = Formula["openssl@1.1"].opt_prefix tex_resources = %w[texlive-extra install-tl texlive-texmf] python_resources = %w[Pygments] resources.each do |r| r.stage do next if tex_resources.include? r.name next if python_resources.include? r.name if File.exist? "Makefile.PL" system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}", "CCFLAGS=-I#{Formula["freetype"].opt_include}/freetype2" system "make" system "make", "install" else system "perl", "Build.PL", "--install_base", libexec system "./Build" system "./Build", "install" end end end # Install Python resources venv = virtualenv_create(libexec, "python3") venv.pip_install resource("Pygments") # Install TeXLive resources resource("texlive-extra").stage do share.install "tlpkg" end resource("install-tl").stage do cd "tlpkg" do (share/"tlpkg").install "installer" (share/"tlpkg").install "tltcl" end end resource("texlive-texmf").stage do share.install "texmf-dist" end # Clean unused files rm_rf share/"texmf-dist/doc" rm_rf share/"tlpkg/installer/wget" rm_rf share/"tlpkg/installer/xz" # Set up config files to use the correct path for the TeXLive root inreplace buildpath/"texk/kpathsea/texmf.cnf", "TEXMFROOT = $SELFAUTOPARENT", "TEXMFROOT = $SELFAUTODIR/share" inreplace share/"texmf-dist/web2c/texmfcnf.lua", "selfautoparent:texmf", "selfautodir:share/texmf" # Fix path resolution in some scripts. The fix for tlmgr.pl, TLUTils.pm, and # tlshell is being upstreamed here: https://www.tug.org/pipermail/tex-live/2021-September/047394.html. # The fix for cjk-gs-integrate.pl is being upstreamed here: https://github.com/texjporg/cjk-gs-support/pull/50. # The author of crossrefware and pedigree-perl has been contacted by email. pathfix_files = %W[ #{buildpath}/texk/texlive/linked_scripts/cjk-gs-integrate/cjk-gs-integrate.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/bbl2bib.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/bibdoiadd.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/bibmradd.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/biburl2doi.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/bibzbladd.pl #{buildpath}/texk/texlive/linked_scripts/crossrefware/ltx2crossrefxml.pl #{buildpath}/texk/texlive/linked_scripts/texlive/tlmgr.pl #{buildpath}/texk/texlive/linked_scripts/pedigree-perl/pedigree.pl #{buildpath}/texk/texlive/linked_scripts/tlshell/tlshell.tcl #{share}/tlpkg/TeXLive/TLUtils.pm ] inreplace pathfix_files, "SELFAUTOPARENT", "TEXMFROOT" args = std_configure_args + [ "--disable-dvisvgm", # needs its own formula "--disable-missing", "--disable-native-texlive-build", # needed when doing a distro build "--disable-static", "--disable-ps2eps", # provided by ps2eps formula "--disable-psutils", # provided by psutils formula "--disable-t1utils", # provided by t1utils formula "--enable-build-in-source-tree", "--enable-shared", "--enable-compiler-warnings=yes", "--with-banner-add=/#{tap.user}", "--with-system-clisp-runtime=system", "--with-system-cairo", "--with-system-freetype2", "--with-system-gd", "--with-system-gmp", "--with-system-graphite2", "--with-system-harfbuzz", "--with-system-icu", "--with-system-libpng", "--with-system-mpfr", "--with-system-ncurses", "--with-system-pixman", "--with-system-potrace", "--with-system-zlib", ] args << if OS.mac? "--without-x" else # Make sure xdvi uses xaw, even if motif is available "--with-xdvi-x-toolkit=xaw" end system "./configure", *args system "make" system "make", "install" system "make", "texlinks" # Create tlmgr config file. This file limits the actions that the user # can perform in 'system' mode, which would write to the cellar. 'tlmgr' should # be used with --usermode whenever possible. (share/"texmf-config/tlmgr/config").write <<~EOS allowed-actions=candidates,check,dump-tlpdb,help,info,list,print-platform,print-platform-info,search,show,version,init-usertree EOS # Delete some Perl scripts that are provided by existing formulae as newer versions. rm bin/"latexindent" # provided by latexindent formula rm bin/"latexdiff" # provided by latexdiff formula rm bin/"latexdiff-vc" # provided by latexdiff formula rm bin/"latexrevise" # provided by latexdiff formula # Wrap some Perl scripts in an env script so that they can find dependencies env_script_files = %w[ crossrefware/bbl2bib.pl crossrefware/bibdoiadd.pl crossrefware/bibmradd.pl crossrefware/biburl2doi.pl crossrefware/bibzbladd.pl crossrefware/ltx2crossrefxml.pl ctan-o-mat/ctan-o-mat.pl ctanify/ctanify ctanupload/ctanupload.pl exceltex/exceltex latex-git-log/latex-git-log pax/pdfannotextractor.pl ptex-fontmaps/kanji-fontmap-creator.pl purifyeps/purifyeps svn-multi/svn-multi.pl texdoctk/texdoctk.pl ulqda/ulqda.pl ] env_script_files.each do |perl_script| bin_name = File.basename(perl_script, ".pl") rm bin/bin_name (bin/bin_name).write_env_script(share/"texmf-dist/scripts"/perl_script, PERL5LIB: ENV["PERL5LIB"]) end # Wrap some Python scripts so they can find dependencies and fix depythontex. python_path = libexec/Language::Python.site_packages("python3") ENV.prepend_path "PYTHONPATH", python_path rm bin/"pygmentex" rm bin/"pythontex" rm bin/"depythontex" (bin/"pygmentex").write_env_script(share/"texmf-dist/scripts/pygmentex/pygmentex.py", PYTHONPATH: ENV["PYTHONPATH"]) (bin/"pythontex").write_env_script(share/"texmf-dist/scripts/pythontex/pythontex3.py", PYTHONPATH: ENV["PYTHONPATH"]) ln_sf share/"texmf-dist/scripts/pythontex/depythontex3.py", bin/"depythontex" # Rewrite shebangs in some Python scripts so they use brewed Python. python_shebang_rewrites = %w[ dviasm/dviasm.py latex-make/figdepth.py latex-make/gensubfig.py latex-make/latexfilter.py latex-make/svg2dev.py latex-make/svgdepth.py latex-papersize/latex-papersize.py lilyglyphs/lilyglyphs_common.py lilyglyphs/lily-glyph-commands.py lilyglyphs/lily-image-commands.py lilyglyphs/lily-rebuild-pdfs.py pdfbook2/pdfbook2 pygmentex/pygmentex.py pythontex/depythontex3.py pythontex/pythontex3.py pythontex/pythontex_install.py spix/spix.py texliveonfly/texliveonfly.py webquiz/webquiz webquiz/webquiz.py webquiz/webquiz_makequiz.py webquiz/webquiz_util.py ] python_shebang_rewrites.each do |python_script| rewrite_shebang detected_python_shebang, share/"texmf-dist/scripts"/python_script end # Delete ebong because it requires Python 2 rm bin/"ebong" # Initialize texlive environment ENV.prepend_path "PATH", bin system "fmtutil-sys", "--all" system "mtxrun", "--generate" system "mktexlsr" end test do assert_match "Usage", shell_output("#{bin}/tex --help") assert_match "revision", shell_output("#{bin}/tlmgr --version") assert_match "AMS mathematical facilities for LaTeX", shell_output("#{bin}/tlmgr info amsmath") (testpath/"test.latex").write <<~EOS \\documentclass[12pt]{article} \\usepackage[utf8]{inputenc} \\usepackage{amsmath} \\usepackage{lipsum} \\title{\\LaTeX\\ test} \\author{\\TeX\\ Team} \\date{September 2021} \\begin{document} \\maketitle \\section*{An equation with amsmath} \\begin{equation} \\label{eu_eqn} e^{\\pi i} + 1 = 0 \\end{equation} The beautiful equation \\ref{eu_eqn} is known as the Euler equation. \\section*{Lorem Ipsum} \\lipsum[3] \\lipsum[5] \\end{document} EOS assert_match "Output written on test.dvi", shell_output("#{bin}/latex #{testpath}/test.latex") assert_predicate testpath/"test.dvi", :exist? assert_match "Output written on test.pdf", shell_output("#{bin}/pdflatex #{testpath}/test.latex") assert_predicate testpath/"test.pdf", :exist? assert_match "This is dvips", shell_output("#{bin}/dvips #{testpath}/test.dvi 2>&1") assert_predicate testpath/"test.ps", :exist? end end
Moisan/homebrew-core
Formula/texlive.rb
Ruby
bsd-2-clause
20,789
class Plag < ApplicationRecord include Anemon belongs_to :doc belongs_to :user has_one :result @anemon = Anemon::Scrapper.new def self.crawl_and_scrap(url ,user ,doc) result = @anemon.crawl_and_scrap(url ,user ,doc) Plag.create({url: result[:url], filename: result[:filename], user: user, doc: doc}) if result end end
mureithi254/anti_plag
app/models/plag.rb
Ruby
bsd-2-clause
345
<?php namespace Zenith\Exception; class SOAPServiceException extends \Exception { /** * Status code * @var int */ protected $statusCode; /** * Status message * @var string */ protected $statusMessage; public function __construct($statusCode, $statusMessage) { $this->statusCode = $statusCode; $this->statusMessage = $statusMessage; $this->message = $statusMessage; } public function getStatusCode() { return $this->statusCode; } public function getStatusMessage() { return $this->statusMessage; } }
emaphp/zenith-framework
src/Zenith/Exception/SOAPServiceException.php
PHP
bsd-2-clause
539
using FlubuCore.Commanding; using Xunit; namespace FlubuCore.Tests.Commanding { public class FlubuConfigurationProviderTests { private FlubuConfigurationProvider _flubuConfigurationProvider; public FlubuConfigurationProviderTests() { _flubuConfigurationProvider = new FlubuConfigurationProvider(); } [Fact] public void BuildConfiguration_GetSimpleKeyValueSettingsFromJsonFile_Succesfull() { var dictionary = _flubuConfigurationProvider.GetConfiguration("appsettings.json"); Assert.Equal(2, dictionary.Count); Assert.Equal("value1_from_json", dictionary["option1"]); } [Fact] public void BuildConfiguration_GetComplexSettingsFromJsonFile_Succesfull() { var exception = Assert.Throws<FlubuConfigurationException>(() => _flubuConfigurationProvider.GetConfiguration("appsettings2.json")); Assert.Equal("Flubu supports only simple key/value JSON configuration.", exception.Message); } [Fact] public void BuildConfiguration_NonExistingJsonConfigurationFile_ReturnsEmptyDictionary() { var dictionary = _flubuConfigurationProvider.GetConfiguration("nonExist.json"); Assert.Empty(dictionary); } } }
flubu-core/flubu.core
src/FlubuCore.Tests/Commanding/FlubuConfigurationProviderTests.cs
C#
bsd-2-clause
1,331
/* Create the initial queues */ INSERT INTO pq_queue (name, scheduled, lock_expires, serial, idempotent) VALUES ('default', 'true', 'January 3 04:05:06 1999 UTC', 'false', 'false'); INSERT INTO pq_queue (name, scheduled, lock_expires, serial, idempotent) VALUES ('serial', 'true', 'January 3 04:05:06 1999 UTC', 'true', 'false'); INSERT INTO pq_queue (name, scheduled, lock_expires, serial, idempotent) VALUES ('failed', 'false', 'January 3 04:05:06 1999 UTC', 'false', 'false');
bretth/django-pq
pq/sql/queue.sql
SQL
bsd-2-clause
480
# Copyright (C) 2006 Tanaka Akira. 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. # # THIS SOFTWARE IS PROVIDED BY AUTHOR 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 AUTHOR 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. require 'clockcount.so' if ClockCount::CLOCKCOUNT_BITS < 64 require 'thread' class << ClockCount alias RawClockCount ClockCount public :RawClockCount attr_accessor :clock_hi attr_accessor :clock_lo end module ClockCount HI_STEP = 1 << ClockCount::CLOCKCOUNT_BITS end ClockCount.clock_hi = 0 ClockCount.clock_lo = ClockCount.RawClockCount module Kernel module_function def ClockCount Thread.exclusive { c2 = ClockCount.RawClockCount ClockCount.clock_hi += ClockCount::HI_STEP if ClockCount.clock_lo > c2 ClockCount.clock_lo = c2 ClockCount.clock_hi + c2 } end Thread.new { while true ClockCount() # call redefined version sleep 1 # shold work if less than 4GHz. end } end end
akr/clockcount
lib/clockcount.rb
Ruby
bsd-2-clause
2,091
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2019 Inviwo Foundation * 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. * * 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. * *********************************************************************************/ #ifndef IVW_MESHCONVERTER_H #define IVW_MESHCONVERTER_H #include <modules/base/basemoduledefine.h> #include <inviwo/core/common/inviwo.h> #include <inviwo/core/datastructures/geometry/mesh.h> namespace inviwo { namespace meshutil { /** * Will construct a new mesh out of the given mesh with its position and color buffer, if existing, * and all index buffers but with the DrawMode set to Points */ std::unique_ptr<Mesh> toPointMesh(const Mesh& mesh); /** * Will construct a new mesh out of the given mesh with its position and color buffer, if existing. * It will discard all IndexBuffes with DrawType equal to Points, copy all IndexBuffers with * DrawType equal to Lines, and construct IndexBuffers with lines out of all IndexBuffers with * DrawType equal to Triangles. */ std::unique_ptr<Mesh> toLineMesh(const Mesh& mesh); } // namespace meshutil } // namespace inviwo #endif // IVW_MESHCONVERTER_H
Sparkier/inviwo
modules/base/include/modules/base/algorithm/mesh/meshconverter.h
C
bsd-2-clause
2,507
<div data-bind="visible: isValidation, with: validationViewModel"> <div class="container" data-bind="visible: fetching"> <button class="btn btn-lg btn-warning center-block"> <span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading... </button> </div> <div data-bind="visible: !fetching()"> <div data-bind="visible: false === report()"> <table class="reportList"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Created</th> <th></th> </tr> </thead> <tbody data-bind="foreach: reportList"> <tr> <td data-bind="text: id, click: $parent.goToReport"></td> <td data-bind="liveEditor: name, click: name.edit"> <span class="view" data-bind="text: name"></span> <input class="edit" data-bind="value: name, executeOnEnter: name.stopEditing, focus: name.editing, event: { blur: name.stopEditing }" /> </td> <td data-bind="text: new Date($data.created() * 1000), click: $parent.goToReport"></td> <td> <a data-bind="click: $parent.deleteReport" aria-hidden="true" aria-label="Delete"> <span class="glyphicon glyphicon-trash"></span> </a> <a data-bind="click: $parent.downloadReport" aria-hidden="true" aria-label="Download"> <span class="glyphicon glyphicon-download-alt"></span> </a> </td> </tr> </tbody> </table> <div> <button class="btn btn-default" type="button" data-bind="click: newReport">New Report</button> </div> <table class="reportList" data-bind="visible: $root.config.admin"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Created</th> <th></th> </tr> </thead> <tbody data-bind="foreach: referenceList"> <tr> <td data-bind="text: id"></td> <td data-bind="liveEditor: name, click: name.edit"> <span class="view" data-bind="text: name"></span> <input class="edit" data-bind="value: name, executeOnEnter: name.stopEditing, focus: name.editing, event: { blur: name.stopEditing }" /> </td> <td data-bind="text: new Date($data.created() * 1000)"></td> <td> <a data-bind="click: $parent.deleteReference" aria-hidden="true" aria-label="Delete"> <span class="glyphicon glyphicon-trash"></span> </a> <a data-bind="click: $parent.downloadReference" aria-hidden="true" aria-label="Download"> <span class="glyphicon glyphicon-download-alt"></span> </a> </td> </tr> </tbody> </table> <div> <button class="btn btn-default" type="button" data-bind="click: newReference, visible: $root.config.admin">New Reference</button> </div> </div> <div data-bind="visible: report"> <p> Report: <span data-bind="text: report"></span> </p> <table class='table resultsSummary'> <thead> <tr> <th></th> <th>Tests not run</th> <th>Subtests not run</th> <th>Tests failed</th> <th>Subtests failed</th> </tr> </thead> <tbody> <tr> <td></td> <td data-bind="text: totalTestsNotRun"></td> <td data-bind="text: totalSubtestsNotRun"></td> <td data-bind="text: totalTestsFailed"></td> <td data-bind="text: totalSubtestsFailed"></td> </tr> </tbody> </table> <table class="reportLog" data-bind="visible: !fetching()"> <thead> <tr> <th>Type</th> <th>Test</th> <th>Subtest</th> <th>Message</th> </tr> </thead> <tbody data-bind="foreach: log"> <tr> <td data-bind="text: type"></td> <td data-bind="text: test"></td> <td data-bind="text: subtest"></td> <td data-bind="text: message"></td> </tr> </tbody> </table> <div class="row pull-right"> <ul class="pagination"> <li data-bind="css: { disabled: pageIndex() <= 1 }"> <a data-bind="click: function () { goToPage(1) }">|&laquo;</a> </li> <li data-bind="css: { disabled: pageIndex() <= 1 }"> <a data-bind="click: function () { goToPage(pageIndex() - 1) }">&laquo;</a> </li> <!-- ko foreach: pages --> <li data-bind="css: { active: $data == $parent.pageIndex(), disabled: '&hellip;' == $data }"> <a data-bind="text: $data, click: $parent.goToPage.bind($data)"></a> </li> <!-- /ko --> <li data-bind="css: { disabled: pageIndex() >= numPages() }"> <a data-bind="click: function () { goToPage(pageIndex() + 1) }">&raquo;</a> </li> <li data-bind="css: { disabled: pageIndex() >= numPages() }"> <a data-bind="click: function () { goToPage(numPages()) }">&raquo;|</a> </li> </ul> </div> </div> </div> </div>
jeremypoulter/WPT_Results_Collection_Server
html/tab-validation.html
HTML
bsd-2-clause
5,753
package com.atlassian.jira.plugins.dvcs.webwork; import com.atlassian.jira.config.FeatureManager; import com.atlassian.jira.issue.Issue; import com.atlassian.jira.security.PermissionManager; import com.atlassian.jira.software.api.permissions.SoftwareProjectPermissions; import com.atlassian.jira.user.ApplicationUser; import com.atlassian.plugin.PluginAccessor; import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static com.google.common.base.Preconditions.checkNotNull; @Component public class PanelVisibilityManager { private static final String DEVSUMMARY_PLUGIN_ID = "com.atlassian.jira.plugins.jira-development-integration-plugin"; private static final String LABS_OPT_IN = "jira.plugin.devstatus.phasetwo"; private final PermissionManager permissionManager; private final PluginAccessor pluginAccessor; private final FeatureManager featureManager; @Autowired @SuppressWarnings("SpringJavaAutowiringInspection") public PanelVisibilityManager(@ComponentImport PermissionManager permissionManager, @ComponentImport PluginAccessor pluginAccessor, @ComponentImport FeatureManager featureManager) { this.permissionManager = checkNotNull(permissionManager); this.pluginAccessor = checkNotNull(pluginAccessor); this.featureManager = checkNotNull(featureManager); } public boolean showPanel(Issue issue, ApplicationUser user) { return (!pluginAccessor.isPluginEnabled(DEVSUMMARY_PLUGIN_ID) || !featureManager.isEnabled(LABS_OPT_IN) || // JIRA 6.1.x was installed with 0.x of the devsummary plugin, everything else after will want to hide this panel pluginAccessor.getPlugin(DEVSUMMARY_PLUGIN_ID).getPluginInformation().getVersion().startsWith("0.")) && permissionManager.hasPermission(SoftwareProjectPermissions.VIEW_DEV_TOOLS, issue, user); } }
edgehosting/jira-dvcs-connector
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/webwork/PanelVisibilityManager.java
Java
bsd-2-clause
2,052
/* * Copyright (c) 2011-2022, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DART_CONSTRAINT_PGSBOXEDLCPSOLVER_HPP_ #define DART_CONSTRAINT_PGSBOXEDLCPSOLVER_HPP_ #include <vector> #include "dart/constraint/BoxedLcpSolver.hpp" namespace dart { namespace constraint { /// Implementation of projected Gauss-Seidel (PGS) LCP solver. class PgsBoxedLcpSolver : public BoxedLcpSolver { public: struct Option { int mMaxIteration; double mDeltaXThreshold; double mRelativeDeltaXTolerance; double mEpsilonForDivision; bool mRandomizeConstraintOrder; Option( int maxIteration = 30, double deltaXTolerance = 1e-6, double relativeDeltaXTolerance = 1e-3, double epsilonForDivision = 1e-9, bool randomizeConstraintOrder = false); }; // Documentation inherited. const std::string& getType() const override; /// Returns type for this class static const std::string& getStaticType(); // Documentation inherited. bool solve( int n, double* A, double* x, double* b, int nub, double* lo, double* hi, int* findex, bool earlyTermination) override; #ifndef NDEBUG // Documentation inherited. bool canSolve(int n, const double* A) override; #endif /// Sets options void setOption(const Option& option); /// Returns options. const Option& getOption() const; protected: Option mOption; mutable std::vector<int> mCacheOrder; mutable std::vector<double> mCacheD; mutable Eigen::VectorXd mCachedNormalizedA; mutable Eigen::MatrixXd mCachedNormalizedB; mutable Eigen::VectorXd mCacheZ; mutable Eigen::VectorXd mCacheOldX; }; } // namespace constraint } // namespace dart #endif // DART_CONSTRAINT_PGSBOXEDLCPSOLVER_HPP_
dartsim/dart
dart/constraint/PgsBoxedLcpSolver.hpp
C++
bsd-2-clause
3,315
//using EA; namespace EAAddinFramework.Utils { /// <summary> /// EA item (Diagram, Package, Element,..) to remember. It stores: GUID, ObjectType as String, ObjectType, EA object as Object /// </summary> public class EaItem { public string Guid { get; private set; } public string SqlObjectType { get; private set; } public EA.ObjectType EaObjectType {get; set;} public object EaObject { get; set; } #region Constructor /// <summary> /// Constructor of an EAItem /// </summary> /// <param name="guid"></param> /// <param name="sqlObjType"></param> /// <param name="eaObjectType"></param> /// <param name="eaObject"></param> public EaItem(string guid, string sqlObjType, EA.ObjectType eaObjectType, object eaObject) { Init(guid, sqlObjType, eaObjectType, eaObject); } /// <summary> /// Constructor /// </summary> /// <param name="guid"></param> /// <param name="sqlObjType"></param> /// <param name="eaObjectType"></param> public EaItem(string guid, string sqlObjType, EA.ObjectType eaObjectType) { Init(guid, sqlObjType, eaObjectType, null); } /// <summary> /// Constructor /// </summary> /// <param name="guid"></param> /// <param name="sqlObjType"></param> public EaItem(string guid, string sqlObjType) { Init(guid, sqlObjType, EA.ObjectType.otNone, null); } #endregion #region Initialize /// <summary> /// Initialize the EaItem /// </summary> /// <param name="guid"></param> /// <param name="sqlObjType"></param> /// <param name="objType"></param> /// <param name="eaObject"></param> private void Init(string guid, string sqlObjType, EA.ObjectType objType, object eaObject) { Guid = guid; SqlObjectType = sqlObjType; EaObjectType = objType; EaObject = eaObject; } #endregion } }
Helmut-Ortmann/EnterpriseArchitect_hoTools
AddinFramework/Utils/EaItem.cs
C#
bsd-2-clause
2,155
from setuptools import find_packages, setup from auspost_pac import __version__ as version setup( name='python-auspost-pac', version=version, license='BSD', author='Sam Kingston', author_email='sam@sjkwi.com.au', description='Python API for Australia Post\'s Postage Assessment Calculator (pac).', url='https://github.com/sjkingo/python-auspost-pac', install_requires=[ 'cached_property', 'frozendict', 'requests', ], packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', ], )
sjkingo/python-auspost-pac
setup.py
Python
bsd-2-clause
900
class Nlopt < Formula desc "Free/open-source library for nonlinear optimization" homepage "https://nlopt.readthedocs.io/" url "https://github.com/stevengj/nlopt/releases/download/nlopt-2.4.2/nlopt-2.4.2.tar.gz" sha256 "8099633de9d71cbc06cd435da993eb424bbcdbded8f803cdaa9fb8c6e09c8e89" revision 2 bottle do cellar :any sha256 "9b08f332287446d6eb32c7b6fdf3732b1459dae9b9d04af3bf11d7924d549ebc" => :mojave sha256 "8b24f8a85b1b9e553cfd97a88fb22093926fe787bbeeaa598636baf7adfb1ea3" => :high_sierra sha256 "183d661c2b34ff468162b4bcc3bc7c287bcab47ff1bd4b902ea00fe188db1e52" => :sierra sha256 "cfb26ea39b36e9a9ad472e2600864d040f02531ba2c922798f82455a25b73a30" => :el_capitan sha256 "eed62f227cdfd93ba00d7abe061b4136945a4511d67651d0fa4aa07b196b7b7d" => :yosemite end head do url "https://github.com/stevengj/nlopt.git" depends_on "cmake" => :build depends_on "swig" => :build end depends_on "numpy" => :recommended def install ENV.deparallelize if build.head? system "cmake", ".", *std_cmake_args, "-DBUILD_MATLAB=OFF", "-DBUILD_OCTAVE=OFF", "-DWITH_CXX=ON" else system "./configure", "--prefix=#{prefix}", "--enable-shared", "--with-cxx", "--without-octave" system "make" end system "make", "install" # Create library links for C programs %w[0.dylib dylib a].each do |suffix| lib.install_symlink "#{lib}/libnlopt_cxx.#{suffix}" => "#{lib}/libnlopt.#{suffix}" end end test do # Based on http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial#Example_in_C.2FC.2B.2B (testpath/"test.c").write <<~EOS #include <math.h> #include <nlopt.h> #include <stdio.h> double myfunc(unsigned n, const double *x, double *grad, void *my_func_data) { if (grad) { grad[0] = 0.0; grad[1] = 0.5 / sqrt(x[1]); } return sqrt(x[1]); } typedef struct { double a, b; } my_constraint_data; double myconstraint(unsigned n, const double *x, double *grad, void *data) { my_constraint_data *d = (my_constraint_data *) data; double a = d->a, b = d->b; if (grad) { grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b); grad[1] = -1.0; } return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]); } int main() { double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */ nlopt_opt opt; opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */ nlopt_set_lower_bounds(opt, lb); nlopt_set_min_objective(opt, myfunc, NULL); my_constraint_data data[2] = { {2,0}, {-1,1} }; nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8); nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8); nlopt_set_xtol_rel(opt, 1e-4); double x[2] = { 1.234, 5.678 }; /* some initial guess */ double minf; /* the minimum objective value, upon return */ if (nlopt_optimize(opt, x, &minf) < 0) return 1; else printf("found minimum at f(%g,%g) = %0.10g", x[0], x[1], minf); nlopt_destroy(opt); } EOS system ENV.cc, "test.c", "-o", "test", "-lnlopt", "-lm" assert_match "found minimum", shell_output("./test") end end
DomT4/homebrew-core
Formula/nlopt.rb
Ruby
bsd-2-clause
3,469
/* * WHEEL (Workflow in Hierarchical distributEd parallEL) * * Copyright (c) 2016-2017 Research Institute for Information Technology(RIIT), Kyushu University. All rights reserved. * Copyright (c) 2016-2017 Advanced Institute for Computational Science, RIKEN. All rights reserved. */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var fs = require("fs"); var path = require("path"); var os = require("os"); var logger = require("./logger"); var ServerConfig = require("./serverConfig"); var SwfType = require("./swfType"); var SwfState = require("./swfState"); /** * Utility for server */ var ServerUtility = (function () { function ServerUtility() { } /** * copy file * @param path_src source path string * @param path_dst destination path string */ ServerUtility.copyFile = function (path_src, path_dst) { if (!fs.existsSync(path_src)) { return; } var path_dst_file = path_dst; //if target is a directory a new file with the same name will be created if (fs.existsSync(path_dst) || fs.lstatSync(path_dst).isDirectory()) { path_dst_file = path.join(path_dst, path.basename(path_src)); } if (fs.existsSync(path_dst_file)) { fs.unlinkSync(path_dst_file); } fs.writeFileSync(path_dst_file, fs.readFileSync(path_src)); }; /** * copy file async * @param path_src source path string * @param path_dst destination path string * @param callback The function to call when we have finished copy file */ ServerUtility.copyFileAsync = function (path_src, path_dst, callback) { var path_dst_file = path_dst; var copy = function () { fs.readFile(path_src, function (err, data) { if (err) { callback(err); return; } fs.writeFile(path_dst_file, data, function (err) { if (err) { callback(err); return; } callback(); }); }); }; fs.stat(path_src, function (err, stat) { if (err) { callback(err); return; } fs.lstat(path_dst, function (err, stat) { if (!err && stat.isDirectory()) { path_dst_file = path.join(path_dst, path.basename(path_src)); } fs.stat(path_dst_file, function (err, stat) { if (err) { copy(); return; } fs.unlink(path_dst_file, function (err) { if (err) { callback(err); return; } copy(); }); }); }); }); }; /** * copy folder * @param path_src source path string * @param path_dst destination path string */ ServerUtility.copyFolder = function (path_src, path_dst) { if (!fs.existsSync(path_src)) { return; } if (!fs.existsSync(path_dst)) { fs.mkdirSync(path_dst); } //copy if (fs.lstatSync(path_src).isDirectory()) { var files = fs.readdirSync(path_src); files.forEach(function (name_base) { var path_src_child = path.join(path_src, name_base); if (fs.lstatSync(path_src_child).isDirectory()) { ServerUtility.copyFolder(path_src_child, path.join(path_dst, name_base)); } else { ServerUtility.copyFile(path_src_child, path_dst); } }); } }; /** * copy folder async * @param path_src source path string * @param path_dst destination path string * @param callback The funcion to call when we have finished to copy folder */ ServerUtility.copyFolderAsync = function (path_src, path_dst, callback) { var _this = this; var filenames; var loop = function () { var filename = filenames.shift(); if (!filename) { callback(); return; } var path_src_child = path.join(path_src, filename); fs.lstat(path_src_child, function (err, stat) { if (err) { callback(err); return; } if (stat.isDirectory()) { _this.copyFolderAsync(path_src_child, path.join(path_dst, filename), loop); } else { _this.copyFileAsync(path_src_child, path_dst, loop); } }); }; fs.stat(path_src, function (err, stat) { if (err) { callback(err); return; } fs.stat(path_dst, function (err, stat) { fs.mkdir(path_dst, function (err) { fs.lstat(path_src, function (err, stat) { if (err) { callback(err); return; } if (!stat.isDirectory()) { callback(new Error(path_src + " is not directory")); return; } fs.readdir(path_src, function (err, files) { if (err) { callback(err); return; } filenames = files; loop(); }); }); }); }); }); }; /** * unlink specified directory * @param path_dir unlink directory path */ ServerUtility.unlinkDirectory = function (path_dir) { if (!fs.existsSync(path_dir)) { return; } if (fs.lstatSync(path_dir).isDirectory()) { var name_bases = fs.readdirSync(path_dir); for (var i = 0; i < name_bases.length; i++) { var path_child = path.join(path_dir, name_bases[i]); if (fs.lstatSync(path_child).isDirectory()) { ServerUtility.unlinkDirectory(path_child); } else { fs.unlinkSync(path_child); } } fs.rmdirSync(path_dir); } }; /** * unlink specified directory async * @param path_dir unlink directory path * @param callback The funcion to call when we have finished to unlink directory */ ServerUtility.unlinkDirectoryAsync = function (path_dir, callback) { var _this = this; fs.lstat(path_dir, function (err, stat) { if (err) { callback(err); return; } if (stat.isDirectory()) { fs.readdir(path_dir, function (err, files) { if (err) { callback(err); return; } var loop = function () { var file = files.shift(); if (!file) { fs.rmdir(path_dir, function (err) { callback(err); }); return; } var path_child = path.join(path_dir, file); fs.lstat(path_child, function (err, stat) { if (err) { loop(); return; } if (stat.isDirectory()) { _this.unlinkDirectoryAsync(path_child, loop); } else { fs.unlink(path_child, function (err) { loop(); }); } }); }; loop(); }); } else { callback(); } }); }; /** * link directory * @param path_src source path string * @param path_dst destination path string */ ServerUtility.linkDirectory = function (path_src, path_dst) { if (!fs.existsSync(path_src)) { return; } if (!fs.existsSync(path_dst)) { fs.mkdirSync(path_dst); } //copy if (fs.lstatSync(path_src).isDirectory()) { var files = fs.readdirSync(path_src); files.forEach(function (name_base) { var path_src_child = path.join(path_src, name_base); if (fs.lstatSync(path_src_child).isDirectory()) { ServerUtility.copyFolder(path_src_child, path.join(path_dst, name_base)); } else { ServerUtility.copyFile(path_src_child, path_dst); } }); } }; /** * write file with replace keyword * @param src_path path of source file * @param dst_path path of destination file * @param values to replace set of key and value */ ServerUtility.writeFileKeywordReplaced = function (src_path, dst_path, values) { var data = fs.readFileSync(src_path); var text = String(data); for (var key in values) { text = text.replace("" + key, String(values[key])); } fs.writeFileSync(dst_path, text); }; /** * write file async with replace keyword * @param src_path path of source file * @param dst_path path of destination file * @param values to replace set of key and value * @param callback The function to call when we have finished to write file */ ServerUtility.writeFileKeywordReplacedAsync = function (src_path, dst_path, values, callback) { fs.readFile(src_path, function (err, data) { if (err) { logger.error(err); callback(err); return; } var text = data.toString(); Object.keys(values).forEach(function (key) { text = text.replace(key, String(values[key])); }); fs.writeFile(dst_path, text, function (err) { if (err) { callback(err); return; } callback(); }); }); }; /** * get all host infomation * @param callback The function to call when we have finished to get host information */ ServerUtility.getHostInfo = function (callback) { fs.readFile(ServerUtility.getHostListPath(), function (err, data) { if (err) { callback(err); return; } try { var hostListJson = JSON.parse(data.toString()); callback(undefined, hostListJson); } catch (err) { callback(err); } }); }; /** * delete host information * @param name delete host label name * @param callback The function to call when we have finished to delete host information */ ServerUtility.deleteHostInfo = function (name, callback) { this.getHostInfo(function (err, remoteHostList) { if (err) { callback(err); return; } if (!remoteHostList) { callback(new Error('host list does not exist')); return; } remoteHostList = remoteHostList.filter(function (host) { return host.name != name; }); fs.writeFile(ServerUtility.getHostListPath(), JSON.stringify(remoteHostList, null, '\t'), function (err) { if (err) { callback(err); } else { callback(); } }); }); }; /** * add host information * @param addHostInfo add host information * @param callback The function to call when we have finished to add host information */ ServerUtility.addHostInfo = function (addHostInfo, callback) { this.getHostInfo(function (err, remoteHostList) { if (err) { callback(err); return; } if (!remoteHostList) { callback(new Error('host list does not exist')); return; } remoteHostList = remoteHostList.filter(function (host) { return host.name !== addHostInfo.name; }); remoteHostList.push(addHostInfo); fs.writeFile(ServerUtility.getHostListPath(), JSON.stringify(remoteHostList, null, '\t'), function (err) { if (err) { callback(err); } else { callback(); } }); }); }; /** * get host list path * @return host list path */ ServerUtility.getHostListPath = function () { return path.join(__dirname, this.config.remotehost); }; /** * read template project json file * @return template project json data */ ServerUtility.readTemplateProjectJson = function () { var filepath = this.getTypeOfJson(SwfType.PROJECT).getTemplateFilePath(); return this.readProjectJson(filepath); }; /** * read template workflow json file * @return template workflow json data */ ServerUtility.readTemplateWorkflowJson = function () { var filepath = this.getTypeOfJson(SwfType.WORKFLOW).getTemplateFilePath(); return this.readJson(filepath); }; /** * read projct json * @param filepath project json file path * @return project json data */ ServerUtility.readProjectJson = function (filepath) { var regex = new RegExp("(?:" + this.config.extension.project.replace(/\./, '\.') + ")$"); if (!filepath.match(regex)) { logger.error("file extension is not " + this.config.extension.project); return null; } var data = fs.readFileSync(filepath); var projectJson = JSON.parse(data.toString()); return projectJson; }; /** * read json file * @param filepath json file path */ ServerUtility.readJson = function (filepath) { var data = fs.readFileSync(filepath); var json = JSON.parse(data.toString()); return json; }; /** * read .wf.json file tree * @param treeJsonFilepath task json file (.wf.json or .tsk.json file) * @return task json file */ ServerUtility.createTreeJson = function (treeJsonFilepath) { var _this = this; var parent = this.readJson(treeJsonFilepath); var parentDirname = path.dirname(treeJsonFilepath); parent.children = []; if (parent.children_file) { parent.children_file.forEach(function (child, index) { var childFilePath = path.resolve(parentDirname, child.path); if (path.dirname(childFilePath).length <= parentDirname.length) { logger.error("find circular reference. file=" + treeJsonFilepath); } else { var childJson = _this.createTreeJson(childFilePath); if (childJson != null) { parent.children.push(childJson); } } }); } return parent; }; /** * renumbering display order * @param treeJson tree json date */ ServerUtility.setDisplayOrder = function (treeJson) { var _this = this; var order = 0; treeJson.children.forEach(function (child, index) { var relations = treeJson.relations.filter(function (relation) { return relation.index_after_task === index; }); var fileRelations = treeJson.file_relations.filter(function (relation) { return relation.index_after_task === index; }); if (!relations[0] && !fileRelations[0]) { child.order = order; order += 100; } }); function setOrder(before) { treeJson.relations .filter(function (relation) { return relation.index_before_task === before; }) .forEach(function (relation) { return updateOrder(relation); }); treeJson.file_relations .filter(function (relation) { return relation.index_before_task === before; }) .forEach(function (relation) { return updateOrder(relation); }); } function updateOrder(relation) { var child = treeJson.children[relation.index_after_task]; var afterOrder = treeJson.children[relation.index_before_task].order + 1; if (child.order === undefined) { child.order = afterOrder; } else { child.order = Math.max(child.order, afterOrder); } setOrder(relation.index_after_task); } treeJson.children.forEach(function (child, index) { if (child.order !== undefined && child.order % 100 === 0) { setOrder(index); } _this.setDisplayOrder(child); }); }; /** * create log node json * @param path_taskFile path json file (.wf.json or .tsk.json file) * @return swf project json object */ ServerUtility.createLogJson = function (path_taskFile) { var tree = this.createTreeJson(path_taskFile); this.setDisplayOrder(tree); var planningState = SwfState.PLANNING; (function convertTreeToLog(treeJson, parentDir) { treeJson.path = path.join(parentDir, treeJson.path); var logJson = { name: treeJson.name, path: treeJson.path, description: treeJson.description, type: treeJson.type, state: planningState, execution_start_date: '', execution_end_date: '', children: [], order: treeJson.order, remote: treeJson.remote }; Object.keys(treeJson).forEach(function (key) { if (logJson[key] === undefined) { delete treeJson[key]; } }); Object.keys(logJson).forEach(function (key) { if (treeJson[key] === undefined) { treeJson[key] = logJson[key]; } }); treeJson.children.forEach(function (child) { return convertTreeToLog(child, logJson.path); }); })(tree, path.dirname(path.dirname(path_taskFile))); return tree; }; /** * create project json data * @param path_project project json file (.prj.json) * @return project json data */ ServerUtility.createProjectJson = function (path_project) { var projectJson = this.readProjectJson(path_project); var dir_project = path.dirname(path_project); var path_workflow = path.resolve(dir_project, projectJson.path_workflow); projectJson.log = this.createLogJson(path_workflow); return projectJson; }; /** * write json data * @param filepath write file path * @param json write json data * @param callback The function to call when we write json file */ ServerUtility.writeJson = function (filepath, json, callback) { fs.writeFile(filepath, JSON.stringify(json, null, '\t'), function (err) { if (err) { callback(err); return; } callback(); }); }; /** * whether specified hostname is localhost or not * @param hostname hostname * @return whether specified hostname is localhost or not */ ServerUtility.isLocalHost = function (hostname) { return (hostname === 'localhost') || (hostname === '127.0.0.1'); }; /** * whether platform is windows or not * @return whether platform is windows or not */ ServerUtility.isWindows = function () { return os.platform() === 'win32'; }; /** * whether platform is linux or not * @return whether platform is linux or not */ ServerUtility.isLinux = function () { return os.platform() === 'linux'; }; /** * whether platform is mac or not * @return whether platform is mac or not */ ServerUtility.isMac = function () { return os.platform() === 'darwin'; }; /** * whether platform is unix or not * @return whether platform is unix or not */ ServerUtility.isUnix = function () { return this.isLinux() || this.isMac(); }; /** * get instane by type * @param target filetype or tree json data * @return instance by type */ ServerUtility.getTypeOfJson = function (target) { var type; if (typeof target === 'string') { type = target; } else { type = target.type; } switch (type) { case SwfType.PROJECT: return new TypeProject(); case SwfType.WORKFLOW: return new TypeWorkflow(); case SwfType.TASK: return new TypeTask(); case SwfType.FOR: return new TypeFor(); case SwfType.IF: return new TypeIf(); case SwfType.ELSE: return new TypeElse(); case SwfType.BREAK: return new TypeBreak(); case SwfType.REMOTETASK: return new TypeRemoteTask(); case SwfType.JOB: return new TypeJob(); case SwfType.CONDITION: return new TypeCondition(); case SwfType.PSTUDY: return new TypePStudy(); default: throw new TypeError('file type is undefined'); } }; return ServerUtility; }()); /** * config parameter */ ServerUtility.config = ServerConfig.getConfig(); /** * type base */ var TypeBase = (function () { /** * create new instance * @param type SwfType */ function TypeBase(type) { /** * config date */ this.config = ServerConfig.getConfig(); this.type = type; } /** * get file extension name * @return file extension name */ TypeBase.prototype.getExtension = function () { return this.config.extension[this.type.toLocaleLowerCase()]; }; /** * get template file path * @return template file path */ TypeBase.prototype.getTemplateFilePath = function () { return path.normalize(__dirname + "/" + this.config.template[this.type.toLocaleLowerCase()]); }; /** * get default file name * @return default file name */ TypeBase.prototype.getDefaultName = function () { return "" + this.config.default_filename + this.getExtension(); }; /** * get file type * @return file type */ TypeBase.prototype.getType = function () { return this.type; }; /** * run task */ TypeBase.prototype.run = function () { throw new Error('function is not implemented'); }; return TypeBase; }()); /** * type project */ var TypeProject = (function (_super) { __extends(TypeProject, _super); /** * create new instance */ function TypeProject() { return _super.call(this, SwfType.PROJECT) || this; } return TypeProject; }(TypeBase)); /** * type task */ var TypeTask = (function (_super) { __extends(TypeTask, _super); /** * create new instance */ function TypeTask() { return _super.call(this, SwfType.TASK) || this; } return TypeTask; }(TypeBase)); /** * type workflow */ var TypeWorkflow = (function (_super) { __extends(TypeWorkflow, _super); /** * create new instance */ function TypeWorkflow() { return _super.call(this, SwfType.WORKFLOW) || this; } return TypeWorkflow; }(TypeBase)); var TypeFor = (function (_super) { __extends(TypeFor, _super); /** * create new instance */ function TypeFor() { return _super.call(this, SwfType.FOR) || this; } return TypeFor; }(TypeBase)); /** * type if */ var TypeIf = (function (_super) { __extends(TypeIf, _super); /** * create new instance */ function TypeIf() { return _super.call(this, SwfType.IF) || this; } return TypeIf; }(TypeBase)); /** * type else */ var TypeElse = (function (_super) { __extends(TypeElse, _super); /** * create new instance */ function TypeElse() { return _super.call(this, SwfType.ELSE) || this; } return TypeElse; }(TypeBase)); /** * type break */ var TypeBreak = (function (_super) { __extends(TypeBreak, _super); /** * create new instance */ function TypeBreak() { return _super.call(this, SwfType.BREAK) || this; } return TypeBreak; }(TypeBase)); /** * type remote task */ var TypeRemoteTask = (function (_super) { __extends(TypeRemoteTask, _super); /** * create new instance */ function TypeRemoteTask() { return _super.call(this, SwfType.REMOTETASK) || this; } return TypeRemoteTask; }(TypeBase)); /** * type job */ var TypeJob = (function (_super) { __extends(TypeJob, _super); /** * create new instance */ function TypeJob() { return _super.call(this, SwfType.JOB) || this; } return TypeJob; }(TypeBase)); /** * type condition */ var TypeCondition = (function (_super) { __extends(TypeCondition, _super); /** * create new instance */ function TypeCondition() { return _super.call(this, SwfType.CONDITION) || this; } return TypeCondition; }(TypeBase)); /** * type parameter study */ var TypePStudy = (function (_super) { __extends(TypePStudy, _super); /** * create new instance */ function TypePStudy() { return _super.call(this, SwfType.PSTUDY) || this; } return TypePStudy; }(TypeBase)); module.exports = ServerUtility; //# sourceMappingURL=serverUtility.js.map
RIIT-KyushuUniv/WHEEL
app/serverUtility.js
JavaScript
bsd-2-clause
27,569
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>mapfart.com &middot; Mapfart API</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="aaron, racicot, z-pulley, gis, spatial"> <meta name="author" content="Aaron Racicot"> <link href="/static/css/bootstrap.css" rel="stylesheet"> <link href="/static/css/bootstrap-responsive.css" rel="stylesheet"> <link href="/static/css/mapfart.css" rel="stylesheet"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link rel="shortcut icon" href="/static/favicon.png"> </head> <body onload="init()"> <div class="navbar-wrapper"> <div class="container"> <div class="navbar navbar-inverse"> <div class="navbar-inner"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/">mapfart.com</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="http://mapfart.com/recent">Recent Farts</a></li> </ul> </div><!--/.nav-collapse --> </div><!-- /.navbar-inner --> </div><!-- /.navbar --> </div> <!-- /.container --> </div><!-- /.navbar-wrapper --> <!-- MAIN CONTENT --> <div class="maincontent"> <div class="container"> <h2>What the hell is a <span class="muted">mapfart?</span></h2> <h3><i>A simple web service to take a geodata POST and <span class="muted">try</span> to make a map from it.</i></h3> <h2>What do I need to <span class="muted">install</span> to use it?</h2> <h3><i>Nothing... it just uses <span class="muted">Curl</span></i></h3> <h2>What the hell is <span class="muted">Curl?</span></h2> <h3><i>This service might not be for you...</i></h3> <h2>When might this be <span class="muted">useful?</span></h2> <h3><i>In a <span class="muted">headless situation</span> (i.e. on a remote server) where you want to <span class="muted">preview</span> the geodata... Then again... maybe it is totally useless...</i></h3> <h2>What do I <span class="muted">get?</span></h2> <h3><i>Nothing... you POST. All kidding aside, you get a PNG image back.</i></h3> <h2>What <span class="muted">formats</span> are supported?</h2> <h3><i>Well, we dont actually "support" anything... this is a toy. If you want to try it out, send over GeoJSON, WKT, or WKB and cross your fingers.</i></h3> <h2>What <span class="muted">tools</span> are being used?</h2> <h3><i>GeoJSON is rendered using Mapserver, WTK and WKB are rendered via Geometry Tools (just for fun)</i></h3> <h2>What was the <span class="muted">inspiration?</span></h2> <h3><i>Well, <a href="http://datafart.com">datafart.com</a> of course.</i></h3> <br> <h2><span class="muted">Set it up</span> please:</h2> <h3>Simple (default)</h3> <pre> alias mapfart='curl -H "Content-Type: application/octet-stream" --data-binary @- mapfart.com/api/fart' </pre> <h3>Crunchy (change output projection) (example EPSG:3857)</h3> <pre> alias mapfart='curl -H "Content-Type: application/octet-stream" --data-binary @- mapfart.com/api/3857/fart' </pre> <h3>Hipster (change output projection AND mapsize) (example EPSG:3857, 2000x2000px)</h3> <pre> alias mapfart='curl -H "Content-Type: application/octet-stream" --data-binary @- mapfart.com/api/3857/2000/2000/fart' </pre> <br> <br> <h2><span class="muted">Examples</span> please:</h2> <h3>Simple GeoJSON file</h3> <script src="https://gist.github.com/aaronr/5199177.js"></script> <pre> z-air:~ aaronr$ cat geojson.json | mapfart </pre> <hr class="featurette-divider"> <h3>Local Shapefile via ogr2ogr</h3> <pre> z-air:~ aaronr$ ogr2ogr -f GeoJSON /vsistdout/ ne_110m_admin_0_countries.shp -sql "select * from ne_110m_admin_0_countries where name='United States'" | mapfart </pre> <hr class="featurette-divider"> <h3>Remote Shapefile via ogr2ogr</h3> <pre> z-air:~ aaronr$ ogr2ogr -f GeoJSON /vsistdout/ /vsizip/vsicurl/http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip/ne_110m_admin_0_countries.shp -sql "select * from ne_110m_admin_0_countries where name='United States' or name='Germany'" | mapfart </pre> <hr class="featurette-divider"> <h3>Postgis via ogr2ogr</h3> <pre> z-air:~ aaronr$ ogr2ogr -f "GeoJSON" /vsistdout/ PG:dbname=test ne_admin_bounds -where "name = 'United States'" | mapfart </pre> <hr class="featurette-divider"> <h3>WKT as text</h3> <pre> z-air:~ aaronr$ echo 'LINESTRING(3 4,10 50,20 25)' | mapfart </pre> <hr class="featurette-divider"> <h3>WKB as text (bbox of United States)</h3> <pre> z-air:~ aaronr$ echo '0103000020E61000000100000005000000F8DD2EC7507965C020EC866D8BEA3240F8DD2EC7507965C08CAA3399E5D651409AF04BFDBCBD50C08CAA3399E5D651409AF04BFDBCBD50C020EC866D8BEA3240F8DD2EC7507965C020EC866D8BEA3240' | mapfart </pre> <hr class="featurette-divider"> <h3>WKB (single shape) via psql</h3> <pre> z-air:~ aaronr$ psql -A -t -c "select geom from ne_admin_bounds where name = 'United States'" testdb | mapfart </pre> <hr class="featurette-divider"> <h3>WKT using <a href="http://jericks.github.com/geometrycommands/index.html">Geometry Commands</a></h3> <pre> z-air:~ aaronr$ geom buffer -g 'LINESTRING(3 4,10 50,20 25)' -d 2 | mapfart </pre> </div> </div> <!-- FOOTER --> <footer> <p class="pull-right"><a href="#">Back to top</a></p> <p>&copy; 2013 Aaron Racicot &middot;</p> </footer> <!-- Javascript ====================================== --> <script src="/static/js/jquery.js"></script> <script src="/static/js/bootstrap-transition.js"></script> <script src="/static/js/bootstrap-alert.js"></script> <script src="/static/js/bootstrap-modal.js"></script> <script src="/static/js/bootstrap-dropdown.js"></script> <script src="/static/js/bootstrap-scrollspy.js"></script> <script src="/static/js/bootstrap-tab.js"></script> <script src="/static/js/bootstrap-tooltip.js"></script> <script src="/static/js/bootstrap-popover.js"></script> <script src="/static/js/bootstrap-button.js"></script> <script src="/static/js/bootstrap-collapse.js"></script> <script src="/static/js/bootstrap-carousel.js"></script> <script src="/static/js/bootstrap-typeahead.js"></script> <!--script src="http://code.onion.com/fartscroll.js"></script--> <!--script src="/static/js/fart.js"></script--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1253169-9']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
aaronr/mapfart
templates/index.html
HTML
bsd-2-clause
7,403
/* * Copywrite 2014-2015 Krzysztof Stasik. All rights reserved. */ #pragma once #include "base/core/types.h" #include "rush/punch/server.h" #include "../common/punch_message.h" #include "base/network/url.h" #include "base/network/socket.h" #include <vector> namespace Rush { namespace Punch { static const s32 kPunchCommandTimeoutMs = 10 * 1000; static const s32 kPunchCommandRetryMs = 1000; struct PunchOperation { // kRequest means a_url is the originator. enum Type { kRequest, kExternal } type; Base::Socket::Address a_public; Base::Socket::Address a_private; Base::Socket::Address b_public; Base::Socket::Address b_private; s32 punch_resend; s32 timeout; Rush::Punch::RequestId request_id; Rush::Punch::RequestId connect_id; }; class PunchServer { public: PunchServer(); ~PunchServer(); bool Open(const Base::Url &url, u16 *port); void Update(u32 dt); private: void UpdatePunchOperations(u32 dt); private: Base::Socket::Handle m_socket; Base::Url m_url; std::vector<PunchOperation> m_punch_ops; Rush::Punch::RequestId m_generator; }; } // namespace Punch } // namespace Rush
pretty-wise/rush
transport/src/punch/server/punch_server.h
C
bsd-2-clause
1,129
/* */ /* | PC-LISP (C) 1984-1990 Peter J.Ashwood-Smith */ #include <stdio.h> #include "lisp.h" /* | Emit characters to '*buff' from '*s' as long as we do not meet a spec '%' or | the \0. If we meet a % that is not followed by a % then stop otherwise emit | a single % and keep going. When done '*s' points to the first char in the | spec to be processed (done by next routine) or '\0' and *buff points to the | end of the buffer written (ie it has been advanced and null terminated). */ static int emit_to_spec(left, buff, s) int *left; /* bytes left in buffer for our use */ char **buff; /* pointer to buffer pointer */ char **s; /* pointer to spec pointer */ { register char *t; register char *x = *buff; for(t = *s; *t != '\0'; t++) { /* for each char in spec */ if ((*left)-- <= 0) goto er; /* if no more room in buffer then get out */ if (*t != '%') /* if not %d %x ... */ *x++ = *t; /* char is just emitted to buff */ else { /* else it is a %d...*/ t += 1; /* skip % to look ahead by one */ if (*t == '\0') goto er; /* %\0 is an error in spec */ if (*t == '%') /* but make sure not %% */ *x++ = '%'; /* because that's just a single % */ else { /* if not %% then is real spec so */ t -= 1; /* back up to % and then */ break; /* stop so next routine can handle */ } } } *s = t; /* advance pointer for next routine */ *x = '\0'; /* null terminate buffer */ *buff = x; /* advance buffer pointer */ return(1); /* return success */ er: return(0); } /* | Emit the next arg in the arg list '*form' according to the spec '*s' and | advance *s to the end of the spec when done. Basically we loop through every | character up to the end of a spec string. long parameters in form have specs | like %<stuff>{d|x|o|u}. Double parameters in form have specs similar to the | long but terminated with {f|e|g}, string are terminated with {s} and characters | with {c}. The <stuff> may consist of {#,-,+, ,0-9,.,l} and nothing else. Note | that '*' is deliberately not supported! Once we have extracted the full spec | and made sure it is reasonably valid and extracted the corresponding parameter | for it from 'form' we simply call fprintf with the spec and argument. */ static int emit_next_spec(left, buff, s, form) int *left; /* room left in buffer in bytes */ char **buff; /* pointer to buffer sweep pointer */ char **s; /* pointer to spec sweep pointer */ struct conscell **form; /* argument list */ { register char *t; /* 't' is what we sweep through spec */ long ival; /* long value if %d ... */ double fval; /* double value if %f ... */ char *sval; /* string value if %s ... */ int c; /* temporary char for char swap */ int len; /* length of addition to buffer */ /* | We are about to process a spec %... something so there must be at least one | argument available. */ if (*form == NULL) goto er; /* | Loop through all chars in the spec string from one after the % until we get one of | the spec terminating characters which we then process and then drop out through the | ok label. */ for(t = (*s) + 1 ; ; t++) { switch(*t) { /* | We have something of the form %<stuff>{d|x|o|u} so the corresponding argument which | should be a fixnum so get one and call the fprintf routine using the exact spec | passed and the long as an argument. We must null terminate the spec so we get the | next char first so that we can put the char back after the call to fprintf when | we are done. */ case 'd' : case 'x' : case 'o' : case 'u' : case 'X' : if (!GetFix((*form)->carp, &ival)) goto er; t += 1; c = *t; *t = '\0'; sprintf(*buff, *s, ival); *t = c; goto ok; /* | We have something of the form %<stuff>{f|e|g} so the corresponding argument which | should be a flonum so get one and call the fprintf routine using the exact spec | passed and the double as an argument. We must null terminate the spec so we get the | next char first so that we can put the char back after the call to fprintf when | we are done. */ case 'f' : case 'e' : case 'g' : case 'E' : case 'G' : if (!GetFloat((*form)->carp, &fval)) goto er; t += 1; c = *t; *t = '\0'; sprintf(*buff, *s, fval); *t = c; goto ok; /* | We have something of the form %<stuff>{s} so the corresponding argument which | should be a string so get one and call the fprintf routine using the exact spec | passed and the string as an argument. We must null terminate the spec so we get the | next char first so that we can put the char back after the call to fprintf when | we are done. */ case 's' : if (!GetString((*form)->carp, &sval)) goto er; t += 1; c = *t; *t = '\0'; sprintf(*buff, *s, sval); *t = c; goto ok; /* | We have something of the form %<stuff>{c} so the corresponding argument which | should be a string so get one and call the fprintf routine using the exact spec | passed and the first char as an argument. We must null terminate the spec so we get the | next char first so that we can put the char back after the call to fprintf when | we are done. */ case 'c' : if (!GetString((*form)->carp, &sval)) goto er; t += 1; c = *t; *t = '\0'; sprintf(*buff, *s, sval[0]); *t = c; goto ok; /* | We have a <stuff> character so just skipt it. We do not check syntax beyond the | fact that only chars in this set may be in the <stuff>. Note deliberate abscence | of '*'! */ case '#' : case '-' : case '+' : case ' ' : case '.' : case 'l' : case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : break; /* | Any other character in <stuff> is not allowed by printf so flag it now. */ default : goto er; } } er: return(0); ok: *s = t; /* advance to end of % spec */ *form = (*form)->cdrp; /* advance to next argument */ len = strlen(*buff); /* need length of expanded spec */ *buff += len; /* advance to next slot in buffer */ if ((*left)-- <= 0) goto er; /* if this overflowed the buffer throw error */ return(1); } /* | do_fprintf(buff, form) - will do a formatted sprintf of the arguments to the | given buffer. The first thing in the form is the format specifier as per normal | printf standards, the rest are the arguments to be formatted. */ static int do_sprintf(left, buff, form) int *left; char *buff; struct conscell *form; { char *s; char *b; if (form == NULL) goto er; if ((form->celltype != CONSCELL)||(!GetString(form->carp,&s))) goto er; form = form->cdrp; for(b = buff ; ; ) { if (!emit_to_spec(left, &b, &s)) goto er; if (*s == '\0') break; if (!emit_next_spec(left, &b, &s, &form)) goto er; if (*s == '\0') break; } if (form != NULL) goto er; /* all args must have been used! */ return(1); er: return(0); } /* | t <- (printf spec [arg] [arg] ....) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ struct conscell *buprintf(form) struct conscell *form; { char buff[MAXATOMSIZE]; int left = sizeof(buff) - 1; if (do_sprintf(&left, buff, form)) { printf("%s", buff); return(LIST(thold)); } ierror("printf"); /* doesn't return */ return NULL; /* keep compiler happy */ } /* | t <- (fprintf port spec [arg] [arg] ....) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | If writing to a socket that we were previously reading from must rewind the | socket and reset the isread so that we know we are now writing to it. */ struct conscell *bufprintf(form) struct conscell *form; { char buff[MAXATOMSIZE]; struct filecell *f; int left = sizeof(buff) - 1; if ((form == NULL)||(form->carp == NULL)) goto er; f = PORT(form->carp); if ((f->celltype != FILECELL) || (f->atom == NULL)) goto er; if (do_sprintf(&left, buff, form->cdrp)) { if (f->issocket && f->state == 1) rewind(f->atom); /* if was reading socket rewind before writing */ f->state = 2; /* set new state to writing */ fprintf(f->atom, "%s", buff); return(LIST(thold)); } er: ierror("fprintf"); /* doesn't return */ return NULL; /* keep compiler happy */ } /* | str <- (sprintf spec [arg] [arg] ....) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ struct conscell *busprintf(form) struct conscell *form; { char buff[MAXATOMSIZE]; int left = sizeof(buff) - 1; if (form == NULL) goto er; if (do_sprintf(&left, buff, form)) { if (strlen(buff) >= MAXATOMSIZE) goto er; /* too big for a string */ return(LIST(insertstring(buff))); } er: ierror("sprintf"); /* doesn't return */ return NULL; /* keep compiler happy */ }
blakemcbride/PC-LISP
src/buprintf.c
C
bsd-2-clause
10,526
'use strict'; var react = require('react') , document = require('./components/document'); module.exports.renderView = function renderView(req, res, props) { var html = react.renderComponentToString(document(props)); res.end(html); }
accosine/spandex
lib/views.js
JavaScript
bsd-2-clause
241
// This file was procedurally generated from the following sources: // - src/annex-b-fns/global-existing-global-init.case // - src/annex-b-fns/global/block.template /*--- description: Variable binding is left in place by legacy function hoisting. CreateGlobalVariableBinding leaves the binding as non-enumerable even if it has the chance to change it to be enumerable. (Block statement in the global scope containing a function declaration) esid: sec-web-compat-globaldeclarationinstantiation es6id: B.3.3.2 flags: [generated, noStrict] includes: [fnGlobalObject.js, propertyHelper.js] info: | B.3.3.3 Changes to GlobalDeclarationInstantiation [...] Perform ? varEnvRec.CreateGlobalVarBinding(F, true). [...] ---*/ var global = fnGlobalObject(); Object.defineProperty(global, 'f', { value: 'x', enumerable: true, writable: true, configurable: false }); $262.evalScript(` assert.sameValue(f, 'x'); verifyProperty(global, 'f', { enumerable: true, writable: true, configurable: false }, { restore: true }); `); $262.evalScript(` { function f() { return 'inner declaration'; } } `); $262.evalScript(` verifyProperty(global, 'f', { enumerable: true, writable: true, configurable: false }); `);
sebastienros/jint
Jint.Tests.Test262/test/annexB/language/global-code/block-decl-global-existing-global-init.js
JavaScript
bsd-2-clause
1,234
#!/bin/sh # Surya Saha # BTI/PPath@Cornell # Purpose: Make dot plots for full chr length alignment with all and 1-1 mapping between ref and query # Use with v4 mummer https://github.com/mummer4/mummer/releases # All matches are 100% identical and only ATGC regions are reported usage(){ echo "usage: $0 <ref.fa> <query.fa> <prefix for outfiles> <min tile length>" exit 1 } if [ "$#" -ne 4 ] then usage fi printf "Ref file: %s \n" "$1" printf "Query file: %s \n" "$2" printf "Prefix: %s \n" "$3" printf "Min tile length : %d \n" "$4" # unique matches mummer -mum -l "$4" -b -c -n -qthreads 6 "$1" "$2" > "$3".mummer.uniq.both.out mummerplot --png --prefix "$3".uniq --title "$3".uniq "$3".mummer.uniq.both.out # all matches mummer -maxmatch -l "$4" -b -c -n -threads 6 -qthreads 6 "$1" "$2" > "$3".mummer.all.both.out mummerplot --png --prefix "$3".all --title "$3".all "$3".mummer.all.both.out #cleanup /bin/rm -f "${3}".uniq.rplot /bin/rm -f "${3}".uniq.gp /bin/rm -f "${3}".uniq.fplot /bin/rm -f "${3}".all.rplot /bin/rm -f "${3}".all.gp /bin/rm -f "${3}".all.fplot
suryasaha/Utils
makeChrDotplotsMummer.sh
Shell
bsd-2-clause
1,081
db.addUser('admin','admin');
EqualExperts/Tayra
distribution-template/demo/createAdmin.js
JavaScript
bsd-2-clause
29
class Llnode < Formula desc "LLDB plugin for live/post-mortem debugging of node.js apps" homepage "https://github.com/nodejs/llnode" url "https://github.com/nodejs/llnode/archive/v1.6.2.tar.gz" sha256 "d5e979812f7e4ec62b451beb30770dcb8c7f7184fe8816fc6a13ba2b35c1b919" bottle do cellar :any sha256 "cb965fb47971316eb8928157eefd03c9bcdb13387fa9984291e3dd36809845c6" => :high_sierra sha256 "cba54eddd2cbc47a628a1163f5d02bea21bd7759e95f7c3c905142d4a8fb757a" => :sierra sha256 "83c34005044ba77217d0c9415268a9fa72392213191fe474d8cca0b8f68957a8" => :el_capitan end depends_on :macos => :yosemite depends_on :python => :build resource "gyp" do url "https://chromium.googlesource.com/external/gyp.git", :revision => "324dd166b7c0b39d513026fa52d6280ac6d56770" end resource "lldb" do if DevelopmentTools.clang_build_version >= 802 # lldb 390 url "https://github.com/llvm-mirror/lldb.git", :revision => "d556e60f02a7404b291d07cac2f27512c73bc743" elsif DevelopmentTools.clang_build_version >= 800 # lldb 360.1 url "https://github.com/llvm-mirror/lldb.git", :revision => "839b868e2993dcffc7fea898a1167f1cec097a82" else # It claims it to be lldb 350.0 for Xcode 7.3, but in fact it is based # of 34. # Xcode < 7.3 uses 340.4, so I assume we should be safe to go with this. url "http://llvm.org/svn/llvm-project/lldb/tags/RELEASE_34/final/", :using => :svn end end def install (buildpath/"lldb").install resource("lldb") (buildpath/"tools/gyp").install resource("gyp") system "./gyp_llnode" system "make", "-C", "out/" prefix.install "out/Release/llnode.dylib" end def caveats; <<~EOS `brew install llnode` does not link the plugin to LLDB PlugIns dir. To load this plugin in LLDB, one will need to either * Type `plugin load #{opt_prefix}/llnode.dylib` on each run of lldb * Install plugin into PlugIns dir manually: mkdir -p ~/Library/Application\\ Support/LLDB/PlugIns ln -sf #{opt_prefix}/llnode.dylib \\ ~/Library/Application\\ Support/LLDB/PlugIns/ EOS end test do lldb_out = pipe_output "lldb", <<~EOS plugin load #{opt_prefix}/llnode.dylib help v8 quit EOS assert_match "v8 bt", lldb_out end end
robohack/homebrew-core
Formula/llnode.rb
Ruby
bsd-2-clause
2,355
# confstore Configuration Storage System
walkb4urun/confstore
README.md
Markdown
bsd-2-clause
41
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SharpNetwork.Core; using SharpNetwork.SimpleWebSocket; namespace ChatServer { public partial class ChatServerForm : Form { Server m_ChatServer = new Server(); public ChatServerForm() { InitializeComponent(); } public void LogMsg(string msg) { BeginInvoke((Action)(() => { if (mmChat.Lines.Length > 1024) { List<string> finalLines = mmChat.Lines.ToList(); finalLines.RemoveRange(0, 512); mmChat.Lines = finalLines.ToArray(); } mmChat.AppendText("[" + DateTime.Now.ToString("HH:mm:ss") + "] " + msg + "\n"); mmChat.SelectionStart = mmChat.Text.Length; mmChat.ScrollToCaret(); })); } public void ProcessMsg(string msg) { var parts = msg.Split('|'); var act = parts[0]; var user = parts[1]; var chat = parts.Length >= 3 ? parts[2] : ""; if (act == "JOIN") LogMsg(user + " has joined chatroom"); else if (act == "LEAVE") LogMsg(user + " has left chatroom"); else if (act == "CHAT") LogMsg(user + ": " + chat); WebMessage webmsg = new WebMessage(msg); webmsg.MaskFlag = (byte)1; m_ChatServer.Broadcast(webmsg); } private void ChatServerForm_Load(object sender, EventArgs e) { m_ChatServer.SetIoFilter(new MessageCodec(1024 * 1024 * 2)); // set max buffer size to 2m ... m_ChatServer.SetIoHandler(new ServerNetworkEventHandler(this)); //m_ChatServer.SetCert(new X509Certificate2(certFilepath, certKey)); m_ChatServer.Start(9090); LogMsg("Server is listening on 9090..."); } private void ChatServerForm_FormClosing(object sender, FormClosingEventArgs e) { m_ChatServer.Stop(); } } public class ServerNetworkEventHandler : NetworkEventHandler { ChatServerForm m_MainForm = null; public ServerNetworkEventHandler(ChatServerForm mainForm) : base() { IsOrderlyProcess = true; m_MainForm = mainForm; } public override void OnConnect(Session session) { base.OnConnect(session); } public override void OnHandshake(Session session) { base.OnHandshake(session); m_MainForm.LogMsg("new client connected"); } public override void OnDisconnect(Session session) { base.OnDisconnect(session); m_MainForm.LogMsg("a client disconnected"); } public override void OnError(Session session, int errortype, Exception error) { base.OnError(session, errortype, error); m_MainForm.LogMsg("socket error: " + error.Message); } protected override void ProcessMessage(SessionContext ctx) { Session session = ctx.Session; WebMessage msg = (WebMessage)ctx.Data; m_MainForm.ProcessMsg(msg.MessageContent); } } }
joelam789/sharp-network
example/ChatServer/ChatServerForm.cs
C#
bsd-2-clause
3,460
#Execute ################################################################################################# # Uninstall a program silently # # This script checks the registry for software to remove matching the search string # it can remove both msi packages and run WinPE uninstallers. # This uninstaller will automatically determine whether to run the uninstall.exe for the # program to remove, or if it should remove the program with msiexec. # A list of all installed programs can be created using the query-InstalledSoftware-search.ps1 # script. Make sure that the searches you pass to this script are unique enough to only remove # what you want to remove. ################################################################################################# $SoftToRemove = Read-Host "Software to Remove" ## Script function for removing software $script = 'function uninstall ($SoftToRemove = $null){ if ($SoftToRemove -ne $null){ $uninstall32 = Get-ChildItem "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { Get-ItemProperty $_.PSPath } | ? { $_ -match $SoftToRemove } | select UninstallString, DisplayName $uninstall64 = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { Get-ItemProperty $_.PSPath } | ? { $_ -match $SoftToRemove } | select UninstallString, DisplayName $uninstall32c = @() $uninstall64c = @() $uninstall32 | ForEach-Object { if ( $_.UninstallString ){ $uninstall32c += $_.UninstallString } } $uninstall64 | ForEach-Object { if ( $_.UninstallString ){ $uninstall64c += $_.UninstallString } } function thisUninstall ($uninstArr) { $uninstArr | foreach { $thisUninstall = $_ -Replace "msiexec.exe","" -replace "/I", "" -replace "/X", "" $thisUninstall = $thisUninstall.Trim() if ($thisUninstall -match ".exe"){ Start-Process $thisUninstall -arg "/S" -Wait } else { Start-Process "msiexec.exe" -arg "/X `"$thisUninstall`" /qn /norestart" -Wait } } } thisUninstall $uninstall32c thisUninstall $uninstall64c } } uninstall ' + $SoftToRemove $uninstallBlock = [ScriptBlock]::Create($script) Write-Host "Uninstalling $SoftToRemove.." -ForegroundColor Yellow Invoke-Command -ScriptBlock $uninstallBlock Pause
Layer8Err/PowerShell_fmwrk
Local/UninstallSoftware.ps1
PowerShell
bsd-2-clause
2,580
<?php interface InterfaceWithStaticMethod { public static function staticMethod(); }
TheTypoMaster/SPHERE-Framework
Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/0.3.9/vendor/phpunit/phpunit-mock-objects/tests/_fixture/InterfaceWithStaticMethod.php
PHP
bsd-2-clause
91
import io import sys import mock import argparse from monolith.compat import unittest from monolith.cli.base import arg from monolith.cli.base import ExecutionManager from monolith.cli.base import SimpleExecutionManager from monolith.cli.base import BaseCommand from monolith.cli.base import CommandError from monolith.cli.base import LabelCommand from monolith.cli.base import SingleLabelCommand from monolith.cli.base import Parser from monolith.cli.exceptions import AlreadyRegistered from io import StringIO class DummyCommand(BaseCommand): pass class AnotherDummyCommand(BaseCommand): pass class TestExecutionManager(unittest.TestCase): def assertRegistryClassesEqual(self, actual, expected): self.assertEqual(list(sorted(actual)), list(sorted(expected))) for key in actual: self.assertEqual(actual[key].__class__, expected[key], "Command class don't match for %r (it's %r but " "expected %r)" % (key, actual[key].__class__, expected[key])) def setUp(self): self.manager = ExecutionManager(['foobar'], stderr=StringIO()) def test_init_prog_name(self): self.assertEqual(self.manager.prog_name, 'foobar') def test_init_stderr(self): manager = ExecutionManager() self.assertEqual(manager.stderr, sys.stderr) def test_default_argv(self): with mock.patch.object(sys, 'argv', ['vcs', 'foo', 'bar']): manager = ExecutionManager() self.assertEqual(manager.argv, ['foo', 'bar']) def test_get_usage(self): self.manager.usage = 'foobar baz' self.assertEqual(self.manager.get_usage(), 'foobar baz') def test_get_parser(self): self.manager.usage = 'foo bar' parser = self.manager.get_parser() self.assertIsInstance(parser, argparse.ArgumentParser) self.assertEqual(parser.prog, 'foobar') # argv[0] self.assertEqual(parser.usage, 'foo bar') self.assertEqual(parser.stream, self.manager.stderr) def test_get_parser_calls_setup_parser(self): class DummyCommand(BaseCommand): pass self.manager.register('foo', DummyCommand) with mock.patch.object(DummyCommand, 'setup_parser') as setup_parser: self.manager.get_parser() self.assertTrue(setup_parser.called) def test_register(self): Command = type('Command', (BaseCommand,), {}) self.manager.register('foo', Command) self.assertRegistryClassesEqual(self.manager.registry, {'foo': Command}) command = self.manager.registry['foo'] self.assertEqual(command.manager, self.manager) def test_register_raise_if_command_with_same_name_registered(self): Command = type('Command', (BaseCommand,), {}) self.manager.register('foobar', Command) with self.assertRaises(AlreadyRegistered): self.manager.register('foobar', Command) def test_register_respects_force_argument(self): Command1 = type('Command', (BaseCommand,), {}) Command2 = type('Command', (BaseCommand,), {}) self.manager.register('foobar', Command1) self.manager.register('foobar', Command2, force=True) self.assertRegistryClassesEqual(self.manager.registry, { 'foobar': Command2}) def test_get_commands(self): FooCommand = type('FooCommand', (BaseCommand,), {}) BarCommand = type('BarCommand', (BaseCommand,), {}) self.manager.register('foo', FooCommand) self.manager.register('bar', BarCommand) self.assertEqual(list(self.manager.get_commands().keys()), ['bar', 'foo']) self.assertRegistryClassesEqual(self.manager.get_commands(), { 'foo': FooCommand, 'bar': BarCommand, }) def test_get_commands_to_register(self): FooCommand = type('FooCommand', (BaseCommand,), {}) BarCommand = type('BarCommand', (BaseCommand,), {}) class Manager(ExecutionManager): def get_commands_to_register(self): return { 'foo': FooCommand, 'bar': BarCommand, } manager = Manager(['foobar']) self.assertRegistryClassesEqual(manager.registry, { 'foo': FooCommand, 'bar': BarCommand, }) def test_call_command(self): class Command(BaseCommand): name = 'init' handle = mock.Mock() self.manager.register('init', Command) self.manager.call_command('init') self.assertTrue(Command.handle.called) def test_called_command_has_prog_name_properly_set(self): prog_names = [] class Command(BaseCommand): name = 'init' def handle(self, namespace): prog_names.append(self.prog_name) self.manager.register('init', Command) self.manager.call_command('init') self.assertEqual(prog_names, ['foobar']) def test_call_command_with_args(self): class Command(BaseCommand): args = [ arg('-f', '--force', action='store_true', default=False), ] name = 'add' handle = mock.Mock() self.manager.register('add', Command) self.manager.call_command('add', '-f') self.assertTrue(Command.handle.called) namespace = Command.handle.call_args[0][0] self.assertTrue(namespace.force) @mock.patch('monolith.cli.base.sys.stderr') def test_call_command_fails(self, stderr): class Command(BaseCommand): args = [ arg('-f', '--force', action='store_true', default=False), ] name = 'add' def handle(self, namespace): raise CommandError('foo bar baz', 92) self.manager.register('add', Command) with self.assertRaises(SystemExit): self.manager.call_command('add', '-f') stderr.write.assert_called_once_with('ERROR: foo bar baz\n') def test_execute_calls_handle_command(self): class Command(BaseCommand): args = [ arg('-f', '--force', action='store_true', default=False), ] name = 'add' handle = mock.Mock() self.manager.register('add', Command) with mock.patch.object(sys, 'argv', ['prog', 'add', '-f']): self.manager.execute() namespace = Command.handle.call_args[0][0] Command.handle.assert_called_once_with(namespace) class TestSimpleExecutionManager(unittest.TestCase): def test_get_commands_to_register(self): # importing dummy commands to local namespace so they have full class # paths properly set from monolith.tests.test_cli import DummyCommand from monolith.tests.test_cli import AnotherDummyCommand manager = SimpleExecutionManager('git', { 'push': DummyCommand, 'pull': 'monolith.tests.test_cli.AnotherDummyCommand', }) self.assertDictEqual(manager.get_commands_to_register(), { 'push': DummyCommand, 'pull': AnotherDummyCommand, }) class TestBaseCommand(unittest.TestCase): def test_get_args(self): Command = type('Command', (BaseCommand,), {'args': ['foo', 'bar']}) command = Command() self.assertEqual(command.get_args(), ['foo', 'bar']) def test_handle_raises_error(self): with self.assertRaises(NotImplementedError): BaseCommand().handle(argparse.Namespace()) def test_post_register_hooks(self): Command = type('Command', (BaseCommand,), {'args': ['foo', 'bar']}) class Command(BaseCommand): def post_register(self, manager): manager.completion = True manager = ExecutionManager() self.assertFalse(manager.completion) manager.register('completion', Command) self.assertTrue(manager.completion) class TestLabelCommand(unittest.TestCase): def test_handle_raise_if_handle_label_not_implemented(self): command = LabelCommand() with self.assertRaises(NotImplementedError): command.handle(argparse.Namespace(labels=['foo'])) def test_handle_calls_handle_label(self): namespace = argparse.Namespace(labels=['foo', 'bar']) command = LabelCommand() command.handle_label = mock.Mock() command.handle(namespace) self.assertEqual(command.handle_label.call_args_list, [ arg('foo', namespace), arg('bar', namespace), ]) def test_labels_required_true(self): Command = type('Command', (LabelCommand,), {'labels_required': True}) command = Command() self.assertEqual(command.get_args()[0].kwargs.get('nargs'), '+') def test_labels_required_false(self): Command = type('Command', (LabelCommand,), {'labels_required': False}) command = Command() self.assertEqual(command.get_args()[0].kwargs.get('nargs'), '*') def test_handle_no_labels_called_if_no_labels_given(self): Command = type('Command', (LabelCommand,), {'labels_required': False}) command = Command() command.handle_no_labels = mock.Mock() namespace = argparse.Namespace(labels=[]) command.handle(namespace) command.handle_no_labels.assert_called_once_with(namespace) class TestSingleLabelCommand(unittest.TestCase): def test_get_label_arg(self): Command = type('Command', (SingleLabelCommand,), {}) label_arg = Command().get_label_arg() self.assertEqual(label_arg, arg('label', default=Command.label_default_value, nargs='?')) def test_get_args(self): Command = type('Command', (SingleLabelCommand,), {}) command = Command() self.assertEqual(command.get_args(), [command.get_label_arg()]) def test_handle_raise_if_handle_label_not_implemented(self): command = SingleLabelCommand() with self.assertRaises(NotImplementedError): command.handle(argparse.Namespace(label='foo')) def test_handle_calls_handle_label(self): namespace = argparse.Namespace(label='foobar') command = SingleLabelCommand() command.handle_label = mock.Mock() command.handle(namespace) self.assertEqual(command.handle_label.call_args_list, [ arg('foobar', namespace), ]) class TestArg(unittest.TestCase): def test_args(self): self.assertEqual(arg(1, 2, 'foo', bar='baz').args, (1, 2, 'foo')) def test_kargs(self): self.assertEqual(arg(1, 2, 'foo', bar='baz').kwargs, {'bar': 'baz'}) class TestParser(unittest.TestCase): def setUp(self): self.stream = io.StringIO() self.parser = Parser(stream=self.stream) def test_print_message_default_file(self): self.parser._print_message('foobar') self.assertEqual(self.stream.getvalue(), 'foobar')
lukaszb/monolith
monolith/tests/test_cli.py
Python
bsd-2-clause
11,047
/** * Copyright 2013 - Eric Bidelman * * 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. * @fileoverview * A polyfill implementation of the HTML5 Filesystem API which sits on top of * IndexedDB as storage layer. Files and folders are stored as FileEntry and * FolderEntry objects in a single object store. IDBKeyRanges are used to query * into a folder. A single object store is sufficient because we can utilize the * properties of ASCII. Namely, ASCII / is followed by ASCII 0. Thus, * "/one/two/" comes before "/one/two/ANYTHING" comes before "/one/two/0". * * @author Eric Bidelman (ebidel@gmail.com) * @version: 0.0.5 */ 'use strict'; (function(exports) { // Bomb out if the Filesystem API is available natively. if (exports.requestFileSystem || exports.webkitRequestFileSystem) { return; } // Bomb out if no indexedDB available var indexedDB = exports.indexedDB || exports.mozIndexedDB || exports.msIndexedDB; if (!indexedDB) { return; } // Check to see if IndexedDB support blobs var support = new function() { var dbName = "blob-support"; indexedDB.deleteDatabase(dbName).onsuccess = function() { var request = indexedDB.open(dbName, 1.0); request.onerror = function() { support.blob = false; }; request.onsuccess = function() { var db = request.result; try { var blob = new Blob(["test"], {type: "text/plain"}); var transaction = db.transaction("store", "readwrite"); transaction.objectStore("store").put(blob, "key"); support.blob = true; } catch (err) { support.blob = false; } finally { db.close(); indexedDB.deleteDatabase(dbName); } }; request.onupgradeneeded = function() { request.result.createObjectStore("store"); }; }; }; var Base64ToBlob = function(dataURL) { var BASE64_MARKER = ';base64,'; if (dataURL.indexOf(BASE64_MARKER) == -1) { var parts = dataURL.split(','); var contentType = parts[0].split(':')[1]; var raw = decodeURIComponent(parts[1]); return new Blob([raw], {type: contentType}); } var parts = dataURL.split(BASE64_MARKER); var contentType = parts[0].split(':')[1]; var raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], {type: contentType}); }; var BlobToBase64 = function(blob, onload) { var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { onload(reader.result); }; }; if (!exports.PERSISTENT) { exports.TEMPORARY = 0; exports.PERSISTENT = 1; } // Prevent errors in browsers that don't support FileError. // TODO: FF 13+ supports DOM4 Events (DOMError). Use them instead? if (exports.FileError === undefined) { window.FileError = function() {}; FileError.prototype.prototype = Error.prototype; } if (!FileError.INVALID_MODIFICATION_ERR) { FileError.INVALID_MODIFICATION_ERR = 9; FileError.NOT_FOUND_ERR = 1; } function MyFileError(obj) { var code_ = obj.code; var name_ = obj.name; // Required for FF 11. Object.defineProperty(this, 'code', { set: function(code) { code_ = code; }, get: function() { return code_; } }); Object.defineProperty(this, 'name', { set: function(name) { name_ = name; }, get: function() { return name_; } }); } MyFileError.prototype = FileError.prototype; MyFileError.prototype.toString = Error.prototype.toString; var INVALID_MODIFICATION_ERR = new MyFileError({ code: FileError.INVALID_MODIFICATION_ERR, name: 'INVALID_MODIFICATION_ERR'}); var NOT_IMPLEMENTED_ERR = new MyFileError({code: 1000, name: 'Not implemented'}); var NOT_FOUND_ERR = new MyFileError({code: FileError.NOT_FOUND_ERR, name: 'Not found'}); var fs_ = null; // Browsers other than Chrome don't implement persistent vs. temporary storage. // but default to temporary anyway. var storageType_ = 'temporary'; var idb_ = {}; idb_.db = null; var FILE_STORE_ = 'entries'; var DIR_SEPARATOR = '/'; var DIR_OPEN_BOUND = String.fromCharCode(DIR_SEPARATOR.charCodeAt(0) + 1); // When saving an entry, the fullPath should always lead with a slash and never // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute // one. This method ensures path is legit! function resolveToFullPath_(cwdFullPath, path) { if (path === undefined) { return cwdFullPath; } var fullPath = path; var relativePath = path[0] != DIR_SEPARATOR; if (relativePath) { fullPath = cwdFullPath + DIR_SEPARATOR + path; } // Normalize '.'s, '..'s and '//'s. var parts = fullPath.split(DIR_SEPARATOR); var finalParts = []; for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part === '..') { // Go up one level. if (!finalParts.length) { throw Error('Invalid path'); } finalParts.pop(); } else if (part === '.') { // Skip over the current directory. } else if (part !== '') { // Eliminate sequences of '/'s as well as possible leading/trailing '/'s. finalParts.push(part); } } fullPath = DIR_SEPARATOR + finalParts.join(DIR_SEPARATOR); // fullPath is guaranteed to be normalized by construction at this point: // '.'s, '..'s, '//'s will never appear in it. return fullPath; } // // Path can be relative or absolute. If relative, it's taken from the cwd_. // // If a filesystem URL is passed it, it is simple returned // function pathToFsURL_(path) { // path = resolveToFullPath_(cwdFullPath, path); // path = fs_.root.toURL() + path.substring(1); // return path; // }; /** * Interface to wrap the native File interface. * * This interface is necessary for creating zero-length (empty) files, * something the Filesystem API allows you to do. Unfortunately, File's * constructor cannot be called directly, making it impossible to instantiate * an empty File in JS. * * @param {Object} opts Initial values. * @constructor */ function MyFile(opts) { var blob_ = null; this.size = opts.size || 0; this.name = opts.name || ''; this.type = opts.type || ''; this.lastModifiedDate = opts.lastModifiedDate || null; //this.slice = Blob.prototype.slice; // Doesn't work with structured clones. // Need some black magic to correct the object's size/name/type based on the // blob that is saved. Object.defineProperty(this, 'blob_', { enumerable: true, get: function() { return blob_; }, set: function (val) { blob_ = val; this.size = blob_.size; this.name = blob_.name; this.type = blob_.type; this.lastModifiedDate = blob_.lastModifiedDate; }.bind(this) }); } MyFile.prototype.constructor = MyFile; //MyFile.prototype.slice = Blob.prototype.slice; /** * Interface to writing a Blob/File. * * Modeled from: * dev.w3.org/2009/dap/file-system/file-writer.html#the-filewriter-interface * * @param {FileEntry} fileEntry The FileEntry associated with this writer. * @constructor */ function FileWriter(fileEntry) { if (!fileEntry) { throw Error('Expected fileEntry argument to write.'); } var position_ = 0; var blob_ = fileEntry.file_ ? fileEntry.file_.blob_ : null; Object.defineProperty(this, 'position', { get: function() { return position_; } }); Object.defineProperty(this, 'length', { get: function() { return blob_ ? blob_.size : 0; } }); this.seek = function(offset) { position_ = offset; if (position_ > this.length) { position_ = this.length; } if (position_ < 0) { position_ += this.length; } if (position_ < 0) { position_ = 0; } }; this.truncate = function(size) { if (blob_) { if (size < this.length) { blob_ = blob_.slice(0, size); } else { blob_ = new Blob([blob_, new Uint8Array(size - this.length)], {type: blob_.type}); } } else { blob_ = new Blob([]); } position_ = 0; // truncate from beginning of file. this.write(blob_); // calls onwritestart and onwriteend. }; this.write = function(data) { if (!data) { throw Error('Expected blob argument to write.'); } // Call onwritestart if it was defined. if (this.onwritestart) { this.onwritestart(); } // TODO: not handling onprogress, onwrite, onabort. Throw an error if // they're defined. if (blob_) { // Calc the head and tail fragments var head = blob_.slice(0, position_); var tail = blob_.slice(position_ + data.size); // Calc the padding var padding = position_ - head.size; if (padding < 0) { padding = 0; } // Do the "write". In fact, a full overwrite of the Blob. // TODO: figure out if data.type should overwrite the exist blob's type. blob_ = new Blob([head, new Uint8Array(padding), data, tail], {type: blob_.type}); } else { blob_ = new Blob([data], {type: data.type}); } var writeFile = function(blob) { // Blob might be a DataURI depending on browser support. fileEntry.file_.blob_ = blob; fileEntry.file_.lastModifiedDate = data.lastModifiedDate || new Date(); idb_.put(fileEntry, function(entry) { if (!support.blob) { // Set the blob we're writing on this file entry so we can recall it later. fileEntry.file_.blob_ = blob_; fileEntry.file_.lastModifiedDate = data.lastModifiedDate || null; } // Add size of data written to writer.position. position_ += data.size; if (this.onwriteend) { this.onwriteend(); } }.bind(this), this.onerror); }.bind(this); if (support.blob) { writeFile(blob_); } else { BlobToBase64(blob_, writeFile); } }; } /** * Interface for listing a directory's contents (files and folders). * * Modeled from: * dev.w3.org/2009/dap/file-system/pub/FileSystem/#idl-def-DirectoryReader * * @constructor */ function DirectoryReader(dirEntry) { var dirEntry_ = dirEntry; var used_ = false; this.readEntries = function(successCallback, opt_errorCallback) { if (!successCallback) { throw Error('Expected successCallback argument.'); } // This is necessary to mimic the way DirectoryReader.readEntries() should // normally behavior. According to spec, readEntries() needs to be called // until the length of result array is 0. To handle someone implementing // a recursive call to readEntries(), get everything from indexedDB on the // first shot. Then (DirectoryReader has been used), return an empty // result array. if (!used_) { idb_.getAllEntries(dirEntry_.fullPath, function(entries) { used_= true; successCallback(entries); }, opt_errorCallback); } else { successCallback([]); } }; }; /** * Interface supplies information about the state of a file or directory. * * Modeled from: * dev.w3.org/2009/dap/file-system/file-dir-sys.html#idl-def-Metadata * * @constructor */ function Metadata(modificationTime, size) { this.modificationTime_ = modificationTime || null; this.size_ = size || 0; } Metadata.prototype = { get modificationTime() { return this.modificationTime_; }, get size() { return this.size_; } } /** * Interface representing entries in a filesystem, each of which may be a File * or DirectoryEntry. * * Modeled from: * dev.w3.org/2009/dap/file-system/pub/FileSystem/#idl-def-Entry * * @constructor */ function Entry() {} Entry.prototype = { name: null, fullPath: null, filesystem: null, copyTo: function() { throw NOT_IMPLEMENTED_ERR; }, getMetadata: function(successCallback, opt_errorCallback) { if (!successCallback) { throw Error('Expected successCallback argument.'); } try { if (this.isFile) { successCallback( new Metadata(this.file_.lastModifiedDate, this.file_.size)); } else { opt_errorCallback(new MyFileError({code: 1001, name: 'getMetadata() not implemented for DirectoryEntry'})); } } catch(e) { opt_errorCallback && opt_errorCallback(e); } }, getParent: function() { throw NOT_IMPLEMENTED_ERR; }, moveTo: function() { throw NOT_IMPLEMENTED_ERR; }, remove: function(successCallback, opt_errorCallback) { if (!successCallback) { throw Error('Expected successCallback argument.'); } // TODO: This doesn't protect against directories that have content in it. // Should throw an error instead if the dirEntry is not empty. idb_['delete'](this.fullPath, function() { successCallback(); }, opt_errorCallback); }, toURL: function() { var origin = location.protocol + '//' + location.host; return 'filesystem:' + origin + DIR_SEPARATOR + storageType_.toLowerCase() + this.fullPath; }, }; /** * Interface representing a file in the filesystem. * * Modeled from: * dev.w3.org/2009/dap/file-system/pub/FileSystem/#the-fileentry-interface * * @param {FileEntry} opt_fileEntry Optional FileEntry to initialize this * object from. * @constructor * @extends {Entry} */ function FileEntry(opt_fileEntry) { this.file_ = null; Object.defineProperty(this, 'isFile', { enumerable: true, get: function() { return true; } }); Object.defineProperty(this, 'isDirectory', { enumerable: true, get: function() { return false; } }); // Create this entry from properties from an existing FileEntry. if (opt_fileEntry) { this.file_ = opt_fileEntry.file_; this.name = opt_fileEntry.name; this.fullPath = opt_fileEntry.fullPath; this.filesystem = opt_fileEntry.filesystem; if (typeof(this.file_.blob_) === "string") { this.file_.blob_ = Base64ToBlob(this.file_.blob_); } } } FileEntry.prototype = new Entry(); FileEntry.prototype.constructor = FileEntry; FileEntry.prototype.createWriter = function(callback) { // TODO: figure out if there's a way to dispatch onwrite event as we're writing // data to IDB. Right now, we're only calling onwritend/onerror // FileEntry.write(). callback(new FileWriter(this)); }; FileEntry.prototype.file = function(successCallback, opt_errorCallback) { if (!successCallback) { throw Error('Expected successCallback argument.'); } if (this.file_ == null) { if (opt_errorCallback) { opt_errorCallback(NOT_FOUND_ERR); } else { throw NOT_FOUND_ERR; } return; } // If we're returning a zero-length (empty) file, return the fake file obj. // Otherwise, return the native File object that we've stashed. var file = this.file_.blob_ == null ? this.file_ : this.file_.blob_; file.lastModifiedDate = this.file_.lastModifiedDate; // Add Blob.slice() to this wrapped object. Currently won't work :( /*if (!val.slice) { val.slice = Blob.prototype.slice; // Hack to add back in .slice(). }*/ successCallback(file); }; /** * Interface representing a directory in the filesystem. * * Modeled from: * dev.w3.org/2009/dap/file-system/pub/FileSystem/#the-directoryentry-interface * * @param {DirectoryEntry} opt_folderEntry Optional DirectoryEntry to * initialize this object from. * @constructor * @extends {Entry} */ function DirectoryEntry(opt_folderEntry) { Object.defineProperty(this, 'isFile', { enumerable: true, get: function() { return false; } }); Object.defineProperty(this, 'isDirectory', { enumerable: true, get: function() { return true; } }); // Create this entry from properties from an existing DirectoryEntry. if (opt_folderEntry) { this.name = opt_folderEntry.name; this.fullPath = opt_folderEntry.fullPath; this.filesystem = opt_folderEntry.filesystem; } } DirectoryEntry.prototype = new Entry(); DirectoryEntry.prototype.constructor = DirectoryEntry; DirectoryEntry.prototype.createReader = function() { return new DirectoryReader(this); }; DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, opt_errorCallback) { // Create an absolute path if we were handed a relative one. path = resolveToFullPath_(this.fullPath, path); idb_.get(path, function(folderEntry) { if (!options) { options = {}; } if (options.create === true && options.exclusive === true && folderEntry) { // If create and exclusive are both true, and the path already exists, // getDirectory must fail. if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } else if (options.create === true && !folderEntry) { // If create is true, the path doesn't exist, and no other error occurs, // getDirectory must create it as a zero-length file and return a corresponding // DirectoryEntry. var dirEntry = new DirectoryEntry(); dirEntry.name = path.split(DIR_SEPARATOR).pop(); // Just need filename. dirEntry.fullPath = path; dirEntry.filesystem = fs_; idb_.put(dirEntry, successCallback, opt_errorCallback); } else if (options.create === true && folderEntry) { if (folderEntry.isDirectory) { // IDB won't save methods, so we need re-create the DirectoryEntry. successCallback(new DirectoryEntry(folderEntry)); } else { if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } } else if ((!options.create || options.create === false) && !folderEntry) { // Handle root special. It should always exist. if (path == DIR_SEPARATOR) { folderEntry = new DirectoryEntry(); folderEntry.name = ''; folderEntry.fullPath = DIR_SEPARATOR; folderEntry.filesystem = fs_; successCallback(folderEntry); return; } // If create is not true and the path doesn't exist, getDirectory must fail. if (opt_errorCallback) { opt_errorCallback(NOT_FOUND_ERR); return; } } else if ((!options.create || options.create === false) && folderEntry && folderEntry.isFile) { // If create is not true and the path exists, but is a file, getDirectory // must fail. if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } else { // Otherwise, if no other error occurs, getDirectory must return a // DirectoryEntry corresponding to path. // IDB won't' save methods, so we need re-create DirectoryEntry. successCallback(new DirectoryEntry(folderEntry)); } }, opt_errorCallback); }; DirectoryEntry.prototype.getFile = function(path, options, successCallback, opt_errorCallback) { // Create an absolute path if we were handed a relative one. path = resolveToFullPath_(this.fullPath, path); idb_.get(path, function(fileEntry) { if (!options) { options = {}; } if (options.create === true && options.exclusive === true && fileEntry) { // If create and exclusive are both true, and the path already exists, // getFile must fail. if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } else if (options.create === true && !fileEntry) { // If create is true, the path doesn't exist, and no other error occurs, // getFile must create it as a zero-length file and return a corresponding // FileEntry. var fileEntry = new FileEntry(); fileEntry.name = path.split(DIR_SEPARATOR).pop(); // Just need filename. fileEntry.fullPath = path; fileEntry.filesystem = fs_; fileEntry.file_ = new MyFile({size: 0, name: fileEntry.name, lastModifiedDate: new Date()}); idb_.put(fileEntry, successCallback, opt_errorCallback); } else if (options.create === true && fileEntry) { if (fileEntry.isFile) { // IDB won't save methods, so we need re-create the FileEntry. successCallback(new FileEntry(fileEntry)); } else { if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } } else if ((!options.create || options.create === false) && !fileEntry) { // If create is not true and the path doesn't exist, getFile must fail. if (opt_errorCallback) { opt_errorCallback(NOT_FOUND_ERR); return; } } else if ((!options.create || options.create === false) && fileEntry && fileEntry.isDirectory) { // If create is not true and the path exists, but is a directory, getFile // must fail. if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } else { // Otherwise, if no other error occurs, getFile must return a FileEntry // corresponding to path. // IDB won't' save methods, so we need re-create the FileEntry. successCallback(new FileEntry(fileEntry)); } }, opt_errorCallback); }; DirectoryEntry.prototype.removeRecursively = function(successCallback, opt_errorCallback) { if (!successCallback) { throw Error('Expected successCallback argument.'); } this.remove(successCallback, opt_errorCallback); }; /** * Interface representing a filesystem. * * Modeled from: * dev.w3.org/2009/dap/file-system/pub/FileSystem/#idl-def-LocalFileSystem * * @param {number} type Kind of storage to use, either TEMPORARY or PERSISTENT. * @param {number} size Storage space (bytes) the application expects to need. * @constructor */ function DOMFileSystem(type, size) { storageType_ = type == exports.TEMPORARY ? 'Temporary' : 'Persistent'; this.name = (location.protocol + location.host).replace(/:/g, '_') + ':' + storageType_; this.root = new DirectoryEntry(); this.root.fullPath = DIR_SEPARATOR; this.root.filesystem = this; this.root.name = ''; } function requestFileSystem(type, size, successCallback, opt_errorCallback) { if (type != exports.TEMPORARY && type != exports.PERSISTENT) { if (opt_errorCallback) { opt_errorCallback(INVALID_MODIFICATION_ERR); return; } } fs_ = new DOMFileSystem(type, size); idb_.open(fs_.name, function(e) { successCallback(fs_); }, opt_errorCallback); } function resolveLocalFileSystemURL(url, successCallback, opt_errorCallback) { var origin = location.protocol + '//' + location.host; var base = 'filesystem:' + origin + DIR_SEPARATOR + storageType_.toLowerCase(); url = url.replace(base, ''); if (url.substr(-1) === '/') { url = url.slice(0, -1); } if (url) { idb_.get(url, function(entry) { if (entry) { if (entry.isFile) { return successCallback(new FileEntry(entry)); } else if (entry.isDirectory) { return successCallback(new DirectoryEntry(entry)); } } else { opt_errorCallback && opt_errorCallback(NOT_FOUND_ERR); } }, opt_errorCallback); } else { successCallback(fs_.root); } } // Core logic to handle IDB operations ========================================= idb_.open = function(dbName, successCallback, opt_errorCallback) { var self = this; // TODO: FF 12.0a1 isn't liking a db name with : in it. var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/); request.onerror = opt_errorCallback || onError; request.onupgradeneeded = function(e) { // First open was called or higher db version was used. // console.log('onupgradeneeded: oldVersion:' + e.oldVersion, // 'newVersion:' + e.newVersion); self.db = e.target.result; self.db.onerror = onError; if (!self.db.objectStoreNames.contains(FILE_STORE_)) { var store = self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/); } }; request.onsuccess = function(e) { self.db = e.target.result; self.db.onerror = onError; successCallback(e); }; request.onblocked = opt_errorCallback || onError; }; idb_.close = function() { this.db.close(); this.db = null; }; // TODO: figure out if we should ever call this method. The filesystem API // doesn't allow you to delete a filesystem once it is 'created'. Users should // use the public remove/removeRecursively API instead. idb_.drop = function(successCallback, opt_errorCallback) { if (!this.db) { return; } var dbName = this.db.name; var request = indexedDB.deleteDatabase(dbName); request.onsuccess = function(e) { successCallback(e); }; request.onerror = opt_errorCallback || onError; idb_.close(); }; idb_.get = function(fullPath, successCallback, opt_errorCallback) { if (!this.db) { return; } var tx = this.db.transaction([FILE_STORE_], 'readonly'); //var request = tx.objectStore(FILE_STORE_).get(fullPath); var range = IDBKeyRange.bound(fullPath, fullPath + DIR_OPEN_BOUND, false, true); var request = tx.objectStore(FILE_STORE_).get(range); tx.onabort = opt_errorCallback || onError; tx.oncomplete = function(e) { successCallback(request.result); }; }; idb_.getAllEntries = function(fullPath, successCallback, opt_errorCallback) { if (!this.db) { return; } var results = []; //var range = IDBKeyRange.lowerBound(fullPath, true); //var range = IDBKeyRange.upperBound(fullPath, true); // Treat the root entry special. Querying it returns all entries because // they match '/'. var range = null; if (fullPath != DIR_SEPARATOR) { //console.log(fullPath + '/', fullPath + DIR_OPEN_BOUND) range = IDBKeyRange.bound( fullPath + DIR_SEPARATOR, fullPath + DIR_OPEN_BOUND, false, true); } var tx = this.db.transaction([FILE_STORE_], 'readonly'); tx.onabort = opt_errorCallback || onError; tx.oncomplete = function(e) { // TODO: figure out how to do be range queries instead of filtering result // in memory :( results = results.filter(function(val) { var valPartsLen = val.fullPath.split(DIR_SEPARATOR).length; var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length; if (fullPath == DIR_SEPARATOR && valPartsLen < fullPathPartsLen + 1) { // Hack to filter out entries in the root folder. This is inefficient // because reading the entires of fs.root (e.g. '/') returns ALL // results in the database, then filters out the entries not in '/'. return val; } else if (fullPath != DIR_SEPARATOR && valPartsLen == fullPathPartsLen + 1) { // If this a subfolder and entry is a direct child, include it in // the results. Otherwise, it's not an entry of this folder. return val; } }); successCallback(results); }; var request = tx.objectStore(FILE_STORE_).openCursor(range); request.onsuccess = function(e) { var cursor = e.target.result; if (cursor) { var val = cursor.value; results.push(val.isFile ? new FileEntry(val) : new DirectoryEntry(val)); cursor['continue'](); } }; }; idb_['delete'] = function(fullPath, successCallback, opt_errorCallback) { if (!this.db) { return; } var tx = this.db.transaction([FILE_STORE_], 'readwrite'); tx.oncomplete = successCallback; tx.onabort = opt_errorCallback || onError; //var request = tx.objectStore(FILE_STORE_).delete(fullPath); var range = IDBKeyRange.bound( fullPath, fullPath + DIR_OPEN_BOUND, false, true); var request = tx.objectStore(FILE_STORE_)['delete'](range); }; idb_.put = function(entry, successCallback, opt_errorCallback) { if (!this.db) { return; } var tx = this.db.transaction([FILE_STORE_], 'readwrite'); tx.onabort = opt_errorCallback || onError; tx.oncomplete = function(e) { // TODO: Error is thrown if we pass the request event back instead. successCallback(entry); }; var request = tx.objectStore(FILE_STORE_).put(entry, entry.fullPath); }; // Global error handler. Errors bubble from request, to transaction, to db. function onError(e) { switch (e.target.errorCode) { case 12: console.log('Error - Attempt to open db with a lower version than the ' + 'current one.'); break; default: console.log('errorCode: ' + e.target.errorCode); } console.log(e, e.code, e.message); } // Clean up. // TODO: decide if this is the best place for this. exports.addEventListener('beforeunload', function(e) { idb_.db.close(); }, false); //exports.idb = idb_; exports.requestFileSystem = requestFileSystem; exports.resolveLocalFileSystemURL = resolveLocalFileSystemURL; // Export more stuff (to window) for unit tests to do their thing. if (exports === window && exports.RUNNING_TESTS) { exports['Entry'] = Entry; exports['FileEntry'] = FileEntry; exports['DirectoryEntry'] = DirectoryEntry; exports['resolveToFullPath_'] = resolveToFullPath_; exports['Metadata'] = Metadata; exports['Base64ToBlob'] = Base64ToBlob; } })(self); // Don't use window because we want to run in workers.
alpine9000/BitMachine
external/idb.filesystem.js
JavaScript
bsd-2-clause
30,058
class Kotlin < Formula desc "Statically typed programming language for the JVM" homepage "https://kotlinlang.org/" url "https://github.com/JetBrains/kotlin/releases/download/v1.5.31/kotlin-compiler-1.5.31.zip" sha256 "661111286f3e5ac06aaf3a9403d869d9a96a176b62b141814be626a47249fe9e" license "Apache-2.0" livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any_skip_relocation, all: "c465a77943a1b7f7a8dafac62e2ed153c6e89400527459cf349fdfd858140f36" end depends_on "openjdk" def install libexec.install "bin", "build.txt", "lib" rm Dir[libexec/"bin/*.bat"] bin.install Dir[libexec/"bin/*"] bin.env_script_all_files libexec/"bin", Language::Java.overridable_java_home_env prefix.install "license" end test do (testpath/"test.kt").write <<~EOS fun main(args: Array<String>) { println("Hello World!") } EOS system bin/"kotlinc", "test.kt", "-include-runtime", "-d", "test.jar" system bin/"kotlinc-js", "test.kt", "-output", "test.js" system bin/"kotlinc-jvm", "test.kt", "-include-runtime", "-d", "test.jar" end end
Moisan/homebrew-core
Formula/kotlin.rb
Ruby
bsd-2-clause
1,151
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>org.gradle.api.tasks.bundling (Gradle API 2.2.1)</title> <meta name="keywords" content="org.gradle.api.tasks.bundling package"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" title="Style"> <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon"> <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon"> <script type="text/javascript"> function windowTitle() { parent.document.title="org.gradle.api.tasks.bundling (Gradle API 2.2.1)"; } </script> <noscript> </noscript> </head> <body class="center" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <a name="navbar_top_firstrow"><!-- --></a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../index.html?org/gradle/api/tasks/bundling/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> </div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Package org.gradle.api.tasks.bundling</h1> </div> <div class="header"> <h2 title=" Tasks for bundling JVM components into JAR files. " class="title"> Tasks for bundling JVM components into JAR files. </h2> </div> <div class="contentContainer"> <div class="summary"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Class Summary"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tbody> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="AbstractArchiveTask.html" title="class in org/gradle/api/tasks/bundling"> AbstractArchiveTask </a></strong> </td> <td><CODE>AbstractArchiveTask</CODE> is the base class for all archive tasks.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="Jar.html" title="class in org/gradle/api/tasks/bundling"> Jar </a></strong> </td> <td>Assembles a JAR archive.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="Tar.html" title="class in org/gradle/api/tasks/bundling"> Tar </a></strong> </td> <td>Assembles a TAR archive.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="War.html" title="class in org/gradle/api/tasks/bundling"> War </a></strong> </td> <td>Assembles a WAR archive.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="Zip.html" title="class in org/gradle/api/tasks/bundling"> Zip </a></strong> </td> <td>Assembles a ZIP archive.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="Zip.ZipCopyActionImpl.html" title="class in org/gradle/api/tasks/bundling"> Zip.ZipCopyActionImpl </a></strong> </td> <td>DO NOT REMOVE.</td> </tr> </tbody> </table> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Enum Summary"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tbody> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="Compression.html" title="class in org/gradle/api/tasks/bundling"> Compression </a></strong> </td> <td>Specifies the compression which should be applied to a TAR archive.</td> </tr> <tr class="altColor"> <td class="colOne"> <strong><a href="ZipEntryCompression.html" title="class in org/gradle/api/tasks/bundling"> ZipEntryCompression </a></strong> </td> <td>Specifies the compression level of an archives contents.</td> </tr> </tbody> </table> </li> </ul> </div> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li> <li><a href="deprecated-list.html" target="_top">No Frames</a></li> </ul> </div> <div class="aboutLanguage"><em>Gradle API 2.2.1</em></div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/docs/groovydoc/org/gradle/api/tasks/bundling/package-summary.html
HTML
bsd-2-clause
7,682
#include "event.h" #include "asio.h" #ifdef ASIO_USE_IOCP #include "../actor/messageq.h" #include "../mem/pool.h" #include <string.h> #include <signal.h> #include <stdbool.h> #include <winsock2.h> // Requests to start and stop timers and to listen to stdin go through a // request queue so that all operations can be performed in a single thread // (the asio background thread). #define MAX_SIGNAL 32 struct asio_backend_t { HANDLE wakeup; bool stop; asio_event_t* sighandlers[MAX_SIGNAL]; messageq_t q; }; enum // Event requests { ASIO_STDIN_NOTIFY = 5, ASIO_STDIN_RESUME = 6, ASIO_SET_TIMER = 7, ASIO_CANCEL_TIMER = 8, ASIO_SET_SIGNAL = 9, ASIO_CANCEL_SIGNAL = 10 }; static void send_request(asio_event_t* ev, int req) { asio_backend_t* b = asio_get_backend(); asio_msg_t* msg = (asio_msg_t*)pony_alloc_msg( POOL_INDEX(sizeof(asio_msg_t)), 0); msg->event = ev; msg->flags = req; messageq_push(&b->q, (pony_msg_t*)msg); SetEvent(b->wakeup); } static void signal_handler(int sig) { if(sig >= MAX_SIGNAL) return; // Reset the signal handler. signal(sig, signal_handler); asio_backend_t* b = asio_get_backend(); asio_event_t* ev = b->sighandlers[sig]; asio_event_send(ev, ASIO_SIGNAL, 1); } void CALLBACK timer_fire(void* arg, DWORD timer_low, DWORD timer_high) { // A timer has fired, notify the actor asio_event_send((asio_event_t*)arg, ASIO_TIMER, 0); } asio_backend_t* asio_backend_init() { asio_backend_t* b = POOL_ALLOC(asio_backend_t); memset(b, 0, sizeof(asio_backend_t)); messageq_init(&b->q); b->wakeup = CreateEvent(NULL, FALSE, FALSE, NULL); b->stop = false; if(b->wakeup == NULL) { POOL_FREE(asio_backend_t, b); return NULL; } return b; } void asio_backend_terminate(asio_backend_t* b) { b->stop = true; SetEvent(b->wakeup); } DECLARE_THREAD_FN(asio_backend_dispatch) { pony_register_thread(); asio_backend_t* b = (asio_backend_t*)arg; asio_event_t* stdin_event = NULL; HANDLE handles[2]; handles[0] = b->wakeup; handles[1] = GetStdHandle(STD_INPUT_HANDLE); // handleCount indicates: // 1 => only listen on queue wake event // 2 => listen on queue wake event and stdin int handleCount = 1; while(!b->stop) { switch(WaitForMultipleObjectsEx(handleCount, handles, FALSE, -1, TRUE)) { case WAIT_OBJECT_0: { // Process all items on our queue. // Since our wake event is not manual, it has already been reset by the // time we reach here. asio_msg_t* msg; while((msg = (asio_msg_t*)messageq_pop(&b->q)) != NULL) { asio_event_t* ev = msg->event; switch(msg->flags) { case ASIO_STDIN_NOTIFY: // Who to notify about stdin events has changed stdin_event = ev; if(stdin_event == NULL) // No-one listening, don't wait on stdin handleCount = 1; else // Someone wants stdin, include it in the wait set handleCount = 2; break; case ASIO_STDIN_RESUME: // Console events have been read, we can continue waiting on // stdin now if(stdin_event != NULL) handleCount = 2; break; case ASIO_SET_TIMER: { // Windows timer resolution is 100ns, adjust given time int64_t dueTime = -(int64_t)ev->nsec / 100; LARGE_INTEGER liDueTime; liDueTime.LowPart = (DWORD)(dueTime & 0xFFFFFFFF); liDueTime.HighPart = (LONG)(dueTime >> 32); SetWaitableTimer(ev->timer, &liDueTime, 0, timer_fire, (void*)ev, FALSE); break; } case ASIO_CANCEL_TIMER: { CancelWaitableTimer(ev->timer); CloseHandle(ev->timer); ev->timer = NULL; // Now that we've called cancel no more fire APCs can happen for // this timer, so we're safe to send the dispose notify now. ev->flags = ASIO_DISPOSABLE; asio_event_send(ev, ASIO_DISPOSABLE, 0); break; } case ASIO_SET_SIGNAL: { int sig = (int)ev->nsec; if(b->sighandlers[sig] == NULL) { b->sighandlers[sig] = ev; signal(sig, signal_handler); } break; } case ASIO_CANCEL_SIGNAL: { asio_event_t* ev = msg->event; int sig = (int)ev->nsec; if(b->sighandlers[sig] == ev) { b->sighandlers[sig] = NULL; signal(sig, SIG_DFL); } ev->flags = ASIO_DISPOSABLE; asio_event_send(ev, ASIO_DISPOSABLE, 0); break; } default: // Something's gone very wrong if we reach here break; } } break; } case WAIT_OBJECT_0 + 1: // Stdin has input available. // Since the console input signal state is level triggered not edge // triggered we have to stop waiting on stdin now until the current // input is read. handleCount = 1; // Notify the stdin event listener stdin_event->flags = ASIO_READ; asio_event_send(stdin_event, ASIO_READ, 0); break; default: break; } } CloseHandle(b->wakeup); messageq_destroy(&b->q); POOL_FREE(asio_backend_t, b); return NULL; } // Called from stdfd.c to resume waiting on stdin after a read void iocp_resume_stdin() { send_request(NULL, ASIO_STDIN_RESUME); } void asio_event_subscribe(asio_event_t* ev) { if((ev == NULL) || (ev->flags == ASIO_DISPOSABLE) || (ev->flags == ASIO_DESTROYED)) return; asio_backend_t* b = asio_get_backend(); if(ev->noisy) asio_noisy_add(); if((ev->flags & ASIO_TIMER) != 0) { // Need to start a timer. // We can create it here but not start it. That must be done in the // background thread because that's where we want the fire APC to happen. // ev->data is initially the time (in nsec) and ends up as the handle. ev->timer = CreateWaitableTimer(NULL, FALSE, NULL); send_request(ev, ASIO_SET_TIMER); } else if((ev->flags & ASIO_SIGNAL) != 0) { if(ev->nsec < MAX_SIGNAL) send_request(ev, ASIO_SET_SIGNAL); } else if(ev->fd == 0) { // Need to subscribe to stdin send_request(ev, ASIO_STDIN_NOTIFY); } } void asio_event_setnsec(asio_event_t* ev, uint64_t nsec) { if((ev == NULL) || (ev->flags == ASIO_DISPOSABLE) || (ev->flags == ASIO_DESTROYED)) return; if((ev->flags & ASIO_TIMER) != 0) { // Need to restart a timer. // That must be done in the background thread because that's where we want // the fire APC to happen. ev->nsec = nsec; send_request(ev, ASIO_SET_TIMER); } } void asio_event_unsubscribe(asio_event_t* ev) { if((ev == NULL) || (ev->flags == ASIO_DISPOSABLE) || (ev->flags == ASIO_DESTROYED)) return; asio_backend_t* b = asio_get_backend(); if(ev->noisy) { asio_noisy_remove(); ev->noisy = false; } if((ev->flags & ASIO_TIMER) != 0) { // Need to cancel a timer. // The timer set goes through our request queue and if we did the cancel // here it might overtake the set. So you put the cancel through the queue // as well. send_request(ev, ASIO_CANCEL_TIMER); } else if((ev->flags & ASIO_SIGNAL) != 0) { if(ev->nsec < MAX_SIGNAL) { send_request(ev, ASIO_CANCEL_SIGNAL); } else { ev->flags = ASIO_DISPOSABLE; asio_event_send(ev, ASIO_DISPOSABLE, 0); } } else if((ev->flags & (ASIO_READ | ASIO_WRITE)) != 0) { // Need to unsubscribe from stdin if(ev->fd == 0) send_request(NULL, ASIO_STDIN_NOTIFY); ev->flags = ASIO_DISPOSABLE; asio_event_send(ev, ASIO_DISPOSABLE, 0); } } #endif
jemc/ponyc
src/libponyrt/asio/iocp.c
C
bsd-2-clause
8,106
/*- * Copyright (c) 2010 Redpill Linpro AS * All rights reserved. * * Author: Poul-Henning Kamp <phk@phk.freebsd.dk> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * Memory barriers * * XXX: It is utterly braindamaged, that no standard facility for this * XXX: is available. The "just use pthreads locking" excuse does not * XXX: make sense, and does not apply to two unthreaded programs sharing * XXX: a memory segment. */ #ifndef VMB_H_INCLUDED #define VMB_H_INCLUDED #if defined(__FreeBSD__) #include <sys/param.h> #endif #if defined(__FreeBSD__) && __FreeBSD_version >= 800058 #include <sys/types.h> #include <machine/atomic.h> #define VMB() mb() #define VWMB() wmb() #define VRMB() rmb() #elif defined(__amd64__) && defined(__GNUC__) #define VMB() __asm __volatile("mfence;" : : : "memory") #define VWMB() __asm __volatile("sfence;" : : : "memory") #define VRMB() __asm __volatile("lfence;" : : : "memory") #elif defined(__arm__) #define VMB() #define VWMB() #define VRMB() #elif defined(__i386__) && defined(__GNUC__) #define VMB() __asm __volatile("lock; addl $0,(%%esp)" : : : "memory") #define VWMB() __asm __volatile("lock; addl $0,(%%esp)" : : : "memory") #define VRMB() __asm __volatile("lock; addl $0,(%%esp)" : : : "memory") #elif defined(__sparc64__) && defined(__GNUC__) #define VMB() __asm__ __volatile__ ("membar #MemIssue": : :"memory") #define VWMB() VMB() #define VRMB() VMB() #else #define VMB_NEEDS_PTHREAD_WORKAROUND_THIS_IS_BAD_FOR_PERFORMANCE 1 void vmb_pthread(void); #define VMB() vmb_pthread() #define VWMB() vmb_pthread() #define VRMB() vmb_pthread() #endif #endif /* VMB_H_INCLUDED */
drwilco/varnish-cache-old
include/vmb.h
C
bsd-2-clause
2,885
using System; using System.ComponentModel; using System.Data; using System.Windows.Forms; using bv.common.Configuration; using bv.common.Core; using DevExpress.XtraEditors; using bv.common.win; using bv.common.db.Core; using DevExpress.XtraGrid.Views.Grid; using EIDSS.RAM_DB.DBService.QueryBuilder; using EIDSS.RAM.Components; using eidss.model.Resources; using bv.winclient.Core; namespace EIDSS.RAM.QueryBuilder { public partial class QuerySearchObjectInfo : BaseRamDetailPanel { private readonly FilterControlHelper m_FilterControlHelper; #region Init public QuerySearchObjectInfo() { InitializeComponent(); QuerySearchObjectDbService = new QuerySearchObject_DB(); DbService = QuerySearchObjectDbService; SearchObject = DefaultSearchObject; Order = 0; m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter); m_FilterControlHelper.OnFilterChanged += DisplayFilter; splitContainer.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel")); imlbcAvailableField.ImageList = RamFieldIcons.ImageList; imTypeImage.SmallImages = RamFieldIcons.ImageList; } public QuerySearchObjectInfo(long aSearchObject) { InitializeComponent(); QuerySearchObjectDbService = new QuerySearchObject_DB(); DbService = QuerySearchObjectDbService; SearchObject = aSearchObject; Order = 0; m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter); m_FilterControlHelper.OnFilterChanged += DisplayFilter; splitContainer.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel")); imlbcAvailableField.ImageList = RamFieldIcons.ImageList; imTypeImage.SmallImages = RamFieldIcons.ImageList; } public QuerySearchObjectInfo(long aSearchObject, int aOrder) { InitializeComponent(); QuerySearchObjectDbService = new QuerySearchObject_DB(); DbService = QuerySearchObjectDbService; SearchObject = aSearchObject; Order = aOrder >= 0 ? aOrder : 0; m_FilterControlHelper = new FilterControlHelper(QuerySearchFilter); m_FilterControlHelper.OnFilterChanged += DisplayFilter; splitContainer.SetPanelCollapsed(Config.GetBoolSetting("CollapseFilterPanel")); imlbcAvailableField.ImageList = RamFieldIcons.ImageList; imTypeImage.SmallImages = RamFieldIcons.ImageList; } /// <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 (Utils.IsCalledFromUnitTest()) // return; m_FilterControlHelper.OnFilterChanged -= DisplayFilter; m_FilterControlHelper.Dispose(); eventManager.ClearAllReferences(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion #region Keys public override object GetKey(string tableName, string keyFieldName) { return QuerySearchObjectDbService.ID; } #endregion #region Properties public readonly static long DefaultSearchObject = 10082000; // "sobHumanCases" private long m_SearchObject = -1L; [BrowsableAttribute(false), DefaultValueAttribute(-1L), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public long SearchObject { get { return m_SearchObject; } set { if (m_SearchObject != value) { m_SearchObject = value; UpdateQuerySearchObjectID(); } } } [BrowsableAttribute(false), DefaultValueAttribute(-1L), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public QuerySearchObject_DB QuerySearchObjectDbService { get; set; } private int m_Order = 0; [BrowsableAttribute(false), DefaultValueAttribute(0), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Order { get { return m_Order; } set { if (m_Order != value) { m_Order = value; UpdateQuerySearchObjectOrder(); } } } private bool m_IsFFObject = false; [BrowsableAttribute(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsFFObject { get { return m_IsFFObject; } } private long m_FormType = -1L; [BrowsableAttribute(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new long FormType { get { return m_FormType; } } private HACode m_ObjectHACode = HACode.None; [BrowsableAttribute(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public HACode ObjectHACode { get { return m_ObjectHACode; } } [BrowsableAttribute(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string CaptionText { get { if (Utils.IsEmpty(m_SearchObject) == false) { if (m_Order > 0) { return string.Format( "{0} # {1}", LookupCache.GetLookupValue( m_SearchObject, LookupTables.SearchObject, "Name"), m_Order); } return LookupCache.GetLookupValue( m_SearchObject, LookupTables.SearchObject, "Name"); } return (""); } } private string GetFieldGroupCaption { get { string caption = CaptionText; if (Utils.IsEmpty(caption) == false) { caption = string.Format("{0} - {1}", caption, EidssMessages.Get("msgFieldGroupSuffix", "Fields", null)); } return caption; } } private string GetFilterGroupCaption { get { string caption = CaptionText; if (Utils.IsEmpty(caption) == false) { caption = string.Format("{0} - {1}", caption, EidssMessages.Get("msgFilterGroupSuffix", "Filters", null)); } return caption; } } public override bool ReadOnly { get { return base.ReadOnly; } set { base.ReadOnly = value; btnAdd.Enabled = (!value); btnAddAll.Enabled = (!value); btnRemove.Enabled = (!value); btnRemoveAll.Enabled = (!value); gvSelectedField.OptionsBehavior.Editable = (!value); QuerySearchFilter.Enabled = (!value); } } #endregion #region Bindings private void BindAvailableFieldList() { string filterByDiagnosis = ""; if (m_IsFFObject) { //Core.LookupBinder.BindParameterForFFTypeLookup(lbcAvailableField); Core.LookupBinder.BindParameterForFFTypeLookup(imlbcAvailableField); if ((m_FormType == 10034010) || //Human Clinical Signs (m_FormType == 10034011)) //Human Epi Investigations { Core.LookupBinder.BindDiagnosisHACodeLookup(cbFilterByDiagnosis, baseDataSet, LookupTables.HumanStandardDiagnosis, null, true, true); filterByDiagnosis = " and DiagnosisString like '%'"; } } else { //Core.LookupBinder.BindSearchFieldLookup(lbcAvailableField); Core.LookupBinder.BindSearchFieldLookup(imlbcAvailableField); } //DataView dv = (DataView)lbcAvailableField.DataSource; DataView dv = (DataView)imlbcAvailableField.DataSource; dv.RowFilter = string.Format("idfsSearchObject = '{0}' and blnAvailable = 1 {1}", m_SearchObject, filterByDiagnosis); } private void BindSelectedFieldList() { gcSelectedField.DataSource = null; gcSelectedField.DataSource = new DataView( baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "FieldCaption", DataViewRowState.CurrentRows); imTypeImage.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; imTypeImage.Items.Clear(); imTypeImage.Items.AddRange(new DevExpress.XtraEditors.Controls.ImageComboBoxItem[] { new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 0, 0), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 1, 1), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 2, 2), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 3, 3), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 4, 4), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 5, 5), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 6, 6), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 7, 7), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("", 8, 8)}); if (ReadOnly) gvSelectedField.OptionsBehavior.Editable = false; } private void UpdateFieldList() { //if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null)) if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null)) { DataView dvSelectedField = (DataView)gcSelectedField.DataSource; //DataView dvAvailableField = (DataView)lbcAvailableField.DataSource; DataView dvAvailableField = (DataView)imlbcAvailableField.DataSource; int ind; DataRow rAvailable = null; foreach (DataRow r in dvAvailableField.Table.Rows) { if (Utils.Str(r["idfsSearchObject"]) == Utils.Str(m_SearchObject)) r["blnAvailable"] = true; } for (ind = 0; ind < dvSelectedField.Count; ind++) { DataRowView rSelected = null; rSelected = dvSelectedField[ind]; if (m_IsFFObject) { string fieldKey = Utils.Str(rSelected["FieldAlias"]); rAvailable = dvAvailableField.Table.Rows.Find(fieldKey); } else rAvailable = dvAvailableField.Table.Rows.Find(rSelected["idfsSearchField"]); if (rAvailable != null) { rAvailable.BeginEdit(); rAvailable["blnAvailable"] = false; rAvailable.EndEdit(); } } if (dvAvailableField.Count >= 0) { //lbcAvailableField.SelectedIndex = 0; imlbcAvailableField.SelectedIndex = 0; } } } private void BindFilterTree() { if (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)) m_FilterControlHelper.Bind((long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"], baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].DefaultView, baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].DefaultView); else m_FilterControlHelper.Bind((long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"], null, baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].DefaultView); } protected override void DefineBinding() { if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) && (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0) && (Utils.IsEmpty(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"]) == false) && (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] is long) && ((long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] != -1L)) { m_SearchObject = (long)baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"]; } BindAvailableFieldList(); BindSelectedFieldList(); BindFilterTree(); } private void QuerySearchObjectInfo_AfterLoadData(object sender, EventArgs e) { UpdateQuerySearchObjectID(); UpdateFieldList(); UpdateConditionText(); } #endregion #region Update Methods private void UpdateConditionList(object aQuerySearchFieldID) { if (Utils.IsEmpty(aQuerySearchFieldID)) { return; } if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup))) UpdateConditionText(); } /// <summary> /// Updates visibility of diagnosis controls and location of other controls depending on specified form type. /// </summary> /// <param name="formType">Form type to determine state of visibility.</param> private void UpdateVisibilityOfDiagnosisByFormType ( long formType ) { bool isVisible = (formType == 10034010) || // Human Clinical Signs (formType == 10034011); // Human Epi Investigations bool ret = false; if (lblFilterByDiagnosis != null) { if (lblFilterByDiagnosis.Visible == isVisible) { ret = true; } lblFilterByDiagnosis.Visible = isVisible; } if (cbFilterByDiagnosis != null) { if (ret && (cbFilterByDiagnosis.Visible == isVisible)) { ret = true; } cbFilterByDiagnosis.Visible = isVisible; } if (ret) { return; } if (isVisible) { if (lblAvailableField != null) { lblAvailableField.Top = 28; } if (lblSelectedField != null) { lblSelectedField.Top = 28; } if (imlbcAvailableField != null) { imlbcAvailableField.Top = 47; imlbcAvailableField.Height = navSearchFields.Height - 85; // Height of Navigator bar is greater that 85. Validaion is not needed. } if (gcSelectedField != null) { gcSelectedField.Top = 47; gcSelectedField.Height = navSearchFields.Height - 85; // Height of Navigator bar is greater that 85. Validaion is not needed. } if (btnAdd != null) { btnAdd.Top = 116; } if (btnRemove != null) { btnRemove.Top = 148; } if (btnAddAll != null) { btnAddAll.Top = 180; } if (btnRemoveAll != null) { btnRemoveAll.Top = 212; } } else { if (lblAvailableField != null) { lblAvailableField.Top = 2; } if (lblSelectedField != null) { lblSelectedField.Top = 2; } if (imlbcAvailableField != null) { imlbcAvailableField.Top = 21; imlbcAvailableField.Height = navSearchFields.Height - 59; // Height of Navigator bar is greater that 59. Validaion is not needed. } if (gcSelectedField != null) { gcSelectedField.Top = 21; gcSelectedField.Height = navSearchFields.Height - 59; // Height of Navigator bar is greater that 59. Validaion is not needed. } if (btnAdd != null) { btnAdd.Top = 90; } if (btnRemove != null) { btnRemove.Top = 122; } if (btnAddAll != null) { btnAddAll.Top = 154; } if (btnRemoveAll != null) { btnRemoveAll.Top = 186; } } } private void UpdateFFType() { DataView dvObject = LookupCache.Get(LookupTables.SearchObject); if (dvObject != null) { dvObject.RowFilter = string.Format("idfsSearchObject = {0}", m_SearchObject); if ((dvObject.Count > 0) && (Utils.IsEmpty(dvObject[0]["idfsFormType"]) == false) && (dvObject[0]["idfsFormType"] is long) && ((long)dvObject[0]["idfsFormType"] != -1L)) { //if ((m_IsFFObject == false) && (lbcAvailableField.DataSource != null)) if ((m_IsFFObject == false) && (imlbcAvailableField.DataSource != null)) { BindAvailableFieldList(); } m_IsFFObject = true; m_FormType = (long)dvObject[0]["idfsFormType"]; UpdateVisibilityOfDiagnosisByFormType(m_FormType); return; } } //if (m_IsFFObject && lbcAvailableField.DataSource != null) if (m_IsFFObject && imlbcAvailableField.DataSource != null) { BindAvailableFieldList(); } m_IsFFObject = false; m_FormType = -1L; UpdateVisibilityOfDiagnosisByFormType(m_FormType); } private void UpdateObjectHACode() { DataView dvObject = LookupCache.Get(LookupTables.SearchObject); if (dvObject != null) { dvObject.RowFilter = string.Format("idfsSearchObject = {0}", m_SearchObject); if ((dvObject.Count > 0) && (Utils.IsEmpty(dvObject[0]["intHACode"]) == false)) { m_ObjectHACode = (HACode)dvObject[0]["intHACode"]; if (m_FilterControlHelper != null) { m_FilterControlHelper.ObjectHACode = m_ObjectHACode; } return; } } m_ObjectHACode = HACode.None; if (m_FilterControlHelper != null) { m_FilterControlHelper.ObjectHACode = m_ObjectHACode; } } private void UpdateQuerySearchObjectID() { if (IsDesignMode()) { return; } grpSearchFields.Caption = GetFieldGroupCaption; grcQueryObjectFiltration.Text = GetFilterGroupCaption; UpdateFFType(); UpdateObjectHACode(); if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) && (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0)) { if (Utils.Str(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"]) != Utils.Str(m_SearchObject)) { if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)) && (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count > 0)) { int ind; for (ind = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count - 1; ind >= 0; ind--) { if (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind].RowState != DataRowState.Deleted) { UpdateConditionList( baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind]["idfQuerySearchField"]); baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind].Delete(); m_FilterControlHelper.Refresh(); } } } UpdateFieldList(); } if (Utils.IsEmpty(m_SearchObject)) { baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] = DBNull.Value; } else { baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfsSearchObject"] = m_SearchObject; } } //if (lbcAvailableField.DataSource != null) if (imlbcAvailableField.DataSource != null) { //DataView dv = (DataView)lbcAvailableField.DataSource; var dv = (DataView)imlbcAvailableField.DataSource; dv.RowFilter = string.Format("idfsSearchObject = {0} and blnAvailable = 1 ", m_SearchObject); } } private void UpdateQuerySearchObjectOrder() { grpSearchFields.Caption = GetFieldGroupCaption; grcQueryObjectFiltration.Text = GetFilterGroupCaption; if ((baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject)) && (baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows.Count > 0)) { baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["intOrder"] = m_Order; } } private string GetConditionText(long aQueryConditionGroupID, bool addOperation) { if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false)) { return ""; } DataRow rGroup = baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Find(aQueryConditionGroupID); if ((rGroup == null) || (rGroup.RowState == DataRowState.Deleted)) { return ""; } string strOr = ""; string strNot = ""; if (addOperation) { if (Utils.IsEmpty(rGroup["blnJoinByOr"]) == false) { if ((bool)rGroup["blnJoinByOr"]) { strOr = " " + EidssMessages.Get("msgOR", "OR"); } else { strOr = " " + EidssMessages.Get("msgAND", "AND"); } } if (!Utils.IsEmpty(rGroup["blnUseNot"]) && ((bool)rGroup["blnUseNot"])) { strNot = " " + EidssMessages.Get("msgNOT", "NOT"); } } string cond = strOr + strNot; if (cond.Length > 0) { cond = cond + " "; } cond = cond + "{0}"; if (Utils.IsEmpty(rGroup["idfQuerySearchFieldCondition"]) == false) { return string.Format(cond, rGroup["SearchFieldConditionText"]); } cond = string.Format(cond, "({0})"); DataRow[] dr = baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Select(string.Format("idfParentQueryConditionGroup = {0} ", aQueryConditionGroupID), "intOrder", DataViewRowState.CurrentRows); foreach (DataRow r in dr) { cond = string.Format(cond, GetConditionText((long)r["idfQueryConditionGroup"], true) + "{0}"); } return string.Format(cond, ""); } private void UpdateConditionText() { if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false)) { return; } foreach (DataRow r in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows) { if (r.RowState != DataRowState.Deleted) { r["SearchFieldConditionText"] = GetConditionText((long)r["idfQueryConditionGroup"], false); } } } #endregion #region Handlers private void btnAdd_Click(object sender, EventArgs e) { //if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { //DataView dvAvailable = (DataView)lbcAvailableField.DataSource; var dvAvailable = (DataView)imlbcAvailableField.DataSource; //if ((lbcAvailableField.SelectedIndex >= 0) && // (lbcAvailableField.SelectedIndex < dvAvailable.Count)) if ((imlbcAvailableField.SelectedIndex >= 0) && (imlbcAvailableField.SelectedIndex < dvAvailable.Count)) { //DataRow rAvailable = dvAvailable[lbcAvailableField.SelectedIndex].Row; DataRow rAvailable = dvAvailable[imlbcAvailableField.SelectedIndex].Row; rAvailable.BeginEdit(); rAvailable["blnAvailable"] = false; rAvailable.EndEdit(); long querySearchFieldID = -1L; DataRow[] r = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Select( string.Format("idfQuerySearchField <= {0}", querySearchFieldID), "idfQuerySearchField"); if (r.Length > 0) { if (r[0].RowState != DataRowState.Deleted) { querySearchFieldID = (long)(r[0]["idfQuerySearchField"]) - 1; } else { querySearchFieldID = (long)(r[0]["idfQuerySearchField", DataRowVersion.Original]) - 1; } } DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].NewRow(); rSelected["idfQuerySearchField"] = querySearchFieldID; rSelected["idfQuerySearchObject"] = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"]; rSelected["idfsSearchField"] = rAvailable["idfsSearchField"]; if (m_IsFFObject) { rSelected["FieldCaption"] = rAvailable["ParameterName"]; rSelected["blnShow"] = 1; rSelected["idfsParameter"] = rAvailable["idfsParameter"]; rSelected["FieldAlias"] = rAvailable["FieldAlias"]; rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"]; } else { rSelected["FieldCaption"] = rAvailable["FieldCaption"]; rSelected["blnShow"] = 1; rSelected["idfsParameter"] = DBNull.Value; rSelected["FieldAlias"] = rAvailable["strSearchFieldAlias"]; rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"]; } baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Add(rSelected); m_FilterControlHelper.Refresh(); } } } private void imlbcAvailableField_MouseDoubleClick(object sender, MouseEventArgs e) { if ((!ReadOnly) && (e.Button == MouseButtons.Left) && //(lbcAvailableField.SelectedIndex >= 0) && //(lbcAvailableField.GetItemRectangle(lbcAvailableField.SelectedIndex) != null) && //(lbcAvailableField.GetItemRectangle(lbcAvailableField.SelectedIndex).Contains(e.Location) == true)) (imlbcAvailableField.SelectedIndex >= 0) && (imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex) != null) && imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Contains(e.Location)) { btnAdd_Click(sender, new EventArgs()); } } private void imlbcAvailableField_MouseMove(object sender, MouseEventArgs e) { ImageListBoxControl listBoxControl = sender as ImageListBoxControl; if (listBoxControl != null) { int index = listBoxControl.IndexFromPoint(new System.Drawing.Point(e.X, e.Y)); string item = ""; var point = new System.Drawing.Point(e.X, e.Y); if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { var dvAvailable = (DataView)imlbcAvailableField.DataSource; DataRowView r = null; if (index != -1) { r = listBoxControl.GetItem(index) as DataRowView; } else if ((imlbcAvailableField.SelectedIndex >= 0) && (imlbcAvailableField.SelectedIndex < dvAvailable.Count)) { r = dvAvailable[imlbcAvailableField.SelectedIndex]; point = new System.Drawing.Point( imlbcAvailableField.Right, imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Top); } if (r != null) { if (m_IsFFObject) { item = r["ParameterName"] as string; } else { item = r["FieldCaption"] as string; } } } if (Utils.IsEmpty(item) == false) { ttcAvailableField.ShowHint(item, listBoxControl.PointToScreen(point)); } else { ttcAvailableField.HideHint(); } } } private void imlbcAvailableField_MouseLeave(object sender, EventArgs e) { ttcAvailableField.HideHint(); } private void imlbcAvailableField_SelectedIndexChanged(object sender, EventArgs e) { if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { var dvAvailable = (DataView)imlbcAvailableField.DataSource; string item = ""; if ((imlbcAvailableField.SelectedIndex >= 0) && (imlbcAvailableField.SelectedIndex < dvAvailable.Count)) { DataRowView r = dvAvailable[imlbcAvailableField.SelectedIndex]; if (r != null) { if (m_IsFFObject) { item = r["ParameterName"] as string; } else { item = r["FieldCaption"] as string; } } } if (Utils.IsEmpty(item) == false) { ttcAvailableField.ShowHint(item, imlbcAvailableField.PointToScreen(new System.Drawing.Point( imlbcAvailableField.Right, imlbcAvailableField.GetItemRectangle(imlbcAvailableField.SelectedIndex).Top))); } else { ttcAvailableField.HideHint(); } } } private void btnRemove_Click(object sender, EventArgs e) { //if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { var dvSelected = (DataView) gcSelectedField.DataSource; if ((gvSelectedField.FocusedRowHandle >= 0) && (gvSelectedField.FocusedRowHandle < dvSelected.Count)) { DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Find( gvSelectedField.GetFocusedRowCellValue("idfQuerySearchField")); if ((rSelected != null) && (rSelected.RowState != DataRowState.Deleted)) { //DataView dvAvailable = (DataView)lbcAvailableField.DataSource; var dvAvailable = (DataView) imlbcAvailableField.DataSource; DataRow rAvailable; if (m_IsFFObject) { string fieldKey = Utils.Str(rSelected["FieldAlias"]); rAvailable = dvAvailable.Table.Rows.Find(fieldKey); } else { rAvailable = dvAvailable.Table.Rows.Find(rSelected["idfsSearchField"]); } if (rAvailable != null) { rAvailable.BeginEdit(); rAvailable["blnAvailable"] = true; rAvailable.EndEdit(); } UpdateConditionList(rSelected["idfQuerySearchField"]); rSelected.Delete(); m_FilterControlHelper.Refresh(); } } } } private void gvSelectedField_RowCellClick(object sender, RowCellClickEventArgs e) { if ((!ReadOnly) && (e.Button == MouseButtons.Left) && (e.Clicks == 2) && (e.RowHandle >= 0) && (e.Column.FieldName == "FieldCaption")) { btnRemove_Click(sender, new EventArgs()); } } private void btnAddAll_Click(object sender, EventArgs e) { //if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { //DataView dvAvailable = (DataView)lbcAvailableField.DataSource; var dvAvailable = (DataView)imlbcAvailableField.DataSource; DataRow rAvailable; long querySearchFieldID = -1L; if (dvAvailable.Count > 0) { int ind; DataRow[] r = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Select( string.Format("idfQuerySearchField <= {0}", querySearchFieldID), "idfQuerySearchField"); if (r.Length > 0) { if (r[0].RowState != DataRowState.Deleted) { querySearchFieldID = (long)(r[0]["idfQuerySearchField"]) - 1; } else { querySearchFieldID = (long)(r[0]["idfQuerySearchField", DataRowVersion.Original]) - 1; } } for (ind = dvAvailable.Count - 1; ind >= 0; ind--) { rAvailable = dvAvailable[ind].Row; rAvailable.BeginEdit(); rAvailable["blnAvailable"] = false; rAvailable.EndEdit(); DataRow rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].NewRow(); rSelected["idfQuerySearchField"] = querySearchFieldID; rSelected["idfQuerySearchObject"] = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"]; rSelected["idfsSearchField"] = rAvailable["idfsSearchField"]; if (m_IsFFObject) { rSelected["FieldCaption"] = rAvailable["ParameterName"]; rSelected["blnShow"] = 1; rSelected["idfsParameter"] = rAvailable["idfsParameter"]; rSelected["FieldAlias"] = rAvailable["FieldAlias"]; rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"]; } else { rSelected["FieldCaption"] = rAvailable["FieldCaption"]; rSelected["blnShow"] = 1; rSelected["idfsParameter"] = DBNull.Value; rSelected["FieldAlias"] = rAvailable["strSearchFieldAlias"]; rSelected["TypeImageIndex"] = rAvailable["TypeImageIndex"]; } baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Add(rSelected); querySearchFieldID = querySearchFieldID - 1; } m_FilterControlHelper.Refresh(); } } } private void btnRemoveAll_Click(object sender, EventArgs e) { //if ((lbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && if ((imlbcAvailableField.DataSource != null) && (gcSelectedField.DataSource != null) && (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField))) { int ind; DataRow rSelected; for (ind = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count - 1; ind >= 0; ind--) { rSelected = baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows[ind]; if (rSelected.RowState != DataRowState.Deleted) { //DataView dvAvailable = (DataView)lbcAvailableField.DataSource; DataView dvAvailable = (DataView)imlbcAvailableField.DataSource; DataRow rAvailable = null; if (m_IsFFObject) { string fieldKey = Utils.Str(rSelected["FieldAlias"]); rAvailable = dvAvailable.Table.Rows.Find(fieldKey); } else { rAvailable = dvAvailable.Table.Rows.Find(rSelected["idfsSearchField"]); } if (rAvailable != null) { rAvailable.BeginEdit(); rAvailable["blnAvailable"] = true; rAvailable.EndEdit(); } UpdateConditionList(rSelected["idfQuerySearchField"]); rSelected.Delete(); } } m_FilterControlHelper.Refresh(); } } private void cbFilterByDiagnosis_EditValueChanged(object sender, EventArgs e) { if ((m_FormType != 10034010) && //Human Clinical Signs (m_FormType != 10034011)) //Human Epi Investigations { return; } if (imlbcAvailableField.DataSource == null) { return; } string filterByDiagnosis = " and DiagnosisString like '{0}'"; if (Utils.IsEmpty(cbFilterByDiagnosis.EditValue)) { filterByDiagnosis = string.Format(filterByDiagnosis, "%"); } else { filterByDiagnosis = string.Format(filterByDiagnosis, string.Format("%{0};%", Utils.Str(cbFilterByDiagnosis.EditValue))); } DataView dv = (DataView)imlbcAvailableField.DataSource; dv.RowFilter = string.Format("idfsSearchObject = '{0}' and blnAvailable = 1 {1}", m_SearchObject, filterByDiagnosis); } #endregion #region Special Methods private void DisplayFilter(object sender, FilterChangedEventArgs e) { txtFilterText.Lines = m_FilterControlHelper.FilterLines; } private DataSet m_DS; public void SaveQuerySearchObjectInfo() { if (baseDataSet == null) { m_DS = null; return; } m_DS = baseDataSet.Copy(); if (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false) { return; } } private static long GetNewNegativeID(long[] oldList, long idEx) { for (int i = 0; i < oldList.Length; i++) { if (oldList[i] == idEx) { return -(i + 1); } } return 0; } public void RestoreQuerySearchObjectInfo(long qsoID) { if (m_DS == null) { return; } object id = qsoID; LoadData(ref id); foreach (DataTable dt in baseDataSet.Tables) { dt.Rows.Clear(); } baseDataSet.Merge(m_DS); baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchObject].Rows[0]["idfQuerySearchObject"] = QuerySearchObjectDbService.ID; long fieldID = -1L; var fieldList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count]; foreach (DataRow rField in baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows) { if (rField.RowState != DataRowState.Deleted) { fieldList[-fieldID - 1] = (long) rField["idfnQuerySearchField"]; rField["idfQuerySearchField"] = fieldID; rField["idfQuerySearchObject"] = QuerySearchObjectDbService.ID; fieldID = fieldID - 1; } } long groupID = -1L; var groupList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Count]; foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows) { if (rGroup.RowState != DataRowState.Deleted) { rGroup["idfQueryConditionGroup"] = groupID; rGroup["idfQuerySearchObject"] = QuerySearchObjectDbService.ID; groupID = groupID - 1; } } foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows) { if (rGroup.RowState != DataRowState.Deleted) { if (Utils.IsEmpty(rGroup["idfParentQueryConditionGroup"]) == false) { long groupIDNew = GetNewNegativeID(groupList, (long)rGroup["idfParentQueryConditionGroup"]); rGroup["idfParentQueryConditionGroup"] = groupIDNew; } } } DefineBinding(); AfterLoad(); m_DS = null; } public void Copy(long qsoID, long queryID) { QuerySearchObjectDbService.Copy(baseDataSet, qsoID, queryID); long fieldID = -1L; var fieldList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows.Count]; foreach (DataRow rField in baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField].Rows) { if (rField.RowState != DataRowState.Deleted) { fieldList[(int)(-fieldID - 1)] = (long)rField["idfQuerySearchField"]; rField["idfQuerySearchField"] = fieldID; rField["idfQuerySearchObject"] = QuerySearchObjectDbService.ID; fieldID = fieldID - 1; } } long groupID = 0; var groupList = new long[baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows.Count]; long lastGroupID = 0; foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows) { if (rGroup.RowState != DataRowState.Deleted) { var groupIDEx = (long)rGroup["idfQueryConditionGroup"]; if (groupIDEx != lastGroupID) { groupID = groupID - 1; lastGroupID = groupIDEx; groupList[(int)(-groupID - 1)] = groupIDEx; } rGroup["idfQueryConditionGroup"] = groupID; if (Utils.IsEmpty(rGroup["idfQuerySearchField"]) == false) { rGroup["idfQuerySearchField"] = GetNewNegativeID(fieldList, (long)rGroup["idfQuerySearchField"]); } rGroup["idfQuerySearchObject"] = QuerySearchObjectDbService.ID; } } foreach (DataRow rGroup in baseDataSet.Tables[QuerySearchObject_DB.tasQueryConditionGroup].Rows) { if (rGroup.RowState != DataRowState.Deleted) { if (Utils.IsEmpty(rGroup["idfParentQueryConditionGroup"]) == false) { long groupIDNew = GetNewNegativeID(groupList, (long)rGroup["idfParentQueryConditionGroup"]); rGroup["idfParentQueryConditionGroup"] = groupIDNew; } } } BindFilterTree(); } private void splitContainer_SplitGroupPanelCollapsed(object sender, SplitGroupPanelCollapsedEventArgs e) { UserConfigWriter.Instance.SetItem("CollapseFilterPanel", e.Collapsed.ToString()); UserConfigWriter.Instance.Save(); Config.ReloadSettings(); } #endregion #region Validate Methods public bool ValidateQSOInfo() { if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchObject) == false)) return true; var dvField =new DataView(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "", DataViewRowState.CurrentRows); if (dvField.Count == 0) return false; return m_FilterControlHelper.Validate(); } public void ShowQSOInfoError() { var dvField =new DataView(baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "", DataViewRowState.CurrentRows); if (dvField.Count == 0) MessageForm.Show(EidssMessages.Get("msgNoSearchField", "No fields are selected. Remove this search object or select some available fields.")); } #endregion #region Post Methods public override bool HasChanges() { return m_FilterControlHelper.HasChanges || base.HasChanges(); } private void QuerySearchObjectInfo_OnAfterPost(object sender, EventArgs e) { if ((baseDataSet == null) || (baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQueryConditionGroup) == false)) return; baseDataSet.AcceptChanges(); m_FilterControlHelper.UpdateFieldInfo(); m_FilterControlHelper.HasChanges = false; } private void QuerySearchObjectInfo_OnBeforePost(object sender, EventArgs e) { m_FilterControlHelper.Flush(null, 0); } #endregion #region Get Functions internal DataView GetQuerySearchFieldView() { DataView dvField = null; if ((baseDataSet != null) && baseDataSet.Tables.Contains(QuerySearchObject_DB.tasQuerySearchField)) { dvField = new DataView( baseDataSet.Tables[QuerySearchObject_DB.tasQuerySearchField], "", "idfQuerySearchField", DataViewRowState.CurrentRows); if (dvField.Count == 0) { dvField = null; } } return dvField; } #endregion } }
EIDSS/EIDSS-Legacy
EIDSS v5/vb/EIDSS/EIDSS.RAM/QueryBuilder/QuerySearchObjectInfo.cs
C#
bsd-2-clause
53,738
#!/bin/sh -e ninja -C output/debug cm4all-beng-proxy export G_SLICE=always-malloc VALGRIND_FLAGS="--leak-check=yes --show-reachable=yes" VALGRIND_FLAGS="$VALGRIND_FLAGS --track-fds=yes --track-origins=yes" VALGRIND_FLAGS="$VALGRIND_FLAGS --suppressions=valgrind.suppressions" exec valgrind $VALGRIND_FLAGS ./output/debug/cm4all-beng-proxy -vvvvv "$@"
CM4all/beng-proxy
valgrind.sh
Shell
bsd-2-clause
355
// // Copyright (c) 2009, Markus Rickert // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "Metric.h" #include "Model.h" namespace rl { namespace plan { Metric::Metric(Model* model, const bool& transformed) : model(model), transformed(transformed) { } Metric::~Metric() { } Metric::Distance Metric::operator()(const Value& lhs, const Value& rhs) const { if (this->transformed) { return this->model->transformedDistance(*lhs.first, *rhs.first); } else { return this->model->distance(*lhs.first, *rhs.first); } } Metric::Distance Metric::operator()(const Distance& lhs, const Distance& rhs, const ::std::size_t& index) const { return this->model->transformedDistance(lhs, rhs, index); } Metric::Value::Value() : first(), second() { } Metric::Value::Value(const ::rl::math::Vector* first, void* second) : first(first), second(second) { } const ::rl::math::Real* Metric::Value::begin() const { return this->first->data(); } const ::rl::math::Real* Metric::Value::end() const { return this->first->data() + this->first->size(); } ::std::size_t Metric::Value::size() const { return this->first->size(); } } }
roboticslibrary/rl
src/rl/plan/Metric.cpp
C++
bsd-2-clause
2,538
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "BlueprintFieldNodeSpawner.h" #include "BlueprintDelegateNodeSpawner.generated.h" // Forward declarations class UK2Node_BaseMCDelegate; /** * Takes care of spawning various nodes associated with delegates. Serves as the * "action" portion for certain FBlueprintActionMenuItems. Evolved from * FEdGraphSchemaAction_K2Delegate, FEdGraphSchemaAction_K2AssignDelegate, etc. */ UCLASS(Transient) class BLUEPRINTGRAPH_API UBlueprintDelegateNodeSpawner : public UBlueprintFieldNodeSpawner { GENERATED_UCLASS_BODY() public: /** * Creates a new UBlueprintDelegateNodeSpawner for the specified property. * Does not do any compatibility checking to ensure that the property is * accessible from blueprints (do that before calling this). * * @param NodeClass The node type that you want the spawner to spawn. * @param Property The property you want assigned to spawned nodes. * @param Outer Optional outer for the new spawner (if left null, the transient package will be used). * @return A newly allocated instance of this class. */ static UBlueprintDelegateNodeSpawner* Create(TSubclassOf<UK2Node_BaseMCDelegate> NodeClass, UMulticastDelegateProperty const* const Property, UObject* Outer = nullptr); /** * Accessor to the delegate property that this spawner wraps (the delegate * that this will assign spawned nodes with). * * @return The delegate property that this was initialized with. */ UMulticastDelegateProperty const* GetDelegateProperty() const; };
PopCap/GameIdea
Engine/Source/Editor/BlueprintGraph/Classes/BlueprintDelegateNodeSpawner.h
C
bsd-2-clause
1,581
cask 'nosqlbooster-for-mongodb' do version '5.2.0' sha256 '13902f919e7a5485e168e86d0523dba44bee7f918c90631c8015358bbb2533d1' url "https://nosqlbooster.com/s3/download/releasesv#{version.major}/nosqlbooster4mongo-#{version}.dmg" appcast 'https://nosqlbooster.com/downloads' name 'NoSQLBooster for MongoDB' homepage 'https://nosqlbooster.com/' app 'NoSQLBooster for MongoDB.app' end
esebastian/homebrew-cask
Casks/nosqlbooster-for-mongodb.rb
Ruby
bsd-2-clause
397
--- Title: "Experimentation drives innovation " Date: 2019-10-30 16:05:08 -0700 --- # Experiment ### Two group experiment Typical control and treatment T test U test Proportion test Chi-Square test, exact test [All above look for p-value, p>.05 does not mean H naught is true, merely stats absence of evidence to reject it. Absence of evidence is not the evidence of absence]. Simulation, BF (Bayesian Factor) ### Factorial 2+ factors such as dosage and age group ANOVA Hierarchical Bayesian regression ### Crossover , sequential ? Cochran Armitage trend test Bandit (Thompson sampling, Bayesian UCB) ![](&&&SFLOCALFILEPATH&&&IMG_0328.PNG)
MikeXL/www
_posts/2019-10-30-experimentation-drives-innovation.md
Markdown
bsd-2-clause
656
class Php < Formula desc "General-purpose scripting language" homepage "https://secure.php.net/" url "https://php.net/get/php-7.2.8.tar.xz/from/this/mirror" sha256 "53ba0708be8a7db44256e3ae9fcecc91b811e5b5119e6080c951ffe7910ffb0f" bottle do sha256 "a1672a1e262cc8ba9091482ac16d8d23f75cdcbf50195aeda160a8d5e55da0b2" => :high_sierra sha256 "64d538f3732b3671267dcdb2b2b785564b2301b0a3eb1c414d58edb603e5eef5" => :sierra sha256 "693da1396df17c9b0628d8856985340249765f38b25ae95d227a751e4e45aec2" => :el_capitan end depends_on "httpd" => [:build, :test] depends_on "pkg-config" => :build depends_on "apr" depends_on "apr-util" depends_on "argon2" depends_on "aspell" depends_on "autoconf" depends_on "curl" if MacOS.version < :lion depends_on "freetds" depends_on "freetype" depends_on "gettext" depends_on "glib" depends_on "gmp" depends_on "icu4c" depends_on "jpeg" depends_on "libpng" depends_on "libpq" depends_on "libsodium" depends_on "libzip" depends_on "openssl" depends_on "pcre" depends_on "unixodbc" depends_on "webp" needs :cxx11 def install # Ensure that libxml2 will be detected correctly in older MacOS if MacOS.version == :el_capitan || MacOS.version == :sierra ENV["SDKROOT"] = MacOS.sdk_path end inreplace "configure" do |s| s.gsub! "APACHE_THREADED_MPM=`$APXS_HTTPD -V | grep 'threaded:.*yes'`", "APACHE_THREADED_MPM=" s.gsub! "APXS_LIBEXECDIR='$(INSTALL_ROOT)'`$APXS -q LIBEXECDIR`", "APXS_LIBEXECDIR='$(INSTALL_ROOT)#{lib}/httpd/modules'" s.gsub! "-z `$APXS -q SYSCONFDIR`", "-z ''" end # Update error message in apache sapi to better explain the requirements # of using Apache http in combination with php if the non-compatible MPM # has been selected. Homebrew has chosen not to support being able to # compile a thread safe version of PHP and therefore it is not # possible to recompile as suggested in the original message inreplace "sapi/apache2handler/sapi_apache2.c", "You need to recompile PHP.", "Homebrew PHP does not support a thread-safe php binary. "\ "To use the PHP apache sapi please change "\ "your httpd config to use the prefork MPM" inreplace "sapi/fpm/php-fpm.conf.in", ";daemonize = yes", "daemonize = no" # Required due to icu4c dependency ENV.cxx11 config_path = etc/"php/#{php_version}" # Prevent system pear config from inhibiting pear install (config_path/"pear.conf").delete if (config_path/"pear.conf").exist? # Prevent homebrew from harcoding path to sed shim in phpize script ENV["lt_cv_path_SED"] = "sed" args = %W[ --prefix=#{prefix} --localstatedir=#{var} --sysconfdir=#{config_path} --with-config-file-path=#{config_path} --with-config-file-scan-dir=#{config_path}/conf.d --with-pear=#{pkgshare}/pear --enable-bcmath --enable-calendar --enable-dba --enable-dtrace --enable-exif --enable-ftp --enable-fpm --enable-intl --enable-mbregex --enable-mbstring --enable-mysqlnd --enable-opcache-file --enable-pcntl --enable-phpdbg --enable-phpdbg-webhelper --enable-shmop --enable-soap --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --enable-wddx --enable-zip --with-apxs2=#{Formula["httpd"].opt_bin}/apxs --with-bz2 --with-fpm-user=_www --with-fpm-group=_www --with-freetype-dir=#{Formula["freetype"].opt_prefix} --with-gd --with-gettext=#{Formula["gettext"].opt_prefix} --with-gmp=#{Formula["gmp"].opt_prefix} --with-icu-dir=#{Formula["icu4c"].opt_prefix} --with-jpeg-dir=#{Formula["jpeg"].opt_prefix} --with-kerberos --with-layout=GNU --with-ldap --with-ldap-sasl --with-libedit --with-libzip --with-mhash --with-mysql-sock=/tmp/mysql.sock --with-mysqli=mysqlnd --with-ndbm --with-openssl=#{Formula["openssl"].opt_prefix} --with-password-argon2=#{Formula["argon2"].opt_prefix} --with-pdo-dblib=#{Formula["freetds"].opt_prefix} --with-pdo-mysql=mysqlnd --with-pdo-odbc=unixODBC,#{Formula["unixodbc"].opt_prefix} --with-pdo-pgsql=#{Formula["libpq"].opt_prefix} --with-pgsql=#{Formula["libpq"].opt_prefix} --with-pic --with-png-dir=#{Formula["libpng"].opt_prefix} --with-pspell=#{Formula["aspell"].opt_prefix} --with-sodium=#{Formula["libsodium"].opt_prefix} --with-unixODBC=#{Formula["unixodbc"].opt_prefix} --with-webp-dir=#{Formula["webp"].opt_prefix} --with-xmlrpc --with-xsl --with-zlib ] if MacOS.version < :lion args << "--with-curl=#{Formula["curl"].opt_prefix}" else args << "--with-curl" end system "./configure", *args system "make" system "make", "install" # Allow pecl to install outside of Cellar extension_dir = Utils.popen_read("#{bin}/php-config --extension-dir").chomp orig_ext_dir = File.basename(extension_dir) inreplace bin/"php-config", lib/"php", prefix/"pecl" inreplace "php.ini-development", "; extension_dir = \"./\"", "extension_dir = \"#{HOMEBREW_PREFIX}/lib/php/pecl/#{orig_ext_dir}\"" config_files = { "php.ini-development" => "php.ini", "sapi/fpm/php-fpm.conf" => "php-fpm.conf", "sapi/fpm/www.conf" => "php-fpm.d/www.conf", } config_files.each_value do |dst| dst_default = config_path/"#{dst}.default" rm dst_default if dst_default.exist? end config_path.install config_files unless (var/"log/php-fpm.log").exist? (var/"log").mkpath touch var/"log/php-fpm.log" end end def post_install pear_prefix = pkgshare/"pear" pear_files = %W[ #{pear_prefix}/.depdblock #{pear_prefix}/.filemap #{pear_prefix}/.depdb #{pear_prefix}/.lock ] %W[ #{pear_prefix}/.channels #{pear_prefix}/.channels/.alias ].each do |f| chmod 0755, f pear_files.concat(Dir["#{f}/*"]) end chmod 0644, pear_files # Custom location for extensions installed via pecl pecl_path = HOMEBREW_PREFIX/"lib/php/pecl" ln_s pecl_path, prefix/"pecl" unless (prefix/"pecl").exist? extension_dir = Utils.popen_read("#{bin}/php-config --extension-dir").chomp php_basename = File.basename(extension_dir) php_ext_dir = opt_prefix/"lib/php"/php_basename # fix pear config to install outside cellar pear_path = HOMEBREW_PREFIX/"share/pear" cp_r pkgshare/"pear/.", pear_path { "php_ini" => etc/"php/#{php_version}/php.ini", "php_dir" => pear_path, "doc_dir" => pear_path/"doc", "ext_dir" => pecl_path/php_basename, "bin_dir" => opt_bin, "data_dir" => pear_path/"data", "cfg_dir" => pear_path/"cfg", "www_dir" => pear_path/"htdocs", "man_dir" => HOMEBREW_PREFIX/"share/man", "test_dir" => pear_path/"test", "php_bin" => opt_bin/"php", }.each do |key, value| value.mkpath if key =~ /(?<!bin|man)_dir$/ system bin/"pear", "config-set", key, value, "system" end system bin/"pear", "update-channels" %w[ opcache ].each do |e| ext_config_path = etc/"php/#{php_version}/conf.d/ext-#{e}.ini" extension_type = (e == "opcache") ? "zend_extension" : "extension" if ext_config_path.exist? inreplace ext_config_path, /#{extension_type}=.*$/, "#{extension_type}=#{php_ext_dir}/#{e}.so" else ext_config_path.write <<~EOS [#{e}] #{extension_type}="#{php_ext_dir}/#{e}.so" EOS end end end def caveats <<~EOS To enable PHP in Apache add the following to httpd.conf and restart Apache: LoadModule php7_module #{opt_lib}/httpd/modules/libphp7.so <FilesMatch \\.php$> SetHandler application/x-httpd-php </FilesMatch> Finally, check DirectoryIndex includes index.php DirectoryIndex index.php index.html The php.ini and php-fpm.ini file can be found in: #{etc}/php/#{php_version}/ EOS end def php_version version.to_s.split(".")[0..1].join(".") end plist_options :manual => "php-fpm" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_sbin}/php-fpm</string> <string>--nodaemonize</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/php-fpm.log</string> </dict> </plist> EOS end test do assert_match /^Zend OPcache$/, shell_output("#{bin}/php -i"), "Zend OPCache extension not loaded" system "#{sbin}/php-fpm", "-t" system "#{bin}/phpdbg", "-V" system "#{bin}/php-cgi", "-m" # Prevent SNMP extension to be added assert_no_match /^snmp$/, shell_output("#{bin}/php -m"), "SNMP extension doesn't work reliably with Homebrew on High Sierra" begin require "socket" server = TCPServer.new(0) port = server.addr[1] server_fpm = TCPServer.new(0) port_fpm = server_fpm.addr[1] server.close server_fpm.close expected_output = /^Hello world!$/ (testpath/"index.php").write <<~EOS <?php echo 'Hello world!'; EOS (testpath/"missingdotphp").write <<~EOS <?php echo 'Hello world!'; EOS main_config = <<~EOS Listen #{port} ServerName localhost:#{port} DocumentRoot "#{testpath}" ErrorLog "#{testpath}/httpd-error.log" ServerRoot "#{Formula["httpd"].opt_prefix}" PidFile "#{testpath}/httpd.pid" LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so LoadModule unixd_module lib/httpd/modules/mod_unixd.so LoadModule dir_module lib/httpd/modules/mod_dir.so DirectoryIndex index.php EOS (testpath/"httpd.conf").write <<~EOS #{main_config} LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so LoadModule php7_module #{lib}/httpd/modules/libphp7.so <FilesMatch \\.(php|phar)$> SetHandler application/x-httpd-php </FilesMatch> EOS (testpath/"fpm.conf").write <<~EOS [global] daemonize=no [www] listen = 127.0.0.1:#{port_fpm} pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 EOS (testpath/"httpd-fpm.conf").write <<~EOS #{main_config} LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so LoadModule proxy_module lib/httpd/modules/mod_proxy.so LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so <FilesMatch \\.(php|phar)$> SetHandler "proxy:fcgi://127.0.0.1:#{port_fpm}" </FilesMatch> EOS pid = fork do exec Formula["httpd"].opt_bin/"httpd", "-X", "-f", "#{testpath}/httpd.conf" end sleep 3 assert_match expected_output, shell_output("curl -s 127.0.0.1:#{port}") Process.kill("TERM", pid) Process.wait(pid) fpm_pid = fork do exec sbin/"php-fpm", "-y", "fpm.conf" end pid = fork do exec Formula["httpd"].opt_bin/"httpd", "-X", "-f", "#{testpath}/httpd-fpm.conf" end sleep 3 assert_match expected_output, shell_output("curl -s 127.0.0.1:#{port}") ensure if pid Process.kill("TERM", pid) Process.wait(pid) end if fpm_pid Process.kill("TERM", fpm_pid) Process.wait(fpm_pid) end end end end
ilovezfs/homebrew-core
Formula/php.rb
Ruby
bsd-2-clause
12,262
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon Jul 29 11:38:01 CEST 2019 // Last Modified: Wed Jul 31 21:20:06 CEST 2019 // Filename: humdiff.cpp // URL: https://github.com/craigsapp/humlib/blob/master/cli/humdiff.cpp // Syntax: C++11 // vim: ts=3 noexpandtab nowrap // // Description: Compare contents of two similar scores. // #include "humlib.h" #include <iostream> using namespace hum; using namespace std; // Function declarations: void compareFiles (HumdrumFileSet& humset); ostream& compareTimePoints (ostream& out, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset); void extractTimePoints (vector<TimePoint>& points, HumdrumFile& infile); ostream& printTimePoints (ostream& out, vector<TimePoint>& timepoints); void compareLines (HumNum minval, vector<int>& indexes, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset); void getNoteList (vector<NotePoint>& notelist, HumdrumFile& infile, int line, int measure, int sourceindex, int tpindex); int findNoteInList (NotePoint& np, vector<NotePoint>& nps); void printNotePoints (vector<NotePoint>& notelist); void markNote (NotePoint& np); /////////////////////////////////////////////////////////////////////////// Options options; int Marked = 0; int main(int argc, char** argv) { options.define("r|reference=i:0", "sequence number of reference score"); options.define("report=b", "display report of differences"); options.define("time-points|times=b", "display timepoint lists for each file"); options.define("note-points|notes=b", "display notepoint lists for each file"); options.define("c|color=s:red", "color for markers"); options.process(argc, argv); HumdrumFileSet humset(options); int reference = options.getInteger("reference"); if (reference > 1) { if (reference > humset.getCount()) { cerr << "Error: work number is too large: " << reference << endl; cerr << "Maximum is " << humset.getCount() << endl; return 1; } reference--; humset.swap(0, reference); } if (humset.getSize() == 0) { cerr << "Usage: " << options.getCommand() << " files" << endl; return 1; } else if (humset.getSize() < 2) { cerr << "Error: requires two or more files" << endl; cerr << "Usage: " << options.getCommand() << " files" << endl; return 1; } else { HumNum targetdur = humset[0].getScoreDuration(); for (int i=1; i<humset.getSize(); i++) { HumNum dur = humset[i].getScoreDuration(); if (dur != targetdur) { cerr << "Error: all files must have the same duration" << endl; return 1; } } compareFiles(humset); } if (!options.getBoolean("report")) { humset[0].createLinesFromTokens(); cout << humset[0]; if (Marked) { cout << "!!!RDF**kern: @ = marked note"; if (options.getBoolean("color")) { cout << "color=\"" << options.getString("color") << "\""; } cout << endl; } } return 0; } ////////////////////////////// // // compareFiles -- // void compareFiles(HumdrumFileSet& humset) { vector<vector<TimePoint>> timepoints(humset.getSize());; for (int i=0; i<humset.getSize(); i++) { extractTimePoints(timepoints.at(i), humset[i]); } if (options.getBoolean("time-points")) { for (int i=0; i<(int)timepoints.size(); i++) { printTimePoints(cout, timepoints[i]); } } compareTimePoints(cout, timepoints, humset); } ////////////////////////////// // // printTimePoints -- // ostream& printTimePoints(ostream& out, vector<TimePoint>& timepoints) { for (int i=0; i<(int)timepoints.size(); i++) { out << "TIMEPOINT " << i << ":" << endl; out << timepoints[i] << endl; } return out; } ////////////////////////////// // // compareTimePoints -- // ostream& compareTimePoints(ostream& out, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset) { vector<int> indexes(timepoints.size(), 0); HumNum minval; HumNum value; int found; vector<int> increment(timepoints.size(), 0); while ((1)) { if (indexes.at(0) >= timepoints.at(0).size()) { // at the end of the list of notes for the first file. // break from the comparison for now and figure out how // to report differences of added notes in the other file(s) // later. break; } timepoints.at(0).at(indexes.at(0)).index.resize(timepoints.size()); for (int i=1; i<timepoints.size(); i++) { timepoints.at(0).at(indexes.at(0)).index.at(i) = -1; } minval = timepoints.at(0).at(indexes.at(0)).timestamp; for (int i=1; i<(int)timepoints.size(); i++) { if (indexes.at(i) >= timepoints.at(i).size()) { continue; } value = timepoints.at(i).at(indexes.at(i)).timestamp; if (value < minval) { minval = value; } } found = 0; fill(increment.begin(), increment.end(), 0); for (int i=0; i<(int)timepoints.size(); i++) { if (indexes.at(i) >= timepoints.at(i).size()) { // index is too large for file, so skip checking it. continue; } found = 1; value = timepoints.at(i).at(indexes.at(i)).timestamp; if (value == minval) { timepoints.at(0).at(indexes.at(0)).index.at(i) = timepoints.at(i).at(indexes.at(i)).index.at(0); increment.at(i)++; } } if (!found) { break; } else { compareLines(minval, indexes, timepoints, humset); } for (int i=0; i<(int)increment.size(); i++) { indexes.at(i) += increment.at(i); } } return out; } ////////////////////////////// // // printNotePoints -- // void printNotePoints(vector<NotePoint>& notelist) { cout << "vvvvvvvvvvvvvvvvvvvvvvvvv" << endl; for (int i=0; i<(int)notelist.size(); i++) { cout << "NOTE " << i << endl; cout << notelist.at(i) << endl; } cout << "^^^^^^^^^^^^^^^^^^^^^^^^^" << endl; cout << endl; } ////////////////////////////// // // markNote -- mark the note (since it does not have a match in other edition(s). // void markNote(NotePoint& np) { Marked = 1; HTp token = np.token; if (!token) { return; } if (!token->isChord()) { string contents = *token; contents += "@"; token->setText(contents); return; } vector<string> tokens = token->getSubtokens(); tokens[np.subindex] += "@"; string output = tokens[0]; for (int i=1; i<(int)tokens.size(); i++) { output += " "; output += tokens[i]; } token->setText(output); } ////////////////////////////// // // compareLines -- // void compareLines(HumNum minval, vector<int>& indexes, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset) { bool reportQ = options.getBoolean("report"); // cerr << "COMPARING LINES ====================================" << endl; vector<vector<NotePoint>> notelist(indexes.size()); for (int i=0; i<(int)timepoints.size(); i++) { if (indexes.at(i) >= (int)timepoints.at(i).size()) { continue; } if (timepoints.at(i).at(indexes.at(i)).timestamp != minval) { // not at the same time continue; } getNoteList(notelist.at(i), humset[i], timepoints.at(i).at(indexes.at(i)).index[0], timepoints.at(i).at(indexes.at(i)).measure, i, indexes.at(i)); } for (int i=0; i<(int)notelist.at(0).size(); i++) { notelist.at(0).at(i).matched.resize(notelist.size()); fill(notelist.at(0).at(i).matched.begin(), notelist.at(0).at(i).matched.end(), -1); notelist.at(0).at(i).matched.at(0) = i; for (int j=1; j<(int)notelist.size(); j++) { int status = findNoteInList(notelist.at(0).at(i), notelist.at(j)); notelist.at(0).at(i).matched.at(j) = status; if ((status < 0) && !reportQ) { markNote(notelist.at(0).at(i)); } } } if (options.getBoolean("notes")) { for (int i=0; i<notelist.size(); i++) { cerr << "========== NOTES FOR I=" << i << endl; printNotePoints(notelist.at(i)); cerr << endl; } } if (!reportQ) { return; } // report for (int i=0; i<(int)notelist.at(0).size(); i++) { for (int j=1; j<(int)notelist.at(0).at(i).matched.size(); j++) { if (notelist.at(0).at(i).matched.at(j) < 0) { cout << "NOTE " << notelist.at(0).at(i).subtoken << " DOES NOT HAVE EXACT MATCH IN SOURCE " << j << endl; int humindex = notelist.at(0).at(i).token->getLineIndex(); cout << "\tREFERENCE MEASURE\t: " << notelist.at(0).at(i).measure << endl; cout << "\tREFERENCE LINE NO.\t: " << humindex+1 << endl; cout << "\tREFERENCE LINE TEXT\t: " << humset[0][humindex] << endl; cout << "\tTARGET " << j << " LINE NO. "; if (j < 10) { cout << " "; } cout << ":\t" << "X" << endl; cout << "\tTARGET " << j << " LINE TEXT"; if (j < 10) { cout << " "; } cout << ":\t" << "X" << endl; cout << endl; } } } } ////////////////////////////// // // findNoteInList -- // int findNoteInList(NotePoint& np, vector<NotePoint>& nps) { for (int i=0; i<(int)nps.size(); i++) { // cerr << "COMPARING " << np.token << " (" << np.b40 << ") TO " << nps.at(i).token << " (" << nps.at(i).b40 << ") " << endl; if (nps.at(i).processed) { continue; } if (nps.at(i).b40 != np.b40) { continue; } if (nps.at(i).duration != np.duration) { continue; } return i; } // cerr << "\tCannot find note " << np.token << " on line " << np.token->getLineIndex() << " in other work" << endl; return -1; } ////////////////////////////// // // getNoteList -- // void getNoteList(vector<NotePoint>& notelist, HumdrumFile& infile, int line, int measure, int sourceindex, int tpindex) { for (int i=0; i<infile[line].getFieldCount(); i++) { HTp token = infile.token(line, i); if (!token->isKern()) { continue; } if (token->isNull()) { continue; } if (token->isRest()) { continue; } int scount = token->getSubtokenCount(); int track = token->getTrack(); int layer = token->getSubtrack(); for (int j=0; j<scount; j++) { string subtok = token->getSubtoken(j); if (subtok.find("]") != string::npos) { continue; } if (subtok.find("_") != string::npos) { continue; } // found a note to store; notelist.resize(notelist.size() + 1); notelist.back().token = token; notelist.back().subtoken = subtok; notelist.back().subindex = j; notelist.back().measurequarter = token->getDurationFromBarline(); notelist.back().measure = notelist.back().track = track; notelist.back().layer = layer; notelist.back().sourceindex = sourceindex; notelist.back().tpindex = tpindex; notelist.back().duration = token->getTiedDuration(); notelist.back().b40 = Convert::kernToBase40(subtok); } } } ////////////////////////////// // // extractTimePoints -- Extract a list of the timestamps in a file. // void extractTimePoints(vector<TimePoint>& points, HumdrumFile& infile) { TimePoint tp; points.clear(); HumRegex hre; points.reserve(infile.getLineCount()); int measure = -1; for (int i=0; i<infile.getLineCount(); i++) { if (infile[i].isBarline()) { if (hre.search(infile.token(i, 0), "(\\d+)")) { measure = hre.getMatchInt(1); } } if (!infile[i].isData()) { continue; } if (infile[i].getDuration() == 0) { // ignore grace notes for now continue; } tp.clear(); tp.file.push_back(&infile); tp.index.push_back(i); tp.timestamp = infile[i].getDurationFromStart(); tp.measure = measure; points.push_back(tp); } }
humdrum-tools/minHumdrum
cli/humdiff-old.cpp
C++
bsd-2-clause
11,280
/* Copyright 2012 Joe Hermaszewski. 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. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #pragma once #include <memory> #include <string> #include <vector> #include <compiler/semantic_analysis/complete_type.hpp> #include <compiler/tokens/token.hpp> namespace JoeLang { enum class Type; namespace Compiler { typedef std::vector<unsigned> ArrayExtents; class CodeGenerator; class Expression; typedef std::unique_ptr<Expression> Expression_up; class Parameter; class Parser; class SemaAnalyzer; class Semantic; class SemanticSpecifier; using SemanticSpecifier_up = std::unique_ptr<SemanticSpecifier>; enum class SemanticType; class Variable; using Variable_sp = std::shared_ptr<Variable>; /** * \class ArraySpecifier * \ingroup Tokens * \brief Matches a ArraySpecifier * * ArraySpecifier = '[' Expression ']' */ class ArraySpecifier : public JoeLang::Compiler::Token { public: /** This asserts that expression is not null **/ ArraySpecifier ( Expression_up expression ); virtual ~ArraySpecifier (); void PerformSema( SemaAnalyzer& sema ); Expression_up GetExpression(); /** * Extracts the values from a list of array specifiers * \param specifiers * The array specifiers * \param sema * The semantic analyzer used to evaluate the expression */ static ArrayExtents GetArrayExtents( std::vector<std::unique_ptr<ArraySpecifier> >& specifiers, SemaAnalyzer& sema ); /** * Parses an array specifier * \param parser * The current Parser * \param token * The returned token on a successful parse * \return * true upon parsing successfully * false if the parse failed */ static bool Parse ( Parser& parser, std::unique_ptr<ArraySpecifier>& token ); static bool classof( const Token* t ); static bool classof( const ArraySpecifier* d ); private: Expression_up m_Expression; }; /** * \class FunctionSpecifier * \ingroup Tokens * \brief Matches a FunctionSpecifier * * FunctionSpecifier = '(' (Parameter(,Parameter)*)? ')' */ class FunctionSpecifier : public JoeLang::Compiler::Token { public: /** This asserts that no parameter is null **/ FunctionSpecifier ( std::vector<std::unique_ptr<Parameter>> parameters ); virtual ~FunctionSpecifier (); bool PerformSema( SemaAnalyzer& sema ); /** * Registers the parameters as variables with sema */ void DeclareParameters( SemaAnalyzer& sema ); std::vector<CompleteType> GetParameterTypes() const; std::vector<Variable_sp> GetParameters() const; /** * Parses a function specifier * \param parser * The current Parser * \param token * The returned token on a successful parse * \return * true upon parsing successfully * false if the parse failed */ static bool Parse ( Parser& parser, std::unique_ptr<FunctionSpecifier>& token ); static bool classof( const Token* t ); static bool classof( const FunctionSpecifier* d ); private: std::vector<std::unique_ptr<Parameter> > m_Parameters; }; /** * \class SemanticSpecifier * \ingroup Tokens * \brief Matches a semantic specifier * * SemanticSpecifier = ':' identifier ( '[' Expression ']' ) */ class SemanticSpecifier : public JoeLang::Compiler::Token { public: /** This constructor asserts on an empty string **/ SemanticSpecifier ( std::string string, Expression_up index_expression = nullptr ); virtual ~SemanticSpecifier (); bool HasIndex() const; /** This must only be called after PerformSema **/ Semantic GetSemantic() const; /** * Performs semantic analysis on the semantic * This will resolve the index expression if there is one */ void PerformSema( SemaAnalyzer& sema ); static bool Parse ( Parser& parser, SemanticSpecifier_up& token ); static bool classof( const Token* t ); static bool classof( const SemanticSpecifier* d ); private: std::string m_String; Expression_up m_IndexExpression; unsigned m_Index; SemanticType m_SemanticType; }; } // namespace Compiler } // namespace JoeLang
expipiplus1/joelang
src/compiler/tokens/declarator_specifier.hpp
C++
bsd-2-clause
5,805
# Copyright (c) 2015-2018 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. import numpy as np from .tod import TOD from .noise import Noise from ..op import Operator from .. import timing as timing class AnalyticNoise(Noise): """ Class representing an analytic noise model. This generates an analytic PSD for a set of detectors, given input values for the knee frequency, NET, exponent, sample rate, minimum frequency, etc. Args: detectors (list): List of detectors. rate (dict): Dictionary of sample rates in Hertz. fmin (dict): Dictionary of minimum frequencies for high pass fknee (dict): Dictionary of knee frequencies. alpha (dict): Dictionary of alpha exponents (positive, not negative!). NET (dict): Dictionary of detector NETs. """ def __init__(self, *, detectors, rate, fmin, fknee, alpha, NET): self._rate = rate self._fmin = fmin self._fknee = fknee self._alpha = alpha self._NET = NET for d in detectors: if self._alpha[d] < 0.0: raise RuntimeError( "alpha exponents should be positive in this formalism") freqs = {} psds = {} last_nyquist = None for d in detectors: if (self._fknee[d] > 0.0) and (self._fknee[d] < self._fmin[d]): raise RuntimeError("If knee frequency is non-zero, it must " "be greater than f_min") nyquist = self._rate[d] / 2.0 if nyquist != last_nyquist: tempfreq = [] # this starting point corresponds to a high-pass of # 30 years, so should be low enough for any interpolation! cur = 1.0e-9 # this value seems to provide a good density of points # in log space. while cur < nyquist: tempfreq.append(cur) cur *= 1.4 # put a final point at Nyquist tempfreq.append(nyquist) tempfreq = np.array(tempfreq, dtype=np.float64) last_nyquist = nyquist freqs[d] = tempfreq if self._fknee[d] > 0.0: ktemp = np.power(self._fknee[d], self._alpha[d]) mtemp = np.power(self._fmin[d], self._alpha[d]) temp = np.power(freqs[d], self._alpha[d]) psds[d] = (temp + ktemp) / (temp + mtemp) psds[d] *= (self._NET[d] * self._NET[d]) else: psds[d] = np.ones_like(freqs[d]) psds[d] *= (self._NET[d] * self._NET[d]) # call the parent class constructor to store the psds super().__init__(detectors=detectors, freqs=freqs, psds=psds) def rate(self, det): """(float): the sample rate in Hz. """ return self._rate[det] def fmin(self, det): """(float): the minimum frequency in Hz, used as a high pass. """ return self._fmin[det] def fknee(self, det): """(float): the knee frequency in Hz. """ return self._fknee[det] def alpha(self, det): """(float): the (positive!) slope exponent. """ return self._alpha[det] def NET(self, det): """(float): the NET. """ return self._NET[det]
tskisner/pytoast
src/python/tod/sim_noise.py
Python
bsd-2-clause
3,547
package org.jvnet.annox.reader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.jvnet.annox.model.XClass; import org.jvnet.annox.model.XConstructor; import org.jvnet.annox.model.XField; import org.jvnet.annox.model.XMethod; import org.jvnet.annox.model.XPackage; import org.jvnet.annox.reflect.AnnotatedElementException; public interface XReader { public XPackage getXPackage(Package thePackage) throws AnnotatedElementException; public XClass getXClass(Class<?> theClass) throws AnnotatedElementException; public XField getXField(Field theField) throws AnnotatedElementException; public XField getXField(Class<?> theClass, Field theField) throws AnnotatedElementException; public XConstructor getXConstructor(Constructor<?> theConstructor) throws AnnotatedElementException; public XConstructor getXConstructor(Class<?> theClass, Constructor<?> theConstructor) throws AnnotatedElementException; public XMethod getXMethod(Method theMethod) throws AnnotatedElementException; public XMethod getXMethod(Class<?> theClass, Method theMethod) throws AnnotatedElementException; }
highsource/annox
core/src/main/java/org/jvnet/annox/reader/XReader.java
Java
bsd-2-clause
1,176
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; namespace ConcurrencyHelpers.Interfaces { public delegate void ElapsedTimerEventHandler(object sender, ElapsedTimerEventArgs e); public interface ITimer: IDisposable { int Period { get; } void Start(int period = 0, int delay = 0); void Stop(); event ElapsedTimerEventHandler Elapsed; int TimesRun { get; } bool Running { get; } } }
kendarorg/ConcurrencyHelpers
ConcurrencyHelpers/src/ConcurrencyHelpers/Interfaces/ITimer.cs
C#
bsd-2-clause
1,897
/** @file kmeans.c ** @brief K-means - Declaration ** @author Andrea Vedaldi, David Novotny **/ /* Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. Copyright (C) 2013 Andrea Vedaldi and David Novotny. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ /** <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page kmeans K-means clustering @author Andrea Vedaldi @author David Novotny @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @ref kmeans.h implements a number of algorithm for **K-means quantization**: Lloyd @cite{lloyd82least}, an accelerated version by Elkan @cite{elkan03using}, and a large scale algorithm based on Approximate Nearest Neighbors (ANN). All algorithms support @c float or @c double data and can use the $l^1$ or the $l^2$ distance for clustering. Furthermore, all algorithms can take advantage of multiple CPU cores. Please see @subpage kmeans-fundamentals for a technical description of K-means and of the algorithms implemented here. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-starting Getting started <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The goal of K-means is to partition a dataset into $K$ &ldquo;compact&rdquo; clusters. The following example demonstrates using @ref kmeans.h in the C programming language to partition @c numData @c float vectors into compute @c numCenters clusters using Lloyd's algorithm: @code #include <vl/kmeans.h> double energy ; double * centers ; // Use float data and the L2 distance for clustering KMeans * kmeans = vl_kmeans_new (VLDistanceL2, VL_TYPE_FLOAT) ; // Use Lloyd algorithm vl_kmeans_set_algorithm (kmeans, VlKMeansLloyd) ; // Initialize the cluster centers by randomly sampling the data vl_kmeans_init_centers_with_rand_data (kmeans, data, dimension, numData, numCenters) ; // Run at most 100 iterations of cluster refinement using Lloyd algorithm vl_kmeans_set_max_num_iterations (kmeans, 100) ; vl_kmeans_refine_centers (kmeans, data, numData) ; // Obtain the energy of the solution energy = vl_kmeans_get_energy(kmeans) ; // Obtain the cluster centers centers = vl_kmeans_get_centers(kmeans) ; @endcode Once the centers have been obtained, new data points can be assigned to clusters by using the ::vl_kmeans_quantize function: @code vl_uint32 * assignments = vl_malloc(sizeof(vl_uint32) * numData) ; float * distances = vl_malloc(sizeof(float) * numData) ; vl_kmeans_quantize(kmeans, assignments, distances, data, numData) ; @endcode Alternatively, one can directly assign new pointers to the closest centers, without bothering with a ::VlKMeans object. There are several considerations that may impact the performance of KMeans. First, since K-means is usually based local optimization algorithm, the **initialization method** is important. The following initialization methods are supported: Method | Function | Description ---------------|-----------------------------------------|----------------------------------------------- Random samples | ::vl_kmeans_init_centers_with_rand_data | Random data points K-means++ | ::vl_kmeans_init_centers_plus_plus | Random selection biased towards diversity Custom | ::vl_kmeans_set_centers | Choose centers (useful to run quantization only) See @ref kmeans-init for further details. The initialization methods use a randomized selection of the data points; the random number generator init is controlled by ::vl_rand_init. The second important choice is the **optimization algorithm**. The following optimization algorithms are supported: Algorithm | Symbol | See | Description ------------|------------------|-------------------|----------------------------------------------- Lloyd | ::VlKMeansLloyd | @ref kmeans-lloyd | Alternate EM-style optimization Elkan | ::VlKMeansElkan | @ref kmeans-elkan | A speedup using triangular inequalities ANN | ::VlKMeansANN | @ref kmeans-ann | A speedup using approximated nearest neighbors See the relative sections for further details. These algorithm are iterative, and stop when either a **maximum number of iterations** (::vl_kmeans_set_max_num_iterations) is reached, or when the energy changes sufficiently slowly in one iteration (::vl_kmeans_set_min_energy_variation). All the three algorithms support multithreaded computations. The number of threads used is usually controlled globally by ::vl_set_num_threads. **/ /** <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @page kmeans-fundamentals K-means fundamentals @tableofcontents <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Given $n$ points $\bx_1,\dots,\bx_n \in \real^d$, the goal of K-means is find $K$ `centers` $\bc_1,\dots,\bc_m \in \real^d$ and `assignments` $q_1,\dots,q_n \in \{1,\dots,K\}$ of the points to the centers such that the sum of distances \[ E(\bc_1,\dots,\bc_k,q_1,\dots,q_n) = \sum_{i=1}^n \|\bx_i - \bc_{q_i} \|_p^p \] is minimized. $K$-means is obtained for the case $p=2$ ($l^2$ norm), because in this case the optimal centers are the means of the input vectors assigned to them. Here the generalization $p=1$ ($l^1$ norm) will also be considered. Up to normalization, the K-means objective $E$ is also the average reconstruction error if the original points are approximated with the cluster centers. Thus K-means is used not only to group the input points into cluster, but also to `quantize` their values. K-means is widely used in computer vision, for example in the construction of vocabularies of visual features (visual words). In these applications the number $n$ of points to cluster and/or the number $K$ of clusters is often large. Unfortunately, minimizing the objective $E$ is in general a difficult combinatorial problem, so locally optimal or approximated solutions are sought instead. The basic K-means algorithm alternate between re-estimating the centers and the assignments (@ref kmeans-lloyd). Combined with a good initialization strategy (@ref kmeans-init) and, potentially, by re-running the optimization from a number of randomized starting states, this algorithm may attain satisfactory solutions in practice. However, despite its simplicity, Lloyd's algorithm is often too slow. A good replacement is Elkan's algorithm (@ref kmeans-elkan), which uses the triangular inequality to cut down significantly the cost of Lloyd's algorithm. Since this algorithm is otherwise equivalent, it should often be preferred. For very large problems (millions of point to clusters and hundreds, thousands, or more clusters to find), even Elkan's algorithm is not sufficiently fast. In these cases, one can resort to a variant of Lloyd's algorithm that uses an approximated nearest neighbors routine (@ref kmeans-ann). <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-init Initialization methods <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> All the $K$-means algorithms considered here find locally optimal solutions; as such the way they are initialized is important. @ref kmeans.h supports the following initialization algorithms: @par Random data samples The simplest initialization method is to sample $K$ points at random from the input data and use them as initial values for the cluster centers. @par K-means++ @cite{arthur07k-means} proposes a randomized initialization of the centers which improves upon random selection. The first center $\bc_1$ is selected at random from the data points $\bx_1, \dots, \bx_n $ and the distance from this center to all points $\|\bx_i - \bc_1\|_p^p$ is computed. Then the second center $\bc_2$ is selected at random from the data points with probability proportional to the distance. The procedure is repeated to obtain the other centers by using the minimum distance to the centers collected so far. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-lloyd Lloyd's algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The most common K-means method is Lloyd's algorithm @cite{lloyd82least}. This algorithm is based on the observation that, while jointly optimizing clusters and assignment is difficult, optimizing one given the other is easy. Lloyd's algorithm alternates the steps: 1. **Quantization.** Each point $\bx_i$ is reassigned to the center $\bc_{q_j}$ closer to it. This requires finding for each point the closest among $K$ other points, which is potentially slow. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize its average distances to the points assigned to it. It is easy to show that the best center is the mean or median of the points, respectively if the $l^2$ or $l^1$ norm is considered. A naive implementation of the assignment step requires $O(dnK)$ operations, where $d$ is the dimensionality of the data, $n$ the number of data points, and $K$ the number of centers. Updating the centers is much cheaper: $O(dn)$ operations suffice to compute the $K$ means and a slightly higher cost is required for the medians. Clearly, the bottleneck is the assignment computation, and this is what the other K-means algorithm try to improve. During the iterations, it can happen that a cluster becomes empty. In this case, K-means automatically **&ldquo;restarts&rdquo; the cluster** center by selecting a training point at random. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-elkan Elkan's algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> Elkan's algorithm @cite{elkan03using} is a variation of Lloyd alternate optimization algorithm (@ref kmeans-lloyd) that uses the triangular inequality to avoid many distance calculations when assigning points to clusters. While much faster than Lloyd, Elkan's method uses storage proportional to the umber of clusters by data points, which makes it unpractical for a very large number of clusters. The idea of this algorithm is that, if a center update does not move them much, then most of the point-to-center computations can be avoided when the point-to-center assignments are recomputed. To detect which distances need evaluation, the triangular inequality is used to lower and upper bound distances after a center update. Elkan algorithms uses two key observations. First, one has \[ \|\bx_i - \bc_{q_i}\|_p \leq \|\bc - \bc_{q_i}\|_p / 2 \quad\Rightarrow\quad \|\bx_i - \bc_{q_i}\|_p \leq \|\bx_i - \bc\|_p. \] Thus if the distance between $\bx_i$ and its current center $\bc_{q_i}$ is less than half the distance of the center $\bc_{q_i}$ to another center $\bc$, then $\bc$ can be skipped when the new assignment for $\bx_i$ is searched. Checking this requires keeping track of all the inter-center distances, but centers are typically a small fraction of the training data, so overall this can be a significant saving. In particular, if this condition is satisfied for all the centers $\bc \not= \bc_{q_i}$, the point $\bx_i$ can be skipped completely. Furthermore, the condition can be tested also based on an upper bound $UB_i$ of $\|\bx_i - \bc_{q_i}\|_p$. Second, if a center $\bc$ is updated to $\hat{\bc}$, then the new distance from $\bx$ to $\hat{\bc}$ is bounded from below and above by \[ \|\bx - \bc\|_p - \|bc - \hat\bc\|_p \leq \|\bx - \hat{\bc}\|_p \leq \|\bx - \hat{\bc}\|_p + \|\bc + \hat{\bc}\|_p. \] This allows to maintain an upper bound on the distance of $\bx_i$ to its current center $\bc_{q_i}$ and a lower bound to any other center $\bc$: @f{align*} UB_i & \leftarrow UB_i + \|\bc_{q_i} - \hat{\bc}_{q_i} \|_p \\ LB_i(\bc) & \leftarrow LB_i(\bc) - \|\bc -\hat \bc\|_p. @f} Thus the K-means algorithm becomes: 1. **Initialization.** Compute $LB_i(\bc) = \|\bx_i -\hat \bc\|_p$ for all points and centers. Find the current assignments $q_i$ and bounds $UB_i$ by finding the closest centers to each point: $UB_i = \min_{\bc} LB_i(\bc)$. 2. **Center estimation.** 1. Recompute all the centers based on the new means; call the updated version $\hat{\bc}$. 2. Update all the bounds based on the distance $\|\bc - \hat\bc\|_p$ as explained above. 3. Set $\bc \leftarrow \hat\bc$ for all the centers and go to the next iteration. 3. **Quantization.** 1. Skip any point $\bx_i$ such that $UB_i \leq \frac{1}{2} \|\bc_{q_i} - \bc\|_p$ for all centers $\bc \not= \bc_{q_i}$. 2. For each remaining point $\bx_i$ and center $\bc \not= \bc_{q_i}$: 1. Skip $\bc$ if \[ UB_i \leq \frac{1}{2} \| \bc_{q_i} - \bc \| \quad\text{or}\quad UB_i \leq LB_i(\bc). \] The first condition reflects the first observation above; the second uses the bounds to decide if $\bc$ can be closer than the current center $\bc_{q_i}$ to the point $\bx_i$. If the center cannot be skipped, continue as follows. 3. Skip $\bc$ if the condition above is satisfied after making the upper bound tight: \[ UB_i = LB_i(\bc_{q_i}) = \| \bx_i - \bc_{q_i} \|_p. \] Note that the latter calculation can be done only once for $\bx_i$. If the center cannot be skipped still, continue as follows. 4. Tighten the lower bound too: \[ LB_i(\bc) = \| \bx_i - \bc \|_p. \] At this point both $UB_i$ and $LB_i(\bc)$ are tight. If $LB_i < UB_i$, then the point $\bx_i$ should be reassigned to $\bc$. Update $q_i$ to the index of center $\bc$ and reset $UB_i = LB_i(\bc)$. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> @section kmeans-ann ANN algorithm <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> The *Approximate Nearest Neighbor* (ANN) K-means algorithm @cite{beis97shape} @cite{silpa-anan08optimised} @cite{muja09fast} is a variant of Lloyd's algorithm (@ref kmeans-lloyd) uses a best-bin-first randomized KD-tree algorithm to approximately (and quickly) find the closest cluster center to each point. The KD-tree implementation is based on @ref kdtree. The algorithm can be summarized as follows: 1. **Quantization.** Each point $\bx_i$ is reassigned to the center $\bc_{q_j}$ closer to it. This starts by indexing the $K$ centers by a KD-tree and then using the latter to quickly find the closest center for every training point. The search is approximated to further improve speed. This opens up the possibility that a data point may receive an assignment that is *worse* than the current one. This is avoided by checking that the new assignment estimated by using ANN is an improvement; otherwise the old assignment is kept. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize its average distances to the points assigned to it. It is easy to show that the best center is the mean or median of the points, respectively if the $l^2$ or $l^1$ norm is considered. The key is to trade-off carefully the speedup obtained by using the ANN algorithm and the loss in accuracy when retrieving neighbors. Due to the curse of dimensionality, KD-trees become less effective for higher dimensional data, so that the search cost, which in the best case is logarithmic with this data structure, may become effectively linear. This is somehow mitigated by the fact that new a new KD-tree is computed at each iteration, reducing the likelihood that points may get stuck with sub-optimal assignments. Experiments with the quantization of 128-dimensional SIFT features show that the ANN algorithm may use one quarter of the comparisons of Elkan's while retaining a similar solution accuracy. */ #include "kmeans.h" #include "generic.h" #include "mathop.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /* ================================================================ */ #ifndef VL_KMEANS_INSTANTIATING /** ------------------------------------------------------------------ ** @brief Reset state ** ** The function reset the state of the KMeans object. It deletes ** any stored centers, releasing the corresponding memory. This ** cancels the effect of seeding or setting the centers, but ** does not change the other configuration parameters. **/ void vl_kmeans_reset (VlKMeans * self) { self->numCenters = 0 ; self->dimension = 0 ; if (self->centers) vl_free(self->centers) ; if (self->centerDistances) vl_free(self->centerDistances) ; self->centers = NULL ; self->centerDistances = NULL ; } /** ------------------------------------------------------------------ ** @brief Create a new KMeans object ** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE) ** @param distance distance. ** @return new KMeans object instance. **/ VlKMeans * vl_kmeans_new (vl_type dataType, VlVectorComparisonType distance) { VlKMeans * self = vl_calloc(1, sizeof(VlKMeans)) ; self->algorithm = VlKMeansLloyd ; self->distance = distance ; self->dataType = dataType ; self->verbosity = 0 ; self->maxNumIterations = 100 ; self->minEnergyVariation = 1e-4 ; self->numRepetitions = 1 ; self->centers = NULL ; self->centerDistances = NULL ; self->numTrees = 3; self->maxNumComparisons = 100; vl_kmeans_reset (self) ; return self ; } /** ------------------------------------------------------------------ ** @brief Create a new KMeans object by copy ** @param kmeans KMeans object to copy. ** @return new copy. **/ VlKMeans * vl_kmeans_new_copy (VlKMeans const * kmeans) { VlKMeans * self = vl_malloc(sizeof(VlKMeans)) ; self->algorithm = kmeans->algorithm ; self->distance = kmeans->distance ; self->dataType = kmeans->dataType ; self->verbosity = kmeans->verbosity ; self->maxNumIterations = kmeans->maxNumIterations ; self->numRepetitions = kmeans->numRepetitions ; self->dimension = kmeans->dimension ; self->numCenters = kmeans->numCenters ; self->centers = NULL ; self->centerDistances = NULL ; self->numTrees = kmeans->numTrees; self->maxNumComparisons = kmeans->maxNumComparisons; if (kmeans->centers) { vl_size dataSize = vl_get_type_size(self->dataType) * self->dimension * self->numCenters ; self->centers = vl_malloc(dataSize) ; memcpy (self->centers, kmeans->centers, dataSize) ; } if (kmeans->centerDistances) { vl_size dataSize = vl_get_type_size(self->dataType) * self->numCenters * self->numCenters ; self->centerDistances = vl_malloc(dataSize) ; memcpy (self->centerDistances, kmeans->centerDistances, dataSize) ; } return self ; } /** ------------------------------------------------------------------ ** @brief Deletes a KMeans object ** @param self KMeans object instance. ** ** The function deletes the KMeans object instance created ** by ::vl_kmeans_new. **/ void vl_kmeans_delete (VlKMeans * self) { vl_kmeans_reset (self) ; vl_free (self) ; } /* an helper structure */ typedef struct _VlKMeansSortWrapper { vl_uint32 * permutation ; void const * data ; vl_size stride ; } VlKMeansSortWrapper ; /* ---------------------------------------------------------------- */ /* Instantiate shuffle algorithm */ #define VL_SHUFFLE_type vl_uindex #define VL_SHUFFLE_prefix _vl_kmeans #include "shuffle-def.h" /* #ifdef VL_KMEANS_INSTANTITATING */ #endif /* ================================================================ */ #ifdef VL_KMEANS_INSTANTIATING /* ---------------------------------------------------------------- */ /* Set centers */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_set_centers_, SFX) (VlKMeans * self, TYPE const * centers, vl_size dimension, vl_size numCenters) { self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; memcpy ((TYPE*)self->centers, centers, sizeof(TYPE) * dimension * numCenters) ; } /* ---------------------------------------------------------------- */ /* Random seeding */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_init_centers_with_rand_data_, SFX) (VlKMeans * self, TYPE const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex i, j, k ; VlRand * rand = vl_get_rand () ; self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; { vl_uindex * perm = vl_malloc (sizeof(vl_uindex) * numData) ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif TYPE * distances = vl_malloc (sizeof(TYPE) * numCenters) ; /* get a random permutation of the data point */ for (i = 0 ; i < numData ; ++i) perm[i] = i ; _vl_kmeans_shuffle (perm, numData, rand) ; for (k = 0, i = 0 ; k < numCenters ; ++ i) { /* compare the next data point to all centers collected so far to detect duplicates (if there are enough left) */ if (numCenters - k < numData - i) { vl_bool duplicateDetected = VL_FALSE ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distances, dimension, data + dimension * perm[i], 1, (TYPE*)self->centers, k, distFn) ; for (j = 0 ; j < k ; ++j) { duplicateDetected |= (distances[j] == 0) ; } if (duplicateDetected) continue ; } /* ok, it is not a duplicate so we can accept it! */ memcpy ((TYPE*)self->centers + dimension * k, data + dimension * perm[i], sizeof(TYPE) * dimension) ; k ++ ; } vl_free(distances) ; vl_free(perm) ; } } /* ---------------------------------------------------------------- */ /* kmeans++ seeding */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_init_centers_plus_plus_, SFX) (VlKMeans * self, TYPE const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex x, c ; VlRand * rand = vl_get_rand () ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; TYPE * minDistances = vl_malloc (sizeof(TYPE) * numData) ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif self->dimension = dimension ; self->numCenters = numCenters ; self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ; for (x = 0 ; x < numData ; ++x) { minDistances[x] = (TYPE) VL_INFINITY_D ; } /* select the first point at random */ x = vl_rand_uindex (rand, numData) ; c = 0 ; while (1) { TYPE energy = 0 ; TYPE acc = 0 ; TYPE thresh = (TYPE) vl_rand_real1 (rand) ; memcpy ((TYPE*)self->centers + c * dimension, data + x * dimension, sizeof(TYPE) * dimension) ; c ++ ; if (c == numCenters) break ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX) (distances, dimension, (TYPE*)self->centers + (c - 1) * dimension, 1, data, numData, distFn) ; for (x = 0 ; x < numData ; ++x) { minDistances[x] = VL_MIN(minDistances[x], distances[x]) ; energy += minDistances[x] ; } for (x = 0 ; x < numData - 1 ; ++x) { acc += minDistances[x] ; if (acc >= thresh * energy) break ; } } vl_free(distances) ; vl_free(minDistances) ; } /* ---------------------------------------------------------------- */ /* Quantization */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_quantize_, SFX) (VlKMeans * self, vl_uint32 * assignments, TYPE * distances, TYPE const * data, vl_size numData) { vl_index i ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif #ifdef _OPENMP #pragma omp parallel default(none) \ shared(self, distances, assignments, numData, distFn, data) \ num_threads(vl_get_max_threads()) #endif { /* vl_malloc cannot be used here if mapped to MATLAB malloc */ TYPE * distanceToCenters = malloc(sizeof(TYPE) * self->numCenters) ; #ifdef _OPENMP #pragma omp for #endif for (i = 0 ; i < (signed)numData ; ++i) { vl_uindex k ; TYPE bestDistance = (TYPE) VL_INFINITY_D ; VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distanceToCenters, self->dimension, data + self->dimension * i, 1, (TYPE*)self->centers, self->numCenters, distFn) ; for (k = 0 ; k < self->numCenters ; ++k) { if (distanceToCenters[k] < bestDistance) { bestDistance = distanceToCenters[k] ; assignments[i] = (vl_uint32)k ; } } if (distances) distances[i] = bestDistance ; } free(distanceToCenters) ; } } /* ---------------------------------------------------------------- */ /* ANN quantization */ /* ---------------------------------------------------------------- */ static void VL_XCAT(_vl_kmeans_quantize_ann_, SFX) (VlKMeans * self, vl_uint32 * assignments, TYPE * distances, TYPE const * data, vl_size numData, vl_bool update) { #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif VlKDForest * forest = vl_kdforest_new(self->dataType,self->dimension,self->numTrees, self->distance) ; vl_kdforest_set_max_num_comparisons(forest,self->maxNumComparisons); vl_kdforest_set_thresholding_method(forest,VL_KDTREE_MEDIAN); vl_kdforest_build(forest,self->numCenters,self->centers); #ifdef _OPENMP #pragma omp parallel default(none) \ num_threads(vl_get_max_threads()) \ shared(self, forest, update, assignments, distances, data, numData, distFn) #endif { VlKDForestNeighbor neighbor ; VlKDForestSearcher * searcher ; vl_index x; #ifdef _OPENMP #pragma omp critical #endif searcher = vl_kdforest_new_searcher (forest) ; #ifdef _OPENMP #pragma omp for #endif for(x = 0 ; x < (signed)numData ; ++x) { vl_kdforestsearcher_query (searcher, &neighbor, 1, (TYPE const *) (data + x*self->dimension)); if (distances) { if(!update) { distances[x] = (TYPE) neighbor.distance; assignments[x] = (vl_uint32) neighbor.index ; } else { TYPE prevDist = (TYPE) distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension *assignments[x]); if (prevDist > (TYPE) neighbor.distance) { distances[x] = (TYPE) neighbor.distance ; assignments[x] = (vl_uint32) neighbor.index ; } else { distances[x] = prevDist ; } } } else { assignments[x] = (vl_uint32) neighbor.index ; } } /* end for */ } /* end of parallel region */ vl_kdforest_delete(forest); } /* ---------------------------------------------------------------- */ /* Helper functions */ /* ---------------------------------------------------------------- */ /* The sorting routine is used to find increasing permutation of each * data dimension. This is used to quickly find the median for l1 * distance clustering. */ VL_INLINE TYPE VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp) (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB) { return ((TYPE*)array->data) [array->permutation[indexA] * array->stride] - ((TYPE*)array->data) [array->permutation[indexB] * array->stride] ; } VL_INLINE void VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap) (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB) { vl_uint32 tmp = array->permutation[indexA] ; array->permutation[indexA] = array->permutation[indexB] ; array->permutation[indexB] = tmp ; } #define VL_QSORT_prefix VL_XCAT3(_vl_kmeans_, SFX, _qsort) #define VL_QSORT_array VlKMeansSortWrapper* #define VL_QSORT_cmp VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp) #define VL_QSORT_swap VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap) #include "qsort-def.h" static void VL_XCAT(_vl_kmeans_sort_data_helper_, SFX) (VlKMeans * self, vl_uint32 * permutations, TYPE const * data, vl_size numData) { vl_uindex d, x ; for (d = 0 ; d < self->dimension ; ++d) { VlKMeansSortWrapper array ; array.permutation = permutations + d * numData ; array.data = data + d ; array.stride = self->dimension ; for (x = 0 ; x < numData ; ++x) { array.permutation[x] = (vl_uint32)x ; } VL_XCAT3(_vl_kmeans_, SFX, _qsort_sort)(&array, numData) ; } } /* ---------------------------------------------------------------- */ /* Lloyd refinement */ /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size c, d, x, iteration ; double previousEnergy = VL_INFINITY_D ; double initialEnergy = VL_INFINITY_D ; double energy ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; VlRand * rand = vl_get_rand () ; vl_size totNumRestartedCenters = 0 ; vl_size numRestartedCenters = 0 ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } for (energy = VL_INFINITY_D, iteration = 0; 1 ; ++ iteration) { /* assign data to cluters */ VL_XCAT(_vl_kmeans_quantize_, SFX)(self, assignments, distances, data, numData) ; /* compute energy */ energy = 0 ; for (x = 0 ; x < numData ; ++x) energy += distances[x] ; if (self->verbosity) { VL_PRINTF("kmeans: Lloyd iter %d: energy = %g\n", iteration, energy) ; } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: Lloyd terminating because maximum number of iterations reached\n") ; } break ; } if (energy == previousEnergy) { if (self->verbosity) { VL_PRINTF("kmeans: Lloyd terminating because the algorithm fully converged\n") ; } break ; } if (iteration == 0) { initialEnergy = energy ; } else { double eps = (previousEnergy - energy) / (initialEnergy - energy) ; if (eps < self->minEnergyVariation) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ; } break ; } } /* begin next iteration */ previousEnergy = energy ; /* update clusters */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < numData ; ++x) { clusterMasses[assignments[x]] ++ ; } numRestartedCenters = 0 ; switch (self->distance) { case VlDistanceL2: memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < numData ; ++x) { TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { ((TYPE*)self->centers) [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } } break ; default: abort(); } /* done compute centers */ totNumRestartedCenters += numRestartedCenters ; if (self->verbosity && numRestartedCenters) { VL_PRINTF("kmeans: Lloyd iter %d: restarted %d centers\n", iteration, numRestartedCenters) ; } } /* next Lloyd iteration */ if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; return energy ; } static double VL_XCAT(_vl_kmeans_update_center_distances_, SFX) (VlKMeans * self) { #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif if (! self->centerDistances) { self->centerDistances = vl_malloc (sizeof(TYPE) * self->numCenters * self->numCenters) ; } VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(self->centerDistances, self->dimension, self->centers, self->numCenters, NULL, 0, distFn) ; return self->numCenters * (self->numCenters - 1) / 2 ; } static double VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size c, d, x, iteration ; double initialEnergy = VL_INFINITY_D ; double previousEnergy = VL_INFINITY_D ; double energy ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; VlRand * rand = vl_get_rand () ; vl_size totNumRestartedCenters = 0 ; vl_size numRestartedCenters = 0 ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } for (energy = VL_INFINITY_D, iteration = 0; 1 ; ++ iteration) { /* assign data to cluters */ VL_XCAT(_vl_kmeans_quantize_ann_, SFX)(self, assignments, distances, data, numData, iteration > 0) ; /* compute energy */ energy = 0 ; for (x = 0 ; x < numData ; ++x) energy += distances[x] ; if (self->verbosity) { VL_PRINTF("kmeans: ANN iter %d: energy = %g\n", iteration, energy) ; } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the maximum number of iterations has been reached\n") ; } break ; } if (energy == previousEnergy) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the algorithm fully converged\n") ; } break ; } if (iteration == 0) { initialEnergy = energy ; } else { double eps = (previousEnergy - energy) / (initialEnergy - energy) ; if (eps < self->minEnergyVariation) { if (self->verbosity) { VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ; } break ; } } /* begin next iteration */ previousEnergy = energy ; /* update clusters */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < numData ; ++x) { clusterMasses[assignments[x]] ++ ; } numRestartedCenters = 0 ; switch (self->distance) { case VlDistanceL2: memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < numData ; ++x) { TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { ((TYPE*)self->centers) [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = (TYPE*)self->centers + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } } break ; default: VL_PRINT("bad distance set: %d\n",self->distance); abort(); } /* done compute centers */ totNumRestartedCenters += numRestartedCenters ; if (self->verbosity && numRestartedCenters) { VL_PRINTF("kmeans: ANN iter %d: restarted %d centers\n", iteration, numRestartedCenters) ; } } if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; return energy ; } /* ---------------------------------------------------------------- */ /* Elkan refinement */ /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { vl_size d, iteration ; vl_index x ; vl_uint32 c, j ; vl_bool allDone ; TYPE * distances = vl_malloc (sizeof(TYPE) * numData) ; vl_uint32 * assignments = vl_malloc (sizeof(vl_uint32) * numData) ; vl_size * clusterMasses = vl_malloc (sizeof(vl_size) * numData) ; VlRand * rand = vl_get_rand () ; #if (FLT == VL_TYPE_FLOAT) VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ; #else VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ; #endif TYPE * nextCenterDistances = vl_malloc (sizeof(TYPE) * self->numCenters) ; TYPE * pointToClosestCenterUB = vl_malloc (sizeof(TYPE) * numData) ; vl_bool * pointToClosestCenterUBIsStrict = vl_malloc (sizeof(vl_bool) * numData) ; TYPE * pointToCenterLB = vl_malloc (sizeof(TYPE) * numData * self->numCenters) ; TYPE * newCenters = vl_malloc(sizeof(TYPE) * self->dimension * self->numCenters) ; TYPE * centerToNewCenterDistances = vl_malloc (sizeof(TYPE) * self->numCenters) ; vl_uint32 * permutations = NULL ; vl_size * numSeenSoFar = NULL ; double energy ; vl_size totDistanceComputationsToInit = 0 ; vl_size totDistanceComputationsToRefreshUB = 0 ; vl_size totDistanceComputationsToRefreshLB = 0 ; vl_size totDistanceComputationsToRefreshCenterDistances = 0 ; vl_size totDistanceComputationsToNewCenters = 0 ; vl_size totDistanceComputationsToFinalize = 0 ; vl_size totNumRestartedCenters = 0 ; if (self->distance == VlDistanceL1) { permutations = vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ; numSeenSoFar = vl_malloc(sizeof(vl_size) * self->numCenters) ; VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Initialization */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* An iteration is: get_new_centers + reassign + get_energy. This counts as iteration 0, where get_new_centers is assumed to be performed before calling the train function by the initialization function */ /* update distances between centers */ totDistanceComputationsToInit += VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ; /* assigmen points to the initial centers and initialize bounds */ memset(pointToCenterLB, 0, sizeof(TYPE) * self->numCenters * numData) ; for (x = 0 ; x < (signed)numData ; ++x) { TYPE distance ; /* do the first center */ assignments[x] = 0 ; distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + 0) ; pointToClosestCenterUB[x] = distance ; pointToClosestCenterUBIsStrict[x] = VL_TRUE ; pointToCenterLB[0 + x * self->numCenters] = distance ; totDistanceComputationsToInit += 1 ; /* do other centers */ for (c = 1 ; c < self->numCenters ; ++c) { /* Can skip if the center assigned so far is twice as close as its distance to the center under consideration */ if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + assignments[x] * self->numCenters]) { continue ; } distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + c * self->dimension) ; pointToCenterLB[c + x * self->numCenters] = distance ; totDistanceComputationsToInit += 1 ; if (distance < pointToClosestCenterUB[x]) { pointToClosestCenterUB[x] = distance ; assignments[x] = c ; } } } /* compute UB on energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++x) { energy += pointToClosestCenterUB[x] ; } if (self->verbosity) { VL_PRINTF("kmeans: Elkan iter 0: energy = %g, dist. calc. = %d\n", energy, totDistanceComputationsToInit) ; } /* #define SANITY*/ #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies after initial assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f\n", cc, xx, a, b) ; } } } #endif /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Iterations */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ for (iteration = 1 ; 1; ++iteration) { vl_size numDistanceComputationsToRefreshUB = 0 ; vl_size numDistanceComputationsToRefreshLB = 0 ; vl_size numDistanceComputationsToRefreshCenterDistances = 0 ; vl_size numDistanceComputationsToNewCenters = 0 ; vl_size numRestartedCenters = 0 ; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Compute new centers */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ memset(clusterMasses, 0, sizeof(vl_size) * numData) ; for (x = 0 ; x < (signed)numData ; ++x) { clusterMasses[assignments[x]] ++ ; } switch (self->distance) { case VlDistanceL2: memset(newCenters, 0, sizeof(TYPE) * self->dimension * self->numCenters) ; for (x = 0 ; x < (signed)numData ; ++x) { TYPE * cpt = newCenters + assignments[x] * self->dimension ; TYPE const * xpt = data + x * self->dimension ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] += xpt[d] ; } } for (c = 0 ; c < self->numCenters ; ++c) { TYPE * cpt = newCenters + c * self->dimension ; if (clusterMasses[c] > 0) { TYPE mass = clusterMasses[c] ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] /= mass ; } } else { /* restart the center */ vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; case VlDistanceL1: for (d = 0 ; d < self->dimension ; ++d) { vl_uint32 * perm = permutations + d * numData ; memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ; for (x = 0; x < (signed)numData ; ++x) { c = assignments[perm[x]] ; if (2 * numSeenSoFar[c] < clusterMasses[c]) { newCenters [d + c * self->dimension] = data [d + perm[x] * self->dimension] ; } numSeenSoFar[c] ++ ; } } /* restart the centers as required */ for (c = 0 ; c < self->numCenters ; ++c) { if (clusterMasses[c] == 0) { TYPE * cpt = newCenters + c * self->dimension ; vl_uindex x = vl_rand_uindex(rand, numData) ; numRestartedCenters ++ ; for (d = 0 ; d < self->dimension ; ++d) { cpt[d] = data[x * self->dimension + d] ; } } } break ; default: abort(); } /* done compute centers */ /* compute the distance from the old centers to the new centers */ for (c = 0 ; c < self->numCenters ; ++c) { TYPE distance = distFn(self->dimension, newCenters + c * self->dimension, (TYPE*)self->centers + c * self->dimension) ; centerToNewCenterDistances[c] = distance ; numDistanceComputationsToNewCenters += 1 ; } /* make the new centers current */ { TYPE * tmp = self->centers ; self->centers = newCenters ; newCenters = tmp ; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Reassign points to a centers */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* Update distances between centers. */ numDistanceComputationsToRefreshCenterDistances += VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ; for (c = 0 ; c < self->numCenters ; ++c) { nextCenterDistances[c] = (TYPE) VL_INFINITY_D ; for (j = 0 ; j < self->numCenters ; ++j) { if (j == c) continue ; nextCenterDistances[c] = VL_MIN(nextCenterDistances[c], ((TYPE*)self->centerDistances) [j + c * self->numCenters]) ; } } /* Update upper bounds on point-to-closest-center distances based on the center variation. */ for (x = 0 ; x < (signed)numData ; ++x) { TYPE a = pointToClosestCenterUB[x] ; TYPE b = centerToNewCenterDistances[assignments[x]] ; if (self->distance == VlDistanceL1) { pointToClosestCenterUB[x] = a + b ; } else { #if (FLT == VL_TYPE_FLOAT) TYPE sqrtab = sqrtf (a * b) ; #else TYPE sqrtab = sqrt (a * b) ; #endif pointToClosestCenterUB[x] = a + b + 2.0 * sqrtab ; } pointToClosestCenterUBIsStrict[x] = VL_FALSE ; } /* Update lower bounds on point-to-center distances based on the center variation. */ #if defined(_OPENMP) #pragma omp parallel for default(shared) private(x,c) num_threads(vl_get_max_threads()) #endif for (x = 0 ; x < (signed)numData ; ++x) { for (c = 0 ; c < self->numCenters ; ++c) { TYPE a = pointToCenterLB[c + x * self->numCenters] ; TYPE b = centerToNewCenterDistances[c] ; if (a < b) { pointToCenterLB[c + x * self->numCenters] = 0 ; } else { if (self->distance == VlDistanceL1) { pointToCenterLB[c + x * self->numCenters] = a - b ; } else { #if (FLT == VL_TYPE_FLOAT) TYPE sqrtab = sqrtf (a * b) ; #else TYPE sqrtab = sqrt (a * b) ; #endif pointToCenterLB[c + x * self->numCenters] = a + b - 2.0 * sqrtab ; } } } } #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies before assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n", cc, xx, a, b, assignments[xx]) ; } } } #endif /* Scan the data and do the reassignments. Use the bounds to skip as many point-to-center distance calculations as possible. */ allDone = VL_TRUE ; #if defined(_OPENMP) #pragma omp parallel for \ default(none) \ shared(self,numData, \ pointToClosestCenterUB,pointToCenterLB, \ nextCenterDistances,pointToClosestCenterUBIsStrict, \ assignments,data,distFn,allDone) \ private(c,x) \ reduction(+:numDistanceComputationsToRefreshUB,numDistanceComputationsToRefreshLB) \ num_threads(vl_get_max_threads()) #endif for (x = 0 ; x < (signed)numData ; ++ x) { /* A point x sticks with its current center assignmets[x] the UB to d(x, c[assigmnets[x]]) is not larger than half the distance of c[assigments[x]] to any other center c. */ if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= nextCenterDistances[assignments[x]]) { continue ; } for (c = 0 ; c < self->numCenters ; ++c) { vl_uint32 cx = assignments[x] ; TYPE distance ; /* The point is not reassigned to a given center c if either: 0 - c is already the assigned center 1 - The UB of d(x, c[assignments[x]]) is smaller than half the distance of c[assigments[x]] to c, OR 2 - The UB of d(x, c[assignmets[x]]) is smaller than the LB of the distance of x to c. */ if (cx == c) { continue ; } if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + cx * self->numCenters]) { continue ; } if (pointToClosestCenterUB[x] <= pointToCenterLB [c + x * self->numCenters]) { continue ; } /* If the UB is loose, try recomputing it and test again */ if (! pointToClosestCenterUBIsStrict[x]) { distance = distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension * cx) ; pointToClosestCenterUB[x] = distance ; pointToClosestCenterUBIsStrict[x] = VL_TRUE ; pointToCenterLB[cx + x * self->numCenters] = distance ; numDistanceComputationsToRefreshUB += 1 ; if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) * pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances) [c + cx * self->numCenters]) { continue ; } if (pointToClosestCenterUB[x] <= pointToCenterLB [c + x * self->numCenters]) { continue ; } } /* Now the UB is strict (equal to d(x, assignments[x])), but we still could not exclude that x should be reassigned to c. We therefore compute the distance, update the LB, and check if a reassigmnet must be made */ distance = distFn(self->dimension, data + x * self->dimension, (TYPE*)self->centers + c * self->dimension) ; numDistanceComputationsToRefreshLB += 1 ; pointToCenterLB[c + x * self->numCenters] = distance ; if (distance < pointToClosestCenterUB[x]) { assignments[x] = c ; pointToClosestCenterUB[x] = distance ; allDone = VL_FALSE ; /* the UB strict flag is already set here */ } } /* assign center */ } /* next data point */ totDistanceComputationsToRefreshUB += numDistanceComputationsToRefreshUB ; totDistanceComputationsToRefreshLB += numDistanceComputationsToRefreshLB ; totDistanceComputationsToRefreshCenterDistances += numDistanceComputationsToRefreshCenterDistances ; totDistanceComputationsToNewCenters += numDistanceComputationsToNewCenters ; totNumRestartedCenters += numRestartedCenters ; #ifdef SANITY { int xx ; int cc ; TYPE tol = 1e-5 ; VL_PRINTF("inconsistencies after assignments:\n"); for (xx = 0 ; xx < numData ; ++xx) { for (cc = 0 ; cc < self->numCenters ; ++cc) { TYPE a = pointToCenterLB[cc + xx * self->numCenters] ; TYPE b = distFn(self->dimension, data + self->dimension * xx, (TYPE*)self->centers + self->dimension * cc) ; if (cc == assignments[xx]) { TYPE z = pointToClosestCenterUB[xx] ; if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n", cc, xx, z, b) ; } if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n", cc, xx, a, b, assignments[xx]) ; } } } #endif /* compute UB on energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++x) { energy += pointToClosestCenterUB[x] ; } if (self->verbosity) { vl_size numDistanceComputations = numDistanceComputationsToRefreshUB + numDistanceComputationsToRefreshLB + numDistanceComputationsToRefreshCenterDistances + numDistanceComputationsToNewCenters ; VL_PRINTF("kmeans: Elkan iter %d: energy <= %g, dist. calc. = %d\n", iteration, energy, numDistanceComputations) ; if (numRestartedCenters) { VL_PRINTF("kmeans: Elkan iter %d: restarted %d centers\n", iteration, energy, numRestartedCenters) ; } if (self->verbosity > 1) { VL_PRINTF("kmeans: Elkan iter %d: total dist. calc. per type: " "UB: %.1f%% (%d), LB: %.1f%% (%d), " "intra_center: %.1f%% (%d), " "new_center: %.1f%% (%d)\n", iteration, 100.0 * numDistanceComputationsToRefreshUB / numDistanceComputations, numDistanceComputationsToRefreshUB, 100.0 *numDistanceComputationsToRefreshLB / numDistanceComputations, numDistanceComputationsToRefreshLB, 100.0 * numDistanceComputationsToRefreshCenterDistances / numDistanceComputations, numDistanceComputationsToRefreshCenterDistances, 100.0 * numDistanceComputationsToNewCenters / numDistanceComputations, numDistanceComputationsToNewCenters) ; } } /* check termination conditions */ if (iteration >= self->maxNumIterations) { if (self->verbosity) { VL_PRINTF("kmeans: Elkan terminating because maximum number of iterations reached\n") ; } break ; } if (allDone) { if (self->verbosity) { VL_PRINTF("kmeans: Elkan terminating because the algorithm fully converged\n") ; } break ; } } /* next Elkan iteration */ /* compute true energy */ energy = 0 ; for (x = 0 ; x < (signed)numData ; ++ x) { vl_uindex cx = assignments [x] ; energy += distFn(self->dimension, data + self->dimension * x, (TYPE*)self->centers + self->dimension * cx) ; totDistanceComputationsToFinalize += 1 ; } { vl_size totDistanceComputations = totDistanceComputationsToInit + totDistanceComputationsToRefreshUB + totDistanceComputationsToRefreshLB + totDistanceComputationsToRefreshCenterDistances + totDistanceComputationsToNewCenters + totDistanceComputationsToFinalize ; double saving = (double)totDistanceComputations / (iteration * self->numCenters * numData) ; if (self->verbosity) { VL_PRINTF("kmeans: Elkan: total dist. calc.: %d (%.2f %% of Lloyd)\n", totDistanceComputations, saving * 100.0) ; if (totNumRestartedCenters) { VL_PRINTF("kmeans: Elkan: there have been %d restarts\n", totNumRestartedCenters) ; } } if (self->verbosity > 1) { VL_PRINTF("kmeans: Elkan: total dist. calc. per type: " "init: %.1f%% (%d), UB: %.1f%% (%d), LB: %.1f%% (%d), " "intra_center: %.1f%% (%d), " "new_center: %.1f%% (%d), " "finalize: %.1f%% (%d)\n", 100.0 * totDistanceComputationsToInit / totDistanceComputations, totDistanceComputationsToInit, 100.0 * totDistanceComputationsToRefreshUB / totDistanceComputations, totDistanceComputationsToRefreshUB, 100.0 *totDistanceComputationsToRefreshLB / totDistanceComputations, totDistanceComputationsToRefreshLB, 100.0 * totDistanceComputationsToRefreshCenterDistances / totDistanceComputations, totDistanceComputationsToRefreshCenterDistances, 100.0 * totDistanceComputationsToNewCenters / totDistanceComputations, totDistanceComputationsToNewCenters, 100.0 * totDistanceComputationsToFinalize / totDistanceComputations, totDistanceComputationsToFinalize) ; } } if (permutations) { vl_free(permutations) ; } if (numSeenSoFar) { vl_free(numSeenSoFar) ; } vl_free(distances) ; vl_free(assignments) ; vl_free(clusterMasses) ; vl_free(nextCenterDistances) ; vl_free(pointToClosestCenterUB) ; vl_free(pointToClosestCenterUBIsStrict) ; vl_free(pointToCenterLB) ; vl_free(newCenters) ; vl_free(centerToNewCenterDistances) ; return energy ; } /* ---------------------------------------------------------------- */ static double VL_XCAT(_vl_kmeans_refine_centers_, SFX) (VlKMeans * self, TYPE const * data, vl_size numData) { switch (self->algorithm) { case VlKMeansLloyd: return VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX)(self, data, numData) ; break ; case VlKMeansElkan: return VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX)(self, data, numData) ; break ; case VlKMeansANN: return VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX)(self, data, numData) ; break ; default: abort() ; } } /* VL_KMEANS_INSTANTIATING */ #else #ifndef __DOXYGEN__ #define FLT VL_TYPE_FLOAT #define TYPE float #define SFX f #define VL_KMEANS_INSTANTIATING #include "kmeans.c" #define FLT VL_TYPE_DOUBLE #define TYPE double #define SFX d #define VL_KMEANS_INSTANTIATING #include "kmeans.c" #endif /* VL_KMEANS_INSTANTIATING */ #endif /* ================================================================ */ #ifndef VL_KMEANS_INSTANTIATING /** ------------------------------------------------------------------ ** @brief Set centers ** @param self KMeans object. ** @param centers centers to copy. ** @param dimension data dimension. ** @param numCenters number of centers. **/ void vl_kmeans_set_centers (VlKMeans * self, void const * centers, vl_size dimension, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_set_centers_f (self, (float const *)centers, dimension, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_set_centers_d (self, (double const *)centers, dimension, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief init centers by randomly sampling data ** @param self KMeans object. ** @param data data to sample from. ** @param dimension data dimension. ** @param numData nmber of data points. ** @param numCenters number of centers. ** ** The function inits the KMeans centers by randomly sampling ** the data @a data. **/ void vl_kmeans_init_centers_with_rand_data (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_init_centers_with_rand_data_f (self, (float const *)data, dimension, numData, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_init_centers_with_rand_data_d (self, (double const *)data, dimension, numData, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Seed centers by the KMeans++ algorithm ** @param self KMeans object. ** @param data data to sample from. ** @param dimension data dimension. ** @param numData nmber of data points. ** @param numCenters number of centers. **/ void vl_kmeans_init_centers_plus_plus (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_kmeans_reset (self) ; switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_init_centers_plus_plus_f (self, (float const *)data, dimension, numData, numCenters) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_init_centers_plus_plus_d (self, (double const *)data, dimension, numData, numCenters) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Quantize data ** @param self KMeans object. ** @param assignments data to closest center assignments (output). ** @param distances data to closest center distance (output). ** @param data data to quantize. ** @param numData number of data points to quantize. **/ void vl_kmeans_quantize (VlKMeans * self, vl_uint32 * assignments, void * distances, void const * data, vl_size numData) { switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_quantize_f (self, assignments, distances, (float const *)data, numData) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_quantize_d (self, assignments, distances, (double const *)data, numData) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Quantize data using approximate nearest neighbours (ANN). ** @param self KMeans object. ** @param assignments data to centers assignments (output). ** @param distances data to closes center distance (output) ** @param data data to quantize. ** @param numData number of data points. ** @param update choose wether to update current assignments. ** ** The function uses an ANN procedure to compute the approximate ** nearest neighbours of the input data point. ** ** Setting @a update to ::VL_TRUE will cause the algorithm ** to *update existing assignments*. This means that each ** element of @a assignments and @a distances is updated ony if the ** ANN procedure can find a better assignment of the existing one. **/ void vl_kmeans_quantize_ann (VlKMeans * self, vl_uint32 * assignments, void * distances, void const * data, vl_size numData, vl_bool update) { switch (self->dataType) { case VL_TYPE_FLOAT : _vl_kmeans_quantize_ann_f (self, assignments, distances, (float const *)data, numData, update) ; break ; case VL_TYPE_DOUBLE : _vl_kmeans_quantize_ann_d (self, assignments, distances, (double const *)data, numData, update) ; break ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Refine center locations. ** @param self KMeans object. ** @param data data to quantize. ** @param numData number of data points. ** @return K-means energy at the end of optimization. ** ** The function calls the underlying K-means quantization algorithm ** (@ref VlKMeansAlgorithm) to quantize the specified data @a data. ** The function assumes that the cluster centers have already ** been assigned by using one of the seeding functions, or by ** setting them. **/ double vl_kmeans_refine_centers (VlKMeans * self, void const * data, vl_size numData) { assert (self->centers) ; switch (self->dataType) { case VL_TYPE_FLOAT : return _vl_kmeans_refine_centers_f (self, (float const *)data, numData) ; case VL_TYPE_DOUBLE : return _vl_kmeans_refine_centers_d (self, (double const *)data, numData) ; default: abort() ; } } /** ------------------------------------------------------------------ ** @brief Cluster data. ** @param self KMeans object. ** @param data data to quantize. ** @param dimension data dimension. ** @param numData number of data points. ** @param numCenters number of clusters. ** @return K-means energy at the end of optimization. ** ** The function initializes the centers by using the initialization ** algorithm set by ::vl_kmeans_set_initialization and refines them ** by the quantization algorithm set by ::vl_kmeans_set_algorithm. ** The process is repeated one or more times (see ** ::vl_kmeans_set_num_repetitions) and the resutl with smaller ** energy is retained. **/ double vl_kmeans_cluster (VlKMeans * self, void const * data, vl_size dimension, vl_size numData, vl_size numCenters) { vl_uindex repetition ; double bestEnergy = VL_INFINITY_D ; void * bestCenters = NULL ; for (repetition = 0 ; repetition < self->numRepetitions ; ++ repetition) { double energy ; double timeRef ; if (self->verbosity) { VL_PRINTF("kmeans: repetition %d of %d\n", repetition + 1, self->numRepetitions) ; } timeRef = vl_get_cpu_time() ; switch (self->initialization) { case VlKMeansRandomSelection : vl_kmeans_init_centers_with_rand_data (self, data, dimension, numData, numCenters) ; break ; case VlKMeansPlusPlus : vl_kmeans_init_centers_plus_plus (self, data, dimension, numData, numCenters) ; break ; default: abort() ; } if (self->verbosity) { VL_PRINTF("kmeans: K-means initialized in %.2f s\n", vl_get_cpu_time() - timeRef) ; } timeRef = vl_get_cpu_time () ; energy = vl_kmeans_refine_centers (self, data, numData) ; if (self->verbosity) { VL_PRINTF("kmeans: K-means terminated in %.2f s with energy %g\n", vl_get_cpu_time() - timeRef, energy) ; } /* copy centers to output if current solution is optimal */ /* check repetition == 0 as well in case energy = NaN, which */ /* can happen if the data contain NaNs */ if (energy < bestEnergy || repetition == 0) { void * temp ; bestEnergy = energy ; if (bestCenters == NULL) { bestCenters = vl_malloc(vl_get_type_size(self->dataType) * self->dimension * self->numCenters) ; } /* swap buffers */ temp = bestCenters ; bestCenters = self->centers ; self->centers = temp ; } /* better energy */ } /* next repetition */ vl_free (self->centers) ; self->centers = bestCenters ; return bestEnergy ; } /* VL_KMEANS_INSTANTIATING */ #endif #undef SFX #undef TYPE #undef FLT #undef VL_KMEANS_INSTANTIATING
ojwoodford/ojwul
features/private/vlfeat/vl/kmeans.c
C
bsd-2-clause
72,182
//============================================================================ // MCKL/include/mckl/core/estimator.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2018, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef MCKL_CORE_ESTIMATOR_HPP #define MCKL_CORE_ESTIMATOR_HPP #include <mckl/internal/common.hpp> #include <mckl/core/estimate_matrix.hpp> MCKL_PUSH_CLANG_WARNING("-Wpadded") namespace mckl { /// \brief Estimator for iterative Monte Carlo algorithms /// \ingroup Core template <typename T, typename... Args> class Estimator : public EstimateMatrix<T> { public: Estimator() = default; Estimator(std::size_t dim) : EstimateMatrix<T>(0, dim) {} template <typename Eval> Estimator(std::size_t dim, Eval &&eval) : EstimateMatrix<T>(dim), eval_(std::forward<Eval>(eval)) { } using EstimateMatrix<T>::estimate; /// \brief Set a new estimate evaluation method template <typename Eval> std::enable_if_t<!std::is_convertible<Eval, int>::value> estimate( Eval &&eval) { eval_ = std::forward<Eval>(eval); } /// \brief Get the average of estimates after `cut` iterations using every /// `thin` elements template <typename OutputIter> OutputIter average( OutputIter first, std::size_t cut = 0, std::size_t thin = 1) const { const std::size_t n = this->num_iter(); const std::size_t d = this->dim(); if (cut >= n) { return first; } thin = thin < 1 ? 1 : thin; if (n - cut < thin) { return this->read_estimate(cut, first); } if (thin < 1) { thin = 1; } Vector<T> sum(d, T()); std::size_t k = 0; while (cut < n) { add(d, this->row_data(cut), sum.data(), sum.data()); cut += thin; ++k; } mul(d, static_cast<T>(1.0l / n), sum.data(), sum.data()); return std::copy(sum.begin(), sum.end(), first); } protected: template <typename... CallArgs> void eval(CallArgs &&... args) { runtime_assert(static_cast<bool>(eval_), "**Estimator::eval** used with an invalid evaluation object"); eval_(std::forward<CallArgs>(args)...); } private: std::function<void(Args...)> eval_; }; // class Estimator } // namespace mckl MCKL_POP_CLANG_WARNING #endif // MCKL_CORE_ESTIMATOR_HPP
zhouyan/MCKL
include/mckl/core/estimator.hpp
C++
bsd-2-clause
3,971
{% load inplace_edit %} <div class="object_list"> {% for object,ser in generic_object_list.object_list_serialize %} <ul class="flatblocks-object"> {% for field,value in ser.fields.items %} {% with "object."|add:field as var %} <li>{{ field }}:{% inplace_edit var %}</li> {% endwith %} {% endfor %} </ul> {% endfor %} </div>
Krozark/django-Kraggne-inplaceeditform-adaptator
Kraggne_inplaceeditform_adaptator/templates/flatblocks/object_list.html
HTML
bsd-2-clause
349
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "Core.h" #include "ISourceControlProvider.h" class SOURCECONTROLWINDOWS_API FSourceControlWindows { public: /** Opens a dialog to choose packages to submit */ static void ChoosePackagesToCheckIn(); /** Determines whether we can choose packages to check in (we cant if an operation is already in progress) */ static bool CanChoosePackagesToCheckIn(); /** * Display check in dialog for the specified packages * * @param bUseSourceControlStateCache Whether to use the cached source control status, or force the status to be updated * @param InPackageNames Names of packages to check in * @param InPendingDeletePaths Directories to check for files marked 'pending delete' * @param InConfigFiles Config filenames to check in */ static bool PromptForCheckin(bool bUseSourceControlStateCache, const TArray<FString>& InPackageNames, const TArray<FString>& InPendingDeletePaths = TArray<FString>(), const TArray<FString>& InConfigFiles = TArray<FString>()); /** * Display file revision history for the provided packages * * @param InPackageNames Names of packages to display file revision history for */ static void DisplayRevisionHistory( const TArray<FString>& InPackagesNames ); /** * Prompt the user with a revert files dialog, allowing them to specify which packages, if any, should be reverted. * * @param InPackageNames Names of the packages to consider for reverting * * @return true if the files were reverted; false if the user canceled out of the dialog */ static bool PromptForRevert(const TArray<FString>& InPackageNames ); protected: /** Callback for ChoosePackagesToCheckIn(), continues to bring up UI once source control operations are complete */ static void ChoosePackagesToCheckInCallback(const FSourceControlOperationRef& InOperation, ECommandResult::Type InResult); /** Called when the process has completed and we have packages to check in */ static void ChoosePackagesToCheckInCompleted(const TArray<UPackage*>& LoadedPackages, const TArray<FString>& PackageNames, const TArray<FString>& ConfigFiles); /** Delegate called when the user has decided to cancel the check in process */ static void ChoosePackagesToCheckInCancelled(FSourceControlOperationRef InOperation); private: /** The notification in place while we choose packages to check in */ static TWeakPtr<class SNotificationItem> ChoosePackagesToCheckInNotification; };
PopCap/GameIdea
Engine/Source/Editor/SourceControlWindows/Public/SourceControlWindows.h
C
bsd-2-clause
2,500
require "rubygems" require "formula_installer" require "hbc/cask_dependencies" require "hbc/staged" require "hbc/verify" module Hbc class Installer extend Predicable # TODO: it is unwise for Hbc::Staged to be a module, when we are # dealing with both staged and unstaged Casks here. This should # either be a class which is only sometimes instantiated, or there # should be explicit checks on whether staged state is valid in # every method. include Staged include Verify PERSISTENT_METADATA_SUBDIRS = ["gpg"].freeze def initialize(cask, command: SystemCommand, force: false, skip_cask_deps: false, binaries: true, verbose: false, require_sha: false) @cask = cask @command = command @force = force @skip_cask_deps = skip_cask_deps @binaries = binaries @verbose = verbose @require_sha = require_sha @reinstall = false end attr_predicate :binaries?, :force?, :skip_cask_deps?, :require_sha?, :verbose? def self.print_caveats(cask) odebug "Printing caveats" return if cask.caveats.empty? output = capture_output do cask.caveats.each do |caveat| if caveat.respond_to?(:eval_and_print) caveat.eval_and_print(cask) else puts caveat end end end return if output.empty? ohai "Caveats" puts output end def self.capture_output(&block) old_stdout = $stdout $stdout = Buffer.new($stdout.tty?) block.call output = $stdout.string $stdout = old_stdout output end def fetch odebug "Hbc::Installer#fetch" satisfy_dependencies verify_has_sha if require_sha? && !force? download verify end def stage odebug "Hbc::Installer#stage" extract_primary_container save_caskfile rescue StandardError => e purge_versioned_files raise e end def install odebug "Hbc::Installer#install" if @cask.installed? && !force? && !@reinstall raise CaskAlreadyInstalledError, @cask end check_conflicts print_caveats fetch uninstall_existing_cask if @reinstall oh1 "Installing Cask #{@cask}" stage install_artifacts enable_accessibility_access puts summary end def check_conflicts return unless @cask.conflicts_with @cask.conflicts_with.cask.each do |conflicting_cask| begin conflicting_cask = CaskLoader.load(conflicting_cask) if conflicting_cask.installed? raise CaskConflictError.new(@cask, conflicting_cask) end rescue CaskUnavailableError next # Ignore conflicting Casks that do not exist. end end end def reinstall odebug "Hbc::Installer#reinstall" @reinstall = true install end def uninstall_existing_cask return unless @cask.installed? # use the same cask file that was used for installation, if possible installed_caskfile = @cask.installed_caskfile installed_cask = installed_caskfile.exist? ? CaskLoader.load_from_file(installed_caskfile) : @cask # Always force uninstallation, ignore method parameter Installer.new(installed_cask, binaries: binaries?, verbose: verbose?, force: true).uninstall end def summary s = "" s << "#{Emoji.install_badge} " if Emoji.enabled? s << "#{@cask} was successfully installed!" end def download odebug "Downloading" @downloaded_path = Download.new(@cask, force: false).perform odebug "Downloaded to -> #{@downloaded_path}" @downloaded_path end def verify_has_sha odebug "Checking cask has checksum" return unless @cask.sha256 == :no_check raise CaskNoShasumError, @cask.token end def verify Verify.all(@cask, @downloaded_path) end def extract_primary_container odebug "Extracting primary container" FileUtils.mkdir_p @cask.staged_path container = if @cask.container && @cask.container.type Container.from_type(@cask.container.type) else Container.for_path(@downloaded_path, @command) end unless container raise CaskError, "Uh oh, could not figure out how to unpack '#{@downloaded_path}'" end odebug "Using container class #{container} for #{@downloaded_path}" container.new(@cask, @downloaded_path, @command, verbose: verbose?).extract end def install_artifacts already_installed_artifacts = [] odebug "Installing artifacts" artifacts = Artifact.for_cask(@cask, command: @command, verbose: verbose?, force: force?) odebug "#{artifacts.length} artifact/s defined", artifacts artifacts.each do |artifact| next unless artifact.respond_to?(:install_phase) odebug "Installing artifact of class #{artifact.class}" if artifact.is_a?(Artifact::Binary) next unless binaries? end artifact.install_phase already_installed_artifacts.unshift(artifact) end rescue StandardError => e begin already_installed_artifacts.each do |artifact| next unless artifact.respond_to?(:uninstall_phase) odebug "Reverting installation of artifact of class #{artifact.class}" artifact.uninstall_phase end ensure purge_versioned_files raise e end end # TODO: move dependencies to a separate class # dependencies should also apply for "brew cask stage" # override dependencies with --force or perhaps --force-deps def satisfy_dependencies return unless @cask.depends_on ohai "Satisfying dependencies" macos_dependencies arch_dependencies x11_dependencies formula_dependencies cask_dependencies unless skip_cask_deps? end def macos_dependencies return unless @cask.depends_on.macos if @cask.depends_on.macos.first.is_a?(Array) operator, release = @cask.depends_on.macos.first unless MacOS.version.send(operator, release) raise CaskError, "Cask #{@cask} depends on macOS release #{operator} #{release}, but you are running release #{MacOS.version}." end elsif @cask.depends_on.macos.length > 1 unless @cask.depends_on.macos.include?(Gem::Version.new(MacOS.version.to_s)) raise CaskError, "Cask #{@cask} depends on macOS release being one of [#{@cask.depends_on.macos.map(&:to_s).join(", ")}], but you are running release #{MacOS.version}." end else unless MacOS.version == @cask.depends_on.macos.first raise CaskError, "Cask #{@cask} depends on macOS release #{@cask.depends_on.macos.first}, but you are running release #{MacOS.version}." end end end def arch_dependencies return if @cask.depends_on.arch.nil? @current_arch ||= { type: Hardware::CPU.type, bits: Hardware::CPU.bits } return if @cask.depends_on.arch.any? do |arch| arch[:type] == @current_arch[:type] && Array(arch[:bits]).include?(@current_arch[:bits]) end raise CaskError, "Cask #{@cask} depends on hardware architecture being one of [#{@cask.depends_on.arch.map(&:to_s).join(", ")}], but you are running #{@current_arch}" end def x11_dependencies return unless @cask.depends_on.x11 raise CaskX11DependencyError, @cask.token unless MacOS::X11.installed? end def formula_dependencies formulae = @cask.depends_on.formula.map { |f| Formula[f] } return if formulae.empty? if formulae.all?(&:any_version_installed?) puts "All Formula dependencies satisfied." return end not_installed = formulae.reject(&:any_version_installed?) ohai "Installing Formula dependencies: #{not_installed.map(&:to_s).join(", ")}" not_installed.each do |formula| begin old_argv = ARGV.dup ARGV.replace([]) FormulaInstaller.new(formula).tap do |fi| fi.installed_as_dependency = true fi.installed_on_request = false fi.show_header = true fi.verbose = verbose? fi.prelude fi.install fi.finish end ensure ARGV.replace(old_argv) end end end def cask_dependencies return if @cask.depends_on.cask.empty? casks = CaskDependencies.new(@cask) if casks.all?(&:installed?) puts "All Cask dependencies satisfied." return end not_installed = casks.reject(&:installed?) ohai "Installing Cask dependencies: #{not_installed.map(&:to_s).join(", ")}" not_installed.each do |cask| Installer.new(cask, binaries: binaries?, verbose: verbose?, skip_cask_deps: true, force: false).install end end def print_caveats self.class.print_caveats(@cask) end # TODO: logically could be in a separate class def enable_accessibility_access return unless @cask.accessibility_access ohai "Enabling accessibility access" if MacOS.version <= :mountain_lion @command.run!("/usr/bin/touch", args: [Hbc.pre_mavericks_accessibility_dotfile], sudo: true) elsif MacOS.version <= :yosemite @command.run!("/usr/bin/sqlite3", args: [ Hbc.tcc_db, "INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','#{bundle_identifier}',0,1,1,NULL);", ], sudo: true) elsif MacOS.version <= :el_capitan @command.run!("/usr/bin/sqlite3", args: [ Hbc.tcc_db, "INSERT OR REPLACE INTO access VALUES('kTCCServiceAccessibility','#{bundle_identifier}',0,1,1,NULL,NULL);", ], sudo: true) else opoo <<-EOS.undent Accessibility access cannot be enabled automatically on this version of macOS. See System Preferences to enable it manually. EOS end rescue StandardError => e purge_versioned_files raise e end def disable_accessibility_access return unless @cask.accessibility_access if MacOS.version >= :mavericks && MacOS.version <= :el_capitan ohai "Disabling accessibility access" @command.run!("/usr/bin/sqlite3", args: [ Hbc.tcc_db, "DELETE FROM access WHERE client='#{bundle_identifier}';", ], sudo: true) else opoo <<-EOS.undent Accessibility access cannot be disabled automatically on this version of macOS. See System Preferences to disable it manually. EOS end end def save_caskfile old_savedir = @cask.metadata_timestamped_path return unless @cask.sourcefile_path savedir = @cask.metadata_subdir("Casks", timestamp: :now, create: true) FileUtils.copy @cask.sourcefile_path, savedir old_savedir.rmtree unless old_savedir.nil? end def uninstall oh1 "Uninstalling Cask #{@cask}" disable_accessibility_access uninstall_artifacts purge_versioned_files purge_caskroom_path if force? end def uninstall_artifacts odebug "Un-installing artifacts" artifacts = Artifact.for_cask(@cask, command: @command, verbose: verbose?, force: force?) odebug "#{artifacts.length} artifact/s defined", artifacts artifacts.each do |artifact| next unless artifact.respond_to?(:uninstall_phase) odebug "Un-installing artifact of class #{artifact.class}" artifact.uninstall_phase end end def zap ohai %Q(Implied "brew cask uninstall #{@cask}") uninstall_artifacts if Artifact::Zap.me?(@cask) ohai "Dispatching zap stanza" Artifact::Zap.new(@cask, command: @command).zap_phase else opoo "No zap stanza present for Cask '#{@cask}'" end ohai "Removing all staged versions of Cask '#{@cask}'" purge_caskroom_path end def gain_permissions_remove(path) Utils.gain_permissions_remove(path, command: @command) end def purge_versioned_files odebug "Purging files for version #{@cask.version} of Cask #{@cask}" # versioned staged distribution gain_permissions_remove(@cask.staged_path) if !@cask.staged_path.nil? && @cask.staged_path.exist? # Homebrew-Cask metadata if @cask.metadata_versioned_path.respond_to?(:children) && @cask.metadata_versioned_path.exist? @cask.metadata_versioned_path.children.each do |subdir| unless PERSISTENT_METADATA_SUBDIRS.include?(subdir.basename) gain_permissions_remove(subdir) end end end @cask.metadata_versioned_path.rmdir_if_possible @cask.metadata_master_container_path.rmdir_if_possible # toplevel staged distribution @cask.caskroom_path.rmdir_if_possible end def purge_caskroom_path odebug "Purging all staged versions of Cask #{@cask}" gain_permissions_remove(@cask.caskroom_path) end end end
gregory-nisbet/brew
Library/Homebrew/cask/lib/hbc/installer.rb
Ruby
bsd-2-clause
13,482
--[[ Copyright 2004-2012 Mathias Fiedler. 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. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]] function getParserName(name) return name.."Parser" end function generateParser(name, table, tokenNames, context, path) local parser = Parser(name, table, tokenNames) local headerFile = path.."/"..getParserName(name)..".hpp" local result = output(headerFile) if result then print(result) end --print("header:"..headerFile) print("generating "..name.." parser") {%/* @{--printTable(parser.names)} @{--printTable(parser.captures)} @{--printTable(parser)} */ %} parser:generateHeader() flush() local implFile = path.."/private/"..getParserName(name)..".cpp" result = output(implFile) if result then print(result) end parser:generateImpl() flush() end function Parser(name, parser, tokenNames) local classname = getParserName(name) local ctrlClass = getParserName(name).."Ctrl" local ctrl = "parserCtrl" local tokentype = "int" parser.names = tokenNames function getStateHandlerName(state) return "handleState"..state end function getReductionHandlerName(production) return "reduce"..production end function parser:generateHeader() --printTable(self) {% #ifndef ${string.upper(classname)}_HPP #define ${string.upper(classname)}_HPP class $ctrlClass; class $classname { public: $classname($ctrlClass& ctrl); void parse(); private: int shift(int); int push(int); int recall(int); $ctrlClass& $ctrl; int ($classname::*next)(int); int token; int symbol; @{self:generateTokenStructures()} void reduce(int, int); void ignore(int); @{for i = 0, #self.productions do} void ${getReductionHandlerName(i)}(); @{end} @{for state=0,#self do} int ${getStateHandlerName(state)}(@{self[state].info.ignorable}?int context@;); @{end} }; #endif %} end function parser:generateTokenStructures(deps) if deps then if next(deps) then for tok, dep in pairs(deps) do local name = self:getTokenName(tok) {%struct { @{self:generateTokenStructures(dep)} } $name; %} end else {%const char* str;%} end else for tok, deps in pairs(self.captures) do local name = self:getTokenName(tok) local Name = self:getTokenName(tok, 1) {% struct Tok$Name { @{self:generateTokenStructures(deps)} }; %} end {% struct { @{for tok, deps in pairs(self.captures) do local name = self:getTokenName(tok) local Name = self:getTokenName(tok, 1)} Tok$Name *$name; @{end} } curr; union { @{for tok, deps in pairs(self.captures) do local name = self:getTokenName(tok) local Name = self:getTokenName(tok, 1)} Tok$Name $name; @{end} } parent; %} end end function parser:generateImpl() {% #include "../$classname.hpp" #include "../${name}Tokens.hpp" #include "../../src/$ctrlClass.hpp" using namespace ${name}Tokens; @{self:generateCtor()} @{self:generateDtor()} void $classname::parse() { ${getStateHandlerName(0)}(); } $tokentype $classname::shift(int context) { return token = $ctrl.shift(context); } $tokentype $classname::push(int) { next = &$classname::recall; return symbol; } $tokentype $classname::recall(int) { next = &$classname::shift; return token; } void $classname::reduce(int production, $tokentype sym) { symbol = sym; next = &$classname::push; $ctrl.reduce(production); } void $classname::ignore(int production) { next = &$classname::recall; $ctrl.reduce(production); } @{self:generateReductionHandlers()} @{self:generateStateHandlers()} %} end function parser:generateCtor() local caps = self.captures --printTable(caps) {% $classname::$classname($ctrlClass &ctrl) : $ctrl(ctrl), next(&$classname::shift), token(0), symbol(0) { @{for token, deps in pairs(caps) do} curr.${self:getTokenName(token)} = 0; // $token @{end} } %} --[[for (typename std::map<Token, std::set<std::basic_string<Token> > >::const_iterator iCap = capturedTokens.begin(); iCap != capturedTokens.end(); ++iCap) stream << "curr." << getTokenName(iCap->first) << " = 0;" << newline; stream << revindent << "}" << newline;*/]] end function parser:generateDtor() {% %} end function parser:tokenMember(tokenList, ptr) local result = "" --printTable(tokenList) for i = 1, #tokenList do local tok = tokenList[i] local name = self:getTokenName(tok) result = result..name if ptr and i == 1 then result = result.."->" else result = result.."." end end return result end function parser:generateReductionHandlers() for i = 0, #self.productions do self:generateReductionHandler(i) end end function parser:generateReductionHandler(prodNo) local head = self.productions[prodNo].head local body = self.productions[prodNo].body local actions = self.productions[prodNo].actions local lparams = {} if actions then for i, action in ipairs(actions) do if action[0] then local lparam = {head} for ia, t in ipairs(action[0]) do table.insert(lparam, t) end table.insert(lparams, lparam) end end end local headname = self:getTokenName(head) {% // $headname ->@{for i,v in ipairs(body) do} ${self:getTokenName(v)}@{end} void $classname::${getReductionHandlerName(prodNo)}() { @{if head == 0 then}ignore($prodNo);@{else}reduce($prodNo, TOK_$headname);@{end} @{if actions then for i, action in pairs(actions) do self:generateAction(action) end end} @{self:generateCapturesUpdate(prodNo, lparams)} } %} end function parser:generateAction(action) if action[0] then {%parent.${self:tokenMember(action[0])}str = %} end local func = action["function"] if func then --printTable(action) {%$ctrl.$func(%} for i, arg in ipairs(action) do {%@{1<i}?, @;curr.${self:tokenMember(arg, true)}str%} end {%); %} elseif action[1] then {%curr.${self:tokenMember(action[1], true)}str; %} end end function parser:generateCapturesUpdate(prodNo, lparams) local prod = self.productions[prodNo] local head = prod.head local caps = self.captures[head] local actions = prod.actions local tokenlist = { head } --printTable(lparams) --printTable(caps) if caps then self:generateCaptureUpdate(tokenlist, caps, lparams, prod) end end function parser:generateCaptureUpdate(tokenlist, deps, lparams, prod) if next(deps) then for tok, dependencies in pairs(deps) do table.insert(tokenlist, tok) self:generateCaptureUpdate(tokenlist, dependencies, lparams, prod) table.remove(tokenlist) end else local islparam = false --printTable(tokenlist) for i, lparam in ipairs(lparams) do --printTable(lparam) if list.equal(lparam, tokenlist) then islparam = true break end end if not islparam then {% parent.${self:tokenMember(tokenlist)}str = %} if #tokenlist > 1 and list.contains(prod.body, tokenlist[2]) then local member = self:tokenMember(list.sublist(tokenlist, 2), true) {%curr.${member}str;%} else {%0;%} end end end end function parser:generateStateHandlers() --printTable(self) for state=0,#self do local v = self[state] local accepted = self:getAccepted(v) local simpleState = true for i, acc in ipairs(accepted) do if self.nonterminals[acc] then simpleState = false --printTable(accepted) --write(acc.." not in terminals") break; end end --printTable(v.reduces) if v.reduces then for prodNo, reduce in pairs(v.reduces) do if #self.productions[prodNo].body == 0 then --printTable(self.productions[prodNo]) simpleState = false; end end end --TODO: check if there's a head of ignore production accepted simpleState = false; --printTable(self[state]) {% @{self[state].info.ignorable}?//<IGNORABLE>@; @{for i, inf in ipairs(self[state].info) do} //@{self:generateInfoComment(inf)} @{end} int $classname::${getStateHandlerName(state)}(@{self[state].info.ignorable}?int context@;) { @{if v.reduces and not v.shifts and nil == next(v.reduces, next(v.reduces)) then} @{self:generateSingleReduce(state, v.context, next(v.reduces))} @{elseif simpleState then} int result = 0; @{self:generateStateHandlerSwitch(state, v)} return --result; @{else} int result = 0; do { @{self:generateStateHandlerSwitch(state, v)} } while(result == 0); return --result; @{end} } %} end end function parser:generateInfoComment(info) --printTable(info) if info.ignore then {%<ignore> %} end local prod = self.productions[info.production] if prod then local head = self:getTokenName(prod.head) function printBody() for i,tok in ipairs(prod.body) do local tokenname = self:getTokenName(tok) {%@{i-1==info.dot}?.@: @;$tokenname%} end if info.dot == #prod.body then {%.%} end end function printFollow() for i,tok in ipairs(info.follows) do local tokenname = self:getTokenName(tok) {%@{i>1}? @;$tokenname%} end end {%[$head ->@{printBody()}], (@{printFollow()})%} end end function parser:generateStateHandlerSwitch(state, statetable) local context = statetable.context if self[state].info.ignorable then context = "context" end local defaultHandled = false {% switch((this->*next)($context)) { @{if statetable.shifts then for tok, nextState in pairs(statetable.shifts) do local name = self:getTokenName(tok) local nextContext = nil if self[nextState].info.ignorable then nextContext = context end } case TOK_$name: @{self:generateStateHandling(tok, nextState, nextContext)} @{end end} @{if statetable.reduces then local defaultProd, defaultTok = next(statetable.reduces) for production, tokens in pairs(statetable.reduces) do --printTable(self.productions[production].body) local bodylen = #self.productions[production].body if bodylen > 0 and production == defaultProd then self:generateCases() defaultHandled = true else self:generateCases(tokens) end } result = $bodylen; ${getReductionHandlerName(production)}(); break; @{ end end} @{if not defaultHandled then self:generateErrorHandling(state, statetable) end} } %} end function parser:generateCases(tokens) if tokens then for ic, tok in ipairs(tokens) do local name = self:getTokenName(tok) {% case TOK_$name:%} end else {% default:%} end end function parser:generateSingleReduce(state, context, production, reduce) if self[state].info.ignorable then context = "context" end {% (this->*next)($context); ${getReductionHandlerName(production)}(); return ${#self.productions[production].body - 1}; %} end function parser:getAccepted(row) local accepted = {} if row.shifts then for tok, nextState in pairs(row.shifts) do table.insert(accepted, tok) end end if row.reduces then for prod, tokens in pairs(row.reduces) do for i, tok in ipairs(tokens) do table.insert(accepted, tok) end end end return accepted end function parser:generateErrorHandling(state, row) local accepted = self:getAccepted(row) table.sort(accepted) {% default: { const $tokentype expected[] = { @{for i,tok in ipairs(accepted) do local name = self:getTokenName(tok)}TOK_$name, @{end}}; result = $ctrl.error(sizeof(expected) / sizeof(expected[0]), expected); break; } %} end function parser:getTokenName(tok, uppercase) local tokenname = self.names[tok] if tokenname then local firstChar = string.sub(tokenname, 1, 1) if firstChar == '"' or firstChar == '/' then tokenname = tok elseif uppercase then tokenname = string.upper(firstChar)..string.sub(tokenname, 2) end else tokenname = "END" end return tokenname end function parser:generateStateHandling(tok, nextState, context) if self.captures[tok] then local tokenname = self:getTokenName(tok) local tokenName = self:getTokenName(tok, 1) local terminal = (next(self.captures[tok]) == nil); {% { Tok$tokenName tok@{not terminal}? = parent.$tokenname@;; @{terminal}?tok.str = $ctrl.string();@; Tok$tokenName *prev = curr.$tokenname; curr.$tokenname = &tok; result = ${getStateHandlerName(nextState)}($context); @{terminal}?$ctrl.release(curr.$tokenname->str);@; curr.$tokenname = prev; break; } %} else {%result = ${getStateHandlerName(nextState)}($context); break;%} end end return parser end
jackscan/parlucid
gramdefparser/parsergen.lua
Lua
bsd-2-clause
14,506
cask 'navicat-for-mysql' do version '11.2.15' sha256 '590b5f9d39ba42fde79923ae39723cdbe39fc4a8da31308e8bdf17f7ceb0addd' url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_mysql_en.dmg" name 'Navicat for MySQL' homepage 'https://www.navicat.com/products/navicat-for-mysql' app 'Navicat for MySQL.app' end
elyscape/homebrew-cask
Casks/navicat-for-mysql.rb
Ruby
bsd-2-clause
347
// basic protocol helpers var symbolExists = typeof Symbol !== 'undefined'; var protocols = { iterator: symbolExists ? Symbol.iterator : '@@iterator' }; function throwProtocolError(name, coll) { throw new Error("don't know how to " + name + " collection: " + coll); } function fulfillsProtocol(obj, name) { if(name === 'iterator') { // Accept ill-formed iterators that don't conform to the // protocol by accepting just next() return obj[protocols.iterator] || obj.next; } return obj[protocols[name]]; } function getProtocolProperty(obj, name) { return obj[protocols[name]]; } function iterator(coll) { var iter = getProtocolProperty(coll, 'iterator'); if(iter) { return iter.call(coll); } else if(coll.next) { // Basic duck typing to accept an ill-formed iterator that doesn't // conform to the iterator protocol (all iterators should have the // @@iterator method and return themselves, but some engines don't // have that on generators like older v8) return coll; } else if(isArray(coll)) { return new ArrayIterator(coll); } else if(isObject(coll)) { return new ObjectIterator(coll); } } function ArrayIterator(arr) { this.arr = arr; this.index = 0; } ArrayIterator.prototype.next = function() { if(this.index < this.arr.length) { return { value: this.arr[this.index++], done: false }; } return { done: true } }; function ObjectIterator(obj) { this.obj = obj; this.keys = Object.keys(obj); this.index = 0; } ObjectIterator.prototype.next = function() { if(this.index < this.keys.length) { var k = this.keys[this.index++]; return { value: [k, this.obj[k]], done: false }; } return { done: true } }; // helpers var toString = Object.prototype.toString; var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) { return toString.call(obj) == '[object Array]'; }; function isFunction(x) { return typeof x === 'function'; } function isObject(x) { return x instanceof Object && Object.getPrototypeOf(x) === Object.getPrototypeOf({}); } function isNumber(x) { return typeof x === 'number'; } function Reduced(value) { this['@@transducer/reduced'] = true; this['@@transducer/value'] = value; } function isReduced(x) { return (x instanceof Reduced) || (x && x['@@transducer/reduced']); } function deref(x) { return x['@@transducer/value']; } /** * This is for transforms that may call their nested transforms before * Reduced-wrapping the result (e.g. "take"), to avoid nested Reduced. */ function ensureReduced(val) { if(isReduced(val)) { return val; } else { return new Reduced(val); } } /** * This is for tranforms that call their nested transforms when * performing completion (like "partition"), to avoid signaling * termination after already completing. */ function ensureUnreduced(v) { if(isReduced(v)) { return deref(v); } else { return v; } } function reduce(coll, xform, init) { if(isArray(coll)) { var result = init; var index = -1; var len = coll.length; while(++index < len) { result = xform['@@transducer/step'](result, coll[index]); if(isReduced(result)) { result = deref(result); break; } } return xform['@@transducer/result'](result); } else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { result = xform['@@transducer/step'](result, val.value); if(isReduced(result)) { result = deref(result); break; } val = iter.next(); } return xform['@@transducer/result'](result); } throwProtocolError('iterate', coll); } function transduce(coll, xform, reducer, init) { if (typeof reducer === 'function') { reducer = transformer(reducer); } xform = xform(reducer); if(init === undefined) { init = xform['@@transducer/init'](); } return reduce(coll, xform, init); } function compose() { var funcs = Array.prototype.slice.call(arguments); return function(r) { var value = r; for(var i=funcs.length-1; i>=0; i--) { value = funcs[i](value); } return value; } } // transformations function transformer(f) { var t = {}; t['@@transducer/init'] = function() { throw new Error('init value unavailable'); }; t['@@transducer/result'] = function(v) { return v; }; t['@@transducer/step'] = f; return t; } function bound(f, ctx, count) { count = count != null ? count : 1; if(!ctx) { return f; } else { switch(count) { case 1: return function(x) { return f.call(ctx, x); } case 2: return function(x, y) { return f.call(ctx, x, y); } default: return f.bind(ctx); } } } function arrayMap(arr, f, ctx) { var index = -1; var length = arr.length; var result = Array(length); f = bound(f, ctx, 2); while (++index < length) { result[index] = f(arr[index], index); } return result; } function arrayFilter(arr, f, ctx) { var len = arr.length; var result = []; f = bound(f, ctx, 2); for(var i=0; i<len; i++) { if(f(arr[i], i)) { result.push(arr[i]); } } return result; } function Map(f, xform) { this.xform = xform; this.f = f; } Map.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Map.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Map.prototype['@@transducer/step'] = function(res, input) { return this.xform['@@transducer/step'](res, this.f(input)); }; function map(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayMap(coll, f, ctx); } return seq(coll, map(f)); } return function(xform) { return new Map(f, xform); } } function Filter(f, xform) { this.xform = xform; this.f = f; } Filter.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Filter.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Filter.prototype['@@transducer/step'] = function(res, input) { if(this.f(input)) { return this.xform['@@transducer/step'](res, input); } return res; }; function filter(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayFilter(coll, f, ctx); } return seq(coll, filter(f)); } return function(xform) { return new Filter(f, xform); }; } function remove(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); return filter(coll, function(x) { return !f(x); }); } function keep(coll) { return filter(coll, function(x) { return x != null }); } function Dedupe(xform) { this.xform = xform; this.last = undefined; } Dedupe.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Dedupe.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Dedupe.prototype['@@transducer/step'] = function(result, input) { if(input !== this.last) { this.last = input; return this.xform['@@transducer/step'](result, input); } return result; }; function dedupe(coll) { if(coll) { return seq(coll, dedupe()); } return function(xform) { return new Dedupe(xform); } } function TakeWhile(f, xform) { this.xform = xform; this.f = f; } TakeWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeWhile.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeWhile.prototype['@@transducer/step'] = function(result, input) { if(this.f(input)) { return this.xform['@@transducer/step'](result, input); } return new Reduced(result); }; function takeWhile(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { return seq(coll, takeWhile(f)); } return function(xform) { return new TakeWhile(f, xform); } } function Take(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Take.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Take.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Take.prototype['@@transducer/step'] = function(result, input) { if (this.i < this.n) { result = this.xform['@@transducer/step'](result, input); if(this.i + 1 >= this.n) { // Finish reducing on the same step as the final value. TODO: // double-check that this doesn't break any semantics result = ensureReduced(result); } } this.i++; return result; }; function take(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, take(n)); } return function(xform) { return new Take(n, xform); } } function Drop(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Drop.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Drop.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Drop.prototype['@@transducer/step'] = function(result, input) { if(this.i++ < this.n) { return result; } return this.xform['@@transducer/step'](result, input); }; function drop(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, drop(n)); } return function(xform) { return new Drop(n, xform); } } function DropWhile(f, xform) { this.xform = xform; this.f = f; this.dropping = true; } DropWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; DropWhile.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; DropWhile.prototype['@@transducer/step'] = function(result, input) { if(this.dropping) { if(this.f(input)) { return result; } else { this.dropping = false; } } return this.xform['@@transducer/step'](result, input); }; function dropWhile(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { return seq(coll, dropWhile(f)); } return function(xform) { return new DropWhile(f, xform); } } function Partition(n, xform) { this.n = n; this.i = 0; this.xform = xform; this.part = new Array(n); } Partition.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Partition.prototype['@@transducer/result'] = function(v) { if (this.i > 0) { return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i))); } return this.xform['@@transducer/result'](v); }; Partition.prototype['@@transducer/step'] = function(result, input) { this.part[this.i] = input; this.i += 1; if (this.i === this.n) { var out = this.part.slice(0, this.n); this.part = new Array(this.n); this.i = 0; return this.xform['@@transducer/step'](result, out); } return result; }; function partition(coll, n) { if (isNumber(coll)) { n = coll; coll = null; } if (coll) { return seq(coll, partition(n)); } return function(xform) { return new Partition(n, xform); }; } var NOTHING = {}; function PartitionBy(f, xform) { // TODO: take an "opts" object that allows the user to specify // equality this.f = f; this.xform = xform; this.part = []; this.last = NOTHING; } PartitionBy.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; PartitionBy.prototype['@@transducer/result'] = function(v) { var l = this.part.length; if (l > 0) { return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, l))); } return this.xform['@@transducer/result'](v); }; PartitionBy.prototype['@@transducer/step'] = function(result, input) { var current = this.f(input); if (current === this.last || this.last === NOTHING) { this.part.push(input); } else { result = this.xform['@@transducer/step'](result, this.part); this.part = [input]; } this.last = current; return result; }; function partitionBy(coll, f, ctx) { if (isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if (coll) { return seq(coll, partitionBy(f)); } return function(xform) { return new PartitionBy(f, xform); }; } function Interpose(sep, xform) { this.sep = sep; this.xform = xform; this.started = false; } Interpose.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Interpose.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Interpose.prototype['@@transducer/step'] = function(result, input) { if (this.started) { var withSep = this.xform['@@transducer/step'](result, this.sep); if (isReduced(withSep)) { return withSep; } else { return this.xform['@@transducer/step'](withSep, input); } } else { this.started = true; return this.xform['@@transducer/step'](result, input); } }; /** * Returns a new collection containing elements of the given * collection, separated by the specified separator. Returns a * transducer if a collection is not provided. */ function interpose(coll, separator) { if (arguments.length === 1) { separator = coll; return function(xform) { return new Interpose(separator, xform); }; } return seq(coll, interpose(separator)); } function Repeat(n, xform) { this.xform = xform; this.n = n; } Repeat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Repeat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Repeat.prototype['@@transducer/step'] = function(result, input) { var n = this.n; var r = result; for (var i = 0; i < n; i++) { r = this.xform['@@transducer/step'](r, input); if (isReduced(r)) { break; } } return r; }; /** * Returns a new collection containing elements of the given * collection, each repeated n times. Returns a transducer if a * collection is not provided. */ function repeat(coll, n) { if (arguments.length === 1) { n = coll; return function(xform) { return new Repeat(n, xform); }; } return seq(coll, repeat(n)); } function TakeNth(n, xform) { this.xform = xform; this.n = n; this.i = -1; } TakeNth.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeNth.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeNth.prototype['@@transducer/step'] = function(result, input) { this.i += 1; if (this.i % this.n === 0) { return this.xform['@@transducer/step'](result, input); } return result; }; /** * Returns a new collection of every nth element of the given * collection. Returns a transducer if a collection is not provided. */ function takeNth(coll, nth) { if (arguments.length === 1) { nth = coll; return function(xform) { return new TakeNth(nth, xform); }; } return seq(coll, takeNth(nth)); } // pure transducers (cannot take collections) function Cat(xform) { this.xform = xform; } Cat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Cat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Cat.prototype['@@transducer/step'] = function(result, input) { var xform = this.xform; var newxform = {}; newxform['@@transducer/init'] = function() { return xform['@@transducer/init'](); }; newxform['@@transducer/result'] = function(v) { return v; }; newxform['@@transducer/step'] = function(result, input) { var val = xform['@@transducer/step'](result, input); return isReduced(val) ? deref(val) : val; }; return reduce(input, newxform, result); }; function cat(xform) { return new Cat(xform); } function mapcat(f, ctx) { f = bound(f, ctx); return compose(map(f), cat); } // collection helpers function push(arr, x) { arr.push(x); return arr; } function merge(obj, x) { if(isArray(x) && x.length === 2) { obj[x[0]] = x[1]; } else { var keys = Object.keys(x); var len = keys.length; for(var i=0; i<len; i++) { obj[keys[i]] = x[keys[i]]; } } return obj; } var arrayReducer = {}; arrayReducer['@@transducer/init'] = function() { return []; }; arrayReducer['@@transducer/result'] = function(v) { return v; }; arrayReducer['@@transducer/step'] = push; var objReducer = {}; objReducer['@@transducer/init'] = function() { return {}; }; objReducer['@@transducer/result'] = function(v) { return v; }; objReducer['@@transducer/step'] = merge; // building new collections function toArray(coll, xform) { if(!xform) { return reduce(coll, arrayReducer, []); } return transduce(coll, xform, arrayReducer, []); } function toObj(coll, xform) { if(!xform) { return reduce(coll, objReducer, {}); } return transduce(coll, xform, objReducer, {}); } function toIter(coll, xform) { if(!xform) { return iterator(coll); } return new LazyTransformer(xform, coll); } function seq(coll, xform) { if(isArray(coll)) { return transduce(coll, xform, arrayReducer, []); } else if(isObject(coll)) { return transduce(coll, xform, objReducer, {}); } else if(coll['@@transducer/step']) { var init; if(coll['@@transducer/init']) { init = coll['@@transducer/init'](); } else { init = new coll.constructor(); } return transduce(coll, xform, coll, init); } else if(fulfillsProtocol(coll, 'iterator')) { return new LazyTransformer(xform, coll); } throwProtocolError('sequence', coll); } function into(to, xform, from) { if(isArray(to)) { return transduce(from, xform, arrayReducer, to); } else if(isObject(to)) { return transduce(from, xform, objReducer, to); } else if(to['@@transducer/step']) { return transduce(from, xform, to, to); } throwProtocolError('into', to); } // laziness var stepper = {}; stepper['@@transducer/result'] = function(v) { return isReduced(v) ? deref(v) : v; }; stepper['@@transducer/step'] = function(lt, x) { lt.items.push(x); return lt.rest; }; function Stepper(xform, iter) { this.xform = xform(stepper); this.iter = iter; } Stepper.prototype['@@transducer/step'] = function(lt) { var len = lt.items.length; while(lt.items.length === len) { var n = this.iter.next(); if(n.done || isReduced(n.value)) { // finalize this.xform['@@transducer/result'](this); break; } // step this.xform['@@transducer/step'](lt, n.value); } } function LazyTransformer(xform, coll) { this.iter = iterator(coll); this.items = []; this.stepper = new Stepper(xform, iterator(coll)); } LazyTransformer.prototype[protocols.iterator] = function() { return this; } LazyTransformer.prototype.next = function() { this['@@transducer/step'](); if(this.items.length) { return { value: this.items.pop(), done: false } } else { return { done: true }; } }; LazyTransformer.prototype['@@transducer/step'] = function() { if(!this.items.length) { this.stepper['@@transducer/step'](this); } } // util function range(n) { var arr = new Array(n); for(var i=0; i<arr.length; i++) { arr[i] = i; } return arr; } module.exports = { reduce: reduce, transformer: transformer, Reduced: Reduced, isReduced: isReduced, iterator: iterator, push: push, merge: merge, transduce: transduce, seq: seq, toArray: toArray, toObj: toObj, toIter: toIter, into: into, compose: compose, map: map, filter: filter, remove: remove, cat: cat, mapcat: mapcat, keep: keep, dedupe: dedupe, take: take, takeWhile: takeWhile, takeNth: takeNth, drop: drop, dropWhile: dropWhile, partition: partition, partitionBy: partitionBy, interpose: interpose, repeat: repeat, range: range, LazyTransformer: LazyTransformer };
milosh86/transducers.js
transducers.js
JavaScript
bsd-2-clause
20,596
#!/bin/bash set -ev set -o pipefail . Scripts/set-travis-tag-to-latest.sh pod env # Lint the podspec to check for errors. Don't call `pod spec lint`, because we want it to evaluate locally # Using sed to remove logging from output until CocoaPods issue #7577 is implemented and I can use the # OS_ACTIVITY_MODE = disable environment variable from the test spec scheme pod lib lint --verbose | sed -l '/xctest\[/d; /^$/d' . Scripts/unset-travis-tag.sh
abbeycode/UnzipKit
Scripts/cocoapod-validate.sh
Shell
bsd-2-clause
456
class Hdf5 < Formula desc "File format designed to store large amounts of data" homepage "https://www.hdfgroup.org/HDF5" url "https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-1.12.0/src/hdf5-1.12.0.tar.bz2" sha256 "97906268640a6e9ce0cde703d5a71c9ac3092eded729591279bf2e3ca9765f61" revision 1 bottle do cellar :any_skip_relocation sha256 "e0990f7a52f3f66fd8d546ff1e1d26d4a0cec5ebc9a45ec21fb5335359d6878a" => :catalina sha256 "3b681a12f21a576b4c80d84d52dbe8ff9380ecc517f9b742dbe26faf5ffc289a" => :mojave sha256 "331f9a49fb5abb3344a6dc7ff626e37d799418d8de507487c30aff91e2b22265" => :high_sierra sha256 "42d53ea00773e82bfd8766eac00aaef3886ed21a99668bc22d4fae5a71283847" => :x86_64_linux end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "gcc" # for gfortran depends_on "szip" uses_from_macos "zlib" def install inreplace %w[c++/src/h5c++.in fortran/src/h5fc.in bin/h5cc.in], "${libdir}/libhdf5.settings", "#{pkgshare}/libhdf5.settings" inreplace "src/Makefile.am", "settingsdir=$(libdir)", "settingsdir=#{pkgshare}" system "autoreconf", "-fiv" args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --with-szlib=#{Formula["szip"].opt_prefix} --enable-build-mode=production --enable-fortran --enable-cxx ] args << "--with-zlib=#{Formula["zlib"].opt_prefix}" unless OS.mac? system "./configure", *args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include "hdf5.h" int main() { printf("%d.%d.%d\\n", H5_VERS_MAJOR, H5_VERS_MINOR, H5_VERS_RELEASE); return 0; } EOS system "#{bin}/h5cc", "test.c" assert_equal version.to_s, shell_output("./a.out").chomp (testpath/"test.f90").write <<~EOS use hdf5 integer(hid_t) :: f, dspace, dset integer(hsize_t), dimension(2) :: dims = [2, 2] integer :: error = 0, major, minor, rel call h5open_f (error) if (error /= 0) call abort call h5fcreate_f ("test.h5", H5F_ACC_TRUNC_F, f, error) if (error /= 0) call abort call h5screate_simple_f (2, dims, dspace, error) if (error /= 0) call abort call h5dcreate_f (f, "data", H5T_NATIVE_INTEGER, dspace, dset, error) if (error /= 0) call abort call h5dclose_f (dset, error) if (error /= 0) call abort call h5sclose_f (dspace, error) if (error /= 0) call abort call h5fclose_f (f, error) if (error /= 0) call abort call h5close_f (error) if (error /= 0) call abort CALL h5get_libversion_f (major, minor, rel, error) if (error /= 0) call abort write (*,"(I0,'.',I0,'.',I0)") major, minor, rel end EOS system "#{bin}/h5fc", "test.f90" assert_equal version.to_s, shell_output("./a.out").chomp end end
rwhogg/homebrew-core
Formula/hdf5.rb
Ruby
bsd-2-clause
3,016
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> @import "css/design.css"; @import "css/controls.css"; </style> <title><?=App::$title; ?></title> </head> <body> <div class="header"> <h1><?=App::$title; ?></h1> </div> <div class="menu"> <a href="index.php">главная</a> <? if(App::$user->isGuest()): ?> <a href="register.php">регистрация</a> <a href="auth.php?login">войти</a> <? else: ?> <a href="user.php?list">пользователи</a> <a href="user.php">профиль</a> <a href="auth.php?logout">выйти</a> <? endif; ?> </div> <?if(!empty($errors)): ?> <div class="errors"> <ul> <? foreach($errors as $errorSource=>$errors): ?> <? foreach($errors as $error): ?> <li><?=$error;?></li> <? endforeach; ?> <? endforeach; ?> </ul> </div> <? endif; ?> <?if(!empty($messages)): ?> <div class="messages"> <ul> <? foreach($messages as $message): ?> <p><?=$message[0]?></p> <? if($message[1] != null): ?> &emsp;<?=implode(' | ', $message[1]);?> <? endif; ?> <? endforeach; ?> </ul> </div> <? endif; ?> <div id="content"> <?=$content;?> </div> </body> </html>
the-admax/php-homework-2010
protected/views/layout.php
PHP
bsd-2-clause
1,619
#ifndef SLIDER_HPP_ #define SLIDER_HPP_ #include "Button.hpp" namespace reprize { namespace inf { class Slider : public Button { public: Slider(const Str& name_, const res::Material* bg_, const res::Font* fn_, const Vec3& pad_) : Button(name_, bg_, fn_, pad_) {} Slider(const Slider& src_) : Button(src_) {} virtual ~Slider(void) {} virtual Slider* Clone(const bool with_child_ = true) { return new Slider(*this); } void appendix(const Str& arg_, res::Props* props_) { knob = new Button("Knob", form_mdl->get_material(), font, Vec3()); Widget::Add(knob); knob->resize(form_mdl->get_material()->get_size()); knob->appendix(RE_CHECKED, NULL); // XXX this will be a glyph // knob->set_event_transparent(true); knob->set_draggable_area(Vec3(area.get_x(), area.get_y())); // child_topleft.add(box_pad.get_x(), 0, 0); // set_alpha(0); // add_caption(arg_); // box->rearrange(); } /* void init(Node* cmd_, const Str& prop_arg_, const Align align_ = TOP) { knob = // knob->init(cmd_, prop_arg_, align_);set the cmd at this point knob->resize(form_mdl->get_material()->get_size()); // caption = new Caption("00", form_mdl->get_material(), font, 0, 0); // caption->write(Str("00"), font); // knob->Add(caption); std::stringstream ss; ss << area.get_x() << " " << area.get_y() + pad.get_x() << " " << 0; // knob->find("draggable")->exec(ss.str()); bool v_margin = knob->get_area().get_x() > area.get_x(); bool h_margin = knob->get_area().get_y() > area.get_y(); Widget::Add(knob); resize(Vec3(area.get_x() - v_margin * pad.get_y() * 2, area.get_y() - h_margin * pad.get_x() * 2)); knob->set_draggable_area(Vec3(area.get_x(), area.get_y())); knob->repos(Vec3()); // we need to get range or something from xml_->get_att("range") // if you want to 'drag to exec some command', you can add cmd to Button::dragging } */ virtual void pressed(const Vec3& pos_) { Vec3 knob_center = knob->get_area() / 2; knob->pressed(mtt->get_c_mtx().get_pos() + knob->get_rel_mtx().get_pos() + knob_center); dragging(pos_); } virtual void released(const Vec3& pos_) { } virtual void dragging(const Vec3& pos_) { knob->dragging(pos_); } virtual void typed(const InputCode key_) { Vec3 pos = knob->get_mtt()->get_c_mtx().get_pos(); RE_DBG("slider"); switch (key_) { case K_UP: RE_DBG("up"); dragging(Vec3(0, -5, 0)); break; case K_LEFT: RE_DBG("left"); dragging(Vec3(-5, 0, 0)); break; case K_RIGHT: RE_DBG("right"); dragging(Vec3(5, 0, 0)); break; case K_DOWN: RE_DBG("down"); dragging(Vec3(0, 5, 0)); break; } } virtual void eval(const res::Matter* parent_mtt_) { Entity::eval(parent_mtt_); /* if (knob->get_rel_pos() != prev_knob_pos) { prev_knob_pos = knob->get_rel_pos(); Vec3 ratio = prev_knob_pos / (area - knob->get_area()); std::stringstream ss; ss << " " << ratio.get_x() << " " << ratio.get_y(); // caption->setf(font, 0, ss.str().c_str()); // cmd_arg = ss.str(); activate(); } */ } protected: Button* knob; Caption* caption; Vec3 prev_knob_pos; }; } } #endif
szk/reprize
interface/widget/Slider.hpp
C++
bsd-2-clause
3,977